@sentry/cloudflare 10.47.0 → 10.49.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 (171) hide show
  1. package/build/cjs/client.js.map +1 -1
  2. package/build/cjs/durableobject.js +42 -16
  3. package/build/cjs/durableobject.js.map +1 -1
  4. package/build/cjs/index.js +3 -0
  5. package/build/cjs/index.js.map +1 -1
  6. package/build/cjs/instrument.js +72 -8
  7. package/build/cjs/instrument.js.map +1 -1
  8. package/build/cjs/instrumentations/instrumentDurableObjectNamespace.js +56 -0
  9. package/build/cjs/instrumentations/instrumentDurableObjectNamespace.js.map +1 -0
  10. package/build/cjs/instrumentations/instrumentDurableObjectStorage.js +38 -3
  11. package/build/cjs/instrumentations/instrumentDurableObjectStorage.js.map +1 -1
  12. package/build/cjs/instrumentations/instrumentWorkerEntrypoint.js +101 -0
  13. package/build/cjs/instrumentations/instrumentWorkerEntrypoint.js.map +1 -0
  14. package/build/cjs/instrumentations/worker/instrumentEmail.js +16 -13
  15. package/build/cjs/instrumentations/worker/instrumentEmail.js.map +1 -1
  16. package/build/cjs/instrumentations/worker/instrumentEnv.js +83 -0
  17. package/build/cjs/instrumentations/worker/instrumentEnv.js.map +1 -0
  18. package/build/cjs/instrumentations/worker/instrumentFetch.js +36 -10
  19. package/build/cjs/instrumentations/worker/instrumentFetch.js.map +1 -1
  20. package/build/cjs/instrumentations/worker/instrumentFetcher.js +38 -0
  21. package/build/cjs/instrumentations/worker/instrumentFetcher.js.map +1 -0
  22. package/build/cjs/instrumentations/worker/instrumentQueue.js +36 -10
  23. package/build/cjs/instrumentations/worker/instrumentQueue.js.map +1 -1
  24. package/build/cjs/instrumentations/worker/instrumentScheduled.js +36 -13
  25. package/build/cjs/instrumentations/worker/instrumentScheduled.js.map +1 -1
  26. package/build/cjs/instrumentations/worker/instrumentTail.js +34 -10
  27. package/build/cjs/instrumentations/worker/instrumentTail.js.map +1 -1
  28. package/build/cjs/integrations/tracing/vercelai.js +2 -1
  29. package/build/cjs/integrations/tracing/vercelai.js.map +1 -1
  30. package/build/cjs/request.js +5 -6
  31. package/build/cjs/request.js.map +1 -1
  32. package/build/cjs/scope-utils.js.map +1 -1
  33. package/build/cjs/sdk.js +6 -1
  34. package/build/cjs/sdk.js.map +1 -1
  35. package/build/cjs/utils/instrumentContext.js +2 -1
  36. package/build/cjs/utils/instrumentContext.js.map +1 -1
  37. package/build/cjs/utils/isBinding.js +32 -0
  38. package/build/cjs/utils/isBinding.js.map +1 -0
  39. package/build/cjs/utils/isCloudflareClass.js +29 -0
  40. package/build/cjs/utils/isCloudflareClass.js.map +1 -0
  41. package/build/cjs/utils/rpcOptions.js +84 -0
  42. package/build/cjs/utils/rpcOptions.js.map +1 -0
  43. package/build/cjs/utils/traceLinks.js +78 -0
  44. package/build/cjs/utils/traceLinks.js.map +1 -0
  45. package/build/cjs/withSentry.js +31 -20
  46. package/build/cjs/withSentry.js.map +1 -1
  47. package/build/cjs/workflows.js +3 -2
  48. package/build/cjs/workflows.js.map +1 -1
  49. package/build/cjs/wrapMethodWithSentry.js +157 -112
  50. package/build/cjs/wrapMethodWithSentry.js.map +1 -1
  51. package/build/esm/client.js.map +1 -1
  52. package/build/esm/durableobject.js +43 -17
  53. package/build/esm/durableobject.js.map +1 -1
  54. package/build/esm/index.js +1 -1
  55. package/build/esm/instrument.js +71 -8
  56. package/build/esm/instrument.js.map +1 -1
  57. package/build/esm/instrumentations/instrumentDurableObjectNamespace.js +54 -0
  58. package/build/esm/instrumentations/instrumentDurableObjectNamespace.js.map +1 -0
  59. package/build/esm/instrumentations/instrumentDurableObjectStorage.js +39 -4
  60. package/build/esm/instrumentations/instrumentDurableObjectStorage.js.map +1 -1
  61. package/build/esm/instrumentations/instrumentWorkerEntrypoint.js +99 -0
  62. package/build/esm/instrumentations/instrumentWorkerEntrypoint.js.map +1 -0
  63. package/build/esm/instrumentations/worker/instrumentEmail.js +17 -14
  64. package/build/esm/instrumentations/worker/instrumentEmail.js.map +1 -1
  65. package/build/esm/instrumentations/worker/instrumentEnv.js +81 -0
  66. package/build/esm/instrumentations/worker/instrumentEnv.js.map +1 -0
  67. package/build/esm/instrumentations/worker/instrumentFetch.js +37 -12
  68. package/build/esm/instrumentations/worker/instrumentFetch.js.map +1 -1
  69. package/build/esm/instrumentations/worker/instrumentFetcher.js +36 -0
  70. package/build/esm/instrumentations/worker/instrumentFetcher.js.map +1 -0
  71. package/build/esm/instrumentations/worker/instrumentQueue.js +37 -12
  72. package/build/esm/instrumentations/worker/instrumentQueue.js.map +1 -1
  73. package/build/esm/instrumentations/worker/instrumentScheduled.js +37 -15
  74. package/build/esm/instrumentations/worker/instrumentScheduled.js.map +1 -1
  75. package/build/esm/instrumentations/worker/instrumentTail.js +35 -12
  76. package/build/esm/instrumentations/worker/instrumentTail.js.map +1 -1
  77. package/build/esm/integrations/tracing/vercelai.js +2 -1
  78. package/build/esm/integrations/tracing/vercelai.js.map +1 -1
  79. package/build/esm/package.json +1 -1
  80. package/build/esm/request.js +5 -6
  81. package/build/esm/request.js.map +1 -1
  82. package/build/esm/scope-utils.js.map +1 -1
  83. package/build/esm/sdk.js +7 -2
  84. package/build/esm/sdk.js.map +1 -1
  85. package/build/esm/utils/instrumentContext.js +2 -1
  86. package/build/esm/utils/instrumentContext.js.map +1 -1
  87. package/build/esm/utils/isBinding.js +29 -0
  88. package/build/esm/utils/isBinding.js.map +1 -0
  89. package/build/esm/utils/isCloudflareClass.js +27 -0
  90. package/build/esm/utils/isCloudflareClass.js.map +1 -0
  91. package/build/esm/utils/rpcOptions.js +81 -0
  92. package/build/esm/utils/rpcOptions.js.map +1 -0
  93. package/build/esm/utils/traceLinks.js +73 -0
  94. package/build/esm/utils/traceLinks.js.map +1 -0
  95. package/build/esm/withSentry.js +32 -21
  96. package/build/esm/withSentry.js.map +1 -1
  97. package/build/esm/workflows.js +3 -2
  98. package/build/esm/workflows.js.map +1 -1
  99. package/build/esm/wrapMethodWithSentry.js +159 -114
  100. package/build/esm/wrapMethodWithSentry.js.map +1 -1
  101. package/build/types/client.d.ts +39 -10
  102. package/build/types/client.d.ts.map +1 -1
  103. package/build/types/durableobject.d.ts.map +1 -1
  104. package/build/types/index.d.ts +1 -1
  105. package/build/types/index.d.ts.map +1 -1
  106. package/build/types/instrument.d.ts +15 -4
  107. package/build/types/instrument.d.ts.map +1 -1
  108. package/build/types/instrumentations/instrumentDurableObjectNamespace.d.ts +12 -0
  109. package/build/types/instrumentations/instrumentDurableObjectNamespace.d.ts.map +1 -0
  110. package/build/types/instrumentations/instrumentDurableObjectStorage.d.ts +8 -1
  111. package/build/types/instrumentations/instrumentDurableObjectStorage.d.ts.map +1 -1
  112. package/build/types/instrumentations/instrumentWorkerEntrypoint.d.ts +42 -0
  113. package/build/types/instrumentations/instrumentWorkerEntrypoint.d.ts.map +1 -0
  114. package/build/types/instrumentations/worker/instrumentEmail.d.ts +2 -1
  115. package/build/types/instrumentations/worker/instrumentEmail.d.ts.map +1 -1
  116. package/build/types/instrumentations/worker/instrumentEnv.d.ts +16 -0
  117. package/build/types/instrumentations/worker/instrumentEnv.d.ts.map +1 -0
  118. package/build/types/instrumentations/worker/instrumentFetch.d.ts +6 -1
  119. package/build/types/instrumentations/worker/instrumentFetch.d.ts.map +1 -1
  120. package/build/types/instrumentations/worker/instrumentFetcher.d.ts +10 -0
  121. package/build/types/instrumentations/worker/instrumentFetcher.d.ts.map +1 -0
  122. package/build/types/instrumentations/worker/instrumentQueue.d.ts +6 -1
  123. package/build/types/instrumentations/worker/instrumentQueue.d.ts.map +1 -1
  124. package/build/types/instrumentations/worker/instrumentScheduled.d.ts +6 -1
  125. package/build/types/instrumentations/worker/instrumentScheduled.d.ts.map +1 -1
  126. package/build/types/instrumentations/worker/instrumentTail.d.ts +6 -1
  127. package/build/types/instrumentations/worker/instrumentTail.d.ts.map +1 -1
  128. package/build/types/integrations/tracing/vercelai.d.ts +9 -1
  129. package/build/types/integrations/tracing/vercelai.d.ts.map +1 -1
  130. package/build/types/request.d.ts +3 -3
  131. package/build/types/request.d.ts.map +1 -1
  132. package/build/types/scope-utils.d.ts +2 -2
  133. package/build/types/scope-utils.d.ts.map +1 -1
  134. package/build/types/sdk.d.ts.map +1 -1
  135. package/build/types/utils/instrumentContext.d.ts.map +1 -1
  136. package/build/types/utils/isBinding.d.ts +49 -0
  137. package/build/types/utils/isBinding.d.ts.map +1 -0
  138. package/build/types/utils/isCloudflareClass.d.ts +30 -0
  139. package/build/types/utils/isCloudflareClass.d.ts.map +1 -0
  140. package/build/types/utils/rpcOptions.d.ts +24 -0
  141. package/build/types/utils/rpcOptions.d.ts.map +1 -0
  142. package/build/types/utils/traceLinks.d.ts +27 -0
  143. package/build/types/utils/traceLinks.d.ts.map +1 -0
  144. package/build/types/withSentry.d.ts +3 -2
  145. package/build/types/withSentry.d.ts.map +1 -1
  146. package/build/types/workflows.d.ts.map +1 -1
  147. package/build/types/wrapMethodWithSentry.d.ts +19 -2
  148. package/build/types/wrapMethodWithSentry.d.ts.map +1 -1
  149. package/build/types-ts3.8/client.d.ts +39 -10
  150. package/build/types-ts3.8/index.d.ts +1 -1
  151. package/build/types-ts3.8/instrument.d.ts +15 -4
  152. package/build/types-ts3.8/instrumentations/instrumentDurableObjectNamespace.d.ts +12 -0
  153. package/build/types-ts3.8/instrumentations/instrumentDurableObjectStorage.d.ts +8 -1
  154. package/build/types-ts3.8/instrumentations/instrumentWorkerEntrypoint.d.ts +42 -0
  155. package/build/types-ts3.8/instrumentations/worker/instrumentEmail.d.ts +2 -1
  156. package/build/types-ts3.8/instrumentations/worker/instrumentEnv.d.ts +16 -0
  157. package/build/types-ts3.8/instrumentations/worker/instrumentFetch.d.ts +6 -1
  158. package/build/types-ts3.8/instrumentations/worker/instrumentFetcher.d.ts +10 -0
  159. package/build/types-ts3.8/instrumentations/worker/instrumentQueue.d.ts +6 -1
  160. package/build/types-ts3.8/instrumentations/worker/instrumentScheduled.d.ts +6 -1
  161. package/build/types-ts3.8/instrumentations/worker/instrumentTail.d.ts +6 -1
  162. package/build/types-ts3.8/integrations/tracing/vercelai.d.ts +9 -1
  163. package/build/types-ts3.8/request.d.ts +3 -3
  164. package/build/types-ts3.8/scope-utils.d.ts +2 -2
  165. package/build/types-ts3.8/utils/isBinding.d.ts +49 -0
  166. package/build/types-ts3.8/utils/isCloudflareClass.d.ts +30 -0
  167. package/build/types-ts3.8/utils/rpcOptions.d.ts +24 -0
  168. package/build/types-ts3.8/utils/traceLinks.d.ts +27 -0
  169. package/build/types-ts3.8/withSentry.d.ts +3 -2
  170. package/build/types-ts3.8/wrapMethodWithSentry.d.ts +19 -2
  171. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"workflows.js","sources":["../../src/workflows.ts"],"sourcesContent":["import type { PropagationContext } from '@sentry/core';\nimport {\n captureException,\n flush,\n getCurrentScope,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n startSpan,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type {\n WorkflowEntrypoint,\n WorkflowEvent,\n WorkflowSleepDuration,\n WorkflowStep,\n WorkflowStepConfig,\n WorkflowStepEvent,\n WorkflowTimeoutDuration,\n} from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport type { CloudflareOptions } from './client';\nimport { flushAndDispose } from './flush';\nimport { addCloudResourceContext } from './scope-utils';\nimport { init } from './sdk';\nimport { instrumentContext } from './utils/instrumentContext';\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 _ctx: ExecutionContext,\n private _options: CloudflareOptions,\n private _step: WorkflowStep,\n ) {}\n\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n callback: (...args: unknown[]) => Promise<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n config: WorkflowStepConfig,\n callback: (...args: unknown[]) => Promise<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n configOrCallback: WorkflowStepConfig | (() => Promise<T>),\n maybeCallback?: (...args: unknown[]) => Promise<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 userCallback = (maybeCallback || configOrCallback) as (...args: unknown[]) => Promise<T>;\n const config = typeof configOrCallback === 'function' ? undefined : configOrCallback;\n\n const instrumentedCallback = async (...args: unknown[]): Promise<T> => {\n return startSpan(\n {\n op: 'function.step.do',\n name,\n scope: scopeForStep,\n attributes: {\n 'cloudflare.workflow.timeout': config?.timeout,\n 'cloudflare.workflow.retries.backoff': config?.retries?.backoff,\n 'cloudflare.workflow.retries.delay': config?.retries?.delay,\n 'cloudflare.workflow.retries.limit': config?.retries?.limit,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.workflow',\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'task',\n },\n },\n async span => {\n try {\n const result = await userCallback(...args);\n span.setStatus({ code: 1 });\n return result;\n } catch (error) {\n captureException(error, { mechanism: { handled: true, type: 'auto.faas.cloudflare.workflow' } });\n throw error;\n } finally {\n this._ctx.waitUntil(flush(2000));\n }\n },\n );\n };\n\n return config ? this._step.do(name, config, instrumentedCallback) : 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, // Environment type\n P, // Payload type\n T extends WorkflowEntrypoint<E, P>, // WorkflowEntrypoint type\n C extends new (ctx: ExecutionContext, env: E) => T, // Constructor type of the WorkflowEntrypoint class\n>(optionsCallback: (env: E) => CloudflareOptions, WorkFlowClass: C): C {\n return new Proxy(WorkFlowClass, {\n construct(target: C, args: [ctx: ExecutionContext, env: E], newTarget) {\n const [ctx, env] = args;\n const context = instrumentContext(ctx);\n args[0] = context;\n\n const options = optionsCallback(env);\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 setAsyncLocalStorageAsyncContextStrategy();\n\n return withIsolationScope(async isolationScope => {\n const client = init({ ...options, 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, context, options, step),\n );\n } finally {\n context.waitUntil(flushAndDispose(client));\n }\n });\n });\n };\n }\n return Reflect.get(obj, prop, receiver);\n },\n });\n },\n });\n}\n"],"names":["getCurrentScope","startSpan","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","captureException","flush","instrumentContext","setAsyncLocalStorageAsyncContextStrategy","withIsolationScope","init","addCloudResourceContext","withScope","flushAndDispose"],"mappings":";;;;;;;;;AA2BA,MAAM,UAAA,GAAa,qEAAqE;;AAExF;AACA;AACA;AACO,eAAe,kCAAkC,CAAC,UAAU,EAA2B;AAC9F,EAAE,MAAM,MAAM,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;AACvF,EAAE;AACF,IAAI,KAAK,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,GAAG,CAAC;AAClC;AACA,OAAO,KAAK,CAAC,CAAC,EAAE,EAAE;AAClB,OAAO,GAAG,CAAC,CAAA,IAAK,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC;AAC/C,OAAO,IAAI,CAAC,EAAE;AACd;AACA;;AAEA,eAAe,gCAAgC,CAAC,UAAU,EAAuC;AACjG,EAAE,MAAM,OAAA,GAAU,UAAU,CAAC,IAAI,CAAC,UAAU;AAC5C,MAAM,UAAU,CAAC,OAAO,CAAC,IAAI,EAAE,E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AU,CAAC;AACrG,kBAAkB,KAAK,CAAC,qBAAqB,CAAC,kBAAkB,CAAC;;AAEjE,kBAAkB,IAAI;AACtB,oBAAoB,OAAO,MAAM,GAAG,CAAC,GAAG,CAAC,IAAI;AAC7C,sBAAsB,GAAG;AACzB,sBAAsB,KAAK;AAC3B,sBAAsB,IAAI,mBAAmB,CAAC,KAAK,CAAC,UAAU,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC;AACvF,qBAAqB;AACrB,kBAAkB,UAAU;AAC5B,oBAAoB,OAAO,CAAC,SAAS,CAACC,qBAAe,CAAC,MAAM,CAAC,CAAC;AAC9D,kBAAkB;AAClB,gBAAgB,CAAC,CAAC;AAClB,cAAc,CAAC,CAAC;AAChB,YAAY,CAAC;AACb,UAAU;AACV,UAAU,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,QAAQ,CAAC;AACjD,QAAQ,CAAC;AACT,OAAO,CAAC;AACR,IAAI,CAAC;AACL,GAAG,CAAC;AACJ;;;;;"}
1
+ {"version":3,"file":"workflows.js","sources":["../../src/workflows.ts"],"sourcesContent":["import type { PropagationContext } from '@sentry/core';\nimport {\n captureException,\n flush,\n getCurrentScope,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n startSpan,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type {\n WorkflowEntrypoint,\n WorkflowEvent,\n WorkflowSleepDuration,\n WorkflowStep,\n WorkflowStepConfig,\n WorkflowStepEvent,\n WorkflowTimeoutDuration,\n} from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport type { CloudflareOptions } from './client';\nimport { flushAndDispose } from './flush';\nimport { instrumentEnv } from './instrumentations/worker/instrumentEnv';\nimport { addCloudResourceContext } from './scope-utils';\nimport { init } from './sdk';\nimport { instrumentContext } from './utils/instrumentContext';\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 _ctx: ExecutionContext,\n private _options: CloudflareOptions,\n private _step: WorkflowStep,\n ) {}\n\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n callback: (...args: unknown[]) => Promise<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n config: WorkflowStepConfig,\n callback: (...args: unknown[]) => Promise<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n configOrCallback: WorkflowStepConfig | (() => Promise<T>),\n maybeCallback?: (...args: unknown[]) => Promise<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 userCallback = (maybeCallback || configOrCallback) as (...args: unknown[]) => Promise<T>;\n const config = typeof configOrCallback === 'function' ? undefined : configOrCallback;\n\n const instrumentedCallback = async (...args: unknown[]): Promise<T> => {\n return startSpan(\n {\n op: 'function.step.do',\n name,\n scope: scopeForStep,\n attributes: {\n 'cloudflare.workflow.timeout': config?.timeout,\n 'cloudflare.workflow.retries.backoff': config?.retries?.backoff,\n 'cloudflare.workflow.retries.delay': config?.retries?.delay,\n 'cloudflare.workflow.retries.limit': config?.retries?.limit,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.workflow',\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'task',\n },\n },\n async span => {\n try {\n const result = await userCallback(...args);\n span.setStatus({ code: 1 });\n return result;\n } catch (error) {\n captureException(error, { mechanism: { handled: true, type: 'auto.faas.cloudflare.workflow' } });\n throw error;\n } finally {\n this._ctx.waitUntil(flush(2000));\n }\n },\n );\n };\n\n return config ? this._step.do(name, config, instrumentedCallback) : 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, // Environment type\n P, // Payload type\n T extends WorkflowEntrypoint<E, P>, // WorkflowEntrypoint type\n C extends new (ctx: ExecutionContext, env: E) => T, // Constructor type of the WorkflowEntrypoint class\n>(optionsCallback: (env: E) => CloudflareOptions, WorkFlowClass: C): C {\n return new Proxy(WorkFlowClass, {\n construct(target: C, args: [ctx: ExecutionContext, env: E], 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 setAsyncLocalStorageAsyncContextStrategy();\n\n return withIsolationScope(async isolationScope => {\n const client = init({ ...options, 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, context, options, step),\n );\n } finally {\n context.waitUntil(flushAndDispose(client));\n }\n });\n });\n };\n }\n return Reflect.get(obj, prop, receiver);\n },\n });\n },\n });\n}\n"],"names":["getCurrentScope","startSpan","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","captureException","flush","instrumentContext","instrumentEnv","setAsyncLocalStorageAsyncContextStrategy","withIsolationScope","init","addCloudResourceContext","withScope","flushAndDispose"],"mappings":";;;;;;;;;;AA4BA,MAAM,UAAA,GAAa,qEAAqE;;AAExF;AACA;AACA;AACO,eAAe,kCAAkC,CAAC,UAAU,EAA2B;AAC9F,EAAE,MAAM,MAAM,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;AACvF,EAAE;AACF,IAAI,KAAK,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,GAAG,CAAC;AAClC;AACA,OAAO,KAAK,CAAC,CAAC,EAA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,IAAI,EAAkC;AAClG,cAAcC,8CAAwC,EAAE;;AAExD,cAAc,OAAOC,uBAAkB,CAAC,MAAM,kBAAkB;AAChE,gBAAgB,MAAM,MAAA,GAASC,QAAI,CAAC,EAAE,GAAG,OAAO,EAAE,YAAY,EAAE,KAAA,EAAO,CAAC;AACxE,gBAAgB,cAAc,CAAC,SAAS,CAAC,MAAM,CAAC;;AAEhD,gBAAgBC,kCAAuB,CAAC,cAAc,CAAC;;AAEvD,gBAAgB,OAAOC,cAAS,CAAC,MAAM,SAAS;AAChD,kBAAkB,MAAM,qBAAqB,MAAM,gCAAgC,CAAC,KAAK,CAAC,UAAU,CAAC;AACrG,kBAAkB,KAAK,CAAC,qBAAqB,CAAC,kBAAkB,CAAC;;AAEjE,kBAAkB,IAAI;AACtB,oBAAoB,OAAO,MAAM,GAAG,CAAC,GAAG,CAAC,IAAI;AAC7C,sBAAsB,GAAG;AACzB,sBAAsB,KAAK;AAC3B,sBAAsB,IAAI,mBAAmB,CAAC,KAAK,CAAC,UAAU,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC;AACvF,qBAAqB;AACrB,kBAAkB,UAAU;AAC5B,oBAAoB,OAAO,CAAC,SAAS,CAACC,qBAAe,CAAC,MAAM,CAAC,CAAC;AAC9D,kBAAkB;AAClB,gBAAgB,CAAC,CAAC;AAClB,cAAc,CAAC,CAAC;AAChB,YAAY,CAAC;AACb,UAAU;AACV,UAAU,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,QAAQ,CAAC;AACjD,QAAQ,CAAC;AACT,OAAO,CAAC;AACR,IAAI,CAAC;AACL,GAAG,CAAC;AACJ;;;;;"}
@@ -4,11 +4,13 @@ const core = require('@sentry/core');
4
4
  const flush = require('./flush.js');
5
5
  const instrument = require('./instrument.js');
6
6
  const sdk = require('./sdk.js');
7
+ const traceLinks = require('./utils/traceLinks.js');
7
8
 
8
9
  /** Extended DurableObjectState with originalStorage exposed by instrumentContext */
9
10
 
10
11
  /**
11
- * Wraps a method with Sentry tracing.
12
+ * Wraps a method with Sentry error tracking and optional tracing.
13
+ * Supports starting new traces and linking to previous invocations via Durable Object storage.
12
14
  *
13
15
  * @param wrapperOptions - The options for the wrapper.
14
16
  * @param handler - The method to wrap.
@@ -22,128 +24,171 @@ function wrapMethodWithSentry(
22
24
  callback,
23
25
  noMark,
24
26
  ) {
25
- if (instrument.isInstrumented(handler)) {
26
- return handler;
27
- }
28
-
29
- if (!noMark) {
30
- instrument.markAsInstrumented(handler);
31
- }
32
-
33
- return new Proxy(handler, {
34
- apply(target, thisArg, args) {
35
- const currentClient = core.getClient();
36
- // if a client is already set, use withScope, otherwise use withIsolationScope
37
- const sentryWithScope = currentClient ? core.withScope : core.withIsolationScope;
38
-
39
- const wrappedFunction = (scope) => {
40
- // In certain situations, the passed context can become undefined.
41
- // For example, for Astro while prerendering pages at build time.
42
- // see: https://github.com/getsentry/sentry-javascript/issues/13217
43
- const context = wrapperOptions.context ;
44
-
45
- const waitUntil = context?.waitUntil?.bind?.(context);
46
-
47
- let currentClient = scope.getClient();
48
- // Check if client exists AND is still usable (transport not disposed)
49
- // This handles the case where a previous handler disposed the client
50
- // but the scope still holds a reference to it (e.g., alarm handlers in Durable Objects)
51
- if (!currentClient?.getTransport()) {
52
- const client = sdk.init({ ...wrapperOptions.options, ctx: context });
53
- scope.setClient(client);
54
- currentClient = client;
55
- }
56
-
57
- const clientToDispose = currentClient;
58
-
59
- if (!wrapperOptions.spanName) {
60
- try {
61
- if (callback) {
62
- callback(...args);
27
+ return instrument.ensureInstrumented(
28
+ handler,
29
+ original =>
30
+ new Proxy(original, {
31
+ apply(target, thisArg, args) {
32
+ const { startNewTrace } = wrapperOptions;
33
+
34
+ // For startNewTrace, always use withIsolationScope to ensure a fresh scope
35
+ // Otherwise, use existing client's scope or isolation scope
36
+ const currentClient = core.getClient();
37
+ const sentryWithScope = startNewTrace ? core.withIsolationScope : currentClient ? core.withScope : core.withIsolationScope;
38
+
39
+ const wrappedFunction = (scope) => {
40
+ // In certain situations, the passed context can become undefined.
41
+ // For example, for Astro while prerendering pages at build time.
42
+ // see: https://github.com/getsentry/sentry-javascript/issues/13217
43
+ const context = wrapperOptions.context;
44
+
45
+ const waitUntil = context?.waitUntil?.bind?.(context);
46
+ const storage = context && 'originalStorage' in context ? context.originalStorage : undefined;
47
+
48
+ let scopeClient = scope.getClient();
49
+ // Check if client exists AND is still usable (transport not disposed)
50
+ // This handles the case where a previous handler disposed the client
51
+ // but the scope still holds a reference to it (e.g., alarm handlers in Durable Objects)
52
+ // For startNewTrace, always create a fresh client
53
+ if (startNewTrace || !scopeClient?.getTransport()) {
54
+ const client = sdk.init({
55
+ ...wrapperOptions.options,
56
+ ctx: context ,
57
+ });
58
+ scope.setClient(client);
59
+ scopeClient = client;
63
60
  }
64
- const result = Reflect.apply(target, thisArg, args);
65
-
66
- if (core.isThenable(result)) {
67
- return result.then(
68
- (res) => {
69
- waitUntil?.(flush.flushAndDispose(clientToDispose));
70
- return res;
71
- },
72
- (e) => {
73
- core.captureException(e, {
74
- mechanism: {
75
- type: 'auto.faas.cloudflare.durable_object',
76
- handled: false,
61
+
62
+ const clientToDispose = scopeClient;
63
+ const methodName = wrapperOptions.spanName || 'unknown';
64
+
65
+ const teardown = async () => {
66
+ if (startNewTrace && storage) {
67
+ await traceLinks.storeSpanContext(storage, methodName);
68
+ }
69
+ await flush.flushAndDispose(clientToDispose);
70
+ };
71
+
72
+ if (!wrapperOptions.spanName) {
73
+ try {
74
+ if (callback) {
75
+ callback(...args);
76
+ }
77
+
78
+ const result = Reflect.apply(target, thisArg, args);
79
+
80
+ if (core.isThenable(result)) {
81
+ return result.then(
82
+ (res) => {
83
+ waitUntil?.(teardown());
84
+ return res;
77
85
  },
78
- });
79
- waitUntil?.(flush.flushAndDispose(clientToDispose));
80
- throw e;
81
- },
82
- );
83
- } else {
84
- waitUntil?.(flush.flushAndDispose(clientToDispose));
85
- return result;
86
- }
87
- } catch (e) {
88
- core.captureException(e, {
89
- mechanism: {
90
- type: 'auto.faas.cloudflare.durable_object',
91
- handled: false,
92
- },
93
- });
94
- waitUntil?.(flush.flushAndDispose(clientToDispose));
95
- throw e;
96
- }
97
- }
98
-
99
- const attributes = wrapperOptions.spanOp
100
- ? {
101
- [core.SEMANTIC_ATTRIBUTE_SENTRY_OP]: wrapperOptions.spanOp,
102
- [core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.durable_object',
86
+ (e) => {
87
+ core.captureException(e, {
88
+ mechanism: {
89
+ type: 'auto.faas.cloudflare.durable_object',
90
+ handled: false,
91
+ },
92
+ });
93
+ waitUntil?.(teardown());
94
+ throw e;
95
+ },
96
+ );
97
+ } else {
98
+ waitUntil?.(teardown());
99
+ return result;
100
+ }
101
+ } catch (e) {
102
+ core.captureException(e, {
103
+ mechanism: {
104
+ type: 'auto.faas.cloudflare.durable_object',
105
+ handled: false,
106
+ },
107
+ });
108
+ waitUntil?.(teardown());
109
+ throw e;
110
+ }
103
111
  }
104
- : {};
105
-
106
- return core.startSpan({ name: wrapperOptions.spanName, attributes }, () => {
107
- try {
108
- const result = Reflect.apply(target, thisArg, args);
109
-
110
- if (core.isThenable(result)) {
111
- return result.then(
112
- (res) => {
113
- waitUntil?.(flush.flushAndDispose(clientToDispose));
114
- return res;
115
- },
116
- (e) => {
112
+
113
+ const attributes = wrapperOptions.spanOp
114
+ ? {
115
+ [core.SEMANTIC_ATTRIBUTE_SENTRY_OP]: wrapperOptions.spanOp,
116
+ [core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.durable_object',
117
+ }
118
+ : {};
119
+
120
+ const executeSpan = () => {
121
+ return core.startSpan({ name: methodName, attributes }, span => {
122
+ // When linking to previous trace, fetch the stored context and add links asynchronously
123
+ // This avoids blocking the response while fetching from storage
124
+ if (startNewTrace && storage) {
125
+ waitUntil?.(
126
+ traceLinks.getStoredSpanContext(storage, methodName).then(storedContext => {
127
+ if (storedContext) {
128
+ span.addLinks(traceLinks.buildSpanLinks(storedContext));
129
+ // TODO: Remove this once EAP can store span links. We currently only set this attribute so that we
130
+ // can obtain the previous trace information from the EAP store. Long-term, EAP will handle
131
+ // span links and then we should remove this again. Also throwing in a TODO(v11), to remind us
132
+ // to check this at v11 time :)
133
+ const sampledFlag = storedContext.sampled ? '1' : '0';
134
+ span.setAttribute(
135
+ 'sentry.previous_trace',
136
+ `${storedContext.traceId}-${storedContext.spanId}-${sampledFlag}`,
137
+ );
138
+ }
139
+ }),
140
+ );
141
+ }
142
+
143
+ try {
144
+ const result = Reflect.apply(target, thisArg, args);
145
+
146
+ if (core.isThenable(result)) {
147
+ return result.then(
148
+ (res) => {
149
+ waitUntil?.(teardown());
150
+ return res;
151
+ },
152
+ (e) => {
153
+ core.captureException(e, {
154
+ mechanism: {
155
+ type: 'auto.faas.cloudflare.durable_object',
156
+ handled: false,
157
+ },
158
+ });
159
+ waitUntil?.(teardown());
160
+ throw e;
161
+ },
162
+ );
163
+ } else {
164
+ waitUntil?.(teardown());
165
+ return result;
166
+ }
167
+ } catch (e) {
117
168
  core.captureException(e, {
118
169
  mechanism: {
119
170
  type: 'auto.faas.cloudflare.durable_object',
120
171
  handled: false,
121
172
  },
122
173
  });
123
- waitUntil?.(flush.flushAndDispose(clientToDispose));
174
+ waitUntil?.(teardown());
124
175
  throw e;
125
- },
126
- );
127
- } else {
128
- waitUntil?.(flush.flushAndDispose(clientToDispose));
129
- return result;
176
+ }
177
+ });
178
+ };
179
+
180
+ if (startNewTrace) {
181
+ return core.startNewTrace(() => executeSpan());
130
182
  }
131
- } catch (e) {
132
- core.captureException(e, {
133
- mechanism: {
134
- type: 'auto.faas.cloudflare.durable_object',
135
- handled: false,
136
- },
137
- });
138
- waitUntil?.(flush.flushAndDispose(clientToDispose));
139
- throw e;
140
- }
141
- });
142
- };
143
-
144
- return sentryWithScope(wrappedFunction);
145
- },
146
- });
183
+
184
+ return executeSpan();
185
+ };
186
+
187
+ return sentryWithScope(wrappedFunction);
188
+ },
189
+ }),
190
+ noMark,
191
+ );
147
192
  }
148
193
 
149
194
  exports.wrapMethodWithSentry = wrapMethodWithSentry;
@@ -1 +1 @@
1
- {"version":3,"file":"wrapMethodWithSentry.js","sources":["../../src/wrapMethodWithSentry.ts"],"sourcesContent":["import type { DurableObjectStorage } from '@cloudflare/workers-types';\nimport {\n captureException,\n getClient,\n isThenable,\n type Scope,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n startSpan,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type { CloudflareOptions } from './client';\nimport { flushAndDispose } from './flush';\nimport { isInstrumented, markAsInstrumented } from './instrument';\nimport { init } from './sdk';\n\n/** Extended DurableObjectState with originalStorage exposed by instrumentContext */\ninterface InstrumentedDurableObjectState extends DurableObjectState {\n originalStorage?: DurableObjectStorage;\n}\n\ntype MethodWrapperOptions = {\n spanName?: string;\n spanOp?: string;\n options: CloudflareOptions;\n context: ExecutionContext | DurableObjectState;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type UncheckedMethod = (...args: any[]) => any;\ntype OriginalMethod = UncheckedMethod;\n\n/**\n * Wraps a method with Sentry tracing.\n *\n * @param wrapperOptions - The options for the wrapper.\n * @param handler - The method to wrap.\n * @param callback - The callback to call.\n * @param noMark - Whether to mark the method as instrumented.\n * @returns The wrapped method.\n */\nexport function wrapMethodWithSentry<T extends OriginalMethod>(\n wrapperOptions: MethodWrapperOptions,\n handler: T,\n callback?: (...args: Parameters<T>) => void,\n noMark?: true,\n): T {\n if (isInstrumented(handler)) {\n return handler;\n }\n\n if (!noMark) {\n markAsInstrumented(handler);\n }\n\n return new Proxy(handler, {\n apply(target, thisArg, args: Parameters<T>) {\n const currentClient = getClient();\n // if a client is already set, use withScope, otherwise use withIsolationScope\n const sentryWithScope = currentClient ? withScope : withIsolationScope;\n\n const wrappedFunction = (scope: Scope): unknown => {\n // In certain situations, the passed context can become undefined.\n // For example, for Astro while prerendering pages at build time.\n // see: https://github.com/getsentry/sentry-javascript/issues/13217\n const context = wrapperOptions.context as InstrumentedDurableObjectState | undefined;\n\n const waitUntil = context?.waitUntil?.bind?.(context);\n\n let currentClient = scope.getClient();\n // Check if client exists AND is still usable (transport not disposed)\n // This handles the case where a previous handler disposed the client\n // but the scope still holds a reference to it (e.g., alarm handlers in Durable Objects)\n if (!currentClient?.getTransport()) {\n const client = init({ ...wrapperOptions.options, ctx: context as unknown as ExecutionContext | undefined });\n scope.setClient(client);\n currentClient = client;\n }\n\n const clientToDispose = currentClient;\n\n if (!wrapperOptions.spanName) {\n try {\n if (callback) {\n callback(...args);\n }\n const result = Reflect.apply(target, thisArg, args);\n\n if (isThenable(result)) {\n return result.then(\n (res: unknown) => {\n waitUntil?.(flushAndDispose(clientToDispose));\n return res;\n },\n (e: unknown) => {\n captureException(e, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object',\n handled: false,\n },\n });\n waitUntil?.(flushAndDispose(clientToDispose));\n throw e;\n },\n );\n } else {\n waitUntil?.(flushAndDispose(clientToDispose));\n return result;\n }\n } catch (e) {\n captureException(e, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object',\n handled: false,\n },\n });\n waitUntil?.(flushAndDispose(clientToDispose));\n throw e;\n }\n }\n\n const attributes = wrapperOptions.spanOp\n ? {\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: wrapperOptions.spanOp,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.durable_object',\n }\n : {};\n\n return startSpan({ name: wrapperOptions.spanName, attributes }, () => {\n try {\n const result = Reflect.apply(target, thisArg, args);\n\n if (isThenable(result)) {\n return result.then(\n (res: unknown) => {\n waitUntil?.(flushAndDispose(clientToDispose));\n return res;\n },\n (e: unknown) => {\n captureException(e, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object',\n handled: false,\n },\n });\n waitUntil?.(flushAndDispose(clientToDispose));\n throw e;\n },\n );\n } else {\n waitUntil?.(flushAndDispose(clientToDispose));\n return result;\n }\n } catch (e) {\n captureException(e, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object',\n handled: false,\n },\n });\n waitUntil?.(flushAndDispose(clientToDispose));\n throw e;\n }\n });\n };\n\n return sentryWithScope(wrappedFunction);\n },\n });\n}\n"],"names":["isInstrumented","markAsInstrumented","getClient","withScope","withIsolationScope","init","isThenable","flushAndDispose","captureException","SEMANTIC_ATTRIBUTE_SENTRY_OP","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","startSpan"],"mappings":";;;;;;;AAiBA;;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,oBAAoB;AACpC,EAAE,cAAc;AAChB,EAAE,OAAO;AACT,EAAE,QAAQ;AACV,EAAE,MAAM;AACR,EAAK;AACL,EAAE,IAAIA,yBAAc,CAAC,OAAO,CAAC,EAAE;AAC/B,IAAI,OAAO,OAAO;AAClB,EAAE;;AAEF,EAAE,IAAI,CAAC,MAAM,EAAE;AACf,IAAIC,6BAAkB,CAAC,OAAO,CAAC;AAC/B,EAAE;;AAEF,EAAE,OAAO,IAAI,KAAK,CAAC,OAAO,EAAE;AAC5B,IAAI,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,EAAiB;AAChD,MAAM,MAAM,aAAA,GAAgBC,cAAS,EAAE;AACvC;AACA,MAAM,MAAM,eAAA,GAAkB,gBAAgBC,cAAA,GAAYC,uBAAkB;;AAE5E,MAAM,MAAM,eAAA,GAAkB,CAAC,KAAK,KAAqB;AACzD;AACA;AACA;AACA,QAAQ,MAAM,OAAA,GAAU,cAAc,CAAC,OAAA;;AAEvC,QAAQ,MAAM,SAAA,GAAY,OAAO,EAAE,SAAS,EAAE,IAAI,GAAG,OAAO,CAAC;;AAE7D,QAAQ,IAAI,aAAA,GAAgB,KAAK,CAAC,SAAS,EAAE;AAC7C;AACA;AACA;AAC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AACnB,cAAc,SAAS,GAAGA,qBAAe,CAAC,eAAe,CAAC,CAAC;AAC3D,cAAc,OAAO,MAAM;AAC3B,YAAY;AACZ,UAAU,CAAA,CAAE,OAAO,CAAC,EAAE;AACtB,YAAYC,qBAAgB,CAAC,CAAC,EAAE;AAChC,cAAc,SAAS,EAAE;AACzB,gBAAgB,IAAI,EAAE,qCAAqC;AAC3D,gBAAgB,OAAO,EAAE,KAAK;AAC9B,eAAe;AACf,aAAa,CAAC;AACd,YAAY,SAAS,GAAGD,qBAAe,CAAC,eAAe,CAAC,CAAC;AACzD,YAAY,MAAM,CAAC;AACnB,UAAU;AACV,QAAQ,CAAC,CAAC;AACV,MAAM,CAAC;;AAEP,MAAM,OAAO,eAAe,CAAC,eAAe,CAAC;AAC7C,IAAI,CAAC;AACL,GAAG,CAAC;AACJ;;;;"}
1
+ {"version":3,"file":"wrapMethodWithSentry.js","sources":["../../src/wrapMethodWithSentry.ts"],"sourcesContent":["import type { DurableObjectStorage } from '@cloudflare/workers-types';\nimport {\n captureException,\n getClient,\n isThenable,\n type Scope,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n startNewTrace as startNewTraceCore,\n startSpan,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type { CloudflareOptions } from './client';\nimport { flushAndDispose } from './flush';\nimport { ensureInstrumented } from './instrument';\nimport { init } from './sdk';\nimport { buildSpanLinks, getStoredSpanContext, storeSpanContext } from './utils/traceLinks';\n\n/** Extended DurableObjectState with originalStorage exposed by instrumentContext */\ninterface InstrumentedDurableObjectState extends DurableObjectState {\n originalStorage?: DurableObjectStorage;\n}\n\ntype MethodWrapperOptions = {\n spanName?: string;\n spanOp?: string;\n options: CloudflareOptions;\n context: ExecutionContext | InstrumentedDurableObjectState;\n /**\n * If true, starts a fresh trace instead of inheriting from a parent trace.\n * Useful for scheduled/independent invocations like alarms.\n *\n * If true, it also stores the current span context and links to the previous invocation's span.\n * Uses Durable Object storage to persist the link. The link is set asynchronously via `span.addLinks()`\n * in a `waitUntil` to avoid blocking.\n *\n * @default false\n */\n startNewTrace?: boolean;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type UncheckedMethod = (...args: any[]) => any;\ntype OriginalMethod = UncheckedMethod;\n\n/**\n * Wraps a method with Sentry error tracking and optional tracing.\n * Supports starting new traces and linking to previous invocations via Durable Object storage.\n *\n * @param wrapperOptions - The options for the wrapper.\n * @param handler - The method to wrap.\n * @param callback - The callback to call.\n * @param noMark - Whether to mark the method as instrumented.\n * @returns The wrapped method.\n */\nexport function wrapMethodWithSentry<T extends OriginalMethod>(\n wrapperOptions: MethodWrapperOptions,\n handler: T,\n callback?: (...args: Parameters<T>) => void,\n noMark?: true,\n): T {\n return ensureInstrumented(\n handler,\n original =>\n new Proxy(original, {\n apply(target, thisArg, args: Parameters<T>) {\n const { startNewTrace } = wrapperOptions;\n\n // For startNewTrace, always use withIsolationScope to ensure a fresh scope\n // Otherwise, use existing client's scope or isolation scope\n const currentClient = getClient();\n const sentryWithScope = startNewTrace ? withIsolationScope : currentClient ? withScope : withIsolationScope;\n\n const wrappedFunction = (scope: Scope): unknown | Promise<unknown> => {\n // In certain situations, the passed context can become undefined.\n // For example, for Astro while prerendering pages at build time.\n // see: https://github.com/getsentry/sentry-javascript/issues/13217\n const context: typeof wrapperOptions.context | undefined = wrapperOptions.context;\n\n const waitUntil = context?.waitUntil?.bind?.(context);\n const storage = context && 'originalStorage' in context ? context.originalStorage : undefined;\n\n let scopeClient = scope.getClient();\n // Check if client exists AND is still usable (transport not disposed)\n // This handles the case where a previous handler disposed the client\n // but the scope still holds a reference to it (e.g., alarm handlers in Durable Objects)\n // For startNewTrace, always create a fresh client\n if (startNewTrace || !scopeClient?.getTransport()) {\n const client = init({\n ...wrapperOptions.options,\n ctx: context as unknown as ExecutionContext | undefined,\n });\n scope.setClient(client);\n scopeClient = client;\n }\n\n const clientToDispose = scopeClient;\n const methodName = wrapperOptions.spanName || 'unknown';\n\n const teardown = async (): Promise<void> => {\n if (startNewTrace && storage) {\n await storeSpanContext(storage, methodName);\n }\n await flushAndDispose(clientToDispose);\n };\n\n if (!wrapperOptions.spanName) {\n try {\n if (callback) {\n callback(...args);\n }\n\n const result = Reflect.apply(target, thisArg, args);\n\n if (isThenable(result)) {\n return result.then(\n (res: unknown) => {\n waitUntil?.(teardown());\n return res;\n },\n (e: unknown) => {\n captureException(e, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object',\n handled: false,\n },\n });\n waitUntil?.(teardown());\n throw e;\n },\n );\n } else {\n waitUntil?.(teardown());\n return result;\n }\n } catch (e) {\n captureException(e, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object',\n handled: false,\n },\n });\n waitUntil?.(teardown());\n throw e;\n }\n }\n\n const attributes = wrapperOptions.spanOp\n ? {\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: wrapperOptions.spanOp,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.durable_object',\n }\n : {};\n\n const executeSpan = (): unknown => {\n return startSpan({ name: methodName, attributes }, span => {\n // When linking to previous trace, fetch the stored context and add links asynchronously\n // This avoids blocking the response while fetching from storage\n if (startNewTrace && storage) {\n waitUntil?.(\n getStoredSpanContext(storage, methodName).then(storedContext => {\n if (storedContext) {\n span.addLinks(buildSpanLinks(storedContext));\n // TODO: Remove this once EAP can store span links. We currently only set this attribute so that we\n // can obtain the previous trace information from the EAP store. Long-term, EAP will handle\n // span links and then we should remove this again. Also throwing in a TODO(v11), to remind us\n // to check this at v11 time :)\n const sampledFlag = storedContext.sampled ? '1' : '0';\n span.setAttribute(\n 'sentry.previous_trace',\n `${storedContext.traceId}-${storedContext.spanId}-${sampledFlag}`,\n );\n }\n }),\n );\n }\n\n try {\n const result = Reflect.apply(target, thisArg, args);\n\n if (isThenable(result)) {\n return result.then(\n (res: unknown) => {\n waitUntil?.(teardown());\n return res;\n },\n (e: unknown) => {\n captureException(e, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object',\n handled: false,\n },\n });\n waitUntil?.(teardown());\n throw e;\n },\n );\n } else {\n waitUntil?.(teardown());\n return result;\n }\n } catch (e) {\n captureException(e, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object',\n handled: false,\n },\n });\n waitUntil?.(teardown());\n throw e;\n }\n });\n };\n\n if (startNewTrace) {\n return startNewTraceCore(() => executeSpan());\n }\n\n return executeSpan();\n };\n\n return sentryWithScope(wrappedFunction);\n },\n }),\n noMark,\n );\n}\n"],"names":["ensureInstrumented","getClient","withIsolationScope","withScope","init","storeSpanContext","flushAndDispose","isThenable","captureException","SEMANTIC_ATTRIBUTE_SENTRY_OP","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","startSpan","getStoredSpanContext","buildSpanLinks","startNewTraceCore"],"mappings":";;;;;;;;AAmBA;;AA2BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,oBAAoB;AACpC,EAAE,cAAc;AAChB,EAAE,OAAO;AACT,EAAE,QAAQ;AACV,EAAE,MAAM;AACR,EAAK;AACL,EAAE,OAAOA,6BAAkB;AAC3B,IAAI,OAAO;AACX,IAAI,QAAA;AACJ,MAAM,IAAI,KAAK,CAAC,QAAQ,EAAE;AAC1B,QAAQ,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,EAAiB;AACpD,UAAU,MAAM,EAAE,aAAA,EAAc,GAAI,cAAc;;AAElD;AACA;AACA,UAAU,MAAM,aAAA,GAAgBC,cAAS,EAAE;AAC3C,UAAU,MAAM,eAAA,GAAkB,aAAA,GAAgBC,uBAAA,GAAqB,aAAA,GAAgBC,cAAA,GAAYD,uBAAkB;;AAErH,UAAU,MAAM,eAAA,GAAkB,CAAC,KAAK,KAAwC;AAChF;AACA;AACA;AACA,YAAY,MAAM,OAAO,GAA8C,cAAc,CAAC,OAAO;;AAE7F,YAAY,MAAM,SAAA,GA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,EAAA;AACA,kBAAAA,qBAAA,CAAA,CAAA,EAAA;AACA,oBAAA,SAAA,EAAA;AACA,sBAAA,IAAA,EAAA,qCAAA;AACA,sBAAA,OAAA,EAAA,KAAA;AACA,qBAAA;AACA,mBAAA,CAAA;AACA,kBAAA,SAAA,GAAA,QAAA,EAAA,CAAA;AACA,kBAAA,MAAA,CAAA;AACA,gBAAA;AACA,cAAA,CAAA,CAAA;AACA,YAAA,CAAA;;AAEA,YAAA,IAAA,aAAA,EAAA;AACA,cAAA,OAAAM,kBAAA,CAAA,MAAA,WAAA,EAAA,CAAA;AACA,YAAA;;AAEA,YAAA,OAAA,WAAA,EAAA;AACA,UAAA,CAAA;;AAEA,UAAA,OAAA,eAAA,CAAA,eAAA,CAAA;AACA,QAAA,CAAA;AACA,OAAA,CAAA;AACA,IAAA,MAAA;AACA,GAAA;AACA;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sources":["../../src/client.ts"],"sourcesContent":["import type { ClientOptions, Options, ServerRuntimeClientOptions } from '@sentry/core';\nimport { applySdkMetadata, debug, ServerRuntimeClient } from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { makeFlushLock } from './flush';\nimport type { CloudflareTransportOptions } from './transport';\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 /**\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 };\n\n super(clientOptions);\n this._flushLock = flushLock;\n\n // Track span lifecycle to know when to flush\n this._unsubscribeSpanStart = this.on('spanStart', span => {\n const spanId = span.spanContext().spanId;\n DEBUG_BUILD && debug.log('[CloudflareClient] Span started:', spanId);\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, resolving promise');\n this._resolveSpanCompletion();\n this._resetSpanCompletionPromise();\n }\n });\n }\n\n /**\n * Flushes pending operations and ensures all data is processed.\n * If a timeout is provided, the operation will be completed within the specified time limit.\n *\n * It will wait for all pending spans to complete before flushing.\n *\n * @param {number} [timeout] - Optional timeout in milliseconds to force the completion of the flush operation.\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 if (this._flushLock) {\n await this._flushLock.finalize();\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 return super.flush(timeout);\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 /**\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\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 * The Cloudflare SDK is not OpenTelemetry native, however, we set up some OpenTelemetry compatibility\n * via a custom trace provider.\n * This ensures that any spans emitted via `@opentelemetry/api` will be captured by Sentry.\n * HOWEVER, big caveat: This does not handle custom context handling, it will always work off the current scope.\n * This should be good enough for many, but not all integrations.\n *\n * If you want to opt-out of setting up the OpenTelemetry compatibility tracer, set this to `true`.\n *\n * @default false\n */\n skipOpenTelemetrySetup?: boolean;\n\n /**\n * Enable instrumentation of prototype methods for DurableObjects.\n *\n * When `true`, the SDK will wrap all methods on the DurableObject prototype chain\n * to automatically create spans and capture errors for RPC method calls.\n *\n * When an array of strings is provided, only the specified method names will be instrumented.\n *\n * This feature adds runtime overhead as it wraps methods at the prototype level.\n * Only enable this if you need automatic instrumentation of prototype methods.\n *\n * @default false\n * @example\n * ```ts\n * // Instrument all prototype methods\n * instrumentPrototypeMethods: true\n *\n * // Instrument only specific methods\n * instrumentPrototypeMethods: ['myMethod', 'anotherMethod']\n * ```\n */\n instrumentPrototypeMethods?: boolean | string[];\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?: ExecutionContext;\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":[],"mappings":";;;AAMA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,gBAAA,SAAyB,mBAAA,CAAoB;;AAE1D,kBAAU,aAAa,GAAgB,IAAI,GAAG,GAAC;AAC/C,GAAE,OAAA,GAAA,CAAA,IAAA,CAAQ,sBAAsB,GAAyB,KAAA;AACzD,GAAE,OAAA,GAAA,CAAA,IAAA,CAAQ,sBAAsB,GAAwB,KAAA;;AAExD,GAAE,OAAA,GAAA,CAAA,IAAA,CAAQ,qBAAqB,GAAwB,KAAA;AACvD,GAAE,OAAA,GAAA,CAAA,IAAA,CAAQ,mBAAmB,GAAwB,KAAA;;AAErD;AACA;AACA;AACA;AACA,GAAS,WAAW,CAAC,OAAO,EAA2B;AACvD,IAAI,gBAAgB,CAAC,OAAO,EAAE,YAAY,CAAC;AAC3C,IAAI,OAAO,CAAC,SAAA,GAAY,OAAO,CAAC,SAAA,IAAa,EAAE;AAC/C,IAAI,MAAM,EAAE,SAAS,EAAE,GAAG,aAAA,EAAc,GAAI,OAAO;;AAEnD,IAAI,MAAM,aAAa,GAA+B;AACtD,MAAM,GAAG,aAAa;AACtB,MAAM,QAAQ,EAAE,YAAY;AAC5B;AACA,MAAM,OAAO,EAAE,EAAE,IAAI,EAAE,cAAc;AACrC;A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;AACA;AACA;AACA;AACA;AACA;AACA,IAAkB,OAAO,GAAS;AAClC,IAAI,eAAe,KAAK,CAAC,GAAG,CAAC,wCAAwC,CAAC;;AAEtE,IAAI,KAAK,CAAC,OAAO,EAAE;;AAEnB,IAAI,IAAI,IAAI,CAAC,qBAAqB,EAAE;AACpC,MAAM,IAAI,CAAC,qBAAqB,EAAE;AAClC,MAAM,IAAI,CAAC,qBAAA,GAAwB,IAAI;AACvC,IAAI;AACJ,IAAI,IAAI,IAAI,CAAC,mBAAmB,EAAE;AAClC,MAAM,IAAI,CAAC,mBAAmB,EAAE;AAChC,MAAM,IAAI,CAAC,mBAAA,GAAsB,IAAI;AACrC,IAAI;;AAEJ,IAAI,IAAI,CAAC,2BAA2B,EAAE;AACtC,IAAI,CAAC,IAAA,GAA4E,UAAA,GAAa,SAAS;AACvG,EAAE;;AAEF;AACA;AACA;AACA,GAAU,2BAA2B,GAAS;AAC9C,IAAI,IAAI,CAAC,aAAa,CAAC,KAAK,EAAE;AAC9B,IAAI,IAAI,CAAC,sBAAA,GAAyB,IAAI;AACtC,IAAI,IAAI,CAAC,sBAAA,GAAyB,IAAI;AACtC,EAAE;AACF;;;;"}
1
+ {"version":3,"file":"client.js","sources":["../../src/client.ts"],"sourcesContent":["import type { ClientOptions, Options, ServerRuntimeClientOptions } from '@sentry/core';\nimport { applySdkMetadata, debug, ServerRuntimeClient } from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { makeFlushLock } from './flush';\nimport type { CloudflareTransportOptions } from './transport';\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 /**\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 };\n\n super(clientOptions);\n this._flushLock = flushLock;\n\n // Track span lifecycle to know when to flush\n this._unsubscribeSpanStart = this.on('spanStart', span => {\n const spanId = span.spanContext().spanId;\n DEBUG_BUILD && debug.log('[CloudflareClient] Span started:', spanId);\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, resolving promise');\n this._resolveSpanCompletion();\n this._resetSpanCompletionPromise();\n }\n });\n }\n\n /**\n * Flushes pending operations and ensures all data is processed.\n * If a timeout is provided, the operation will be completed within the specified time limit.\n *\n * It will wait for all pending spans to complete before flushing.\n *\n * @param {number} [timeout] - Optional timeout in milliseconds to force the completion of the flush operation.\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 if (this._flushLock) {\n await this._flushLock.finalize();\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 return super.flush(timeout);\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 /**\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\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 * The Cloudflare SDK is not OpenTelemetry native, however, we set up some OpenTelemetry compatibility\n * via a custom trace provider.\n * This ensures that any spans emitted via `@opentelemetry/api` will be captured by Sentry.\n * HOWEVER, big caveat: This does not handle custom context handling, it will always work off the current scope.\n * This should be good enough for many, but not all integrations.\n *\n * If you want to opt-out of setting up the OpenTelemetry compatibility tracer, set this to `true`.\n *\n * @default false\n */\n skipOpenTelemetrySetup?: boolean;\n\n /**\n * Enable trace propagation for RPC calls between Workers, Durable Objects, and Service Bindings.\n *\n * When enabled, trace context (sentry-trace + baggage) is propagated across:\n * - `stub.fetch()` calls to Durable Objects (via HTTP headers)\n * - Service binding `fetch()` calls (via HTTP headers)\n * - RPC method calls to Durable Objects (via trailing argument)\n *\n * When enabled on the **receiver side** (DurableObject), the SDK will also:\n * - Extract and continue traces from incoming RPC calls\n * - Create spans for each RPC method invocation\n * - Capture errors thrown by RPC methods\n *\n * **Important:** This option should be enabled on **both sides** for full trace propagation.\n *\n * @default false\n * @example\n * ```ts\n * // Worker side (caller)\n * export default Sentry.withSentry(\n * (env) => ({\n * dsn: env.SENTRY_DSN,\n * enableRpcTracePropagation: true,\n * }),\n * handler,\n * );\n *\n * // Durable Object side (receiver)\n * export const MyDO = Sentry.instrumentDurableObjectWithSentry(\n * (env) => ({\n * dsn: env.SENTRY_DSN,\n * enableRpcTracePropagation: true,\n * }),\n * MyDOBase,\n * );\n * ```\n */\n enableRpcTracePropagation?: boolean;\n\n /**\n * @deprecated Use `enableRpcTracePropagation` instead. This option will be removed in a future major version.\n *\n * Enable instrumentation of prototype methods for DurableObjects.\n *\n * When `true`, the SDK will wrap all methods on the DurableObject prototype chain\n * to automatically create spans and capture errors for RPC method calls.\n *\n * When an array of strings is provided, only the specified method names will be instrumented.\n *\n * @default false\n */\n instrumentPrototypeMethods?: boolean | string[];\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?: ExecutionContext;\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":[],"mappings":";;;AAMA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,gBAAA,SAAyB,mBAAA,CAAoB;;AAE1D,kBAAU,aAAa,GAAgB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BAA2B,GAAS;AAC9C,IAAI,IAAI,CAAC,aAAa,CAAC,KAAK,EAAE;AAC9B,IAAI,IAAI,CAAC,sBAAA,GAAyB,IAAI;AACtC,IAAI,IAAI,CAAC,sBAAA,GAAyB,IAAI;AACtC,EAAE;AACF;;;;"}
@@ -1,9 +1,11 @@
1
1
  import { captureException } from '@sentry/core';
2
2
  import { setAsyncLocalStorageAsyncContextStrategy } from './async.js';
3
- import { isInstrumented, markAsInstrumented } from './instrument.js';
3
+ import { ensureInstrumented, getInstrumented, markAsInstrumented } from './instrument.js';
4
+ import { instrumentEnv } from './instrumentations/worker/instrumentEnv.js';
4
5
  import { getFinalOptions } from './options.js';
5
6
  import { wrapRequestHandler } from './request.js';
6
7
  import { instrumentContext } from './utils/instrumentContext.js';
8
+ import { getPrototypeMethodFilter } from './utils/rpcOptions.js';
7
9
  import { wrapMethodWithSentry } from './wrapMethodWithSentry.js';
8
10
 
9
11
  /* eslint-disable @typescript-eslint/unbound-method */
@@ -48,10 +50,10 @@ function instrumentDurableObjectWithSentry
48
50
  construct(target, [ctx, env]) {
49
51
  setAsyncLocalStorageAsyncContextStrategy();
50
52
  const context = instrumentContext(ctx);
51
-
52
53
  const options = getFinalOptions(optionsCallback(env), env);
54
+ const instrumentedEnv = instrumentEnv(env, options);
53
55
 
54
- const obj = new target(context, env);
56
+ const obj = new target(context, instrumentedEnv);
55
57
 
56
58
  // These are the methods that are available on a Durable Object
57
59
  // ref: https://developers.cloudflare.com/durable-objects/api/base/
@@ -63,20 +65,26 @@ function instrumentDurableObjectWithSentry
63
65
 
64
66
  // Any other public methods on the Durable Object instance are RPC calls.
65
67
 
66
- if (obj.fetch && typeof obj.fetch === 'function' && !isInstrumented(obj.fetch)) {
67
- obj.fetch = new Proxy(obj.fetch, {
68
- apply(target, thisArg, args) {
69
- return wrapRequestHandler({ options, request: args[0], context }, () =>
70
- Reflect.apply(target, thisArg, args),
71
- );
72
- },
73
- });
74
-
75
- markAsInstrumented(obj.fetch);
68
+ if (obj.fetch && typeof obj.fetch === 'function') {
69
+ obj.fetch = ensureInstrumented(
70
+ obj.fetch,
71
+ original =>
72
+ new Proxy(original, {
73
+ apply(target, thisArg, args) {
74
+ return wrapRequestHandler({ options, request: args[0], context }, () => {
75
+ return Reflect.apply(target, thisArg, args);
76
+ });
77
+ },
78
+ }),
79
+ );
76
80
  }
77
81
 
78
82
  if (obj.alarm && typeof obj.alarm === 'function') {
79
- obj.alarm = wrapMethodWithSentry({ options, context, spanName: 'alarm' }, obj.alarm);
83
+ // Alarms are independent invocations, so we start a new trace and link to the previous alarm
84
+ obj.alarm = wrapMethodWithSentry(
85
+ { options, context, spanName: 'alarm', spanOp: 'function', startNewTrace: true },
86
+ obj.alarm,
87
+ );
80
88
  }
81
89
 
82
90
  if (obj.webSocketMessage && typeof obj.webSocketMessage === 'function') {
@@ -141,8 +149,10 @@ function instrumentDurableObjectWithSentry
141
149
  configurable: false,
142
150
  });
143
151
 
144
- if (options?.instrumentPrototypeMethods) {
145
- instrumentPrototype(target, options.instrumentPrototypeMethods);
152
+ const methodFilter = getPrototypeMethodFilter(options);
153
+
154
+ if (methodFilter) {
155
+ instrumentPrototype(target, methodFilter);
146
156
  }
147
157
 
148
158
  return obj;
@@ -173,7 +183,18 @@ function instrumentPrototype(target, methodsToInstrument) {
173
183
  methodNames.forEach(methodName => {
174
184
  const originalMethod = (proto )[methodName];
175
185
 
176
- if (!originalMethod || isInstrumented(originalMethod)) {
186
+ if (!originalMethod) {
187
+ return;
188
+ }
189
+
190
+ const existingInstrumented = getInstrumented(originalMethod);
191
+ if (existingInstrumented) {
192
+ Object.defineProperty(proto, methodName, {
193
+ value: existingInstrumented,
194
+ enumerable: false,
195
+ writable: true,
196
+ configurable: true,
197
+ });
177
198
  return;
178
199
  }
179
200
 
@@ -211,6 +232,11 @@ function instrumentPrototype(target, methodsToInstrument) {
211
232
  return wrapper.apply(this, args);
212
233
  };
213
234
 
235
+ // Only mark wrappedMethod as instrumented (not originalMethod → wrappedMethod).
236
+ // originalMethod must stay unmapped because wrappedMethod calls
237
+ // wrapMethodWithSentry(options, originalMethod) on each invocation to create
238
+ // a per-instance proxy. If originalMethod mapped to wrappedMethod, that call
239
+ // would return wrappedMethod itself, causing infinite recursion.
214
240
  markAsInstrumented(wrappedMethod);
215
241
 
216
242
  // Replace the prototype method