effect-cf 0.33.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +31 -1079
  3. package/dist/{Artifacts-DnHQA-Ax.d.mts → Artifacts-B3r3RuTB.d.mts} +1 -48
  4. package/dist/{Artifacts-CSIk1Oml.mjs → Artifacts-CBxWGeZB.mjs} +2 -7
  5. package/dist/{Binding-pfilNJmP.mjs → Binding-C82jRhdr.mjs} +1 -2
  6. package/dist/{Binding-xJJJPmiD.d.mts → Binding-DKcLrQCM.d.mts} +0 -45
  7. package/dist/ComputerArtifacts.d.mts +1 -3
  8. package/dist/ComputerArtifacts.mjs +1 -2
  9. package/dist/ComputerWorkspace.d.mts +1 -10
  10. package/dist/ComputerWorkspace.mjs +1 -2
  11. package/dist/ComputerWorkspaceHost.d.mts +1 -9
  12. package/dist/{ContainerNamespace-CFjiLw8b.d.mts → ContainerNamespace-DbLaeFhN.d.mts} +1 -14
  13. package/dist/{DurableObjectState-BpRjz6-q.d.mts → DurableObjectState-CrEunfQ-.d.mts} +82 -252
  14. package/dist/{DurableObjectState-CVLLse69.mjs → DurableObjectState-De4ZojhY.mjs} +1 -39
  15. package/dist/{ErrorMessage-BM0K-Nik.mjs → ErrorMessage-Byx2OgNd.mjs} +0 -1
  16. package/dist/{Hyperdrive-z-9fFz15.d.mts → Hyperdrive-HrwFlZ6x.d.mts} +1 -4
  17. package/dist/HyperdrivePg.d.mts +2 -11
  18. package/dist/HyperdrivePg.mjs +0 -8
  19. package/dist/Sandbox.d.mts +2 -32
  20. package/dist/Sandbox.mjs +2 -11
  21. package/dist/Vitest.d.mts +3 -31
  22. package/dist/Vitest.mjs +2 -17
  23. package/dist/{WorkflowBinding-lBR4_-op.d.mts → WorkflowBinding-BumVQTuW.d.mts} +2 -5
  24. package/dist/index.d.mts +34 -480
  25. package/dist/index.mjs +174 -312
  26. package/package.json +1 -1
  27. package/src/AiGateway.ts +0 -6
  28. package/src/AnalyticsEngine.ts +0 -9
  29. package/src/Artifacts.ts +0 -47
  30. package/src/Binding.ts +0 -8
  31. package/src/BrowserRendering.ts +0 -4
  32. package/src/Cache.ts +0 -19
  33. package/src/CloudflareOtlp.ts +3 -39
  34. package/src/ComputerArtifacts.ts +0 -2
  35. package/src/ComputerWorkspace.ts +0 -9
  36. package/src/ComputerWorkspaceHost.ts +0 -8
  37. package/src/ContainerNamespace.ts +0 -13
  38. package/src/D1.ts +0 -22
  39. package/src/DurableObject.ts +45 -25
  40. package/src/DurableObjectAlarm.ts +6 -210
  41. package/src/DurableObjectDefinition.ts +8 -20
  42. package/src/DurableObjectNamespace.ts +57 -112
  43. package/src/DurableObjectRpcWebSocket.ts +3 -19
  44. package/src/DurableObjectSqlite.ts +0 -12
  45. package/src/DurableObjectState.ts +0 -18
  46. package/src/DurableObjectStorage.ts +2 -35
  47. package/src/DurableObjectWebSocket.ts +0 -31
  48. package/src/Email.ts +0 -12
  49. package/src/Environment.ts +0 -37
  50. package/src/Hyperdrive.ts +0 -3
  51. package/src/HyperdrivePg.ts +0 -9
  52. package/src/Images.ts +0 -5
  53. package/src/Kv.ts +0 -15
  54. package/src/QueueBinding.ts +0 -2
  55. package/src/R2.ts +0 -5
  56. package/src/RpcDefinition.ts +0 -2
  57. package/src/RpcTracing.ts +133 -0
  58. package/src/Sandbox.ts +0 -30
  59. package/src/ServiceBinding.ts +48 -125
  60. package/src/Vectorize.ts +0 -5
  61. package/src/Vitest.ts +0 -28
  62. package/src/WebTransport.ts +0 -15
  63. package/src/Worker.ts +36 -57
  64. package/src/WorkerDefinition.ts +5 -14
  65. package/src/WorkersAi.ts +0 -4
  66. package/src/Workflow.ts +0 -5
  67. package/src/WorkflowBinding.ts +0 -3
  68. package/src/index.ts +1 -0
  69. package/src/internal/Entrypoint.ts +23 -4
  70. package/src/internal/ErrorMessage.ts +0 -1
  71. package/src/internal/RpcInvocation.ts +18 -1
  72. package/src/internal/Runtime.ts +12 -7
  73. package/src/internal/WorkerContext.ts +0 -11
package/dist/index.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
- import { a as WorkerEnvironment, i as WorkerConfig, n as violationsMessage, r as Environment_exports, t as causeMessage } from "./ErrorMessage-BM0K-Nik.mjs";
3
- import { n as Service$2, r as layer$19, t as Binding_exports } from "./Binding-pfilNJmP.mjs";
4
- import { n as Artifacts_exports } from "./Artifacts-CSIk1Oml.mjs";
5
- import { a as DurableObjectWebSocket_exports, c as DurableObjectStorage_exports, i as fromExecutionContext, n as DurableObjectState_exports, o as DurableWebSocketAttachmentError, r as fromDurableObjectState, s as fromWebSocket, t as DurableObjectState } from "./DurableObjectState-CVLLse69.mjs";
6
- import { Cause, Clock, Config, ConfigProvider, Context, Data, DateTime, Duration, Effect, Exit, Function as Function$1, Layer, ManagedRuntime, Option, Predicate, Queue, Result, Schema } from "effect";
2
+ import { a as WorkerEnvironment, i as WorkerConfig, n as violationsMessage, r as Environment_exports, t as causeMessage } from "./ErrorMessage-Byx2OgNd.mjs";
3
+ import { n as Service$2, r as layer$19, t as Binding_exports } from "./Binding-C82jRhdr.mjs";
4
+ import { n as Artifacts_exports } from "./Artifacts-CBxWGeZB.mjs";
5
+ import { a as DurableObjectWebSocket_exports, c as DurableObjectStorage_exports, i as fromExecutionContext, n as DurableObjectState_exports, o as DurableWebSocketAttachmentError, r as fromDurableObjectState, s as fromWebSocket, t as DurableObjectState } from "./DurableObjectState-De4ZojhY.mjs";
6
+ import { Cause, Clock, Config, ConfigProvider, Context, Data, DateTime, Duration, Effect, Exit, Function as Function$1, Layer, ManagedRuntime, Option, Predicate, Queue, References, Result, Schema, Tracer } from "effect";
7
7
  import { FetchHttpClient, HttpClient, HttpClientRequest, HttpEffect, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
8
8
  import { OtlpExporter, OtlpLogger, OtlpMetrics, OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
9
9
  import { D1Client } from "@effect/sql-d1";
@@ -24,7 +24,6 @@ var WorkersAi_exports = /* @__PURE__ */ __exportAll({
24
24
  makeClient: () => makeClient$15
25
25
  });
26
26
  const expectedWorkersAiBinding = "Workers AI binding with run(), gateway(), and models()";
27
- /** Error raised when a Workers AI operation fails. */
28
27
  var WorkersAiOperationError = class extends Data.TaggedError("WorkersAiOperationError") {
29
28
  get message() {
30
29
  return `Workers AI ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
@@ -97,7 +96,6 @@ var AiGateway_exports = /* @__PURE__ */ __exportAll({
97
96
  makeHttpClient: () => makeHttpClient
98
97
  });
99
98
  const expectedAiGatewayBinding = "Workers AI binding with gateway()";
100
- /** Error raised when an AI Gateway operation fails. */
101
99
  var AiGatewayOperationError = class extends Data.TaggedError("AiGatewayOperationError") {
102
100
  get message() {
103
101
  return `AI Gateway ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
@@ -306,19 +304,16 @@ const AnalyticsEngineDataPointSchema = Schema.Struct({
306
304
  });
307
305
  const decodeQueryResponse = Schema.decodeUnknownEffect(queryResponseSchema);
308
306
  const decodeDataPoint = Schema.decodeUnknownEffect(AnalyticsEngineDataPointSchema);
309
- /** Error raised when an Analytics Engine operation fails. */
310
307
  var AnalyticsEngineOperationError = class extends Data.TaggedError("AnalyticsEngineOperationError") {
311
308
  get message() {
312
309
  return `Analytics Engine ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
313
310
  }
314
311
  };
315
- /** Error raised when an Analytics Engine write input violates Cloudflare limits. */
316
312
  var AnalyticsEngineWriteValidationError = class extends Data.TaggedError("AnalyticsEngineWriteValidationError") {
317
313
  get message() {
318
314
  return `Analytics Engine ${this.operation} for binding "${this.binding}" failed validation: ${violationsMessage(this.violations)}`;
319
315
  }
320
316
  };
321
- /** Error raised when an Analytics Engine SQL API query fails. */
322
317
  var AnalyticsEngineQueryError = class extends Data.TaggedError("AnalyticsEngineQueryError") {};
323
318
  const analyticsEngineError = (binding, operation, cause) => new AnalyticsEngineOperationError({
324
319
  binding,
@@ -523,7 +518,6 @@ var BrowserRendering_exports = /* @__PURE__ */ __exportAll({
523
518
  makeClient: () => makeClient$12
524
519
  });
525
520
  const expectedBrowserRenderingBinding = "Browser Rendering binding resource";
526
- /** Error raised when a Browser Rendering operation fails. */
527
521
  var BrowserRenderingOperationError = class extends Data.TaggedError("BrowserRenderingOperationError") {
528
522
  get message() {
529
523
  return `Browser Rendering ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
@@ -596,13 +590,11 @@ var Cache_exports = /* @__PURE__ */ __exportAll({
596
590
  makeCacheClient: () => makeCacheClient,
597
591
  makeClient: () => makeClient$11
598
592
  });
599
- /** Error raised when a Cloudflare Cache API operation fails. */
600
593
  var CacheOperationError = class extends Data.TaggedError("CacheOperationError") {
601
594
  get message() {
602
595
  return `Cache ${this.operation} failed for cache "${this.cache}": ${causeMessage(this.cause)}`;
603
596
  }
604
597
  };
605
- /** Service for Cloudflare's global Cache API. */
606
598
  var CacheStorage = class extends Context.Service()("effect-cf/CacheStorage") {};
607
599
  const cacheError = (cache, operation, cause) => new CacheOperationError({
608
600
  cache,
@@ -617,7 +609,6 @@ const spanOptions$2 = (cache, operation) => ({ attributes: {
617
609
  cache,
618
610
  operation
619
611
  } });
620
- /** Wraps a native Cloudflare `Cache` instance. */
621
612
  const makeCacheClient = (cache, name = "default") => ({
622
613
  name,
623
614
  match: Effect.fn("Cache.match", spanOptions$2(name, "match"))((request, options) => tryCachePromise(name, "match", () => cache.match(request, options)).pipe(Effect.map(Option.fromUndefinedOr))),
@@ -625,43 +616,19 @@ const makeCacheClient = (cache, name = "default") => ({
625
616
  delete: Effect.fn("Cache.delete", spanOptions$2(name, "delete"))((request, options) => tryCachePromise(name, "delete", () => cache.delete(request, options))),
626
617
  rawUnsafe: Effect.succeed(cache)
627
618
  });
628
- /** Wraps a native Cloudflare `CacheStorage` instance. */
629
619
  const makeClient$11 = (storage) => ({
630
620
  default: makeCacheClient(storage.default),
631
621
  open: (name) => tryCachePromise(name, "open", () => storage.open(name)).pipe(Effect.map((cache) => makeCacheClient(cache, name)), Effect.withSpan("Cache.open", spanOptions$2(name, "open"))),
632
622
  rawUnsafe: Effect.succeed(storage)
633
623
  });
634
- /** Provides Cache API services from an explicit native `CacheStorage` instance. */
635
624
  const layerFrom = (storage) => Layer.succeed(CacheStorage, makeClient$11(storage));
636
- /** Provides Cache API services from Cloudflare's global `caches` object. */
637
625
  const layer$14 = Layer.sync(CacheStorage, () => makeClient$11(caches));
638
626
  //#endregion
639
627
  //#region src/CloudflareOtlp.ts
640
628
  /**
641
- * OTLP telemetry layers for Cloudflare Workers and Durable Objects.
642
- *
643
- * Every layer exposes {@link OtlpExporter.Flusher}, which drains buffered
644
- * telemetry on demand. Cloudflare isolates can freeze before the periodic
645
- * export interval fires. Effect-backed Worker fetch handlers, Worker or
646
- * Durable Object native RPC handlers, and Durable Object alarm handlers
647
- * schedule this flusher automatically. These automatic flushes are capped at
648
- * two seconds and silently discard timeouts and failures so telemetry cannot
649
- * extend or fail the user event, or recursively log through an unhealthy
650
- * exporter.
651
- *
652
- * Other entrypoint lifecycles, including queue handlers, do not flush
653
- * automatically. Applications can flush explicitly or hand the flush to their
654
- * `waitUntil` mechanism, and own the timeout and failure policy at that call
655
- * site:
656
- *
657
- * ```ts
658
- * const flusher = yield* OtlpExporter.Flusher;
659
- *
660
- * yield* flusher.flush.pipe(
661
- * Effect.timeoutOption("2 seconds"),
662
- * Effect.ignoreCause,
663
- * );
664
- * ```
629
+ * Worker fetch/RPC and Durable Object alarm/RPC handlers schedule a best-effort
630
+ * flusher. It settles within two seconds; queues and other lifecycles must
631
+ * flush explicitly. Failures are ignored so telemetry cannot fail user events.
665
632
  */
666
633
  var CloudflareOtlp_exports = /* @__PURE__ */ __exportAll({
667
634
  layer: () => layer$13,
@@ -692,7 +659,6 @@ const makeResource = (options, runtimeAttributes) => ({
692
659
  }
693
660
  });
694
661
  const serializationLayer = (serialization) => serialization === "json" ? OtlpSerialization.layerJson : OtlpSerialization.layerProtobuf;
695
- /** Merges a non-empty signal layer list; callers handle the empty case. */
696
662
  const mergeSignalLayers = (layers) => {
697
663
  let merged = layers[0];
698
664
  for (let index = 1; index < layers.length; index++) merged = Layer.mergeAll(merged, layers[index]);
@@ -791,7 +757,6 @@ const ContainerState = Schema.Union([Schema.Struct({
791
757
  status: Schema.Literal("stopped_with_code"),
792
758
  exitCode: Schema.optionalKey(Schema.Int)
793
759
  })]);
794
- /** Failure raised when invoking a named Container operation. */
795
760
  var ContainerOperationError = class extends Data.TaggedError("ContainerOperationError") {
796
761
  get message() {
797
762
  return `Container ${this.operation} failed for binding "${this.binding}" instance "${this.instance}": ${causeMessage(this.cause)}`;
@@ -889,7 +854,6 @@ const makeClient$10 = (definition) => (namespace) => {
889
854
  };
890
855
  const layer$12 = (tag, definition) => layer$19(tag, definition.binding, (value) => isContainerNamespaceResource(value), makeClient$10(definition), { expected: expectedContainerNamespace });
891
856
  const make$14 = (id) => Tag$12()(id);
892
- /** Creates a typed Effect service for a Cloudflare Container namespace. */
893
857
  const Tag$12 = () => (id) => {
894
858
  const tag = Context.Service()(`effect-cf/Container/${id}`);
895
859
  const makeLayer = (definition) => layer$12(tag, definition);
@@ -931,25 +895,7 @@ var D1_exports = /* @__PURE__ */ __exportAll({
931
895
  const TypeId$2 = "~effect-cf/D1";
932
896
  const expectedD1Database = "D1 database binding with prepare(), batch(), and exec()";
933
897
  const isD1Database = (value) => Predicate.hasProperty(value, "prepare") && Predicate.isFunction(value.prepare) && Predicate.hasProperty(value, "batch") && Predicate.isFunction(value.batch) && Predicate.hasProperty(value, "exec") && Predicate.isFunction(value.exec);
934
- /**
935
- * Creates a typed D1 service tag plus Effect helpers.
936
- */
937
898
  const make$13 = (id, definition) => Service$1()(id, definition);
938
- /**
939
- * Builds a D1 service around a Cloudflare D1 database binding.
940
- *
941
- * The returned service exposes the raw `D1Database` binding and `sqlLayer(...)`
942
- * for providing `effect/unstable/sql` via `@effect/sql-d1`.
943
- *
944
- * @example
945
- * ```ts
946
- * class TodoDatabase extends D1.Service<TodoDatabase>()("TodoDatabase", {
947
- * binding: "TODO_DB",
948
- * }) {}
949
- *
950
- * const SqlLive = TodoDatabase.sqlLayer();
951
- * ```
952
- */
953
899
  const Service$1 = () => (id, definition) => {
954
900
  const tag = Service$2()(id, definition.binding, isD1Database, void 0, { expected: expectedD1Database });
955
901
  const sqlLayer = (options) => Layer.unwrap(Effect.gen(function* () {
@@ -1213,7 +1159,6 @@ const encodeWireError = (error) => {
1213
1159
  return error;
1214
1160
  }
1215
1161
  };
1216
- /** Restores package RPC errors from the {@link encodeWireError} envelope. */
1217
1162
  const decodeWireError = (cause) => {
1218
1163
  if (!(cause instanceof Error)) return cause;
1219
1164
  try {
@@ -1309,19 +1254,123 @@ const make$11 = (id, methods) => {
1309
1254
  };
1310
1255
  };
1311
1256
  //#endregion
1257
+ //#region src/RpcTracing.ts
1258
+ var RpcTracing_exports = /* @__PURE__ */ __exportAll({
1259
+ RpcTraceContext: () => RpcTraceContext,
1260
+ withRpcClientSpan: () => withRpcClientSpan,
1261
+ withRpcServerSpan: () => withRpcServerSpan,
1262
+ withRpcTraceContext: () => withRpcTraceContext
1263
+ });
1264
+ /**
1265
+ * Live native RPC metadata. Opted-in receivers reserve a valid trailing value
1266
+ * with this tag for transport context; do not use it as a final domain argument.
1267
+ * Never store this in durable messages or envelopes.
1268
+ */
1269
+ const RpcTraceContext = Schema.Struct({
1270
+ _tag: Schema.Literal("effect-cf/RpcTraceContext/v1"),
1271
+ traceId: Schema.String.check(Schema.isPattern(/^(?!0{32}$)[0-9a-f]{32}$/)),
1272
+ spanId: Schema.String.check(Schema.isPattern(/^(?!0{16}$)[0-9a-f]{16}$/)),
1273
+ sampled: Schema.Boolean
1274
+ });
1275
+ const isRpcTraceContext$1 = Schema.is(RpcTraceContext);
1276
+ /**
1277
+ * Appends the current live parent only for a receiver that has opted in.
1278
+ * Call this inside the CLIENT span, immediately before the native invocation.
1279
+ * With no valid propagating parent, the original argument array is returned.
1280
+ */
1281
+ const withRpcTraceContext = Effect.fnUntraced(function* (args) {
1282
+ if (yield* Tracer.DisablePropagation) return args;
1283
+ const parent = yield* Effect.serviceOption(Tracer.ParentSpan);
1284
+ if (Option.isNone(parent) || Context.get(parent.value.annotations, Tracer.DisablePropagation)) return args;
1285
+ const context = {
1286
+ _tag: "effect-cf/RpcTraceContext/v1",
1287
+ traceId: parent.value.traceId,
1288
+ spanId: parent.value.spanId,
1289
+ sampled: parent.value.sampled
1290
+ };
1291
+ return isRpcTraceContext$1(context) ? [...args, context] : args;
1292
+ });
1293
+ const attributes = (service, method) => ({
1294
+ "sentry.op": "rpc",
1295
+ "rpc.system.name": "cloudflare",
1296
+ "rpc.method": `${service}/${method}`,
1297
+ "server.address": service
1298
+ });
1299
+ const withRpcSpan = (effect, service, method, options) => Effect.useSpan(`${service}/${method}`, {
1300
+ ...options,
1301
+ attributes: attributes(service, method)
1302
+ }, (span) => effect.pipe(Effect.withParentSpan(span), Effect.onExit((exit) => {
1303
+ if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause) || span.status._tag === "Ended") return Effect.void;
1304
+ return Effect.gen(function* () {
1305
+ const endTime = (yield* References.TracerTimingEnabled) ? yield* Clock.currentTimeNanos : 0n;
1306
+ span.attribute("error.type", "_OTHER");
1307
+ span.end(endTime, Exit.fail("RPC failed"));
1308
+ });
1309
+ })));
1310
+ /** Wrap the whole call, including native result resolution and success decoding. */
1311
+ const withRpcClientSpan = (effect, binding, method) => withRpcSpan(effect, binding, method, { kind: "client" });
1312
+ /**
1313
+ * Optional application instrumentation for the entire receiver effect.
1314
+ * Use in a RunSymbol override to include argument decode, handler and encode.
1315
+ * Records stable service/method attributes and failure status, not argument or
1316
+ * error payloads. The original typed failure still propagates to the caller.
1317
+ */
1318
+ const withRpcServerSpan = (effect, invocation) => withRpcSpan(effect, invocation.service, invocation.method, {
1319
+ kind: "server",
1320
+ parent: invocation.parent === void 0 ? void 0 : Tracer.externalSpan(invocation.parent)
1321
+ });
1322
+ //#endregion
1323
+ //#region src/internal/RpcInvocation.ts
1324
+ /** Scoped to the incoming event effect, never the instance runtime or storage. */
1325
+ var CurrentInvocation = class extends Context.Service()("effect-cf/internal/RpcInvocation") {};
1326
+ const recordDecodedArgs = (args) => Effect.map(Effect.serviceOption(CurrentInvocation), (invocation) => {
1327
+ if (Option.isSome(invocation)) invocation.value.decodedArgs = args;
1328
+ });
1329
+ const invokeWithReceiver = (value, receiver, args) => {
1330
+ return Function.prototype.apply.call(value, receiver, args);
1331
+ };
1332
+ const lookupRpcMethod = (target, method, makeError) => Effect.try({
1333
+ try: () => {
1334
+ if (!Predicate.isObjectKeyword(target)) throw new TypeError(`RPC target is not object-like`);
1335
+ const receiver = target;
1336
+ const value = receiver[method];
1337
+ if (!Predicate.isFunction(value)) throw new TypeError(`RPC method "${String(method)}" is not callable`);
1338
+ const callable = value;
1339
+ return (...args) => invokeWithReceiver(callable, receiver, args);
1340
+ },
1341
+ catch: makeError
1342
+ });
1343
+ const invokeRpcMethod = Effect.fnUntraced(function* (target, method, args, makeError) {
1344
+ const fn = yield* lookupRpcMethod(target, method, makeError);
1345
+ return yield* Effect.try({
1346
+ try: () => fn(...args),
1347
+ catch: makeError
1348
+ });
1349
+ });
1350
+ //#endregion
1312
1351
  //#region src/internal/Entrypoint.ts
1313
- const invokeEntrypointRpcMethod = (self, method, args, run, onExit) => {
1314
- const handler = Effect.suspend(() => method(...args)).pipe(Effect.mapError(encodeWireError));
1315
- return run(self, onExit === void 0 ? handler : handler.pipe(Effect.onExit(() => onExit(self))));
1352
+ const isRpcTraceContext = Schema.is(RpcTraceContext);
1353
+ const invokeEntrypointRpcMethod = (self, method, args, run, onExit, service, key, rpcTracing) => {
1354
+ const last = args.at(-1);
1355
+ const parent = rpcTracing !== void 0 && isRpcTraceContext(last) ? last : void 0;
1356
+ const handlerArgs = parent === void 0 ? args : args.slice(0, -1);
1357
+ const invocation = {
1358
+ service: rpcTracing?.service ?? service,
1359
+ method: key,
1360
+ args: handlerArgs,
1361
+ parent
1362
+ };
1363
+ const handler = Effect.suspend(() => method(...handlerArgs)).pipe(Effect.provideService(CurrentInvocation, invocation), Effect.mapError(encodeWireError));
1364
+ return run(self, onExit === void 0 ? handler : handler.pipe(Effect.onExit(() => onExit(self))), invocation);
1316
1365
  };
1317
1366
  const provideEntrypointServices = (layer, services) => layer.pipe(Layer.provideMerge(services));
1318
- const defineEntrypointRpcMethods = (target, prototype, rpc, reservedMethodNames, run, onExit) => {
1367
+ const defineEntrypointRpcMethods = (target, prototype, rpc, reservedMethodNames, run, onExit, rpcTracing) => {
1319
1368
  const methods = rpc ?? {};
1320
1369
  assertNoReservedMethods(target, methods, reservedMethodNames);
1321
1370
  for (const [key, method] of Object.entries(methods)) Object.defineProperty(prototype, key, {
1322
1371
  enumerable: true,
1323
1372
  value(...args) {
1324
- return invokeEntrypointRpcMethod(this, method, args, run, onExit);
1373
+ return invokeEntrypointRpcMethod(this, method, args, run, onExit, target, key, rpcTracing);
1325
1374
  }
1326
1375
  });
1327
1376
  };
@@ -1344,9 +1393,13 @@ const makeEntrypointRuntime = (layer, env, services) => {
1344
1393
  return ManagedRuntime.make(provideEntrypointServices(layer, entrypointServices));
1345
1394
  };
1346
1395
  function runEventPromise(...args) {
1347
- const [runtime, effect, eventLayer] = args;
1348
- if (eventLayer === void 0) return runtime.runPromise(Effect.scoped(effect));
1349
- return runtime.runPromise(Effect.scoped(effect.pipe(Effect.provide(eventLayer, { local: true }))));
1396
+ const [runtime, effect, eventLayer, parent] = args;
1397
+ if (eventLayer === void 0) {
1398
+ const event = Effect.scoped(effect);
1399
+ return runtime.runPromise(parent === void 0 ? event : Effect.withParentSpan(event, parent));
1400
+ }
1401
+ const event = Effect.scoped(effect.pipe(Effect.provide(eventLayer, { local: true })));
1402
+ return runtime.runPromise(parent === void 0 ? event : Effect.withParentSpan(event, parent));
1350
1403
  }
1351
1404
  //#endregion
1352
1405
  //#region src/internal/Telemetry.ts
@@ -1386,29 +1439,6 @@ const resolve = (value) => Predicate.isPromiseLike(value) ? Effect.tryPromise({
1386
1439
  });
1387
1440
  const scoped = (value) => Effect.acquireRelease(resolve(value), (resolved) => dispose(resolved));
1388
1441
  //#endregion
1389
- //#region src/internal/RpcInvocation.ts
1390
- const invokeWithReceiver = (value, receiver, args) => {
1391
- return Function.prototype.apply.call(value, receiver, args);
1392
- };
1393
- const lookupRpcMethod = (target, method, makeError) => Effect.try({
1394
- try: () => {
1395
- if (!Predicate.isObjectKeyword(target)) throw new TypeError(`RPC target is not object-like`);
1396
- const receiver = target;
1397
- const value = receiver[method];
1398
- if (!Predicate.isFunction(value)) throw new TypeError(`RPC method "${String(method)}" is not callable`);
1399
- const callable = value;
1400
- return (...args) => invokeWithReceiver(callable, receiver, args);
1401
- },
1402
- catch: makeError
1403
- });
1404
- const invokeRpcMethod = Effect.fnUntraced(function* (target, method, args, makeError) {
1405
- const fn = yield* lookupRpcMethod(target, method, makeError);
1406
- return yield* Effect.try({
1407
- try: () => fn(...args),
1408
- catch: makeError
1409
- });
1410
- });
1411
- //#endregion
1412
1442
  //#region src/ServiceBinding.ts
1413
1443
  var ServiceBinding_exports = /* @__PURE__ */ __exportAll({
1414
1444
  Service: () => Service,
@@ -1451,14 +1481,15 @@ const makeClient$8 = (definition) => {
1451
1481
  })
1452
1482
  });
1453
1483
  });
1454
- const rpc = Effect.fn("ServiceBinding.rpc")(function* (method, ...args) {
1484
+ const rpc = Effect.fnUntraced(function* (method, ...args) {
1455
1485
  const methodName = String(method);
1456
1486
  const encodedArgs = definition.definition === void 0 ? args : yield* encodeArgs(definition.definition, methodName, args).pipe(Effect.mapError((cause) => new ServiceBindingRpcError({
1457
1487
  binding: definition.binding,
1458
1488
  method: methodName,
1459
1489
  cause
1460
1490
  })));
1461
- return yield* invokeRpcMethod(service, method, encodedArgs, (cause) => new ServiceBindingRpcError({
1491
+ const nativeArgs = definition.rpcTracing ? yield* withRpcTraceContext(encodedArgs) : encodedArgs;
1492
+ return yield* invokeRpcMethod(service, method, nativeArgs, (cause) => new ServiceBindingRpcError({
1462
1493
  binding: definition.binding,
1463
1494
  method: methodName,
1464
1495
  cause
@@ -1472,7 +1503,7 @@ const makeClient$8 = (definition) => {
1472
1503
  cause
1473
1504
  })));
1474
1505
  });
1475
- const call = Effect.fn("ServiceBinding.call")(function* (method, ...args) {
1506
+ const call = Effect.fnUntraced(function* (method, ...args) {
1476
1507
  const methodName = String(method);
1477
1508
  const value = yield* resolve(yield* rpc(method, ...args)).pipe(Effect.mapError((cause) => new ServiceBindingRpcError({
1478
1509
  binding: definition.binding,
@@ -1480,13 +1511,13 @@ const makeClient$8 = (definition) => {
1480
1511
  cause
1481
1512
  })));
1482
1513
  return yield* decodeSuccess$2(methodName, value);
1483
- });
1484
- const scopedCall = Effect.fn("ServiceBinding.scopedCall")(function* (method, ...args) {
1514
+ }, (effect, ...args) => withRpcClientSpan(effect, definition.binding, String(args[0])));
1515
+ const scopedCall = Effect.fnUntraced(function* (method, ...args) {
1485
1516
  const methodName = String(method);
1486
1517
  const result = yield* rpc(method, ...args);
1487
1518
  const value = yield* scoped(result);
1488
1519
  return yield* decodeSuccess$2(methodName, value);
1489
- });
1520
+ }, (effect, ...args) => withRpcClientSpan(effect, definition.binding, String(args[0])));
1490
1521
  const directMethods = makeDirectMethods$1(definition.definition, call);
1491
1522
  return Object.assign(directMethods, {
1492
1523
  fetch,
@@ -1497,35 +1528,6 @@ const makeClient$8 = (definition) => {
1497
1528
  };
1498
1529
  };
1499
1530
  const layer$10 = (tag, definition) => layer$19(tag, definition.binding, (value) => isServiceBindingClient(value), makeClient$8(definition), { expected: expectedServiceBinding });
1500
- /**
1501
- * Creates a typed Effect service for a Worker service binding.
1502
- *
1503
- * Returned value includes:
1504
- * - a Context tag for dependency injection
1505
- * - `fetch(...)` for raw HTTP forwarding
1506
- * - `rpc(...)` for raw Cloudflare RPC results
1507
- * - `call(...)` for resolved and decoded RPC results
1508
- * - `scopedCall(...)` for scoped and decoded disposable RPC results
1509
- * - direct RPC methods when `definition` is provided
1510
- *
1511
- * @example
1512
- * ```ts
1513
- * const Counter = WorkerDefinition.make("Counter", {
1514
- * increment: WorkerDefinition.method({
1515
- * args: [Schema.Number],
1516
- * success: Schema.Number,
1517
- * }),
1518
- * });
1519
- *
1520
- * const CounterLive = Counter.layer({ binding: "COUNTER" });
1521
- *
1522
- * const program = Effect.gen(function* () {
1523
- * const counter = yield* Counter;
1524
- * const next = yield* counter.increment(1);
1525
- * return next;
1526
- * });
1527
- * ```
1528
- */
1529
1531
  const Service = () => (id, definition) => {
1530
1532
  const tag = Service$2()(id, definition.binding, (value) => isServiceBindingClient(value), makeClient$8(definition));
1531
1533
  const fetch = Effect.fnUntraced(function* (input, init) {
@@ -1590,19 +1592,6 @@ const assumeTagClass = (value) => {
1590
1592
  * Defines a single RPC method schema in a worker definition.
1591
1593
  */
1592
1594
  const method$1 = method$2;
1593
- /**
1594
- * Creates a typed worker RPC definition plus helpers for implementation and bindings.
1595
- *
1596
- * @example
1597
- * ```ts
1598
- * const CounterWorker = WorkerDefinition.make("CounterWorker", {
1599
- * increment: WorkerDefinition.method({
1600
- * args: [Schema.Number],
1601
- * success: Schema.Number,
1602
- * }),
1603
- * });
1604
- * ```
1605
- */
1606
1595
  const makeDefinition$3 = (id, methods) => {
1607
1596
  assertNoReservedMethods("Worker", methods, reservedMethodNames$3);
1608
1597
  const definition = make$11(id, methods);
@@ -1655,6 +1644,7 @@ const wrapHandlers$1 = (definition, handlers) => {
1655
1644
  const handler = handlers[key];
1656
1645
  wrapped[key] = (...args) => Effect.gen(function* () {
1657
1646
  const decodedArgs = yield* decodeArgs(definition, key, args);
1647
+ yield* recordDecodedArgs(decodedArgs);
1658
1648
  const value = yield* handler(...decodedArgs);
1659
1649
  return yield* encodeSuccess(definition, key, value);
1660
1650
  });
@@ -1670,6 +1660,7 @@ const implement$3 = (_definition, handlers) => handlers;
1670
1660
  var Worker_exports = /* @__PURE__ */ __exportAll({
1671
1661
  ExecutionContext: () => ExecutionContext,
1672
1662
  NativeRequest: () => NativeRequest,
1663
+ RunSymbol: () => RunSymbol$1,
1673
1664
  Tag: () => Tag$9,
1674
1665
  WorkerContext: () => WorkerContext,
1675
1666
  implement: () => implement$3,
@@ -1678,30 +1669,9 @@ var Worker_exports = /* @__PURE__ */ __exportAll({
1678
1669
  makeFetchHandler: () => makeFetchHandler,
1679
1670
  method: () => method$1
1680
1671
  });
1681
- /**
1682
- * Access to Cloudflare's native `ExecutionContext`.
1683
- */
1684
1672
  var ExecutionContext = class extends Context.Service()("effect-cf/ExecutionContext") {};
1685
- /**
1686
- * Service used inside handlers to schedule background work via `waitUntil`.
1687
- *
1688
- * @example
1689
- * ```ts
1690
- * const handler = Effect.gen(function* () {
1691
- * const ctx = yield* Worker.WorkerContext;
1692
- * yield* ctx.waitUntil(Effect.log("flush analytics"));
1693
- * return new Response("ok");
1694
- * });
1695
- * ```
1696
- */
1697
1673
  var WorkerContext = class extends Context.Service()("effect-cf/WorkerContext") {};
1698
- /**
1699
- * Access to the incoming `Request` currently handled by a worker or Durable Object fetch.
1700
- */
1701
1674
  var NativeRequest = class extends Context.Service()("effect-cf/NativeRequest") {};
1702
- /**
1703
- * Returns `true` when the request is a websocket upgrade request.
1704
- */
1705
1675
  const isWebSocketUpgrade = (request) => request.headers.get("Upgrade")?.toLowerCase() === "websocket";
1706
1676
  const reservedMethodNames$2 = /* @__PURE__ */ new Set([
1707
1677
  "constructor",
@@ -1719,6 +1689,7 @@ const reservedMethodNames$2 = /* @__PURE__ */ new Set([
1719
1689
  "webSocketClose",
1720
1690
  "webSocketError"
1721
1691
  ]);
1692
+ /** Override to instrument the whole event, then call super[RunSymbol]. */
1722
1693
  const RunSymbol$1 = Symbol.for("effect-cf/Worker/run");
1723
1694
  const FetchSymbol = Symbol.for("effect-cf/Worker/fetch");
1724
1695
  const renderFetchSuccess = (effect) => Effect.suspend(() => {
@@ -1761,10 +1732,12 @@ function make$9(layer, optionsOrFetch) {
1761
1732
  super(ctx, env);
1762
1733
  this.runtime = makeEntrypointRuntime(layer, env, Layer.mergeAll(Layer.succeed(ExecutionContext, ctx), Layer.succeed(WorkerContext, fromExecutionContext(ctx))));
1763
1734
  }
1764
- [RunSymbol$1](effect) {
1735
+ [RunSymbol$1](effect, runOptions = {}) {
1765
1736
  const eventLayer = options.eventLayer;
1766
- if (eventLayer === void 0) return runEventPromise(this.runtime, effect);
1767
- return runEventPromise(this.runtime, effect, eventLayer);
1737
+ const parent = runOptions.rpc?.parent;
1738
+ const parentSpan = parent === void 0 ? void 0 : Tracer.externalSpan(parent);
1739
+ if (eventLayer === void 0) return runEventPromise(this.runtime, effect, void 0, parentSpan);
1740
+ return runEventPromise(this.runtime, effect, eventLayer, parentSpan);
1768
1741
  }
1769
1742
  fetch(request) {
1770
1743
  return this[FetchSymbol](request);
@@ -1774,16 +1747,19 @@ function make$9(layer, optionsOrFetch) {
1774
1747
  if (fetchHandler === void 0) return Promise.resolve(new Response("Not Found", { status: 404 }));
1775
1748
  const ctx = requestContext ?? this.ctx;
1776
1749
  const requestServices = Layer.mergeAll(Layer.succeed(NativeRequest, request), Layer.succeed(HttpServerRequest.HttpServerRequest, HttpServerRequest.fromWeb(request)), Layer.succeed(ExecutionContext, ctx), Layer.succeed(WorkerContext, fromExecutionContext(ctx)));
1777
- return this[RunSymbol$1](renderFetchSuccess(fetchHandler).pipe(Effect.tap(() => scheduleTelemetryFlush$1), Effect.provide(requestServices)));
1750
+ return this[RunSymbol$1](renderFetchSuccess(fetchHandler).pipe(Effect.tap(() => scheduleTelemetryFlush$1), Effect.provide(requestServices)), { event: "fetch" });
1778
1751
  }
1779
1752
  queue(batch) {
1780
1753
  const queueHandler = options.queue;
1781
1754
  if (queueHandler === void 0) return Promise.resolve();
1782
1755
  const messages = batch.messages.map((message) => fromMessage(message, message.body));
1783
- return this[RunSymbol$1](queueHandler(fromMessageBatch(batch, messages)));
1756
+ return this[RunSymbol$1](queueHandler(fromMessageBatch(batch, messages)), { event: "queue" });
1784
1757
  }
1785
1758
  }
1786
- defineEntrypointRpcMethods("Worker", EffectWorker.prototype, options.rpc, reservedMethodNames$2, (self, effect) => self[RunSymbol$1](effect), () => scheduleTelemetryFlush$1);
1759
+ defineEntrypointRpcMethods("Worker", EffectWorker.prototype, options.rpc, reservedMethodNames$2, (self, effect, rpc) => self[RunSymbol$1](effect, {
1760
+ event: "rpc",
1761
+ rpc
1762
+ }), () => scheduleTelemetryFlush$1, options.rpcTracing);
1787
1763
  return assumeEntrypointClass(EffectWorker);
1788
1764
  }
1789
1765
  function makeFetchHandler(layer, options) {
@@ -1842,20 +1818,21 @@ const makeClient$7 = (definition) => {
1842
1818
  cause
1843
1819
  })
1844
1820
  });
1845
- const rpc = Effect.fn("DurableObjectNamespace.rpc")(function* (stub, method, ...args) {
1821
+ const rpc = Effect.fnUntraced(function* (stub, method, ...args) {
1846
1822
  const methodName = String(method);
1847
1823
  const encodedArgs = definition.definition === void 0 ? args : yield* encodeArgs(definition.definition, methodName, args).pipe(Effect.mapError((cause) => new DurableObjectRpcError({
1848
1824
  binding: definition.binding,
1849
1825
  method: methodName,
1850
1826
  cause
1851
1827
  })));
1852
- return yield* invokeRpcMethod(stub, method, encodedArgs, (cause) => new DurableObjectRpcError({
1828
+ const nativeArgs = definition.rpcTracing ? yield* withRpcTraceContext(encodedArgs) : encodedArgs;
1829
+ return yield* invokeRpcMethod(stub, method, nativeArgs, (cause) => new DurableObjectRpcError({
1853
1830
  binding: definition.binding,
1854
1831
  method: methodName,
1855
1832
  cause
1856
1833
  }));
1857
1834
  });
1858
- const decodeSuccess$1 = Effect.fn("DurableObjectNamespace.decodeSuccess")(function* (methodName, value) {
1835
+ const decodeSuccess$1 = Effect.fnUntraced(function* (methodName, value) {
1859
1836
  if (definition.definition === void 0) return value;
1860
1837
  return yield* decodeSuccess(definition.definition, methodName, value).pipe(Effect.mapError((cause) => new DurableObjectRpcError({
1861
1838
  binding: definition.binding,
@@ -1863,7 +1840,7 @@ const makeClient$7 = (definition) => {
1863
1840
  cause
1864
1841
  })));
1865
1842
  });
1866
- const call = Effect.fn("DurableObjectNamespace.call")(function* (stub, method, ...args) {
1843
+ const call = Effect.fnUntraced(function* (stub, method, ...args) {
1867
1844
  const methodName = String(method);
1868
1845
  const value = yield* resolve(yield* rpc(stub, method, ...args)).pipe(Effect.mapError((cause) => new DurableObjectRpcError({
1869
1846
  binding: definition.binding,
@@ -1871,13 +1848,13 @@ const makeClient$7 = (definition) => {
1871
1848
  cause
1872
1849
  })));
1873
1850
  return yield* decodeSuccess$1(methodName, value);
1874
- });
1875
- const scopedCall = Effect.fn("DurableObjectNamespace.scopedCall")(function* (stub, method, ...args) {
1851
+ }, (effect, ...args) => withRpcClientSpan(effect, definition.binding, String(args[1])));
1852
+ const scopedCall = Effect.fnUntraced(function* (stub, method, ...args) {
1876
1853
  const methodName = String(method);
1877
1854
  const result = yield* rpc(stub, method, ...args);
1878
1855
  const value = yield* scoped(result);
1879
1856
  return yield* decodeSuccess$1(methodName, value);
1880
- });
1857
+ }, (effect, ...args) => withRpcClientSpan(effect, definition.binding, String(args[1])));
1881
1858
  const directMethods = makeDirectMethods(definition.definition, {
1882
1859
  call,
1883
1860
  fetch,
@@ -1941,19 +1918,6 @@ const reservedMethodNames$1 = /* @__PURE__ */ new Set([
1941
1918
  function method(definition) {
1942
1919
  return method$2(definition);
1943
1920
  }
1944
- /**
1945
- * Creates a Durable Object RPC definition plus implementation/binding helpers.
1946
- *
1947
- * @example
1948
- * ```ts
1949
- * const ChatRoom = DurableObjectDefinition.make("ChatRoom", {
1950
- * postMessage: DurableObjectDefinition.method({
1951
- * args: [Schema.String],
1952
- * success: Schema.Void,
1953
- * }),
1954
- * });
1955
- * ```
1956
- */
1957
1921
  const makeDefinition$2 = (id, methods) => {
1958
1922
  assertNoReservedMethods("Durable Object", methods, reservedMethodNames$1);
1959
1923
  const definition = make$11(id, methods);
@@ -1993,15 +1957,15 @@ const Tag$8 = () => (id, methods) => {
1993
1957
  const fetch = Effect.fn("DurableObject.fetch")(function* (stub, input, init) {
1994
1958
  return yield* (yield* tag).fetch(stub, input, init);
1995
1959
  });
1996
- const rpc = Effect.fn("DurableObject.rpc")(function* (stub, methodName, ...args) {
1960
+ const rpc = Effect.fnUntraced(function* (stub, methodName, ...args) {
1997
1961
  const invokeRpc = (yield* tag).rpc;
1998
1962
  return yield* invokeRpc(stub, methodName, ...args);
1999
1963
  });
2000
- const call = Effect.fn("DurableObject.call")(function* (stub, methodName, ...args) {
1964
+ const call = Effect.fnUntraced(function* (stub, methodName, ...args) {
2001
1965
  const invokeCall = (yield* tag).call;
2002
1966
  return yield* invokeCall(stub, methodName, ...args);
2003
1967
  });
2004
- const scopedCall = Effect.fn("DurableObject.scopedCall")(function* (stub, methodName, ...args) {
1968
+ const scopedCall = Effect.fnUntraced(function* (stub, methodName, ...args) {
2005
1969
  const invokeScopedCall = (yield* tag).scopedCall;
2006
1970
  return yield* invokeScopedCall(stub, methodName, ...args);
2007
1971
  });
@@ -2039,6 +2003,7 @@ const wrapHandlers = (definition, handlers) => {
2039
2003
  const handler = handlers[key];
2040
2004
  wrapped[key] = (...args) => Effect.gen(function* () {
2041
2005
  const decodedArgs = yield* decodeArgs(definition, key, args);
2006
+ yield* recordDecodedArgs(decodedArgs);
2042
2007
  const value = yield* handler(...decodedArgs);
2043
2008
  return yield* encodeSuccess(definition, key, value);
2044
2009
  });
@@ -2052,6 +2017,7 @@ const implement$2 = (_definition, handlers) => handlers;
2052
2017
  //#endregion
2053
2018
  //#region src/DurableObject.ts
2054
2019
  var DurableObject_exports = /* @__PURE__ */ __exportAll({
2020
+ RunSymbol: () => RunSymbol,
2055
2021
  Tag: () => Tag$8,
2056
2022
  implement: () => implement$2,
2057
2023
  make: () => make$7,
@@ -2066,11 +2032,9 @@ const reservedMethodNames = /* @__PURE__ */ new Set([
2066
2032
  "webSocketClose",
2067
2033
  "webSocketError"
2068
2034
  ]);
2035
+ /** Override to instrument the whole event, then call super[RunSymbol]. */
2069
2036
  const RunSymbol = Symbol.for("effect-cf/DurableObject/run");
2070
2037
  const scheduleTelemetryFlush = scheduleTelemetryFlush$2((flush) => Effect.flatMap(DurableObjectState, (state) => state.waitUntil(flush)));
2071
- /**
2072
- * Creates a Durable Object class backed by a single managed Effect runtime.
2073
- */
2074
2038
  const make$7 = (layer, options = {}) => {
2075
2039
  class EffectDurableObject extends DurableObject {
2076
2040
  runtime;
@@ -2082,13 +2046,15 @@ const make$7 = (layer, options = {}) => {
2082
2046
  }
2083
2047
  [RunSymbol](effect, runOptions = {}) {
2084
2048
  const eventLayer = runOptions.eventLayer === false ? void 0 : options.eventLayer;
2085
- if (eventLayer === void 0) return runEventPromise(this.runtime, effect);
2086
- return runEventPromise(this.runtime, effect, eventLayer);
2049
+ const parent = runOptions.rpc?.parent;
2050
+ const parentSpan = parent === void 0 ? void 0 : Tracer.externalSpan(parent);
2051
+ if (eventLayer === void 0) return runEventPromise(this.runtime, effect, void 0, parentSpan);
2052
+ return runEventPromise(this.runtime, effect, eventLayer, parentSpan);
2087
2053
  }
2088
2054
  fetch(request) {
2089
2055
  const fetchHandler = options.fetch;
2090
2056
  if (fetchHandler === void 0) return Promise.resolve(new Response("Not Found", { status: 404 }));
2091
- return this[RunSymbol](Effect.provideService(fetchHandler, NativeRequest, request));
2057
+ return this[RunSymbol](Effect.provideService(fetchHandler, NativeRequest, request), { event: "fetch" });
2092
2058
  }
2093
2059
  alarm(alarmInfo) {
2094
2060
  const logicalAlarms = options.alarms?.pipe(Effect.asVoid);
@@ -2097,19 +2063,22 @@ const make$7 = (layer, options = {}) => {
2097
2063
  yield* logicalAlarms;
2098
2064
  yield* rawAlarm;
2099
2065
  }) : logicalAlarms ?? rawAlarm;
2100
- if (alarmEffect !== void 0) return this[RunSymbol](alarmEffect.pipe(Effect.onExit(() => scheduleTelemetryFlush)));
2066
+ if (alarmEffect !== void 0) return this[RunSymbol](alarmEffect.pipe(Effect.onExit(() => scheduleTelemetryFlush)), { event: "alarm" });
2101
2067
  }
2102
2068
  webSocketMessage(socket, message) {
2103
- if (options.webSocketMessage !== void 0) return this[RunSymbol](options.webSocketMessage(fromWebSocket(socket), message));
2069
+ if (options.webSocketMessage !== void 0) return this[RunSymbol](options.webSocketMessage(fromWebSocket(socket), message), { event: "webSocketMessage" });
2104
2070
  }
2105
2071
  webSocketClose(socket, code, reason, wasClean) {
2106
- if (options.webSocketClose !== void 0) return this[RunSymbol](options.webSocketClose(fromWebSocket(socket), code, reason, wasClean));
2072
+ if (options.webSocketClose !== void 0) return this[RunSymbol](options.webSocketClose(fromWebSocket(socket), code, reason, wasClean), { event: "webSocketClose" });
2107
2073
  }
2108
2074
  webSocketError(socket, cause) {
2109
- if (options.webSocketError !== void 0) return this[RunSymbol](options.webSocketError(fromWebSocket(socket), cause));
2075
+ if (options.webSocketError !== void 0) return this[RunSymbol](options.webSocketError(fromWebSocket(socket), cause), { event: "webSocketError" });
2110
2076
  }
2111
2077
  }
2112
- defineEntrypointRpcMethods("Durable Object", EffectDurableObject.prototype, options.rpc, reservedMethodNames, (self, effect) => self[RunSymbol](effect), () => scheduleTelemetryFlush);
2078
+ defineEntrypointRpcMethods("Durable Object", EffectDurableObject.prototype, options.rpc, reservedMethodNames, (self, effect, rpc) => self[RunSymbol](effect, {
2079
+ event: "rpc",
2080
+ rpc
2081
+ }), () => scheduleTelemetryFlush, options.rpcTracing);
2113
2082
  return assumeEntrypointClass(EffectDurableObject);
2114
2083
  };
2115
2084
  //#endregion
@@ -2165,30 +2134,10 @@ var StoredAlarmDecodeError = class extends Data.TaggedError("StoredAlarmDecodeEr
2165
2134
  return `Failed to decode stored alarm "${this.storageId}": ${causeMessage(this.cause)}`;
2166
2135
  }
2167
2136
  };
2168
- /**
2169
- * Events handled by `processDueAlarms`.
2170
- *
2171
- * `AlarmDue` represents one durable alarm whose scheduled time is now due. The
2172
- * `tag` is the consumer-owned routing key, while `id` is the stable alarm id
2173
- * within that tag.
2174
- *
2175
- * `scheduledAt` is the logical due-after timestamp from durable storage. It is
2176
- * not expected to match the current Durable Object alarm invocation time,
2177
- * especially during retries. Retries re-scan durable rows with `run_at <= now`
2178
- * and identify logical events by `{ tag, id }`.
2179
- *
2180
- * @example Handling events by tag
2181
- * ```ts
2182
- * yield* durableObjectAlarm.processDueAlarms((event) =>
2183
- * event.tag === "heartbeat"
2184
- * ? heartbeatManager.handleAlarmEvent(event).pipe(Effect.asVoid)
2185
- * : Effect.void
2186
- * );
2187
- * ```
2188
- */
2189
2137
  const DurableObjectAlarmEvent = Schema.TaggedUnion({ AlarmDue: {
2190
2138
  id: Schema.NonEmptyString,
2191
2139
  payload: Schema.Json,
2140
+ /** Persisted due time, which can differ from the invocation time during retries. */
2192
2141
  scheduledAt: Schema.DateTimeUtc,
2193
2142
  tag: Schema.NonEmptyString
2194
2143
  } });
@@ -2278,50 +2227,6 @@ const define = (definitions) => ({ handlers: (handlers, options) => processDue((
2278
2227
  return action ?? optionAction;
2279
2228
  })
2280
2229
  }) });
2281
- /**
2282
- * SQLite-backed Durable Object alarm scheduler.
2283
- *
2284
- * `DurableObjectAlarm` stores alarms in the current Durable Object's SQLite storage
2285
- * and keeps the platform alarm set to the earliest pending scheduled alarm. The
2286
- * platform alarm timestamp is only a wake-up hint; logical event identity comes
2287
- * from persisted `{ tag, id }` rows.
2288
- *
2289
- * Retry safety depends on acknowledgement ordering. `processDueAlarms` runs the
2290
- * caller's handler first and only then conditionally deletes or advances the
2291
- * same selected row. By default, handler failures are isolated: the failed row
2292
- * is retried after a delay, later due rows continue, and the platform alarm is
2293
- * reconciled once at the end. Use `mode: "ordered"` for strict workflows where
2294
- * one failed logical alarm should block later due alarms.
2295
- *
2296
- * Provide `DurableObjectAlarm.layer` anywhere `DurableObjectState` is available.
2297
- *
2298
- * @example Providing the service
2299
- * ```ts
2300
- * const program = Effect.gen(function* () {
2301
- * const durableObjectAlarm = yield* DurableObjectAlarm;
2302
- * const now = yield* DateTime.now;
2303
- *
2304
- * yield* durableObjectAlarm.scheduleAlarm({
2305
- * tag: "heartbeat",
2306
- * id: "heartbeat-check",
2307
- * runAt: DateTime.add(now, { seconds: 5 }),
2308
- * repeatEvery: Duration.seconds(5),
2309
- * payload: null,
2310
- * });
2311
- * }).pipe(Effect.provide(DurableObjectAlarm.layer));
2312
- * ```
2313
- *
2314
- * @example Processing due alarms
2315
- * ```ts
2316
- * const handledEvents = yield* durableObjectAlarm.processDueAlarms((event) =>
2317
- * Effect.gen(function* () {
2318
- * if (event.tag === "heartbeat") {
2319
- * yield* heartbeatManager.handleAlarmEvent(event);
2320
- * }
2321
- * })
2322
- * );
2323
- * ```
2324
- */
2325
2230
  var DurableObjectAlarm = class DurableObjectAlarm extends Context.Service()("effect-cf/DurableObjectAlarm") {
2326
2231
  static layer = Layer.effect(DurableObjectAlarm, Effect.gen(function* () {
2327
2232
  const state = yield* DurableObjectState;
@@ -2486,9 +2391,6 @@ const ResumableAttachmentMetadataSchema = Schema.Struct({
2486
2391
  subscriptions: Schema.Array(PersistedSubscriptionSchema)
2487
2392
  });
2488
2393
  const decodeResumableAttachment = Schema.decodeUnknownOption(ResumableAttachmentMetadataSchema);
2489
- /**
2490
- * Context tag for the Durable Object RPC websocket service.
2491
- */
2492
2394
  var DurableObjectRpcWebSocket = class extends Context.Service()("effect-cf/DurableObjectRpcWebSocket") {};
2493
2395
  /**
2494
2396
  * Builds a hibernation-aware transport that bridges Durable Object websocket
@@ -3004,17 +2906,6 @@ const makeHeartbeatController = (state, serialization, policy) => Effect.gen(fun
3004
2906
  //#endregion
3005
2907
  //#region src/DurableObjectSqlite.ts
3006
2908
  var DurableObjectSqlite_exports = /* @__PURE__ */ __exportAll({ layer: () => layer$7 });
3007
- /**
3008
- * Provides `effect/unstable/sql` from the current Durable Object SQLite storage.
3009
- *
3010
- * @example
3011
- * ```ts
3012
- * const RoomLayer = Layer.mergeAll(
3013
- * DurableObjectSqlite.layer(),
3014
- * OtherRoomServices,
3015
- * );
3016
- * ```
3017
- */
3018
2909
  const layer$7 = (options) => Layer.unwrap(Effect.gen(function* () {
3019
2910
  const state = yield* DurableObjectState;
3020
2911
  return SqliteClient.layer({
@@ -3038,17 +2929,13 @@ var Email_exports = /* @__PURE__ */ __exportAll({
3038
2929
  });
3039
2930
  const expectedSendEmailBinding = "Send Email binding with send()";
3040
2931
  const textEncoder = new TextEncoder();
3041
- /** Documented Cloudflare Email Sending limits. */
3042
2932
  const sendLimits = {
3043
- /** Combined `to`, `cc`, and `bcc` addresses per message. */
3044
2933
  maxRecipients: 50,
3045
2934
  maxAttachments: 32,
3046
- /** Total message size, including attachments. Not enforced client side. */
3047
2935
  maxMessageBytes: 5 * 1024 * 1024,
3048
2936
  maxHeaderNameBytes: 100,
3049
2937
  maxHeaderValueBytes: 2048,
3050
2938
  maxHeadersBytes: 16 * 1024,
3051
- /** Allowlisted custom headers, excluding `X-` prefixed headers. */
3052
2939
  maxAllowlistHeaders: 20
3053
2940
  };
3054
2941
  /**
@@ -3081,14 +2968,12 @@ const emailErrorCodes = [
3081
2968
  "E_HEADERS_TOO_LARGE",
3082
2969
  "E_HEADERS_TOO_MANY"
3083
2970
  ];
3084
- /** Error raised when a Cloudflare Send Email operation fails. */
3085
2971
  var EmailOperationError = class extends Data.TaggedError("EmailOperationError") {
3086
2972
  get message() {
3087
2973
  const code = this.code === void 0 ? "" : ` (${this.code})`;
3088
2974
  return `Email ${this.operation} failed for binding "${this.binding}"${code}: ${causeMessage(this.cause)}`;
3089
2975
  }
3090
2976
  };
3091
- /** Error raised when a message violates documented Cloudflare Email Sending limits. */
3092
2977
  var EmailValidationError = class extends Data.TaggedError("EmailValidationError") {
3093
2978
  get message() {
3094
2979
  return `Email ${this.operation} for binding "${this.binding}" failed validation: ${violationsMessage(this.violations)}`;
@@ -3309,7 +3194,6 @@ var Images_exports = /* @__PURE__ */ __exportAll({
3309
3194
  });
3310
3195
  const TypeId = "~effect-cf/Images/Steps";
3311
3196
  const expectedImagesBinding = "Images binding with info() and input()";
3312
- /** Error raised when a Cloudflare Images operation fails. */
3313
3197
  var ImagesOperationError = class extends Data.TaggedError("ImagesOperationError") {
3314
3198
  get message() {
3315
3199
  return `Images ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
@@ -3320,7 +3204,6 @@ const makeSteps = (steps) => ({
3320
3204
  [TypeId]: TypeId,
3321
3205
  steps
3322
3206
  });
3323
- /** Empty Images transformation pipeline. */
3324
3207
  const empty = makeSteps([]);
3325
3208
  const transform = Function$1.dual(2, (steps, transformValue) => makeSteps([...steps.steps, Step.Transform({ transform: transformValue })]));
3326
3209
  const draw = Function$1.dual(2, (steps, drawValue) => makeSteps([...steps.steps, Step.Draw(drawValue)]));
@@ -3407,7 +3290,6 @@ var Kv_exports = /* @__PURE__ */ __exportAll({
3407
3290
  makeClient: () => makeClient$3
3408
3291
  });
3409
3292
  const expectedKvNamespace = "KV namespace binding with get(), put(), delete(), getWithMetadata(), and list()";
3410
- /** Error raised when a KV operation fails. */
3411
3293
  var KvOperationError = class extends Data.TaggedError("KvOperationError") {
3412
3294
  get message() {
3413
3295
  return `Kv ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
@@ -3531,7 +3413,6 @@ var R2_exports = /* @__PURE__ */ __exportAll({
3531
3413
  makeClient: () => makeClient$2
3532
3414
  });
3533
3415
  const expectedR2Bucket = "R2 bucket binding with head(), get(), put(), createMultipartUpload(), resumeMultipartUpload(), delete(), and list()";
3534
- /** Error raised when an R2 operation fails. */
3535
3416
  var R2OperationError = class extends Data.TaggedError("R2OperationError") {
3536
3417
  get message() {
3537
3418
  return `R2 ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
@@ -3639,7 +3520,6 @@ var Vectorize_exports = /* @__PURE__ */ __exportAll({
3639
3520
  makeClient: () => makeClient$1
3640
3521
  });
3641
3522
  const expectedVectorizeBinding = "Vectorize index binding with describe(), query(), insert(), upsert(), deleteByIds(), and getByIds()";
3642
- /** Error raised when a Vectorize operation fails. */
3643
3523
  var VectorizeOperationError = class extends Data.TaggedError("VectorizeOperationError") {
3644
3524
  get message() {
3645
3525
  return `Vectorize ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
@@ -3715,11 +3595,8 @@ var WebTransport_exports = /* @__PURE__ */ __exportAll({
3715
3595
  * `Record<string, unknown>` side of `request.cf`.
3716
3596
  */
3717
3597
  var InboundTransport = class extends Schema.Class("InboundTransport")({
3718
- /** The HTTP protocol the client used, e.g. `"HTTP/2"` or `"HTTP/3"`. */
3719
3598
  httpProtocol: Schema.String,
3720
- /** Client round-trip time; only present for QUIC (HTTP/3) connections. */
3721
3599
  clientQuicRtt: Schema.optional(Schema.Number),
3722
- /** Client round-trip time; only present for TCP (HTTP/1.x, HTTP/2) connections. */
3723
3600
  clientTcpRtt: Schema.optional(Schema.Number)
3724
3601
  }) {};
3725
3602
  const decodeInboundTransport = Schema.decodeUnknownResult(InboundTransport);
@@ -3731,16 +3608,7 @@ const decodeInboundTransport = Schema.decodeUnknownResult(InboundTransport);
3731
3608
  * the expected shape.
3732
3609
  */
3733
3610
  const inboundTransport = (request) => Result.getSuccess(decodeInboundTransport(request.cf));
3734
- /**
3735
- * Returns `true` when the client reached Cloudflare's edge over QUIC
3736
- * (HTTP/3). Prefers the documented QUIC signal (`clientQuicRtt` is only
3737
- * present for QUIC connections) and falls back to the `httpProtocol` string.
3738
- *
3739
- * Note this describes the browser→edge hop only: the edge always terminates
3740
- * QUIC, and the Worker still handles an ordinary `fetch` Request.
3741
- */
3742
3611
  const isHttp3 = (transport) => transport.clientQuicRtt !== void 0 || transport.httpProtocol === "HTTP/3";
3743
- /** Feature-detects the WebTransport capabilities of the current runtime. */
3744
3612
  const capabilities = Effect.sync(() => {
3745
3613
  const runtime = globalThis;
3746
3614
  return {
@@ -3748,7 +3616,6 @@ const capabilities = Effect.sync(() => {
3748
3616
  outboundSessions: Predicate.hasProperty(runtime, "WebTransport") && Predicate.isFunction(runtime["WebTransport"])
3749
3617
  };
3750
3618
  });
3751
- /** Raised when a WebTransport capability is unavailable in this runtime. */
3752
3619
  var WebTransportUnsupportedError = class extends Data.TaggedError("WebTransportUnsupportedError") {
3753
3620
  get message() {
3754
3621
  return this.capability === "inbound-sessions" ? "Cloudflare Workers cannot accept inbound WebTransport sessions: the edge terminates QUIC and no runtime session API exists (cloudflare/workerd#6451). Use Durable Object WebSockets for bidirectional push." : "This Workers runtime provides no WebTransport client: workerd has no QUIC stack and cloudflare:sockets is TCP-only.";
@@ -3918,10 +3785,6 @@ const wrapHandler = (definition, handler) => {
3918
3785
  const implement$1 = (_definition, handler) => handler;
3919
3786
  //#endregion
3920
3787
  //#region src/Workflow.ts
3921
- /**
3922
- * Effect wrapper for Cloudflare Workflows entrypoints and bindings; distinct
3923
- * from Effect's runtime-agnostic `effect/unstable/workflow` cluster module.
3924
- */
3925
3788
  var Workflow_exports = /* @__PURE__ */ __exportAll({
3926
3789
  Tag: () => Tag,
3927
3790
  WorkflowEvent: () => WorkflowEvent$1,
@@ -3937,7 +3800,6 @@ var Workflow_exports = /* @__PURE__ */ __exportAll({
3937
3800
  waitForEvent: () => waitForEvent
3938
3801
  });
3939
3802
  var WorkflowEvent$1 = class extends Context.Service()("effect-cf/WorkflowEvent") {};
3940
- /** Failure raised when a Cloudflare Workflow step operation rejects. */
3941
3803
  var WorkflowStepError = class extends Data.TaggedError("WorkflowStepError") {
3942
3804
  get message() {
3943
3805
  const step = this.step === void 0 ? "" : ` in step "${this.step}"`;
@@ -4035,4 +3897,4 @@ const waitForEvent = (name, options) => Effect.flatMap(WorkflowStep$1, (workflow
4035
3897
  const Tag = Tag$1;
4036
3898
  const implement = implement$1;
4037
3899
  //#endregion
4038
- export { AiGateway_exports as AiGateway, AnalyticsEngine_exports as AnalyticsEngine, Artifacts_exports as Artifacts, Binding_exports as Binding, BrowserRendering_exports as BrowserRendering, Cache_exports as Cache, CloudflareOtlp_exports as CloudflareOtlp, ContainerNamespace_exports as ContainerNamespace, D1_exports as D1, DurableObject_exports as DurableObject, DurableObjectAlarm_exports as DurableObjectAlarm, DurableObjectDefinition_exports as DurableObjectDefinition, DurableObjectNamespace_exports as DurableObjectNamespace, DurableObjectRpcWebSocket_exports as DurableObjectRpcWebSocket, DurableObjectSqlite_exports as DurableObjectSqlite, DurableObjectState_exports as DurableObjectState, DurableObjectStorage_exports as DurableObjectStorage, DurableObjectWebSocket_exports as DurableObjectWebSocket, Email_exports as Email, Environment_exports as Environment, Hyperdrive_exports as Hyperdrive, Images_exports as Images, Kv_exports as Kv, Queue_exports as Queue, QueueBinding_exports as QueueBinding, QueueDefinition_exports as QueueDefinition, R2_exports as R2, Rpc_exports as Rpc, RpcDefinition_exports as RpcDefinition, ServiceBinding_exports as ServiceBinding, Vectorize_exports as Vectorize, WebTransport_exports as WebTransport, Worker_exports as Worker, WorkerConfig, WorkerDefinition_exports as WorkerDefinition, WorkerEnvironment, WorkersAi_exports as WorkersAi, Workflow_exports as Workflow, WorkflowBinding_exports as WorkflowBinding, WorkflowDefinition_exports as WorkflowDefinition };
3900
+ export { AiGateway_exports as AiGateway, AnalyticsEngine_exports as AnalyticsEngine, Artifacts_exports as Artifacts, Binding_exports as Binding, BrowserRendering_exports as BrowserRendering, Cache_exports as Cache, CloudflareOtlp_exports as CloudflareOtlp, ContainerNamespace_exports as ContainerNamespace, D1_exports as D1, DurableObject_exports as DurableObject, DurableObjectAlarm_exports as DurableObjectAlarm, DurableObjectDefinition_exports as DurableObjectDefinition, DurableObjectNamespace_exports as DurableObjectNamespace, DurableObjectRpcWebSocket_exports as DurableObjectRpcWebSocket, DurableObjectSqlite_exports as DurableObjectSqlite, DurableObjectState_exports as DurableObjectState, DurableObjectStorage_exports as DurableObjectStorage, DurableObjectWebSocket_exports as DurableObjectWebSocket, Email_exports as Email, Environment_exports as Environment, Hyperdrive_exports as Hyperdrive, Images_exports as Images, Kv_exports as Kv, Queue_exports as Queue, QueueBinding_exports as QueueBinding, QueueDefinition_exports as QueueDefinition, R2_exports as R2, Rpc_exports as Rpc, RpcDefinition_exports as RpcDefinition, RpcTracing_exports as RpcTracing, ServiceBinding_exports as ServiceBinding, Vectorize_exports as Vectorize, WebTransport_exports as WebTransport, Worker_exports as Worker, WorkerConfig, WorkerDefinition_exports as WorkerDefinition, WorkerEnvironment, WorkersAi_exports as WorkersAi, Workflow_exports as Workflow, WorkflowBinding_exports as WorkflowBinding, WorkflowDefinition_exports as WorkflowDefinition };