@sentry/cloudflare 10.55.0 → 10.57.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.
- package/build/cjs/client.js +3 -0
- package/build/cjs/client.js.map +1 -1
- package/build/cjs/durableobject.js +21 -20
- package/build/cjs/durableobject.js.map +1 -1
- package/build/cjs/index.js +2 -2
- package/build/cjs/instrumentations/instrumentDurableObjectStorage.js +1 -1
- package/build/cjs/instrumentations/instrumentDurableObjectStorage.js.map +1 -1
- package/build/cjs/{d1.js → instrumentations/worker/instrumentD1.js} +10 -2
- package/build/cjs/instrumentations/worker/instrumentD1.js.map +1 -0
- package/build/cjs/instrumentations/worker/instrumentEnv.js +6 -0
- package/build/cjs/instrumentations/worker/instrumentEnv.js.map +1 -1
- package/build/cjs/integrations/httpServer.js.map +1 -1
- package/build/cjs/request.js +7 -3
- package/build/cjs/request.js.map +1 -1
- package/build/cjs/sdk.js +2 -3
- package/build/cjs/sdk.js.map +1 -1
- package/build/cjs/utils/isBinding.js +4 -0
- package/build/cjs/utils/isBinding.js.map +1 -1
- package/build/cjs/utils/traceLinks.js +6 -5
- package/build/cjs/utils/traceLinks.js.map +1 -1
- package/build/cjs/workflows.js +9 -1
- package/build/cjs/workflows.js.map +1 -1
- package/build/cjs/wrapMethodWithSentry.js +43 -66
- package/build/cjs/wrapMethodWithSentry.js.map +1 -1
- package/build/esm/client.js +4 -1
- package/build/esm/client.js.map +1 -1
- package/build/esm/durableobject.js +21 -20
- package/build/esm/durableobject.js.map +1 -1
- package/build/esm/index.js +1 -1
- package/build/esm/instrumentations/instrumentDurableObjectStorage.js +1 -1
- package/build/esm/instrumentations/instrumentDurableObjectStorage.js.map +1 -1
- package/build/esm/{d1.js → instrumentations/worker/instrumentD1.js} +10 -3
- package/build/esm/instrumentations/worker/instrumentD1.js.map +1 -0
- package/build/esm/instrumentations/worker/instrumentEnv.js +7 -1
- package/build/esm/instrumentations/worker/instrumentEnv.js.map +1 -1
- package/build/esm/integrations/httpServer.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/esm/request.js +7 -3
- package/build/esm/request.js.map +1 -1
- package/build/esm/sdk.js +2 -3
- package/build/esm/sdk.js.map +1 -1
- package/build/esm/utils/isBinding.js +4 -1
- package/build/esm/utils/isBinding.js.map +1 -1
- package/build/esm/utils/traceLinks.js +7 -6
- package/build/esm/utils/traceLinks.js.map +1 -1
- package/build/esm/workflows.js +9 -1
- package/build/esm/workflows.js.map +1 -1
- package/build/esm/wrapMethodWithSentry.js +45 -68
- package/build/esm/wrapMethodWithSentry.js.map +1 -1
- package/build/types/client.d.ts.map +1 -1
- package/build/types/durableobject.d.ts.map +1 -1
- package/build/types/index.d.ts +1 -1
- package/build/types/index.d.ts.map +1 -1
- package/build/types/{d1.d.ts → instrumentations/worker/instrumentD1.d.ts} +4 -2
- package/build/types/instrumentations/worker/instrumentD1.d.ts.map +1 -0
- package/build/types/instrumentations/worker/instrumentEnv.d.ts.map +1 -1
- package/build/types/integrations/httpServer.d.ts.map +1 -1
- package/build/types/request.d.ts.map +1 -1
- package/build/types/sdk.d.ts.map +1 -1
- package/build/types/utils/isBinding.d.ts +6 -1
- package/build/types/utils/isBinding.d.ts.map +1 -1
- package/build/types/utils/traceLinks.d.ts +3 -2
- package/build/types/utils/traceLinks.d.ts.map +1 -1
- package/build/types/workflows.d.ts.map +1 -1
- package/build/types/wrapMethodWithSentry.d.ts.map +1 -1
- package/build/types-ts3.8/index.d.ts +1 -1
- package/build/types-ts3.8/{d1.d.ts → instrumentations/worker/instrumentD1.d.ts} +4 -2
- package/build/types-ts3.8/utils/isBinding.d.ts +6 -1
- package/build/types-ts3.8/utils/traceLinks.d.ts +3 -2
- package/package.json +2 -2
- package/build/cjs/d1.js.map +0 -1
- package/build/esm/d1.js.map +0 -1
- package/build/types/d1.d.ts.map +0 -1
package/build/cjs/client.js
CHANGED
|
@@ -30,6 +30,9 @@ class CloudflareClient extends core.ServerRuntimeClient {
|
|
|
30
30
|
this._unsubscribeSpanStart = this.on("spanStart", (span) => {
|
|
31
31
|
const spanId = span.spanContext().spanId;
|
|
32
32
|
debugBuild.DEBUG_BUILD && core.debug.log("[CloudflareClient] Span started:", spanId);
|
|
33
|
+
if (!core.spanIsSampled(span)) {
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
33
36
|
this._pendingSpans.add(spanId);
|
|
34
37
|
if (!this._spanCompletionPromise) {
|
|
35
38
|
this._spanCompletionPromise = new Promise((resolve) => {
|
package/build/cjs/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sources":["../../src/client.ts"],"sourcesContent":["import type { ClientOptions, Options, ServerRuntimeClientOptions } from '@sentry/core';\nimport { applySdkMetadata, debug, ServerRuntimeClient } from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { makeFlushLock } from './flush';\nimport type { CloudflareTransportOptions } from './transport';\n\n/**\n * The Sentry Cloudflare SDK Client.\n *\n * @see CloudflareClientOptions for documentation on configuration options.\n * @see ServerRuntimeClient for usage documentation.\n */\nexport class CloudflareClient extends ServerRuntimeClient {\n private readonly _flushLock: ReturnType<typeof makeFlushLock> | void;\n private _pendingSpans: Set<string> = new Set();\n private _spanCompletionPromise: Promise<void> | null = null;\n private _resolveSpanCompletion: (() => void) | null = null;\n\n private _unsubscribeSpanStart: (() => void) | null = null;\n private _unsubscribeSpanEnd: (() => void) | null = null;\n\n /**\n * Creates a new Cloudflare SDK instance.\n * @param options Configuration options for this SDK.\n */\n public constructor(options: CloudflareClientOptions) {\n applySdkMetadata(options, 'cloudflare');\n options._metadata = options._metadata || {};\n const { flushLock, ...serverOptions } = options;\n\n const clientOptions: ServerRuntimeClientOptions = {\n ...serverOptions,\n platform: 'javascript',\n // TODO: Grab version information\n runtime: { name: 'cloudflare' },\n // TODO: Add server name\n _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 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"],"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;A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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;;;;"}
|
|
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;AAA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W,MAAM;AACf,YAAAD,sBAAA,IACEC,UAAA,CAAM,GAAA,CAAI,kDAAA,EAAoD,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;;;;"}
|
|
@@ -7,17 +7,10 @@ const instrumentEnv = require('./instrumentations/worker/instrumentEnv.js');
|
|
|
7
7
|
const options = require('./options.js');
|
|
8
8
|
const request = require('./request.js');
|
|
9
9
|
const instrumentContext = require('./utils/instrumentContext.js');
|
|
10
|
+
const rpcMeta = require('./utils/rpcMeta.js');
|
|
10
11
|
const rpcOptions = require('./utils/rpcOptions.js');
|
|
11
12
|
const wrapMethodWithSentry = require('./wrapMethodWithSentry.js');
|
|
12
13
|
|
|
13
|
-
const BUILT_IN_DO_METHODS = /* @__PURE__ */ new Set([
|
|
14
|
-
"constructor",
|
|
15
|
-
"fetch",
|
|
16
|
-
"alarm",
|
|
17
|
-
"webSocketError",
|
|
18
|
-
"webSocketClose",
|
|
19
|
-
"webSocketMessage"
|
|
20
|
-
]);
|
|
21
14
|
function instrumentDurableObjectWithSentry(optionsCallback, DurableObjectClass) {
|
|
22
15
|
return new Proxy(DurableObjectClass, {
|
|
23
16
|
construct(target, [ctx, env]) {
|
|
@@ -71,31 +64,39 @@ function instrumentDurableObjectWithSentry(optionsCallback, DurableObjectClass)
|
|
|
71
64
|
}
|
|
72
65
|
const instrumentPrototypeMethods = Array.isArray(options$1.instrumentPrototypeMethods) ? options$1.instrumentPrototypeMethods : void 0;
|
|
73
66
|
const allowSet = instrumentPrototypeMethods ? new Set(instrumentPrototypeMethods) : null;
|
|
74
|
-
const
|
|
67
|
+
const alwaysTrace = options$1.enableRpcTracePropagation === void 0;
|
|
68
|
+
const methodCache = /* @__PURE__ */ new Map();
|
|
75
69
|
return new Proxy(obj, {
|
|
76
70
|
get(proxyTarget, prop, receiver) {
|
|
77
71
|
const value = Reflect.get(proxyTarget, prop, receiver);
|
|
78
|
-
if (typeof prop !== "string" ||
|
|
72
|
+
if (typeof prop !== "string" || typeof value !== "function" || prop === "constructor") {
|
|
79
73
|
return value;
|
|
80
74
|
}
|
|
81
|
-
const cached =
|
|
75
|
+
const cached = methodCache.get(prop);
|
|
82
76
|
if (cached) {
|
|
83
77
|
return cached;
|
|
84
78
|
}
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
return
|
|
79
|
+
const boundMethod = value.bind(proxyTarget);
|
|
80
|
+
if (prop in Object.prototype || Object.prototype.hasOwnProperty.call(proxyTarget, prop) || allowSet && !allowSet.has(prop)) {
|
|
81
|
+
methodCache.set(prop, boundMethod);
|
|
82
|
+
return boundMethod;
|
|
89
83
|
}
|
|
90
|
-
const
|
|
91
|
-
const wrapped = wrapMethodWithSentry.wrapMethodWithSentry(
|
|
84
|
+
const tracedMethod = wrapMethodWithSentry.wrapMethodWithSentry(
|
|
92
85
|
{ options: options$1, context, spanName: prop, spanOp: "rpc" },
|
|
93
|
-
|
|
86
|
+
boundMethod,
|
|
94
87
|
void 0,
|
|
95
88
|
true
|
|
96
89
|
);
|
|
97
|
-
|
|
98
|
-
|
|
90
|
+
if (alwaysTrace) {
|
|
91
|
+
methodCache.set(prop, tracedMethod);
|
|
92
|
+
return tracedMethod;
|
|
93
|
+
}
|
|
94
|
+
const wrappedMethod = ((...args) => {
|
|
95
|
+
const { rpcMeta: rpcMeta$1 } = rpcMeta.extractRpcMeta(args);
|
|
96
|
+
return rpcMeta$1 ? tracedMethod(...args) : boundMethod(...args);
|
|
97
|
+
});
|
|
98
|
+
methodCache.set(prop, wrappedMethod);
|
|
99
|
+
return wrappedMethod;
|
|
99
100
|
}
|
|
100
101
|
});
|
|
101
102
|
}
|
|
@@ -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 { getEffectiveRpcPropagation } from './utils/rpcOptions';\nimport { type UncheckedMethod, wrapMethodWithSentry } from './wrapMethodWithSentry';\n\nconst BUILT_IN_DO_METHODS = new Set([\n 'constructor',\n 'fetch',\n 'alarm',\n 'webSocketError',\n 'webSocketClose',\n 'webSocketMessage',\n]);\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 const instrumentPrototypeMethods = Array.isArray(options.instrumentPrototypeMethods)\n ? options.instrumentPrototypeMethods\n : undefined;\n const allowSet = instrumentPrototypeMethods ? new Set(instrumentPrototypeMethods) : null;\n\n // Return a Proxy that lazily wraps prototype methods on access.\n // This avoids iterating the prototype chain at construction time —\n // we only check if a property is an RPC method when it's accessed.\n const rpcMethodCache = 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' || BUILT_IN_DO_METHODS.has(prop)) {\n return value;\n }\n\n const cached = rpcMethodCache.get(prop);\n\n if (cached) {\n return cached;\n }\n\n if (\n typeof value !== 'function' ||\n Object.prototype.hasOwnProperty.call(proxyTarget, prop) ||\n (allowSet && !allowSet.has(prop)) ||\n // Exclude inherited Object.prototype methods (toString, valueOf, etc.)\n // These are not RPC methods and should not create spans\n prop in Object.prototype\n ) {\n return value;\n }\n\n // Bind the method to the original object to ensure private fields work correctly.\n // When called via the Proxy, `this` would be the Proxy, but private fields require\n // the original object. Bound functions ignore the thisArg passed via Reflect.apply.\n const boundValue = (value as UncheckedMethod).bind(proxyTarget);\n\n const wrapped = wrapMethodWithSentry(\n { options, context, spanName: prop, spanOp: 'rpc' },\n boundValue,\n undefined,\n true,\n );\n\n rpcMethodCache.set(prop, wrapped);\n\n return wrapped;\n },\n });\n },\n });\n}\n"],"names":["setAsyncLocalStorageAsyncContextStrategy","instrumentContext","options","getFinalOptions","instrumentEnv","ensureInstrumented","target","wrapRequestHandler","wrapMethodWithSentry","captureException","getEffectiveRpcPropagation"],"mappings":";;;;;;;;;;;;AAaA,MAAM,mBAAA,uBAA0B,GAAA,CAAI;AAAA,EAClC,aAAA;AAAA,EACA,OAAA;AAAA,EACA,OAAA;AAAA,EACA,gBAAA;AAAA,EACA,gBAAA;AAAA,EACA;AACF,CAAC,CAAA;AAmCM,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,CAA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,QAAA,IAAY,CAAC,QAAA,CAAS,IAAI,IAAI,CAAA;AAAA;AAAA,UAG/B,IAAA,IAAQ,OAAO,SAAA,EACf;AACA,YAAA,OAAO,KAAA;AAAA,UACT;AAKA,UAAA,MAAM,UAAA,GAAc,KAAA,CAA0B,IAAA,CAAK,WAAW,CAAA;AAE9D,UAAA,MAAM,OAAA,GAAUM,yCAAA;AAAA,YACd,WAAEN,SAAA,EAAS,OAAA,EAAS,QAAA,EAAU,IAAA,EAAM,QAAQ,KAAA,EAAM;AAAA,YAClD,UAAA;AAAA,YACA,KAAA,CAAA;AAAA,YACA;AAAA,WACF;AAEA,UAAA,cAAA,CAAe,GAAA,CAAI,MAAM,OAAO,CAAA;AAEhC,UAAA,OAAO,OAAA;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]) {\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 const instrumentPrototypeMethods = Array.isArray(options.instrumentPrototypeMethods)\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,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IACE,IAAA,IAAQ,MAAA,CAAO,SAAA,IACf,MAAA,CAAO,UAAU,cAAA,CAAe,IAAA,CAAK,WAAA,EAAa,IAAI,KACrD,QAAA,IAAY,CAAC,QAAA,CAAS,GAAA,CAAI,IAAI,CAAA,EAC/B;AACA,YAAA,WAAA,CAAY,GAAA,CAAI,MAAM,WAAW,CAAA;AAEjC,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;;;;"}
|
package/build/cjs/index.js
CHANGED
|
@@ -11,7 +11,7 @@ const httpServer = require('./integrations/httpServer.js');
|
|
|
11
11
|
const fetch = require('./integrations/fetch.js');
|
|
12
12
|
const vercelai = require('./integrations/tracing/vercelai.js');
|
|
13
13
|
const hono = require('./integrations/hono.js');
|
|
14
|
-
const
|
|
14
|
+
const instrumentD1 = require('./instrumentations/worker/instrumentD1.js');
|
|
15
15
|
const workflows = require('./workflows.js');
|
|
16
16
|
const async = require('./async.js');
|
|
17
17
|
|
|
@@ -113,7 +113,7 @@ exports.httpServerIntegration = httpServer.httpServerIntegration;
|
|
|
113
113
|
exports.fetchIntegration = fetch.fetchIntegration;
|
|
114
114
|
exports.vercelAIIntegration = vercelai.vercelAIIntegration;
|
|
115
115
|
exports.honoIntegration = hono.honoIntegration;
|
|
116
|
-
exports.instrumentD1WithSentry =
|
|
116
|
+
exports.instrumentD1WithSentry = instrumentD1.instrumentD1WithSentry;
|
|
117
117
|
exports.instrumentWorkflowWithSentry = workflows.instrumentWorkflowWithSentry;
|
|
118
118
|
exports.setAsyncLocalStorageAsyncContextStrategy = async.setAsyncLocalStorageAsyncContextStrategy;
|
|
119
119
|
//# sourceMappingURL=index.js.map
|
|
@@ -30,7 +30,7 @@ function instrumentDurableObjectStorage(storage, waitUntil) {
|
|
|
30
30
|
() => {
|
|
31
31
|
const teardown = async () => {
|
|
32
32
|
if (methodName === "setAlarm") {
|
|
33
|
-
|
|
33
|
+
traceLinks.storeSpanContext(target, "alarm");
|
|
34
34
|
}
|
|
35
35
|
};
|
|
36
36
|
const result = original.apply(target, args);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"instrumentDurableObjectStorage.js","sources":["../../../src/instrumentations/instrumentDurableObjectStorage.ts"],"sourcesContent":["import type { DurableObjectStorage } from '@cloudflare/workers-types';\nimport { isThenable, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, startSpan } from '@sentry/core';\nimport { storeSpanContext } from '../utils/traceLinks';\n\nconst STORAGE_METHODS_TO_INSTRUMENT = ['get', 'put', 'delete', 'list', 'setAlarm', 'getAlarm', 'deleteAlarm'] as const;\n\ntype StorageMethod = (typeof STORAGE_METHODS_TO_INSTRUMENT)[number];\n\ntype WaitUntil = (promise: Promise<unknown>) => void;\n\n/**\n * Instruments DurableObjectStorage methods with Sentry spans.\n *\n * Wraps the following async methods:\n * - get, put, delete, list (KV API)\n * - setAlarm, getAlarm, deleteAlarm (Alarm API)\n *\n * When setAlarm is called, it also stores the current span context so that when\n * the alarm fires later, it can link back to the trace that called setAlarm.\n *\n * @param storage - The DurableObjectStorage instance to instrument\n * @param waitUntil - Optional waitUntil function to defer span context storage\n * @returns An instrumented DurableObjectStorage instance\n */\nexport function instrumentDurableObjectStorage(\n storage: DurableObjectStorage,\n waitUntil?: WaitUntil,\n): DurableObjectStorage {\n return new Proxy(storage, {\n get(target, prop, _receiver) {\n // Use `target` as the receiver instead of the proxy (`_receiver`).\n // Native workerd getters (e.g., `storage.sql`) validate `this` via\n // internal slots. Passing the proxy as receiver breaks that check,\n // causing \"Illegal invocation: function called with incorrect `this`\n // reference\" errors.\n const original = Reflect.get(target, prop, target);\n\n if (typeof original !== 'function') {\n return original;\n }\n\n const methodName = prop as string;\n if (!STORAGE_METHODS_TO_INSTRUMENT.includes(methodName as StorageMethod)) {\n return (original as (...args: unknown[]) => unknown).bind(target);\n }\n\n return function (this: unknown, ...args: unknown[]) {\n return startSpan(\n {\n // Use underscore naming to match Cloudflare's native instrumentation (e.g., \"durable_object_storage_get\")\n name: `durable_object_storage_${methodName}`,\n op: 'db',\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.cloudflare.durable_object',\n 'db.system.name': 'cloudflare.durable_object.storage',\n 'db.operation.name': methodName,\n },\n },\n () => {\n const teardown = async (): Promise<void> => {\n // When setAlarm is called, store the current span context so that when the alarm\n // fires later, it can link back to the trace that called setAlarm.\n // We use the original (uninstrumented) storage (target) to avoid creating a span\n // for this internal operation. The storage is deferred via waitUntil to not block.\n if (methodName === 'setAlarm') {\n
|
|
1
|
+
{"version":3,"file":"instrumentDurableObjectStorage.js","sources":["../../../src/instrumentations/instrumentDurableObjectStorage.ts"],"sourcesContent":["import type { DurableObjectStorage } from '@cloudflare/workers-types';\nimport { isThenable, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, startSpan } from '@sentry/core';\nimport { storeSpanContext } from '../utils/traceLinks';\n\nconst STORAGE_METHODS_TO_INSTRUMENT = ['get', 'put', 'delete', 'list', 'setAlarm', 'getAlarm', 'deleteAlarm'] as const;\n\ntype StorageMethod = (typeof STORAGE_METHODS_TO_INSTRUMENT)[number];\n\ntype WaitUntil = (promise: Promise<unknown>) => void;\n\n/**\n * Instruments DurableObjectStorage methods with Sentry spans.\n *\n * Wraps the following async methods:\n * - get, put, delete, list (KV API)\n * - setAlarm, getAlarm, deleteAlarm (Alarm API)\n *\n * When setAlarm is called, it also stores the current span context so that when\n * the alarm fires later, it can link back to the trace that called setAlarm.\n *\n * @param storage - The DurableObjectStorage instance to instrument\n * @param waitUntil - Optional waitUntil function to defer span context storage\n * @returns An instrumented DurableObjectStorage instance\n */\nexport function instrumentDurableObjectStorage(\n storage: DurableObjectStorage,\n waitUntil?: WaitUntil,\n): DurableObjectStorage {\n return new Proxy(storage, {\n get(target, prop, _receiver) {\n // Use `target` as the receiver instead of the proxy (`_receiver`).\n // Native workerd getters (e.g., `storage.sql`) validate `this` via\n // internal slots. Passing the proxy as receiver breaks that check,\n // causing \"Illegal invocation: function called with incorrect `this`\n // reference\" errors.\n const original = Reflect.get(target, prop, target);\n\n if (typeof original !== 'function') {\n return original;\n }\n\n const methodName = prop as string;\n if (!STORAGE_METHODS_TO_INSTRUMENT.includes(methodName as StorageMethod)) {\n return (original as (...args: unknown[]) => unknown).bind(target);\n }\n\n return function (this: unknown, ...args: unknown[]) {\n return startSpan(\n {\n // Use underscore naming to match Cloudflare's native instrumentation (e.g., \"durable_object_storage_get\")\n name: `durable_object_storage_${methodName}`,\n op: 'db',\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.cloudflare.durable_object',\n 'db.system.name': 'cloudflare.durable_object.storage',\n 'db.operation.name': methodName,\n },\n },\n () => {\n const teardown = async (): Promise<void> => {\n // When setAlarm is called, store the current span context so that when the alarm\n // fires later, it can link back to the trace that called setAlarm.\n // We use the original (uninstrumented) storage (target) to avoid creating a span\n // for this internal operation. The storage is deferred via waitUntil to not block.\n if (methodName === 'setAlarm') {\n storeSpanContext(target, 'alarm');\n }\n };\n\n const result = (original as (...args: unknown[]) => unknown).apply(target, args);\n\n if (!isThenable(result)) {\n waitUntil?.(teardown());\n\n return result;\n }\n\n return result.then(\n res => {\n waitUntil?.(teardown());\n return res;\n },\n e => {\n throw e;\n },\n );\n },\n );\n };\n },\n });\n}\n"],"names":["startSpan","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","storeSpanContext","isThenable"],"mappings":";;;;;AAIA,MAAM,6BAAA,GAAgC,CAAC,KAAA,EAAO,KAAA,EAAO,UAAU,MAAA,EAAQ,UAAA,EAAY,YAAY,aAAa,CAAA;AAoBrG,SAAS,8BAAA,CACd,SACA,SAAA,EACsB;AACtB,EAAA,OAAO,IAAI,MAAM,OAAA,EAAS;AAAA,IACxB,GAAA,CAAI,MAAA,EAAQ,IAAA,EAAM,SAAA,EAAW;AAM3B,MAAA,MAAM,QAAA,GAAW,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,MAAM,MAAM,CAAA;AAEjD,MAAA,IAAI,OAAO,aAAa,UAAA,EAAY;AAClC,QAAA,OAAO,QAAA;AAAA,MACT;AAEA,MAAA,MAAM,UAAA,GAAa,IAAA;AACnB,MAAA,IAAI,CAAC,6BAAA,CAA8B,QAAA,CAAS,UAA2B,CAAA,EAAG;AACxE,QAAA,OAAQ,QAAA,CAA6C,KAAK,MAAM,CAAA;AAAA,MAClE;AAEA,MAAA,OAAO,YAA4B,IAAA,EAAiB;AAClD,QAAA,OAAOA,cAAA;AAAA,UACL;AAAA;AAAA,YAEE,IAAA,EAAM,0BAA0B,UAAU,CAAA,CAAA;AAAA,YAC1C,EAAA,EAAI,IAAA;AAAA,YACJ,UAAA,EAAY;AAAA,cACV,CAACC,qCAAgC,GAAG,mCAAA;AAAA,cACpC,gBAAA,EAAkB,mCAAA;AAAA,cAClB,mBAAA,EAAqB;AAAA;AACvB,WACF;AAAA,UACA,MAAM;AACJ,YAAA,MAAM,WAAW,YAA2B;AAK1C,cAAA,IAAI,eAAe,UAAA,EAAY;AAC7B,gBAAAC,2BAAA,CAAiB,QAAQ,OAAO,CAAA;AAAA,cAClC;AAAA,YACF,CAAA;AAEA,YAAA,MAAM,MAAA,GAAU,QAAA,CAA6C,KAAA,CAAM,MAAA,EAAQ,IAAI,CAAA;AAE/E,YAAA,IAAI,CAACC,eAAA,CAAW,MAAM,CAAA,EAAG;AACvB,cAAA,SAAA,GAAY,UAAU,CAAA;AAEtB,cAAA,OAAO,MAAA;AAAA,YACT;AAEA,YAAA,OAAO,MAAA,CAAO,IAAA;AAAA,cACZ,CAAA,GAAA,KAAO;AACL,gBAAA,SAAA,GAAY,UAAU,CAAA;AACtB,gBAAA,OAAO,GAAA;AAAA,cACT,CAAA;AAAA,cACA,CAAA,CAAA,KAAK;AACH,gBAAA,MAAM,CAAA;AAAA,cACR;AAAA,aACF;AAAA,UACF;AAAA,SACF;AAAA,MACF,CAAA;AAAA,IACF;AAAA,GACD,CAAA;AACH;;;;"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
|
|
3
3
|
const core = require('@sentry/core');
|
|
4
|
+
const instrument = require('../../instrument.js');
|
|
4
5
|
|
|
5
6
|
const patchedStatement = /* @__PURE__ */ new WeakSet();
|
|
6
7
|
function instrumentD1PreparedStatementQueries(statement, query) {
|
|
@@ -89,7 +90,7 @@ function createStartSpanOptions(query, type) {
|
|
|
89
90
|
}
|
|
90
91
|
};
|
|
91
92
|
}
|
|
92
|
-
function
|
|
93
|
+
function _instrumentD1(db) {
|
|
93
94
|
db.prepare = new Proxy(db.prepare, {
|
|
94
95
|
apply(target, thisArg, args) {
|
|
95
96
|
const [query] = args;
|
|
@@ -98,6 +99,13 @@ function instrumentD1WithSentry(db) {
|
|
|
98
99
|
});
|
|
99
100
|
return db;
|
|
100
101
|
}
|
|
102
|
+
function instrumentD1(db) {
|
|
103
|
+
return instrument.ensureInstrumented(db, _instrumentD1);
|
|
104
|
+
}
|
|
105
|
+
function instrumentD1WithSentry(db) {
|
|
106
|
+
return instrumentD1(db);
|
|
107
|
+
}
|
|
101
108
|
|
|
109
|
+
exports.instrumentD1 = instrumentD1;
|
|
102
110
|
exports.instrumentD1WithSentry = instrumentD1WithSentry;
|
|
103
|
-
//# sourceMappingURL=
|
|
111
|
+
//# sourceMappingURL=instrumentD1.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"instrumentD1.js","sources":["../../../../src/instrumentations/worker/instrumentD1.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/unbound-method */\nimport type { D1Database, D1PreparedStatement, D1Response } from '@cloudflare/workers-types';\nimport type { Span, SpanAttributes, StartSpanOptions } from '@sentry/core';\nimport { addBreadcrumb, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SPAN_STATUS_ERROR, startSpan } from '@sentry/core';\nimport { ensureInstrumented } from '../../instrument';\n\n// Patching is based on internal Cloudflare D1 API\n// https://github.com/cloudflare/workerd/blob/cd5279e7b305003f1d9c851e73efa9d67e4b68b2/src/cloudflare/internal/d1-api.ts\n\nconst patchedStatement = new WeakSet<D1PreparedStatement>();\n\n/**\n * Patches the query methods of a Cloudflare D1 prepared statement with Sentry.\n */\nfunction instrumentD1PreparedStatementQueries(statement: D1PreparedStatement, query: string): D1PreparedStatement {\n if (patchedStatement.has(statement)) {\n return statement;\n }\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n statement.first = new Proxy(statement.first, {\n apply(target, thisArg, args: Parameters<typeof statement.first>) {\n return startSpan(createStartSpanOptions(query, 'first'), async () => {\n const res = await Reflect.apply(target, thisArg, args);\n createD1Breadcrumb(query, 'first');\n return res;\n });\n },\n });\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n statement.run = new Proxy(statement.run, {\n apply(target, thisArg, args: Parameters<typeof statement.run>) {\n return startSpan(createStartSpanOptions(query, 'run'), async span => {\n const d1Response = await Reflect.apply(target, thisArg, args);\n applyD1ReturnObjectToSpan(span, d1Response);\n createD1Breadcrumb(query, 'run', d1Response);\n return d1Response;\n });\n },\n });\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n statement.all = new Proxy(statement.all, {\n apply(target, thisArg, args: Parameters<typeof statement.all>) {\n return startSpan(createStartSpanOptions(query, 'all'), async span => {\n const d1Result = await Reflect.apply(target, thisArg, args);\n applyD1ReturnObjectToSpan(span, d1Result);\n createD1Breadcrumb(query, 'all', d1Result);\n return d1Result;\n });\n },\n });\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n statement.raw = new Proxy(statement.raw, {\n apply(target, thisArg, args: Parameters<typeof statement.raw>) {\n return startSpan(createStartSpanOptions(query, 'raw'), async () => {\n const res = await Reflect.apply(target, thisArg, args);\n createD1Breadcrumb(query, 'raw');\n return res;\n });\n },\n });\n\n patchedStatement.add(statement);\n\n return statement;\n}\n\n/**\n * Instruments a Cloudflare D1 prepared statement with Sentry.\n *\n * This is meant to be used as a top-level call, under the hood it calls `instrumentD1PreparedStatementQueries`\n * to patch the query methods. The reason for this abstraction is to ensure that the `bind` method is also patched.\n */\nfunction instrumentD1PreparedStatement(statement: D1PreparedStatement, query: string): D1PreparedStatement {\n // statement.bind() returns a new instance of D1PreparedStatement, so we have to patch it as well.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n statement.bind = new Proxy(statement.bind, {\n apply(target, thisArg, args: Parameters<typeof statement.bind>) {\n return instrumentD1PreparedStatementQueries(Reflect.apply(target, thisArg, args), query);\n },\n });\n\n return instrumentD1PreparedStatementQueries(statement, query);\n}\n\n/**\n * Add D1Response meta information to a span.\n *\n * See: https://developers.cloudflare.com/d1/build-with-d1/d1-client-api/#return-object\n */\nfunction applyD1ReturnObjectToSpan(span: Span, d1Result: D1Response): void {\n if (!d1Result.success) {\n span.setStatus({ code: SPAN_STATUS_ERROR });\n }\n\n span.setAttributes(getAttributesFromD1Response(d1Result));\n}\n\nfunction getAttributesFromD1Response(d1Result: D1Response): SpanAttributes {\n return {\n 'cloudflare.d1.duration': d1Result.meta.duration,\n 'cloudflare.d1.rows_read': d1Result.meta.rows_read,\n 'cloudflare.d1.rows_written': d1Result.meta.rows_written,\n };\n}\n\nfunction createD1Breadcrumb(query: string, type: 'first' | 'run' | 'all' | 'raw', d1Result?: D1Response): void {\n addBreadcrumb({\n category: 'query',\n message: query,\n data: {\n ...(d1Result ? getAttributesFromD1Response(d1Result) : {}),\n 'cloudflare.d1.query_type': type,\n },\n });\n}\n\nfunction createStartSpanOptions(query: string, type: 'first' | 'run' | 'all' | 'raw'): StartSpanOptions {\n return {\n op: 'db.query',\n name: query,\n attributes: {\n 'cloudflare.d1.query_type': type,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.cloudflare.d1',\n },\n };\n}\n\nfunction _instrumentD1(db: D1Database): D1Database {\n db.prepare = new Proxy(db.prepare, {\n apply(target, thisArg, args: Parameters<typeof db.prepare>) {\n const [query] = args;\n return instrumentD1PreparedStatement(Reflect.apply(target, thisArg, args), query);\n },\n });\n\n return db;\n}\n\nexport function instrumentD1(db: D1Database): D1Database {\n return ensureInstrumented(db, _instrumentD1);\n}\n\n// todo(v11): Remove this export\n/**\n * Instruments Cloudflare D1 bindings with Sentry.\n *\n * @deprecated `withSentry()` automatically instruments all D1 bindings via `env`\n * so this function is not needed anymore. It will be removed in the next major version of the SDK.\n *\n * @example\n *\n * ```js\n * // env.DB is the D1 DB binding configured in your `wrangler.toml`\n * const db = instrumentD1WithSentry(env.DB);\n * // Now you can use the database as usual\n * await db.prepare('SELECT * FROM table WHERE id = ?').bind(1).run();\n * ```\n */\nexport function instrumentD1WithSentry(db: D1Database): D1Database {\n return instrumentD1(db);\n}\n"],"names":["startSpan","SPAN_STATUS_ERROR","addBreadcrumb","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","ensureInstrumented"],"mappings":";;;;;AASA,MAAM,gBAAA,uBA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AA,CAAQ,KAAA,CAAM,QAAQ,OAAA,EAAS,IAAI,GAAG,KAAK,CAAA;AAAA,IAClF;AAAA,GACD,CAAA;AAED,EAAA,OAAO,EAAA;AACT;AAEO,SAAS,aAAa,EAAA,EAA4B;AACvD,EAAA,OAAOC,6BAAA,CAAmB,IAAI,aAAa,CAAA;AAC7C;AAkBO,SAAS,uBAAuB,EAAA,EAA4B;AACjE,EAAA,OAAO,aAAa,EAAE,CAAA;AACxB;;;;;"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
|
|
3
3
|
const isBinding = require('../../utils/isBinding.js');
|
|
4
|
+
const instrumentD1 = require('./instrumentD1.js');
|
|
4
5
|
const rpcMeta = require('../../utils/rpcMeta.js');
|
|
5
6
|
const rpcOptions = require('../../utils/rpcOptions.js');
|
|
6
7
|
const instrumentDurableObjectNamespace = require('../instrumentDurableObjectNamespace.js');
|
|
@@ -26,6 +27,11 @@ function instrumentEnv(env, options) {
|
|
|
26
27
|
if (cached) {
|
|
27
28
|
return cached;
|
|
28
29
|
}
|
|
30
|
+
if (isBinding.isD1Database(item)) {
|
|
31
|
+
const instrumented = instrumentD1.instrumentD1(item);
|
|
32
|
+
instrumentedBindings.set(item, instrumented);
|
|
33
|
+
return instrumented;
|
|
34
|
+
}
|
|
29
35
|
if (isBinding.isQueue(item)) {
|
|
30
36
|
const bindingName = typeof prop === "string" ? prop : String(prop);
|
|
31
37
|
const instrumented = instrumentQueueProducer.instrumentQueueProducer(item, bindingName);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"instrumentEnv.js","sources":["../../../../src/instrumentations/worker/instrumentEnv.ts"],"sourcesContent":["import type { CloudflareOptions } from '../../client';\nimport { isDurableObjectNamespace, isJSRPC, isQueue } from '../../utils/isBinding';\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';\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 *\n * Extensible for future binding types (KV, D1, etc.).\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 (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 (!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","isQueue","instrumentQueueProducer","isDurableObjectNamespace","instrumentDurableObjectNamespace","isJSRPC","target","instrumentFetcher","STUB_NON_RPC_METHODS","appendRpcMeta"],"mappings":"
|
|
1
|
+
{"version":3,"file":"instrumentEnv.js","sources":["../../../../src/instrumentations/worker/instrumentEnv.ts"],"sourcesContent":["import type { CloudflareOptions } from '../../client';\nimport { isD1Database, isDurableObjectNamespace, isJSRPC, isQueue } 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';\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 *\n * Extensible for future binding types (KV, D1, etc.).\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 (!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","isDurableObjectNamespace","instrumentDurableObjectNamespace","isJSRPC","target","instrumentFetcher","STUB_NON_RPC_METHODS","appendRpcMeta"],"mappings":";;;;;;;;;;AASA,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;AAgBnD,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,GAAUA,qCAAA,CAA2B,OAAO,CAAA,GAAI,KAAA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G;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":"httpServer.js","sources":["../../../src/integrations/httpServer.ts"],"sourcesContent":["import type { Client, IntegrationFn, MaxRequestBodySize } from '@sentry/core';\nimport { captureBodyFromWinterCGRequest, defineIntegration, getIsolationScope } from '@sentry/core';\n\nconst INTEGRATION_NAME = 'HttpServer';\n\nexport interface HttpServerIntegrationOptions {\n /**\n * Controls the maximum size of incoming request bodies attached to events.\n *\n * Only applies to requests with textual content types (text/*, application/json,\n * application/x-www-form-urlencoded, application/xml, application/graphql).\n * Binary data is not captured.\n *\n * Available options:\n * - `'none'`: No request bodies will be attached\n * - `'small'`: Request bodies up to 1,000 bytes will be attached\n * - `'medium'`: Request bodies up to 10,000 bytes will be attached (default)\n * - `'always'`: Request bodies will always be attached (up to 1MB limit)\n *\n * @default 'medium'\n */\n maxRequestBodySize?: MaxRequestBodySize;\n\n /**\n * Do not capture the request body for incoming HTTP requests to URLs where the given callback returns `true`.\n * This can be useful for long running requests where the body is not needed, health check endpoints,\n * or requests containing sensitive data that should not be captured.\n *\n * @param url The full URL of the incoming request, including query string, protocol, host, etc.\n * @param request The incoming Request object.\n * @returns `true` to skip body capture for this request, `false` to capture normally.\n *\n * @example\n * ```ts\n * Sentry.httpServerIntegration({\n * ignoreRequestBody: (url) => url.includes('/health') || url.includes('/upload'),\n * })\n * ```\n */\n ignoreRequestBody?: (url: string, request: Request) => boolean;\n}\n\ninterface HttpServerIntegrationInstance {\n name: string;\n maxRequestBodySize: MaxRequestBodySize;\n ignoreRequestBody?: (url: string, request: Request) => boolean;\n}\n\nconst _httpServerIntegration = ((options: HttpServerIntegrationOptions = {}): HttpServerIntegrationInstance => {\n return {\n name: INTEGRATION_NAME,\n maxRequestBodySize: options.maxRequestBodySize ?? 'medium',\n ignoreRequestBody: options.ignoreRequestBody,\n };\n}) satisfies IntegrationFn;\n\n/**\n * Configures incoming HTTP request handling for Cloudflare Workers.\n *\n * This integration controls how incoming HTTP request data is captured,\n * matching the API of `httpServerIntegration` in Node.js.\n *\n * @example\n * ```ts\n * Sentry.init({\n * integrations: [\n * Sentry.httpServerIntegration({\n * maxRequestBodySize: 'medium',\n * ignoreRequestBody: (url) => url.includes('/health'),\n * }),\n * ],\n * });\n * ```\n */\nexport const httpServerIntegration = defineIntegration(_httpServerIntegration);\n\n/**\n * Capture the request body based on the HttpServer integration config.\n * Called internally by `wrapRequestHandler`.\n */\nexport async function captureIncomingRequestBody(client: Client, request: Request): Promise<void> {\n const integration = client.getIntegrationByName<HttpServerIntegrationInstance>(INTEGRATION_NAME);\n\n if (!integration) {\n return;\n }\n\n const maxRequestBodySize = integration.maxRequestBodySize;\n\n if (maxRequestBodySize === 'none') {\n return;\n }\n\n // Skip GET and HEAD requests - they don't have bodies\n // Also skip OPTIONS, even if they may have a body, they might not give a lot of extra value\n if (request.method === 'GET' || request.method === 'HEAD' || request.method === 'OPTIONS') {\n return;\n }\n\n if (integration.ignoreRequestBody?.(request.url, request)) {\n return;\n }\n\n const isolationScope = getIsolationScope();\n await captureBodyFromWinterCGRequest(request, isolationScope, maxRequestBodySize);\n}\n"],"names":["defineIntegration","getIsolationScope","captureBodyFromWinterCGRequest"],"mappings":";;;;AAGA,MAAM,gBAAA,GAAmB,YAAA;AA6CzB,MAAM,sBAAA,IAA0B,CAAC,OAAA,GAAwC,EAAC,KAAqC;AAC7G,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,kBAAA,EAAoB,QAAQ,kBAAA,IAAsB,QAAA;AAAA,IAClD,mBAAmB,OAAA,CAAQ;AAAA,GAC7B;AACF,CAAA,CAAA;AAoBO,MAAM,qBAAA,GAAwBA,uBAAkB,sBAAsB;AAM7E,eAAsB,0BAAA,CAA2B,QAAgB,OAAA,EAAiC;AAChG,EAAA,MAAM,WAAA,GAAc,MAAA,CAAO,oBAAA,CAAoD,gBAAgB,CAAA;AAE/F,EAAA,IAAI,CAAC,WAAA,EAAa;AAChB,IAAA;AAAA,EACF;
|
|
1
|
+
{"version":3,"file":"httpServer.js","sources":["../../../src/integrations/httpServer.ts"],"sourcesContent":["import type { Client, IntegrationFn, MaxRequestBodySize } from '@sentry/core';\nimport { captureBodyFromWinterCGRequest, defineIntegration, getIsolationScope } from '@sentry/core';\n\nconst INTEGRATION_NAME = 'HttpServer';\n\nexport interface HttpServerIntegrationOptions {\n /**\n * Controls the maximum size of incoming request bodies attached to events.\n *\n * Only applies to requests with textual content types (text/*, application/json,\n * application/x-www-form-urlencoded, application/xml, application/graphql).\n * Binary data is not captured.\n *\n * Available options:\n * - `'none'`: No request bodies will be attached\n * - `'small'`: Request bodies up to 1,000 bytes will be attached\n * - `'medium'`: Request bodies up to 10,000 bytes will be attached (default)\n * - `'always'`: Request bodies will always be attached (up to 1MB limit)\n *\n * @default 'medium'\n */\n maxRequestBodySize?: MaxRequestBodySize;\n\n /**\n * Do not capture the request body for incoming HTTP requests to URLs where the given callback returns `true`.\n * This can be useful for long running requests where the body is not needed, health check endpoints,\n * or requests containing sensitive data that should not be captured.\n *\n * @param url The full URL of the incoming request, including query string, protocol, host, etc.\n * @param request The incoming Request object.\n * @returns `true` to skip body capture for this request, `false` to capture normally.\n *\n * @example\n * ```ts\n * Sentry.httpServerIntegration({\n * ignoreRequestBody: (url) => url.includes('/health') || url.includes('/upload'),\n * })\n * ```\n */\n ignoreRequestBody?: (url: string, request: Request) => boolean;\n}\n\ninterface HttpServerIntegrationInstance {\n name: string;\n maxRequestBodySize: MaxRequestBodySize;\n ignoreRequestBody?: (url: string, request: Request) => boolean;\n}\n\nconst _httpServerIntegration = ((options: HttpServerIntegrationOptions = {}): HttpServerIntegrationInstance => {\n return {\n name: INTEGRATION_NAME,\n maxRequestBodySize: options.maxRequestBodySize ?? 'medium',\n ignoreRequestBody: options.ignoreRequestBody,\n };\n}) satisfies IntegrationFn;\n\n/**\n * Configures incoming HTTP request handling for Cloudflare Workers.\n *\n * This integration controls how incoming HTTP request data is captured,\n * matching the API of `httpServerIntegration` in Node.js.\n *\n * @example\n * ```ts\n * Sentry.init({\n * integrations: [\n * Sentry.httpServerIntegration({\n * maxRequestBodySize: 'medium',\n * ignoreRequestBody: (url) => url.includes('/health'),\n * }),\n * ],\n * });\n * ```\n */\nexport const httpServerIntegration = defineIntegration(_httpServerIntegration);\n\n/**\n * Capture the request body based on the HttpServer integration config.\n * Called internally by `wrapRequestHandler`.\n */\nexport async function captureIncomingRequestBody(client: Client, request: Request): Promise<void> {\n const integration = client.getIntegrationByName<HttpServerIntegrationInstance>(INTEGRATION_NAME);\n\n if (!integration) {\n return;\n }\n\n // TODO(v11): Gate incoming request body capture on `dataCollection.httpBodies` (capture only when\n // `'incomingRequest'` is listed) instead of defaulting to `'medium'`.\n const maxRequestBodySize = integration.maxRequestBodySize;\n\n if (maxRequestBodySize === 'none') {\n return;\n }\n\n // Skip GET and HEAD requests - they don't have bodies\n // Also skip OPTIONS, even if they may have a body, they might not give a lot of extra value\n if (request.method === 'GET' || request.method === 'HEAD' || request.method === 'OPTIONS') {\n return;\n }\n\n if (integration.ignoreRequestBody?.(request.url, request)) {\n return;\n }\n\n const isolationScope = getIsolationScope();\n await captureBodyFromWinterCGRequest(request, isolationScope, maxRequestBodySize);\n}\n"],"names":["defineIntegration","getIsolationScope","captureBodyFromWinterCGRequest"],"mappings":";;;;AAGA,MAAM,gBAAA,GAAmB,YAAA;AA6CzB,MAAM,sBAAA,IAA0B,CAAC,OAAA,GAAwC,EAAC,KAAqC;AAC7G,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,kBAAA,EAAoB,QAAQ,kBAAA,IAAsB,QAAA;AAAA,IAClD,mBAAmB,OAAA,CAAQ;AAAA,GAC7B;AACF,CAAA,CAAA;AAoBO,MAAM,qBAAA,GAAwBA,uBAAkB,sBAAsB;AAM7E,eAAsB,0BAAA,CAA2B,QAAgB,OAAA,EAAiC;AAChG,EAAA,MAAM,WAAA,GAAc,MAAA,CAAO,oBAAA,CAAoD,gBAAgB,CAAA;AAE/F,EAAA,IAAI,CAAC,WAAA,EAAa;AAChB,IAAA;AAAA,EACF;AAIA,EAAA,MAAM,qBAAqB,WAAA,CAAY,kBAAA;AAEvC,EAAA,IAAI,uBAAuB,MAAA,EAAQ;AACjC,IAAA;AAAA,EACF;AAIA,EAAA,IAAI,OAAA,CAAQ,WAAW,KAAA,IAAS,OAAA,CAAQ,WAAW,MAAA,IAAU,OAAA,CAAQ,WAAW,SAAA,EAAW;AACzF,IAAA;AAAA,EACF;AAEA,EAAA,IAAI,WAAA,CAAY,iBAAA,GAAoB,OAAA,CAAQ,GAAA,EAAK,OAAO,CAAA,EAAG;AACzD,IAAA;AAAA,EACF;AAEA,EAAA,MAAM,iBAAiBC,sBAAA,EAAkB;AACzC,EAAA,MAAMC,mCAAA,CAA+B,OAAA,EAAS,cAAA,EAAgB,kBAAkB,CAAA;AAClF;;;;;"}
|
package/build/cjs/request.js
CHANGED
|
@@ -7,11 +7,15 @@ const scopeUtils = require('./scope-utils.js');
|
|
|
7
7
|
const sdk = require('./sdk.js');
|
|
8
8
|
const streaming = require('./utils/streaming.js');
|
|
9
9
|
|
|
10
|
+
function getRequestErrorMechanismType(context) {
|
|
11
|
+
return context && "storage" in context ? "auto.faas.cloudflare.durable_object" : "auto.http.cloudflare";
|
|
12
|
+
}
|
|
10
13
|
function wrapRequestHandler(wrapperOptions, handler) {
|
|
11
14
|
return core.withIsolationScope(async (isolationScope) => {
|
|
12
15
|
const { options, request, captureErrors = true } = wrapperOptions;
|
|
13
16
|
const context = wrapperOptions.context;
|
|
14
17
|
const waitUntil = context ? flush.getOriginalWaitUntil(context)?.bind(context) : void 0;
|
|
18
|
+
const errorMechanismType = getRequestErrorMechanismType(context);
|
|
15
19
|
const client = sdk.init({ ...options, ctx: context });
|
|
16
20
|
isolationScope.setClient(client);
|
|
17
21
|
const urlObject = core.parseStringToURLObject(request.url);
|
|
@@ -28,7 +32,7 @@ function wrapRequestHandler(wrapperOptions, handler) {
|
|
|
28
32
|
attributes,
|
|
29
33
|
core.httpHeadersToSpanAttributes(
|
|
30
34
|
core.winterCGHeadersToDict(request.headers),
|
|
31
|
-
core.getClient()?.
|
|
35
|
+
core.getClient()?.getDataCollectionOptions() ?? false
|
|
32
36
|
)
|
|
33
37
|
);
|
|
34
38
|
attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_OP] = "http.server";
|
|
@@ -45,7 +49,7 @@ function wrapRequestHandler(wrapperOptions, handler) {
|
|
|
45
49
|
return await handler();
|
|
46
50
|
} catch (e) {
|
|
47
51
|
if (captureErrors) {
|
|
48
|
-
core.captureException(e, { mechanism: { handled: false, type:
|
|
52
|
+
core.captureException(e, { mechanism: { handled: false, type: errorMechanismType } });
|
|
49
53
|
}
|
|
50
54
|
throw e;
|
|
51
55
|
} finally {
|
|
@@ -66,7 +70,7 @@ function wrapRequestHandler(wrapperOptions, handler) {
|
|
|
66
70
|
} catch (e) {
|
|
67
71
|
span.end();
|
|
68
72
|
if (captureErrors) {
|
|
69
|
-
core.captureException(e, { mechanism: { handled: false, type:
|
|
73
|
+
core.captureException(e, { mechanism: { handled: false, type: errorMechanismType } });
|
|
70
74
|
}
|
|
71
75
|
waitUntil?.(flush.flushAndDispose(client));
|
|
72
76
|
throw e;
|
package/build/cjs/request.js.map
CHANGED
|
@@ -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\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\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()?.getOptions().sendDefaultPii ?? 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: 'auto.http.cloudflare' } });\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: 'auto.http.cloudflare' } });\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":";;;;;;;;;AAyCO,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;AAE3E,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,EAAiB;AACnB,MAAA,UAAA,CAAW,qBAAqB,CAAA,GAAI,eAAA;AAAA,IACtC;AAEA,IAAA,MAAA,CAAO,MAAA;AAAA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,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, 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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rC;AACA,UAAA,OAAO,GAAA;AAAA,QACT,CAAC,CAAA;AAAA,MACH;AAAA,KACF;AAAA,EACF,CAAC,CAAA;AACH;;;;"}
|
package/build/cjs/sdk.js
CHANGED
|
@@ -11,7 +11,7 @@ const transport = require('./transport.js');
|
|
|
11
11
|
const stacktrace = require('./vendor/stacktrace.js');
|
|
12
12
|
|
|
13
13
|
function getDefaultIntegrations(options) {
|
|
14
|
-
const
|
|
14
|
+
const cookiesEnabled = options.sendDefaultPii || options.dataCollection?.cookies != null;
|
|
15
15
|
return [
|
|
16
16
|
// The Dedupe integration should not be used in workflows because we want to
|
|
17
17
|
// capture all step failures, even if they are the same error.
|
|
@@ -25,8 +25,7 @@ function getDefaultIntegrations(options) {
|
|
|
25
25
|
fetch.fetchIntegration(),
|
|
26
26
|
hono.honoIntegration(),
|
|
27
27
|
httpServer.httpServerIntegration(),
|
|
28
|
-
|
|
29
|
-
core.requestDataIntegration(sendDefaultPii ? void 0 : { include: { cookies: false } }),
|
|
28
|
+
core.requestDataIntegration(cookiesEnabled ? void 0 : { include: { cookies: false } }),
|
|
30
29
|
core.consoleIntegration()
|
|
31
30
|
];
|
|
32
31
|
}
|
package/build/cjs/sdk.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk.js","sources":["../../src/sdk.ts"],"sourcesContent":["import type { Integration } from '@sentry/core';\nimport {\n consoleIntegration,\n conversationIdIntegration,\n dedupeIntegration,\n functionToStringIntegration,\n getIntegrationsToSetup,\n inboundFiltersIntegration,\n initAndBind,\n linkedErrorsIntegration,\n requestDataIntegration,\n spanStreamingIntegration,\n stackParserFromStackParserOptions,\n} from '@sentry/core';\nimport type { CloudflareClientOptions, CloudflareOptions } from './client';\nimport { CloudflareClient } from './client';\nimport { makeFlushLock } from './flush';\nimport { httpServerIntegration } from './integrations/httpServer';\nimport { fetchIntegration } from './integrations/fetch';\nimport { honoIntegration } from './integrations/hono';\nimport { setupOpenTelemetryTracer } from './opentelemetry/tracer';\nimport { makeCloudflareTransport } from './transport';\nimport { defaultStackParser } from './vendor/stacktrace';\n\n/** Get the default integrations for the Cloudflare SDK. */\nexport function getDefaultIntegrations(options: CloudflareOptions): Integration[] {\n
|
|
1
|
+
{"version":3,"file":"sdk.js","sources":["../../src/sdk.ts"],"sourcesContent":["import type { Integration } from '@sentry/core';\nimport {\n consoleIntegration,\n conversationIdIntegration,\n dedupeIntegration,\n functionToStringIntegration,\n getIntegrationsToSetup,\n inboundFiltersIntegration,\n initAndBind,\n linkedErrorsIntegration,\n requestDataIntegration,\n spanStreamingIntegration,\n stackParserFromStackParserOptions,\n} from '@sentry/core';\nimport type { CloudflareClientOptions, CloudflareOptions } from './client';\nimport { CloudflareClient } from './client';\nimport { makeFlushLock } from './flush';\nimport { httpServerIntegration } from './integrations/httpServer';\nimport { fetchIntegration } from './integrations/fetch';\nimport { honoIntegration } from './integrations/hono';\nimport { setupOpenTelemetryTracer } from './opentelemetry/tracer';\nimport { makeCloudflareTransport } from './transport';\nimport { defaultStackParser } from './vendor/stacktrace';\n\n/** Get the default integrations for the Cloudflare SDK. */\nexport function getDefaultIntegrations(options: CloudflareOptions): Integration[] {\n // TODO(v11): Drop this transitional gating and let `requestDataIntegration` rely on the resolved\n // `dataCollection` defaults directly. Until then, preserve the historical Cloudflare behavior of not\n // attaching cookies unless the user explicitly opts in via `sendDefaultPii` or `dataCollection.cookies`.\n // eslint-disable-next-line deprecation/deprecation\n const cookiesEnabled = options.sendDefaultPii || options.dataCollection?.cookies != null;\n return [\n // The Dedupe integration should not be used in workflows because we want to\n // capture all step failures, even if they are the same error.\n ...(options.enableDedupe === false ? [] : [dedupeIntegration()]),\n // TODO(v11): Replace with `eventFiltersIntegration` once we remove the deprecated `inboundFiltersIntegration`\n // eslint-disable-next-line deprecation/deprecation\n inboundFiltersIntegration(),\n functionToStringIntegration(),\n conversationIdIntegration(),\n linkedErrorsIntegration(),\n fetchIntegration(),\n honoIntegration(),\n httpServerIntegration(),\n requestDataIntegration(cookiesEnabled ? undefined : { include: { cookies: false } }),\n consoleIntegration(),\n ];\n}\n\n/**\n * Initializes the cloudflare SDK.\n */\nexport function init(options: CloudflareOptions): CloudflareClient | undefined {\n if (options.defaultIntegrations === undefined) {\n options.defaultIntegrations = getDefaultIntegrations(options);\n }\n\n const flushLock = options.ctx ? makeFlushLock(options.ctx) : undefined;\n delete options.ctx;\n\n const resolvedIntegrations = getIntegrationsToSetup(options);\n if (options.traceLifecycle === 'stream' && !resolvedIntegrations.some(i => i.name === 'SpanStreaming')) {\n resolvedIntegrations.push(spanStreamingIntegration());\n }\n\n const clientOptions: CloudflareClientOptions = {\n ...options,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n integrations: resolvedIntegrations,\n transport: options.transport || makeCloudflareTransport,\n flushLock,\n };\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 (!options.skipOpenTelemetrySetup) {\n setupOpenTelemetryTracer();\n }\n\n return initAndBind(CloudflareClient, clientOptions) as CloudflareClient;\n}\n"],"names":["dedupeIntegration","inboundFiltersIntegration","functionToStringIntegration","conversationIdIntegration","linkedErrorsIntegration","fetchIntegration","honoIntegration","httpServerIntegration","requestDataIntegration","consoleIntegration","makeFlushLock","getIntegrationsToSetup","spanStreamingIntegration","stackParserFromStackParserOptions","defaultStackParser","makeCloudflareTransport","setupOpenTelemetryTracer","initAndBind","CloudflareClient"],"mappings":";;;;;;;;;;;;AAyBO,SAAS,uBAAuB,OAAA,EAA2C;AAKhF,EAAA,MAAM,cAAA,GAAiB,OAAA,CAAQ,cAAA,IAAkB,OAAA,CAAQ,gBAAgB,OAAA,IAAW,IAAA;AACpF,EAAA,OAAO;AAAA;AAAA;AAAA,IAGL,GAAI,QAAQ,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AAC,QAAQ,sBAAA,EAAwB;AACnC,IAAAC,+BAAA,EAAyB;AAAA,EAC3B;AAEA,EAAA,OAAOC,gBAAA,CAAYC,yBAAkB,aAAa,CAAA;AACpD;;;;;"}
|
|
@@ -14,7 +14,11 @@ function isDurableObjectNamespace(item) {
|
|
|
14
14
|
function isQueue(item) {
|
|
15
15
|
return item != null && isNotJSRPC(item) && typeof item.send === "function" && typeof item.sendBatch === "function";
|
|
16
16
|
}
|
|
17
|
+
function isD1Database(item) {
|
|
18
|
+
return item != null && isNotJSRPC(item) && typeof item.prepare === "function" && typeof item.batch === "function" && typeof item.exec === "function";
|
|
19
|
+
}
|
|
17
20
|
|
|
21
|
+
exports.isD1Database = isD1Database;
|
|
18
22
|
exports.isDurableObjectNamespace = isDurableObjectNamespace;
|
|
19
23
|
exports.isJSRPC = isJSRPC;
|
|
20
24
|
exports.isQueue = isQueue;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"isBinding.js","sources":["../../../src/utils/isBinding.ts"],"sourcesContent":["/**\n * Adapted from https://github.com/evanderkoogh/otel-cf-workers/blob/effeb549f0a4ed1c55ea0c4f0d8e8e37e5494fb3/src/instrumentation/env.ts\n *\n * BSD 3-Clause License\n *\n * Copyright (c) 2023, Erwin van der Koogh\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport type { DurableObjectNamespace, Queue } from '@cloudflare/workers-types';\n\n/**\n * Checks if a value is a JSRPC proxy (service binding).\n *\n * JSRPC proxies return a truthy value for ANY property access, including\n * properties that don't exist. This makes other duck-type checks unreliable\n * unless we exclude JSRPC first.\n *\n * Must be checked before other binding type checks.\n */\nexport function isJSRPC(item: unknown): item is Service {\n try {\n return !!(item as Record<string, unknown>)[`__some_property_that_will_never_exist__${Math.random()}`];\n } catch {\n return false;\n }\n}\n\nconst isNotJSRPC = (item: unknown): item is Record<string, unknown> => !isJSRPC(item);\n\n/**\n * Duck-type check for DurableObjectNamespace bindings.\n * DurableObjectNamespace has `idFromName`, `idFromString`, `get`, `newUniqueId`.\n */\nexport function isDurableObjectNamespace(item: unknown): item is DurableObjectNamespace {\n return item != null && isNotJSRPC(item) && typeof item.idFromName === 'function';\n}\n\n/**\n * Duck-type check for Queue producer bindings.\n * Queue has `send` and `sendBatch` async methods.\n */\nexport function isQueue(item: unknown): item is Queue {\n return item != null && isNotJSRPC(item) && typeof item.send === 'function' && typeof item.sendBatch === 'function';\n}\n"],"names":[],"mappings":";;AA4CO,SAAS,QAAQ,IAAA,EAAgC;AACtD,EAAA,IAAI;AACF,IAAA,OAAO,CAAC,CAAE,IAAA,CAAiC,0CAA0C,IAAA,CAAK,MAAA,EAAQ,CAAA,CAAE,CAAA;AAAA,EACtG,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF;AAEA,MAAM,UAAA,GAAa,CAAC,IAAA,KAAmD,CAAC,QAAQ,IAAI,CAAA;AAM7E,SAAS,yBAAyB,IAAA,EAA+C;AACtF,EAAA,OAAO,QAAQ,IAAA,IAAQ,UAAA,CAAW,IAAI,CAAA,IAAK,OAAO,KAAK,UAAA,KAAe,UAAA;AACxE;AAMO,SAAS,QAAQ,IAAA,EAA8B;AACpD,EAAA,OAAO,IAAA,IAAQ,IAAA,IAAQ,UAAA,CAAW,IAAI,CAAA,IAAK,OAAO,IAAA,CAAK,IAAA,KAAS,UAAA,IAAc,OAAO,IAAA,CAAK,SAAA,KAAc,UAAA;AAC1G
|
|
1
|
+
{"version":3,"file":"isBinding.js","sources":["../../../src/utils/isBinding.ts"],"sourcesContent":["/**\n * Adapted from https://github.com/evanderkoogh/otel-cf-workers/blob/effeb549f0a4ed1c55ea0c4f0d8e8e37e5494fb3/src/instrumentation/env.ts\n *\n * BSD 3-Clause License\n *\n * Copyright (c) 2023, Erwin van der Koogh\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport type { D1Database, DurableObjectNamespace, Queue } from '@cloudflare/workers-types';\n\n/**\n * Checks if a value is a JSRPC proxy (service binding).\n *\n * JSRPC proxies return a truthy value for ANY property access, including\n * properties that don't exist. This makes other duck-type checks unreliable\n * unless we exclude JSRPC first.\n *\n * Must be checked before other binding type checks.\n */\nexport function isJSRPC(item: unknown): item is Service {\n try {\n return !!(item as Record<string, unknown>)[`__some_property_that_will_never_exist__${Math.random()}`];\n } catch {\n return false;\n }\n}\n\nconst isNotJSRPC = (item: unknown): item is Record<string, unknown> => !isJSRPC(item);\n\n/**\n * Duck-type check for DurableObjectNamespace bindings.\n * DurableObjectNamespace has `idFromName`, `idFromString`, `get`, `newUniqueId`.\n */\nexport function isDurableObjectNamespace(item: unknown): item is DurableObjectNamespace {\n return item != null && isNotJSRPC(item) && typeof item.idFromName === 'function';\n}\n\n/**\n * Duck-type check for Queue producer bindings.\n * Queue has `send` and `sendBatch` async methods.\n */\nexport function isQueue(item: unknown): item is Queue {\n return item != null && isNotJSRPC(item) && typeof item.send === 'function' && typeof item.sendBatch === 'function';\n}\n\n/**\n * Duck-type check for D1Database bindings.\n * D1Database has `prepare`, `batch`, and `exec` methods.\n */\nexport function isD1Database(item: unknown): item is D1Database {\n return (\n item != null &&\n isNotJSRPC(item) &&\n typeof item.prepare === 'function' &&\n typeof item.batch === 'function' &&\n typeof item.exec === 'function'\n );\n}\n"],"names":[],"mappings":";;AA4CO,SAAS,QAAQ,IAAA,EAAgC;AACtD,EAAA,IAAI;AACF,IAAA,OAAO,CAAC,CAAE,IAAA,CAAiC,0CAA0C,IAAA,CAAK,MAAA,EAAQ,CAAA,CAAE,CAAA;AAAA,EACtG,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF;AAEA,MAAM,UAAA,GAAa,CAAC,IAAA,KAAmD,CAAC,QAAQ,IAAI,CAAA;AAM7E,SAAS,yBAAyB,IAAA,EAA+C;AACtF,EAAA,OAAO,QAAQ,IAAA,IAAQ,UAAA,CAAW,IAAI,CAAA,IAAK,OAAO,KAAK,UAAA,KAAe,UAAA;AACxE;AAMO,SAAS,QAAQ,IAAA,EAA8B;AACpD,EAAA,OAAO,IAAA,IAAQ,IAAA,IAAQ,UAAA,CAAW,IAAI,CAAA,IAAK,OAAO,IAAA,CAAK,IAAA,KAAS,UAAA,IAAc,OAAO,IAAA,CAAK,SAAA,KAAc,UAAA;AAC1G;AAMO,SAAS,aAAa,IAAA,EAAmC;AAC9D,EAAA,OACE,IAAA,IAAQ,IAAA,IACR,UAAA,CAAW,IAAI,KACf,OAAO,IAAA,CAAK,OAAA,KAAY,UAAA,IACxB,OAAO,IAAA,CAAK,KAAA,KAAU,UAAA,IACtB,OAAO,KAAK,IAAA,KAAS,UAAA;AAEzB;;;;;;;"}
|