@sentry/cloudflare 10.64.0 → 10.66.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/build/cjs/client.js.map +1 -1
  2. package/build/cjs/durableobject.js +2 -2
  3. package/build/cjs/durableobject.js.map +1 -1
  4. package/build/cjs/flush.js.map +1 -1
  5. package/build/cjs/instrument.js +3 -1
  6. package/build/cjs/instrument.js.map +1 -1
  7. package/build/cjs/instrumentations/worker/instrumentEnv.js +2 -1
  8. package/build/cjs/instrumentations/worker/instrumentEnv.js.map +1 -1
  9. package/build/cjs/instrumentations/worker/instrumentQueueProducer.js.map +1 -1
  10. package/build/cjs/instrumentations/worker/instrumentR2.js +1 -1
  11. package/build/cjs/instrumentations/worker/instrumentR2.js.map +1 -1
  12. package/build/cjs/integrations/hono.js +1 -1
  13. package/build/cjs/integrations/hono.js.map +1 -1
  14. package/build/cjs/options.js +2 -2
  15. package/build/cjs/options.js.map +1 -1
  16. package/build/cjs/pages-plugin.js +2 -4
  17. package/build/cjs/pages-plugin.js.map +1 -1
  18. package/build/cjs/request.js.map +1 -1
  19. package/build/cjs/utils/rpcMeta.js +2 -3
  20. package/build/cjs/utils/rpcMeta.js.map +1 -1
  21. package/build/cjs/workflows.js +11 -5
  22. package/build/cjs/workflows.js.map +1 -1
  23. package/build/cjs/wrapMethodWithSentry.js +1 -1
  24. package/build/cjs/wrapMethodWithSentry.js.map +1 -1
  25. package/build/esm/client.js.map +1 -1
  26. package/build/esm/durableobject.js +2 -2
  27. package/build/esm/durableobject.js.map +1 -1
  28. package/build/esm/flush.js.map +1 -1
  29. package/build/esm/instrument.js +3 -1
  30. package/build/esm/instrument.js.map +1 -1
  31. package/build/esm/instrumentations/worker/instrumentEnv.js +2 -1
  32. package/build/esm/instrumentations/worker/instrumentEnv.js.map +1 -1
  33. package/build/esm/instrumentations/worker/instrumentQueueProducer.js.map +1 -1
  34. package/build/esm/instrumentations/worker/instrumentR2.js +2 -2
  35. package/build/esm/instrumentations/worker/instrumentR2.js.map +1 -1
  36. package/build/esm/integrations/hono.js +2 -2
  37. package/build/esm/integrations/hono.js.map +1 -1
  38. package/build/esm/options.js +3 -3
  39. package/build/esm/options.js.map +1 -1
  40. package/build/esm/package.json +1 -1
  41. package/build/esm/pages-plugin.js +2 -4
  42. package/build/esm/pages-plugin.js.map +1 -1
  43. package/build/esm/request.js.map +1 -1
  44. package/build/esm/utils/rpcMeta.js +3 -4
  45. package/build/esm/utils/rpcMeta.js.map +1 -1
  46. package/build/esm/workflows.js +11 -5
  47. package/build/esm/workflows.js.map +1 -1
  48. package/build/esm/wrapMethodWithSentry.js +2 -2
  49. package/build/esm/wrapMethodWithSentry.js.map +1 -1
  50. package/build/types/client.d.ts +2 -1
  51. package/build/types/client.d.ts.map +1 -1
  52. package/build/types/durableobject.d.ts.map +1 -1
  53. package/build/types/executionContext.d.ts +13 -0
  54. package/build/types/executionContext.d.ts.map +1 -0
  55. package/build/types/flush.d.ts +3 -2
  56. package/build/types/flush.d.ts.map +1 -1
  57. package/build/types/instrument.d.ts.map +1 -1
  58. package/build/types/instrumentations/worker/instrumentEnv.d.ts.map +1 -1
  59. package/build/types/integrations/hono.d.ts.map +1 -1
  60. package/build/types/pages-plugin.d.ts.map +1 -1
  61. package/build/types/request.d.ts +3 -2
  62. package/build/types/request.d.ts.map +1 -1
  63. package/build/types/utils/rpcMeta.d.ts.map +1 -1
  64. package/build/types/workflows.d.ts.map +1 -1
  65. package/build/types/wrapMethodWithSentry.d.ts.map +1 -1
  66. package/build/types-ts3.8/client.d.ts +2 -1
  67. package/build/types-ts3.8/executionContext.d.ts +13 -0
  68. package/build/types-ts3.8/flush.d.ts +3 -2
  69. package/build/types-ts3.8/request.d.ts +3 -2
  70. package/package.json +6 -6
  71. package/build/types/utils/addOriginToSpan.d.ts +0 -5
  72. package/build/types/utils/addOriginToSpan.d.ts.map +0 -1
  73. package/build/types-ts3.8/utils/addOriginToSpan.d.ts +0 -5
@@ -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, spanIsSampled } 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 _flushInterval: 0,\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\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, 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":["ServerRuntimeClient","applySdkMetadata","DEBUG_BUILD","debug","spanIsSampled"],"mappings":";;;;;AAYO,MAAM,yBAAyBA,wBAAA,CAAoB;AAAA;AAAA;AAAA;AAAA;AAAA,EAajD,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;AAEA,IAAA,KAAA,CAAM,aAAa,CAAA;AAzBrB,IAAA,IAAA,CAAQ,aAAA,uBAAiC,GAAA,EAAI;AAC7C,IAAA,IAAA,CAAQ,sBAAA,GAA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IAAA,CAAK,qBAAA,GAAwB,IAAA;AAAA,IAC/B;AACA,IAAA,IAAI,KAAK,mBAAA,EAAqB;AAC5B,MAAA,IAAA,CAAK,mBAAA,EAAoB;AACzB,MAAA,IAAA,CAAK,mBAAA,GAAsB,IAAA;AAAA,IAC7B;AAEA,IAAA,IAAA,CAAK,2BAAA,EAA4B;AACjC,IAAC,KAA4E,UAAA,GAAa,MAAA;AAAA,EAC5F;AAAA;AAAA;AAAA;AAAA,EAKQ,2BAAA,GAAoC;AAC1C,IAAA,IAAA,CAAK,cAAc,KAAA,EAAM;AACzB,IAAA,IAAA,CAAK,sBAAA,GAAyB,IAAA;AAC9B,IAAA,IAAA,CAAK,sBAAA,GAAyB,IAAA;AAAA,EAChC;AACF;;;;"}
1
+ {"version":3,"file":"client.js","sources":["../../src/client.ts"],"sourcesContent":["import type { ClientOptions, Options, ServerRuntimeClientOptions } from '@sentry/core';\nimport { applySdkMetadata, debug, ServerRuntimeClient, spanIsSampled } from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { ExecutionContextCompat } from './executionContext';\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 _flushInterval: 0,\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\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, 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?: ExecutionContextCompat;\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","DEBUG_BUILD","debug","spanIsSampled"],"mappings":";;;;;AAaO,MAAM,yBAAyBA,wBAAA,CAAoB;AAAA;AAAA;AAAA;AAAA;AAAA,EAajD,YAAY,OAAA,EAAkC;AACnD,IAAAC,q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AAoD,SAAA,EAAW,qBAAqB,CAAA;AAChG,YAAA,OAAA,CAAQ,MAAS,CAAA;AAAA,UACnB,GAAG,SAAS;AAAA;AACd,OACD,CAAA;AAED,MAAA,MAAM,kBAAA;AAAA,IACR;AAEA,IAAA,OAAO,KAAA,CAAM,MAAM,OAAO,CAAA;AAAA,EAC5B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWgB,OAAA,GAAgB;AAC9B,IAAAD,sBAAA,IAAeC,UAAA,CAAM,IAAI,wCAAwC,CAAA;AAEjE,IAAA,KAAA,CAAM,OAAA,EAAQ;AAEd,IAAA,IAAI,KAAK,qBAAA,EAAuB;AAC9B,MAAA,IAAA,CAAK,qBAAA,EAAsB;AAC3B,MAAA,IAAA,CAAK,qBAAA,GAAwB,IAAA;AAAA,IAC/B;AACA,IAAA,IAAI,KAAK,mBAAA,EAAqB;AAC5B,MAAA,IAAA,CAAK,mBAAA,EAAoB;AACzB,MAAA,IAAA,CAAK,mBAAA,GAAsB,IAAA;AAAA,IAC7B;AAEA,IAAA,IAAA,CAAK,2BAAA,EAA4B;AACjC,IAAC,KAA4E,UAAA,GAAa,MAAA;AAAA,EAC5F;AAAA;AAAA;AAAA;AAAA,EAKQ,2BAAA,GAAoC;AAC1C,IAAA,IAAA,CAAK,cAAc,KAAA,EAAM;AACzB,IAAA,IAAA,CAAK,sBAAA,GAAyB,IAAA;AAC9B,IAAA,IAAA,CAAK,sBAAA,GAAyB,IAAA;AAAA,EAChC;AACF;;;;"}
@@ -13,12 +13,12 @@ const wrapMethodWithSentry = require('./wrapMethodWithSentry.js');
13
13
 
14
14
  function instrumentDurableObjectWithSentry(optionsCallback, DurableObjectClass) {
15
15
  return new Proxy(DurableObjectClass, {
16
- construct(target, [ctx, env]) {
16
+ construct(target, [ctx, env], newTarget) {
17
17
  async.setAsyncLocalStorageAsyncContextStrategy();
18
18
  const context = instrumentContext.instrumentContext(ctx);
19
19
  const options$1 = options.getFinalOptions(optionsCallback(env), env);
20
20
  const instrumentedEnv = instrumentEnv.instrumentEnv(env, options$1);
21
- const obj = new target(context, instrumentedEnv);
21
+ const obj = Reflect.construct(target, [context, instrumentedEnv], newTarget);
22
22
  if (obj.fetch && typeof obj.fetch === "function") {
23
23
  obj.fetch = instrument.ensureInstrumented(
24
24
  obj.fetch,
@@ -1 +1 @@
1
- {"version":3,"file":"durableobject.js","sources":["../../src/durableobject.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/unbound-method */\nimport { captureException } from '@sentry/core';\nimport type { DurableObject } from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport type { CloudflareOptions } from './client';\nimport { ensureInstrumented } from './instrument';\nimport { instrumentEnv } from './instrumentations/worker/instrumentEnv';\nimport { getFinalOptions } from './options';\nimport { wrapRequestHandler } from './request';\nimport { instrumentContext } from './utils/instrumentContext';\nimport { extractRpcMeta } from './utils/rpcMeta';\nimport { getEffectiveRpcPropagation } from './utils/rpcOptions';\nimport { type UncheckedMethod, wrapMethodWithSentry } from './wrapMethodWithSentry';\n\n/**\n * Instruments a Durable Object class to capture errors and performance data.\n *\n * Instruments the following methods by default:\n * - fetch\n * - alarm\n * - webSocketMessage\n * - webSocketClose\n * - webSocketError\n *\n * To instrument RPC methods (prototype methods), enable the `enableRpcTracePropagation` option.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param DurableObjectClass The Durable Object class to instrument.\n * @returns The instrumented Durable Object class.\n *\n * @example\n * ```ts\n * class MyDurableObjectBase extends DurableObject {\n * constructor(ctx: DurableObjectState, env: Env) {\n * super(ctx, env);\n * }\n * }\n *\n * export const MyDurableObject = instrumentDurableObjectWithSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * }),\n * MyDurableObjectBase,\n * );\n * ```\n */\nexport function instrumentDurableObjectWithSentry<\n E,\n T extends DurableObject<E>,\n C extends new (state: DurableObjectState, env: E) => T,\n>(optionsCallback: (env: E) => CloudflareOptions, DurableObjectClass: C): C {\n return new Proxy(DurableObjectClass, {\n construct(target, [ctx, env]) {\n setAsyncLocalStorageAsyncContextStrategy();\n const context = instrumentContext(ctx);\n const options = getFinalOptions(optionsCallback(env), env);\n const instrumentedEnv = instrumentEnv(env, options);\n\n const obj = new target(context, instrumentedEnv);\n\n // These are the methods that are available on a Durable Object\n // ref: https://developers.cloudflare.com/durable-objects/api/base/\n // obj.alarm\n // obj.fetch\n // obj.webSocketError\n // obj.webSocketClose\n // obj.webSocketMessage\n\n // Any other public methods on the Durable Object instance are RPC calls.\n\n if (obj.fetch && typeof obj.fetch === 'function') {\n obj.fetch = ensureInstrumented(\n obj.fetch,\n original =>\n new Proxy(original, {\n apply(target, thisArg, args) {\n return wrapRequestHandler({ options, request: args[0], context }, () => {\n return Reflect.apply(target, thisArg, args);\n });\n },\n }),\n );\n }\n\n if (obj.alarm && typeof obj.alarm === 'function') {\n // Alarms are independent invocations, so we start a new trace and link to the previous alarm\n obj.alarm = wrapMethodWithSentry(\n { options, context, spanName: 'alarm', spanOp: 'function', startNewTrace: true },\n obj.alarm,\n );\n }\n\n if (obj.webSocketMessage && typeof obj.webSocketMessage === 'function') {\n obj.webSocketMessage = wrapMethodWithSentry(\n { options, context, spanName: 'webSocketMessage' },\n obj.webSocketMessage,\n );\n }\n\n if (obj.webSocketClose && typeof obj.webSocketClose === 'function') {\n obj.webSocketClose = wrapMethodWithSentry({ options, context, spanName: 'webSocketClose' }, obj.webSocketClose);\n }\n\n if (obj.webSocketError && typeof obj.webSocketError === 'function') {\n obj.webSocketError = wrapMethodWithSentry(\n { options, context, spanName: 'webSocketError' },\n obj.webSocketError,\n (_, error) =>\n captureException(error, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object_websocket',\n handled: false,\n },\n }),\n );\n }\n\n // Get effective RPC propagation setting (handles deprecation of instrumentPrototypeMethods)\n const rpcPropagation = getEffectiveRpcPropagation(options);\n\n // Skip RPC instrumentation if not enabled\n if (!rpcPropagation) {\n return obj;\n }\n\n // If `instrumentPrototypeMethods` was passed as an array (deprecated),\n // only the listed method names should be instrumented.\n // eslint-disable-next-line typescript/no-deprecated\n const instrumentPrototypeMethods = Array.isArray(options.instrumentPrototypeMethods)\n ? // eslint-disable-next-line typescript/no-deprecated\n options.instrumentPrototypeMethods\n : undefined;\n const allowSet = instrumentPrototypeMethods ? new Set(instrumentPrototypeMethods) : null;\n\n // When using the deprecated `instrumentPrototypeMethods` option, always create spans.\n // When using the new `enableRpcTracePropagation`, only create spans when RPC metadata is present.\n const alwaysTrace = options.enableRpcTracePropagation === undefined;\n\n // Return a Proxy that binds all methods to the original object and creates spans\n // for RPC calls that have Sentry trace context propagated.\n // Binding is required because frameworks may use private fields (babel WeakMap pattern),\n // which fail if `this` is the Proxy instead of the original object.\n const methodCache = new Map<string, UncheckedMethod>();\n\n return new Proxy(obj, {\n get(proxyTarget, prop, receiver) {\n const value = Reflect.get(proxyTarget, prop, receiver);\n\n if (typeof prop !== 'string' || typeof value !== 'function' || prop === 'constructor') {\n return value;\n }\n\n const cached = methodCache.get(prop);\n\n if (cached) {\n return cached;\n }\n\n const boundMethod = (value as UncheckedMethod).bind(proxyTarget);\n\n if (\n prop in Object.prototype ||\n Object.prototype.hasOwnProperty.call(proxyTarget, prop) ||\n (allowSet && !allowSet.has(prop))\n ) {\n methodCache.set(prop, boundMethod);\n\n return boundMethod;\n }\n\n // Pre-create the traced version\n const tracedMethod = wrapMethodWithSentry(\n { options, context, spanName: prop, spanOp: 'rpc' },\n boundMethod,\n undefined,\n true,\n );\n\n // For deprecated `instrumentPrototypeMethods`, always trace.\n // For new `enableRpcTracePropagation`, only trace when RPC metadata is present.\n if (alwaysTrace) {\n methodCache.set(prop, tracedMethod);\n\n return tracedMethod;\n }\n\n // Wrapper that checks for Sentry RPC metadata at call time\n const wrappedMethod = ((...args: unknown[]) => {\n const { rpcMeta } = extractRpcMeta(args);\n\n // If Sentry RPC metadata is present, use the traced version (creates span)\n // Otherwise, call the bound method directly (no span)\n return rpcMeta ? tracedMethod(...args) : boundMethod(...args);\n }) as UncheckedMethod;\n\n methodCache.set(prop, wrappedMethod);\n\n return wrappedMethod;\n },\n });\n },\n });\n}\n"],"names":["setAsyncLocalStorageAsyncContextStrategy","instrumentContext","options","getFinalOptions","instrumentEnv","ensureInstrumented","target","wrapRequestHandler","wrapMethodWithSentry","captureException","getEffectiveRpcPropagation","rpcMeta","extractRpcMeta"],"mappings":";;;;;;;;;;;;;AA+CO,SAAS,iCAAA,CAId,iBAAgD,kBAAA,EAA0B;AAC1E,EAAA,OAAO,IAAI,MAAM,kBAAA,EAAoB;AAAA,IACnC,SAAA,CAAU,MAAA,EAAQ,CAAC,GAAA,EAAK,GAAG,CAAA,EAAG;AAC5B,MAAAA,8CAAA,EAAyC;AACzC,MAAA,MAAM,OAAA,GAAUC,oCAAkB,GAAG,CAAA;AACrC,MAAA,MAAMC,SAAA,GAAUC,uBAAA,CAAgB,eAAA,CAAgB,GAAG,GAAG,GAAG,CAAA;AACzD,MAAA,MAAM,eAAA,GAAkBC,2BAAA,CAAc,GAAA,EAAKF,SAAO,CAAA;AAElD,MAAA,MAAM,GAAA,GAAM,IAAI,MAAA,CAAO,OAAA,EAAS,eAAe,CAAA;AAY/C,MAAA,IAAI,GAAA,CAAI,KAAA,IAAS,OAAO,GAAA,CAAI,UAAU,UAAA,EAAY;AAChD,QAAA,GAAA,CAAI,KAAA,GAAQG,6BAAA;AAAA,UACV,GAAA,CAAI,KAAA;AAAA,UACJ,CAAA,QAAA,KACE,IAAI,KAAA,CAAM,QAAA,EAAU;AAAA,YAClB,KAAA,CAAMC,OAAAA,EAAQ,OAAA,EAAS,IAAA,EAAM;AAC3B,cAAA,OAAOC,0BAAA,CAAmB,WAAEL,SAAA,EAAS,OAAA,EAAS,KAAK,CAAC,CAAA,EAAG,OAAA,EAAQ,EAAG,MAAM;AACtE,gBAAA,OAAO,OAAA,CAAQ,KAAA,CAAMI,OAAAA,EAA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jC,YAAA,OAAO,WAAA;AAAA,UACT;AAGA,UAAA,MAAM,YAAA,GAAeM,yCAAA;AAAA,YACnB,WAAEN,SAAA,EAAS,OAAA,EAAS,QAAA,EAAU,IAAA,EAAM,QAAQ,KAAA,EAAM;AAAA,YAClD,WAAA;AAAA,YACA,KAAA,CAAA;AAAA,YACA;AAAA,WACF;AAIA,UAAA,IAAI,WAAA,EAAa;AACf,YAAA,WAAA,CAAY,GAAA,CAAI,MAAM,YAAY,CAAA;AAElC,YAAA,OAAO,YAAA;AAAA,UACT;AAGA,UAAA,MAAM,aAAA,IAAiB,IAAI,IAAA,KAAoB;AAC7C,YAAA,MAAM,WAAES,SAAA,EAAQ,GAAIC,sBAAA,CAAe,IAAI,CAAA;AAIvC,YAAA,OAAOD,YAAU,YAAA,CAAa,GAAG,IAAI,CAAA,GAAI,WAAA,CAAY,GAAG,IAAI,CAAA;AAAA,UAC9D,CAAA,CAAA;AAEA,UAAA,WAAA,CAAY,GAAA,CAAI,MAAM,aAAa,CAAA;AAEnC,UAAA,OAAO,aAAA;AAAA,QACT;AAAA,OACD,CAAA;AAAA,IACH;AAAA,GACD,CAAA;AACH;;;;"}
1
+ {"version":3,"file":"durableobject.js","sources":["../../src/durableobject.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/unbound-method */\nimport { captureException } from '@sentry/core';\nimport type { DurableObject } from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport type { CloudflareOptions } from './client';\nimport { ensureInstrumented } from './instrument';\nimport { instrumentEnv } from './instrumentations/worker/instrumentEnv';\nimport { getFinalOptions } from './options';\nimport { wrapRequestHandler } from './request';\nimport { instrumentContext } from './utils/instrumentContext';\nimport { extractRpcMeta } from './utils/rpcMeta';\nimport { getEffectiveRpcPropagation } from './utils/rpcOptions';\nimport { type UncheckedMethod, wrapMethodWithSentry } from './wrapMethodWithSentry';\n\n/**\n * Instruments a Durable Object class to capture errors and performance data.\n *\n * Instruments the following methods by default:\n * - fetch\n * - alarm\n * - webSocketMessage\n * - webSocketClose\n * - webSocketError\n *\n * To instrument RPC methods (prototype methods), enable the `enableRpcTracePropagation` option.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param DurableObjectClass The Durable Object class to instrument.\n * @returns The instrumented Durable Object class.\n *\n * @example\n * ```ts\n * class MyDurableObjectBase extends DurableObject {\n * constructor(ctx: DurableObjectState, env: Env) {\n * super(ctx, env);\n * }\n * }\n *\n * export const MyDurableObject = instrumentDurableObjectWithSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * }),\n * MyDurableObjectBase,\n * );\n * ```\n */\nexport function instrumentDurableObjectWithSentry<\n E,\n T extends DurableObject<E>,\n C extends new (state: DurableObjectState, env: E) => T,\n>(optionsCallback: (env: E) => CloudflareOptions, DurableObjectClass: C): C {\n return new Proxy(DurableObjectClass, {\n construct(target, [ctx, env], newTarget) {\n setAsyncLocalStorageAsyncContextStrategy();\n const context = instrumentContext(ctx);\n const options = getFinalOptions(optionsCallback(env), env);\n const instrumentedEnv = instrumentEnv(env, options);\n\n // Pass `newTarget` so that subclasses of the instrumented class (e.g. the wrapper classes\n // created by wrangler's local dev tooling or `@cloudflare/vitest-pool-workers`) keep their\n // own prototype — otherwise subclass methods disappear and `instanceof` checks break.\n const obj = Reflect.construct(target, [context, instrumentedEnv], newTarget) as T;\n\n // These are the methods that are available on a Durable Object\n // ref: https://developers.cloudflare.com/durable-objects/api/base/\n // obj.alarm\n // obj.fetch\n // obj.webSocketError\n // obj.webSocketClose\n // obj.webSocketMessage\n\n // Any other public methods on the Durable Object instance are RPC calls.\n\n if (obj.fetch && typeof obj.fetch === 'function') {\n obj.fetch = ensureInstrumented(\n obj.fetch,\n original =>\n new Proxy(original, {\n apply(target, thisArg, args) {\n return wrapRequestHandler({ options, request: args[0], context }, () => {\n return Reflect.apply(target, thisArg, args);\n });\n },\n }),\n );\n }\n\n if (obj.alarm && typeof obj.alarm === 'function') {\n // Alarms are independent invocations, so we start a new trace and link to the previous alarm\n obj.alarm = wrapMethodWithSentry(\n { options, context, spanName: 'alarm', spanOp: 'function', startNewTrace: true },\n obj.alarm,\n );\n }\n\n if (obj.webSocketMessage && typeof obj.webSocketMessage === 'function') {\n obj.webSocketMessage = wrapMethodWithSentry(\n { options, context, spanName: 'webSocketMessage' },\n obj.webSocketMessage,\n );\n }\n\n if (obj.webSocketClose && typeof obj.webSocketClose === 'function') {\n obj.webSocketClose = wrapMethodWithSentry({ options, context, spanName: 'webSocketClose' }, obj.webSocketClose);\n }\n\n if (obj.webSocketError && typeof obj.webSocketError === 'function') {\n obj.webSocketError = wrapMethodWithSentry(\n { options, context, spanName: 'webSocketError' },\n obj.webSocketError,\n (_, error) =>\n captureException(error, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object_websocket',\n handled: false,\n },\n }),\n );\n }\n\n // Get effective RPC propagation setting (handles deprecation of instrumentPrototypeMethods)\n const rpcPropagation = getEffectiveRpcPropagation(options);\n\n // Skip RPC instrumentation if not enabled\n if (!rpcPropagation) {\n return obj;\n }\n\n // If `instrumentPrototypeMethods` was passed as an array (deprecated),\n // only the listed method names should be instrumented.\n // eslint-disable-next-line typescript/no-deprecated\n const instrumentPrototypeMethods = Array.isArray(options.instrumentPrototypeMethods)\n ? // eslint-disable-next-line typescript/no-deprecated\n options.instrumentPrototypeMethods\n : undefined;\n const allowSet = instrumentPrototypeMethods ? new Set(instrumentPrototypeMethods) : null;\n\n // When using the deprecated `instrumentPrototypeMethods` option, always create spans.\n // When using the new `enableRpcTracePropagation`, only create spans when RPC metadata is present.\n const alwaysTrace = options.enableRpcTracePropagation === undefined;\n\n // Return a Proxy that binds all methods to the original object and creates spans\n // for RPC calls that have Sentry trace context propagated.\n // Binding is required because frameworks may use private fields (babel WeakMap pattern),\n // which fail if `this` is the Proxy instead of the original object.\n const methodCache = new Map<string, UncheckedMethod>();\n\n return new Proxy(obj, {\n get(proxyTarget, prop, receiver) {\n const value = Reflect.get(proxyTarget, prop, receiver);\n\n if (typeof prop !== 'string' || typeof value !== 'function' || prop === 'constructor') {\n return value;\n }\n\n const cached = methodCache.get(prop);\n\n if (cached) {\n return cached;\n }\n\n const boundMethod = (value as UncheckedMethod).bind(proxyTarget);\n\n if (\n prop in Object.prototype ||\n Object.prototype.hasOwnProperty.call(proxyTarget, prop) ||\n (allowSet && !allowSet.has(prop))\n ) {\n methodCache.set(prop, boundMethod);\n\n return boundMethod;\n }\n\n // Pre-create the traced version\n const tracedMethod = wrapMethodWithSentry(\n { options, context, spanName: prop, spanOp: 'rpc' },\n boundMethod,\n undefined,\n true,\n );\n\n // For deprecated `instrumentPrototypeMethods`, always trace.\n // For new `enableRpcTracePropagation`, only trace when RPC metadata is present.\n if (alwaysTrace) {\n methodCache.set(prop, tracedMethod);\n\n return tracedMethod;\n }\n\n // Wrapper that checks for Sentry RPC metadata at call time\n const wrappedMethod = ((...args: unknown[]) => {\n const { rpcMeta } = extractRpcMeta(args);\n\n // If Sentry RPC metadata is present, use the traced version (creates span)\n // Otherwise, call the bound method directly (no span)\n return rpcMeta ? tracedMethod(...args) : boundMethod(...args);\n }) as UncheckedMethod;\n\n methodCache.set(prop, wrappedMethod);\n\n return wrappedMethod;\n },\n });\n },\n });\n}\n"],"names":["setAsyncLocalStorageAsyncContextStrategy","instrumentContext","options","getFinalOptions","instrumentEnv","ensureInstrumented","target","wrapRequestHandler","wrapMethodWithSentry","captureException","getEffectiveRpcPropagation","rpcMeta","extractRpcMeta"],"mappings":";;;;;;;;;;;;;AA+CO,SAAS,iCAAA,CAId,iBAAgD,kBAAA,EAA0B;AAC1E,EAAA,OAAO,IAAI,MAAM,kBAAA,EAAoB;AAAA,IACnC,UAAU,MAAA,EAAQ,CAAC,GAAA,EAAK,GAAG,GAAG,SAAA,EAAW;AACvC,MAAAA,8CAAA,EAAyC;AACzC,MAAA,MAAM,OAAA,GAAUC,oCAAkB,GAAG,CAAA;AACrC,MAAA,MAAMC,SAAA,GAAUC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AA,UAC9D,CAAA,CAAA;AAEA,UAAA,WAAA,CAAY,GAAA,CAAI,MAAM,aAAa,CAAA;AAEnC,UAAA,OAAO,aAAA;AAAA,QACT;AAAA,OACD,CAAA;AAAA,IACH;AAAA,GACD,CAAA;AACH;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"flush.js","sources":["../../src/flush.ts"],"sourcesContent":["import type { ExecutionContext } from '@cloudflare/workers-types';\nimport type { Client } from '@sentry/core';\nimport { debug, flush } from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build';\n\ntype FlushLock = {\n readonly ready: Promise<void>;\n readonly finalize: () => Promise<void>;\n};\n\ntype FlushLockRegistry = {\n readonly locks: Set<FlushLockInternal>;\n readonly originalWaitUntil: ExecutionContext['waitUntil'];\n};\n\ntype FlushLockInternal = FlushLock & {\n readonly acquire: () => void;\n readonly release: () => void;\n};\n\nconst flushLockRegistries = new WeakMap<ExecutionContext['waitUntil'], FlushLockRegistry>();\n\n/**\n * Returns the original (un-instrumented) waitUntil function for a context.\n * This should be used when calling waitUntil with flushAndDispose to avoid deadlock.\n *\n * The flush lock mechanism wraps context.waitUntil to track pending tasks.\n * If we call waitUntil(flushAndDispose(client)) through the instrumented version,\n * it creates a deadlock because:\n * 1. The instrumented waitUntil acquires the flush lock\n * 2. flushAndDispose calls client.flush() which waits for the lock to be released\n * 3. The lock won't be released until the waitUntil promise completes\n * 4. The waitUntil promise won't complete until flush() returns\n *\n * By using the original waitUntil for flush operations, we bypass this issue.\n */\nexport function getOriginalWaitUntil(context: ExecutionContext): ExecutionContext['waitUntil'] | undefined {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const currentWaitUntil = context.waitUntil;\n const original = flushLockRegistries.get(currentWaitUntil)?.originalWaitUntil;\n return original ?? currentWaitUntil;\n}\n\n/**\n * Enhances the given execution context by wrapping its `waitUntil` method with a proxy\n * to monitor pending tasks, and provides a flusher function to ensure all tasks\n * have been completed before executing any subsequent logic.\n *\n * @param {ExecutionContext} context - The execution context to be enhanced. If no context is provided, the function returns undefined.\n * @return {FlushLock} Returns a flusher function if a valid context is provided, otherwise undefined.\n */\nexport function makeFlushLock(context: ExecutionContext): FlushLock {\n const registry = getOrCreateFlushLockRegistry(context);\n let resolveAllDone: () => void = () => undefined;\n const allDone = new Promise<void>(res => {\n resolveAllDone = res;\n });\n let pending = 0;\n\n const lock: FlushLockInternal = {\n ready: allDone,\n acquire: () => {\n pending++;\n },\n release: () => {\n if (--pending === 0) {\n registry.locks.delete(lock);\n resolveAllDone();\n }\n },\n finalize: () => {\n if (pending === 0) {\n registry.locks.delete(lock);\n resolveAllDone();\n }\n return allDone;\n },\n };\n\n registry.locks.add(lock);\n return Object.freeze(lock);\n}\n\nfunction getOrCreateFlushLockRegistry(context: ExecutionContext): FlushLockRegistry {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const waitUntil = context.waitUntil;\n const existingRegistry = flushLockRegistries.get(waitUntil);\n\n if (existingRegistry) {\n return existingRegistry;\n }\n\n const originalWaitUntil = context.waitUntil.bind(context) as typeof context.waitUntil;\n const registry: FlushLockRegistry = { locks: new Set(), originalWaitUntil };\n const instrumentedWaitUntil: typeof context.waitUntil = promise => {\n // Snapshot active locks so locks created after this call do not wait for earlier waitUntil work.\n const locks = [...registry.locks];\n\n for (const lock of locks) {\n lock.acquire();\n }\n\n return originalWaitUntil(\n promise.finally(() => {\n for (const lock of locks) {\n lock.release();\n }\n }),\n );\n };\n\n flushLockRegistries.set(instrumentedWaitUntil, registry);\n context.waitUntil = instrumentedWaitUntil;\n\n return registry;\n}\n\n/**\n * Flushes the client and then disposes of it to allow garbage collection.\n * This should be called at the end of each request to prevent memory leaks.\n *\n * This function never rejects. On Workers, a rejected promise passed to\n * `ctx.waitUntil` marks the whole invocation as `outcome: exception` even when\n * the handler itself completed successfully. Since flush/dispose is internal\n * SDK housekeeping, a failure here must not fail the user's invocation.\n *\n * @param client - The CloudflareClient instance to flush and dispose\n * @param timeout - Timeout in milliseconds for the flush operation\n * @returns A promise that resolves when flush and dispose are complete\n */\nexport async function flushAndDispose(client: Client | undefined, timeout = 2000): Promise<void> {\n try {\n if (!client) {\n await flush(timeout);\n return;\n }\n await client.flush(timeout);\n } catch (e) {\n DEBUG_BUILD && debug.warn('Failed to flush client', e);\n } finally {\n try {\n client?.dispose();\n } catch (e) {\n DEBUG_BUILD && debug.warn('Failed to dispose client', e);\n }\n }\n}\n"],"names":["flush","DEBUG_BUILD","debug"],"mappings":";;;;;AAoBA,MAAM,mBAAA,uBAA0B,OAAA,EAA0D;AAgBnF,SAAS,qBAAqB,OAAA,EAAsE;AAEzG,EAAA,MAAM,mBAAmB,OAAA,CAAQ,SAAA;AACjC,EAAA,MAAM,QAAA,GAAW,mBAAA,CAAoB,GAAA,CAAI,gBAAgB,CAAA,EAAG,iBAAA;AAC5D,EAAA,OAAO,QAAA,IAAY,gBAAA;AACrB;AAUO,SAAS,cAAc,OAAA,EAAsC;AAClE,EAAA,MAAM,QAAA,GAAW,6BAA6B,OAAO,CAAA;AACrD,EAAA,IAAI,iBAA6B,MAAM,MAAA;AACvC,EAAA,MAAM,OAAA,GAAU,IAAI,OAAA,CAAc,CAAA,GAAA,KAAO;AACvC,IAAA,cAAA,GAAiB,GAAA;AAAA,EACnB,CAAC,CAAA;AACD,EAAA,IAAI,OAAA,GAAU,CAAA;AAEd,EAAA,MAAM,IAAA,GAA0B;AAAA,IAC9B,KAAA,EAAO,OAAA;AAAA,IACP,SAAS,MAAM;AACb,MAAA,OAAA,EAAA;AAAA,IACF,CAAA;AAAA,IACA,SAAS,MAAM;AACb,MAAA,IAAI,EAAE,YAAY,CAAA,EAAG;AACnB,QAAA,QAAA,CAAS,KAAA,CAAM,OAAO,IAAI,CAAA;AAC1B,QAAA,cAAA,EAAe;AAAA,MACjB;AAAA,IACF,CAAA;AAAA,IACA,UAAU,MAAM;AACd,MAAA,IAAI,YAAY,CAAA,EAAG;AACjB,QAAA,QAAA,CAAS,KAAA,CAAM,OAAO,IAAI,CAAA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ACX,MAAA,MAAMA,WAAM,OAAO,CAAA;AACnB,MAAA;AAAA,IACF;AACA,IAAA,MAAM,MAAA,CAAO,MAAM,OAAO,CAAA;AAAA,EAC5B,SAAS,CAAA,EAAG;AACV,IAAAC,sBAAA,IAAeC,UAAA,CAAM,IAAA,CAAK,wBAAA,EAA0B,CAAC,CAAA;AAAA,EACvD,CAAA,SAAE;AACA,IAAA,IAAI;AACF,MAAA,MAAA,EAAQ,OAAA,EAAQ;AAAA,IAClB,SAAS,CAAA,EAAG;AACV,MAAAD,sBAAA,IAAeC,UAAA,CAAM,IAAA,CAAK,0BAAA,EAA4B,CAAC,CAAA;AAAA,IACzD;AAAA,EACF;AACF;;;;;;"}
1
+ {"version":3,"file":"flush.js","sources":["../../src/flush.ts"],"sourcesContent":["import type { ExecutionContext } from '@cloudflare/workers-types';\nimport type { Client } from '@sentry/core';\nimport { debug, flush } from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { ExecutionContextCompat } from './executionContext';\n\ntype FlushLock = {\n readonly ready: Promise<void>;\n readonly finalize: () => Promise<void>;\n};\n\ntype FlushLockRegistry = {\n readonly locks: Set<FlushLockInternal>;\n readonly originalWaitUntil: ExecutionContext['waitUntil'];\n};\n\ntype FlushLockInternal = FlushLock & {\n readonly acquire: () => void;\n readonly release: () => void;\n};\n\nconst flushLockRegistries = new WeakMap<ExecutionContext['waitUntil'], FlushLockRegistry>();\n\n/**\n * Returns the original (un-instrumented) waitUntil function for a context.\n * This should be used when calling waitUntil with flushAndDispose to avoid deadlock.\n *\n * The flush lock mechanism wraps context.waitUntil to track pending tasks.\n * If we call waitUntil(flushAndDispose(client)) through the instrumented version,\n * it creates a deadlock because:\n * 1. The instrumented waitUntil acquires the flush lock\n * 2. flushAndDispose calls client.flush() which waits for the lock to be released\n * 3. The lock won't be released until the waitUntil promise completes\n * 4. The waitUntil promise won't complete until flush() returns\n *\n * By using the original waitUntil for flush operations, we bypass this issue.\n */\nexport function getOriginalWaitUntil(context: ExecutionContextCompat): ExecutionContext['waitUntil'] | undefined {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const currentWaitUntil = context.waitUntil;\n const original = flushLockRegistries.get(currentWaitUntil)?.originalWaitUntil;\n return original ?? currentWaitUntil;\n}\n\n/**\n * Enhances the given execution context by wrapping its `waitUntil` method with a proxy\n * to monitor pending tasks, and provides a flusher function to ensure all tasks\n * have been completed before executing any subsequent logic.\n *\n * @param {ExecutionContext} context - The execution context to be enhanced. If no context is provided, the function returns undefined.\n * @return {FlushLock} Returns a flusher function if a valid context is provided, otherwise undefined.\n */\nexport function makeFlushLock(context: ExecutionContextCompat): FlushLock {\n const registry = getOrCreateFlushLockRegistry(context);\n let resolveAllDone: () => void = () => undefined;\n const allDone = new Promise<void>(res => {\n resolveAllDone = res;\n });\n let pending = 0;\n\n const lock: FlushLockInternal = {\n ready: allDone,\n acquire: () => {\n pending++;\n },\n release: () => {\n if (--pending === 0) {\n registry.locks.delete(lock);\n resolveAllDone();\n }\n },\n finalize: () => {\n if (pending === 0) {\n registry.locks.delete(lock);\n resolveAllDone();\n }\n return allDone;\n },\n };\n\n registry.locks.add(lock);\n return Object.freeze(lock);\n}\n\nfunction getOrCreateFlushLockRegistry(context: ExecutionContextCompat): FlushLockRegistry {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const waitUntil = context.waitUntil;\n const existingRegistry = flushLockRegistries.get(waitUntil);\n\n if (existingRegistry) {\n return existingRegistry;\n }\n\n const originalWaitUntil = context.waitUntil.bind(context) as typeof context.waitUntil;\n const registry: FlushLockRegistry = { locks: new Set(), originalWaitUntil };\n const instrumentedWaitUntil: typeof context.waitUntil = promise => {\n // Snapshot active locks so locks created after this call do not wait for earlier waitUntil work.\n const locks = [...registry.locks];\n\n for (const lock of locks) {\n lock.acquire();\n }\n\n return originalWaitUntil(\n promise.finally(() => {\n for (const lock of locks) {\n lock.release();\n }\n }),\n );\n };\n\n flushLockRegistries.set(instrumentedWaitUntil, registry);\n context.waitUntil = instrumentedWaitUntil;\n\n return registry;\n}\n\n/**\n * Flushes the client and then disposes of it to allow garbage collection.\n * This should be called at the end of each request to prevent memory leaks.\n *\n * This function never rejects. On Workers, a rejected promise passed to\n * `ctx.waitUntil` marks the whole invocation as `outcome: exception` even when\n * the handler itself completed successfully. Since flush/dispose is internal\n * SDK housekeeping, a failure here must not fail the user's invocation.\n *\n * @param client - The CloudflareClient instance to flush and dispose\n * @param timeout - Timeout in milliseconds for the flush operation\n * @returns A promise that resolves when flush and dispose are complete\n */\nexport async function flushAndDispose(client: Client | undefined, timeout = 2000): Promise<void> {\n try {\n if (!client) {\n await flush(timeout);\n return;\n }\n await client.flush(timeout);\n } catch (e) {\n DEBUG_BUILD && debug.warn('Failed to flush client', e);\n } finally {\n try {\n client?.dispose();\n } catch (e) {\n DEBUG_BUILD && debug.warn('Failed to dispose client', e);\n }\n }\n}\n"],"names":["flush","DEBUG_BUILD","debug"],"mappings":";;;;;AAqBA,MAAM,mBAAA,uBAA0B,OAAA,EAA0D;AAgBnF,SAAS,qBAAqB,OAAA,EAA4E;AAE/G,EAAA,MAAM,mBAAmB,OAAA,CAAQ,SAAA;AACjC,EAAA,MAAM,QAAA,GAAW,mBAAA,CAAoB,GAAA,CAAI,gBAAgB,CAAA,EAAG,iBAAA;AAC5D,EAAA,OAAO,QAAA,IAAY,gBAAA;AACrB;AAUO,SAAS,cAAc,OAAA,EAA4C;AACxE,EAAA,MAAM,QAAA,GAAW,6BAA6B,OAAO,CAAA;AACrD,EAAA,IAAI,iBAA6B,MAAM,MAAA;AACvC,EAAA,MAAM,OAAA,GAAU,IAAI,OAAA,CAAc,CAAA,GAAA,KAAO;AACvC,IAAA,cAAA,GAAiB,GAAA;AAAA,EACnB,CAAC,CAAA;AACD,EAAA,IAAI,OAAA,GAAU,CAAA;AAEd,EAAA,MAAM,IAAA,GAA0B;AAAA,IAC9B,KAAA,EAAO,OAAA;AAAA,IACP,SAAS,MAAM;AACb,MAAA,OAAA,EAAA;AAAA,I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F,CAAC;AAAA,KACH;AAAA,EACF,CAAA;AAEA,EAAA,mBAAA,CAAoB,GAAA,CAAI,uBAAuB,QAAQ,CAAA;AACvD,EAAA,OAAA,CAAQ,SAAA,GAAY,qBAAA;AAEpB,EAAA,OAAO,QAAA;AACT;AAeA,eAAsB,eAAA,CAAgB,MAAA,EAA4B,OAAA,GAAU,GAAA,EAAqB;AAC/F,EAAA,IAAI;AACF,IAAA,IAAI,CAAC,MAAA,EAAQ;AACX,MAAA,MAAMA,WAAM,OAAO,CAAA;AACnB,MAAA;AAAA,IACF;AACA,IAAA,MAAM,MAAA,CAAO,MAAM,OAAO,CAAA;AAAA,EAC5B,SAAS,CAAA,EAAG;AACV,IAAAC,sBAAA,IAAeC,UAAA,CAAM,IAAA,CAAK,wBAAA,EAA0B,CAAC,CAAA;AAAA,EACvD,CAAA,SAAE;AACA,IAAA,IAAI;AACF,MAAA,MAAA,EAAQ,OAAA,EAAQ;AAAA,IAClB,SAAS,CAAA,EAAG;AACV,MAAAD,sBAAA,IAAeC,UAAA,CAAM,IAAA,CAAK,0BAAA,EAA4B,CAAC,CAAA;AAAA,IACzD;AAAA,EACF;AACF;;;;;;"}
@@ -1,5 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
 
3
+ const core = require('@sentry/core');
4
+
3
5
  const GLOBAL_KEY = "__SENTRY_INSTRUMENTED_MAP__";
4
6
  function getInstrumentedMap() {
5
7
  const globalObj = globalThis;
@@ -9,7 +11,7 @@ function getInstrumentedMap() {
9
11
  return globalObj[GLOBAL_KEY];
10
12
  }
11
13
  function isWeakMapKey(value) {
12
- return typeof value === "object" && value !== null || typeof value === "function";
14
+ return core.isObjectLike(value) || typeof value === "function";
13
15
  }
14
16
  function markAsInstrumented(original, instrumented) {
15
17
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"instrument.js","sources":["../../src/instrument.ts"],"sourcesContent":["// Use a global WeakMap to track instrumented objects across module instances.\n// This is important for Cloudflare Workers where the module may be bundled\n// separately for workers and Durable Objects, but they share the same global scope.\n// The WeakMap stores original -> instrumented mappings so we can retrieve the\n// instrumented version even if we only have a reference to the original.\nconst GLOBAL_KEY = '__SENTRY_INSTRUMENTED_MAP__' as const;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getInstrumentedMap(): WeakMap<any, any> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const globalObj = globalThis as typeof globalThis & { [GLOBAL_KEY]?: WeakMap<any, any> };\n if (!globalObj[GLOBAL_KEY]) {\n globalObj[GLOBAL_KEY] = new WeakMap();\n }\n return globalObj[GLOBAL_KEY];\n}\n\n/**\n * Check if a value can be used as a WeakMap key.\n * WeakMap keys must be objects or non-registered symbols.\n */\nfunction isWeakMapKey(value: unknown): value is object {\n return (typeof value === 'object' && value !== null) || typeof value === 'function';\n}\n\n/**\n * Mark an object as instrumented, storing the instrumented version.\n * @param original The original uninstrumented object\n * @param instrumented The instrumented version (defaults to original if not provided)\n */\nexport function markAsInstrumented<T>(original: T, instrumented?: T): void {\n try {\n if (isWeakMapKey(original)) {\n // Store mapping from original to instrumented version\n // If instrumented is not provided, store original (for backwards compat)\n getInstrumentedMap().set(original, instrumented ?? original);\n }\n // Also mark the instrumented version itself so we recognize it\n if (isWeakMapKey(instrumented) && instrumented !== original) {\n getInstrumentedMap().set(instrumented, instrumented);\n }\n } catch {\n // ignore errors here\n }\n}\n\n/**\n * Get the instrumented version of an object, if available.\n * Returns the instrumented version if the object was previously instrumented,\n * or undefined if not found.\n */\nexport function getInstrumented<T>(obj: T): T | undefined {\n try {\n if (isWeakMapKey(obj)) {\n return getInstrumentedMap().get(obj) as T | undefined;\n }\n\n return undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Returns the already-instrumented version of `original` if one exists,\n * otherwise calls `instrumentFn` to create it, marks the mapping, and returns it.\n *\n * @param noMark - If true, skips storing the original→instrumented mapping.\n */\nexport function ensureInstrumented<T>(original: T, instrumentFn: (original: T) => T, noMark?: boolean): T {\n const existing = getInstrumented(original);\n\n if (existing) {\n return existing;\n }\n\n const instrumented = instrumentFn(original);\n\n if (!noMark) {\n markAsInstrumented(original, instrumented);\n }\n\n return instrumented;\n}\n"],"names":[],"mappings":";;AAKA,MAAM,UAAA,GAAa,6BAAA;AAGnB,SAAS,kBAAA,GAAwC;AAE/C,EAAA,MAAM,SAAA,GAAY,UAAA;AAClB,EAAA,IAAI,CAAC,SAAA,CAAU,UAAU,CAAA,EAAG;AAC1B,IAAA,SAAA,CAAU,UAAU,CAAA,mBAAI,IAAI,OAAA,EAAQ;AAAA,EACtC;AACA,EAAA,OAAO,UAAU,UAAU,CAAA;AAC7B;AAMA,SAAS,aAAa,KAAA,EAAiC;AACrD,EAAA,OAAQ,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,IAAA,IAAS,OAAO,KAAA,KAAU,UAAA;AAC3E;AAOO,SAAS,kBAAA,CAAsB,UAAa,YAAA,EAAwB;AACzE,EAAA,IAAI;AACF,IAAA,IAAI,YAAA,CAAa,QAAQ,CAAA,EAAG;AAG1B,MAAA,kBAAA,EAAmB,CAAE,GAAA,CAAI,QAAA,EAAU,YAAA,IAAgB,QAAQ,CAAA;AAAA,IAC7D;AAEA,IAAA,IAAI,YAAA,CAAa,YAAY,CAAA,IAAK,YAAA,KAAiB,QAAA,EAAU;AAC3D,MAAA,kBAAA,EAAmB,CAAE,GAAA,CAAI,YAAA,EAAc,YAAY,CAAA;AAAA,IACrD;AAAA,EACF,CAAA,CAAA,MAAQ;AAAA,EAER;AACF;AAOO,SAAS,gBAAmB,GAAA,EAAuB;AACxD,EAAA,IAAI;AACF,IAAA,IAAI,YAAA,CAAa,GAAG,CAAA,EAAG;AACrB,MAAA,OAAO,kBAAA,EAAmB,CAAE,GAAA,CAAI,GAAG,CAAA;AAAA,IACrC;AAEA,IAAA,OAAO,KAAA,CAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAQO,SAAS,kBAAA,CAAsB,QAAA,EAAa,YAAA,EAAkC,MAAA,EAAqB;AACxG,EAAA,MAAM,QAAA,GAAW,gBAAgB,QAAQ,CAAA;AAEzC,EAAA,IAAI,QAAA,EAAU;AACZ,IAAA,OAAO,QAAA;AAAA,EACT;AAEA,EAAA,MAAM,YAAA,GAAe,aAAa,QAAQ,CAAA;AAE1C,EAAA,IAAI,CAAC,MAAA,EAAQ;AACX,IAAA,kBAAA,CAAmB,UAAU,YAAY,CAAA;AAAA,EAC3C;AAEA,EAAA,OAAO,YAAA;AACT;;;;;;"}
1
+ {"version":3,"file":"instrument.js","sources":["../../src/instrument.ts"],"sourcesContent":["// Use a global WeakMap to track instrumented objects across module instances.\n// This is important for Cloudflare Workers where the module may be bundled\n// separately for workers and Durable Objects, but they share the same global scope.\n// The WeakMap stores original -> instrumented mappings so we can retrieve the\n// instrumented version even if we only have a reference to the original.\nimport { isObjectLike } from '@sentry/core';\n\nconst GLOBAL_KEY = '__SENTRY_INSTRUMENTED_MAP__' as const;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getInstrumentedMap(): WeakMap<any, any> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const globalObj = globalThis as typeof globalThis & { [GLOBAL_KEY]?: WeakMap<any, any> };\n if (!globalObj[GLOBAL_KEY]) {\n globalObj[GLOBAL_KEY] = new WeakMap();\n }\n return globalObj[GLOBAL_KEY];\n}\n\n/**\n * Check if a value can be used as a WeakMap key.\n * WeakMap keys must be objects or non-registered symbols.\n */\nfunction isWeakMapKey(value: unknown): value is object {\n return isObjectLike(value) || typeof value === 'function';\n}\n\n/**\n * Mark an object as instrumented, storing the instrumented version.\n * @param original The original uninstrumented object\n * @param instrumented The instrumented version (defaults to original if not provided)\n */\nexport function markAsInstrumented<T>(original: T, instrumented?: T): void {\n try {\n if (isWeakMapKey(original)) {\n // Store mapping from original to instrumented version\n // If instrumented is not provided, store original (for backwards compat)\n getInstrumentedMap().set(original, instrumented ?? original);\n }\n // Also mark the instrumented version itself so we recognize it\n if (isWeakMapKey(instrumented) && instrumented !== original) {\n getInstrumentedMap().set(instrumented, instrumented);\n }\n } catch {\n // ignore errors here\n }\n}\n\n/**\n * Get the instrumented version of an object, if available.\n * Returns the instrumented version if the object was previously instrumented,\n * or undefined if not found.\n */\nexport function getInstrumented<T>(obj: T): T | undefined {\n try {\n if (isWeakMapKey(obj)) {\n return getInstrumentedMap().get(obj) as T | undefined;\n }\n\n return undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Returns the already-instrumented version of `original` if one exists,\n * otherwise calls `instrumentFn` to create it, marks the mapping, and returns it.\n *\n * @param noMark - If true, skips storing the original→instrumented mapping.\n */\nexport function ensureInstrumented<T>(original: T, instrumentFn: (original: T) => T, noMark?: boolean): T {\n const existing = getInstrumented(original);\n\n if (existing) {\n return existing;\n }\n\n const instrumented = instrumentFn(original);\n\n if (!noMark) {\n markAsInstrumented(original, instrumented);\n }\n\n return instrumented;\n}\n"],"names":["isObjectLike"],"mappings":";;;;AAOA,MAAM,UAAA,GAAa,6BAAA;AAGnB,SAAS,kBAAA,GAAwC;AAE/C,EAAA,MAAM,SAAA,GAAY,UAAA;AAClB,EAAA,IAAI,CAAC,SAAA,CAAU,UAAU,CAAA,EAAG;AAC1B,IAAA,SAAA,CAAU,UAAU,CAAA,mBAAI,IAAI,OAAA,EAAQ;AAAA,EACtC;AACA,EAAA,OAAO,UAAU,UAAU,CAAA;AAC7B;AAMA,SAAS,aAAa,KAAA,EAAiC;AACrD,EAAA,OAAOA,iBAAA,CAAa,KAAK,CAAA,IAAK,OAAO,KAAA,KAAU,UAAA;AACjD;AAOO,SAAS,kBAAA,CAAsB,UAAa,YAAA,EAAwB;AACzE,EAAA,IAAI;AACF,IAAA,IAAI,YAAA,CAAa,QAAQ,CAAA,EAAG;AAG1B,MAAA,kBAAA,EAAmB,CAAE,GAAA,CAAI,QAAA,EAAU,YAAA,IAAgB,QAAQ,CAAA;AAAA,IAC7D;AAEA,IAAA,IAAI,YAAA,CAAa,YAAY,CAAA,IAAK,YAAA,KAAiB,QAAA,EAAU;AAC3D,MAAA,kBAAA,EAAmB,CAAE,GAAA,CAAI,YAAA,EAAc,YAAY,CAAA;AAAA,IACrD;AAAA,EACF,CAAA,CAAA,MAAQ;AAAA,EAER;AACF;AAOO,SAAS,gBAAmB,GAAA,EAAuB;AACxD,EAAA,IAAI;AACF,IAAA,IAAI,YAAA,CAAa,GAAG,CAAA,EAAG;AACrB,MAAA,OAAO,kBAAA,EAAmB,CAAE,GAAA,CAAI,GAAG,CAAA;AAAA,IACrC;AAEA,IAAA,OAAO,KAAA,CAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAQO,SAAS,kBAAA,CAAsB,QAAA,EAAa,YAAA,EAAkC,MAAA,EAAqB;AACxG,EAAA,MAAM,QAAA,GAAW,gBAAgB,QAAQ,CAAA;AAEzC,EAAA,IAAI,QAAA,EAAU;AACZ,IAAA,OAAO,QAAA;AAAA,EACT;AAEA,EAAA,MAAM,YAAA,GAAe,aAAa,QAAQ,CAAA;AAE1C,EAAA,IAAI,CAAC,MAAA,EAAQ;AACX,IAAA,kBAAA,CAAmB,UAAU,YAAY,CAAA;AAAA,EAC3C;AAEA,EAAA,OAAO,YAAA;AACT;;;;;;"}
@@ -1,5 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
 
3
+ const core = require('@sentry/core');
3
4
  const isBinding = require('../../utils/isBinding.js');
4
5
  const instrumentD1 = require('./instrumentD1.js');
5
6
  const rpcMeta = require('../../utils/rpcMeta.js');
@@ -10,7 +11,7 @@ const instrumentQueueProducer = require('./instrumentQueueProducer.js');
10
11
  const instrumentR2 = require('./instrumentR2.js');
11
12
 
12
13
  function isProxyable(item) {
13
- return item !== null && (typeof item === "object" || typeof item === "function");
14
+ return core.isObjectLike(item) || typeof item === "function";
14
15
  }
15
16
  const instrumentedBindings = /* @__PURE__ */ new WeakMap();
16
17
  function instrumentEnv(env, options) {
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentEnv.js","sources":["../../../../src/instrumentations/worker/instrumentEnv.ts"],"sourcesContent":["import type { CloudflareOptions } from '../../client';\nimport { isD1Database, isDurableObjectNamespace, isJSRPC, isQueue, isR2Bucket } from '../../utils/isBinding';\nimport { instrumentD1 } from './instrumentD1';\nimport { appendRpcMeta } from '../../utils/rpcMeta';\nimport { getEffectiveRpcPropagation } from '../../utils/rpcOptions';\nimport { instrumentDurableObjectNamespace, STUB_NON_RPC_METHODS } from '../instrumentDurableObjectNamespace';\nimport { instrumentFetcher } from './instrumentFetcher';\nimport { instrumentQueueProducer } from './instrumentQueueProducer';\nimport { instrumentR2Bucket } from './instrumentR2';\n\nfunction isProxyable(item: unknown): item is object {\n return item !== null && (typeof item === 'object' || typeof item === 'function');\n}\n\nconst instrumentedBindings = new WeakMap<object, unknown>();\n\n/**\n * Wraps the Cloudflare `env` object in a Proxy that detects binding types\n * on property access and returns instrumented versions.\n *\n * Currently detects:\n * - DurableObjectNamespace (via `idFromName` duck-typing)\n * - Service bindings / JSRPC proxies\n * - Queue producers (via `send` + `sendBatch` duck-typing)\n * - R2 Buckets (via `head` + `put` + `createMultipartUpload` duck-typing)\n *\n * @param env - The Cloudflare env object to instrument\n * @param options - Optional CloudflareOptions to control RPC trace propagation\n */\nexport function instrumentEnv<Env extends Record<string, unknown>>(env: Env, options?: CloudflareOptions): Env {\n if (!env || typeof env !== 'object') {\n return env;\n }\n\n const rpcPropagation = options ? getEffectiveRpcPropagation(options) : false;\n\n return new Proxy(env, {\n get(target, prop, receiver) {\n const item = Reflect.get(target, prop, receiver);\n\n if (!isProxyable(item)) {\n return item;\n }\n\n const cached = instrumentedBindings.get(item);\n\n if (cached) {\n return cached;\n }\n\n if (isD1Database(item)) {\n const instrumented = instrumentD1(item);\n instrumentedBindings.set(item, instrumented);\n return instrumented;\n }\n\n if (isQueue(item)) {\n const bindingName = typeof prop === 'string' ? prop : String(prop);\n const instrumented = instrumentQueueProducer(item, bindingName);\n instrumentedBindings.set(item, instrumented);\n return instrumented;\n }\n\n if (isR2Bucket(item)) {\n const bindingName = typeof prop === 'string' ? prop : String(prop);\n const instrumented = instrumentR2Bucket(item, bindingName);\n instrumentedBindings.set(item, instrumented);\n return instrumented;\n }\n\n if (!rpcPropagation) {\n return item;\n }\n\n if (isDurableObjectNamespace(item)) {\n const instrumented = instrumentDurableObjectNamespace(item);\n instrumentedBindings.set(item, instrumented);\n return instrumented;\n }\n\n if (isJSRPC(item)) {\n const instrumented = new Proxy(item, {\n get(target, p) {\n const value = Reflect.get(target, p);\n\n if (p === 'fetch' && typeof value === 'function') {\n return instrumentFetcher((...args) => Reflect.apply(value, target, args));\n }\n\n if (typeof value === 'function' && typeof p === 'string' && !STUB_NON_RPC_METHODS.has(p)) {\n return (...args: unknown[]) => Reflect.apply(value, target, appendRpcMeta(args));\n }\n\n return value;\n },\n });\n\n instrumentedBindings.set(item, instrumented);\n return instrumented;\n }\n\n return item;\n },\n });\n}\n"],"names":["getEffectiveRpcPropagation","isD1Database","instrumentD1","isQueue","instrumentQueueProducer","isR2Bucket","instrumentR2Bucket","isDurableObjectNamespace","instrumentDurableObjectNamespace","isJSRPC","target","instrumentFetcher","STUB_NON_RPC_METHODS","appendRpcMeta"],"mappings":";;;;;;;;;;;AAUA,SAAS,YAAY,IAAA,EAA+B;AAClD,EAAA,OAAO,SAAS,IAAA,KAAS,OAAO,IAAA,KAAS,QAAA,IAAY,OAAO,IAAA,KAAS,UAAA,CAAA;AACvE;AAEA,MAAM,oBAAA,uBAA2B,OAAA,EAAyB;AAenD,SAAS,aAAA,CAAmD,KAAU,OAAA,EAAkC;AAC7G,EAAA,IAAI,CAAC,GAAA,IAAO,OAAO,GAAA,KAAQ,QAAA,EAAU;AACnC,IAAA,OAAO,GAAA;AAAA,EACT;AAEA,EAAA,MAAM,cAAA,GAAiB,OAAA,G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instrumentations/worker/instrumentEnv.ts"],"sourcesContent":["import { isObjectLike } from '@sentry/core';\nimport type { CloudflareOptions } from '../../client';\nimport { isD1Database, isDurableObjectNamespace, isJSRPC, isQueue, isR2Bucket } from '../../utils/isBinding';\nimport { instrumentD1 } from './instrumentD1';\nimport { appendRpcMeta } from '../../utils/rpcMeta';\nimport { getEffectiveRpcPropagation } from '../../utils/rpcOptions';\nimport { instrumentDurableObjectNamespace, STUB_NON_RPC_METHODS } from '../instrumentDurableObjectNamespace';\nimport { instrumentFetcher } from './instrumentFetcher';\nimport { instrumentQueueProducer } from './instrumentQueueProducer';\nimport { instrumentR2Bucket } from './instrumentR2';\n\nfunction isProxyable(item: unknown): item is object {\n return isObjectLike(item) || typeof item === 'function';\n}\n\nconst instrumentedBindings = new WeakMap<object, unknown>();\n\n/**\n * Wraps the Cloudflare `env` object in a Proxy that detects binding types\n * on property access and returns instrumented versions.\n *\n * Currently detects:\n * - DurableObjectNamespace (via `idFromName` duck-typing)\n * - Service bindings / JSRPC proxies\n * - Queue producers (via `send` + `sendBatch` duck-typing)\n * - R2 Buckets (via `head` + `put` + `createMultipartUpload` duck-typing)\n *\n * @param env - The Cloudflare env object to instrument\n * @param options - Optional CloudflareOptions to control RPC trace propagation\n */\nexport function instrumentEnv<Env extends Record<string, unknown>>(env: Env, options?: CloudflareOptions): Env {\n if (!env || typeof env !== 'object') {\n return env;\n }\n\n const rpcPropagation = options ? getEffectiveRpcPropagation(options) : false;\n\n return new Proxy(env, {\n get(target, prop, receiver) {\n const item = Reflect.get(target, prop, receiver);\n\n if (!isProxyable(item)) {\n return item;\n }\n\n const cached = instrumentedBindings.get(item);\n\n if (cached) {\n return cached;\n }\n\n if (isD1Database(item)) {\n const instrumented = instrumentD1(item);\n instrumentedBindings.set(item, instrumented);\n return instrumented;\n }\n\n if (isQueue(item)) {\n const bindingName = typeof prop === 'string' ? prop : String(prop);\n const instrumented = instrumentQueueProducer(item, bindingName);\n instrumentedBindings.set(item, instrumented);\n return instrumented;\n }\n\n if (isR2Bucket(item)) {\n const bindingName = typeof prop === 'string' ? prop : String(prop);\n const instrumented = instrumentR2Bucket(item, bindingName);\n instrumentedBindings.set(item, instrumented);\n return instrumented;\n }\n\n if (!rpcPropagation) {\n return item;\n }\n\n if (isDurableObjectNamespace(item)) {\n const instrumented = instrumentDurableObjectNamespace(item);\n instrumentedBindings.set(item, instrumented);\n return instrumented;\n }\n\n if (isJSRPC(item)) {\n const instrumented = new Proxy(item, {\n get(target, p) {\n const value = Reflect.get(target, p);\n\n if (p === 'fetch' && typeof value === 'function') {\n return instrumentFetcher((...args) => Reflect.apply(value, target, args));\n }\n\n if (typeof value === 'function' && typeof p === 'string' && !STUB_NON_RPC_METHODS.has(p)) {\n return (...args: unknown[]) => Reflect.apply(value, target, appendRpcMeta(args));\n }\n\n return value;\n },\n });\n\n instrumentedBindings.set(item, instrumented);\n return instrumented;\n }\n\n return item;\n },\n });\n}\n"],"names":["isObjectLike","getEffectiveRpcPropagation","isD1Database","instrumentD1","isQueue","instrumentQueueProducer","isR2Bucket","instrumentR2Bucket","isDurableObjectNamespace","instrumentDurableObjectNamespace","isJSRPC","target","instrumentFetcher","STUB_NON_RPC_METHODS","appendRpcMeta"],"mappings":";;;;;;;;;;;;AAWA,SAAS,YAAY,IAAA,EAA+B;AAClD,EAAA,OAAOA,iBAAA,CAAa,IAAI,CAAA,IAAK,OAAO,IAAA,KAAS,UAAA;AAC/C;AAEA,MAAM,oBAAA,uBAA2B,OAAA,EAAyB;AAenD,SAAS,aAAA,CAAmD,KAAU,OAAA,EAAkC;AAC7G,EAAA,IAAI,CAAC,GAAA,IAAO,OAAO,GAAA,KAAQ,QAAA,EAAU;AACnC,IAAA,OAAO,GAAA;AAAA,EACT;AAEA,EAAA,MAAM,cAAA,GAAiB,OAAA,GAAUC,qCAAA,CAA2B,OAAO,CAAA,GAAI,KAAA;AAEvE,EAAA,OAAO,IAAI,MAAM,GAAA,EAAK;AAAA,IACpB,GAAA,CAAI,M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kCAAA,CAAyB,IAAI,CAAA,EAAG;AAClC,QAAA,MAAM,YAAA,GAAeC,kEAAiC,IAAI,CAAA;AAC1D,QAAA,oBAAA,CAAqB,GAAA,CAAI,MAAM,YAAY,CAAA;AAC3C,QAAA,OAAO,YAAA;AAAA,MACT;AAEA,MAAA,IAAIC,iBAAA,CAAQ,IAAI,CAAA,EAAG;AACjB,QAAA,MAAM,YAAA,GAAe,IAAI,KAAA,CAAM,IAAA,EAAM;AAAA,UACnC,GAAA,CAAIC,SAAQ,CAAA,EAAG;AACb,YAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,GAAA,CAAIA,OAAAA,EAAQ,CAAC,CAAA;AAEnC,YAAA,IAAI,CAAA,KAAM,OAAA,IAAW,OAAO,KAAA,KAAU,UAAA,EAAY;AAChD,cAAA,OAAOC,mCAAA,CAAkB,IAAI,IAAA,KAAS,OAAA,CAAQ,MAAM,KAAA,EAAOD,OAAAA,EAAQ,IAAI,CAAC,CAAA;AAAA,YAC1E;AAEA,YAAA,IAAI,OAAO,KAAA,KAAU,UAAA,IAAc,OAAO,CAAA,KAAM,YAAY,CAACE,qDAAA,CAAqB,GAAA,CAAI,CAAC,CAAA,EAAG;AACxF,cAAA,OAAO,CAAA,GAAI,SAAoB,OAAA,CAAQ,KAAA,CAAM,OAAOF,OAAAA,EAAQG,qBAAA,CAAc,IAAI,CAAC,CAAA;AAAA,YACjF;AAEA,YAAA,OAAO,KAAA;AAAA,UACT;AAAA,SACD,CAAA;AAED,QAAA,oBAAA,CAAqB,GAAA,CAAI,MAAM,YAAY,CAAA;AAC3C,QAAA,OAAO,YAAA;AAAA,MACT;AAEA,MAAA,OAAO,IAAA;AAAA,IACT;AAAA,GACD,CAAA;AACH;;;;"}
@@ -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 { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, 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 op: 'queue.publish',\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 ...(messageCount !== undefined && { 'messaging.batch.message_count': messageCount }),\n 'messaging.message.body.size': bodySize,\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'queue.publish',\n [SEMANTIC_ATTRIBUTE_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): Promise<void> {\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 ): Promise<void> {\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 return Reflect.get(target, prop, receiver);\n },\n });\n}\n"],"names":["startSpan","SEMANTIC_ATTRIBUTE_SENTRY_OP","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN"],"mappings":";;;;AAGA,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,EAAA,EAAI,eAAA;AAAA,MACJ,IAAA,EAAM,QAAQ,WAAW,CAAA,CAAA;AAAA,MACzB,UAAA,EAAY;AAAA,QACV,kBAAA,EAAoB,YAAA;AAAA,QACpB,4BAAA,EAA8B,WAAA;AAAA,QAC9B,0BAAA,EAA4B,MAAA;AAAA,QAC5B,0BAAA,EAA4B,MAAA;AAAA,QAC5B,GAAI,YAAA,KAAiB,MAAA,IAAa,EAAE,iCAAiC,YAAA,EAAa;AAAA,QAClF,6BAAA,EAA+B,QAAA;AAAA,QAC/B,CAACC,iCAA4B,GAAG,eAAA;AAAA,QAChC,CAACC,qCAAgC,GAAG;AAAA;AACtC,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,SAAS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M,IAAA,CAAK,QAAQ,CAAA;AACxC,UAAA,MAAM,aAAA,GAAgB,YAAA,CAAa,MAAA,CAA2B,CAAC,KAAK,CAAA,KAAM;AACxE,YAAA,MAAM,IAAA,GAAO,WAAA,CAAY,CAAA,CAAE,IAAI,CAAA;AAC/B,YAAA,IAAI,SAAS,MAAA,EAAW;AACtB,cAAA,OAAO,GAAA;AAAA,YACT;AACA,YAAA,OAAA,CAAQ,OAAO,CAAA,IAAK,IAAA;AAAA,UACtB,GAAG,MAAS,CAAA;AAEZ,UAAA,OAAO,gBAAA;AAAA,YAAiB,EAAE,WAAA,EAAa,QAAA,EAAU,aAAA,EAAe,YAAA,EAAc,aAAa,MAAA,EAAO;AAAA,YAAG,MACnG,QAAQ,KAAA,CAAM,QAAA,EAAU,QAAQ,CAAC,YAAA,EAAc,OAAO,CAAC;AAAA,WACzD;AAAA,QACF,CAAA;AAAA,MACF;AAEA,MAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,IAAA,EAAM,QAAQ,CAAA;AAAA,IAC3C;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 { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, 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 op: 'queue.publish',\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 ...(messageCount !== undefined && { 'messaging.batch.message_count': messageCount }),\n 'messaging.message.body.size': bodySize,\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'queue.publish',\n [SEMANTIC_ATTRIBUTE_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 return Reflect.get(target, prop, receiver);\n },\n });\n}\n"],"names":["startSp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,QAAA,EAAU,aAAA,EAAe,YAAA,EAAc,aAAa,MAAA,EAAO;AAAA,YAAG,MACnG,QAAQ,KAAA,CAAM,QAAA,EAAU,QAAQ,CAAC,YAAA,EAAc,OAAO,CAAC;AAAA,WACzD;AAAA,QACF,CAAA;AAAA,MACF;AAEA,MAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,IAAA,EAAM,QAAQ,CAAA;AAAA,IAC3C;AAAA,GACD,CAAA;AACH;;;;"}
@@ -27,7 +27,7 @@ const R2_OPERATIONS = {
27
27
  }
28
28
  };
29
29
  function isR2ListOptions(key) {
30
- return typeof key === "object" && key !== null && !Array.isArray(key);
30
+ return core.isObjectLike(key) && !Array.isArray(key);
31
31
  }
32
32
  function createSpanOptions(bindingName, r2Op, key) {
33
33
  const { spanName, op, operation } = R2_OPERATIONS[r2Op];
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentR2.js","sources":["../../../../src/instrumentations/worker/instrumentR2.ts"],"sourcesContent":["import type { R2Bucket, R2ListOptions, R2MultipartUpload } from '@cloudflare/workers-types';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, startSpan } from '@sentry/core';\n\nconst ORIGIN = 'auto.faas.cloudflare.r2';\n\nconst R2_OPERATIONS = {\n get: { spanName: 'r2_get', op: 'object.get', operation: 'GetObject' },\n head: { spanName: 'r2_head', op: 'object.head', operation: 'HeadObject' },\n put: { spanName: 'r2_put', op: 'object.put', operation: 'PutObject' },\n delete: { spanName: 'r2_delete', op: 'object.delete', operation: 'DeleteObject' },\n list: { spanName: 'r2_list', op: 'object.list', operation: 'ListObjects' },\n uploadPart: { spanName: 'r2_uploadPart', op: 'object.upload_part', operation: 'UploadPart' },\n abortMultipartUpload: {\n spanName: 'r2_abortMultipartUpload',\n op: 'object.multipart_upload.abort',\n operation: 'AbortMultipartUpload',\n },\n createMultipartUpload: {\n spanName: 'r2_createMultipartUpload',\n op: 'object.multipart_upload.create',\n operation: 'CreateMultipartUpload',\n },\n completeMultipartUpload: {\n spanName: 'r2_completeMultipartUpload',\n op: 'object.multipart_upload.complete',\n operation: 'CompleteMultipartUpload',\n },\n} as const;\n\ntype R2OperationKey = keyof typeof R2_OPERATIONS;\n\nfunction isR2ListOptions(key: unknown): key is R2ListOptions {\n return typeof key === 'object' && key !== null && !Array.isArray(key);\n}\n\nfunction createSpanOptions(bindingName: string, r2Op: R2OperationKey, key?: string | string[] | R2ListOptions) {\n const { spanName, op, operation } = R2_OPERATIONS[r2Op];\n const requestKey = Array.isArray(key) ? key.join(', ') : typeof key === 'string' ? key : undefined;\n\n return {\n op,\n name: spanName,\n attributes: {\n 'cloudflare.r2.operation': operation,\n 'cloudflare.r2.bucket': bindingName,\n ...(requestKey !== undefined && { 'cloudflare.r2.request.key': requestKey }),\n ...(isR2ListOptions(key) && key.prefix !== undefined && { 'cloudflare.r2.request.prefix': key.prefix }),\n ...(isR2ListOptions(key) && key.delimiter !== undefined && { 'cloudflare.r2.request.delimiter': key.delimiter }),\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: op,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: ORIGIN,\n },\n };\n}\n\nfunction instrumentR2MultipartUpload(upload: R2MultipartUpload, bindingName: string): R2MultipartUpload {\n const { key } = upload;\n\n return new Proxy(upload, {\n get(target, prop, receiver) {\n if (prop === 'uploadPart') {\n const original = Reflect.get(target, prop, receiver);\n\n return function (this: unknown, ...args: Parameters<R2MultipartUpload['uploadPart']>) {\n const [partNumber] = args;\n\n return startSpan(\n {\n ...createSpanOptions(bindingName, 'uploadPart', key),\n attributes: {\n ...createSpanOptions(bindingName, 'uploadPart', key).attributes,\n 'cloudflare.r2.request.part_number': partNumber,\n },\n },\n () => Reflect.apply(original, target, args),\n );\n };\n }\n\n if (prop === 'abort') {\n const original = Reflect.get(target, prop, receiver);\n\n return function (this: unknown) {\n return startSpan(createSpanOptions(bindingName, 'abortMultipartUpload', key), () =>\n Reflect.apply(original, target, []),\n );\n };\n }\n\n if (prop === 'complete') {\n const original = Reflect.get(target, prop, receiver);\n\n return function (this: unknown, ...args: Parameters<R2MultipartUpload['complete']>) {\n return startSpan(createSpanOptions(bindingName, 'completeMultipartUpload', key), () =>\n Reflect.apply(original, target, args),\n );\n };\n }\n\n return Reflect.get(target, prop, receiver);\n },\n });\n}\n\n/**\n * Wraps a Cloudflare R2 Bucket binding to create spans on bucket operations.\n *\n * Instrumented methods: get, head, put, delete, list, createMultipartUpload,\n * resumeMultipartUpload (and the resulting multipart upload operations).\n */\nexport function instrumentR2Bucket<T extends R2Bucket>(bucket: T, bindingName: string): T {\n return new Proxy(bucket, {\n get(target, prop, receiver) {\n if (prop === 'get' || prop === 'head' || prop === 'put' || prop === 'delete' || prop === 'list') {\n const original = Reflect.get(target, prop, receiver);\n\n return function (this: unknown, ...args: Parameters<R2Bucket[typeof prop]>) {\n const [key] = args;\n\n return startSpan(createSpanOptions(bindingName, prop, key), () => Reflect.apply(original, target, args));\n };\n }\n\n if (prop === 'createMultipartUpload') {\n const original = Reflect.get(target, prop, receiver) as R2Bucket['createMultipartUpload'];\n\n return function (this: unknown, ...args: Parameters<R2Bucket['createMultipartUpload']>) {\n const [key] = args;\n\n return startSpan(createSpanOptions(bindingName, 'createMultipartUpload', key), async () => {\n const upload = await Reflect.apply(original, target, args);\n return instrumentR2MultipartUpload(upload, bindingName);\n });\n };\n }\n\n if (prop === 'resumeMultipartUpload') {\n const original = Reflect.get(target, prop, receiver);\n\n return function (this: unknown, ...args: Parameters<R2Bucket['resumeMultipartUpload']>) {\n const upload = Reflect.apply(original, target, args);\n\n return instrumentR2MultipartUpload(upload, bindingName);\n };\n }\n\n return Reflect.get(target, prop, receiver);\n },\n });\n}\n"],"names":["SEMANTIC_ATTRIBUTE_SENTRY_OP","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","startSpan"],"mappings":";;;;AAGA,MAAM,MAAA,GAAS,yBAAA;AAEf,M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D,UAAA,OAAO,2BAAA,CAA4B,QAAQ,WAAW,CAAA;AAAA,QACxD,CAAA;AAAA,MACF;AAEA,MAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,IAAA,EAAM,QAAQ,CAAA;AAAA,IAC3C;AAAA,GACD,CAAA;AACH;;;;"}
1
+ {"version":3,"file":"instrumentR2.js","sources":["../../../../src/instrumentations/worker/instrumentR2.ts"],"sourcesContent":["import type { R2Bucket, R2ListOptions, R2MultipartUpload } from '@cloudflare/workers-types';\nimport { isObjectLike, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, startSpan } from '@sentry/core';\n\nconst ORIGIN = 'auto.faas.cloudflare.r2';\n\nconst R2_OPERATIONS = {\n get: { spanName: 'r2_get', op: 'object.get', operation: 'GetObject' },\n head: { spanName: 'r2_head', op: 'object.head', operation: 'HeadObject' },\n put: { spanName: 'r2_put', op: 'object.put', operation: 'PutObject' },\n delete: { spanName: 'r2_delete', op: 'object.delete', operation: 'DeleteObject' },\n list: { spanName: 'r2_list', op: 'object.list', operation: 'ListObjects' },\n uploadPart: { spanName: 'r2_uploadPart', op: 'object.upload_part', operation: 'UploadPart' },\n abortMultipartUpload: {\n spanName: 'r2_abortMultipartUpload',\n op: 'object.multipart_upload.abort',\n operation: 'AbortMultipartUpload',\n },\n createMultipartUpload: {\n spanName: 'r2_createMultipartUpload',\n op: 'object.multipart_upload.create',\n operation: 'CreateMultipartUpload',\n },\n completeMultipartUpload: {\n spanName: 'r2_completeMultipartUpload',\n op: 'object.multipart_upload.complete',\n operation: 'CompleteMultipartUpload',\n },\n} as const;\n\ntype R2OperationKey = keyof typeof R2_OPERATIONS;\n\nfunction isR2ListOptions(key: unknown): key is R2ListOptions {\n return isObjectLike(key) && !Array.isArray(key);\n}\n\nfunction createSpanOptions(bindingName: string, r2Op: R2OperationKey, key?: string | string[] | R2ListOptions) {\n const { spanName, op, operation } = R2_OPERATIONS[r2Op];\n const requestKey = Array.isArray(key) ? key.join(', ') : typeof key === 'string' ? key : undefined;\n\n return {\n op,\n name: spanName,\n attributes: {\n 'cloudflare.r2.operation': operation,\n 'cloudflare.r2.bucket': bindingName,\n ...(requestKey !== undefined && { 'cloudflare.r2.request.key': requestKey }),\n ...(isR2ListOptions(key) && key.prefix !== undefined && { 'cloudflare.r2.request.prefix': key.prefix }),\n ...(isR2ListOptions(key) && key.delimiter !== undefined && { 'cloudflare.r2.request.delimiter': key.delimiter }),\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: op,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: ORIGIN,\n },\n };\n}\n\nfunction instrumentR2MultipartUpload(upload: R2MultipartUpload, bindingName: string): R2MultipartUpload {\n const { key } = upload;\n\n return new Proxy(upload, {\n get(target, prop, receiver) {\n if (prop === 'uploadPart') {\n const original = Reflect.get(target, prop, receiver);\n\n return function (this: unknown, ...args: Parameters<R2MultipartUpload['uploadPart']>) {\n const [partNumber] = args;\n\n return startSpan(\n {\n ...createSpanOptions(bindingName, 'uploadPart', key),\n attributes: {\n ...createSpanOptions(bindingName, 'uploadPart', key).attributes,\n 'cloudflare.r2.request.part_number': partNumber,\n },\n },\n () => Reflect.apply(original, target, args),\n );\n };\n }\n\n if (prop === 'abort') {\n const original = Reflect.get(target, prop, receiver);\n\n return function (this: unknown) {\n return startSpan(createSpanOptions(bindingName, 'abortMultipartUpload', key), () =>\n Reflect.apply(original, target, []),\n );\n };\n }\n\n if (prop === 'complete') {\n const original = Reflect.get(target, prop, receiver);\n\n return function (this: unknown, ...args: Parameters<R2MultipartUpload['complete']>) {\n return startSpan(createSpanOptions(bindingName, 'completeMultipartUpload', key), () =>\n Reflect.apply(original, target, args),\n );\n };\n }\n\n return Reflect.get(target, prop, receiver);\n },\n });\n}\n\n/**\n * Wraps a Cloudflare R2 Bucket binding to create spans on bucket operations.\n *\n * Instrumented methods: get, head, put, delete, list, createMultipartUpload,\n * resumeMultipartUpload (and the resulting multipart upload operations).\n */\nexport function instrumentR2Bucket<T extends R2Bucket>(bucket: T, bindingName: string): T {\n return new Proxy(bucket, {\n get(target, prop, receiver) {\n if (prop === 'get' || prop === 'head' || prop === 'put' || prop === 'delete' || prop === 'list') {\n const original = Reflect.get(target, prop, receiver);\n\n return function (this: unknown, ...args: Parameters<R2Bucket[typeof prop]>) {\n const [key] = args;\n\n return startSpan(createSpanOptions(bindingName, prop, key), () => Reflect.apply(original, target, args));\n };\n }\n\n if (prop === 'createMultipartUpload') {\n const original = Reflect.get(target, prop, receiver) as R2Bucket['createMultipartUpload'];\n\n return function (this: unknown, ...args: Parameters<R2Bucket['createMultipartUpload']>) {\n const [key] = args;\n\n return startSpan(createSpanOptions(bindingName, 'createMultipartUpload', key), async () => {\n const upload = await Reflect.apply(original, target, args);\n return instrumentR2MultipartUpload(upload, bindingName);\n });\n };\n }\n\n if (prop === 'resumeMultipartUpload') {\n const original = Reflect.get(target, prop, receiver);\n\n return function (this: unknown, ...args: Parameters<R2Bucket['resumeMultipartUpload']>) {\n const upload = Reflect.apply(original, target, args);\n\n return instrumentR2MultipartUpload(upload, bindingName);\n };\n }\n\n return Reflect.get(target, prop, receiver);\n },\n });\n}\n"],"names":["isObjectLike","SEMANTIC_ATTRIBUTE_SENTRY_OP","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","startSpan"],"mappings":";;;;AAGA,MAAM,MAAA,GAAS,yBAAA;AAEf,MAAM,aAAA,GAAgB;AAAA,EACpB,KAAK,EAAE,QAAA,EAAU,UAAU,EAAA,EAAI,YAAA,EAAc,WAAW,WAAA,EAAY;AAAA,EACpE,MAAM,EAAE,QAAA,EAAU,WAAW,EAAA,EAAI,aAAA,EAAe,WAAW,YAAA,EAAa;AAAA,EACxE,KAAK,EAAE,QAAA,EAAU,UAAU,EAAA,EAAI,YAAA,EAAc,WAAW,WAAA,EAAY;AAAA,EACpE,QAAQ,EAAE,QAAA,EAAU,aAAa,EAAA,EAAI,eAAA,EA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AAA,EAAM,GAAG,CAAA,EAAG,MAAM,OAAA,CAAQ,KAAA,CAAM,QAAA,EAAU,MAAA,EAAQ,IAAI,CAAC,CAAA;AAAA,QACzG,CAAA;AAAA,MACF;AAEA,MAAA,IAAI,SAAS,uBAAA,EAAyB;AACpC,QAAA,MAAM,QAAA,GAAW,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,MAAM,QAAQ,CAAA;AAEnD,QAAA,OAAO,YAA4B,IAAA,EAAqD;AACtF,UAAA,MAAM,CAAC,GAAG,CAAA,GAAI,IAAA;AAEd,UAAA,OAAOA,eAAU,iBAAA,CAAkB,WAAA,EAAa,uBAAA,EAAyB,GAAG,GAAG,YAAY;AACzF,YAAA,MAAM,SAAS,MAAM,OAAA,CAAQ,KAAA,CAAM,QAAA,EAAU,QAAQ,IAAI,CAAA;AACzD,YAAA,OAAO,2BAAA,CAA4B,QAAQ,WAAW,CAAA;AAAA,UACxD,CAAC,CAAA;AAAA,QACH,CAAA;AAAA,MACF;AAEA,MAAA,IAAI,SAAS,uBAAA,EAAyB;AACpC,QAAA,MAAM,QAAA,GAAW,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,MAAM,QAAQ,CAAA;AAEnD,QAAA,OAAO,YAA4B,IAAA,EAAqD;AACtF,UAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,KAAA,CAAM,QAAA,EAAU,QAAQ,IAAI,CAAA;AAEnD,UAAA,OAAO,2BAAA,CAA4B,QAAQ,WAAW,CAAA;AAAA,QACxD,CAAA;AAAA,MACF;AAEA,MAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,IAAA,EAAM,QAAQ,CAAA;AAAA,IAC3C;AAAA,GACD,CAAA;AACH;;;;"}
@@ -11,7 +11,7 @@ function isHonoError(err) {
11
11
  if (err instanceof Error) {
12
12
  return true;
13
13
  }
14
- return typeof err === "object" && err !== null && "status" in err;
14
+ return core.isObjectLike(err) && "status" in err;
15
15
  }
16
16
  const routePath = (c) => c.req?.path ?? "";
17
17
  const _honoIntegration = ((options = {}) => {
@@ -1 +1 @@
1
- {"version":3,"file":"hono.js","sources":["../../../src/integrations/hono.ts"],"sourcesContent":["import type { IntegrationFn } from '@sentry/core';\nimport {\n captureException,\n debug,\n defineIntegration,\n getActiveSpan,\n getClient,\n getIsolationScope,\n getRootSpan,\n updateSpanName,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\n\nconst INTEGRATION_NAME = 'Hono' as const;\n\ninterface HonoError extends Error {\n status?: number;\n}\n\n// Minimal type - only exported for tests\nexport interface HonoContext {\n req: { method: string; path?: string };\n}\n\nexport interface Options {\n /**\n * Callback method deciding whether error should be captured and sent to Sentry\n * @param error Captured middleware error\n */\n shouldHandleError?(this: void, error: HonoError): boolean;\n}\n\n/** Only exported for internal use */\nexport function getHonoIntegration(): ReturnType<typeof _honoIntegration> | undefined {\n return getClient()?.getIntegrationByName(INTEGRATION_NAME);\n}\n\nfunction isHonoError(err: unknown): err is HonoError {\n if (err instanceof Error) {\n return true;\n }\n return typeof err === 'object' && err !== null && 'status' in (err as Record<string, unknown>);\n}\n\n// Vendored from https://github.com/honojs/hono/blob/d3abeb1f801aaa1b334285c73da5f5f022dbcadb/src/helper/route/index.ts#L58-L59\nconst routePath = (c: HonoContext): string => c.req?.path ?? '';\n\nconst _honoIntegration = ((options: Partial<Options> = {}) => {\n return {\n name: INTEGRATION_NAME,\n // Hono error handler: https://github.com/honojs/hono/blob/d3abeb1f801aaa1b334285c73da5f5f022dbcadb/src/hono-base.ts#L35\n handleHonoException(err: HonoError, context: HonoContext): void {\n const shouldHandleError = options.shouldHandleError || defaultShouldHandleError;\n\n if (!isHonoError(err)) {\n DEBUG_BUILD && debug.log(\"[Hono] Won't capture exception in `onError` because it's not a Hono error.\", err);\n return;\n }\n\n if (shouldHandleError(err)) {\n if (context) {\n const activeSpan = getActiveSpan();\n const spanName = `${context.req.method} ${routePath(context)}`;\n\n if (activeSpan) {\n activeSpan.updateName(spanName);\n updateSpanName(getRootSpan(activeSpan), spanName);\n }\n\n getIsolationScope().setTransactionName(spanName);\n }\n\n captureException(err, { mechanism: { handled: false, type: 'auto.faas.hono.error_handler' } });\n } else {\n DEBUG_BUILD && debug.log('[Hono] Not capturing exception because `shouldHandleError` returned `false`.', err);\n }\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Automatically captures exceptions caught with the `onError` handler in Hono.\n *\n * The integration is enabled by default.\n *\n * @deprecated Use the `@sentry/hono` package instead. The `sentry()` middleware from `@sentry/hono/cloudflare`\n * handles error capturing automatically without needing this integration.\n *\n * @example\n * integrations: [\n * honoIntegration({\n * shouldHandleError: (err) => true; // always capture exceptions in onError\n * })\n * ]\n */\nexport const honoIntegration = defineIntegration(_honoIntegration);\n\n/**\n * Default function to determine if an error should be sent to Sentry\n *\n * 3xx and 4xx errors are not sent by default.\n */\nfunction defaultShouldHandleError(error: HonoError): boolean {\n const statusCode = error?.status;\n // 3xx and 4xx errors are not sent by default.\n return statusCode ? statusCode >= 500 || statusCode <= 299 : true;\n}\n"],"names":["getClient","DEBUG_BUILD","debug","getActiveSpan","updateSpanName","getRootSpan","getIsolationScope","captureException","defineIntegration"],"mappings":";;;;;AAaA,MAAM,gBAAA,GAAmB,MAAA;AAoBlB,SAAS,kBAAA,GAAsE;AACpF,EAAA,OAAOA,cAAA,EAAU,EAAG,oBAAA,CAAqB,gBAAgB,CAAA;AAC3D;AAEA,SAAS,YAAY,GAAA,EAAgC;AACnD,EAAA,IAAI,eAAe,KAAA,EAAO;AACxB,IAAA,OAAO,IAAA;AAAA,EACT;AACA,EAAA,OAAO,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,KAAQ,QAAQ,QAAA,IAAa,GAAA;AACjE;AAGA,MAAM,SAAA,GAAY,CAAC,CAAA,KAA2B,CAAA,CAAE,KAAK,IAAA,IAAQ,EAAA;AAE7D,MAAM,gBAAA,IAAoB,CAAC,OAAA,GAA4B,EAAC,KAAM;AAC5D,EAAA,O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,IAAc,GAAA,GAAM,IAAA;AAC/D;;;;;"}
1
+ {"version":3,"file":"hono.js","sources":["../../../src/integrations/hono.ts"],"sourcesContent":["import type { IntegrationFn } from '@sentry/core';\nimport {\n isObjectLike,\n captureException,\n debug,\n defineIntegration,\n getActiveSpan,\n getClient,\n getIsolationScope,\n getRootSpan,\n updateSpanName,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\n\nconst INTEGRATION_NAME = 'Hono' as const;\n\ninterface HonoError extends Error {\n status?: number;\n}\n\n// Minimal type - only exported for tests\nexport interface HonoContext {\n req: { method: string; path?: string };\n}\n\nexport interface Options {\n /**\n * Callback method deciding whether error should be captured and sent to Sentry\n * @param error Captured middleware error\n */\n shouldHandleError?(this: void, error: HonoError): boolean;\n}\n\n/** Only exported for internal use */\nexport function getHonoIntegration(): ReturnType<typeof _honoIntegration> | undefined {\n return getClient()?.getIntegrationByName(INTEGRATION_NAME);\n}\n\nfunction isHonoError(err: unknown): err is HonoError {\n if (err instanceof Error) {\n return true;\n }\n return isObjectLike(err) && 'status' in (err as Record<string, unknown>);\n}\n\n// Vendored from https://github.com/honojs/hono/blob/d3abeb1f801aaa1b334285c73da5f5f022dbcadb/src/helper/route/index.ts#L58-L59\nconst routePath = (c: HonoContext): string => c.req?.path ?? '';\n\nconst _honoIntegration = ((options: Partial<Options> = {}) => {\n return {\n name: INTEGRATION_NAME,\n // Hono error handler: https://github.com/honojs/hono/blob/d3abeb1f801aaa1b334285c73da5f5f022dbcadb/src/hono-base.ts#L35\n handleHonoException(err: HonoError, context: HonoContext): void {\n const shouldHandleError = options.shouldHandleError || defaultShouldHandleError;\n\n if (!isHonoError(err)) {\n DEBUG_BUILD && debug.log(\"[Hono] Won't capture exception in `onError` because it's not a Hono error.\", err);\n return;\n }\n\n if (shouldHandleError(err)) {\n if (context) {\n const activeSpan = getActiveSpan();\n const spanName = `${context.req.method} ${routePath(context)}`;\n\n if (activeSpan) {\n activeSpan.updateName(spanName);\n updateSpanName(getRootSpan(activeSpan), spanName);\n }\n\n getIsolationScope().setTransactionName(spanName);\n }\n\n captureException(err, { mechanism: { handled: false, type: 'auto.faas.hono.error_handler' } });\n } else {\n DEBUG_BUILD && debug.log('[Hono] Not capturing exception because `shouldHandleError` returned `false`.', err);\n }\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Automatically captures exceptions caught with the `onError` handler in Hono.\n *\n * The integration is enabled by default.\n *\n * @deprecated Use the `@sentry/hono` package instead. The `sentry()` middleware from `@sentry/hono/cloudflare`\n * handles error capturing automatically without needing this integration.\n *\n * @example\n * integrations: [\n * honoIntegration({\n * shouldHandleError: (err) => true; // always capture exceptions in onError\n * })\n * ]\n */\nexport const honoIntegration = defineIntegration(_honoIntegration);\n\n/**\n * Default function to determine if an error should be sent to Sentry\n *\n * 3xx and 4xx errors are not sent by default.\n */\nfunction defaultShouldHandleError(error: HonoError): boolean {\n const statusCode = error?.status;\n // 3xx and 4xx errors are not sent by default.\n return statusCode ? statusCode >= 500 || statusCode <= 299 : true;\n}\n"],"names":["getClient","isObjectLike","DEBUG_BUILD","debug","getActiveSpan","updateSpanName","getRootSpan","getIsolationScope","captureException","defineIntegration"],"mappings":";;;;;AAcA,MAAM,gBAAA,GAAmB,MAAA;AAoBlB,SAAS,kBAAA,GAAsE;AACpF,EAAA,OAAOA,cAAA,EAAU,EAAG,oBAAA,CAAqB,gBAAgB,CAAA;AAC3D;AAEA,SAAS,YAAY,GAAA,EAAgC;AACnD,EAAA,IAAI,eAAe,KAAA,EAAO;AACxB,IAAA,OAAO,IAAA;AAAA,EACT;AACA,EAAA,OAAOC,iBAAA,CAAa,GAAG,CAAA,IAAK,QAAA,IAAa,GAAA;AAC3C;AAGA,MAAM,SAAA,GAAY,CAAC,CAAA,KAA2B,CAAA,CAAE,KAAK,IAAA,IAAQ,EAAA;AAE7D,MAAM,gBAAA,IAAoB,CAAC,OAAA,GAA4B,EAAC,KAAM;AAC5D,EAAA,OAAO;AAAA,IACL,IAAA,EA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;AAC/D;;;;;"}
@@ -3,10 +3,10 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3
3
  const core = require('@sentry/core');
4
4
 
5
5
  function isVersionMetadata(value) {
6
- return typeof value === "object" && value !== null && "id" in value && typeof value.id === "string";
6
+ return core.isObjectLike(value) && "id" in value && typeof value.id === "string";
7
7
  }
8
8
  function getEnvVar(env, varName) {
9
- return typeof env === "object" && env !== null && varName in env && typeof env[varName] === "string" ? env[varName] : void 0;
9
+ return core.isObjectLike(env) && varName in env && typeof env[varName] === "string" ? env[varName] : void 0;
10
10
  }
11
11
  function getFinalOptions(userOptions = {}, env) {
12
12
  if (typeof env !== "object" || env === null) {
@@ -1 +1 @@
1
- {"version":3,"file":"options.js","sources":["../../src/options.ts"],"sourcesContent":["import { envToBool } from '@sentry/core';\nimport type { CloudflareOptions } from './client';\n\n/**\n * Cloudflare's version metadata binding structure.\n * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/version-metadata/\n */\ninterface CfVersionMetadata {\n id: string;\n tag?: string;\n timestamp?: string;\n}\n\n/**\n * Checks if the value is a valid CF_VERSION_METADATA binding.\n */\nfunction isVersionMetadata(value: unknown): value is CfVersionMetadata {\n return typeof value === 'object' && value !== null && 'id' in value && typeof value.id === 'string';\n}\n\nfunction getEnvVar<T extends Record<string, unknown>>(env: unknown, varName: keyof T): string | undefined {\n return typeof env === 'object' && env !== null && varName in env && typeof (env as T)[varName] === 'string'\n ? ((env as T)[varName] as string)\n : undefined;\n}\n\n/**\n * Merges the options passed in from the user with the options we read from\n * the Cloudflare `env` environment variable object.\n *\n * Release is determined with the following priority (highest to lowest):\n * 1. User-provided release option\n * 2. SENTRY_RELEASE environment variable\n * 3. CF_VERSION_METADATA.id binding (if configured in the wrangler config)\n *\n * @param userOptions - The options passed in from the user.\n * @param env - The environment variables.\n *\n * @returns The final options.\n */\nexport function getFinalOptions(userOptions: CloudflareOptions = {}, env: unknown): CloudflareOptions {\n if (typeof env !== 'object' || env === null) {\n return userOptions;\n }\n\n // Priority: userOptions.release > SENTRY_RELEASE > CF_VERSION_METADATA.id\n const release =\n 'SENTRY_RELEASE' in env && typeof env.SENTRY_RELEASE === 'string'\n ? env.SENTRY_RELEASE\n : 'CF_VERSION_METADATA' in env && isVersionMetadata(env.CF_VERSION_METADATA)\n ? env.CF_VERSION_METADATA.id\n : undefined;\n\n const tracesSampleRate =\n userOptions.tracesSampleRate ?? parseFloat(getEnvVar(env, 'SENTRY_TRACES_SAMPLE_RATE') ?? '');\n\n return {\n release,\n ...userOptions,\n dsn: userOptions.dsn ?? getEnvVar(env, 'SENTRY_DSN'),\n environment: userOptions.environment ?? getEnvVar(env, 'SENTRY_ENVIRONMENT'),\n tracesSampleRate: isFinite(tracesSampleRate) ? tracesSampleRate : undefined,\n debug: userOptions.debug ?? envToBool(getEnvVar(env, 'SENTRY_DEBUG')),\n tunnel: userOptions.tunnel ?? getEnvVar(env, 'SENTRY_TUNNEL'),\n };\n}\n"],"names":["envToBool"],"mappings":";;;;AAgBA,SAAS,kBAAkB,KAAA,EAA4C;AACrE,EAAA,OAAO,OAAO,UAAU,QAAA,IAAY,KAAA,KAAU,QAAQ,IAAA,IAAQ,KAAA,IAAS,OAAO,KAAA,CAAM,EAAA,KAAO,QAAA;AAC7F;AAEA,SAAS,SAAA,CAA6C,KAAc,OAAA,EAAsC;AACxG,EAAA,OAAO,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,KAAQ,QAAQ,OAAA,IAAW,GAAA,IAAO,OAAQ,GAAA,CAAU,OAAO,CAAA,KAAM,QAAA,GAC7F,GAAA,CAAU,OAAO,CAAA,GACnB,MAAA;AACN;AAgBO,SAAS,eAAA,CAAgB,WAAA,GAAiC,EAAC,EAAG,GAAA,EAAiC;AACpG,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,KAAQ,IAAA,EAAM;AAC3C,IAAA,OAAO,WAAA;AAAA,EACT;AAGA,EAAA,MAAM,UACJ,gBAAA,IAAoB,GAAA,IAAO,OAAO,GAAA,CAAI,mBAAmB,QAAA,GACrD,GAAA,CAAI,cAAA,GACJ,qBAAA,IAAyB,OAAO,iBAAA,CAAkB,GAAA,CAAI,mBAAmB,CAAA,GACvE,GAAA,CAAI,oBAAoB,EAAA,GACxB,MAAA;AAER,EAAA,MAAM,gBAAA,GACJ,YAAY,gBAAA,IAAoB,UAAA,CAAW,UAAU,GAAA,EAAK,2BAA2B,KAAK,EAAE,CAAA;AAE9F,EAAA,OAAO;AAAA,IACL,OAAA;AAAA,IACA,GAAG,WAAA;AAAA,IACH,GAAA,EAAK,WAAA,CAAY,GAAA,IAAO,SAAA,CAAU,KAAK,YAAY,CAAA;AAAA,IACnD,WAAA,EAAa,WAAA,CAAY,WAAA,IAAe,SAAA,CAAU,KAAK,oBAAoB,CAAA;AAAA,IAC3E,gBAAA,EAAkB,QAAA,CAAS,gBAAgB,CAAA,GAAI,gBAAA,GAAmB,MAAA;AAAA,IAClE,OAAO,WAAA,CAAY,KAAA,IAASA,eAAU,SAAA,CAAU,GAAA,EAAK,cAAc,CAAC,CAAA;AAAA,IACpE,MAAA,EAAQ,WAAA,CAAY,MAAA,IAAU,SAAA,CAAU,KAAK,eAAe;AAAA,GAC9D;AACF;;;;"}
1
+ {"version":3,"file":"options.js","sources":["../../src/options.ts"],"sourcesContent":["import { isObjectLike, envToBool } from '@sentry/core';\nimport type { CloudflareOptions } from './client';\n\n/**\n * Cloudflare's version metadata binding structure.\n * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/version-metadata/\n */\ninterface CfVersionMetadata {\n id: string;\n tag?: string;\n timestamp?: string;\n}\n\n/**\n * Checks if the value is a valid CF_VERSION_METADATA binding.\n */\nfunction isVersionMetadata(value: unknown): value is CfVersionMetadata {\n return isObjectLike(value) && 'id' in value && typeof value.id === 'string';\n}\n\nfunction getEnvVar<T extends Record<string, unknown>>(env: unknown, varName: keyof T): string | undefined {\n return isObjectLike(env) && varName in env && typeof (env as T)[varName] === 'string'\n ? ((env as T)[varName] as string)\n : undefined;\n}\n\n/**\n * Merges the options passed in from the user with the options we read from\n * the Cloudflare `env` environment variable object.\n *\n * Release is determined with the following priority (highest to lowest):\n * 1. User-provided release option\n * 2. SENTRY_RELEASE environment variable\n * 3. CF_VERSION_METADATA.id binding (if configured in the wrangler config)\n *\n * @param userOptions - The options passed in from the user.\n * @param env - The environment variables.\n *\n * @returns The final options.\n */\nexport function getFinalOptions(userOptions: CloudflareOptions = {}, env: unknown): CloudflareOptions {\n if (typeof env !== 'object' || env === null) {\n return userOptions;\n }\n\n // Priority: userOptions.release > SENTRY_RELEASE > CF_VERSION_METADATA.id\n const release =\n 'SENTRY_RELEASE' in env && typeof env.SENTRY_RELEASE === 'string'\n ? env.SENTRY_RELEASE\n : 'CF_VERSION_METADATA' in env && isVersionMetadata(env.CF_VERSION_METADATA)\n ? env.CF_VERSION_METADATA.id\n : undefined;\n\n const tracesSampleRate =\n userOptions.tracesSampleRate ?? parseFloat(getEnvVar(env, 'SENTRY_TRACES_SAMPLE_RATE') ?? '');\n\n return {\n release,\n ...userOptions,\n dsn: userOptions.dsn ?? getEnvVar(env, 'SENTRY_DSN'),\n environment: userOptions.environment ?? getEnvVar(env, 'SENTRY_ENVIRONMENT'),\n tracesSampleRate: isFinite(tracesSampleRate) ? tracesSampleRate : undefined,\n debug: userOptions.debug ?? envToBool(getEnvVar(env, 'SENTRY_DEBUG')),\n tunnel: userOptions.tunnel ?? getEnvVar(env, 'SENTRY_TUNNEL'),\n };\n}\n"],"names":["isObjectLike","envToBool"],"mappings":";;;;AAgBA,SAAS,kBAAkB,KAAA,EAA4C;AACrE,EAAA,OAAOA,kBAAa,KAAK,CAAA,IAAK,QAAQ,KAAA,IAAS,OAAO,MAAM,EAAA,KAAO,QAAA;AACrE;AAEA,SAAS,SAAA,CAA6C,KAAc,OAAA,EAAsC;AACxG,EAAA,OAAOA,iBAAA,CAAa,GAAG,CAAA,IAAK,OAAA,IAAW,GAAA,IAAO,OAAQ,GAAA,CAAU,OAAO,CAAA,KAAM,QAAA,GACvE,GAAA,CAAU,OAAO,CAAA,GACnB,MAAA;AACN;AAgBO,SAAS,eAAA,CAAgB,WAAA,GAAiC,EAAC,EAAG,GAAA,EAAiC;AACpG,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,KAAQ,IAAA,EAAM;AAC3C,IAAA,OAAO,WAAA;AAAA,EACT;AAGA,EAAA,MAAM,UACJ,gBAAA,IAAoB,GAAA,IAAO,OAAO,GAAA,CAAI,mBAAmB,QAAA,GACrD,GAAA,CAAI,cAAA,GACJ,qBAAA,IAAyB,OAAO,iBAAA,CAAkB,GAAA,CAAI,mBAAmB,CAAA,GACvE,GAAA,CAAI,oBAAoB,EAAA,GACxB,MAAA;AAER,EAAA,MAAM,gBAAA,GACJ,YAAY,gBAAA,IAAoB,UAAA,CAAW,UAAU,GAAA,EAAK,2BAA2B,KAAK,EAAE,CAAA;AAE9F,EAAA,OAAO;AAAA,IACL,OAAA;AAAA,IACA,GAAG,WAAA;AAAA,IACH,GAAA,EAAK,WAAA,CAAY,GAAA,IAAO,SAAA,CAAU,KAAK,YAAY,CAAA;AAAA,IACnD,WAAA,EAAa,WAAA,CAAY,WAAA,IAAe,SAAA,CAAU,KAAK,oBAAoB,CAAA;AAAA,IAC3E,gBAAA,EAAkB,QAAA,CAAS,gBAAgB,CAAA,GAAI,gBAAA,GAAmB,MAAA;AAAA,IAClE,OAAO,WAAA,CAAY,KAAA,IAASC,eAAU,SAAA,CAAU,GAAA,EAAK,cAAc,CAAC,CAAA;AAAA,IACpE,MAAA,EAAQ,WAAA,CAAY,MAAA,IAAU,SAAA,CAAU,KAAK,eAAe;AAAA,GAC9D;AACF;;;;"}
@@ -10,10 +10,8 @@ function sentryPagesPlugin(handlerOrOptions) {
10
10
  return context.next();
11
11
  }
12
12
  const options = typeof handlerOrOptions === "function" ? handlerOrOptions(context) : handlerOrOptions;
13
- return request.wrapRequestHandler(
14
- { options, request: context.request, context: { ...context, props: {} } },
15
- () => context.next()
16
- );
13
+ const executionContext = { ...context, props: {} };
14
+ return request.wrapRequestHandler({ options, request: context.request, context: executionContext }, () => context.next());
17
15
  };
18
16
  }
19
17
 
@@ -1 +1 @@
1
- {"version":3,"file":"pages-plugin.js","sources":["../../src/pages-plugin.ts"],"sourcesContent":["import { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport type { CloudflareOptions } from './client';\nimport { wrapRequestHandler } from './request';\n\n/**\n * Plugin middleware for Cloudflare Pages.\n *\n * Initializes the SDK and wraps cloudflare pages requests with SDK instrumentation.\n *\n * @example Simple usage\n *\n * ```javascript\n * // functions/_middleware.js\n * import * as Sentry from '@sentry/cloudflare';\n *\n * export const onRequest = Sentry.sentryPagesPlugin({\n * dsn: process.env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * });\n * ```\n *\n * @example Usage with handler function to access context for environmental variables\n *\n * ```javascript\n * import * as Sentry from '@sentry/cloudflare';\n *\n * const const onRequest = Sentry.sentryPagesPlugin((context) => ({\n * dsn: context.env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * })\n * ```\n *\n * @param handlerOrOptions Configuration options or a function that returns configuration options.\n * @returns A plugin function that can be used in Cloudflare Pages.\n */\nexport function sentryPagesPlugin<\n Env = unknown,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Params extends string = any,\n Data extends Record<string, unknown> = Record<string, unknown>,\n // Although it is not ideal to use `any` here, it makes usage more flexible for different setups.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PluginParams = any,\n>(\n handlerOrOptions:\n | CloudflareOptions\n | ((context: EventPluginContext<Env, Params, Data, PluginParams>) => CloudflareOptions),\n): PagesPluginFunction<Env, Params, Data, PluginParams> {\n setAsyncLocalStorageAsyncContextStrategy();\n return context => {\n if (context.request.method === 'OPTIONS' || context.request.method === 'HEAD') {\n return context.next();\n }\n\n const options = typeof handlerOrOptions === 'function' ? handlerOrOptions(context) : handlerOrOptions;\n return wrapRequestHandler({ options, request: context.request, context: { ...context, props: {} } }, () =>\n context.next(),\n );\n };\n}\n"],"names":["setAsyncLocalStorageAsyncContextStrategy","wrapRequestHandler"],"mappings":";;;;;AAmCO,SAAS,kBASd,gBAAA,EAGsD;AACtD,EAAAA,8CAAA,EAAyC;AACzC,EAAA,OAAO,CAAA,OAAA,KAAW;AAChB,IAAA,IAAI,QAAQ,OAAA,CAAQ,MAAA,KAAW,aAAa,OAAA,CAAQ,OAAA,CAAQ,WAAW,MAAA,EAAQ;AAC7E,MAAA,OAAO,QAAQ,IAAA,EAAK;AAAA,IACtB;AAEA,IAAA,MAAM,UAAU,OAAO,gBAAA,KAAqB,UAAA,GAAa,gBAAA,CAAiB,OAAO,CAAA,GAAI,gBAAA;AACrF,IAAA,OAAOC,0BAAA;AAAA,MAAmB,EAAE,OAAA,EAAS,OAAA,EAAS,OAAA,CAAQ,OAAA,EAAS,OAAA,EAAS,EAAE,GAAG,OAAA,EAAS,KAAA,EAAO,EAAC,EAAE,EAAE;AAAA,MAAG,MACnG,QAAQ,IAAA;AAAK,KACf;AAAA,EACF,CAAA;AACF;;;;"}
1
+ {"version":3,"file":"pages-plugin.js","sources":["../../src/pages-plugin.ts"],"sourcesContent":["import { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport type { CloudflareOptions } from './client';\nimport type { ExecutionContextCompat } from './executionContext';\nimport { wrapRequestHandler } from './request';\n\n/**\n * Plugin middleware for Cloudflare Pages.\n *\n * Initializes the SDK and wraps cloudflare pages requests with SDK instrumentation.\n *\n * @example Simple usage\n *\n * ```javascript\n * // functions/_middleware.js\n * import * as Sentry from '@sentry/cloudflare';\n *\n * export const onRequest = Sentry.sentryPagesPlugin({\n * dsn: process.env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * });\n * ```\n *\n * @example Usage with handler function to access context for environmental variables\n *\n * ```javascript\n * import * as Sentry from '@sentry/cloudflare';\n *\n * const const onRequest = Sentry.sentryPagesPlugin((context) => ({\n * dsn: context.env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * })\n * ```\n *\n * @param handlerOrOptions Configuration options or a function that returns configuration options.\n * @returns A plugin function that can be used in Cloudflare Pages.\n */\nexport function sentryPagesPlugin<\n Env = unknown,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Params extends string = any,\n Data extends Record<string, unknown> = Record<string, unknown>,\n // Although it is not ideal to use `any` here, it makes usage more flexible for different setups.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PluginParams = any,\n>(\n handlerOrOptions:\n | CloudflareOptions\n | ((context: EventPluginContext<Env, Params, Data, PluginParams>) => CloudflareOptions),\n): PagesPluginFunction<Env, Params, Data, PluginParams> {\n setAsyncLocalStorageAsyncContextStrategy();\n return context => {\n if (context.request.method === 'OPTIONS' || context.request.method === 'HEAD') {\n return context.next();\n }\n\n const options = typeof handlerOrOptions === 'function' ? handlerOrOptions(context) : handlerOrOptions;\n // A Pages `EventPluginContext` is not a Workers `ExecutionContext`, but `wrapRequestHandler` only\n // uses `waitUntil` and a `'storage' in context` check, both of which this satisfies.\n const executionContext = { ...context, props: {} } as unknown as ExecutionContextCompat;\n return wrapRequestHandler({ options, request: context.request, context: executionContext }, () => context.next());\n };\n}\n"],"names":["setAsyncLocalStorageAsyncContextStrategy","wrapRequestHandler"],"mappings":";;;;;AAoCO,SAAS,kBASd,gBAAA,EAGsD;AACtD,EAAAA,8CAAA,EAAyC;AACzC,EAAA,OAAO,CAAA,OAAA,KAAW;AAChB,IAAA,IAAI,QAAQ,OAAA,CAAQ,MAAA,KAAW,aAAa,OAAA,CAAQ,OAAA,CAAQ,WAAW,MAAA,EAAQ;AAC7E,MAAA,OAAO,QAAQ,IAAA,EAAK;AAAA,IACtB;AAEA,IAAA,MAAM,UAAU,OAAO,gBAAA,KAAqB,UAAA,GAAa,gBAAA,CAAiB,OAAO,CAAA,GAAI,gBAAA;AAGrF,IAAA,MAAM,mBAAmB,EAAE,GAAG,OAAA,EAAS,KAAA,EAAO,EAAC,EAAE;AACjD,IAAA,OAAOC,0BAAA,CAAmB,EAAE,OAAA,EAAS,OAAA,EAAS,OAAA,CAAQ,OAAA,EAAS,OAAA,EAAS,gBAAA,EAAiB,EAAG,MAAM,OAAA,CAAQ,IAAA,EAAM,CAAA;AAAA,EAClH,CAAA;AACF;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"request.js","sources":["../../src/request.ts"],"sourcesContent":["import type { CfProperties, ExecutionContext, IncomingRequestCfProperties } from '@cloudflare/workers-types';\nimport {\n captureException,\n continueTrace,\n getClient,\n getHttpSpanDetailsFromUrlObject,\n httpHeadersToSpanAttributes,\n parseStringToURLObject,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n setHttpStatus,\n startSpanManual,\n winterCGHeadersToDict,\n withIsolationScope,\n} from '@sentry/core';\nimport { captureIncomingRequestBody } from './integrations/httpServer';\nimport type { CloudflareOptions } from './client';\nimport { flushAndDispose, getOriginalWaitUntil } from './flush';\nimport { addCloudResourceContext, addCultureContext, addRequest } from './scope-utils';\nimport { init } from './sdk';\nimport { classifyResponseStreaming } from './utils/streaming';\n\nfunction getRequestErrorMechanismType(context: ExecutionContext | 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\ninterface RequestHandlerWrapperOptions {\n options: CloudflareOptions;\n request: Request<unknown, IncomingRequestCfProperties<unknown> | CfProperties<unknown>>;\n context: ExecutionContext | 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\n/**\n * Wraps a cloudflare request handler in Sentry instrumentation\n */\nexport function wrapRequestHandler(\n wrapperOptions: RequestHandlerWrapperOptions,\n handler: (...args: unknown[]) => Response | Promise<Response>,\n): Promise<Response> {\n return withIsolationScope(async isolationScope => {\n const { options, request, captureErrors = true } = wrapperOptions;\n const context = wrapperOptions.context;\n\n // Use getOriginalWaitUntil to get the un-instrumented waitUntil function.\n // This is crucial to avoid deadlock: the flush lock mechanism wraps waitUntil\n // to track pending tasks. If we use the instrumented version for flushAndDispose,\n // it acquires the lock, then flushAndDispose tries to wait for the same lock,\n // creating a deadlock.\n const waitUntil = context ? getOriginalWaitUntil(context)?.bind(context) : undefined;\n const errorMechanismType = getRequestErrorMechanismType(context);\n\n const client = init({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n const urlObject = parseStringToURLObject(request.url);\n const [name, attributes] = getHttpSpanDetailsFromUrlObject(urlObject, 'server', 'auto.http.cloudflare', request);\n\n const contentLength = request.headers.get('content-length');\n if (contentLength) {\n attributes['http.request.body.size'] = parseInt(contentLength, 10);\n }\n\n const userAgentHeader = request.headers.get('user-agent');\n if (userAgentHeader) {\n attributes['user_agent.original'] = userAgentHeader;\n }\n\n Object.assign(\n attributes,\n httpHeadersToSpanAttributes(\n winterCGHeadersToDict(request.headers),\n getClient()?.getDataCollectionOptions() ?? false,\n ),\n );\n\n attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] = 'http.server';\n\n addCloudResourceContext(isolationScope);\n addRequest(isolationScope, request);\n if (request.cf) {\n addCultureContext(isolationScope, request.cf);\n\n if (typeof request.cf.httpProtocol === 'string') {\n attributes['network.protocol.name'] = request.cf.httpProtocol;\n }\n }\n\n // Do not capture spans for OPTIONS and HEAD requests\n if (request.method === 'OPTIONS' || request.method === 'HEAD') {\n try {\n return await handler();\n } catch (e) {\n if (captureErrors) {\n captureException(e, { mechanism: { handled: false, type: errorMechanismType } });\n }\n throw e;\n } finally {\n waitUntil?.(flushAndDispose(client));\n }\n }\n\n if (client) {\n await captureIncomingRequestBody(client, request);\n }\n\n return continueTrace(\n { sentryTrace: request.headers.get('sentry-trace') || '', baggage: request.headers.get('baggage') },\n () => {\n // Note: This 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\n // Use startSpanManual to control when span ends (needed for streaming responses)\n return startSpanManual({ name, attributes }, async span => {\n let res: Response;\n\n try {\n res = await handler();\n setHttpStatus(span, res.status);\n\n // After the handler runs, the span name might have been updated by nested instrumentation\n // (e.g., Remix parameterizing routes). The span should already have the correct name\n // from that instrumentation, so we don't need to do anything here.\n } catch (e) {\n span.end();\n if (captureErrors) {\n captureException(e, { mechanism: { handled: false, type: errorMechanismType } });\n }\n waitUntil?.(flushAndDispose(client));\n throw e;\n }\n\n // Classify response to detect actual streaming\n const classification = classifyResponseStreaming(res);\n\n if (classification.isStreaming && res.body) {\n try {\n let ended = false;\n\n const endSpanOnce = (): void => {\n if (ended) return;\n\n ended = true;\n span.end();\n waitUntil?.(flushAndDispose(client));\n };\n\n const transform = new TransformStream({\n flush() {\n // Source stream completed normally.\n endSpanOnce();\n },\n cancel() {\n // Client disconnected (or downstream cancelled). The `cancel`\n // is being called while the response is still considered\n // active, so this is a safe place to end the span.\n endSpanOnce();\n },\n });\n\n return new Response(res.body.pipeThrough(transform), {\n status: res.status,\n statusText: res.statusText,\n headers: res.headers,\n });\n } catch {\n span.end();\n waitUntil?.(flushAndDispose(client));\n return res;\n }\n }\n\n // Non-streaming response - end span immediately and return original\n span.end();\n\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 (res.status === 101) {\n waitUntil?.(client?.flush(2000));\n } else {\n waitUntil?.(flushAndDispose(client));\n }\n return res;\n });\n },\n );\n });\n}\n"],"names":["withIsolationScope","getOriginalWaitUntil","init","parseStringToURLObject","getHttpSpanDetailsFromUrlObject","httpHeadersToSpanAttributes","winterCGHeadersToDict","getClient","SEMANTIC_ATTRIBUTE_SENTRY_OP","addCloudResourceContext","addRequest","addCultureContext","captureException","flushAndDispose","captureIncomingRequestBody","continueTrace","startSpanManual","setHttpStatus","classifyResponseStreaming"],"mappings":";;;;;;;;;AAqBA,SAAS,6BAA6B,OAAA,EAA+C;AAEnF,EAAA,OAAO,OAAA,IAAW,SAAA,IAAa,OAAA,GAAU,qCAAA,GAAwC,sBAAA;AACnF;AAsBO,SAAS,kBAAA,CACd,gBACA,OAAA,EACmB;AACnB,EAAA,OAAOA,uBAAA,CAAmB,OAAM,cAAA,KAAkB;AAChD,IAAA,MAAM,EAAE,OAAA,EAAS,OAAA,EAAS,aAAA,GAAgB,MAAK,GAAI,cAAA;AACnD,IAAA,MAAM,UAAU,cAAA,CAAe,OAAA;AAO/B,IAAA,MAAM,YAAY,OAAA,GAAUC,0BAAA,CAAqB,OAAO,CAAA,EAAG,IAAA,CAAK,OAAO,CAAA,GAAI,MAAA;AAC3E,IAAA,MAAM,kBAAA,GAAqB,6BAA6B,OAAO,CAAA;AAE/D,IAAA,MAAM,SAASC,QAAA,CAAK,EAAE,GAAG,OAAA,EAAS,GAAA,EAAK,SAAS,CAAA;AAChD,IAAA,cAAA,CAAe,UAAU,MAAM,CAAA;AAE/B,IAAA,MAAM,SAAA,GAAYC,2BAAA,CAAuB,OAAA,CAAQ,GAAG,CAAA;AACpD,IAAA,MAAM,CAAC,MAAM,UAAU,CAAA,GAAIC,qCAAgC,SAAA,EAAW,QAAA,EAAU,wBAAwB,OAAO,CAAA;AAE/G,IAAA,MAAM,aAAA,GAAgB,OAAA,CAAQ,OAAA,CAAQ,GAAA,CAAI,gBAAgB,CAAA;AAC1D,IAAA,IAAI,aAAA,EAAe;AACjB,MAAA,UAAA,CAAW,wBAAwB,CAAA,GAAI,QAAA,CAAS,aAAA,EAAe,EAAE,CAAA;AAAA,IACnE;AAEA,IAAA,MAAM,eAAA,GAAkB,OAAA,CAAQ,OAAA,CAAQ,GAAA,CAAI,YAAY,CAAA;AACxD,IAAA,IAAI,eAAA,EAAi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,CAAA;AAAA,gBACA,MAAA,GAAS;AAIP,kBAAA,WAAA,EAAY;AAAA,gBACd;AAAA,eACD,CAAA;AAED,cAAA,OAAO,IAAI,QAAA,CAAS,GAAA,CAAI,IAAA,CAAK,WAAA,CAAY,SAAS,CAAA,EAAG;AAAA,gBACnD,QAAQ,GAAA,CAAI,MAAA;AAAA,gBACZ,YAAY,GAAA,CAAI,UAAA;AAAA,gBAChB,SAAS,GAAA,CAAI;AAAA,eACd,CAAA;AAAA,YACH,CAAA,CAAA,MAAQ;AACN,cAAA,IAAA,CAAK,GAAA,EAAI;AACT,cAAA,SAAA,GAAYA,qBAAA,CAAgB,MAAM,CAAC,CAAA;AACnC,cAAA,OAAO,GAAA;AAAA,YACT;AAAA,UACF;AAGA,UAAA,IAAA,CAAK,GAAA,EAAI;AAKT,UAAA,IAAI,GAAA,CAAI,WAAW,GAAA,EAAK;AACtB,YAAA,SAAA,GAAY,MAAA,EAAQ,KAAA,CAAM,GAAI,CAAC,CAAA;AAAA,UACjC,CAAA,MAAO;AACL,YAAA,SAAA,GAAYA,qBAAA,CAAgB,MAAM,CAAC,CAAA;AAAA,UACrC;AACA,UAAA,OAAO,GAAA;AAAA,QACT,CAAC,CAAA;AAAA,MACH;AAAA,KACF;AAAA,EACF,CAAC,CAAA;AACH;;;;"}
1
+ {"version":3,"file":"request.js","sources":["../../src/request.ts"],"sourcesContent":["import type { CfProperties, IncomingRequestCfProperties } from '@cloudflare/workers-types';\nimport {\n captureException,\n continueTrace,\n getClient,\n getHttpSpanDetailsFromUrlObject,\n httpHeadersToSpanAttributes,\n parseStringToURLObject,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n setHttpStatus,\n startSpanManual,\n winterCGHeadersToDict,\n withIsolationScope,\n} from '@sentry/core';\nimport { captureIncomingRequestBody } from './integrations/httpServer';\nimport type { CloudflareOptions } from './client';\nimport type { ExecutionContextCompat } from './executionContext';\nimport { flushAndDispose, getOriginalWaitUntil } from './flush';\nimport { addCloudResourceContext, addCultureContext, addRequest } from './scope-utils';\nimport { init } from './sdk';\nimport { classifyResponseStreaming } from './utils/streaming';\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\ninterface 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\n/**\n * Wraps a cloudflare request handler in Sentry instrumentation\n */\nexport function wrapRequestHandler(\n wrapperOptions: RequestHandlerWrapperOptions,\n handler: (...args: unknown[]) => Response | Promise<Response>,\n): Promise<Response> {\n return withIsolationScope(async isolationScope => {\n const { options, request, captureErrors = true } = wrapperOptions;\n const context = wrapperOptions.context;\n\n // Use getOriginalWaitUntil to get the un-instrumented waitUntil function.\n // This is crucial to avoid deadlock: the flush lock mechanism wraps waitUntil\n // to track pending tasks. If we use the instrumented version for flushAndDispose,\n // it acquires the lock, then flushAndDispose tries to wait for the same lock,\n // creating a deadlock.\n const waitUntil = context ? getOriginalWaitUntil(context)?.bind(context) : undefined;\n const errorMechanismType = getRequestErrorMechanismType(context);\n\n const client = init({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n const urlObject = parseStringToURLObject(request.url);\n const [name, attributes] = getHttpSpanDetailsFromUrlObject(urlObject, 'server', 'auto.http.cloudflare', request);\n\n const contentLength = request.headers.get('content-length');\n if (contentLength) {\n attributes['http.request.body.size'] = parseInt(contentLength, 10);\n }\n\n const userAgentHeader = request.headers.get('user-agent');\n if (userAgentHeader) {\n attributes['user_agent.original'] = userAgentHeader;\n }\n\n Object.assign(\n attributes,\n httpHeadersToSpanAttributes(\n winterCGHeadersToDict(request.headers),\n getClient()?.getDataCollectionOptions() ?? false,\n ),\n );\n\n attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] = 'http.server';\n\n addCloudResourceContext(isolationScope);\n addRequest(isolationScope, request);\n if (request.cf) {\n addCultureContext(isolationScope, request.cf);\n\n if (typeof request.cf.httpProtocol === 'string') {\n attributes['network.protocol.name'] = request.cf.httpProtocol;\n }\n }\n\n // Do not capture spans for OPTIONS and HEAD requests\n if (request.method === 'OPTIONS' || request.method === 'HEAD') {\n try {\n return await handler();\n } catch (e) {\n if (captureErrors) {\n captureException(e, { mechanism: { handled: false, type: errorMechanismType } });\n }\n throw e;\n } finally {\n waitUntil?.(flushAndDispose(client));\n }\n }\n\n if (client) {\n await captureIncomingRequestBody(client, request);\n }\n\n return continueTrace(\n { sentryTrace: request.headers.get('sentry-trace') || '', baggage: request.headers.get('baggage') },\n () => {\n // Note: This 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\n // Use startSpanManual to control when span ends (needed for streaming responses)\n return startSpanManual({ name, attributes }, async span => {\n let res: Response;\n\n try {\n res = await handler();\n setHttpStatus(span, res.status);\n\n // After the handler runs, the span name might have been updated by nested instrumentation\n // (e.g., Remix parameterizing routes). The span should already have the correct name\n // from that instrumentation, so we don't need to do anything here.\n } catch (e) {\n span.end();\n if (captureErrors) {\n captureException(e, { mechanism: { handled: false, type: errorMechanismType } });\n }\n waitUntil?.(flushAndDispose(client));\n throw e;\n }\n\n // Classify response to detect actual streaming\n const classification = classifyResponseStreaming(res);\n\n if (classification.isStreaming && res.body) {\n try {\n let ended = false;\n\n const endSpanOnce = (): void => {\n if (ended) return;\n\n ended = true;\n span.end();\n waitUntil?.(flushAndDispose(client));\n };\n\n const transform = new TransformStream({\n flush() {\n // Source stream completed normally.\n endSpanOnce();\n },\n cancel() {\n // Client disconnected (or downstream cancelled). The `cancel`\n // is being called while the response is still considered\n // active, so this is a safe place to end the span.\n endSpanOnce();\n },\n });\n\n return new Response(res.body.pipeThrough(transform), {\n status: res.status,\n statusText: res.statusText,\n headers: res.headers,\n });\n } catch {\n span.end();\n waitUntil?.(flushAndDispose(client));\n return res;\n }\n }\n\n // Non-streaming response - end span immediately and return original\n span.end();\n\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 (res.status === 101) {\n waitUntil?.(client?.flush(2000));\n } else {\n waitUntil?.(flushAndDispose(client));\n }\n return res;\n });\n },\n );\n });\n}\n"],"names":["withIsolationScope","getOriginalWaitUntil","init","parseStringToURLObject","getHttpSpanDetailsFromUrlObject","httpHeadersToSpanAttributes","winterCGHeadersToDict","getClient","SEMANTIC_ATTRIBUTE_SENTRY_OP","addCloudResourceContext","addRequest","addCultureContext","captureException","flushAndDispose","captureIncomingRequestBody","continueTrace","startSpanManual","setHttpStatus","classifyResponseStreaming"],"mappings":";;;;;;;;;AAsBA,SAAS,6BAA6B,OAAA,EAAqD;AAEzF,EAAA,OAAO,OAAA,IAAW,SAAA,IAAa,OAAA,GAAU,qCAAA,GAAwC,sBAAA;AACnF;AAsBO,SAAS,kBAAA,CACd,gBACA,OAAA,EACmB;AACnB,EAAA,OAAOA,uBAAA,CAAmB,OAAM,cAAA,KAAkB;AAChD,IAAA,MAAM,EAAE,OAAA,EAAS,OAAA,EAAS,aAAA,GAAgB,MAAK,GAAI,cAAA;AACnD,IAAA,MAAM,UAAU,cAAA,CAAe,OAAA;AAO/B,IAAA,MAAM,YAAY,OAAA,GAAUC,0BAAA,CAAqB,OAAO,CAAA,EAAG,IAAA,CAAK,OAAO,CAAA,GAAI,MAAA;AAC3E,IAAA,MAAM,kBAAA,GAAqB,6BAA6B,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,GAAI,CAAC,CAAA;AAAA,UACjC,CAAA,MAAO;AACL,YAAA,SAAA,GAAYA,qBAAA,CAAgB,MAAM,CAAC,CAAA;AAAA,UACrC;AACA,UAAA,OAAO,GAAA;AAAA,QACT,CAAC,CAAA;AAAA,MACH;AAAA,KACF;AAAA,EACF,CAAC,CAAA;AACH;;;;"}
@@ -4,11 +4,10 @@ const core = require('@sentry/core');
4
4
 
5
5
  const SENTRY_RPC_META_KEY = "__sentry_rpc_meta__";
6
6
  function isSentryRpcMeta(value) {
7
- if (typeof value !== "object" || value === null || !(SENTRY_RPC_META_KEY in value)) {
7
+ if (!core.isObjectLike(value) || !(SENTRY_RPC_META_KEY in value)) {
8
8
  return false;
9
9
  }
10
- const sentry = value.__sentry_rpc_meta__;
11
- return typeof sentry === "object" && sentry !== null;
10
+ return core.isObjectLike(value[SENTRY_RPC_META_KEY]);
12
11
  }
13
12
  function appendRpcMeta(args) {
14
13
  const traceData = core.getTraceData();
@@ -1 +1 @@
1
- {"version":3,"file":"rpcMeta.js","sources":["../../../src/utils/rpcMeta.ts"],"sourcesContent":["import { getTraceData, type SerializedTraceData } from '@sentry/core';\n\n/**\n * Key used to identify Sentry RPC metadata in a trailing argument.\n * This enables transparent trace propagation across Cloudflare Workers RPC\n * calls (Cap'n Proto), which have no native header/metadata support.\n */\nconst SENTRY_RPC_META_KEY = '__sentry_rpc_meta__';\n\ninterface SentryRpcMeta {\n __sentry_rpc_meta__: SerializedTraceData;\n}\n\nfunction isSentryRpcMeta(value: unknown): value is SentryRpcMeta {\n if (typeof value !== 'object' || value === null || !(SENTRY_RPC_META_KEY in value)) {\n return false;\n }\n const sentry = (value as SentryRpcMeta).__sentry_rpc_meta__;\n return typeof sentry === 'object' && sentry !== null;\n}\n\n/**\n * Appends Sentry RPC metadata to an args array for trace propagation.\n * If no active trace exists, returns the original args unchanged.\n */\nexport function appendRpcMeta(args: unknown[]): unknown[] {\n const traceData = getTraceData();\n\n if (!traceData['sentry-trace']) {\n return args;\n }\n\n return [...args, { [SENTRY_RPC_META_KEY]: traceData }];\n}\n\n/**\n * Extracts Sentry RPC metadata from the trailing argument of an args array.\n * Returns cleaned args (without meta) and the extracted trace data if found.\n */\nexport function extractRpcMeta<T extends unknown[]>(\n args: T,\n): {\n args: T;\n rpcMeta?: SerializedTraceData;\n} {\n if (args.length === 0) {\n return { args };\n }\n\n const last = args[args.length - 1];\n if (isSentryRpcMeta(last)) {\n return {\n args: args.slice(0, -1) as T,\n rpcMeta: last.__sentry_rpc_meta__,\n };\n }\n\n return { args };\n}\n"],"names":["getTraceData"],"mappings":";;;;AAOA,MAAM,mBAAA,GAAsB,qBAAA;AAM5B,SAAS,gBAAgB,KAAA,EAAwC;AAC/D,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,UAAU,IAAA,IAAQ,EAAE,uBAAuB,KAAA,CAAA,EAAQ;AAClF,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,MAAM,SAAU,KAAA,CAAwB,mBAAA;AACxC,EAAA,OAAO,OAAO,MAAA,KAAW,QAAA,IAAY,MAAA,KAAW,IAAA;AAClD;AAMO,SAAS,cAAc,IAAA,EAA4B;AACxD,EAAA,MAAM,YAAYA,iBAAA,EAAa;AAE/B,EAAA,IAAI,CAAC,SAAA,CAAU,cAAc,CAAA,EAAG;AAC9B,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,OAAO,CAAC,GAAG,IAAA,EAAM,EAAE,CAAC,mBAAmB,GAAG,WAAW,CAAA;AACvD;AAMO,SAAS,eACd,IAAA,EAIA;AACA,EAAA,IAAI,IAAA,CAAK,WAAW,CAAA,EAAG;AACrB,IAAA,OAAO,EAAE,IAAA,EAAK;AAAA,EAChB;AAEA,EAAA,MAAM,IAAA,GAAO,IAAA,CAAK,IAAA,CAAK,MAAA,GAAS,CAAC,CAAA;AACjC,EAAA,IAAI,eAAA,CAAgB,IAAI,CAAA,EAAG;AACzB,IAAA,OAAO;AAAA,MACL,IAAA,EAAM,IAAA,CAAK,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA;AAAA,MACtB,SAAS,IAAA,CAAK;AAAA,KAChB;AAAA,EACF;AAEA,EAAA,OAAO,EAAE,IAAA,EAAK;AAChB;;;;;"}
1
+ {"version":3,"file":"rpcMeta.js","sources":["../../../src/utils/rpcMeta.ts"],"sourcesContent":["import { getTraceData, isObjectLike, type SerializedTraceData } from '@sentry/core';\n\n/**\n * Key used to identify Sentry RPC metadata in a trailing argument.\n * This enables transparent trace propagation across Cloudflare Workers RPC\n * calls (Cap'n Proto), which have no native header/metadata support.\n */\nconst SENTRY_RPC_META_KEY = '__sentry_rpc_meta__';\n\ninterface SentryRpcMeta {\n __sentry_rpc_meta__: SerializedTraceData;\n}\n\nfunction isSentryRpcMeta(value: unknown): value is SentryRpcMeta {\n if (!isObjectLike(value) || !(SENTRY_RPC_META_KEY in value)) {\n return false;\n }\n return isObjectLike(value[SENTRY_RPC_META_KEY]);\n}\n\n/**\n * Appends Sentry RPC metadata to an args array for trace propagation.\n * If no active trace exists, returns the original args unchanged.\n */\nexport function appendRpcMeta(args: unknown[]): unknown[] {\n const traceData = getTraceData();\n\n if (!traceData['sentry-trace']) {\n return args;\n }\n\n return [...args, { [SENTRY_RPC_META_KEY]: traceData }];\n}\n\n/**\n * Extracts Sentry RPC metadata from the trailing argument of an args array.\n * Returns cleaned args (without meta) and the extracted trace data if found.\n */\nexport function extractRpcMeta<T extends unknown[]>(\n args: T,\n): {\n args: T;\n rpcMeta?: SerializedTraceData;\n} {\n if (args.length === 0) {\n return { args };\n }\n\n const last = args[args.length - 1];\n if (isSentryRpcMeta(last)) {\n return {\n args: args.slice(0, -1) as T,\n rpcMeta: last.__sentry_rpc_meta__,\n };\n }\n\n return { args };\n}\n"],"names":["isObjectLike","getTraceData"],"mappings":";;;;AAOA,MAAM,mBAAA,GAAsB,qBAAA;AAM5B,SAAS,gBAAgB,KAAA,EAAwC;AAC/D,EAAA,IAAI,CAACA,iBAAA,CAAa,KAAK,CAAA,IAAK,EAAE,uBAAuB,KAAA,CAAA,EAAQ;AAC3D,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,OAAOA,iBAAA,CAAa,KAAA,CAAM,mBAAmB,CAAC,CAAA;AAChD;AAMO,SAAS,cAAc,IAAA,EAA4B;AACxD,EAAA,MAAM,YAAYC,iBAAA,EAAa;AAE/B,EAAA,IAAI,CAAC,SAAA,CAAU,cAAc,CAAA,EAAG;AAC9B,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,OAAO,CAAC,GAAG,IAAA,EAAM,EAAE,CAAC,mBAAmB,GAAG,WAAW,CAAA;AACvD;AAMO,SAAS,eACd,IAAA,EAIA;AACA,EAAA,IAAI,IAAA,CAAK,WAAW,CAAA,EAAG;AACrB,IAAA,OAAO,EAAE,IAAA,EAAK;AAAA,EAChB;AAEA,EAAA,MAAM,IAAA,GAAO,IAAA,CAAK,IAAA,CAAK,MAAA,GAAS,CAAC,CAAA;AACjC,EAAA,IAAI,eAAA,CAAgB,IAAI,CAAA,EAAG;AACzB,IAAA,OAAO;AAAA,MACL,IAAA,EAAM,IAAA,CAAK,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA;AAAA,MACtB,SAAS,IAAA,CAAK;AAAA,KAChB;AAAA,EACF;AAEA,EAAA,OAAO,EAAE,IAAA,EAAK;AAChB;;;;;"}