@sentry/cloudflare 10.67.0 → 10.69.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 +5 -0
- package/build/cjs/client.js.map +1 -1
- package/build/cjs/defineCloudflareOptions.js +11 -0
- package/build/cjs/defineCloudflareOptions.js.map +1 -0
- package/build/cjs/durableobject.js +131 -96
- package/build/cjs/durableobject.js.map +1 -1
- package/build/cjs/index.js +6 -0
- package/build/cjs/index.js.map +1 -1
- package/build/cjs/instrumentations/agents/index.js +14 -0
- package/build/cjs/instrumentations/agents/index.js.map +1 -0
- package/build/cjs/instrumentations/agents/instrumentAgentCallableRpc.js +52 -0
- package/build/cjs/instrumentations/agents/instrumentAgentCallableRpc.js.map +1 -0
- package/build/cjs/instrumentations/agents/instrumentChatAgentConversation.js +31 -0
- package/build/cjs/instrumentations/agents/instrumentChatAgentConversation.js.map +1 -0
- package/build/cjs/instrumentations/agents/types.js +32 -0
- package/build/cjs/instrumentations/agents/types.js.map +1 -0
- package/build/cjs/instrumentations/instrumentDurableObjectStorage.js +6 -0
- package/build/cjs/instrumentations/instrumentDurableObjectStorage.js.map +1 -1
- package/build/cjs/instrumentations/instrumentSqlStorage.js +1 -1
- package/build/cjs/instrumentations/instrumentSqlStorage.js.map +1 -1
- package/build/cjs/integrations/spotlight.js +64 -0
- package/build/cjs/integrations/spotlight.js.map +1 -0
- package/build/cjs/integrations/tracing/vercelai.js.map +1 -1
- package/build/cjs/nodejs_compat/index.js +10 -4
- package/build/cjs/nodejs_compat/index.js.map +1 -1
- package/build/cjs/nodejs_compat/integrations/tracing/vercelai.js.map +1 -1
- package/build/cjs/options.js +14 -1
- package/build/cjs/options.js.map +1 -1
- package/build/cjs/sdk.js +20 -1
- package/build/cjs/sdk.js.map +1 -1
- package/build/cjs/utils/internalSqlQuery.js +13 -7
- package/build/cjs/utils/internalSqlQuery.js.map +1 -1
- package/build/cjs/utils/internalStorageKey.js +44 -0
- package/build/cjs/utils/internalStorageKey.js.map +1 -0
- package/build/cjs/vite/agentClass.js +114 -0
- package/build/cjs/vite/agentClass.js.map +1 -0
- package/build/cjs/vite/autoInstrument.js +94 -0
- package/build/cjs/vite/autoInstrument.js.map +1 -0
- package/build/cjs/vite/index.js +14 -0
- package/build/cjs/vite/index.js.map +1 -0
- package/build/cjs/vite/instrumentFile.js +31 -0
- package/build/cjs/vite/instrumentFile.js.map +1 -0
- package/build/cjs/vite/moduleShape.js +231 -0
- package/build/cjs/vite/moduleShape.js.map +1 -0
- package/build/cjs/vite/transform.js +149 -0
- package/build/cjs/vite/transform.js.map +1 -0
- package/build/cjs/vite/workerEntrypoint.js +66 -0
- package/build/cjs/vite/workerEntrypoint.js.map +1 -0
- package/build/cjs/vite/wranglerConfig.js +54 -0
- package/build/cjs/vite/wranglerConfig.js.map +1 -0
- package/build/esm/client.js +6 -1
- package/build/esm/client.js.map +1 -1
- package/build/esm/defineCloudflareOptions.js +9 -0
- package/build/esm/defineCloudflareOptions.js.map +1 -0
- package/build/esm/durableobject.js +129 -97
- package/build/esm/durableobject.js.map +1 -1
- package/build/esm/index.js +4 -2
- package/build/esm/index.js.map +1 -1
- package/build/esm/instrumentations/agents/index.js +12 -0
- package/build/esm/instrumentations/agents/index.js.map +1 -0
- package/build/esm/instrumentations/agents/instrumentAgentCallableRpc.js +50 -0
- package/build/esm/instrumentations/agents/instrumentAgentCallableRpc.js.map +1 -0
- package/build/esm/instrumentations/agents/instrumentChatAgentConversation.js +29 -0
- package/build/esm/instrumentations/agents/instrumentChatAgentConversation.js.map +1 -0
- package/build/esm/instrumentations/agents/types.js +26 -0
- package/build/esm/instrumentations/agents/types.js.map +1 -0
- package/build/esm/instrumentations/instrumentDurableObjectStorage.js +7 -1
- package/build/esm/instrumentations/instrumentDurableObjectStorage.js.map +1 -1
- package/build/esm/instrumentations/instrumentSqlStorage.js +1 -1
- package/build/esm/instrumentations/instrumentSqlStorage.js.map +1 -1
- package/build/esm/integrations/spotlight.js +61 -0
- package/build/esm/integrations/spotlight.js.map +1 -0
- package/build/esm/integrations/tracing/vercelai.js.map +1 -1
- package/build/esm/nodejs_compat/index.js +5 -3
- package/build/esm/nodejs_compat/index.js.map +1 -1
- package/build/esm/nodejs_compat/integrations/tracing/vercelai.js.map +1 -1
- package/build/esm/options.js +14 -1
- package/build/esm/options.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/esm/sdk.js +21 -2
- package/build/esm/sdk.js.map +1 -1
- package/build/esm/utils/internalSqlQuery.js +13 -7
- package/build/esm/utils/internalSqlQuery.js.map +1 -1
- package/build/esm/utils/internalStorageKey.js +41 -0
- package/build/esm/utils/internalStorageKey.js.map +1 -0
- package/build/esm/utils/traceLinks.js +1 -1
- package/build/esm/vite/agentClass.js +111 -0
- package/build/esm/vite/agentClass.js.map +1 -0
- package/build/esm/vite/autoInstrument.js +92 -0
- package/build/esm/vite/autoInstrument.js.map +1 -0
- package/build/esm/vite/index.js +12 -0
- package/build/esm/vite/index.js.map +1 -0
- package/build/esm/vite/instrumentFile.js +27 -0
- package/build/esm/vite/instrumentFile.js.map +1 -0
- package/build/esm/vite/moduleShape.js +227 -0
- package/build/esm/vite/moduleShape.js.map +1 -0
- package/build/esm/vite/transform.js +147 -0
- package/build/esm/vite/transform.js.map +1 -0
- package/build/esm/vite/workerEntrypoint.js +64 -0
- package/build/esm/vite/workerEntrypoint.js.map +1 -0
- package/build/esm/vite/wranglerConfig.js +52 -0
- package/build/esm/vite/wranglerConfig.js.map +1 -0
- package/build/types/client.d.ts +37 -0
- package/build/types/client.d.ts.map +1 -1
- package/build/types/defineCloudflareOptions.d.ts +38 -0
- package/build/types/defineCloudflareOptions.d.ts.map +1 -0
- package/build/types/durableobject.d.ts +81 -0
- package/build/types/durableobject.d.ts.map +1 -1
- package/build/types/index.d.ts +4 -2
- package/build/types/index.d.ts.map +1 -1
- package/build/types/instrumentations/agents/index.d.ts +24 -0
- package/build/types/instrumentations/agents/index.d.ts.map +1 -0
- package/build/types/instrumentations/agents/instrumentAgentCallableRpc.d.ts +11 -0
- package/build/types/instrumentations/agents/instrumentAgentCallableRpc.d.ts.map +1 -0
- package/build/types/instrumentations/agents/instrumentChatAgentConversation.d.ts +22 -0
- package/build/types/instrumentations/agents/instrumentChatAgentConversation.d.ts.map +1 -0
- package/build/types/instrumentations/agents/types.d.ts +49 -0
- package/build/types/instrumentations/agents/types.d.ts.map +1 -0
- package/build/types/instrumentations/instrumentDurableObjectStorage.d.ts.map +1 -1
- package/build/types/integrations/spotlight.d.ts +22 -0
- package/build/types/integrations/spotlight.d.ts.map +1 -0
- package/build/types/integrations/tracing/vercelai.d.ts.map +1 -1
- package/build/types/nodejs_compat/index.d.ts +1 -1
- package/build/types/nodejs_compat/index.d.ts.map +1 -1
- package/build/types/nodejs_compat/integrations/tracing/vercelai.d.ts +1 -8
- package/build/types/nodejs_compat/integrations/tracing/vercelai.d.ts.map +1 -1
- package/build/types/options.d.ts.map +1 -1
- package/build/types/sdk.d.ts.map +1 -1
- package/build/types/utils/internalSqlQuery.d.ts +4 -2
- package/build/types/utils/internalSqlQuery.d.ts.map +1 -1
- package/build/types/utils/internalStorageKey.d.ts +22 -0
- package/build/types/utils/internalStorageKey.d.ts.map +1 -0
- package/build/types/vite/agentClass.d.ts +41 -0
- package/build/types/vite/agentClass.d.ts.map +1 -0
- package/build/types/vite/autoInstrument.d.ts +22 -0
- package/build/types/vite/autoInstrument.d.ts.map +1 -0
- package/build/types/vite/index.d.ts +98 -0
- package/build/types/vite/index.d.ts.map +1 -0
- package/build/types/vite/instrumentFile.d.ts +22 -0
- package/build/types/vite/instrumentFile.d.ts.map +1 -0
- package/build/types/vite/moduleShape.d.ts +52 -0
- package/build/types/vite/moduleShape.d.ts.map +1 -0
- package/build/types/vite/transform.d.ts +65 -0
- package/build/types/vite/transform.d.ts.map +1 -0
- package/build/types/vite/workerEntrypoint.d.ts +12 -0
- package/build/types/vite/workerEntrypoint.d.ts.map +1 -0
- package/build/types/vite/wranglerConfig.d.ts +43 -0
- package/build/types/vite/wranglerConfig.d.ts.map +1 -0
- package/build/types-ts3.8/client.d.ts +37 -0
- package/build/types-ts3.8/defineCloudflareOptions.d.ts +38 -0
- package/build/types-ts3.8/durableobject.d.ts +81 -0
- package/build/types-ts3.8/index.d.ts +4 -2
- package/build/types-ts3.8/instrumentations/agents/index.d.ts +24 -0
- package/build/types-ts3.8/instrumentations/agents/instrumentAgentCallableRpc.d.ts +11 -0
- package/build/types-ts3.8/instrumentations/agents/instrumentChatAgentConversation.d.ts +22 -0
- package/build/types-ts3.8/instrumentations/agents/types.d.ts +49 -0
- package/build/types-ts3.8/integrations/spotlight.d.ts +22 -0
- package/build/types-ts3.8/nodejs_compat/index.d.ts +1 -1
- package/build/types-ts3.8/nodejs_compat/integrations/tracing/vercelai.d.ts +7 -14
- package/build/types-ts3.8/utils/internalSqlQuery.d.ts +4 -2
- package/build/types-ts3.8/utils/internalStorageKey.d.ts +22 -0
- package/build/types-ts3.8/vite/agentClass.d.ts +41 -0
- package/build/types-ts3.8/vite/autoInstrument.d.ts +22 -0
- package/build/types-ts3.8/vite/index.d.ts +98 -0
- package/build/types-ts3.8/vite/instrumentFile.d.ts +22 -0
- package/build/types-ts3.8/vite/moduleShape.d.ts +52 -0
- package/build/types-ts3.8/vite/transform.d.ts +65 -0
- package/build/types-ts3.8/vite/workerEntrypoint.d.ts +12 -0
- package/build/types-ts3.8/vite/wranglerConfig.d.ts +43 -0
- package/package.json +19 -5
package/build/cjs/client.js
CHANGED
|
@@ -103,6 +103,11 @@ class CloudflareClient extends core.ServerRuntimeClient {
|
|
|
103
103
|
this._resetSpanCompletionPromise();
|
|
104
104
|
this._flushLock = void 0;
|
|
105
105
|
}
|
|
106
|
+
/** @inheritDoc */
|
|
107
|
+
_setupIntegrations() {
|
|
108
|
+
core._INTERNAL_clearAiProviderSkips();
|
|
109
|
+
super._setupIntegrations();
|
|
110
|
+
}
|
|
106
111
|
/**
|
|
107
112
|
* Resets the span completion promise and resolve function.
|
|
108
113
|
*/
|
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, spanIsSampled } from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { ExecutionContextCompat } from './executionContext';\nimport type { makeFlushLock } from './flush';\nimport type { CloudflareTransportOptions } from './transport';\n\n/**\n * The Sentry Cloudflare SDK Client.\n *\n * @see CloudflareClientOptions for documentation on configuration options.\n * @see ServerRuntimeClient for usage documentation.\n */\nexport class CloudflareClient extends ServerRuntimeClient {\n private readonly _flushLock: ReturnType<typeof makeFlushLock> | void;\n private _pendingSpans: Set<string> = new Set();\n private _spanCompletionPromise: Promise<void> | null = null;\n private _resolveSpanCompletion: (() => void) | null = null;\n\n private _unsubscribeSpanStart: (() => void) | null = null;\n private _unsubscribeSpanEnd: (() => void) | null = null;\n\n /**\n * Creates a new Cloudflare SDK instance.\n * @param options Configuration options for this SDK.\n */\n public constructor(options: CloudflareClientOptions) {\n applySdkMetadata(options, 'cloudflare');\n options._metadata = options._metadata || {};\n const { flushLock, ...serverOptions } = options;\n\n const clientOptions: ServerRuntimeClientOptions = {\n ...serverOptions,\n platform: 'javascript',\n // TODO: Grab version information\n runtime: { name: 'cloudflare' },\n // TODO: Add server name\n _flushInterval: 0,\n };\n\n super(clientOptions);\n this._flushLock = flushLock;\n\n // Track span lifecycle to know when to flush\n this._unsubscribeSpanStart = this.on('spanStart', span => {\n const spanId = span.spanContext().spanId;\n DEBUG_BUILD && debug.log('[CloudflareClient] Span started:', spanId);\n\n // Negatively sampled spans never emit spanEnd,\n // so tracking them would cause _pendingSpans to grow unboundedly.\n // We should fix the inconsistent behavior for NonRecordingSpans in the future but\n // for now, we just ignore them.\n if (!spanIsSampled(span)) {\n return;\n }\n\n this._pendingSpans.add(spanId);\n\n if (!this._spanCompletionPromise) {\n this._spanCompletionPromise = new Promise(resolve => {\n this._resolveSpanCompletion = resolve;\n });\n }\n });\n\n this._unsubscribeSpanEnd = this.on('spanEnd', span => {\n const spanId = span.spanContext().spanId;\n DEBUG_BUILD && debug.log('[CloudflareClient] Span ended:', spanId);\n this._pendingSpans.delete(spanId);\n\n // If no more pending spans, resolve the completion promise\n if (this._pendingSpans.size === 0 && this._resolveSpanCompletion) {\n DEBUG_BUILD && debug.log('[CloudflareClient] All spans completed, resolving promise');\n this._resolveSpanCompletion();\n this._resetSpanCompletionPromise();\n }\n });\n }\n\n /**\n * Flushes pending operations and ensures all data is processed.\n * If a timeout is provided, the operation will be completed within the specified time limit.\n *\n * It will wait for all pending spans to complete before flushing.\n *\n * @param {number} [timeout] - Optional timeout in milliseconds to force the completion of the flush operation.\n * @return {Promise<boolean>} A promise that resolves to a boolean indicating whether the flush operation was successful.\n */\n public async flush(timeout?: number): Promise<boolean> {\n if (this._flushLock) {\n await this._flushLock.finalize();\n }\n\n if (this._pendingSpans.size > 0 && this._spanCompletionPromise) {\n DEBUG_BUILD &&\n debug.log('[CloudflareClient] Waiting for', this._pendingSpans.size, 'pending spans to complete...');\n\n const timeoutMs = timeout ?? 5000;\n const spanCompletionRace = Promise.race([\n this._spanCompletionPromise,\n new Promise(resolve =>\n setTimeout(() => {\n DEBUG_BUILD &&\n debug.log('[CloudflareClient] Span completion timeout after', timeoutMs, 'ms, flushing anyway');\n resolve(undefined);\n }, timeoutMs),\n ),\n ]);\n\n await spanCompletionRace;\n }\n\n return super.flush(timeout);\n }\n\n /**\n * Disposes of the client and releases all resources.\n *\n * This method clears all Cloudflare-specific state in addition to the base client cleanup.\n * It unsubscribes from span lifecycle events and clears pending span tracking.\n *\n * Call this method after flushing to allow the client to be garbage collected.\n * After calling dispose(), the client should not be used anymore.\n */\n public override dispose(): void {\n DEBUG_BUILD && debug.log('[CloudflareClient] Disposing client...');\n\n super.dispose();\n\n if (this._unsubscribeSpanStart) {\n this._unsubscribeSpanStart();\n this._unsubscribeSpanStart = null;\n }\n if (this._unsubscribeSpanEnd) {\n this._unsubscribeSpanEnd();\n this._unsubscribeSpanEnd = null;\n }\n\n this._resetSpanCompletionPromise();\n (this as unknown as { _flushLock: ReturnType<typeof makeFlushLock> | void })._flushLock = undefined;\n }\n\n /**\n * Resets the span completion promise and resolve function.\n */\n private _resetSpanCompletionPromise(): void {\n this._pendingSpans.clear();\n this._spanCompletionPromise = null;\n this._resolveSpanCompletion = null;\n }\n}\n\ninterface BaseCloudflareOptions {\n /**\n * @ignore Used internally to disable the deDupeIntegration for workflows.\n * @hidden Used internally to disable the deDupeIntegration for workflows.\n * @default true\n */\n enableDedupe?: boolean;\n\n /**\n * The Cloudflare SDK is not OpenTelemetry native, however, we set up some OpenTelemetry compatibility\n * via a custom trace provider.\n * This ensures that any spans emitted via `@opentelemetry/api` will be captured by Sentry.\n * HOWEVER, big caveat: This does not handle custom context handling, it will always work off the current scope.\n * This should be good enough for many, but not all integrations.\n *\n * If you want to opt-out of setting up the OpenTelemetry compatibility tracer, set this to `true`.\n *\n * @default false\n */\n skipOpenTelemetrySetup?: boolean;\n\n /**\n * Enable trace propagation for RPC calls between Workers, Durable Objects, and Service Bindings.\n *\n * When enabled, trace context (sentry-trace + baggage) is propagated across:\n * - `stub.fetch()` calls to Durable Objects (via HTTP headers)\n * - Service binding `fetch()` calls (via HTTP headers)\n * - RPC method calls to Durable Objects and WorkerEntrypoints (via trailing argument)\n *\n * When enabled on the **receiver side** (DurableObject or WorkerEntrypoint), 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 * // WorkerEntrypoint side (receiver)\n * export const MyEntrypoint = Sentry.withSentry(\n * env => ({ dsn: env.SENTRY_DSN, enableRpcTracePropagation: true }),\n * MyEntrypointBase,\n * );\n * ```\n */\n enableRpcTracePropagation?: boolean;\n\n /**\n * Table names that should stay instrumented even though they match the reserved `cf_` prefix used\n * by Durable Object frameworks (`agents`, `partyserver`, ...) for their internal SQLite tables.\n *\n * By default, `exec` queries against `cf_`-prefixed tables are treated as framework noise and no\n * `db.query` span is created for them. If one of your own tables happens to use this prefix, add it\n * here to opt it back into instrumentation. Entries are matched against each table name in the\n * query summary — strings must match exactly, while regular expressions give you prefix/pattern\n * matching.\n *\n * @default []\n * @example\n * ```ts\n * export default Sentry.withSentry(\n * (env) => ({\n * dsn: env.SENTRY_DSN,\n * durableObjectSqlSpanAllowlist: ['cf_my_table', /^cf_reports_/],\n * }),\n * handler,\n * );\n * ```\n */\n durableObjectSqlSpanAllowlist?: Array<string | RegExp>;\n\n /**\n * @deprecated Use `enableRpcTracePropagation` instead. This option will be removed in a future major version.\n *\n * Enable instrumentation of prototype methods for DurableObjects.\n *\n * When `true`, the SDK will wrap all methods on the DurableObject prototype chain\n * to automatically create spans and capture errors for RPC method calls.\n *\n * When an array of strings is provided, only the specified method names will be instrumented.\n *\n * @default false\n */\n instrumentPrototypeMethods?: boolean | string[];\n}\n\n/**\n * Configuration options for the Sentry Cloudflare SDK\n *\n * @see @sentry/core Options for more information.\n */\nexport interface CloudflareOptions extends Options<CloudflareTransportOptions>, BaseCloudflareOptions {\n ctx?: ExecutionContextCompat;\n}\n\n/**\n * Configuration options for the Sentry Cloudflare SDK Client class\n *\n * @see CloudflareClient for more information.\n */\nexport interface CloudflareClientOptions extends ClientOptions<CloudflareTransportOptions>, BaseCloudflareOptions {\n flushLock?: ReturnType<typ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imeClientOptions } from '@sentry/core';\nimport {\n _INTERNAL_clearAiProviderSkips,\n applySdkMetadata,\n debug,\n ServerRuntimeClient,\n spanIsSampled,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { ExecutionContextCompat } from './executionContext';\nimport type { makeFlushLock } from './flush';\nimport type { CloudflareTransportOptions } from './transport';\n\n/**\n * The Sentry Cloudflare SDK Client.\n *\n * @see CloudflareClientOptions for documentation on configuration options.\n * @see ServerRuntimeClient for usage documentation.\n */\nexport class CloudflareClient extends ServerRuntimeClient {\n private readonly _flushLock: ReturnType<typeof makeFlushLock> | void;\n private _pendingSpans: Set<string> = new Set();\n private _spanCompletionPromise: Promise<void> | null = null;\n private _resolveSpanCompletion: (() => void) | null = null;\n\n private _unsubscribeSpanStart: (() => void) | null = null;\n private _unsubscribeSpanEnd: (() => void) | null = null;\n\n /**\n * Creates a new Cloudflare SDK instance.\n * @param options Configuration options for this SDK.\n */\n public constructor(options: CloudflareClientOptions) {\n applySdkMetadata(options, 'cloudflare');\n options._metadata = options._metadata || {};\n const { flushLock, ...serverOptions } = options;\n\n const clientOptions: ServerRuntimeClientOptions = {\n ...serverOptions,\n platform: 'javascript',\n // TODO: Grab version information\n runtime: { name: 'cloudflare' },\n // TODO: Add server name\n _flushInterval: 0,\n };\n\n super(clientOptions);\n this._flushLock = flushLock;\n\n // Track span lifecycle to know when to flush\n this._unsubscribeSpanStart = this.on('spanStart', span => {\n const spanId = span.spanContext().spanId;\n DEBUG_BUILD && debug.log('[CloudflareClient] Span started:', spanId);\n\n // Negatively sampled spans never emit spanEnd,\n // so tracking them would cause _pendingSpans to grow unboundedly.\n // We should fix the inconsistent behavior for NonRecordingSpans in the future but\n // for now, we just ignore them.\n if (!spanIsSampled(span)) {\n return;\n }\n\n this._pendingSpans.add(spanId);\n\n if (!this._spanCompletionPromise) {\n this._spanCompletionPromise = new Promise(resolve => {\n this._resolveSpanCompletion = resolve;\n });\n }\n });\n\n this._unsubscribeSpanEnd = this.on('spanEnd', span => {\n const spanId = span.spanContext().spanId;\n DEBUG_BUILD && debug.log('[CloudflareClient] Span ended:', spanId);\n this._pendingSpans.delete(spanId);\n\n // If no more pending spans, resolve the completion promise\n if (this._pendingSpans.size === 0 && this._resolveSpanCompletion) {\n DEBUG_BUILD && debug.log('[CloudflareClient] All spans completed, resolving promise');\n this._resolveSpanCompletion();\n this._resetSpanCompletionPromise();\n }\n });\n }\n\n /**\n * Flushes pending operations and ensures all data is processed.\n * If a timeout is provided, the operation will be completed within the specified time limit.\n *\n * It will wait for all pending spans to complete before flushing.\n *\n * @param {number} [timeout] - Optional timeout in milliseconds to force the completion of the flush operation.\n * @return {Promise<boolean>} A promise that resolves to a boolean indicating whether the flush operation was successful.\n */\n public async flush(timeout?: number): Promise<boolean> {\n if (this._flushLock) {\n await this._flushLock.finalize();\n }\n\n if (this._pendingSpans.size > 0 && this._spanCompletionPromise) {\n DEBUG_BUILD &&\n debug.log('[CloudflareClient] Waiting for', this._pendingSpans.size, 'pending spans to complete...');\n\n const timeoutMs = timeout ?? 5000;\n const spanCompletionRace = Promise.race([\n this._spanCompletionPromise,\n new Promise(resolve =>\n setTimeout(() => {\n DEBUG_BUILD &&\n debug.log('[CloudflareClient] Span completion timeout after', timeoutMs, 'ms, flushing anyway');\n resolve(undefined);\n }, timeoutMs),\n ),\n ]);\n\n await spanCompletionRace;\n }\n\n return super.flush(timeout);\n }\n\n /**\n * Disposes of the client and releases all resources.\n *\n * This method clears all Cloudflare-specific state in addition to the base client cleanup.\n * It unsubscribes from span lifecycle events and clears pending span tracking.\n *\n * Call this method after flushing to allow the client to be garbage collected.\n * After calling dispose(), the client should not be used anymore.\n */\n public override dispose(): void {\n DEBUG_BUILD && debug.log('[CloudflareClient] Disposing client...');\n\n super.dispose();\n\n if (this._unsubscribeSpanStart) {\n this._unsubscribeSpanStart();\n this._unsubscribeSpanStart = null;\n }\n if (this._unsubscribeSpanEnd) {\n this._unsubscribeSpanEnd();\n this._unsubscribeSpanEnd = null;\n }\n\n this._resetSpanCompletionPromise();\n (this as unknown as { _flushLock: ReturnType<typeof makeFlushLock> | void })._flushLock = undefined;\n }\n\n /** @inheritDoc */\n protected override _setupIntegrations(): void {\n // Clear AI provider skip registrations before setting up integrations.\n // The registry is module-global and Cloudflare calls `init()` per request, so without this a\n // single `ai` SDK call would suppress direct `env.AI.run` spans for the rest of the isolate's\n // life. Mirrors the same reset in the Node client.\n _INTERNAL_clearAiProviderSkips();\n super._setupIntegrations();\n }\n\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 and WorkerEntrypoints (via trailing argument)\n *\n * When enabled on the **receiver side** (DurableObject or WorkerEntrypoint), 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 * // WorkerEntrypoint side (receiver)\n * export const MyEntrypoint = Sentry.withSentry(\n * env => ({ dsn: env.SENTRY_DSN, enableRpcTracePropagation: true }),\n * MyEntrypointBase,\n * );\n * ```\n */\n enableRpcTracePropagation?: boolean;\n\n /**\n * Table names that should stay instrumented even though they match the reserved `cf_` prefix used\n * by Durable Object frameworks (`agents`, `partyserver`, ...) for their internal SQLite tables.\n *\n * By default, `exec` queries against `cf_`-prefixed tables are treated as framework noise and no\n * `db.query` span is created for them. If one of your own tables happens to use this prefix, add it\n * here to opt it back into instrumentation. Entries are matched against each table name in the\n * query summary — strings must match exactly, while regular expressions give you prefix/pattern\n * matching.\n *\n * @default []\n * @example\n * ```ts\n * export default Sentry.withSentry(\n * (env) => ({\n * dsn: env.SENTRY_DSN,\n * durableObjectSqlSpanAllowlist: ['cf_my_table', /^cf_reports_/],\n * }),\n * handler,\n * );\n * ```\n */\n durableObjectSqlSpanAllowlist?: Array<string | RegExp>;\n\n /**\n * KV keys that should stay instrumented even though they match a reserved prefix used by Durable\n * Object frameworks (`agents`, `partyserver`, ...) for their internal storage entries.\n *\n * By default, KV reads/writes (`get`, `put`, `delete`, `list`) of `cf_`- or `__ps_`-prefixed keys\n * are treated as framework noise and no `durable_object_storage_*` span is created for them,\n * mirroring how `cf_`-prefixed SQL tables are handled (see {@link durableObjectSqlSpanAllowlist}).\n * If one of your own keys happens to use such a prefix, add it here to opt it back into\n * instrumentation. Strings must match exactly, while regular expressions give you prefix/pattern\n * matching.\n *\n * @default []\n * @example\n * ```ts\n * export default Sentry.withSentry(\n * (env) => ({\n * dsn: env.SENTRY_DSN,\n * durableObjectStorageSpanAllowlist: ['cf_my_key', /^cf_reports_/],\n * }),\n * handler,\n * );\n * ```\n */\n durableObjectStorageSpanAllowlist?: Array<string | RegExp>;\n\n /**\n * @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 * If you use Spotlight by Sentry during development, use\n * this option to forward captured Sentry events to Spotlight.\n *\n * Either set it to true, or provide a specific Spotlight Sidecar URL.\n *\n * More details: https://spotlightjs.com/\n *\n * IMPORTANT: Only set this option to `true` while developing, not in production!\n */\n spotlight?: boolean | string;\n}\n\n/**\n * Configuration options for the Sentry Cloudflare SDK\n *\n * @see @sentry/core Options for more information.\n */\nexport interface CloudflareOptions extends Options<CloudflareTransportOptions>, BaseCloudflareOptions {\n ctx?: ExecutionContextCompat;\n}\n\n/**\n * Configuration options for the Sentry Cloudflare SDK Client class\n *\n * @see CloudflareClient for more information.\n */\nexport interface CloudflareClientOptions extends ClientOptions<CloudflareTransportOptions>, BaseCloudflareOptions {\n flushLock?: ReturnType<typeof makeFlushLock>;\n}\n"],"names":["ServerRuntimeClient","applySdkMetadata","DEBUG_BUILD","debug","spanIsSampled","_INTERNAL_clearAiProviderSkips"],"mappings":";;;;;AAmBO,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,G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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,EAGmB,kBAAA,GAA2B;AAK5C,IAAAE,mCAAA,EAA+B;AAC/B,IAAA,KAAA,CAAM,kBAAA,EAAmB;AAAA,EAC3B;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;;;;"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
|
|
3
|
+
function defineCloudflareOptions(optionsOrCallback) {
|
|
4
|
+
if (typeof optionsOrCallback === "function") {
|
|
5
|
+
return optionsOrCallback;
|
|
6
|
+
}
|
|
7
|
+
return () => optionsOrCallback;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
exports.defineCloudflareOptions = defineCloudflareOptions;
|
|
11
|
+
//# sourceMappingURL=defineCloudflareOptions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"defineCloudflareOptions.js","sources":["../../src/defineCloudflareOptions.ts"],"sourcesContent":["import type { env as cloudflareEnv } from 'cloudflare:workers';\nimport type { CloudflareOptions } from './client';\n\n/**\n * Define the Sentry options for a Cloudflare Worker in a dedicated module.\n *\n * This is the recommended way to configure the SDK when using the Vite plugin's\n * auto-instrumentation: place an `instrument.server.{ts,js,mjs}` file next to\n * the worker entry whose **default export** is the result of this function. The\n * plugin picks it up automatically and hands it to `withSentry`.\n *\n * Unlike Node's `Sentry.init(...)`, the options cannot be applied at module\n * load time on Cloudflare: the DSN and other settings typically come from the\n * per-request `env`, which only exists inside the handler. Pass a callback to\n * read from `env`, or a static object when no `env` access is needed — either\n * way you get full type-checking and autocomplete on {@link CloudflareOptions}.\n *\n * At runtime this is a thin pass-through; it only normalizes a static object\n * into a callback so the plugin always imports a `(env) => options` function.\n *\n * @example\n * ```ts\n * // src/instrument.server.ts\n * import { defineCloudflareOptions } from '@sentry/cloudflare';\n *\n * export default defineCloudflareOptions((env) => ({\n * dsn: env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * }));\n * ```\n *\n * @example\n * ```ts\n * // Static options — no `env` access needed\n * export default defineCloudflareOptions({ tracesSampleRate: 1.0 });\n * ```\n */\nexport function defineCloudflareOptions<Env = typeof cloudflareEnv>(\n optionsOrCallback: CloudflareOptions | ((env: Env) => CloudflareOptions | undefined),\n): (env: Env) => CloudflareOptions | undefined {\n if (typeof optionsOrCallback === 'function') {\n return optionsOrCallback as (env: Env) => CloudflareOptions | undefined;\n }\n\n return () => optionsOrCallback;\n}\n"],"names":[],"mappings":";;AAqCO,SAAS,wBACd,iBAAA,EAC6C;AAC7C,EAAA,IAAI,OAAO,sBAAsB,UAAA,EAAY;AAC3C,IAAA,OAAO,iBAAA;AAAA,EACT;AAEA,EAAA,OAAO,MAAM,iBAAA;AACf;;;;"}
|
|
@@ -9,112 +9,147 @@ const request = require('./request.js');
|
|
|
9
9
|
const instrumentContext = require('./utils/instrumentContext.js');
|
|
10
10
|
const rpcMeta = require('./utils/rpcMeta.js');
|
|
11
11
|
const rpcOptions = require('./utils/rpcOptions.js');
|
|
12
|
+
const index = require('./instrumentations/agents/index.js');
|
|
12
13
|
const wrapMethodWithSentry = require('./wrapMethodWithSentry.js');
|
|
13
14
|
|
|
14
|
-
function
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
})
|
|
32
|
-
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
15
|
+
function constructInstrumentedDurableObject(target, ctx, env, newTarget, optionsCallback) {
|
|
16
|
+
async.setAsyncLocalStorageAsyncContextStrategy();
|
|
17
|
+
const options$1 = options.getFinalOptions(optionsCallback(env), env);
|
|
18
|
+
const context = instrumentContext.instrumentContext(ctx);
|
|
19
|
+
const instrumentedEnv = instrumentEnv.instrumentEnv(env, options$1);
|
|
20
|
+
const obj = Reflect.construct(target, [context, instrumentedEnv], newTarget);
|
|
21
|
+
instrumentDurableObjectHandlers(obj, options$1, context);
|
|
22
|
+
return { obj, options: options$1, context };
|
|
23
|
+
}
|
|
24
|
+
function instrumentDurableObjectHandlers(obj, options, context) {
|
|
25
|
+
if (obj.fetch && typeof obj.fetch === "function") {
|
|
26
|
+
obj.fetch = instrument.ensureInstrumented(
|
|
27
|
+
obj.fetch.bind(obj),
|
|
28
|
+
(original) => new Proxy(original, {
|
|
29
|
+
apply(target, thisArg, args) {
|
|
30
|
+
return request.wrapRequestHandler({ options, request: args[0], context }, () => {
|
|
31
|
+
return Reflect.apply(target, thisArg, args);
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
})
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
if (obj.alarm && typeof obj.alarm === "function") {
|
|
38
|
+
obj.alarm = wrapMethodWithSentry.wrapMethodWithSentry(
|
|
39
|
+
{
|
|
40
|
+
options,
|
|
41
|
+
context,
|
|
42
|
+
spanName: "alarm",
|
|
43
|
+
spanOp: "function",
|
|
44
|
+
startNewTrace: true,
|
|
45
|
+
origin: "auto.faas.cloudflare.durable_object"
|
|
46
|
+
},
|
|
47
|
+
obj.alarm.bind(obj)
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
if (obj.webSocketMessage && typeof obj.webSocketMessage === "function") {
|
|
51
|
+
obj.webSocketMessage = wrapMethodWithSentry.wrapMethodWithSentry(
|
|
52
|
+
{ options, context, spanName: "webSocketMessage", origin: "auto.faas.cloudflare.durable_object" },
|
|
53
|
+
obj.webSocketMessage.bind(obj)
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
if (obj.webSocketClose && typeof obj.webSocketClose === "function") {
|
|
57
|
+
obj.webSocketClose = wrapMethodWithSentry.wrapMethodWithSentry(
|
|
58
|
+
{ options, context, spanName: "webSocketClose", origin: "auto.faas.cloudflare.durable_object" },
|
|
59
|
+
obj.webSocketClose.bind(obj)
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
if (obj.webSocketError && typeof obj.webSocketError === "function") {
|
|
63
|
+
obj.webSocketError = wrapMethodWithSentry.wrapMethodWithSentry(
|
|
64
|
+
{ options, context, spanName: "webSocketError", origin: "auto.faas.cloudflare.durable_object" },
|
|
65
|
+
obj.webSocketError.bind(obj),
|
|
66
|
+
(_, error) => core.captureException(error, {
|
|
67
|
+
mechanism: {
|
|
68
|
+
type: "auto.faas.cloudflare.durable_object_websocket",
|
|
69
|
+
handled: false
|
|
70
|
+
}
|
|
71
|
+
})
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function finalizeWithRpcInstrumentation(obj, options, context) {
|
|
76
|
+
const rpcPropagation = rpcOptions.getEffectiveRpcPropagation(options);
|
|
77
|
+
if (!rpcPropagation) {
|
|
78
|
+
return obj;
|
|
79
|
+
}
|
|
80
|
+
const instrumentPrototypeMethods = Array.isArray(options.instrumentPrototypeMethods) ? (
|
|
81
|
+
// eslint-disable-next-line typescript/no-deprecated
|
|
82
|
+
options.instrumentPrototypeMethods
|
|
83
|
+
) : void 0;
|
|
84
|
+
const allowSet = instrumentPrototypeMethods ? new Set(instrumentPrototypeMethods) : null;
|
|
85
|
+
const alwaysTrace = options.enableRpcTracePropagation === void 0;
|
|
86
|
+
const methodCache = /* @__PURE__ */ new Map();
|
|
87
|
+
return new Proxy(obj, {
|
|
88
|
+
get(proxyTarget, prop, receiver) {
|
|
89
|
+
const value = Reflect.get(proxyTarget, prop, receiver);
|
|
90
|
+
if (typeof prop !== "string" || typeof value !== "function" || prop === "constructor") {
|
|
91
|
+
return value;
|
|
52
92
|
}
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
obj.webSocketClose.bind(obj)
|
|
57
|
-
);
|
|
93
|
+
const cached = methodCache.get(prop);
|
|
94
|
+
if (cached) {
|
|
95
|
+
return cached;
|
|
58
96
|
}
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
(_, error) => core.captureException(error, {
|
|
64
|
-
mechanism: {
|
|
65
|
-
type: "auto.faas.cloudflare.durable_object_websocket",
|
|
66
|
-
handled: false
|
|
67
|
-
}
|
|
68
|
-
})
|
|
69
|
-
);
|
|
97
|
+
const boundMethod = value.bind(proxyTarget);
|
|
98
|
+
if (prop in Object.prototype || Object.prototype.hasOwnProperty.call(proxyTarget, prop) || allowSet && !allowSet.has(prop)) {
|
|
99
|
+
methodCache.set(prop, boundMethod);
|
|
100
|
+
return boundMethod;
|
|
70
101
|
}
|
|
71
|
-
const
|
|
72
|
-
|
|
73
|
-
|
|
102
|
+
const tracedMethod = wrapMethodWithSentry.wrapMethodWithSentry(
|
|
103
|
+
{ options, context, spanName: prop, spanOp: "rpc", origin: "auto.faas.cloudflare.durable_object" },
|
|
104
|
+
boundMethod,
|
|
105
|
+
void 0,
|
|
106
|
+
true
|
|
107
|
+
);
|
|
108
|
+
if (alwaysTrace) {
|
|
109
|
+
methodCache.set(prop, tracedMethod);
|
|
110
|
+
return tracedMethod;
|
|
74
111
|
}
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
) : void 0;
|
|
79
|
-
const allowSet = instrumentPrototypeMethods ? new Set(instrumentPrototypeMethods) : null;
|
|
80
|
-
const alwaysTrace = options$1.enableRpcTracePropagation === void 0;
|
|
81
|
-
const methodCache = /* @__PURE__ */ new Map();
|
|
82
|
-
return new Proxy(obj, {
|
|
83
|
-
get(proxyTarget, prop, receiver) {
|
|
84
|
-
const value = Reflect.get(proxyTarget, prop, receiver);
|
|
85
|
-
if (typeof prop !== "string" || typeof value !== "function" || prop === "constructor") {
|
|
86
|
-
return value;
|
|
87
|
-
}
|
|
88
|
-
const cached = methodCache.get(prop);
|
|
89
|
-
if (cached) {
|
|
90
|
-
return cached;
|
|
91
|
-
}
|
|
92
|
-
const boundMethod = value.bind(proxyTarget);
|
|
93
|
-
if (prop in Object.prototype || Object.prototype.hasOwnProperty.call(proxyTarget, prop) || allowSet && !allowSet.has(prop)) {
|
|
94
|
-
methodCache.set(prop, boundMethod);
|
|
95
|
-
return boundMethod;
|
|
96
|
-
}
|
|
97
|
-
const tracedMethod = wrapMethodWithSentry.wrapMethodWithSentry(
|
|
98
|
-
{ options: options$1, context, spanName: prop, spanOp: "rpc", origin: "auto.faas.cloudflare.durable_object" },
|
|
99
|
-
boundMethod,
|
|
100
|
-
void 0,
|
|
101
|
-
true
|
|
102
|
-
);
|
|
103
|
-
if (alwaysTrace) {
|
|
104
|
-
methodCache.set(prop, tracedMethod);
|
|
105
|
-
return tracedMethod;
|
|
106
|
-
}
|
|
107
|
-
const wrappedMethod = ((...args) => {
|
|
108
|
-
const { rpcMeta: rpcMeta$1 } = rpcMeta.extractRpcMeta(args);
|
|
109
|
-
return rpcMeta$1 ? tracedMethod(...args) : boundMethod(...args);
|
|
110
|
-
});
|
|
111
|
-
methodCache.set(prop, wrappedMethod);
|
|
112
|
-
return wrappedMethod;
|
|
113
|
-
}
|
|
112
|
+
const wrappedMethod = ((...args) => {
|
|
113
|
+
const { rpcMeta: rpcMeta$1 } = rpcMeta.extractRpcMeta(args);
|
|
114
|
+
return rpcMeta$1 ? tracedMethod(...args) : boundMethod(...args);
|
|
114
115
|
});
|
|
116
|
+
methodCache.set(prop, wrappedMethod);
|
|
117
|
+
return wrappedMethod;
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
function instrumentDurableObjectWithSentry(optionsCallback, DurableObjectClass) {
|
|
122
|
+
return new Proxy(DurableObjectClass, {
|
|
123
|
+
construct(target, [ctx, env], newTarget) {
|
|
124
|
+
const { obj, options, context } = constructInstrumentedDurableObject(
|
|
125
|
+
target,
|
|
126
|
+
ctx,
|
|
127
|
+
env,
|
|
128
|
+
newTarget,
|
|
129
|
+
optionsCallback
|
|
130
|
+
);
|
|
131
|
+
return finalizeWithRpcInstrumentation(obj, options, context);
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
function instrumentAgentWithSentry(optionsCallback, AgentClass) {
|
|
136
|
+
return new Proxy(AgentClass, {
|
|
137
|
+
construct(target, [ctx, env], newTarget) {
|
|
138
|
+
const { obj, options, context } = constructInstrumentedDurableObject(
|
|
139
|
+
target,
|
|
140
|
+
ctx,
|
|
141
|
+
env,
|
|
142
|
+
newTarget,
|
|
143
|
+
optionsCallback
|
|
144
|
+
);
|
|
145
|
+
index.instrumentCloudflareAgent(obj);
|
|
146
|
+
return finalizeWithRpcInstrumentation(obj, options, context);
|
|
115
147
|
}
|
|
116
148
|
});
|
|
117
149
|
}
|
|
118
150
|
|
|
151
|
+
exports.constructInstrumentedDurableObject = constructInstrumentedDurableObject;
|
|
152
|
+
exports.finalizeWithRpcInstrumentation = finalizeWithRpcInstrumentation;
|
|
153
|
+
exports.instrumentAgentWithSentry = instrumentAgentWithSentry;
|
|
119
154
|
exports.instrumentDurableObjectWithSentry = instrumentDurableObjectWithSentry;
|
|
120
155
|
//# sourceMappingURL=durableobject.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"durableobject.js","sources":["../../src/durableobject.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/unbound-method */\nimport { captureException } from '@sentry/core';\nimport type { DurableObject } from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport type { CloudflareOptions } from './client';\nimport { ensureInstrumented } from './instrument';\nimport { instrumentEnv } from './instrumentations/worker/instrumentEnv';\nimport { getFinalOptions } from './options';\nimport { wrapRequestHandler } from './request';\nimport { instrumentContext } from './utils/instrumentContext';\nimport { extractRpcMeta } from './utils/rpcMeta';\nimport { getEffectiveRpcPropagation } from './utils/rpcOptions';\nimport { type UncheckedMethod, wrapMethodWithSentry } from './wrapMethodWithSentry';\n\n/**\n * Instruments a Durable Object class to capture errors and performance data.\n *\n * Instruments the following methods by default:\n * - fetch\n * - alarm\n * - webSocketMessage\n * - webSocketClose\n * - webSocketError\n *\n * To instrument RPC methods (prototype methods), enable the `enableRpcTracePropagation` option.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param DurableObjectClass The Durable Object class to instrument.\n * @returns The instrumented Durable Object class.\n *\n * @example\n * ```ts\n * class MyDurableObjectBase extends DurableObject {\n * constructor(ctx: DurableObjectState, env: Env) {\n * super(ctx, env);\n * }\n * }\n *\n * export const MyDurableObject = instrumentDurableObjectWithSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * }),\n * MyDurableObjectBase,\n * );\n * ```\n */\nexport function instrumentDurableObjectWithSentry<\n E,\n T extends DurableObject<E>,\n C extends new (state: DurableObjectState, env: E) => T,\n>(optionsCallback: (env: E) => CloudflareOptions, DurableObjectClass: C): C {\n return new Proxy(DurableObjectClass, {\n construct(target, [ctx, env], newTarget) {\n setAsyncLocalStorageAsyncContextStrategy();\n const context = instrumentContext(ctx);\n const options = getFinalOptions(optionsCallback(env), env);\n const instrumentedEnv = instrumentEnv(env, options);\n\n // Pass `newTarget` so that subclasses of the instrumented class (e.g. the wrapper classes\n // created by wrangler's local dev tooling or `@cloudflare/vitest-pool-workers`) keep their\n // own prototype — otherwise subclass methods disappear and `instanceof` checks break.\n const obj = Reflect.construct(target, [context, instrumentedEnv], newTarget) as T;\n\n // These are the methods that are available on a Durable Object\n // ref: https://developers.cloudflare.com/durable-objects/api/base/\n // obj.alarm\n // obj.fetch\n // obj.webSocketError\n // obj.webSocketClose\n // obj.webSocketMessage\n\n // Any other public methods on the Durable Object instance are RPC calls.\n\n // Bind each built-in handler to this instance before wrapping.\n // See https://github.com/getsentry/sentry-javascript/issues/22328\n if (obj.fetch && typeof obj.fetch === 'function') {\n obj.fetch = ensureInstrumented(\n obj.fetch.bind(obj),\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 {\n options,\n context,\n spanName: 'alarm',\n spanOp: 'function',\n startNewTrace: true,\n origin: 'auto.faas.cloudflare.durable_object',\n },\n obj.alarm.bind(obj),\n );\n }\n\n if (obj.webSocketMessage && typeof obj.webSocketMessage === 'function') {\n obj.webSocketMessage = wrapMethodWithSentry(\n { options, context, spanName: 'webSocketMessage', origin: 'auto.faas.cloudflare.durable_object' },\n obj.webSocketMessage.bind(obj),\n );\n }\n\n if (obj.webSocketClose && typeof obj.webSocketClose === 'function') {\n obj.webSocketClose = wrapMethodWithSentry(\n { options, context, spanName: 'webSocketClose', origin: 'auto.faas.cloudflare.durable_object' },\n obj.webSocketClose.bind(obj),\n );\n }\n\n if (obj.webSocketError && typeof obj.webSocketError === 'function') {\n obj.webSocketError = wrapMethodWithSentry(\n { options, context, spanName: 'webSocketError', origin: 'auto.faas.cloudflare.durable_object' },\n obj.webSocketError.bind(obj),\n (_, error) =>\n captureException(error, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object_websocket',\n handled: false,\n },\n }),\n );\n }\n\n // Get effective RPC propagation setting (handles deprecation of instrumentPrototypeMethods)\n const rpcPropagation = getEffectiveRpcPropagation(options);\n\n // Skip RPC instrumentation if not enabled\n if (!rpcPropagation) {\n return obj;\n }\n\n // If `instrumentPrototypeMethods` was passed as an array (deprecated),\n // only the listed method names should be instrumented.\n // eslint-disable-next-line typescript/no-deprecated\n const instrumentPrototypeMethods = Array.isArray(options.instrumentPrototypeMethods)\n ? // eslint-disable-next-line typescript/no-deprecated\n options.instrumentPrototypeMethods\n : undefined;\n const allowSet = instrumentPrototypeMethods ? new Set(instrumentPrototypeMethods) : null;\n\n // When using the deprecated `instrumentPrototypeMethods` option, always create spans.\n // When using the new `enableRpcTracePropagation`, only create spans when RPC metadata is present.\n const alwaysTrace = options.enableRpcTracePropagation === undefined;\n\n // Return a Proxy that binds all methods to the original object and creates spans\n // for RPC calls that have Sentry trace context propagated.\n // Binding is required because frameworks may use private fields (babel WeakMap pattern),\n // which fail if `this` is the Proxy instead of the original object.\n const methodCache = new Map<string, UncheckedMethod>();\n\n return new Proxy(obj, {\n get(proxyTarget, prop, receiver) {\n const value = Reflect.get(proxyTarget, prop, receiver);\n\n if (typeof prop !== 'string' || typeof value !== 'function' || prop === 'constructor') {\n return value;\n }\n\n const cached = methodCache.get(prop);\n\n if (cached) {\n return cached;\n }\n\n const boundMethod = (value as UncheckedMethod).bind(proxyTarget);\n\n if (\n prop in Object.prototype ||\n Object.prototype.hasOwnProperty.call(proxyTarget, prop) ||\n (allowSet && !allowSet.has(prop))\n ) {\n methodCache.set(prop, boundMethod);\n\n return boundMethod;\n }\n\n // Pre-create the traced version\n const tracedMethod = wrapMethodWithSentry(\n { options, context, spanName: prop, spanOp: 'rpc', origin: 'auto.faas.cloudflare.durable_object' },\n boundMethod,\n undefined,\n true,\n );\n\n // For deprecated `instrumentPrototypeMethods`, always trace.\n // For new `enableRpcTracePropagation`, only trace when RPC metadata is present.\n if (alwaysTrace) {\n methodCache.set(prop, tracedMethod);\n\n return tracedMethod;\n }\n\n // Wrapper that checks for Sentry RPC metadata at call time\n const wrappedMethod = ((...args: unknown[]) => {\n const { rpcMeta } = extractRpcMeta(args);\n\n // If Sentry RPC metadata is present, use the traced version (creates span)\n // Otherwise, call the bound method directly (no span)\n return rpcMeta ? tracedMethod(...args) : boundMethod(...args);\n }) as UncheckedMethod;\n\n methodCache.set(prop, wrappedMethod);\n\n return wrappedMethod;\n },\n });\n },\n });\n}\n"],"names":["setAsyncLocalStorageAsyncContextStrategy","instrumentContext","options","getFinalOptions","instrumentEnv","ensureInstrumented","target","wrapRequestHandler","wrapMethodWithSentry","captureException","getEffectiveRpcPropagation","rpcMeta","extractRpcMeta"],"mappings":";;;;;;;;;;;;;AA+CO,SAAS,iCAAA,CAId,iBAAgD,kBAAA,EAA0B;AAC1E,EAAA,OAAO,IAAI,MAAM,kBAAA,EAAoB;AAAA,IACnC,UAAU,MAAA,EAAQ,CAAC,GAAA,EAAK,GAAG,GAAG,SAAA,EAAW;AACvC,MAAAA,8CAAA,EAAyC;AACzC,MAAA,MAAM,OAAA,GAAUC,oCAAkB,GAAG,CAAA;AACrC,MAAA,MAAMC,SAAA,GAAUC,uBAAA,CAAgB,eAAA,CAAgB,GAAG,GAAG,GAAG,CAAA;AACzD,MAAA,MAAM,eAAA,GAAkBC,2BAAA,CAAc,GAAA,EAAKF,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ACT;AAGA,UAAA,MAAM,aAAA,IAAiB,IAAI,IAAA,KAAoB;AAC7C,YAAA,MAAM,WAAES,SAAA,EAAQ,GAAIC,sBAAA,CAAe,IAAI,CAAA;AAIvC,YAAA,OAAOD,YAAU,YAAA,CAAa,GAAG,IAAI,CAAA,GAAI,WAAA,CAAY,GAAG,IAAI,CAAA;AAAA,UAC9D,CAAA,CAAA;AAEA,UAAA,WAAA,CAAY,GAAA,CAAI,MAAM,aAAa,CAAA;AAEnC,UAAA,OAAO,aAAA;AAAA,QACT;AAAA,OACD,CAAA;AAAA,IACH;AAAA,GACD,CAAA;AACH;;;;"}
|
|
1
|
+
{"version":3,"file":"durableobject.js","sources":["../../src/durableobject.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/unbound-method */\nimport { captureException } from '@sentry/core';\nimport type { DurableObject } from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport type { CloudflareOptions } from './client';\nimport { ensureInstrumented } from './instrument';\nimport { instrumentEnv } from './instrumentations/worker/instrumentEnv';\nimport { getFinalOptions } from './options';\nimport { wrapRequestHandler } from './request';\nimport { instrumentContext } from './utils/instrumentContext';\nimport { extractRpcMeta } from './utils/rpcMeta';\nimport { getEffectiveRpcPropagation } from './utils/rpcOptions';\nimport { instrumentCloudflareAgent } from './instrumentations/agents';\nimport { type UncheckedMethod, wrapMethodWithSentry } from './wrapMethodWithSentry';\n\n/**\n * The instrumented context passed between the shared construction helpers.\n *\n * This is intentionally `any` rather than `ReturnType<typeof instrumentContext<DurableObjectState>>`.\n * A concrete `DurableObjectState` here forces `tsc` to structurally relate its `storage: SqlStorage`\n * graph against the `ExecutionContext | InstrumentedDurableObjectState` parameter of\n * `wrapMethodWithSentry`, while the RPC-branded `DurableObject` from `cloudflare:workers` is also in\n * scope. That union comparison explodes (1296×1296) and hangs the type build. The original inline\n * implementation avoided this only incidentally, because `ctx` reached it as `any` through the Proxy\n * `construct` trap. Keeping the shared context `any` preserves that behavior.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InstrumentedDurableObjectContext = any;\n\n/**\n * Constructs a Durable Object instance and instruments its built-in handler methods\n * (`fetch`, `alarm`, `webSocketMessage`, `webSocketClose`, `webSocketError`).\n *\n * This is the shared construction path used by both {@link instrumentDurableObjectWithSentry}\n * and {@link instrumentAgentWithSentry}. It intentionally does NOT apply the RPC prototype-method\n * proxy — callers apply that last via {@link finalizeWithRpcInstrumentation}, after any additional\n * per-instance instrumentation has been layered onto the returned object.\n *\n * @internal\n */\nexport function constructInstrumentedDurableObject<E, T extends DurableObject<E>>(\n target: new (state: DurableObjectState, env: E) => T,\n ctx: DurableObjectState,\n env: E,\n newTarget: NewableFunction,\n optionsCallback: (env: E) => CloudflareOptions,\n): { obj: T; options: CloudflareOptions; context: InstrumentedDurableObjectContext } {\n setAsyncLocalStorageAsyncContextStrategy();\n const options = getFinalOptions(optionsCallback(env), env);\n // See InstrumentedDurableObjectContext — `ctx` is widened to `any` so the concrete\n // `DurableObjectState` type never enters the checker's relation graph in this module.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const context = instrumentContext(ctx as any);\n const instrumentedEnv = instrumentEnv(env as Record<string, unknown>, options);\n\n // Pass `newTarget` so that subclasses of the instrumented class (e.g. the wrapper classes\n // created by wrangler's local dev tooling or `@cloudflare/vitest-pool-workers`) keep their\n // own prototype — otherwise subclass methods disappear and `instanceof` checks break.\n const obj = Reflect.construct(target, [context, instrumentedEnv], newTarget) as T;\n\n instrumentDurableObjectHandlers(obj, options, context);\n\n return { obj, options, context };\n}\n\n/**\n * Instruments the built-in Durable Object handler methods on a constructed instance.\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 */\nfunction instrumentDurableObjectHandlers<E, T extends DurableObject<E>>(\n obj: T,\n options: CloudflareOptions,\n context: InstrumentedDurableObjectContext,\n): void {\n // Bind each built-in handler to this instance before wrapping.\n // See https://github.com/getsentry/sentry-javascript/issues/22328\n if (obj.fetch && typeof obj.fetch === 'function') {\n obj.fetch = ensureInstrumented(\n obj.fetch.bind(obj),\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 {\n options,\n context,\n spanName: 'alarm',\n spanOp: 'function',\n startNewTrace: true,\n origin: 'auto.faas.cloudflare.durable_object',\n },\n obj.alarm.bind(obj),\n );\n }\n\n if (obj.webSocketMessage && typeof obj.webSocketMessage === 'function') {\n obj.webSocketMessage = wrapMethodWithSentry(\n { options, context, spanName: 'webSocketMessage', origin: 'auto.faas.cloudflare.durable_object' },\n obj.webSocketMessage.bind(obj),\n );\n }\n\n if (obj.webSocketClose && typeof obj.webSocketClose === 'function') {\n obj.webSocketClose = wrapMethodWithSentry(\n { options, context, spanName: 'webSocketClose', origin: 'auto.faas.cloudflare.durable_object' },\n obj.webSocketClose.bind(obj),\n );\n }\n\n if (obj.webSocketError && typeof obj.webSocketError === 'function') {\n obj.webSocketError = wrapMethodWithSentry(\n { options, context, spanName: 'webSocketError', origin: 'auto.faas.cloudflare.durable_object' },\n obj.webSocketError.bind(obj),\n (_, error) =>\n captureException(error, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object_websocket',\n handled: false,\n },\n }),\n );\n }\n}\n\n/**\n * Wraps a constructed (and already handler-instrumented) Durable Object instance with the RPC\n * prototype-method proxy, when RPC trace propagation is enabled. Returns the object unchanged when\n * RPC instrumentation is disabled.\n *\n * This must be applied last, so that any per-instance instrumentation (own properties such as\n * `fetch`, `alarm`, or Agent-specific handlers) is excluded from RPC method tracing.\n *\n * @internal\n */\nexport function finalizeWithRpcInstrumentation<T extends object>(\n obj: T,\n options: CloudflareOptions,\n context: InstrumentedDurableObjectContext,\n): T {\n // Get effective RPC propagation setting (handles deprecation of instrumentPrototypeMethods)\n const rpcPropagation = getEffectiveRpcPropagation(options);\n\n // Skip RPC instrumentation if not enabled\n if (!rpcPropagation) {\n return obj;\n }\n\n // If `instrumentPrototypeMethods` was passed as an array (deprecated),\n // only the listed method names should be instrumented.\n // eslint-disable-next-line typescript/no-deprecated\n const instrumentPrototypeMethods = Array.isArray(options.instrumentPrototypeMethods)\n ? // eslint-disable-next-line typescript/no-deprecated\n options.instrumentPrototypeMethods\n : undefined;\n const allowSet = instrumentPrototypeMethods ? new Set(instrumentPrototypeMethods) : null;\n\n // When using the deprecated `instrumentPrototypeMethods` option, always create spans.\n // When using the new `enableRpcTracePropagation`, only create spans when RPC metadata is present.\n const alwaysTrace = options.enableRpcTracePropagation === undefined;\n\n // Return a Proxy that binds all methods to the original object and creates spans\n // for RPC calls that have Sentry trace context propagated.\n // Binding is required because frameworks may use private fields (babel WeakMap pattern),\n // which fail if `this` is the Proxy instead of the original object.\n const methodCache = new Map<string, UncheckedMethod>();\n\n return new Proxy(obj, {\n get(proxyTarget, prop, receiver) {\n const value = Reflect.get(proxyTarget, prop, receiver);\n\n if (typeof prop !== 'string' || typeof value !== 'function' || prop === 'constructor') {\n return value;\n }\n\n const cached = methodCache.get(prop);\n\n if (cached) {\n return cached;\n }\n\n const boundMethod = (value as UncheckedMethod).bind(proxyTarget);\n\n if (\n prop in Object.prototype ||\n Object.prototype.hasOwnProperty.call(proxyTarget, prop) ||\n (allowSet && !allowSet.has(prop))\n ) {\n methodCache.set(prop, boundMethod);\n\n return boundMethod;\n }\n\n // Pre-create the traced version\n const tracedMethod = wrapMethodWithSentry(\n { options, context, spanName: prop, spanOp: 'rpc', origin: 'auto.faas.cloudflare.durable_object' },\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 * Instruments a Durable Object class to capture errors and performance data.\n *\n * Instruments the following methods by default:\n * - fetch\n * - alarm\n * - webSocketMessage\n * - webSocketClose\n * - webSocketError\n *\n * To instrument RPC methods (prototype methods), enable the `enableRpcTracePropagation` option.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param DurableObjectClass The Durable Object class to instrument.\n * @returns The instrumented Durable Object class.\n *\n * @example\n * ```ts\n * class MyDurableObjectBase extends DurableObject {\n * constructor(ctx: DurableObjectState, env: Env) {\n * super(ctx, env);\n * }\n * }\n *\n * export const MyDurableObject = instrumentDurableObjectWithSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * }),\n * MyDurableObjectBase,\n * );\n * ```\n */\nexport function instrumentDurableObjectWithSentry<\n E,\n T extends DurableObject<E>,\n C extends new (state: DurableObjectState, env: E) => T,\n>(optionsCallback: (env: E) => CloudflareOptions, DurableObjectClass: C): C {\n return new Proxy(DurableObjectClass, {\n construct(target, [ctx, env], newTarget) {\n const { obj, options, context } = constructInstrumentedDurableObject(\n target,\n ctx,\n env,\n newTarget,\n optionsCallback,\n );\n\n return finalizeWithRpcInstrumentation(obj, options, context);\n },\n });\n}\n\n/**\n * Instruments a Cloudflare [`agents`](https://www.npmjs.com/package/agents) Agent class with Sentry.\n *\n * An `Agent` is a Durable Object under the hood, so this applies the same instrumentation as\n * {@link instrumentDurableObjectWithSentry} (request transactions, `alarm`, WebSocket handlers, RPC\n * trace propagation, SQL spans) and additionally captures Agent-specific telemetry via\n * `instrumentCloudflareAgent`:\n *\n * - **Callable RPC spans** — a span (op `rpc`) for each `@callable()` method invoked over WebSocket.\n * - **Breadcrumbs** — for every Agent observability event (`rpc`, `state:update`, `connect`,\n * `disconnect`, `schedule:*`, `queue:*`, `workflow:*`, `email:*`, `mcp:*`, ...).\n *\n * Cloudflare Workers cannot auto-instrument, so the Agent class must be wrapped manually.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param AgentClass The Agent class to instrument.\n * @returns The instrumented Agent class.\n *\n * @example\n * ```ts\n * import { Agent, callable, routeAgentRequest } from 'agents';\n * import * as Sentry from '@sentry/cloudflare';\n *\n * class MyAgentBase extends Agent<Env> {\n * @callable()\n * async greet(name: string): Promise<string> {\n * return `Hello, ${name}!`;\n * }\n * }\n *\n * export const MyAgent = Sentry.instrumentAgentWithSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * enableRpcTracePropagation: true,\n * }),\n * MyAgentBase,\n * );\n * ```\n */\nexport function instrumentAgentWithSentry<\n E,\n T extends DurableObject<E>,\n C extends new (state: DurableObjectState, env: E) => T,\n>(optionsCallback: (env: E) => CloudflareOptions, AgentClass: C): C {\n return new Proxy(AgentClass, {\n construct(target, [ctx, env], newTarget) {\n const { obj, options, context } = constructInstrumentedDurableObject(\n target,\n ctx,\n env,\n newTarget,\n optionsCallback,\n );\n\n instrumentCloudflareAgent(obj);\n\n // Apply RPC prototype-method instrumentation last, so the Agent-specific own-property\n // handlers we just installed are excluded from RPC method tracing.\n return finalizeWithRpcInstrumentation(obj, options, context);\n },\n });\n}\n"],"names":["setAsyncLocalStorageAsyncContextStrategy","options","getFinalOptions","instrumentContext","instrumentEnv","ensureInstrumented","wrapRequestHandler","wrapMethodWithSentry","captureException","getEffectiveRpcPropagation","rpcMeta","extractRpcMeta","instrumentCloudflareAgent"],"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OACF;AAEA,MAAA,OAAO,8BAAA,CAA+B,GAAA,EAAK,OAAA,EAAS,OAAO,CAAA;AAAA,IAC7D;AAAA,GACD,CAAA;AACH;AA0CO,SAAS,yBAAA,CAId,iBAAgD,UAAA,EAAkB;AAClE,EAAA,OAAO,IAAI,MAAM,UAAA,EAAY;AAAA,IAC3B,UAAU,MAAA,EAAQ,CAAC,GAAA,EAAK,GAAG,GAAG,SAAA,EAAW;AACvC,MAAA,MAAM,EAAE,GAAA,EAAK,OAAA,EAAS,OAAA,EAAQ,GAAI,kCAAA;AAAA,QAChC,MAAA;AAAA,QACA,GAAA;AAAA,QACA,GAAA;AAAA,QACA,SAAA;AAAA,QACA;AAAA,OACF;AAEA,MAAAE,+BAAA,CAA0B,GAAG,CAAA;AAI7B,MAAA,OAAO,8BAAA,CAA+B,GAAA,EAAK,OAAA,EAAS,OAAO,CAAA;AAAA,IAC7D;AAAA,GACD,CAAA;AACH;;;;;;;"}
|
package/build/cjs/index.js
CHANGED
|
@@ -2,6 +2,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
2
2
|
|
|
3
3
|
const core = require('@sentry/core');
|
|
4
4
|
const withSentry = require('./withSentry.js');
|
|
5
|
+
const defineCloudflareOptions = require('./defineCloudflareOptions.js');
|
|
5
6
|
const durableobject = require('./durableobject.js');
|
|
6
7
|
const pagesPlugin = require('./pages-plugin.js');
|
|
7
8
|
const request = require('./request.js');
|
|
@@ -9,6 +10,7 @@ const client = require('./client.js');
|
|
|
9
10
|
const sdk = require('./sdk.js');
|
|
10
11
|
const httpServer = require('./integrations/httpServer.js');
|
|
11
12
|
const fetch = require('./integrations/fetch.js');
|
|
13
|
+
const spotlight = require('./integrations/spotlight.js');
|
|
12
14
|
const vercelai = require('./integrations/tracing/vercelai.js');
|
|
13
15
|
const hono = require('./integrations/hono.js');
|
|
14
16
|
const instrumentD1 = require('./instrumentations/worker/instrumentD1.js');
|
|
@@ -65,6 +67,7 @@ exports.instrumentLangChainEmbeddings = core.instrumentLangChainEmbeddings;
|
|
|
65
67
|
exports.instrumentLangGraph = core.instrumentLangGraph;
|
|
66
68
|
exports.instrumentOpenAiClient = core.instrumentOpenAiClient;
|
|
67
69
|
exports.instrumentPostgresJsSql = core.instrumentPostgresJsSql;
|
|
70
|
+
exports.instrumentStateGraph = core.instrumentStateGraph;
|
|
68
71
|
exports.instrumentSupabaseClient = core.instrumentSupabaseClient;
|
|
69
72
|
exports.isEnabled = core.isEnabled;
|
|
70
73
|
exports.isInitialized = core.isInitialized;
|
|
@@ -107,6 +110,8 @@ exports.withStreamedSpan = core.withStreamedSpan;
|
|
|
107
110
|
exports.wrapMcpServerWithSentry = core.wrapMcpServerWithSentry;
|
|
108
111
|
exports.zodErrorsIntegration = core.zodErrorsIntegration;
|
|
109
112
|
exports.withSentry = withSentry.withSentry;
|
|
113
|
+
exports.defineCloudflareOptions = defineCloudflareOptions.defineCloudflareOptions;
|
|
114
|
+
exports.instrumentAgentWithSentry = durableobject.instrumentAgentWithSentry;
|
|
110
115
|
exports.instrumentDurableObjectWithSentry = durableobject.instrumentDurableObjectWithSentry;
|
|
111
116
|
exports.sentryPagesPlugin = pagesPlugin.sentryPagesPlugin;
|
|
112
117
|
exports.wrapRequestHandler = request.wrapRequestHandler;
|
|
@@ -114,6 +119,7 @@ exports.CloudflareClient = client.CloudflareClient;
|
|
|
114
119
|
exports.getDefaultIntegrations = sdk.getDefaultIntegrations;
|
|
115
120
|
exports.httpServerIntegration = httpServer.httpServerIntegration;
|
|
116
121
|
exports.fetchIntegration = fetch.fetchIntegration;
|
|
122
|
+
exports.spotlightIntegration = spotlight.spotlightIntegration;
|
|
117
123
|
exports.vercelAIIntegration = vercelai.vercelAIIntegration;
|
|
118
124
|
exports.honoIntegration = hono.honoIntegration;
|
|
119
125
|
exports.instrumentD1WithSentry = instrumentD1.instrumentD1WithSentry;
|
package/build/cjs/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
|
|
3
|
+
const instrumentAgentCallableRpc = require('./instrumentAgentCallableRpc.js');
|
|
4
|
+
const instrumentChatAgentConversation = require('./instrumentChatAgentConversation.js');
|
|
5
|
+
|
|
6
|
+
function instrumentCloudflareAgent(agent) {
|
|
7
|
+
const internals = agent;
|
|
8
|
+
instrumentAgentCallableRpc.instrumentAgentCallableRpc(internals);
|
|
9
|
+
instrumentChatAgentConversation.instrumentChatAgentConversation(internals);
|
|
10
|
+
return agent;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
exports.instrumentCloudflareAgent = instrumentCloudflareAgent;
|
|
14
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../../src/instrumentations/agents/index.ts"],"sourcesContent":["import { instrumentAgentCallableRpc } from './instrumentAgentCallableRpc';\nimport { instrumentChatAgentConversation } from './instrumentChatAgentConversation';\nimport type { AgentInternals } from './types';\n\n/**\n * Instruments an instance of a Cloudflare [`agents`](https://www.npmjs.com/package/agents) `Agent`\n * with Sentry, adding telemetry that is specific to the Agent's runtime behavior:\n *\n * - **Callable RPC spans** — a span (op `rpc`) for each `@callable()` method invoked over WebSocket.\n * - **Conversation correlation** — sets the conversation id on the scope for each unit of agent\n * work — chat turn or callable RPC call — so `gen_ai` spans created within it are correlated, for\n * chat and plain agents alike. Defaults to the instance `name` and is rotated when the chat is\n * cleared (the `message:clear` observability event).\n *\n * It only hooks the `agents` package internals and uses Sentry's tracing primitives. On Cloudflare\n * Workers, prefer `instrumentAgentWithSentry`, which additionally instruments the Durable Object\n * handlers and initializes the SDK; that function calls this one internally.\n *\n * The hooks replace own-properties on the instance and defer to the original implementation, so\n * they compose with any other instrumentation applied to the same instance.\n *\n * @param agent The `agents` `Agent` instance to instrument.\n * @returns The same instance, instrumented.\n *\n * @internal Use `instrumentAgentWithSentry` instead — this is called internally by it.\n */\nexport function instrumentCloudflareAgent<T extends object>(agent: T): T {\n const internals = agent as T & AgentInternals;\n\n instrumentAgentCallableRpc(internals);\n instrumentChatAgentConversation(internals);\n\n return agent;\n}\n"],"names":["instrumentAgentCallableRpc","instrumentChatAgentConversation"],"mappings":";;;;;AA0BO,SAAS,0BAA4C,KAAA,EAAa;AACvE,EAAA,MAAM,SAAA,GAAY,KAAA;AAElB,EAAAA,qDAAA,CAA2B,SAAS,CAAA;AACpC,EAAAC,+DAAA,CAAgC,SAAS,CAAA;AAEzC,EAAA,OAAO,KAAA;AACT;;;;"}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
|
|
3
|
+
const core = require('@sentry/core');
|
|
4
|
+
const debugBuild = require('../../debug-build.js');
|
|
5
|
+
const types = require('./types.js');
|
|
6
|
+
|
|
7
|
+
function instrumentAgentCallableRpc(obj) {
|
|
8
|
+
const original = obj.onMessage;
|
|
9
|
+
if (typeof original !== "function") {
|
|
10
|
+
debugBuild.DEBUG_BUILD && core.debug.log("[Sentry] Agent `onMessage` not found \u2014 callable RPC span instrumentation skipped.");
|
|
11
|
+
return;
|
|
12
|
+
}
|
|
13
|
+
obj.onMessage = new Proxy(original, {
|
|
14
|
+
apply(target, thisArg, args) {
|
|
15
|
+
const method = extractCallableMethod(args[1]);
|
|
16
|
+
if (!method) {
|
|
17
|
+
return Reflect.apply(target, thisArg, args);
|
|
18
|
+
}
|
|
19
|
+
return core.startSpan(
|
|
20
|
+
{
|
|
21
|
+
name: method,
|
|
22
|
+
attributes: {
|
|
23
|
+
[core.SEMANTIC_ATTRIBUTE_SENTRY_OP]: "rpc",
|
|
24
|
+
[core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: types.AGENT_SPAN_ORIGIN,
|
|
25
|
+
...types.getAgentAttributes(thisArg)
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
() => {
|
|
29
|
+
types.setAgentConversationId(thisArg);
|
|
30
|
+
return Reflect.apply(target, thisArg, args);
|
|
31
|
+
}
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
function extractCallableMethod(message) {
|
|
37
|
+
const text = typeof message === "string" ? message : message instanceof ArrayBuffer ? new TextDecoder().decode(message) : void 0;
|
|
38
|
+
if (!text) {
|
|
39
|
+
return void 0;
|
|
40
|
+
}
|
|
41
|
+
try {
|
|
42
|
+
const parsed = JSON.parse(text);
|
|
43
|
+
if (parsed.type === "rpc" && typeof parsed.method === "string" && Array.isArray(parsed.args)) {
|
|
44
|
+
return parsed.method;
|
|
45
|
+
}
|
|
46
|
+
} catch {
|
|
47
|
+
}
|
|
48
|
+
return void 0;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
exports.instrumentAgentCallableRpc = instrumentAgentCallableRpc;
|
|
52
|
+
//# sourceMappingURL=instrumentAgentCallableRpc.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"instrumentAgentCallableRpc.js","sources":["../../../../src/instrumentations/agents/instrumentAgentCallableRpc.ts"],"sourcesContent":["import { debug, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, startSpan } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { AGENT_SPAN_ORIGIN, type AgentInternals, getAgentAttributes, setAgentConversationId } from './types';\n\n/**\n * Wraps the Agent's `onMessage` handler to create a span for each `@callable()` RPC invocation.\n * RPC requests arrive as WebSocket messages, so this span nests under the active transaction for\n * the WebSocket message (on Cloudflare, the instrumented Durable Object `webSocketMessage` hook).\n *\n * Also sets the conversation id on the scope for the duration of the call: callable methods are the\n * unit of work for plain (non-chat) agents, which run LLM calls just like chat turns do.\n */\nexport function instrumentAgentCallableRpc(obj: AgentInternals): void {\n const original = obj.onMessage;\n if (typeof original !== 'function') {\n DEBUG_BUILD && debug.log('[Sentry] Agent `onMessage` not found — callable RPC span instrumentation skipped.');\n return;\n }\n\n obj.onMessage = new Proxy(original, {\n apply(target, thisArg: AgentInternals, args: unknown[]): unknown {\n const method = extractCallableMethod(args[1]);\n\n if (!method) {\n return Reflect.apply(target, thisArg, args);\n }\n\n return startSpan(\n {\n name: method,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'rpc',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: AGENT_SPAN_ORIGIN,\n ...getAgentAttributes(thisArg),\n },\n },\n () => {\n setAgentConversationId(thisArg);\n return Reflect.apply(target, thisArg, args);\n },\n );\n },\n });\n}\n\n/** Extracts the RPC method name from a WebSocket message, mirroring the SDK's `isRPCRequest`. */\nfunction extractCallableMethod(message: unknown): string | undefined {\n const text =\n typeof message === 'string'\n ? message\n : message instanceof ArrayBuffer\n ? new TextDecoder().decode(message)\n : undefined;\n\n if (!text) {\n return undefined;\n }\n\n try {\n const parsed = JSON.parse(text) as { type?: unknown; method?: unknown; args?: unknown };\n if (parsed.type === 'rpc' && typeof parsed.method === 'string' && Array.isArray(parsed.args)) {\n return parsed.method;\n }\n } catch {\n // Not JSON, or not an RPC request — no span.\n }\n\n return undefined;\n}\n"],"names":["DEBUG_BUILD","debug","startSpan","SEMANTIC_ATTRIBUTE_SENTRY_OP","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","AGENT_SPAN_ORIGIN","getAgentAttributes","setAgentConversationId"],"mappings":";;;;;;AAYO,SAAS,2BAA2B,GAAA,E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A,CAAK,KAAA,CAAM,IAAI,CAAA;AAC9B,IAAA,IAAI,MAAA,CAAO,IAAA,KAAS,KAAA,IAAS,OAAO,MAAA,CAAO,MAAA,KAAW,QAAA,IAAY,KAAA,CAAM,OAAA,CAAQ,MAAA,CAAO,IAAI,CAAA,EAAG;AAC5F,MAAA,OAAO,MAAA,CAAO,MAAA;AAAA,IAChB;AAAA,EACF,CAAA,CAAA,MAAQ;AAAA,EAER;AAEA,EAAA,OAAO,MAAA;AACT;;;;"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
|
|
3
|
+
const core = require('@sentry/core');
|
|
4
|
+
const types = require('./types.js');
|
|
5
|
+
|
|
6
|
+
function instrumentChatAgentConversation(obj) {
|
|
7
|
+
const originalEmit = obj._emit;
|
|
8
|
+
if (typeof originalEmit === "function") {
|
|
9
|
+
obj._emit = new Proxy(originalEmit, {
|
|
10
|
+
apply(target, thisArg, args) {
|
|
11
|
+
if (args[0] === "message:clear") {
|
|
12
|
+
thisArg.__sentryConversationId = core.uuid4();
|
|
13
|
+
}
|
|
14
|
+
return Reflect.apply(target, thisArg, args);
|
|
15
|
+
}
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
const original = obj.onChatMessage;
|
|
19
|
+
if (typeof original !== "function") {
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
obj.onChatMessage = new Proxy(original, {
|
|
23
|
+
apply(target, thisArg, args) {
|
|
24
|
+
types.setAgentConversationId(thisArg);
|
|
25
|
+
return Reflect.apply(target, thisArg, args);
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
exports.instrumentChatAgentConversation = instrumentChatAgentConversation;
|
|
31
|
+
//# sourceMappingURL=instrumentChatAgentConversation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"instrumentChatAgentConversation.js","sources":["../../../../src/instrumentations/agents/instrumentChatAgentConversation.ts"],"sourcesContent":["import { uuid4 } from '@sentry/core';\nimport { type AgentInternals, setAgentConversationId } from './types';\n\n/**\n * For chat agents (`AIChatAgent` from `@cloudflare/ai-chat`), correlates each chat turn's AI spans\n * with a conversation id on the active scope.\n *\n * In the Agents model one agent instance is one long-lived conversation, so the instance `name` is\n * the base conversation id. When the user clears the chat, they expect a fresh conversation — but\n * recreating the Durable Object for that would also drop the MCP/OAuth state stored per instance\n * (GitHub/Sentry sign-in). To get a fresh conversation id *without* losing that state, we rotate an\n * in-memory id on the instance when the SDK reports a cleared chat, and stamp that (falling back to\n * the instance `name` before the first clear).\n *\n * The id itself is not attached to spans here — the SDK's `conversationIdIntegration` reads it off\n * the scope at `spanStart` and stamps `gen_ai.conversation.id` onto the AI spans created inside the\n * turn (e.g. by the Workers AI instrumentation), which correlates a turn's model and tool calls.\n *\n * Plain (non-chat) `Agent`s do not define `onChatMessage`, so they are skipped here — their unit\n * of work is the callable RPC method, where `instrumentAgentCallableRpc` sets the conversation id\n * instead.\n */\nexport function instrumentChatAgentConversation(obj: AgentInternals): void {\n // Rotate the conversation id when the chat is cleared. `_emit` is the central choke-point through\n // which all `agents:*` observability events are published, and it already exists on the base\n // `Agent` class — so this hook composes with the RPC instrumentation, which keys off the same\n // surface. We shadow it with an own property so the original stays reachable on the prototype.\n const originalEmit = obj._emit;\n\n if (typeof originalEmit === 'function') {\n obj._emit = new Proxy(originalEmit, {\n apply(target, thisArg: AgentInternals, args: [string, Record<string, unknown>?]) {\n if (args[0] === 'message:clear') {\n thisArg.__sentryConversationId = uuid4();\n }\n\n return Reflect.apply(target, thisArg, args);\n },\n });\n }\n\n const original = obj.onChatMessage;\n\n if (typeof original !== 'function') {\n return;\n }\n\n obj.onChatMessage = new Proxy(original, {\n apply(target, thisArg: AgentInternals, args: unknown[]): unknown {\n setAgentConversationId(thisArg);\n\n return Reflect.apply(target, thisArg, args);\n },\n });\n}\n"],"names":["uuid4","setAgentConversationId"],"mappings":";;;;;AAsBO,SAAS,gCAAgC,GAAA,EAA2B;AAKzE,EAAA,MAAM,eAAe,GAAA,CAAI,KAAA;AAEzB,EAAA,IAAI,OAAO,iBAAiB,UAAA,EAAY;AACtC,IAAA,GAAA,CAAI,KAAA,GAAQ,IAAI,KAAA,CAAM,YAAA,EAAc;AAAA,MAClC,KAAA,CAAM,MAAA,EAAQ,OAAA,EAAyB,IAAA,EAA0C;AAC/E,QAAA,IAAI,IAAA,CAAK,CAAC,CAAA,KAAM,eAAA,EAAiB;AAC/B,UAAA,OAAA,CAAQ,yBAAyBA,UAAA,EAAM;AAAA,QACzC;AAEA,QAAA,OAAO,OAAA,CAAQ,KAAA,CAAM,MAAA,EAAQ,OAAA,EAAS,IAAI,CAAA;AAAA,MAC5C;AAAA,KACD,CAAA;AAAA,EACH;AAEA,EAAA,MAAM,WAAW,GAAA,CAAI,aAAA;AAErB,EAAA,IAAI,OAAO,aAAa,UAAA,EAAY;AAClC,IAAA;AAAA,EACF;AAEA,EAAA,GAAA,CAAI,aAAA,GAAgB,IAAI,KAAA,CAAM,QAAA,EAAU;AAAA,IACtC,KAAA,CAAM,MAAA,EAAQ,OAAA,EAAyB,IAAA,EAA0B;AAC/D,MAAAC,4BAAA,CAAuB,OAAO,CAAA;AAE9B,MAAA,OAAO,OAAA,CAAQ,KAAA,CAAM,MAAA,EAAQ,OAAA,EAAS,IAAI,CAAA;AAAA,IAC5C;AAAA,GACD,CAAA;AACH;;;;"}
|