@sentry/cloudflare 11.11.0 → 11.12.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 (90) hide show
  1. package/build/cjs/dev/client.js.map +1 -1
  2. package/build/cjs/dev/durableobject.js +20 -4
  3. package/build/cjs/dev/durableobject.js.map +1 -1
  4. package/build/cjs/dev/instrumentations/worker/instrumentEnv.js +4 -3
  5. package/build/cjs/dev/instrumentations/worker/instrumentEnv.js.map +1 -1
  6. package/build/cjs/dev/instrumentations/worker/instrumentQueue.js +31 -0
  7. package/build/cjs/dev/instrumentations/worker/instrumentQueue.js.map +1 -1
  8. package/build/cjs/dev/instrumentations/worker/instrumentQueueProducer.js +38 -16
  9. package/build/cjs/dev/instrumentations/worker/instrumentQueueProducer.js.map +1 -1
  10. package/build/cjs/dev/utils/{rpcPropagation.js → bindingPropagation.js} +6 -3
  11. package/build/cjs/dev/utils/bindingPropagation.js.map +1 -0
  12. package/build/cjs/dev/utils/queueTraceMeta.js +44 -0
  13. package/build/cjs/dev/utils/queueTraceMeta.js.map +1 -0
  14. package/build/cjs/dev/workflows.js +4 -1
  15. package/build/cjs/dev/workflows.js.map +1 -1
  16. package/build/cjs/dev/wrapRequestHandlerWithInit.js +9 -1
  17. package/build/cjs/dev/wrapRequestHandlerWithInit.js.map +1 -1
  18. package/build/cjs/prod/client.js.map +1 -1
  19. package/build/cjs/prod/durableobject.js +20 -4
  20. package/build/cjs/prod/durableobject.js.map +1 -1
  21. package/build/cjs/prod/instrumentations/worker/instrumentEnv.js +4 -3
  22. package/build/cjs/prod/instrumentations/worker/instrumentEnv.js.map +1 -1
  23. package/build/cjs/prod/instrumentations/worker/instrumentQueue.js +31 -0
  24. package/build/cjs/prod/instrumentations/worker/instrumentQueue.js.map +1 -1
  25. package/build/cjs/prod/instrumentations/worker/instrumentQueueProducer.js +38 -16
  26. package/build/cjs/prod/instrumentations/worker/instrumentQueueProducer.js.map +1 -1
  27. package/build/cjs/prod/utils/{rpcPropagation.js → bindingPropagation.js} +6 -3
  28. package/build/cjs/prod/utils/bindingPropagation.js.map +1 -0
  29. package/build/cjs/prod/utils/queueTraceMeta.js +44 -0
  30. package/build/cjs/prod/utils/queueTraceMeta.js.map +1 -0
  31. package/build/cjs/prod/workflows.js +4 -1
  32. package/build/cjs/prod/workflows.js.map +1 -1
  33. package/build/cjs/prod/wrapRequestHandlerWithInit.js +9 -1
  34. package/build/cjs/prod/wrapRequestHandlerWithInit.js.map +1 -1
  35. package/build/esm/dev/client.js.map +1 -1
  36. package/build/esm/dev/durableobject.js +20 -4
  37. package/build/esm/dev/durableobject.js.map +1 -1
  38. package/build/esm/dev/instrumentations/worker/instrumentEnv.js +3 -2
  39. package/build/esm/dev/instrumentations/worker/instrumentEnv.js.map +1 -1
  40. package/build/esm/dev/instrumentations/worker/instrumentQueue.js +32 -1
  41. package/build/esm/dev/instrumentations/worker/instrumentQueue.js.map +1 -1
  42. package/build/esm/dev/instrumentations/worker/instrumentQueueProducer.js +39 -17
  43. package/build/esm/dev/instrumentations/worker/instrumentQueueProducer.js.map +1 -1
  44. package/build/esm/dev/package.json +1 -1
  45. package/build/esm/dev/utils/{rpcPropagation.js → bindingPropagation.js} +6 -4
  46. package/build/esm/dev/utils/bindingPropagation.js.map +1 -0
  47. package/build/esm/dev/utils/queueTraceMeta.js +41 -0
  48. package/build/esm/dev/utils/queueTraceMeta.js.map +1 -0
  49. package/build/esm/dev/workflows.js +5 -2
  50. package/build/esm/dev/workflows.js.map +1 -1
  51. package/build/esm/dev/wrapRequestHandlerWithInit.js +9 -1
  52. package/build/esm/dev/wrapRequestHandlerWithInit.js.map +1 -1
  53. package/build/esm/prod/client.js.map +1 -1
  54. package/build/esm/prod/durableobject.js +20 -4
  55. package/build/esm/prod/durableobject.js.map +1 -1
  56. package/build/esm/prod/instrumentations/worker/instrumentEnv.js +3 -2
  57. package/build/esm/prod/instrumentations/worker/instrumentEnv.js.map +1 -1
  58. package/build/esm/prod/instrumentations/worker/instrumentQueue.js +32 -1
  59. package/build/esm/prod/instrumentations/worker/instrumentQueue.js.map +1 -1
  60. package/build/esm/prod/instrumentations/worker/instrumentQueueProducer.js +39 -17
  61. package/build/esm/prod/instrumentations/worker/instrumentQueueProducer.js.map +1 -1
  62. package/build/esm/prod/package.json +1 -1
  63. package/build/esm/prod/utils/{rpcPropagation.js → bindingPropagation.js} +6 -4
  64. package/build/esm/prod/utils/bindingPropagation.js.map +1 -0
  65. package/build/esm/prod/utils/queueTraceMeta.js +41 -0
  66. package/build/esm/prod/utils/queueTraceMeta.js.map +1 -0
  67. package/build/esm/prod/workflows.js +5 -2
  68. package/build/esm/prod/workflows.js.map +1 -1
  69. package/build/esm/prod/wrapRequestHandlerWithInit.js +9 -1
  70. package/build/esm/prod/wrapRequestHandlerWithInit.js.map +1 -1
  71. package/build/types/client.d.ts +30 -0
  72. package/build/types/client.d.ts.map +1 -1
  73. package/build/types/durableobject.d.ts.map +1 -1
  74. package/build/types/instrumentations/worker/instrumentEnv.d.ts +1 -1
  75. package/build/types/instrumentations/worker/instrumentEnv.d.ts.map +1 -1
  76. package/build/types/instrumentations/worker/instrumentQueue.d.ts.map +1 -1
  77. package/build/types/instrumentations/worker/instrumentQueueProducer.d.ts +1 -1
  78. package/build/types/instrumentations/worker/instrumentQueueProducer.d.ts.map +1 -1
  79. package/build/types/utils/{rpcPropagation.d.ts → bindingPropagation.d.ts} +6 -1
  80. package/build/types/utils/bindingPropagation.d.ts.map +1 -0
  81. package/build/types/utils/queueTraceMeta.d.ts +7 -0
  82. package/build/types/utils/queueTraceMeta.d.ts.map +1 -0
  83. package/build/types/workflows.d.ts.map +1 -1
  84. package/build/types/wrapRequestHandlerWithInit.d.ts.map +1 -1
  85. package/package.json +16 -13
  86. package/build/cjs/dev/utils/rpcPropagation.js.map +0 -1
  87. package/build/cjs/prod/utils/rpcPropagation.js.map +0 -1
  88. package/build/esm/dev/utils/rpcPropagation.js.map +0 -1
  89. package/build/esm/prod/utils/rpcPropagation.js.map +0 -1
  90. package/build/types/utils/rpcPropagation.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentQueueProducer.js","sources":["../../../../../src/instrumentations/worker/instrumentQueueProducer.ts"],"sourcesContent":["import type { MessageSendRequest, Queue, QueueSendBatchOptions, QueueSendOptions } from '@cloudflare/workers-types';\nimport {\n SENTRY_OP,\n SENTRY_ORIGIN,\n MESSAGING_BATCH_MESSAGE_COUNT,\n MESSAGING_DESTINATION_NAME,\n MESSAGING_MESSAGE_BODY_SIZE,\n MESSAGING_OPERATION_NAME,\n MESSAGING_OPERATION_TYPE,\n MESSAGING_SYSTEM,\n} from '@sentry/conventions/attributes';\nimport { QUEUE_PUBLISH } from '@sentry/conventions/op';\nimport { startSpan } from '@sentry/core';\n\nconst ORIGIN = 'auto.faas.cloudflare.queue';\n\nfunction startPublishSpan<T>(\n options: {\n bindingName: string;\n bodySize: number | undefined;\n messageCount?: number;\n },\n callback: () => T,\n): T {\n const { bindingName, bodySize, messageCount } = options;\n\n return startSpan(\n {\n name: `send ${bindingName}`,\n attributes: {\n [MESSAGING_SYSTEM]: 'cloudflare',\n [MESSAGING_DESTINATION_NAME]: bindingName,\n [MESSAGING_OPERATION_TYPE]: 'send',\n [MESSAGING_OPERATION_NAME]: 'send',\n [MESSAGING_BATCH_MESSAGE_COUNT]: messageCount,\n [MESSAGING_MESSAGE_BODY_SIZE]: bodySize,\n [SENTRY_OP]: QUEUE_PUBLISH,\n [SENTRY_ORIGIN]: ORIGIN,\n },\n },\n callback,\n );\n}\n\nfunction getBodySize(body: unknown): number | undefined {\n if (body == null) {\n return undefined;\n }\n\n if (typeof body === 'string') {\n return new TextEncoder().encode(body).byteLength;\n }\n\n if (body instanceof ArrayBuffer) {\n return body.byteLength;\n }\n\n if (ArrayBuffer.isView(body)) {\n return body.byteLength;\n }\n\n try {\n return new TextEncoder().encode(JSON.stringify(body)).byteLength;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Wraps a Queue producer binding to create `queue.publish` spans on\n * `send` and `sendBatch` calls.\n *\n * The queue's own name is not available on the binding object, so we use\n * the env binding key (e.g. `MY_QUEUE`) as `messaging.destination.name`.\n */\nexport function instrumentQueueProducer<T extends Queue>(queue: T, bindingName: string): T {\n return new Proxy(queue, {\n get(target, prop, receiver) {\n if (prop === 'send') {\n const original = Reflect.get(target, prop, receiver) as Queue['send'];\n\n return function (this: unknown, message: unknown, options?: QueueSendOptions): ReturnType<Queue['send']> {\n return startPublishSpan({ bindingName, bodySize: getBodySize(message) }, () =>\n Reflect.apply(original, target, [message, options]),\n );\n };\n }\n\n if (prop === 'sendBatch') {\n const original = Reflect.get(target, prop, receiver) as Queue['sendBatch'];\n return function (\n this: unknown,\n messages: Iterable<MessageSendRequest>,\n options?: QueueSendBatchOptions,\n ): ReturnType<Queue['sendBatch']> {\n const messageArray = Array.from(messages);\n const totalBodySize = messageArray.reduce<number | undefined>((acc, m) => {\n const size = getBodySize(m.body);\n if (size === undefined) {\n return acc;\n }\n return (acc ?? 0) + size;\n }, undefined);\n\n return startPublishSpan({ bindingName, bodySize: totalBodySize, messageCount: messageArray.length }, () =>\n Reflect.apply(original, target, [messageArray, options]),\n );\n };\n }\n\n const value = Reflect.get(target, prop) as unknown;\n\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n}\n"],"names":["startSpan","MESSAGING_SYSTEM","MESSAGING_DESTINATION_NAME","MESSAGING_OPERATION_TYPE","MESSAGING_OPERATION_NAME","MESSAGING_BATCH_MESSAGE_COUNT","MESSAGING_MESSAGE_BODY_SIZE","SENTRY_OP","QUEUE_PUBLISH","SENTRY_ORIGIN"],"mappings":";;;;;;AAcA,MAAM,MAAA,GAAS,4BAAA;AAEf,SAAS,gBAAA,CACP,SAKA,QAAA,EACG;AACH,EAAA,MAAM,EAAE,WAAA,EAAa,QAAA,EAAU,YAAA,EAAa,GAAI,OAAA;AAEhD,EAAA,OAAOA,cAAA;AAAA,IACL;AAAA,MACE,IAAA,EA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A,CAAM,IAAA,CAAK,MAAM,CAAA,GAAI,KAAA;AAAA,IAC5D;AAAA,GACD,CAAA;AACH;;;;"}
1
+ {"version":3,"file":"instrumentQueueProducer.js","sources":["../../../../../src/instrumentations/worker/instrumentQueueProducer.ts"],"sourcesContent":["import type { MessageSendRequest, Queue, QueueSendBatchOptions, QueueSendOptions } from '@cloudflare/workers-types';\nimport {\n SENTRY_OP,\n SENTRY_ORIGIN,\n MESSAGING_BATCH_MESSAGE_COUNT,\n MESSAGING_DESTINATION_NAME,\n MESSAGING_MESSAGE_BODY_SIZE,\n MESSAGING_OPERATION_NAME,\n MESSAGING_OPERATION_TYPE,\n MESSAGING_SYSTEM,\n} from '@sentry/conventions/attributes';\nimport { QUEUE_PUBLISH } from '@sentry/conventions/op';\nimport { getTraceData, startSpan, type Span } from '@sentry/core';\nimport { addQueueTraceContext } from '../../utils/queueTraceMeta';\n\nconst ORIGIN = 'auto.faas.cloudflare.queue';\n\nfunction startPublishSpan<T>(\n options: {\n bindingName: string;\n bodySize: number | undefined;\n messageCount?: number;\n },\n callback: (span: Span) => T,\n): T {\n const { bindingName, bodySize, messageCount } = options;\n\n return startSpan(\n {\n name: `send ${bindingName}`,\n attributes: {\n [MESSAGING_SYSTEM]: 'cloudflare',\n [MESSAGING_DESTINATION_NAME]: bindingName,\n [MESSAGING_OPERATION_TYPE]: 'send',\n [MESSAGING_OPERATION_NAME]: 'send',\n [MESSAGING_BATCH_MESSAGE_COUNT]: messageCount,\n [MESSAGING_MESSAGE_BODY_SIZE]: bodySize,\n [SENTRY_OP]: QUEUE_PUBLISH,\n [SENTRY_ORIGIN]: ORIGIN,\n },\n },\n callback,\n );\n}\n\nfunction getBodySize(body: unknown): number | undefined {\n if (body == null) {\n return undefined;\n }\n\n if (typeof body === 'string') {\n return new TextEncoder().encode(body).byteLength;\n }\n\n if (body instanceof ArrayBuffer) {\n return body.byteLength;\n }\n\n if (ArrayBuffer.isView(body)) {\n return body.byteLength;\n }\n\n try {\n return new TextEncoder().encode(JSON.stringify(body)).byteLength;\n } catch {\n return undefined;\n }\n}\n\nfunction getBatchBodySize(messages: MessageSendRequest[]): number | undefined {\n return messages.reduce<number | undefined>((acc, message) => {\n const size = getBodySize(message.body);\n if (size === undefined) {\n return acc;\n }\n return (acc ?? 0) + size;\n }, undefined);\n}\n\n/**\n * Wraps a Queue producer binding to create `queue.publish` spans on\n * `send` and `sendBatch` calls.\n *\n * The queue's own name is not available on the binding object, so we use\n * the env binding key (e.g. `MY_QUEUE`) as `messaging.destination.name`.\n */\nexport function instrumentQueueProducer<T extends Queue>(\n queue: T,\n bindingName: string,\n enableTracePropagation = false,\n): T {\n return new Proxy(queue, {\n get(target, prop, receiver) {\n if (prop === 'send') {\n const original = Reflect.get(target, prop, receiver) as Queue['send'];\n\n return function (this: unknown, message: unknown, options?: QueueSendOptions): ReturnType<Queue['send']> {\n if (!enableTracePropagation) {\n return startPublishSpan({ bindingName, bodySize: getBodySize(message) }, () =>\n Reflect.apply(original, target, [message, options]),\n );\n }\n\n // The body size is only known once the trace context is injected, which must happen inside\n // the span so the carrier points to queue.publish rather than its parent.\n return startPublishSpan({ bindingName, bodySize: undefined }, span => {\n const tracedMessage = addQueueTraceContext(message, getTraceData()['sentry-trace']);\n span.setAttribute(MESSAGING_MESSAGE_BODY_SIZE, getBodySize(tracedMessage));\n return Reflect.apply(original, target, [tracedMessage, options]);\n });\n };\n }\n\n if (prop === 'sendBatch') {\n const original = Reflect.get(target, prop, receiver) as Queue['sendBatch'];\n return function (\n this: unknown,\n messages: Iterable<MessageSendRequest>,\n options?: QueueSendBatchOptions,\n ): ReturnType<Queue['sendBatch']> {\n const messageArray = Array.from(messages);\n const messageCount = messageArray.length;\n\n if (!enableTracePropagation) {\n return startPublishSpan({ bindingName, bodySize: getBatchBodySize(messageArray), messageCount }, () =>\n Reflect.apply(original, target, [messageArray, options]),\n );\n }\n\n return startPublishSpan({ bindingName, bodySize: undefined, messageCount }, span => {\n // Every message is published by this one span, so they all share its trace context.\n const sentryTrace = getTraceData()['sentry-trace'];\n const tracedMessages = messageArray.map(message => ({\n ...message,\n body: addQueueTraceContext(message.body, sentryTrace),\n }));\n\n span.setAttribute(MESSAGING_MESSAGE_BODY_SIZE, getBatchBodySize(tracedMessages));\n return Reflect.apply(original, target, [tracedMessages, options]);\n });\n };\n }\n\n const value = Reflect.get(target, prop) as unknown;\n\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n}\n"],"names":["startSpan","MESSAGING_SYSTEM","MESSAGING_DESTINATION_NAME","MESSAGING_OPERATION_TYPE","MESSAGING_OPERATION_NAME","MESSAGING_BATCH_MESSAGE_COUNT","MESSAGING_MESSAGE_BODY_SIZE","SENTRY_OP","QUEUE_PUBLISH","SENTRY_ORIGIN","addQueueTraceContext","getTraceData"],"mappings":";;;;;;;AAeA,MAAM,MAAA,GAAS,4BAAA;AAEf,SAAS,gBAAA,CACP,SAKA,QAAA,EACG;AACH,EAAA,MAAM,EAAE,WAAA,EAAa,QAAA,EAAU,YAAA,EAAa,GAAI,OAAA;AAEhD,EAAA,OAAOA,cAAA;AAAA,IACL;AAAA,MACE,IAAA,EAAM,QAAQ,WAAW,CAAA,CAAA;AAAA,MACzB,UAAA,EAAY;AAAA,QACV,CAACC,2BAAgB,GAAG,YAAA;AAAA,QACpB,CAACC,qCAA0B,GAAG,WAAA;AAAA,QAC9B,CAACC,mCAAwB,GAAG,MAAA;AAAA,QAC5B,CAACC,mCAAwB,GAAG,MAAA;AAAA,QAC5B,CAACC,wCAA6B,GAAG,YAAA;AAAA,QACjC,CAACC,sCAA2B,GAAG,QAAA;AAAA,QAC/B,CAACC,oBAAS,GAAGC,gBAAA;AAAA,QACb,CAACC,wBAAa,GAAG;AAAA;AACnB,KACF;AAAA,IACA;AAAA,GACF;AACF;AAEA,SAAS,YAAY,IAAA,EAAmC;AACtD,EAAA,IAAI,QAAQ,IAAA,EAAM;AAChB,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,IAAI,OAAO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WAAA,GAAcK,iBAAA,EAAa,CAAE,cAAc,CAAA;AACjD,YAAA,MAAM,cAAA,GAAiB,YAAA,CAAa,GAAA,CAAI,CAAA,OAAA,MAAY;AAAA,cAClD,GAAG,OAAA;AAAA,cACH,IAAA,EAAMD,mCAAA,CAAqB,OAAA,CAAQ,IAAA,EAAM,WAAW;AAAA,aACtD,CAAE,CAAA;AAEF,YAAA,IAAA,CAAK,YAAA,CAAaJ,sCAAA,EAA6B,gBAAA,CAAiB,cAAc,CAAC,CAAA;AAC/E,YAAA,OAAO,QAAQ,KAAA,CAAM,QAAA,EAAU,QAAQ,CAAC,cAAA,EAAgB,OAAO,CAAC,CAAA;AAAA,UAClE,CAAC,CAAA;AAAA,QACH,CAAA;AAAA,MACF;AAEA,MAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,IAAI,CAAA;AAEtC,MAAA,OAAO,OAAO,KAAA,KAAU,UAAA,GAAa,KAAA,CAAM,IAAA,CAAK,MAAM,CAAA,GAAI,KAAA;AAAA,IAC5D;AAAA,GACD,CAAA;AACH;;;;"}
@@ -3,13 +3,16 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3
3
  const core = require('@sentry/core');
4
4
 
5
5
  const PROPAGATE_TO_NONE = () => false;
6
- function createRpcPropagationResolver(options) {
7
- const bindings = options?.rpcTracePropagationBindings;
6
+ function createBindingPropagationResolver(bindings) {
8
7
  if (!bindings?.length) {
9
8
  return PROPAGATE_TO_NONE;
10
9
  }
11
10
  return (bindingName) => core.matchesTracePropagationTargets(bindingName, bindings, true);
12
11
  }
12
+ function createRpcPropagationResolver(options) {
13
+ return createBindingPropagationResolver(options?.rpcTracePropagationBindings);
14
+ }
13
15
 
16
+ exports.createBindingPropagationResolver = createBindingPropagationResolver;
14
17
  exports.createRpcPropagationResolver = createRpcPropagationResolver;
15
- //# sourceMappingURL=rpcPropagation.js.map
18
+ //# sourceMappingURL=bindingPropagation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bindingPropagation.js","sources":["../../../../src/utils/bindingPropagation.ts"],"sourcesContent":["import { matchesTracePropagationTargets, type TracePropagationTargets } from '@sentry/core';\nimport type { CloudflareOptions } from '../client';\n\nconst PROPAGATE_TO_NONE = () => false;\n\n/**\n * Builds the per-binding predicate that decides whether a binding takes part in trace propagation.\n */\nexport function createBindingPropagationResolver(\n bindings: TracePropagationTargets | undefined,\n): (bindingName: string) => boolean {\n if (!bindings?.length) {\n return PROPAGATE_TO_NONE;\n }\n\n // Strings must match a binding name exactly, without this, an entry of `DB` would also enable\n // propagation for a binding named `MY_DB`. Regular expressions still give pattern matching.\n return (bindingName: string) => matchesTracePropagationTargets(bindingName, bindings, true);\n}\n\n/**\n * Builds the per-binding predicate that decides whether a binding takes part in RPC trace\n * propagation.\n *\n * Callers only. Receivers continue an incoming trace whenever one arrives, so they have nothing to\n * match against.\n */\nexport function createRpcPropagationResolver(options: CloudflareOptions | undefined): (bindingName: string) => boolean {\n return createBindingPropagationResolver(options?.rpcTracePropagationBindings);\n}\n"],"names":["matchesTracePropagationTargets"],"mappings":";;;;AAGA,MAAM,oBAAoB,MAAM,KAAA;AAKzB,SAAS,iCACd,QAAA,EACkC;AAClC,EAAA,IAAI,CAAC,UAAU,MAAA,EAAQ;AACrB,IAAA,OAAO,iBAAA;AAAA,EACT;AAIA,EAAA,OAAO,CAAC,WAAA,KAAwBA,mCAAA,CAA+B,WAAA,EAAa,UAAU,IAAI,CAAA;AAC5F;AASO,SAAS,6BAA6B,OAAA,EAA0E;AACrH,EAAA,OAAO,gCAAA,CAAiC,SAAS,2BAA2B,CAAA;AAC9E;;;;;"}
@@ -0,0 +1,44 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+
3
+ const core = require('@sentry/core');
4
+
5
+ const SENTRY_QUEUE_TRACE_KEY = "__sentry_queue_trace__";
6
+ function isQueueTraceCarrier(body) {
7
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
8
+ return false;
9
+ }
10
+ const prototype = Object.getPrototypeOf(body);
11
+ return prototype === Object.prototype || prototype === null;
12
+ }
13
+ function addQueueTraceContext(body, sentryTrace) {
14
+ if (!isQueueTraceCarrier(body) || !sentryTrace || Object.prototype.hasOwnProperty.call(body, SENTRY_QUEUE_TRACE_KEY)) {
15
+ return body;
16
+ }
17
+ return { ...body, [SENTRY_QUEUE_TRACE_KEY]: sentryTrace };
18
+ }
19
+ function extractQueueTraceContext(body) {
20
+ if (!isQueueTraceCarrier(body)) {
21
+ return void 0;
22
+ }
23
+ if (!Object.prototype.hasOwnProperty.call(body, SENTRY_QUEUE_TRACE_KEY)) {
24
+ return void 0;
25
+ }
26
+ const sentryTrace = body[SENTRY_QUEUE_TRACE_KEY];
27
+ Reflect.deleteProperty(body, SENTRY_QUEUE_TRACE_KEY);
28
+ if (typeof sentryTrace !== "string") {
29
+ return void 0;
30
+ }
31
+ const traceparentData = core.extractTraceparentData(sentryTrace);
32
+ if (!traceparentData?.traceId || !traceparentData.parentSpanId) {
33
+ return void 0;
34
+ }
35
+ return {
36
+ traceId: traceparentData.traceId,
37
+ spanId: traceparentData.parentSpanId,
38
+ sampled: traceparentData.parentSampled
39
+ };
40
+ }
41
+
42
+ exports.addQueueTraceContext = addQueueTraceContext;
43
+ exports.extractQueueTraceContext = extractQueueTraceContext;
44
+ //# sourceMappingURL=queueTraceMeta.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queueTraceMeta.js","sources":["../../../../src/utils/queueTraceMeta.ts"],"sourcesContent":["import { extractTraceparentData } from '@sentry/core';\n\nconst SENTRY_QUEUE_TRACE_KEY = '__sentry_queue_trace__';\n\nfunction isQueueTraceCarrier(body: unknown): body is Record<string, unknown> {\n if (typeof body !== 'object' || body === null || Array.isArray(body)) {\n return false;\n }\n\n // Cloudflare Queues has no message-header API. Only record-like bodies can carry a named field; binary data and\n // other structured-clone values must pass through untouched.\n const prototype = Object.getPrototypeOf(body);\n return prototype === Object.prototype || prototype === null;\n}\n\nexport function addQueueTraceContext(body: unknown, sentryTrace: string | undefined): unknown {\n if (\n !isQueueTraceCarrier(body) ||\n !sentryTrace ||\n Object.prototype.hasOwnProperty.call(body, SENTRY_QUEUE_TRACE_KEY)\n ) {\n return body;\n }\n\n // Cloudflare rejects messages over 128 KB (https://developers.cloudflare.com/queues/platform/limits/),\n // and the field adds about 80 bytes, so a payload right under the limit can start failing to send.\n // Span links only need `sentry-trace`, so baggage would only cost more of that budget. Copy instead\n // of mutating, because callers may reuse a payload after enqueueing it.\n return { ...body, [SENTRY_QUEUE_TRACE_KEY]: sentryTrace };\n}\n\nexport function extractQueueTraceContext(\n body: unknown,\n): { traceId: string; spanId: string; sampled: boolean | undefined } | undefined {\n if (!isQueueTraceCarrier(body)) {\n return undefined;\n }\n\n if (!Object.prototype.hasOwnProperty.call(body, SENTRY_QUEUE_TRACE_KEY)) {\n return undefined;\n }\n\n const sentryTrace = body[SENTRY_QUEUE_TRACE_KEY];\n\n // The key is reserved transport metadata, so strip it even if its value is not a valid trace.\n // Unlike `delete`, this returns false instead of throwing on frozen bodies, which keep the field.\n Reflect.deleteProperty(body, SENTRY_QUEUE_TRACE_KEY);\n\n if (typeof sentryTrace !== 'string') {\n return undefined;\n }\n\n const traceparentData = extractTraceparentData(sentryTrace);\n if (!traceparentData?.traceId || !traceparentData.parentSpanId) {\n return undefined;\n }\n\n return {\n traceId: traceparentData.traceId,\n spanId: traceparentData.parentSpanId,\n sampled: traceparentData.parentSampled,\n };\n}\n"],"names":["extractTraceparentData"],"mappings":";;;;AAEA,MAAM,sBAAA,GAAyB,wBAAA;AAE/B,SAAS,oBAAoB,IAAA,EAAgD;AAC3E,EAAA,IAAI,OAAO,SAAS,QAAA,IAAY,IAAA,KAAS,QAAQ,KAAA,CAAM,OAAA,CAAQ,IAAI,CAAA,EAAG;AACpE,IAAA,OAAO,KAAA;AAAA,EACT;AAIA,EAAA,MAAM,SAAA,GAAY,MAAA,CAAO,cAAA,CAAe,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
27
  };
28
28
  }
29
+ function isNonRetryableError(error) {
30
+ return core.isError(error) && (error.name === "NonRetryableError" || String(error.message).startsWith("NonRetryableError"));
31
+ }
29
32
  class WrappedWorkflowStep {
30
33
  constructor(_instanceId, _options, _step, _waitUntil, _isolationScope) {
31
34
  this._instanceId = _instanceId;
@@ -75,7 +78,7 @@ class WrappedWorkflowStep {
75
78
  span.setStatus({ code: 1 });
76
79
  return result;
77
80
  } catch (error) {
78
- if (isFinalAttempt) {
81
+ if (isFinalAttempt || isNonRetryableError(error)) {
79
82
  core.captureException(error, { mechanism: { handled: true, type: "auto.faas.cloudflare.workflow" } });
80
83
  }
81
84
  throw error;
@@ -1 +1 @@
1
- {"version":3,"file":"workflows.js","sources":["../../../src/workflows.ts"],"sourcesContent":["import {\n SENTRY_SEGMENT_NAME_SOURCE,\n CODE_FUNCTION_NAME,\n SENTRY_OP,\n SENTRY_ORIGIN,\n CLOUDFLARE_WORKFLOW_ATTEMPT,\n CLOUDFLARE_WORKFLOW_RETRIES_BACKOFF,\n CLOUDFLARE_WORKFLOW_RETRIES_DELAY,\n CLOUDFLARE_WORKFLOW_RETRIES_LIMIT,\n CLOUDFLARE_WORKFLOW_TIMEOUT,\n} from '@sentry/conventions/attributes';\nimport { FUNCTION } from '@sentry/conventions/op';\nimport type { PropagationContext, Scope } from '@sentry/core';\nimport { captureException, flush, getCurrentScope, startSpan, withIsolationScope, withScope } from '@sentry/core';\nimport type {\n WorkflowDelayDuration,\n WorkflowEntrypoint,\n WorkflowEvent,\n WorkflowSleepDuration,\n WorkflowStep,\n WorkflowStepConfig,\n WorkflowStepContext,\n WorkflowStepEvent,\n WorkflowStepRollbackOptions,\n WorkflowTimeoutDuration,\n} from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategyForWorker } from './utils/asyncContextStrategy';\nimport type { CloudflareOptions } from './client';\nimport { flushAndDispose, getOriginalWaitUntil } from './flush';\nimport { markAsInstrumented } from './instrument';\nimport { instrumentEnv } from './instrumentations/worker/instrumentEnv';\nimport { addCloudResourceContext } from './scope-utils';\nimport { init } from './sdk';\nimport { instrumentContext } from './utils/instrumentContext';\nimport type { DefaultEnv, ResolveEnv, StrictCloudflareOptions } from './types';\nimport { getInvocationState } from './utils/invocationContext';\nimport { withInvocationIsolationScope } from './utils/invocationScope';\n\nconst UUID_REGEX = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i;\n\n/**\n * Hashes a string to a UUID using SHA-1.\n */\nexport async function deterministicTraceIdFromInstanceId(instanceId: string): Promise<string> {\n const buf = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(instanceId));\n return (\n Array.from(new Uint8Array(buf))\n // We only need the first 16 bytes for the 32 characters\n .slice(0, 16)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('')\n );\n}\n\nasync function propagationContextFromInstanceId(instanceId: string): Promise<PropagationContext> {\n const traceId = UUID_REGEX.test(instanceId)\n ? instanceId.replace(/-/g, '')\n : await deterministicTraceIdFromInstanceId(instanceId);\n\n // Derive sampleRand from last 4 characters of the random UUID\n //\n // We cannot store any state between workflow steps, so we derive the\n // sampleRand from the traceId itself. This ensures that the sampling is\n // consistent across all steps in the same workflow instance.\n const sampleRand = parseInt(traceId.slice(-4), 16) / 0xffff;\n\n return {\n traceId,\n sampleRand,\n };\n}\n\nclass WrappedWorkflowStep implements WorkflowStep {\n public constructor(\n private _instanceId: string,\n private _options: CloudflareOptions,\n private _step: WorkflowStep,\n private _waitUntil: ExecutionContext['waitUntil'],\n private _isolationScope: Scope,\n ) {}\n\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n callback: (ctx: WorkflowStepContext) => Promise<T>,\n rollbackOptions?: WorkflowStepRollbackOptions<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>, const C extends WorkflowStepConfig>(\n name: string,\n config: C,\n callback: (\n ctx: WorkflowStepContext<C['retries'] extends { delay: infer D } ? D : WorkflowDelayDuration | number>,\n ) => Promise<T>,\n rollbackOptions?: WorkflowStepRollbackOptions<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n configOrCallback: WorkflowStepConfig | ((ctx: WorkflowStepContext) => Promise<T>),\n callbackOrRollback?: ((ctx: WorkflowStepContext) => Promise<T>) | WorkflowStepRollbackOptions<T>,\n maybeRollback?: WorkflowStepRollbackOptions<T>,\n ): Promise<T> {\n // Capture the current scope, so parent span (e.g., a startSpan surrounding step.do) is preserved\n const scopeForStep = getCurrentScope();\n\n const hasConfig = typeof configOrCallback !== 'function';\n const config = hasConfig ? configOrCallback : undefined;\n const userCallback = (hasConfig ? callbackOrRollback : configOrCallback) as (\n ctx: WorkflowStepContext,\n ) => Promise<T>;\n const rollbackOptions = (hasConfig ? maybeRollback : callbackOrRollback) as\n | WorkflowStepRollbackOptions<T>\n | undefined;\n\n const instrumentedCallback = async (...args: unknown[]): Promise<T> => {\n // Feature detection: Cloudflare Workflows (April 2026+) pass a step context\n // with `attempt` and `config.retries.limit`. When available, we only capture\n // errors on the final attempt to avoid duplicates during retries.\n const stepContext = args[0] as { attempt?: number; config?: { retries?: { limit?: number } } } | undefined;\n const attempt = stepContext?.attempt;\n const retryLimit = stepContext?.config?.retries?.limit;\n const hasStepContext = typeof attempt === 'number' && typeof retryLimit === 'number';\n\n // Only capture error on final attempt (attempt > retryLimit means no more retries left)\n // or when step context is unavailable (legacy behavior - capture all errors)\n const isFinalAttempt = !hasStepContext || attempt > retryLimit;\n\n // The engine invokes step callbacks outside the async context of `run`, so the\n // run's isolation scope (and with it the invocation state that ties eager sends\n // to this invocation's `waitUntil`) has to be restored explicitly.\n return withIsolationScope(this._isolationScope, () => {\n const invocationState = getInvocationState();\n\n if (invocationState) {\n invocationState.flushPointReached = false;\n }\n\n const stepResult = startSpan(\n {\n name,\n scope: scopeForStep,\n attributes: {\n [SENTRY_OP]: FUNCTION,\n [CODE_FUNCTION_NAME]: name,\n 'workflow.step.name': name,\n [CLOUDFLARE_WORKFLOW_TIMEOUT]: config?.timeout,\n [CLOUDFLARE_WORKFLOW_RETRIES_BACKOFF]: config?.retries?.backoff,\n // In workers-types v5, `delay` may be a `WorkflowDelayFunction`, which isn't a valid span attribute value.\n [CLOUDFLARE_WORKFLOW_RETRIES_DELAY]:\n typeof config?.retries?.delay === 'function' ? undefined : config?.retries?.delay,\n [CLOUDFLARE_WORKFLOW_RETRIES_LIMIT]: config?.retries?.limit,\n [CLOUDFLARE_WORKFLOW_ATTEMPT]: attempt,\n [SENTRY_ORIGIN]: 'auto.faas.cloudflare.workflow',\n [SENTRY_SEGMENT_NAME_SOURCE]: 'task',\n },\n },\n async span => {\n try {\n const result = await (userCallback as (...args: unknown[]) => Promise<T>)(...args);\n span.setStatus({ code: 1 });\n return result;\n } catch (error) {\n if (isFinalAttempt) {\n captureException(error, { mechanism: { handled: true, type: 'auto.faas.cloudflare.workflow' } });\n }\n throw error;\n }\n },\n );\n // Deliver after the step span has ended, so the span rides this flush instead of\n // starting an eager drain (same ordering as `wrapMethodWithSentry`'s teardown). The flush runs on the\n // step's scope: the engine calls the step callback outside of `run()`, so the current scope here has\n // neither the client nor the run's trace, and envelopes without a DSC are dropped by Relay.\n return stepResult.then(\n result => {\n this._waitUntil(withScope(scopeForStep, () => flush(2000)));\n return result;\n },\n error => {\n this._waitUntil(withScope(scopeForStep, () => flush(2000)));\n throw error;\n },\n );\n });\n };\n\n if (config) {\n return rollbackOptions\n ? this._step.do(name, config, instrumentedCallback, rollbackOptions)\n : this._step.do(name, config, instrumentedCallback);\n }\n\n return rollbackOptions\n ? this._step.do(name, instrumentedCallback, rollbackOptions)\n : this._step.do(name, instrumentedCallback);\n }\n\n public async sleep(name: string, duration: WorkflowSleepDuration): Promise<void> {\n return this._step.sleep(name, duration);\n }\n\n public async sleepUntil(name: string, timestamp: Date | number): Promise<void> {\n return this._step.sleepUntil(name, timestamp);\n }\n\n public async waitForEvent<T extends Rpc.Serializable<T>>(\n name: string,\n options: { type: string; timeout?: WorkflowTimeoutDuration | number },\n ): Promise<WorkflowStepEvent<T>> {\n return this._step.waitForEvent<T>(name, options);\n }\n}\n\n/**\n * Instruments a Cloudflare Workflow class with Sentry.\n *\n * @example\n * ```typescript\n * const InstrumentedWorkflow = instrumentWorkflowWithSentry(\n * (env) => ({ dsn: env.SENTRY_DSN }),\n * MyWorkflowClass\n * );\n *\n * export default InstrumentedWorkflow;\n * ```\n *\n * @param optionsCallback - Function that returns Sentry options to initialize Sentry\n * @param WorkflowClass - The workflow class to instrument\n * @returns Instrumented workflow class with the same interface\n */\nexport function instrumentWorkflowWithSentry<\n E = DefaultEnv, // Environment type\n P = unknown, // Payload type\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends WorkflowEntrypoint<any, any> = WorkflowEntrypoint<E, P>, // WorkflowEntrypoint type\n // The constraint must not route through `T`: workers-types defaults `WorkflowEntrypoint`'s\n // `Env` to `unknown` (unlike `WorkerEntrypoint`/`DurableObject`, which default to\n // `Cloudflare.Env`), so a bare subclass would be rejected in a `wrangler types` project.\n // The callback env is resolved from the inferred constructor via `ResolveEnv` instead.\n // oxlint-disable-next-line typescript/no-explicit-any\n C extends new (ctx: ExecutionContext, env: any) => WorkflowEntrypoint<any, any> = new (\n ctx: ExecutionContext,\n // oxlint-disable-next-line typescript/no-explicit-any\n env: any,\n ) => T, // Constructor type of the WorkflowEntrypoint class\n O = unknown,\n>(optionsCallback: (env: ResolveEnv<C, E>) => StrictCloudflareOptions<O>, WorkFlowClass: C): C {\n const InstrumentedClass = new Proxy(WorkFlowClass, {\n // oxlint-disable-next-line typescript/no-explicit-any\n construct(target: C, args: [ctx: ExecutionContext, env: any], newTarget) {\n const [ctx, env] = args;\n const context = instrumentContext(ctx);\n const options = optionsCallback(env);\n args[0] = context;\n args[1] = instrumentEnv(env as Record<string, unknown>, options) as E;\n const instance = Reflect.construct(target, args, newTarget) as T;\n return new Proxy(instance, {\n get(obj, prop, receiver) {\n if (prop === 'run') {\n return async function (event: WorkflowEvent<P>, step: WorkflowStep): Promise<unknown> {\n setAsyncLocalStorageAsyncContextStrategyForWorker();\n\n return withInvocationIsolationScope(async isolationScope => {\n const waitUntil = getOriginalWaitUntil(context).bind(context);\n const client = init({ ...options, ctx: context, enableDedupe: false });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return withScope(async scope => {\n const propagationContext = await propagationContextFromInstanceId(event.instanceId);\n scope.setPropagationContext(propagationContext);\n\n try {\n return await obj.run.call(\n obj,\n event,\n new WrappedWorkflowStep(event.instanceId, options, step, waitUntil, isolationScope),\n );\n } finally {\n waitUntil(flushAndDispose(client));\n }\n });\n }, context);\n };\n }\n return Reflect.get(obj, prop, receiver);\n },\n });\n },\n });\n // Recognizable for `_INTERNAL_wrapUnlessInstrumented`, so auto-instrumentation never nests wrappers.\n markAsInstrumented(InstrumentedClass);\n return InstrumentedClass;\n}\n"],"names":["getCurrentScope","withIsolationScope","getInvocationState","startSpan","SENTRY_OP","FUNCTION","CODE_FUNCTION_NAME","CLOUDFLARE_WORKFLOW_TIMEOUT","CLOUDFLARE_WORKFLOW_RETRIES_BACKOFF","CLOUDFLARE_WORKFLOW_RETRIES_DELAY","CLOUDFLARE_WORKFLOW_RETRIES_LIMIT","CLOUDFLARE_WORKFLOW_ATTEMPT","SENTRY_ORIGIN","SENTRY_SEGMENT_NAME_SOURCE","captureException","withScope","flush","instrumentContext","instrumentEnv","setAsyncLocalStorageAsyncContextStrategyForWorker","withInvocationIsolationScope","getOriginalWaitUntil","init","addCloudResourceContext","flushAndDispose","markAsInstrumented"],"mappings":";;;;;;;;;;;;;;;AAsCA,MAAM,UAAA,GAAa,qEAAA;AAKnB,eAAsB,mCAAmC,UAAA,EAAqC;AAC5F,EAAA,MAAM,GAAA,GAAM,MAAM,MAAA,CAAO,MAAA,CAAO,MAAA,CAAO,OAAA,EAAS,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,UAAU,CAAC,CAAA;AACpF,EAAA,OACE,KAAA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Content":["import {\n SENTRY_SEGMENT_NAME_SOURCE,\n CODE_FUNCTION_NAME,\n SENTRY_OP,\n SENTRY_ORIGIN,\n CLOUDFLARE_WORKFLOW_ATTEMPT,\n CLOUDFLARE_WORKFLOW_RETRIES_BACKOFF,\n CLOUDFLARE_WORKFLOW_RETRIES_DELAY,\n CLOUDFLARE_WORKFLOW_RETRIES_LIMIT,\n CLOUDFLARE_WORKFLOW_TIMEOUT,\n} from '@sentry/conventions/attributes';\nimport { FUNCTION } from '@sentry/conventions/op';\nimport type { PropagationContext, Scope } from '@sentry/core';\nimport {\n captureException,\n flush,\n getCurrentScope,\n isError,\n startSpan,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type {\n WorkflowDelayDuration,\n WorkflowEntrypoint,\n WorkflowEvent,\n WorkflowSleepDuration,\n WorkflowStep,\n WorkflowStepConfig,\n WorkflowStepContext,\n WorkflowStepEvent,\n WorkflowStepRollbackOptions,\n WorkflowTimeoutDuration,\n} from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategyForWorker } from './utils/asyncContextStrategy';\nimport type { CloudflareOptions } from './client';\nimport { flushAndDispose, getOriginalWaitUntil } from './flush';\nimport { markAsInstrumented } from './instrument';\nimport { instrumentEnv } from './instrumentations/worker/instrumentEnv';\nimport { addCloudResourceContext } from './scope-utils';\nimport { init } from './sdk';\nimport { instrumentContext } from './utils/instrumentContext';\nimport type { DefaultEnv, ResolveEnv, StrictCloudflareOptions } from './types';\nimport { getInvocationState } from './utils/invocationContext';\nimport { withInvocationIsolationScope } from './utils/invocationScope';\n\nconst UUID_REGEX = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i;\n\n/**\n * Hashes a string to a UUID using SHA-1.\n */\nexport async function deterministicTraceIdFromInstanceId(instanceId: string): Promise<string> {\n const buf = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(instanceId));\n return (\n Array.from(new Uint8Array(buf))\n // We only need the first 16 bytes for the 32 characters\n .slice(0, 16)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('')\n );\n}\n\nasync function propagationContextFromInstanceId(instanceId: string): Promise<PropagationContext> {\n const traceId = UUID_REGEX.test(instanceId)\n ? instanceId.replace(/-/g, '')\n : await deterministicTraceIdFromInstanceId(instanceId);\n\n // Derive sampleRand from last 4 characters of the random UUID\n //\n // We cannot store any state between workflow steps, so we derive the\n // sampleRand from the traceId itself. This ensures that the sampling is\n // consistent across all steps in the same workflow instance.\n const sampleRand = parseInt(traceId.slice(-4), 16) / 0xffff;\n\n return {\n traceId,\n sampleRand,\n };\n}\n\n// Same check the Workflows engine uses to stop retrying a step. Not `constructor.name`: a\n// `NonRetryableError` with a custom `name` is retried, so capturing it early would duplicate events.\nfunction isNonRetryableError(error: unknown): boolean {\n return (\n isError(error) && (error.name === 'NonRetryableError' || String(error.message).startsWith('NonRetryableError'))\n );\n}\n\nclass WrappedWorkflowStep implements WorkflowStep {\n public constructor(\n private _instanceId: string,\n private _options: CloudflareOptions,\n private _step: WorkflowStep,\n private _waitUntil: ExecutionContext['waitUntil'],\n private _isolationScope: Scope,\n ) {}\n\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n callback: (ctx: WorkflowStepContext) => Promise<T>,\n rollbackOptions?: WorkflowStepRollbackOptions<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>, const C extends WorkflowStepConfig>(\n name: string,\n config: C,\n callback: (\n ctx: WorkflowStepContext<C['retries'] extends { delay: infer D } ? D : WorkflowDelayDuration | number>,\n ) => Promise<T>,\n rollbackOptions?: WorkflowStepRollbackOptions<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n configOrCallback: WorkflowStepConfig | ((ctx: WorkflowStepContext) => Promise<T>),\n callbackOrRollback?: ((ctx: WorkflowStepContext) => Promise<T>) | WorkflowStepRollbackOptions<T>,\n maybeRollback?: WorkflowStepRollbackOptions<T>,\n ): Promise<T> {\n // Capture the current scope, so parent span (e.g., a startSpan surrounding step.do) is preserved\n const scopeForStep = getCurrentScope();\n\n const hasConfig = typeof configOrCallback !== 'function';\n const config = hasConfig ? configOrCallback : undefined;\n const userCallback = (hasConfig ? callbackOrRollback : configOrCallback) as (\n ctx: WorkflowStepContext,\n ) => Promise<T>;\n const rollbackOptions = (hasConfig ? maybeRollback : callbackOrRollback) as\n | WorkflowStepRollbackOptions<T>\n | undefined;\n\n const instrumentedCallback = async (...args: unknown[]): Promise<T> => {\n // Feature detection: Cloudflare Workflows (April 2026+) pass a step context\n // with `attempt` and `config.retries.limit`. When available, we only capture\n // errors on the final attempt to avoid duplicates during retries.\n const stepContext = args[0] as { attempt?: number; config?: { retries?: { limit?: number } } } | undefined;\n const attempt = stepContext?.attempt;\n const retryLimit = stepContext?.config?.retries?.limit;\n const hasStepContext = typeof attempt === 'number' && typeof retryLimit === 'number';\n\n // Only capture error on final attempt (attempt > retryLimit means no more retries left)\n // or when step context is unavailable (legacy behavior - capture all errors)\n const isFinalAttempt = !hasStepContext || attempt > retryLimit;\n\n // The engine invokes step callbacks outside the async context of `run`, so the\n // run's isolation scope (and with it the invocation state that ties eager sends\n // to this invocation's `waitUntil`) has to be restored explicitly.\n return withIsolationScope(this._isolationScope, () => {\n const invocationState = getInvocationState();\n\n if (invocationState) {\n invocationState.flushPointReached = false;\n }\n\n const stepResult = startSpan(\n {\n name,\n scope: scopeForStep,\n attributes: {\n [SENTRY_OP]: FUNCTION,\n [CODE_FUNCTION_NAME]: name,\n 'workflow.step.name': name,\n [CLOUDFLARE_WORKFLOW_TIMEOUT]: config?.timeout,\n [CLOUDFLARE_WORKFLOW_RETRIES_BACKOFF]: config?.retries?.backoff,\n // In workers-types v5, `delay` may be a `WorkflowDelayFunction`, which isn't a valid span attribute value.\n [CLOUDFLARE_WORKFLOW_RETRIES_DELAY]:\n typeof config?.retries?.delay === 'function' ? undefined : config?.retries?.delay,\n [CLOUDFLARE_WORKFLOW_RETRIES_LIMIT]: config?.retries?.limit,\n [CLOUDFLARE_WORKFLOW_ATTEMPT]: attempt,\n [SENTRY_ORIGIN]: 'auto.faas.cloudflare.workflow',\n [SENTRY_SEGMENT_NAME_SOURCE]: 'task',\n },\n },\n async span => {\n try {\n const result = await (userCallback as (...args: unknown[]) => Promise<T>)(...args);\n span.setStatus({ code: 1 });\n return result;\n } catch (error) {\n if (isFinalAttempt || isNonRetryableError(error)) {\n captureException(error, { mechanism: { handled: true, type: 'auto.faas.cloudflare.workflow' } });\n }\n throw error;\n }\n },\n );\n // Deliver after the step span has ended, so the span rides this flush instead of\n // starting an eager drain (same ordering as `wrapMethodWithSentry`'s teardown). The flush runs on the\n // step's scope: the engine calls the step callback outside of `run()`, so the current scope here has\n // neither the client nor the run's trace, and envelopes without a DSC are dropped by Relay.\n return stepResult.then(\n result => {\n this._waitUntil(withScope(scopeForStep, () => flush(2000)));\n return result;\n },\n error => {\n this._waitUntil(withScope(scopeForStep, () => flush(2000)));\n throw error;\n },\n );\n });\n };\n\n if (config) {\n return rollbackOptions\n ? this._step.do(name, config, instrumentedCallback, rollbackOptions)\n : this._step.do(name, config, instrumentedCallback);\n }\n\n return rollbackOptions\n ? this._step.do(name, instrumentedCallback, rollbackOptions)\n : this._step.do(name, instrumentedCallback);\n }\n\n public async sleep(name: string, duration: WorkflowSleepDuration): Promise<void> {\n return this._step.sleep(name, duration);\n }\n\n public async sleepUntil(name: string, timestamp: Date | number): Promise<void> {\n return this._step.sleepUntil(name, timestamp);\n }\n\n public async waitForEvent<T extends Rpc.Serializable<T>>(\n name: string,\n options: { type: string; timeout?: WorkflowTimeoutDuration | number },\n ): Promise<WorkflowStepEvent<T>> {\n return this._step.waitForEvent<T>(name, options);\n }\n}\n\n/**\n * Instruments a Cloudflare Workflow class with Sentry.\n *\n * @example\n * ```typescript\n * const InstrumentedWorkflow = instrumentWorkflowWithSentry(\n * (env) => ({ dsn: env.SENTRY_DSN }),\n * MyWorkflowClass\n * );\n *\n * export default InstrumentedWorkflow;\n * ```\n *\n * @param optionsCallback - Function that returns Sentry options to initialize Sentry\n * @param WorkflowClass - The workflow class to instrument\n * @returns Instrumented workflow class with the same interface\n */\nexport function instrumentWorkflowWithSentry<\n E = DefaultEnv, // Environment type\n P = unknown, // Payload type\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends WorkflowEntrypoint<any, any> = WorkflowEntrypoint<E, P>, // WorkflowEntrypoint type\n // The constraint must not route through `T`: workers-types defaults `WorkflowEntrypoint`'s\n // `Env` to `unknown` (unlike `WorkerEntrypoint`/`DurableObject`, which default to\n // `Cloudflare.Env`), so a bare subclass would be rejected in a `wrangler types` project.\n // The callback env is resolved from the inferred constructor via `ResolveEnv` instead.\n // oxlint-disable-next-line typescript/no-explicit-any\n C extends new (ctx: ExecutionContext, env: any) => WorkflowEntrypoint<any, any> = new (\n ctx: ExecutionContext,\n // oxlint-disable-next-line typescript/no-explicit-any\n env: any,\n ) => T, // Constructor type of the WorkflowEntrypoint class\n O = unknown,\n>(optionsCallback: (env: ResolveEnv<C, E>) => StrictCloudflareOptions<O>, WorkFlowClass: C): C {\n const InstrumentedClass = new Proxy(WorkFlowClass, {\n // oxlint-disable-next-line typescript/no-explicit-any\n construct(target: C, args: [ctx: ExecutionContext, env: any], newTarget) {\n const [ctx, env] = args;\n const context = instrumentContext(ctx);\n const options = optionsCallback(env);\n args[0] = context;\n args[1] = instrumentEnv(env as Record<string, unknown>, options) as E;\n const instance = Reflect.construct(target, args, newTarget) as T;\n return new Proxy(instance, {\n get(obj, prop, receiver) {\n if (prop === 'run') {\n return async function (event: WorkflowEvent<P>, step: WorkflowStep): Promise<unknown> {\n setAsyncLocalStorageAsyncContextStrategyForWorker();\n\n return withInvocationIsolationScope(async isolationScope => {\n const waitUntil = getOriginalWaitUntil(context).bind(context);\n const client = init({ ...options, ctx: context, enableDedupe: false });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return withScope(async scope => {\n const propagationContext = await propagationContextFromInstanceId(event.instanceId);\n scope.setPropagationContext(propagationContext);\n\n try {\n return await obj.run.call(\n obj,\n event,\n new WrappedWorkflowStep(event.instanceId, options, step, waitUntil, isolationScope),\n );\n } finally {\n waitUntil(flushAndDispose(client));\n }\n });\n }, context);\n };\n }\n return Reflect.get(obj, prop, receiver);\n },\n });\n },\n });\n // Recognizable for `_INTERNAL_wrapUnlessInstrumented`, so auto-instrumentation never nests wrappers.\n markAsInstrumented(InstrumentedClass);\n return InstrumentedClass;\n}\n"],"names":["isError","getCurrentScope","withIsolationScope","getInvocationState","startSpan","SENTRY_OP","FUNCTION","CODE_FUNCTION_NAME","CLOUDFLARE_WORKFLOW_TIMEOUT","CLOUDFLARE_WORKFLOW_RETRIES_BACKOFF","CLOUDFLARE_WORKFLOW_RETRIES_DELAY","CLOUDFLARE_WORKFLOW_RETRIES_LIMIT","CLOUDFLARE_WORKFLOW_ATTEMPT","SENTRY_ORIGIN","SENTRY_SEGMENT_NAME_SOURCE","captureException","withScope","flush","instrumentContext","instrumentEnv","setAsyncLocalStorageAsyncContextStrategyForWorker","withInvocationIsolationScope","getOriginalWaitUntil","init","addCloudResourceContext","flushAndDispose","markAsInstrumented"],"mappings":";;;;;;;;;;;;;;;AA8CA,MAAM,UAAA,GAAa,qEAAA;AAKnB,eAAsB,mCAAmC,UAAA,EAAqC;AAC5F,EAAA,MAAM,GAAA,GAAM,MAAM,MAAA,CAAO,MAAA,CAAO,MAAA,CAAO,OAAA,EAAS,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,UAAU,CAAC,CAAA;AACpF,EAAA,OACE,KAAA,CAAM,KAAK,IAAI,UAAA,CAAW,GAAG,CAAC,CAAA,CAE3B,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA,CACX,IAAI,CAAA,CAAA,KAAK,CAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,QAAA,CAAS,GAAG,GAAG,CAAC,CAAA,CACxC,IAAA,CAAK,EAAE,CAAA;AAEd;AAEA,eAAe,iCA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3
3
  const attributes = require('@sentry/conventions/attributes');
4
4
  const core = require('@sentry/core');
5
+ const server = require('@sentry/core/server');
5
6
  const requestHandler = require('@sentry/server-utils/request-handler');
6
7
  const debugBuild = require('./debug-build.js');
7
8
  const httpServer = require('./integrations/httpServer.js');
@@ -11,8 +12,11 @@ const scopeUtils = require('./scope-utils.js');
11
12
  const invocationContext = require('./utils/invocationContext.js');
12
13
  const invocationScope = require('./utils/invocationScope.js');
13
14
 
15
+ function isDurableObjectContext(context) {
16
+ return !!context && "storage" in context;
17
+ }
14
18
  function getRequestErrorMechanismType(context) {
15
- return context && "storage" in context ? "auto.faas.cloudflare.durable_object" : "auto.http.cloudflare";
19
+ return isDurableObjectContext(context) ? "auto.faas.cloudflare.durable_object" : "auto.http.cloudflare";
16
20
  }
17
21
  function wrapRequestHandlerWithInit(wrapperOptions, handler, initSdk) {
18
22
  return invocationScope.withInvocationIsolationScope(async (isolationScope) => {
@@ -23,6 +27,10 @@ function wrapRequestHandlerWithInit(wrapperOptions, handler, initSdk) {
23
27
  const client = initSdk({ ...options, ctx: context });
24
28
  isolationScope.setClient(client);
25
29
  orchestrionDeferredChannels.flushDeferredChannelEvents();
30
+ const tunnelResponse = !isDurableObjectContext(context) && server._INTERNAL_handleServedTunnelRequest(request, client);
31
+ if (tunnelResponse) {
32
+ return tunnelResponse.finally(() => waitUntil?.(flush.flushAndDispose(client)));
33
+ }
26
34
  scopeUtils.addCloudResourceContext(isolationScope);
27
35
  const attributes$1 = {};
28
36
  if (request.cf) {
@@ -1 +1 @@
1
- {"version":3,"file":"wrapRequestHandlerWithInit.js","sources":["../../../src/wrapRequestHandlerWithInit.ts"],"sourcesContent":["import type { CfProperties, IncomingRequestCfProperties } from '@cloudflare/workers-types';\nimport { NETWORK_PROTOCOL_NAME, NETWORK_PROTOCOL_VERSION } from '@sentry/conventions/attributes';\nimport type { SpanAttributes } from '@sentry/core';\nimport { getIsolationScope, safeCallback } from '@sentry/core';\nimport { wrapServerRequestHandler } from '@sentry/server-utils/request-handler';\nimport { DEBUG_BUILD } from './debug-build';\nimport { getHttpServerRequestOptions } from './integrations/httpServer';\nimport { flushDeferredChannelEvents } from './orchestrion-deferred-channels';\nimport type { CloudflareClient, CloudflareOptions } from './client';\nimport type { ExecutionContextCompat } from './executionContext';\nimport { flushAndDispose, getOriginalWaitUntil } from './flush';\nimport { addCloudResourceContext, addCultureContext } from './scope-utils';\nimport { getInvocationState, getInvocationWaitUntil } from './utils/invocationContext';\nimport { withInvocationIsolationScope } from './utils/invocationScope';\n\nfunction getRequestErrorMechanismType(context: ExecutionContextCompat | undefined): string {\n // Durable Object fetch handlers use DO state as context (see instrumentDurableObjectWithSentry)\n return context && 'storage' in context ? 'auto.faas.cloudflare.durable_object' : 'auto.http.cloudflare';\n}\n\nexport interface RequestHandlerWrapperOptions {\n options: CloudflareOptions;\n request: Request<unknown, IncomingRequestCfProperties<unknown> | CfProperties<unknown>>;\n context: ExecutionContextCompat | undefined;\n /**\n * If true, errors will be captured, rethrown and sent to Sentry.\n * Otherwise, errors are rethrown but not captured.\n *\n * You most likely don't want to set this to `false`, if you use `wrapRequestHandler` directly.\n * This is primarily meant as an escape hatch for higher-level SDKs relying on additional error\n * capturing mechanisms where this wrapper captures errors too early or too generally.\n *\n * @default true\n */\n captureErrors?: boolean;\n}\n\ntype InitSdk = (options: CloudflareOptions) => CloudflareClient | undefined;\n\n/**\n * Same as {@link wrapRequestHandler}, but with the SDK initialization injected.\n *\n * Wrappers that are only reachable from the main entry point — where `nodejs_compat` is a\n * requirement anyway — pass `init` from `sdk.ts` so `enableOpenTelemetrySetup` is honored.\n *\n * @internal\n */\nexport function wrapRequestHandlerWithInit(\n wrapperOptions: RequestHandlerWrapperOptions,\n handler: (...args: unknown[]) => Response | Promise<Response>,\n initSdk: InitSdk,\n): Promise<Response> {\n return withInvocationIsolationScope(async isolationScope => {\n const { options, request, captureErrors = true } = wrapperOptions;\n const context = wrapperOptions.context;\n\n // The un-instrumented waitUntil, so flushAndDispose cannot deadlock on the flush\n // lock's own wrapper. Resolved once per invocation and cached on its state; reading\n // `ctx.waitUntil` on a native context is a runtime getter call.\n const invocationState = getInvocationState();\n const waitUntil = invocationState\n ? getInvocationWaitUntil(invocationState)\n : context\n ? getOriginalWaitUntil(context).bind(context)\n : undefined;\n\n const client = initSdk({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n // Emit any orchestrion channel events deferred at module scope (e.g. a top-level\n // `const app = new Hono()` wrapped by build-time instrumentation): we're now in a\n // request, where workerd allows publish, and init() above has registered subscribers.\n flushDeferredChannelEvents();\n\n addCloudResourceContext(isolationScope);\n const attributes: SpanAttributes = {};\n if (request.cf) {\n addCultureContext(isolationScope, request.cf);\n\n if (typeof request.cf.httpProtocol === 'string') {\n const [protocolName, protocolVersion] = request.cf.httpProtocol.toLowerCase().split('/');\n attributes[NETWORK_PROTOCOL_NAME] = protocolName;\n attributes[NETWORK_PROTOCOL_VERSION] = protocolVersion;\n }\n }\n\n if (!client) {\n try {\n return await handler();\n } finally {\n waitUntil?.(flushAndDispose(client));\n }\n }\n\n // Note: The span will not have a duration unless I/O happens in the handler. This is\n // because of how the cloudflare workers runtime works.\n // See: https://developers.cloudflare.com/workers/runtime-apis/performance/\n return wrapServerRequestHandler(\n {\n request,\n client,\n // Without `AsyncLocalStorage`, `withInvocationIsolationScope` does not fork, and the scope it\n // passes in is not the current one. The request data has to go on the current scope, where\n // events captured in the handler read it.\n isolationScope: getIsolationScope(),\n options: getHttpServerRequestOptions(client),\n origin: 'auto.http.cloudflare',\n mechanism: captureErrors ? { handled: false, type: getRequestErrorMechanismType(context) } : undefined,\n attributes,\n isStreamingResponse: response => {\n const classification = safeCallback(\n DEBUG_BUILD ? 'Error in `isStreamingResponse`, using the default classification:' : '',\n () => options.isStreamingResponse?.(response, request),\n () => undefined,\n );\n // An async callback returns a promise, which would otherwise count as `true`.\n return typeof classification === 'boolean' ? classification : undefined;\n },\n onDone: response => {\n // Don't dispose for protocol upgrades (101 Switching Protocols) - the connection stays alive.\n // This includes WebSocket upgrades where webSocketMessage/webSocketClose handlers\n // will still be called and may need the client to capture errors.\n if (response?.status === 101) {\n waitUntil?.(client.flush(2000));\n } else {\n waitUntil?.(flushAndDispose(client));\n }\n },\n },\n () => handler(),\n );\n }, wrapperOptions.context);\n}\n"],"names":["withInvocationIsolationScope","getInvocationState","getInvocationWaitUntil","getOriginalWaitUntil","flushDeferredChannelEvents","addCloudResourceContext","attributes","addCultureContext","NETWORK_PROTOCOL_NAME","NETWORK_PROTOCOL_VERSION","flushAndDispose","wrapServerRequestHandler","getIsolationScope","getHttpServerRequestOptions","safeCallback","DEBUG_BUILD"],"mappings":";;;;;;;;;;;;;AAeA,SAAS,6BAA6B,OAAA,EAAqD;AAEzF,EAAA,OAAO,OAAA,IAAW,SAAA,IAAa,OAAA,GAAU,qCAAA,GAAwC,sBAAA;AACnF;AA6BO,SAAS,0BAAA,CACd,cAAA,EACA,OAAA,EACA,OAAA,EACmB;AACnB,EAAA,OAAOA,4CAAA,CAA6B,OAAM,cAAA,KAAkB;AAC1D,IAAA,MAAM,EAAE,OAAA,EAAS,OAAA,EAAS,aAAA,GAAgB,MAAK,GAAI,cAAA;AACnD,IAAA,MAAM,UAAU,cAAA,CAAe,OAAA;AAK/B,IAAA,MAAM,kBAAkBC,oCAAA,EAAmB;AAC3C,IAAA,MAAM,SAAA,GAAY,eAAA,GACdC,wCAAA,CAAuB,eAAe,CAAA,GACtC,OAAA,GACEC,0BAAA,CAAqB,OAAO,CAAA,CAAE,IAAA,CAAK,OAAO,CAAA,GAC1C,MAAA;AAEN,IAAA,MAAM,SAAS,OAAA,CAAQ,EAAE,GAAG,OAAA,EAAS,GAAA,EAAK,SAAS,CAAA;AACnD,IAAA,cAAA,CAAe,UAAU,MAAM,CAAA;AAK/B,IAAAC,sDAAA,EAA2B;AAE3B,IAAAC,kCAAA,CAAwB,cAAc,CAAA;AACtC,IAAA,MAAMC,eAA6B,EAAC;AACpC,IAAA,IAAI,QAAQ,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E,CAAA;AAAA,QACA,QAAQ,CAAA,QAAA,KAAY;AAIlB,UAAA,IAAI,QAAA,EAAU,WAAW,GAAA,EAAK;AAC5B,YAAA,SAAA,GAAY,MAAA,CAAO,KAAA,CAAM,GAAI,CAAC,CAAA;AAAA,UAChC,CAAA,MAAO;AACL,YAAA,SAAA,GAAYL,qBAAA,CAAgB,MAAM,CAAC,CAAA;AAAA,UACrC;AAAA,QACF;AAAA,OACF;AAAA,MACA,MAAM,OAAA;AAAQ,KAChB;AAAA,EACF,CAAA,EAAG,eAAe,OAAO,CAAA;AAC3B;;;;"}
1
+ {"version":3,"file":"wrapRequestHandlerWithInit.js","sources":["../../../src/wrapRequestHandlerWithInit.ts"],"sourcesContent":["import type { CfProperties, IncomingRequestCfProperties } from '@cloudflare/workers-types';\nimport { NETWORK_PROTOCOL_NAME, NETWORK_PROTOCOL_VERSION } from '@sentry/conventions/attributes';\nimport type { SpanAttributes } from '@sentry/core';\nimport { getIsolationScope, safeCallback } from '@sentry/core';\nimport { _INTERNAL_handleServedTunnelRequest as handleServedTunnelRequest } from '@sentry/core/server';\nimport { wrapServerRequestHandler } from '@sentry/server-utils/request-handler';\nimport { DEBUG_BUILD } from './debug-build';\nimport { getHttpServerRequestOptions } from './integrations/httpServer';\nimport { flushDeferredChannelEvents } from './orchestrion-deferred-channels';\nimport type { CloudflareClient, CloudflareOptions } from './client';\nimport type { ExecutionContextCompat } from './executionContext';\nimport { flushAndDispose, getOriginalWaitUntil } from './flush';\nimport { addCloudResourceContext, addCultureContext } from './scope-utils';\nimport { getInvocationState, getInvocationWaitUntil } from './utils/invocationContext';\nimport { withInvocationIsolationScope } from './utils/invocationScope';\n\nfunction isDurableObjectContext(context: ExecutionContextCompat | undefined): boolean {\n // Durable Object fetch handlers use DO state as context (see instrumentDurableObjectWithSentry)\n return !!context && 'storage' in context;\n}\n\nfunction getRequestErrorMechanismType(context: ExecutionContextCompat | undefined): string {\n return isDurableObjectContext(context) ? 'auto.faas.cloudflare.durable_object' : 'auto.http.cloudflare';\n}\n\nexport interface RequestHandlerWrapperOptions {\n options: CloudflareOptions;\n request: Request<unknown, IncomingRequestCfProperties<unknown> | CfProperties<unknown>>;\n context: ExecutionContextCompat | undefined;\n /**\n * If true, errors will be captured, rethrown and sent to Sentry.\n * Otherwise, errors are rethrown but not captured.\n *\n * You most likely don't want to set this to `false`, if you use `wrapRequestHandler` directly.\n * This is primarily meant as an escape hatch for higher-level SDKs relying on additional error\n * capturing mechanisms where this wrapper captures errors too early or too generally.\n *\n * @default true\n */\n captureErrors?: boolean;\n}\n\ntype InitSdk = (options: CloudflareOptions) => CloudflareClient | undefined;\n\n/**\n * Same as {@link wrapRequestHandler}, but with the SDK initialization injected.\n *\n * Wrappers that are only reachable from the main entry point — where `nodejs_compat` is a\n * requirement anyway — pass `init` from `sdk.ts` so `enableOpenTelemetrySetup` is honored.\n *\n * @internal\n */\nexport function wrapRequestHandlerWithInit(\n wrapperOptions: RequestHandlerWrapperOptions,\n handler: (...args: unknown[]) => Response | Promise<Response>,\n initSdk: InitSdk,\n): Promise<Response> {\n return withInvocationIsolationScope(async isolationScope => {\n const { options, request, captureErrors = true } = wrapperOptions;\n const context = wrapperOptions.context;\n\n // The un-instrumented waitUntil, so flushAndDispose cannot deadlock on the flush\n // lock's own wrapper. Resolved once per invocation and cached on its state; reading\n // `ctx.waitUntil` on a native context is a runtime getter call.\n const invocationState = getInvocationState();\n const waitUntil = invocationState\n ? getInvocationWaitUntil(invocationState)\n : context\n ? getOriginalWaitUntil(context).bind(context)\n : undefined;\n\n const client = initSdk({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n // Emit any orchestrion channel events deferred at module scope (e.g. a top-level\n // `const app = new Hono()` wrapped by build-time instrumentation): we're now in a\n // request, where workerd allows publish, and init() above has registered subscribers.\n flushDeferredChannelEvents();\n\n // The tunnel answers these before the app, with no span. A Durable Object is only reached through the Worker,\n // which answered them already.\n const tunnelResponse = !isDurableObjectContext(context) && handleServedTunnelRequest(request, client);\n if (tunnelResponse) {\n return tunnelResponse.finally(() => waitUntil?.(flushAndDispose(client)));\n }\n\n addCloudResourceContext(isolationScope);\n const attributes: SpanAttributes = {};\n if (request.cf) {\n addCultureContext(isolationScope, request.cf);\n\n if (typeof request.cf.httpProtocol === 'string') {\n const [protocolName, protocolVersion] = request.cf.httpProtocol.toLowerCase().split('/');\n attributes[NETWORK_PROTOCOL_NAME] = protocolName;\n attributes[NETWORK_PROTOCOL_VERSION] = protocolVersion;\n }\n }\n\n if (!client) {\n try {\n return await handler();\n } finally {\n waitUntil?.(flushAndDispose(client));\n }\n }\n\n // Note: The span will not have a duration unless I/O happens in the handler. This is\n // because of how the cloudflare workers runtime works.\n // See: https://developers.cloudflare.com/workers/runtime-apis/performance/\n return wrapServerRequestHandler(\n {\n request,\n client,\n // Without `AsyncLocalStorage`, `withInvocationIsolationScope` does not fork, and the scope it\n // passes in is not the current one. The request data has to go on the current scope, where\n // events captured in the handler read it.\n isolationScope: getIsolationScope(),\n options: getHttpServerRequestOptions(client),\n origin: 'auto.http.cloudflare',\n mechanism: captureErrors ? { handled: false, type: getRequestErrorMechanismType(context) } : undefined,\n attributes,\n isStreamingResponse: response => {\n const classification = safeCallback(\n DEBUG_BUILD ? 'Error in `isStreamingResponse`, using the default classification:' : '',\n () => options.isStreamingResponse?.(response, request),\n () => undefined,\n );\n // An async callback returns a promise, which would otherwise count as `true`.\n return typeof classification === 'boolean' ? classification : undefined;\n },\n onDone: response => {\n // Don't dispose for protocol upgrades (101 Switching Protocols) - the connection stays alive.\n // This includes WebSocket upgrades where webSocketMessage/webSocketClose handlers\n // will still be called and may need the client to capture errors.\n if (response?.status === 101) {\n waitUntil?.(client.flush(2000));\n } else {\n waitUntil?.(flushAndDispose(client));\n }\n },\n },\n () => handler(),\n );\n }, wrapperOptions.context);\n}\n"],"names":["withInvocationIsolationScope","getInvocationState","getInvocationWaitUntil","getOriginalWaitUntil","flushDeferredChannelEvents","handleServedTunnelRequest","flushAndDispose","addCloudResourceContext","attributes","addCultureContext","NETWORK_PROTOCOL_NAME","NETWORK_PROTOCOL_VERSION","wrapServerRequestHandler","getIsolationScope","getHttpServerRequestOptions","safeCallback","DEBUG_BUILD"],"mappings":";;;;;;;;;;;;;;AAgBA,SAAS,uBAAuB,OAAA,EAAsD;AAEpF,EAAA,OAAO,CAAC,CAAC,OAAA,IAAW,SAAA,IAAa,OAAA;AACnC;AAEA,SAAS,6BAA6B,OAAA,EAAqD;AACzF,EAAA,OAAO,sBAAA,CAAuB,OAAO,CAAA,GAAI,qCAAA,GAAwC,sBAAA;AACnF;AA6BO,SAAS,0BAAA,CACd,cAAA,EACA,OAAA,EACA,OAAA,EACmB;AACnB,EAAA,OAAOA,4CAAA,CAA6B,OAAM,cAAA,KAAkB;AAC1D,IAAA,MAAM,EAAE,OAAA,EAAS,OAAA,EAAS,aAAA,GAAgB,MAAK,GAAI,cAAA;AACnD,IAAA,MAAM,UAAU,cAAA,CAAe,OAAA;AAK/B,IAAA,MAAM,kBAAkBC,oCAAA,EAAmB;AAC3C,IAAA,MAAM,SAAA,GAAY,eAAA,GACdC,wCAAA,CAAuB,eAAe,CAAA,GACtC,OAAA,GACEC,0BAAA,CAAqB,OAAO,CAAA,CAAE,IAAA,CAAK,OAAO,CAAA,GAC1C,MAAA;AAEN,IAAA,MAAM,SAAS,OAAA,CAAQ,EAAE,GAAG,OAAA,EAAS,GAAA,EAAK,SAAS,CAAA;AACnD,IAAA,cAAA,CAAe,UAAU,MAAM,CAAA;AAK/B,IAAAC,sDAAA,EAA2B;AAI3B,IAAA,MAAM,iBAAiB,CAAC,sBAAA,CAAuB,OAAO,CAAA,IAAKC,0CAAA,CAA0B,SAAS,MAAM,CAAA;AACpG,IAAA,IAAI,cAAA,EAAgB;AAClB,MAAA,OAAO,eAAe,OAAA,CAAQ,MAAM,YAAYC,qBAAA,CAAgB,MAAM,CAAC,CAAC,CAAA;AAAA,IAC1E;AAEA,IAAAC,kCAAA,CAAwB,cAAc,CAAA;AACt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AAA,KAAmB,SAAA,GAAY,cAAA,GAAiB,MAAA;AAAA,QAChE,CAAA;AAAA,QACA,QAAQ,CAAA,QAAA,KAAY;AAIlB,UAAA,IAAI,QAAA,EAAU,WAAW,GAAA,EAAK;AAC5B,YAAA,SAAA,GAAY,MAAA,CAAO,KAAA,CAAM,GAAI,CAAC,CAAA;AAAA,UAChC,CAAA,MAAO;AACL,YAAA,SAAA,GAAYV,qBAAA,CAAgB,MAAM,CAAC,CAAA;AAAA,UACrC;AAAA,QACF;AAAA,OACF;AAAA,MACA,MAAM,OAAA;AAAQ,KAChB;AAAA,EACF,CAAA,EAAG,eAAe,OAAO,CAAA;AAC3B;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sources":["../../../src/client.ts"],"sourcesContent":["import type { CheckIn, ClientOptions, MonitorConfig, Options, Scope, TracePropagationTargets } from '@sentry/core';\nimport {\n _INTERNAL_clearAiProviderSkips,\n _INTERNAL_flushLogsBuffer,\n _INTERNAL_flushMetricsBuffer,\n applySdkMetadata,\n debug,\n spanIsSampled,\n spanStreamingIntegration,\n} from '@sentry/core';\nimport type { ServerRuntimeClientOptions } from '@sentry/core/server';\nimport { ServerRuntimeClient } from '@sentry/core/server';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { ExecutionContextCompat } from './executionContext';\nimport type { makeFlushLock } from './flush';\nimport type { CloudflareTransportOptions } from './transport';\nimport { getInvocationState, getInvocationWaitUntil } from './utils/invocationContext';\n\ndeclare const __SENTRY_TRACING__: boolean;\n\nconst SPAN_STREAMING_INTEGRATION_NAME = 'SpanStreaming';\n\n/**\n * The Sentry Cloudflare SDK Client.\n *\n * @see CloudflareClientOptions for documentation on configuration options.\n * @see ServerRuntimeClient for usage documentation.\n */\nexport class CloudflareClient extends ServerRuntimeClient {\n private readonly _flushLock: ReturnType<typeof makeFlushLock> | void;\n private _pendingSpans: Set<string> = new Set();\n private _spanCompletionPromise: Promise<void> | null = null;\n private _resolveSpanCompletion: (() => void) | null = null;\n\n private _unsubscribeSpanStart: (() => void) | null = null;\n private _unsubscribeSpanEnd: (() => void) | null = null;\n\n // True while a boundary `flush()` is draining; envelopes created by that drain ride it\n // and must not each start their own eager transport flush.\n private _inBoundaryFlush = false;\n\n /**\n * Whether this client is a cached, cross-invocation client (`cacheClient`).\n * Cached clients are never disposed at an invocation boundary, so their spans/events\n * are delivered eagerly instead of waiting for a per-invocation flush.\n */\n public readonly isCachedClient: boolean;\n\n /**\n * Creates a new Cloudflare SDK instance.\n * @param options Configuration options for this SDK.\n */\n public constructor(options: CloudflareClientOptions) {\n applySdkMetadata(options, 'cloudflare');\n options._metadata = options._metadata || {};\n const { flushLock, ...serverOptions } = options;\n\n const clientOptions: ServerRuntimeClientOptions = {\n ...serverOptions,\n platform: 'javascript',\n // TODO: Grab version information\n runtime: { name: 'cloudflare' },\n // TODO: Add server name\n _flushInterval: 0,\n };\n\n // workerd can't unref timers, so the default 500ms segment-end flush timer holds every\n // Durable Object invocation open (and billed) until it fires, sampled or not. The boundary\n // flush and the eager drain already deliver streamed spans here.\n if (\n (typeof __SENTRY_TRACING__ === 'undefined' || __SENTRY_TRACING__) &&\n clientOptions.traceLifecycle !== 'static' &&\n !clientOptions.integrations.some(i => i.name === SPAN_STREAMING_INTEGRATION_NAME)\n ) {\n clientOptions.integrations.push(spanStreamingIntegration({ flushOnSegmentEnd: false }));\n }\n\n super(clientOptions);\n this._flushLock = flushLock;\n this.isCachedClient = options.cacheClient === true;\n\n // Track span lifecycle to know when to flush. Skipped for cached clients\n // (`cacheClient`): they are never disposed, so spans that end after\n // a flush are still delivered. Per-invocation clients are disposed right after\n // the boundary flush, so the flush must wait for open spans to end otherwise\n // their transaction never gets emitted.\n if (!this.isCachedClient) {\n this._unsubscribeSpanStart = this.on('spanStart', span => {\n const spanId = span.spanContext().spanId;\n DEBUG_BUILD && debug.log('[CloudflareClient] Span started:', spanId);\n\n // Negatively sampled spans never emit spanEnd,\n // so tracking them would cause _pendingSpans to grow unboundedly.\n // We should fix the inconsistent behavior for NonRecordingSpans in the future but\n // for now, we just ignore them.\n if (!spanIsSampled(span)) {\n return;\n }\n\n this._pendingSpans.add(spanId);\n\n if (!this._spanCompletionPromise) {\n this._spanCompletionPromise = new Promise(resolve => {\n this._resolveSpanCompletion = resolve;\n });\n }\n });\n\n this._unsubscribeSpanEnd = this.on('spanEnd', span => {\n const spanId = span.spanContext().spanId;\n DEBUG_BUILD && debug.log('[CloudflareClient] Span ended:', spanId);\n this._pendingSpans.delete(spanId);\n\n // If no more pending spans, resolve the completion promise\n if (this._pendingSpans.size === 0 && this._resolveSpanCompletion) {\n DEBUG_BUILD && debug.log('[CloudflareClient] All spans completed, preparing to flush');\n this._resolveSpanCompletion();\n this._resetSpanCompletionPromise();\n }\n });\n }\n }\n\n /**\n * Flushes pending operations and ensures all data is processed.\n *\n * Each phase waits at most `timeout`: the flush lock of a per-invocation client, pending spans, event\n * processing and the transport drain. So a flush can take a small multiple of `timeout`, which stays well\n * below Cloudflare's 30 second `waitUntil` limit for the timeouts the SDK uses. Sends still pending when\n * the drain times out are aborted.\n *\n * @param {number} [timeout] - Maximum time in milliseconds for each phase of the flush.\n * @return {Promise<boolean>} A promise that resolves to a boolean indicating whether the flush operation was successful.\n */\n public async flush(timeout?: number): Promise<boolean> {\n // Wait for user waitUntil-registered work to settle before draining, so events\n // captured in that work are still in the buffer. Without this the final flush\n // can drain (and the client be disposed) before background captures land.\n //\n // Only per-invocation clients (`cacheClient: false`) have a flush lock; remove this with them in v12.\n // The wait is bounded by `timeout` because a user `waitUntil` task that outlives the invocation\n // would otherwise keep the flush from draining until the runtime cancels it.\n if (this._flushLock) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n this._flushLock.finalize(),\n ...(timeout ? [new Promise<void>(resolve => (timer = setTimeout(resolve, timeout)))] : []),\n ]);\n clearTimeout(timer);\n }\n\n if (this._pendingSpans.size > 0 && this._spanCompletionPromise) {\n DEBUG_BUILD &&\n debug.log('[CloudflareClient] Waiting for', this._pendingSpans.size, 'pending spans to complete...');\n\n const timeoutMs = timeout ?? 5000;\n const spanCompletionRace = Promise.race([\n this._spanCompletionPromise,\n new Promise(resolve =>\n setTimeout(() => {\n DEBUG_BUILD &&\n debug.log('[CloudflareClient] Span completion timeout after', timeoutMs, 'ms, flushing anyway');\n resolve(undefined);\n }, timeoutMs),\n ),\n ]);\n\n await spanCompletionRace;\n }\n\n // Envelopes created while this flush drains (log/metric/span buffers turning into\n // envelopes on the `flush` emit) ride its own transport drain; without the flag each\n // of them would also start an eager drain and a `waitUntil` registration.\n this._inBoundaryFlush = true;\n try {\n return await super.flush(timeout);\n } finally {\n this._inBoundaryFlush = false;\n }\n }\n\n /**\n * Sends the check-in at once instead of holding it for the flush at the end of the invocation.\n * An `in_progress` check-in of a run that is longer than the check-in margin would otherwise\n * reach Sentry too late, and Sentry would mark the run as missed.\n */\n public override captureCheckIn(checkIn: CheckIn, monitorConfig?: MonitorConfig, scope?: Scope): string {\n const checkInId = super.captureCheckIn(checkIn, monitorConfig, scope);\n const transport = this.getTransport();\n if (transport) {\n this._registerWithInvocationWaitUntil(transport.flush(2000));\n }\n return checkInId;\n }\n\n /**\n * Disposes of the client and releases all resources.\n *\n * This method clears all Cloudflare-specific state in addition to the base client cleanup.\n * It unsubscribes from span lifecycle events and clears pending span tracking.\n *\n * Call this method after flushing to allow the client to be garbage collected.\n * After calling dispose(), the client should not be used anymore.\n */\n public override dispose(): void {\n DEBUG_BUILD && debug.log('[CloudflareClient] Disposing client...');\n\n super.dispose();\n\n if (this._unsubscribeSpanStart) {\n this._unsubscribeSpanStart();\n this._unsubscribeSpanStart = null;\n }\n if (this._unsubscribeSpanEnd) {\n this._unsubscribeSpanEnd();\n this._unsubscribeSpanEnd = null;\n }\n\n this._resetSpanCompletionPromise();\n (this as unknown as { _flushLock: ReturnType<typeof makeFlushLock> | void })._flushLock = undefined;\n }\n\n /** @inheritDoc */\n protected override _setupIntegrations(): void {\n // Clear AI provider skip registrations before setting up integrations.\n // The registry is module-global and Cloudflare calls `init()` per request, so without this a\n // single `ai` SDK call would suppress direct `env.AI.run` spans for the rest of the isolate's\n // life. Mirrors the same reset in the Node client.\n _INTERNAL_clearAiProviderSkips();\n super._setupIntegrations();\n\n // Registered after the integrations on purpose: the flush-point marker must run\n // after core and the span buffer have turned their buffers into envelopes on the\n // same `flush` emit (so those envelopes ride the boundary drain instead of starting\n // eager ones), and the eager span handler relies on `spanStreamingIntegration`\n // having already buffered the span that triggers it.\n if (this.isCachedClient) {\n // Marks the invocation's natural flush point: anything captured from now on\n // (post-response `waitUntil` work, detached continuations) has no later flush\n // to ride and is delivered eagerly by the hooks below.\n this.on('flush', () => {\n const invocationState = getInvocationState();\n if (invocationState) {\n invocationState.flushPointReached = true;\n }\n });\n this._setupEagerEnvelopeDelivery();\n this._setupEagerBufferDelivery();\n }\n }\n\n /**\n * Resets the span completion promise and resolve function.\n */\n private _resetSpanCompletionPromise(): void {\n this._pendingSpans.clear();\n this._spanCompletionPromise = null;\n this._resolveSpanCompletion = null;\n }\n\n /**\n * Drains the transport after an envelope has been accepted past the invocation's\n * flush point. The transport queues request producers until `flush()`; before the\n * flush point the boundary `flush()` drains everything, but envelopes created after\n * it (post-response `waitUntil` work, detached continuations) have no later flush to\n * ride. The drain is registered with the invocation's `waitUntil` to keep the fetch\n * alive; outside any instrumented invocation it always runs.\n */\n private _setupEagerEnvelopeDelivery(): void {\n this.on('afterEnvelope', () => {\n const transport = this.getTransport();\n const invocationState = getInvocationState();\n\n if (!transport || this._inBoundaryFlush || (invocationState && !invocationState.flushPointReached)) {\n return;\n }\n\n this._registerWithInvocationWaitUntil(transport.flush(2000));\n });\n }\n\n /**\n * Turns spans, logs and metrics captured past the invocation's flush point into\n * envelopes. Before the flush point the boundary `flush()` drains their buffers; after\n * it (or outside any instrumented invocation) nothing else would: the log/metric idle\n * timer is disabled for this runtime (`_flushInterval: 0`) and the span buffer's own 5s\n * timer fires outside any invocation, where the runtime suspends the send. Each capture\n * drains only its own bucket (the ended span's trace, the log buffer, the metric\n * buffer), so a fan-out of concurrent traces stays one envelope per trace. RPC method\n * spans never reach this path: `wrapMethodWithSentry` runs the boundary flush after the\n * method span has ended, so only work past that (e.g. detached continuations) lands here.\n */\n private _setupEagerBufferDelivery(): void {\n this.on('afterSpanEnd', span => {\n // The trace id must come from the span, not the current scope: `continueTrace`\n // writes the propagation context to the *current* scope, so the forked\n // isolation scope's propagation context carries a different trace id and\n // flushing by it silently no-ops.\n const traceId = span.spanContext().traceId;\n this._eagerDrain(() => this.emit('flushTraceSpans', traceId));\n });\n this.on('afterCaptureLog', () => this._eagerDrain(() => _INTERNAL_flushLogsBuffer(this)));\n this.on('afterCaptureMetric', () => this._eagerDrain(() => _INTERNAL_flushMetricsBuffer(this)));\n }\n\n /**\n * Runs `drain` unless the owning invocation has not reached its flush point yet\n * (before it the boundary `flush()` delivers the buffers).\n */\n private _eagerDrain(drain: () => void): void {\n const invocationState = getInvocationState();\n\n if (invocationState && !invocationState.flushPointReached) {\n return;\n }\n\n drain();\n }\n\n /**\n * Attaches a promise to the `waitUntil` of the invocation that owns the current\n * async context, so the runtime keeps the send alive after the response is returned.\n * Outside any instrumented invocation (or where the context has no `waitUntil`,\n * e.g. Astro prerendering) the send is fire-and-forget.\n */\n private _registerWithInvocationWaitUntil(promise: PromiseLike<unknown>): void {\n const invocationState = getInvocationState();\n const waitUntil = invocationState && getInvocationWaitUntil(invocationState);\n if (!waitUntil) {\n return;\n }\n\n try {\n waitUntil(\n Promise.resolve(promise).then(\n () => undefined,\n () => undefined,\n ),\n );\n } catch {\n // The owning invocation already ended; the send races isolate teardown either way.\n }\n }\n}\n\ninterface BaseCloudflareOptions {\n /**\n * @ignore Used internally to disable the deDupeIntegration for workflows.\n * @hidden Used internally to disable the deDupeIntegration for workflows.\n * @default true\n */\n enableDedupe?: boolean;\n\n /**\n * @ignore Used internally by SDKs that build `defaultIntegrations` from the Cloudflare defaults.\n * @hidden Used internally by SDKs that build `defaultIntegrations` from the Cloudflare defaults.\n *\n * Marks the `defaultIntegrations` list as an extension of the SDK defaults, so the SDK also adds\n * the integrations of instrumented modules that load after `init()`.\n * @default false\n */\n _extendsDefaultIntegrations?: boolean;\n\n /**\n * The Cloudflare SDK is not OpenTelemetry native. By default (`false`) it does not set up a tracer\n * provider; spans are emitted via the SDK's own instrumentation and scopes are isolated with\n * AsyncLocalStorage.\n *\n * Set this to `true` to opt into the OpenTelemetry compatibility tracer, which captures spans\n * emitted via `@opentelemetry/api`. Big caveat: it does not handle custom context, always working\n * off the current scope. This is good enough for many, but not all, integrations.\n *\n * @default false\n */\n enableOpenTelemetrySetup?: boolean;\n\n /**\n * The bindings on `env` that outgoing RPC calls propagate trace context to.\n *\n * Strings match a binding name exactly, regular expressions match by pattern. An empty array\n * (the default) propagates to nothing.\n *\n * RPC has no headers to carry trace context, so the SDK appends it as a trailing argument to\n * every RPC method call on a matching binding. Only a Sentry-instrumented receiver strips that\n * argument again. Anywhere else it arrives as a real argument and changes what the method was\n * called with, so list only the bindings whose receiver you know runs Sentry.\n *\n * Propagation over `stub.fetch()` and service binding `fetch()` uses HTTP headers and is not\n * affected by this option.\n *\n * Strings match a binding name exactly, regular expressions match by pattern. Both match\n * case-insensitively.\n *\n * When you build with the Sentry Cloudflare Vite plugin, bindings that resolve to *this* worker\n * (its own Durable Objects, its self service bindings) are added for you, because the plugin\n * instruments those receivers itself. Whatever you list here is added on top of them.\n *\n * @default []\n * @example\n * ```ts\n * // Propagate to `env.ORDERS` and every `env.SVC_*` binding\n * export default Sentry.withSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * rpcTracePropagationBindings: ['ORDERS', /^SVC_/],\n * }),\n * handler,\n * );\n * ```\n */\n rpcTracePropagationBindings?: TracePropagationTargets;\n\n /**\n * Table names that should stay instrumented even though they match a reserved prefix used by\n * Durable Object frameworks for their internal SQLite tables: `cf_` (`agents`, `partyserver`, ...)\n * and `pi_` (pi-durable in the `PiHarness` of `agents`).\n *\n * By default, `exec` queries against tables with these prefixes are treated as framework noise and\n * no `db.query` span is created for them. If one of your own tables happens to use such a prefix,\n * add it here to opt it back into instrumentation, or add `/^pi_/` to see the statements of\n * pi-durable. Entries are matched against each table name in the\n * query summary — strings must match exactly, while regular expressions give you prefix/pattern\n * matching.\n *\n * @default []\n * @example\n * ```ts\n * export default Sentry.withSentry(\n * (env) => ({\n * dsn: env.SENTRY_DSN,\n * durableObjectSqlSpanAllowlist: ['cf_my_table', /^cf_reports_/],\n * }),\n * handler,\n * );\n * ```\n */\n durableObjectSqlSpanAllowlist?: Array<string | RegExp>;\n\n /**\n * KV keys that should stay instrumented even though they match a reserved prefix used by Durable\n * Object frameworks (`agents`, `partyserver`, ...) for their internal storage entries.\n *\n * By default, KV reads/writes (`get`, `put`, `delete`, `list`) of `cf_`- or `__ps_`-prefixed keys\n * are treated as framework noise and no `durable_object_storage_*` span is created for them,\n * mirroring how `cf_`-prefixed SQL tables are handled (see {@link durableObjectSqlSpanAllowlist}).\n * If one of your own keys happens to use such a prefix, add it here to opt it back into\n * instrumentation. Strings must match exactly, while regular expressions give you prefix/pattern\n * matching.\n *\n * @default []\n * @example\n * ```ts\n * export default Sentry.withSentry(\n * (env) => ({\n * dsn: env.SENTRY_DSN,\n * durableObjectStorageSpanAllowlist: ['cf_my_key', /^cf_reports_/],\n * }),\n * handler,\n * );\n * ```\n */\n durableObjectStorageSpanAllowlist?: Array<string | RegExp>;\n\n /**\n * Sets an optional server name (device name).\n *\n * This is useful for identifying which server or instance is sending events.\n */\n serverName?: string;\n\n /**\n * If you use Spotlight by Sentry during development, use\n * this option to forward captured Sentry events to Spotlight.\n *\n * Either set it to true, or provide a specific Spotlight Sidecar URL.\n *\n * More details: https://spotlightjs.com/\n *\n * IMPORTANT: Only set this option to `true` while developing, not in production!\n */\n spotlight?: boolean | string;\n\n /**\n * Cache the client and reuse it across invocations within the same isolate.\n *\n * The SDK creates one client per isolate and reuses it for all requests/DO\n * handlers in that isolate. This avoids the per-invocation cost of\n * constructing a new client.\n *\n * Since a cached client outlives any single invocation, data captured after an\n * invocation's flush point (post-response `waitUntil` work, detached background\n * work) is delivered eagerly instead of waiting for a flush that never comes.\n *\n * The first `init()` in an isolate decides the cached client's options; later\n * `init()` calls with different options (e.g. another DSN) reuse the cached client\n * unchanged (a debug warning is logged for a DSN change). Use `cacheClient: false`\n * when options must differ per invocation.\n *\n * When disabled, a new client is created per invocation and disposed after the\n * handler completes.\n *\n * @default true\n */\n cacheClient?: boolean;\n\n /**\n * A function that receives the response of a `fetch` handler and the request it answers, and\n * returns whether the response body is still being produced after the handler returns.\n *\n * For `true`, the SDK keeps the `http.server` span open until the body has been sent, so spans\n * created while the body streams stay inside the request. It does this by passing the body through\n * a `TransformStream`. For `false`, the SDK ends the span when the handler returns and sends the\n * response unchanged. For `undefined` or any other value, the SDK decides: Server-Sent Events,\n * NDJSON and `application/stream+json` responses, and `text/plain` and `text/x-component`\n * responses without a `Content-Length` header count as streamed. HTML does not, so return `true`\n * for pages that are rendered with streamed SSR.\n *\n * The function must be synchronous and must not read the response body. Use the status, the\n * headers and the request URL.\n *\n * @example\n * ```ts\n * // src/instrument.server.ts\n * import { defineCloudflareOptions } from '@sentry/cloudflare';\n *\n * export default defineCloudflareOptions(env => ({\n * dsn: env.SENTRY_DSN,\n * isStreamingResponse: response =>\n * response.headers.get('content-type')?.startsWith('text/html') ? true : undefined,\n * }));\n * ```\n */\n isStreamingResponse?: (response: Response, request: Request) => boolean | undefined;\n}\n\n/**\n * Configuration options for the Sentry Cloudflare SDK\n *\n * @see @sentry/core Options for more information.\n */\nexport interface CloudflareOptions extends Options<CloudflareTransportOptions>, BaseCloudflareOptions {\n ctx?: ExecutionContextCompat;\n\n /**\n * A URL to send this server's own envelopes to instead of the Sentry ingest URL. To serve the managed tunnel for the\n * browser, use `serveTunnelIntegration`.\n */\n tunnel?: string;\n}\n\n/**\n * Configuration options for the Sentry Cloudflare SDK Client class\n *\n * @see CloudflareClient for more information.\n */\nexport interface CloudflareClientOptions extends ClientOptions<CloudflareTransportOptions>, BaseCloudflareOptions {\n flushLock?: ReturnType<typeof makeFlushLock>;\n}\n"],"names":["ServerRuntimeClient","applySdkMetadata","spanStreamingIntegration","DEBUG_BUILD","debug","spanIsSampled","_INTERNAL_clearAiProviderSkips","getInvocationState","_INTERNAL_flushLogsBuffer","_INTERNAL_flushMetricsBuffer","getInvocationWaitUntil"],"mappings":";;;;;;;AAoBA,MAAM,+BAAA,GAAkC,eAAA;AAQjC,MAAM,yBAAyBA,0BAAA,CAAoB;AAAA;AAAA;AAAA;AAAA;AAAA,EAwBjD,YAAY,OAAA,EAAkC;AACnD,IAAAC,qBAAA,CAAiB,SAAS,YAAY,CAAA;AACtC,IAAA,OAAA,CAAQ,SAAA,GAAY,OAAA,CAAQ,SAAA,IAAa,EAAC;AAC1C,IAAA,MAAM,EAAE,SAAA,EAAW,GAAG,aAAA,EAAc,GAAI,OAAA;AAExC,IAAA,MAAM,aAAA,GAA4C;AAAA,MAChD,GAAG,aAAA;AAAA,MACH,QAAA,EAAU,YAAA;AAAA;AAAA,MAEV,OAAA,EAAS,EAAE,IAAA,EAAM,YAAA,EAAa;AAAA;AAAA,MAE9B,cAAA,EAAgB;AAAA,KAClB;AAKA,IAAA,IAAA,CACG,OAAO,kBAAA,KAAuB,WAAA,IAAe,kBAAA,KAC9C,cAAc,cAAA,KAAmB,QAAA,IACjC,CAAC,aAAA,CAAc,aAAa,IAAA,CAAK,CAAA,CAAA,KAAK,CAAA,CAAE,IAAA,KAAS,+BAA+B,CAAA,EAChF;AACA,MAAA,aAAA,CAAc,aAAa,IAAA,CAAKC,6BAAA,CAAyB,EAAE,iBAAA,EAAmB,KAAA,EAAO,CAAC,CAAA;AAAA,IACxF;AAEA,IAAA,KAAA,CAAM,aAAa,CAAA;AA/CrB,IAAA,IAAA,CAAQ,aAAA,uBAAiC,GAAA,EAAI;AAC7C,IAAA,IAAA,CAAQ,sBAAA,GAA+C,IAAA;AACvD,IAAA,IAAA,C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,MAAA,MAAM,OAAA,GAAU,IAAA,CAAK,WAAA,EAAY,CAAE,OAAA;AACnC,MAAA,IAAA,CAAK,YAAY,MAAM,IAAA,CAAK,IAAA,CAAK,iBAAA,EAAmB,OAAO,CAAC,CAAA;AAAA,IAC9D,CAAC,CAAA;AACD,IAAA,IAAA,CAAK,EAAA,CAAG,mBAAmB,MAAM,IAAA,CAAK,YAAY,MAAMC,8BAAA,CAA0B,IAAI,CAAC,CAAC,CAAA;AACxF,IAAA,IAAA,CAAK,EAAA,CAAG,sBAAsB,MAAM,IAAA,CAAK,YAAY,MAAMC,iCAAA,CAA6B,IAAI,CAAC,CAAC,CAAA;AAAA,EAChG;AAAA;AAAA;AAAA;AAAA;AAAA,EAMQ,YAAY,KAAA,EAAyB;AAC3C,IAAA,MAAM,kBAAkBF,oCAAA,EAAmB;AAE3C,IAAA,IAAI,eAAA,IAAmB,CAAC,eAAA,CAAgB,iBAAA,EAAmB;AACzD,MAAA;AAAA,IACF;AAEA,IAAA,KAAA,EAAM;AAAA,EACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQQ,iCAAiC,OAAA,EAAqC;AAC5E,IAAA,MAAM,kBAAkBA,oCAAA,EAAmB;AAC3C,IAAA,MAAM,SAAA,GAAY,eAAA,IAAmBG,wCAAA,CAAuB,eAAe,CAAA;AAC3E,IAAA,IAAI,CAAC,SAAA,EAAW;AACd,MAAA;AAAA,IACF;AAEA,IAAA,IAAI;AACF,MAAA,SAAA;AAAA,QACE,OAAA,CAAQ,OAAA,CAAQ,OAAO,CAAA,CAAE,IAAA;AAAA,UACvB,MAAM,KAAA,CAAA;AAAA,UACN,MAAM,KAAA;AAAA;AACR,OACF;AAAA,IACF,CAAA,CAAA,MAAQ;AAAA,IAER;AAAA,EACF;AACF;;;;"}
1
+ {"version":3,"file":"client.js","sources":["../../../src/client.ts"],"sourcesContent":["import type { CheckIn, ClientOptions, MonitorConfig, Options, Scope, TracePropagationTargets } from '@sentry/core';\nimport {\n _INTERNAL_clearAiProviderSkips,\n _INTERNAL_flushLogsBuffer,\n _INTERNAL_flushMetricsBuffer,\n applySdkMetadata,\n debug,\n spanIsSampled,\n spanStreamingIntegration,\n} from '@sentry/core';\nimport type { ServerRuntimeClientOptions } from '@sentry/core/server';\nimport { ServerRuntimeClient } from '@sentry/core/server';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { ExecutionContextCompat } from './executionContext';\nimport type { makeFlushLock } from './flush';\nimport type { CloudflareTransportOptions } from './transport';\nimport { getInvocationState, getInvocationWaitUntil } from './utils/invocationContext';\n\ndeclare const __SENTRY_TRACING__: boolean;\n\nconst SPAN_STREAMING_INTEGRATION_NAME = 'SpanStreaming';\n\n/**\n * The Sentry Cloudflare SDK Client.\n *\n * @see CloudflareClientOptions for documentation on configuration options.\n * @see ServerRuntimeClient for usage documentation.\n */\nexport class CloudflareClient extends ServerRuntimeClient {\n private readonly _flushLock: ReturnType<typeof makeFlushLock> | void;\n private _pendingSpans: Set<string> = new Set();\n private _spanCompletionPromise: Promise<void> | null = null;\n private _resolveSpanCompletion: (() => void) | null = null;\n\n private _unsubscribeSpanStart: (() => void) | null = null;\n private _unsubscribeSpanEnd: (() => void) | null = null;\n\n // True while a boundary `flush()` is draining; envelopes created by that drain ride it\n // and must not each start their own eager transport flush.\n private _inBoundaryFlush = false;\n\n /**\n * Whether this client is a cached, cross-invocation client (`cacheClient`).\n * Cached clients are never disposed at an invocation boundary, so their spans/events\n * are delivered eagerly instead of waiting for a per-invocation flush.\n */\n public readonly isCachedClient: boolean;\n\n /**\n * Creates a new Cloudflare SDK instance.\n * @param options Configuration options for this SDK.\n */\n public constructor(options: CloudflareClientOptions) {\n applySdkMetadata(options, 'cloudflare');\n options._metadata = options._metadata || {};\n const { flushLock, ...serverOptions } = options;\n\n const clientOptions: ServerRuntimeClientOptions = {\n ...serverOptions,\n platform: 'javascript',\n // TODO: Grab version information\n runtime: { name: 'cloudflare' },\n // TODO: Add server name\n _flushInterval: 0,\n };\n\n // workerd can't unref timers, so the default 500ms segment-end flush timer holds every\n // Durable Object invocation open (and billed) until it fires, sampled or not. The boundary\n // flush and the eager drain already deliver streamed spans here.\n if (\n (typeof __SENTRY_TRACING__ === 'undefined' || __SENTRY_TRACING__) &&\n clientOptions.traceLifecycle !== 'static' &&\n !clientOptions.integrations.some(i => i.name === SPAN_STREAMING_INTEGRATION_NAME)\n ) {\n clientOptions.integrations.push(spanStreamingIntegration({ flushOnSegmentEnd: false }));\n }\n\n super(clientOptions);\n this._flushLock = flushLock;\n this.isCachedClient = options.cacheClient === true;\n\n // Track span lifecycle to know when to flush. Skipped for cached clients\n // (`cacheClient`): they are never disposed, so spans that end after\n // a flush are still delivered. Per-invocation clients are disposed right after\n // the boundary flush, so the flush must wait for open spans to end otherwise\n // their transaction never gets emitted.\n if (!this.isCachedClient) {\n this._unsubscribeSpanStart = this.on('spanStart', span => {\n const spanId = span.spanContext().spanId;\n DEBUG_BUILD && debug.log('[CloudflareClient] Span started:', spanId);\n\n // Negatively sampled spans never emit spanEnd,\n // so tracking them would cause _pendingSpans to grow unboundedly.\n // We should fix the inconsistent behavior for NonRecordingSpans in the future but\n // for now, we just ignore them.\n if (!spanIsSampled(span)) {\n return;\n }\n\n this._pendingSpans.add(spanId);\n\n if (!this._spanCompletionPromise) {\n this._spanCompletionPromise = new Promise(resolve => {\n this._resolveSpanCompletion = resolve;\n });\n }\n });\n\n this._unsubscribeSpanEnd = this.on('spanEnd', span => {\n const spanId = span.spanContext().spanId;\n DEBUG_BUILD && debug.log('[CloudflareClient] Span ended:', spanId);\n this._pendingSpans.delete(spanId);\n\n // If no more pending spans, resolve the completion promise\n if (this._pendingSpans.size === 0 && this._resolveSpanCompletion) {\n DEBUG_BUILD && debug.log('[CloudflareClient] All spans completed, preparing to flush');\n this._resolveSpanCompletion();\n this._resetSpanCompletionPromise();\n }\n });\n }\n }\n\n /**\n * Flushes pending operations and ensures all data is processed.\n *\n * Each phase waits at most `timeout`: the flush lock of a per-invocation client, pending spans, event\n * processing and the transport drain. So a flush can take a small multiple of `timeout`, which stays well\n * below Cloudflare's 30 second `waitUntil` limit for the timeouts the SDK uses. Sends still pending when\n * the drain times out are aborted.\n *\n * @param {number} [timeout] - Maximum time in milliseconds for each phase of the flush.\n * @return {Promise<boolean>} A promise that resolves to a boolean indicating whether the flush operation was successful.\n */\n public async flush(timeout?: number): Promise<boolean> {\n // Wait for user waitUntil-registered work to settle before draining, so events\n // captured in that work are still in the buffer. Without this the final flush\n // can drain (and the client be disposed) before background captures land.\n //\n // Only per-invocation clients (`cacheClient: false`) have a flush lock; remove this with them in v12.\n // The wait is bounded by `timeout` because a user `waitUntil` task that outlives the invocation\n // would otherwise keep the flush from draining until the runtime cancels it.\n if (this._flushLock) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n this._flushLock.finalize(),\n ...(timeout ? [new Promise<void>(resolve => (timer = setTimeout(resolve, timeout)))] : []),\n ]);\n clearTimeout(timer);\n }\n\n if (this._pendingSpans.size > 0 && this._spanCompletionPromise) {\n DEBUG_BUILD &&\n debug.log('[CloudflareClient] Waiting for', this._pendingSpans.size, 'pending spans to complete...');\n\n const timeoutMs = timeout ?? 5000;\n const spanCompletionRace = Promise.race([\n this._spanCompletionPromise,\n new Promise(resolve =>\n setTimeout(() => {\n DEBUG_BUILD &&\n debug.log('[CloudflareClient] Span completion timeout after', timeoutMs, 'ms, flushing anyway');\n resolve(undefined);\n }, timeoutMs),\n ),\n ]);\n\n await spanCompletionRace;\n }\n\n // Envelopes created while this flush drains (log/metric/span buffers turning into\n // envelopes on the `flush` emit) ride its own transport drain; without the flag each\n // of them would also start an eager drain and a `waitUntil` registration.\n this._inBoundaryFlush = true;\n try {\n return await super.flush(timeout);\n } finally {\n this._inBoundaryFlush = false;\n }\n }\n\n /**\n * Sends the check-in at once instead of holding it for the flush at the end of the invocation.\n * An `in_progress` check-in of a run that is longer than the check-in margin would otherwise\n * reach Sentry too late, and Sentry would mark the run as missed.\n */\n public override captureCheckIn(checkIn: CheckIn, monitorConfig?: MonitorConfig, scope?: Scope): string {\n const checkInId = super.captureCheckIn(checkIn, monitorConfig, scope);\n const transport = this.getTransport();\n if (transport) {\n this._registerWithInvocationWaitUntil(transport.flush(2000));\n }\n return checkInId;\n }\n\n /**\n * Disposes of the client and releases all resources.\n *\n * This method clears all Cloudflare-specific state in addition to the base client cleanup.\n * It unsubscribes from span lifecycle events and clears pending span tracking.\n *\n * Call this method after flushing to allow the client to be garbage collected.\n * After calling dispose(), the client should not be used anymore.\n */\n public override dispose(): void {\n DEBUG_BUILD && debug.log('[CloudflareClient] Disposing client...');\n\n super.dispose();\n\n if (this._unsubscribeSpanStart) {\n this._unsubscribeSpanStart();\n this._unsubscribeSpanStart = null;\n }\n if (this._unsubscribeSpanEnd) {\n this._unsubscribeSpanEnd();\n this._unsubscribeSpanEnd = null;\n }\n\n this._resetSpanCompletionPromise();\n (this as unknown as { _flushLock: ReturnType<typeof makeFlushLock> | void })._flushLock = undefined;\n }\n\n /** @inheritDoc */\n protected override _setupIntegrations(): void {\n // Clear AI provider skip registrations before setting up integrations.\n // The registry is module-global and Cloudflare calls `init()` per request, so without this a\n // single `ai` SDK call would suppress direct `env.AI.run` spans for the rest of the isolate's\n // life. Mirrors the same reset in the Node client.\n _INTERNAL_clearAiProviderSkips();\n super._setupIntegrations();\n\n // Registered after the integrations on purpose: the flush-point marker must run\n // after core and the span buffer have turned their buffers into envelopes on the\n // same `flush` emit (so those envelopes ride the boundary drain instead of starting\n // eager ones), and the eager span handler relies on `spanStreamingIntegration`\n // having already buffered the span that triggers it.\n if (this.isCachedClient) {\n // Marks the invocation's natural flush point: anything captured from now on\n // (post-response `waitUntil` work, detached continuations) has no later flush\n // to ride and is delivered eagerly by the hooks below.\n this.on('flush', () => {\n const invocationState = getInvocationState();\n if (invocationState) {\n invocationState.flushPointReached = true;\n }\n });\n this._setupEagerEnvelopeDelivery();\n this._setupEagerBufferDelivery();\n }\n }\n\n /**\n * Resets the span completion promise and resolve function.\n */\n private _resetSpanCompletionPromise(): void {\n this._pendingSpans.clear();\n this._spanCompletionPromise = null;\n this._resolveSpanCompletion = null;\n }\n\n /**\n * Drains the transport after an envelope has been accepted past the invocation's\n * flush point. The transport queues request producers until `flush()`; before the\n * flush point the boundary `flush()` drains everything, but envelopes created after\n * it (post-response `waitUntil` work, detached continuations) have no later flush to\n * ride. The drain is registered with the invocation's `waitUntil` to keep the fetch\n * alive; outside any instrumented invocation it always runs.\n */\n private _setupEagerEnvelopeDelivery(): void {\n this.on('afterEnvelope', () => {\n const transport = this.getTransport();\n const invocationState = getInvocationState();\n\n if (!transport || this._inBoundaryFlush || (invocationState && !invocationState.flushPointReached)) {\n return;\n }\n\n this._registerWithInvocationWaitUntil(transport.flush(2000));\n });\n }\n\n /**\n * Turns spans, logs and metrics captured past the invocation's flush point into\n * envelopes. Before the flush point the boundary `flush()` drains their buffers; after\n * it (or outside any instrumented invocation) nothing else would: the log/metric idle\n * timer is disabled for this runtime (`_flushInterval: 0`) and the span buffer's own 5s\n * timer fires outside any invocation, where the runtime suspends the send. Each capture\n * drains only its own bucket (the ended span's trace, the log buffer, the metric\n * buffer), so a fan-out of concurrent traces stays one envelope per trace. RPC method\n * spans never reach this path: `wrapMethodWithSentry` runs the boundary flush after the\n * method span has ended, so only work past that (e.g. detached continuations) lands here.\n */\n private _setupEagerBufferDelivery(): void {\n this.on('afterSpanEnd', span => {\n // The trace id must come from the span, not the current scope: `continueTrace`\n // writes the propagation context to the *current* scope, so the forked\n // isolation scope's propagation context carries a different trace id and\n // flushing by it silently no-ops.\n const traceId = span.spanContext().traceId;\n this._eagerDrain(() => this.emit('flushTraceSpans', traceId));\n });\n this.on('afterCaptureLog', () => this._eagerDrain(() => _INTERNAL_flushLogsBuffer(this)));\n this.on('afterCaptureMetric', () => this._eagerDrain(() => _INTERNAL_flushMetricsBuffer(this)));\n }\n\n /**\n * Runs `drain` unless the owning invocation has not reached its flush point yet\n * (before it the boundary `flush()` delivers the buffers).\n */\n private _eagerDrain(drain: () => void): void {\n const invocationState = getInvocationState();\n\n if (invocationState && !invocationState.flushPointReached) {\n return;\n }\n\n drain();\n }\n\n /**\n * Attaches a promise to the `waitUntil` of the invocation that owns the current\n * async context, so the runtime keeps the send alive after the response is returned.\n * Outside any instrumented invocation (or where the context has no `waitUntil`,\n * e.g. Astro prerendering) the send is fire-and-forget.\n */\n private _registerWithInvocationWaitUntil(promise: PromiseLike<unknown>): void {\n const invocationState = getInvocationState();\n const waitUntil = invocationState && getInvocationWaitUntil(invocationState);\n if (!waitUntil) {\n return;\n }\n\n try {\n waitUntil(\n Promise.resolve(promise).then(\n () => undefined,\n () => undefined,\n ),\n );\n } catch {\n // The owning invocation already ended; the send races isolate teardown either way.\n }\n }\n}\n\ninterface BaseCloudflareOptions {\n /**\n * @ignore Used internally to disable the deDupeIntegration for workflows.\n * @hidden Used internally to disable the deDupeIntegration for workflows.\n * @default true\n */\n enableDedupe?: boolean;\n\n /**\n * @ignore Used internally by SDKs that build `defaultIntegrations` from the Cloudflare defaults.\n * @hidden Used internally by SDKs that build `defaultIntegrations` from the Cloudflare defaults.\n *\n * Marks the `defaultIntegrations` list as an extension of the SDK defaults, so the SDK also adds\n * the integrations of instrumented modules that load after `init()`.\n * @default false\n */\n _extendsDefaultIntegrations?: boolean;\n\n /**\n * The Cloudflare SDK is not OpenTelemetry native. By default (`false`) it does not set up a tracer\n * provider; spans are emitted via the SDK's own instrumentation and scopes are isolated with\n * AsyncLocalStorage.\n *\n * Set this to `true` to opt into the OpenTelemetry compatibility tracer, which captures spans\n * emitted via `@opentelemetry/api`. Big caveat: it does not handle custom context, always working\n * off the current scope. This is good enough for many, but not all, integrations.\n *\n * @default false\n */\n enableOpenTelemetrySetup?: boolean;\n\n /**\n * The bindings on `env` that outgoing RPC calls propagate trace context to.\n *\n * Strings match a binding name exactly, regular expressions match by pattern. An empty array\n * (the default) propagates to nothing.\n *\n * RPC has no headers to carry trace context, so the SDK appends it as a trailing argument to\n * every RPC method call on a matching binding. Only a Sentry-instrumented receiver strips that\n * argument again. Anywhere else it arrives as a real argument and changes what the method was\n * called with, so list only the bindings whose receiver you know runs Sentry.\n *\n * Propagation over `stub.fetch()` and service binding `fetch()` uses HTTP headers and is not\n * affected by this option.\n *\n * Strings match a binding name exactly, regular expressions match by pattern. Both match\n * case-insensitively.\n *\n * When you build with the Sentry Cloudflare Vite plugin, bindings that resolve to *this* worker\n * (its own Durable Objects, its self service bindings) are added for you, because the plugin\n * instruments those receivers itself. Whatever you list here is added on top of them.\n *\n * @default []\n * @example\n * ```ts\n * // Propagate to `env.ORDERS` and every `env.SVC_*` binding\n * export default Sentry.withSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * rpcTracePropagationBindings: ['ORDERS', /^SVC_/],\n * }),\n * handler,\n * );\n * ```\n */\n rpcTracePropagationBindings?: TracePropagationTargets;\n\n /**\n * The Queue producer bindings on `env` that outgoing messages propagate trace context to.\n *\n * Cloudflare Queues has no message headers, so the SDK adds the producer's `sentry-trace` to\n * plain-object message bodies under `__sentry_queue_trace__`. Arrays, binary data and other\n * non-plain values are sent unchanged. A Sentry-instrumented consumer removes that field before\n * your queue handler runs and links its `queue.process` span to every producer in the batch.\n * Anywhere else the field arrives as part of the message body, so list only the queues whose\n * consumer you know runs Sentry.\n *\n * The field adds about 80 bytes to each message. Cloudflare rejects messages over 128 KB, so a\n * message close to that limit can fail to send once propagation is enabled.\n *\n * Strings match a binding name exactly, regular expressions match by pattern. Both match\n * case-insensitively.\n *\n * @default []\n * @example\n * ```ts\n * // Propagate to `env.BILLING_QUEUE` and every `env.JOBS_*` binding\n * export default Sentry.withSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * queueTracePropagationBindings: ['BILLING_QUEUE', /^JOBS_/],\n * }),\n * handler,\n * );\n * ```\n */\n queueTracePropagationBindings?: TracePropagationTargets;\n\n /**\n * Table names that should stay instrumented even though they match a reserved prefix used by\n * Durable Object frameworks for their internal SQLite tables: `cf_` (`agents`, `partyserver`, ...)\n * and `pi_` (pi-durable in the `PiHarness` of `agents`).\n *\n * By default, `exec` queries against tables with these prefixes are treated as framework noise and\n * no `db.query` span is created for them. If one of your own tables happens to use such a prefix,\n * add it here to opt it back into instrumentation, or add `/^pi_/` to see the statements of\n * pi-durable. Entries are matched against each table name in the\n * query summary — strings must match exactly, while regular expressions give you prefix/pattern\n * matching.\n *\n * @default []\n * @example\n * ```ts\n * export default Sentry.withSentry(\n * (env) => ({\n * dsn: env.SENTRY_DSN,\n * durableObjectSqlSpanAllowlist: ['cf_my_table', /^cf_reports_/],\n * }),\n * handler,\n * );\n * ```\n */\n durableObjectSqlSpanAllowlist?: Array<string | RegExp>;\n\n /**\n * KV keys that should stay instrumented even though they match a reserved prefix used by Durable\n * Object frameworks (`agents`, `partyserver`, ...) for their internal storage entries.\n *\n * By default, KV reads/writes (`get`, `put`, `delete`, `list`) of `cf_`- or `__ps_`-prefixed keys\n * are treated as framework noise and no `durable_object_storage_*` span is created for them,\n * mirroring how `cf_`-prefixed SQL tables are handled (see {@link durableObjectSqlSpanAllowlist}).\n * If one of your own keys happens to use such a prefix, add it here to opt it back into\n * instrumentation. Strings must match exactly, while regular expressions give you prefix/pattern\n * matching.\n *\n * @default []\n * @example\n * ```ts\n * export default Sentry.withSentry(\n * (env) => ({\n * dsn: env.SENTRY_DSN,\n * durableObjectStorageSpanAllowlist: ['cf_my_key', /^cf_reports_/],\n * }),\n * handler,\n * );\n * ```\n */\n durableObjectStorageSpanAllowlist?: Array<string | RegExp>;\n\n /**\n * Sets an optional server name (device name).\n *\n * This is useful for identifying which server or instance is sending events.\n */\n serverName?: string;\n\n /**\n * If you use Spotlight by Sentry during development, use\n * this option to forward captured Sentry events to Spotlight.\n *\n * Either set it to true, or provide a specific Spotlight Sidecar URL.\n *\n * More details: https://spotlightjs.com/\n *\n * IMPORTANT: Only set this option to `true` while developing, not in production!\n */\n spotlight?: boolean | string;\n\n /**\n * Cache the client and reuse it across invocations within the same isolate.\n *\n * The SDK creates one client per isolate and reuses it for all requests/DO\n * handlers in that isolate. This avoids the per-invocation cost of\n * constructing a new client.\n *\n * Since a cached client outlives any single invocation, data captured after an\n * invocation's flush point (post-response `waitUntil` work, detached background\n * work) is delivered eagerly instead of waiting for a flush that never comes.\n *\n * The first `init()` in an isolate decides the cached client's options; later\n * `init()` calls with different options (e.g. another DSN) reuse the cached client\n * unchanged (a debug warning is logged for a DSN change). Use `cacheClient: false`\n * when options must differ per invocation.\n *\n * When disabled, a new client is created per invocation and disposed after the\n * handler completes.\n *\n * @default true\n */\n cacheClient?: boolean;\n\n /**\n * A function that receives the response of a `fetch` handler and the request it answers, and\n * returns whether the response body is still being produced after the handler returns.\n *\n * For `true`, the SDK keeps the `http.server` span open until the body has been sent, so spans\n * created while the body streams stay inside the request. It does this by passing the body through\n * a `TransformStream`. For `false`, the SDK ends the span when the handler returns and sends the\n * response unchanged. For `undefined` or any other value, the SDK decides: Server-Sent Events,\n * NDJSON and `application/stream+json` responses, and `text/plain` and `text/x-component`\n * responses without a `Content-Length` header count as streamed. HTML does not, so return `true`\n * for pages that are rendered with streamed SSR.\n *\n * The function must be synchronous and must not read the response body. Use the status, the\n * headers and the request URL.\n *\n * @example\n * ```ts\n * // src/instrument.server.ts\n * import { defineCloudflareOptions } from '@sentry/cloudflare';\n *\n * export default defineCloudflareOptions(env => ({\n * dsn: env.SENTRY_DSN,\n * isStreamingResponse: response =>\n * response.headers.get('content-type')?.startsWith('text/html') ? true : undefined,\n * }));\n * ```\n */\n isStreamingResponse?: (response: Response, request: Request) => boolean | undefined;\n}\n\n/**\n * Configuration options for the Sentry Cloudflare SDK\n *\n * @see @sentry/core Options for more information.\n */\nexport interface CloudflareOptions extends Options<CloudflareTransportOptions>, BaseCloudflareOptions {\n ctx?: ExecutionContextCompat;\n\n /**\n * A URL to send this server's own envelopes to instead of the Sentry ingest URL. To serve the managed tunnel for the\n * browser, use `serveTunnelIntegration`.\n */\n tunnel?: string;\n}\n\n/**\n * Configuration options for the Sentry Cloudflare SDK Client class\n *\n * @see CloudflareClient for more information.\n */\nexport interface CloudflareClientOptions extends ClientOptions<CloudflareTransportOptions>, BaseCloudflareOptions {\n flushLock?: ReturnType<typeof makeFlushLock>;\n}\n"],"names":["ServerRuntimeClient","applySdkMetadata","spanStreamingIntegration","DEBUG_BUILD","debug","spanIsSampled","_INTERNAL_clearAiProviderSkips","getInvocationState","_INTERNAL_flushLogsBuffer","_INTERNAL_flushMetricsBuffer","getInvocationWaitUntil"],"mappings":";;;;;;;AAoBA,MAAM,+BAAA,GAAkC,eAAA;AAQjC,MAAM,yBAAyBA,0BAAA,CAAoB;AAAA;AAAA;AAAA;AAAA;AAAA,EAwBjD,YAAY,OAAA,EAAkC;AACnD,IAAAC,qBAAA,CAAiB,SAAS,YAAY,CAAA;AACtC,IAAA,OAAA,CAAQ,SAAA,GAAY,OAAA,CAAQ,SAAA,IAAa,EAAC;AAC1C,IAAA,MAAM,EAAE,SAAA,EAAW,GAAG,aAAA,EAAc,GAAI,OAAA;AAExC,IAAA,MAAM,aAAA,GAA4C;AAAA,MAChD,GAAG,aAAA;AAAA,MACH,QAAA,EAAU,YAAA;AAAA;AAAA,MAEV,OAAA,EAAS,EAAE,IAAA,EAAM,YAAA,EAAa;AAAA;AAAA,MAE9B,cAAA,EAAgB;AAAA,KAClB;AAKA,IAAA,IAAA,CACG,OAAO,kBAAA,KAAuB,WAAA,IAAe,kBAAA,KAC9C,cAAc,cAAA,KAAmB,QAAA,IACjC,CAAC,aAAA,CAAc,aAAa,IAAA,CAAK,CAAA,CAAA,KAAK,CAAA,CAAE,IAAA,KAAS,+BAA+B,CAAA,EAChF;AACA,MAAA,aAAA,CAAc,aAAa,IAAA,CAAKC,6BAAA,CAAyB,EAAE,iBAAA,EAAmB,KAAA,EAAO,CAAC,CAAA;AAAA,IACxF;AAEA,IAAA,KAAA,CAAM,aAAa,CAAA;AA/CrB,IAAA,IAAA,CAAQ,aAAA,uBAAiC,GAAA,EAAI;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DurableObjectHandlers = require('./instrumentations/instrumentDurableObjectHandlers.js');
8
8
  const instrumentEnv = require('./instrumentations/worker/instrumentEnv.js');
9
9
  const options = require('./options.js');
10
+ const orchestrionDeferredChannels = require('./orchestrion-deferred-channels.js');
11
+ const sdk = require('./sdk.js');
10
12
  const instrumentContext = require('./utils/instrumentContext.js');
11
13
  const invocationScope = require('./utils/invocationScope.js');
12
14
  const rpcMeta = require('./utils/rpcMeta.js');
@@ -20,10 +22,14 @@ function constructInstrumentedDurableObject(target, ctx, env, newTarget, options
20
22
  const instrumentedEnv = instrumentEnv.instrumentEnv(env, options$1);
21
23
  const prototype = newTarget.prototype ?? target.prototype;
22
24
  const cachedFrameworkManagedMethods = frameworkManagedMethodsCache.get(prototype);
23
- const methodsBeforeConstruction = cachedFrameworkManagedMethods ? void 0 : resolvePrototypeMethods(prototype);
24
- const obj = invocationScope.withConstructionIsolationScope(
25
- () => Reflect.construct(target, [context, instrumentedEnv], newTarget)
26
- );
25
+ const methodsBeforeConstruction = cachedFrameworkManagedMethods ? void 0 : resolveMethodsBeforeFirstConstruction(prototype);
26
+ const obj = invocationScope.withConstructionIsolationScope(() => {
27
+ if (options$1.cacheClient !== false) {
28
+ sdk.init({ ...options$1 });
29
+ orchestrionDeferredChannels.flushDeferredChannelEvents();
30
+ }
31
+ return Reflect.construct(target, [context, instrumentedEnv], newTarget);
32
+ });
27
33
  const frameworkManagedMethods = resolveFrameworkManagedMethods(
28
34
  prototype,
29
35
  obj,
@@ -34,6 +40,15 @@ function constructInstrumentedDurableObject(target, ctx, env, newTarget, options
34
40
  return { obj, options: options$1, context, frameworkManagedMethods };
35
41
  }
36
42
  const frameworkManagedMethodsCache = /* @__PURE__ */ new WeakMap();
43
+ const methodsBeforeFirstConstructionCache = /* @__PURE__ */ new WeakMap();
44
+ function resolveMethodsBeforeFirstConstruction(prototype) {
45
+ let methods = methodsBeforeFirstConstructionCache.get(prototype);
46
+ if (!methods) {
47
+ methods = resolvePrototypeMethods(prototype);
48
+ methodsBeforeFirstConstructionCache.set(prototype, methods);
49
+ }
50
+ return methods;
51
+ }
37
52
  function resolvePrototypeMethods(prototype) {
38
53
  const methods = /* @__PURE__ */ new Map();
39
54
  for (let current = prototype; current && current !== Object.prototype; current = Object.getPrototypeOf(current)) {
@@ -62,6 +77,7 @@ function resolveFrameworkManagedMethods(prototype, obj, methodsBeforeConstructio
62
77
  }
63
78
  }
64
79
  frameworkManagedMethodsCache.set(prototype, managed);
80
+ methodsBeforeFirstConstructionCache.delete(prototype);
65
81
  return managed;
66
82
  }
67
83
  const RESERVED_RPC_METHOD_NAMES = /* @__PURE__ */ new Set([