@sentry/cloudflare 10.19.0 → 10.21.0-alpha.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.
@@ -6,6 +6,7 @@ const instrument = require('./instrument.js');
6
6
  const options = require('./options.js');
7
7
  const request = require('./request.js');
8
8
  const sdk = require('./sdk.js');
9
+ const copyExecutionContext = require('./utils/copyExecutionContext.js');
9
10
 
10
11
  /* eslint-disable @typescript-eslint/unbound-method */
11
12
 
@@ -170,8 +171,9 @@ function instrumentDurableObjectWithSentry
170
171
 
171
172
  (optionsCallback, DurableObjectClass) {
172
173
  return new Proxy(DurableObjectClass, {
173
- construct(target, [context, env]) {
174
+ construct(target, [ctx, env]) {
174
175
  async.setAsyncLocalStorageAsyncContextStrategy();
176
+ const context = copyExecutionContext.copyExecutionContext(ctx);
175
177
 
176
178
  const options$1 = options.getFinalOptions(optionsCallback(env), env);
177
179
 
@@ -1 +1 @@
1
- {"version":3,"file":"durableobject.js","sources":["../../src/durableobject.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/unbound-method */\nimport {\n type Scope,\n captureException,\n flush,\n getClient,\n isThenable,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n startSpan,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type { DurableObject } from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport type { CloudflareOptions } from './client';\nimport { isInstrumented, markAsInstrumented } from './instrument';\nimport { getFinalOptions } from './options';\nimport { wrapRequestHandler } from './request';\nimport { init } from './sdk';\n\ntype MethodWrapperOptions = {\n spanName?: string;\n spanOp?: string;\n options: CloudflareOptions;\n context: ExecutionContext | DurableObjectState;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype OriginalMethod = (...args: any[]) => any;\n\nfunction wrapMethodWithSentry<T extends OriginalMethod>(\n wrapperOptions: MethodWrapperOptions,\n handler: T,\n callback?: (...args: Parameters<T>) => void,\n noMark?: true,\n): T {\n if (isInstrumented(handler)) {\n return handler;\n }\n\n if (!noMark) {\n markAsInstrumented(handler);\n }\n\n return new Proxy(handler, {\n apply(target, thisArg, args: Parameters<T>) {\n const currentClient = getClient();\n // if a client is already set, use withScope, otherwise use withIsolationScope\n const sentryWithScope = currentClient ? withScope : withIsolationScope;\n\n const wrappedFunction = (scope: Scope): unknown => {\n // In certain situations, the passed context can become undefined.\n // For example, for Astro while prerendering pages at build time.\n // see: https://github.com/getsentry/sentry-javascript/issues/13217\n const context = wrapperOptions.context as ExecutionContext | undefined;\n\n const waitUntil = context?.waitUntil?.bind?.(context);\n\n const currentClient = scope.getClient();\n if (!currentClient) {\n const client = init({ ...wrapperOptions.options, ctx: context });\n scope.setClient(client);\n }\n\n if (!wrapperOptions.spanName) {\n try {\n if (callback) {\n callback(...args);\n }\n const result = Reflect.apply(target, thisArg, args);\n\n if (isThenable(result)) {\n return result.then(\n (res: unknown) => {\n waitUntil?.(flush(2000));\n return res;\n },\n (e: unknown) => {\n captureException(e, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object',\n handled: false,\n },\n });\n waitUntil?.(flush(2000));\n throw e;\n },\n );\n } else {\n waitUntil?.(flush(2000));\n return result;\n }\n } catch (e) {\n captureException(e, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object',\n handled: false,\n },\n });\n waitUntil?.(flush(2000));\n throw e;\n }\n }\n\n const attributes = wrapperOptions.spanOp\n ? {\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: wrapperOptions.spanOp,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.durable_object',\n }\n : {};\n\n return startSpan({ name: wrapperOptions.spanName, attributes }, () => {\n try {\n const result = Reflect.apply(target, thisArg, args);\n\n if (isThenable(result)) {\n return result.then(\n (res: unknown) => {\n waitUntil?.(flush(2000));\n return res;\n },\n (e: unknown) => {\n captureException(e, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object',\n handled: false,\n },\n });\n waitUntil?.(flush(2000));\n throw e;\n },\n );\n } else {\n waitUntil?.(flush(2000));\n return result;\n }\n } catch (e) {\n captureException(e, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object',\n handled: false,\n },\n });\n waitUntil?.(flush(2000));\n throw e;\n }\n });\n };\n\n return sentryWithScope(wrappedFunction);\n },\n });\n}\n\n/**\n * Instruments a Durable Object class to capture errors and performance data.\n *\n * Instruments the following methods:\n * - fetch\n * - alarm\n * - webSocketMessage\n * - webSocketClose\n * - webSocketError\n *\n * as well as any other public RPC methods on the Durable Object instance.\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, [context, env]) {\n setAsyncLocalStorageAsyncContextStrategy();\n\n const options = getFinalOptions(optionsCallback(env), env);\n\n const obj = new target(context, env);\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' && !isInstrumented(obj.fetch)) {\n obj.fetch = new Proxy(obj.fetch, {\n apply(target, thisArg, args) {\n return wrapRequestHandler({ options, request: args[0], context }, () =>\n Reflect.apply(target, thisArg, args),\n );\n },\n });\n\n markAsInstrumented(obj.fetch);\n }\n\n if (obj.alarm && typeof obj.alarm === 'function') {\n obj.alarm = wrapMethodWithSentry({ options, context, spanName: 'alarm' }, obj.alarm);\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 for (const method of Object.getOwnPropertyNames(obj)) {\n if (\n method === 'fetch' ||\n method === 'alarm' ||\n method === 'webSocketError' ||\n method === 'webSocketClose' ||\n method === 'webSocketMessage'\n ) {\n continue;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n const value = (obj as any)[method] as unknown;\n if (typeof value === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n (obj as any)[method] = wrapMethodWithSentry(\n { options, context, spanName: method, spanOp: 'rpc' },\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n value as (...args: any[]) => any,\n );\n }\n }\n\n // Store context and options on the instance for prototype methods to access\n Object.defineProperty(obj, '__SENTRY_CONTEXT__', {\n value: context,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n\n Object.defineProperty(obj, '__SENTRY_OPTIONS__', {\n value: options,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n\n if (options?.instrumentPrototypeMethods) {\n instrumentPrototype(target, options.instrumentPrototypeMethods);\n }\n\n return obj;\n },\n });\n}\n\nfunction instrumentPrototype<T extends NewableFunction>(target: T, methodsToInstrument: boolean | string[]): void {\n const proto = target.prototype;\n\n // Get all methods from the prototype chain\n const methodNames = new Set<string>();\n let current = proto;\n\n while (current && current !== Object.prototype) {\n Object.getOwnPropertyNames(current).forEach(name => {\n if (name !== 'constructor' && typeof (current as Record<string, unknown>)[name] === 'function') {\n methodNames.add(name);\n }\n });\n current = Object.getPrototypeOf(current);\n }\n\n // Create a set for efficient lookups when methodsToInstrument is an array\n const methodsToInstrumentSet = Array.isArray(methodsToInstrument) ? new Set(methodsToInstrument) : null;\n\n // Instrument each method on the prototype\n methodNames.forEach(methodName => {\n const originalMethod = (proto as Record<string, unknown>)[methodName];\n\n if (!originalMethod || isInstrumented(originalMethod)) {\n return;\n }\n\n // If methodsToInstrument is an array, only instrument methods in that set\n if (methodsToInstrumentSet && !methodsToInstrumentSet.has(methodName)) {\n return;\n }\n\n // Create a wrapper that gets context/options from the instance at runtime\n const wrappedMethod = function (this: any, ...args: any[]): unknown {\n const thisWithSentry = this as {\n __SENTRY_CONTEXT__: DurableObjectState;\n __SENTRY_OPTIONS__: CloudflareOptions;\n };\n const instanceContext = thisWithSentry.__SENTRY_CONTEXT__;\n const instanceOptions = thisWithSentry.__SENTRY_OPTIONS__;\n\n if (!instanceOptions) {\n // Fallback to original method if no Sentry data found\n return (originalMethod as (...args: any[]) => any).apply(this, args);\n }\n\n // Use the existing wrapper but with instance-specific context/options\n const wrapper = wrapMethodWithSentry(\n {\n options: instanceOptions,\n context: instanceContext,\n spanName: methodName,\n spanOp: 'rpc',\n },\n originalMethod as (...args: any[]) => any,\n undefined,\n true, // noMark = true since we'll mark the prototype method\n );\n\n return (wrapper as (...args: any[]) => any).apply(this, args);\n };\n\n markAsInstrumented(wrappedMethod);\n\n // Replace the prototype method\n Object.defineProperty(proto, methodName, {\n value: wrappedMethod,\n enumerable: false,\n writable: true,\n configurable: true,\n });\n });\n}\n"],"names":["isInstrumented","markAsInstrumented","getClient","withScope","withIsolationScope","init","isThenable","flush","captureException","SEMANTIC_ATTRIBUTE_SENTRY_OP","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","startSpan","setAsyncLocalStorageAsyncContextStrategy","options","getFinalOptions","wrapRequestHandler"],"mappings":";;;;;;;;;AAAA;;AA+BA,SAAS,oBAAoB;AAC7B,EAAE,cAAc;AAChB,EAAE,OAAO;AACT,EAAE,QAAQ;AACV,EAAE,MAAM;AACR,EAAK;AACL,EAAE,IAAIA,yBAAc,CAAC,OAAO,CAAC,EAAE;AAC/B,IAAI,OAAO,OAAO;AAClB;;AAEA,EAAE,IAAI,CAAC,MAAM,EAAE;AACf,IAAIC,6BAAkB,CAAC,OAAO,CAAC;AAC/B;;AAEA,EAAE,OAAO,IAAI,KAAK,CAAC,OAAO,EAAE;AAC5B,IAAI,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,EAAiB;AAChD,MAAM,MAAM,aAAA,GAAgBC,cAAS,EAAE;AACvC;AACA,MAAM,MAAM,eAAA,GAAkB,gBAAgBC,cAAA,GAAYC,uBAAkB;;AAE5E,MAAM,MAAM,eAAA,GAAkB,CAAC,KAAK,KAAqB;AACzD;AACA;AACA;AACA,QAAQ,MAAM,OAAA,GAAU,cAAc,CAAC,OAAA;;AAEvC,QAAQ,MAAM,SAAA,GAAY,OAAO,EAAE,SAAS,EAAE,IAAI,GAAG,OAAO,CAAC;;AAE7D,QAAQ,MAAM,aAAA,GAAgB,KAAK,CAAC,SAAS,EAAE;AAC/C,QAAQ,IAAI,CAAC,aAAa,EAAE;AAC5B,UAAU,MAAM,MAAA,GAASC,QAAI,CAAC,EAAE,GAAG,cAAc,CAAC,OAAO,EAAE,GAAG,EAAE,OAAA,EAAS,CAAC;AAC1E,UAAU,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC;AACjC;;AAEA,QAAQ,IAAI,CAAC,cAAc,CAAC,QAAQ,EAAE;AAC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AAClC,UAAU,OAAO,EAAE,eAAe;AAClC,UAAU,QAAQ,EAAE,UAAU;AAC9B,UAAU,MAAM,EAAE,KAAK;AACvB,SAAS;AACT,QAAQ,cAAA;AACR,QAAQ,SAAS;AACjB,QAAQ,IAAI;AACZ,OAAO;;AAEP,MAAM,OAAO,CAAC,OAAA,GAAoC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC;AACnE,KAAK;;AAEL,IAAIC,6BAAkB,CAAC,aAAa,CAAC;;AAErC;AACA,IAAI,MAAM,CAAC,cAAc,CAAC,KAAK,EAAE,UAAU,EAAE;AAC7C,MAAM,KAAK,EAAE,aAAa;AAC1B,MAAM,UAAU,EAAE,KAAK;AACvB,MAAM,QAAQ,EAAE,IAAI;AACpB,MAAM,YAAY,EAAE,IAAI;AACxB,KAAK,CAAC;AACN,GAAG,CAAC;AACJ;;;;"}
1
+ {"version":3,"file":"durableobject.js","sources":["../../src/durableobject.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/unbound-method */\nimport {\n type Scope,\n captureException,\n flush,\n getClient,\n isThenable,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n startSpan,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type { DurableObject } from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport type { CloudflareOptions } from './client';\nimport { isInstrumented, markAsInstrumented } from './instrument';\nimport { getFinalOptions } from './options';\nimport { wrapRequestHandler } from './request';\nimport { init } from './sdk';\nimport { copyExecutionContext } from './utils/copyExecutionContext';\n\ntype MethodWrapperOptions = {\n spanName?: string;\n spanOp?: string;\n options: CloudflareOptions;\n context: ExecutionContext | DurableObjectState;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype OriginalMethod = (...args: any[]) => any;\n\nfunction wrapMethodWithSentry<T extends OriginalMethod>(\n wrapperOptions: MethodWrapperOptions,\n handler: T,\n callback?: (...args: Parameters<T>) => void,\n noMark?: true,\n): T {\n if (isInstrumented(handler)) {\n return handler;\n }\n\n if (!noMark) {\n markAsInstrumented(handler);\n }\n\n return new Proxy(handler, {\n apply(target, thisArg, args: Parameters<T>) {\n const currentClient = getClient();\n // if a client is already set, use withScope, otherwise use withIsolationScope\n const sentryWithScope = currentClient ? withScope : withIsolationScope;\n\n const wrappedFunction = (scope: Scope): unknown => {\n // In certain situations, the passed context can become undefined.\n // For example, for Astro while prerendering pages at build time.\n // see: https://github.com/getsentry/sentry-javascript/issues/13217\n const context = wrapperOptions.context as ExecutionContext | undefined;\n\n const waitUntil = context?.waitUntil?.bind?.(context);\n\n const currentClient = scope.getClient();\n if (!currentClient) {\n const client = init({ ...wrapperOptions.options, ctx: context });\n scope.setClient(client);\n }\n\n if (!wrapperOptions.spanName) {\n try {\n if (callback) {\n callback(...args);\n }\n const result = Reflect.apply(target, thisArg, args);\n\n if (isThenable(result)) {\n return result.then(\n (res: unknown) => {\n waitUntil?.(flush(2000));\n return res;\n },\n (e: unknown) => {\n captureException(e, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object',\n handled: false,\n },\n });\n waitUntil?.(flush(2000));\n throw e;\n },\n );\n } else {\n waitUntil?.(flush(2000));\n return result;\n }\n } catch (e) {\n captureException(e, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object',\n handled: false,\n },\n });\n waitUntil?.(flush(2000));\n throw e;\n }\n }\n\n const attributes = wrapperOptions.spanOp\n ? {\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: wrapperOptions.spanOp,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.durable_object',\n }\n : {};\n\n return startSpan({ name: wrapperOptions.spanName, attributes }, () => {\n try {\n const result = Reflect.apply(target, thisArg, args);\n\n if (isThenable(result)) {\n return result.then(\n (res: unknown) => {\n waitUntil?.(flush(2000));\n return res;\n },\n (e: unknown) => {\n captureException(e, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object',\n handled: false,\n },\n });\n waitUntil?.(flush(2000));\n throw e;\n },\n );\n } else {\n waitUntil?.(flush(2000));\n return result;\n }\n } catch (e) {\n captureException(e, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object',\n handled: false,\n },\n });\n waitUntil?.(flush(2000));\n throw e;\n }\n });\n };\n\n return sentryWithScope(wrappedFunction);\n },\n });\n}\n\n/**\n * Instruments a Durable Object class to capture errors and performance data.\n *\n * Instruments the following methods:\n * - fetch\n * - alarm\n * - webSocketMessage\n * - webSocketClose\n * - webSocketError\n *\n * as well as any other public RPC methods on the Durable Object instance.\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 = copyExecutionContext(ctx);\n\n const options = getFinalOptions(optionsCallback(env), env);\n\n const obj = new target(context, env);\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' && !isInstrumented(obj.fetch)) {\n obj.fetch = new Proxy(obj.fetch, {\n apply(target, thisArg, args) {\n return wrapRequestHandler({ options, request: args[0], context }, () =>\n Reflect.apply(target, thisArg, args),\n );\n },\n });\n\n markAsInstrumented(obj.fetch);\n }\n\n if (obj.alarm && typeof obj.alarm === 'function') {\n obj.alarm = wrapMethodWithSentry({ options, context, spanName: 'alarm' }, obj.alarm);\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 for (const method of Object.getOwnPropertyNames(obj)) {\n if (\n method === 'fetch' ||\n method === 'alarm' ||\n method === 'webSocketError' ||\n method === 'webSocketClose' ||\n method === 'webSocketMessage'\n ) {\n continue;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n const value = (obj as any)[method] as unknown;\n if (typeof value === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n (obj as any)[method] = wrapMethodWithSentry(\n { options, context, spanName: method, spanOp: 'rpc' },\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n value as (...args: any[]) => any,\n );\n }\n }\n\n // Store context and options on the instance for prototype methods to access\n Object.defineProperty(obj, '__SENTRY_CONTEXT__', {\n value: context,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n\n Object.defineProperty(obj, '__SENTRY_OPTIONS__', {\n value: options,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n\n if (options?.instrumentPrototypeMethods) {\n instrumentPrototype(target, options.instrumentPrototypeMethods);\n }\n\n return obj;\n },\n });\n}\n\nfunction instrumentPrototype<T extends NewableFunction>(target: T, methodsToInstrument: boolean | string[]): void {\n const proto = target.prototype;\n\n // Get all methods from the prototype chain\n const methodNames = new Set<string>();\n let current = proto;\n\n while (current && current !== Object.prototype) {\n Object.getOwnPropertyNames(current).forEach(name => {\n if (name !== 'constructor' && typeof (current as Record<string, unknown>)[name] === 'function') {\n methodNames.add(name);\n }\n });\n current = Object.getPrototypeOf(current);\n }\n\n // Create a set for efficient lookups when methodsToInstrument is an array\n const methodsToInstrumentSet = Array.isArray(methodsToInstrument) ? new Set(methodsToInstrument) : null;\n\n // Instrument each method on the prototype\n methodNames.forEach(methodName => {\n const originalMethod = (proto as Record<string, unknown>)[methodName];\n\n if (!originalMethod || isInstrumented(originalMethod)) {\n return;\n }\n\n // If methodsToInstrument is an array, only instrument methods in that set\n if (methodsToInstrumentSet && !methodsToInstrumentSet.has(methodName)) {\n return;\n }\n\n // Create a wrapper that gets context/options from the instance at runtime\n const wrappedMethod = function (this: any, ...args: any[]): unknown {\n const thisWithSentry = this as {\n __SENTRY_CONTEXT__: DurableObjectState;\n __SENTRY_OPTIONS__: CloudflareOptions;\n };\n const instanceContext = thisWithSentry.__SENTRY_CONTEXT__;\n const instanceOptions = thisWithSentry.__SENTRY_OPTIONS__;\n\n if (!instanceOptions) {\n // Fallback to original method if no Sentry data found\n return (originalMethod as (...args: any[]) => any).apply(this, args);\n }\n\n // Use the existing wrapper but with instance-specific context/options\n const wrapper = wrapMethodWithSentry(\n {\n options: instanceOptions,\n context: instanceContext,\n spanName: methodName,\n spanOp: 'rpc',\n },\n originalMethod as (...args: any[]) => any,\n undefined,\n true, // noMark = true since we'll mark the prototype method\n );\n\n return (wrapper as (...args: any[]) => any).apply(this, args);\n };\n\n markAsInstrumented(wrappedMethod);\n\n // Replace the prototype method\n Object.defineProperty(proto, methodName, {\n value: wrappedMethod,\n enumerable: false,\n writable: true,\n configurable: true,\n });\n });\n}\n"],"names":["isInstrumented","markAsInstrumented","getClient","withScope","withIsolationScope","init","isThenable","flush","captureException","SEMANTIC_ATTRIBUTE_SENTRY_OP","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","startSpan","setAsyncLocalStorageAsyncContextStrategy","copyExecutionContext","options","getFinalOptions","wrapRequestHandler"],"mappings":";;;;;;;;;;AAAA;;AAgCA,SAAS,oBAAoB;AAC7B,EAAE,cAAc;AAChB,EAAE,OAAO;AACT,EAAE,QAAQ;AACV,EAAE,MAAM;AACR,EAAK;AACL,EAAE,IAAIA,yBAAc,CAAC,OAAO,CAAC,EAAE;AAC/B,IAAI,OAAO,OAAO;AAClB;;AAEA,EAAE,IAAI,CAAC,MAAM,EAAE;AACf,IAAIC,6BAAkB,CAAC,OAAO,CAAC;AAC/B;;AAEA,EAAE,OAAO,IAAI,KAAK,CAAC,OAAO,EAAE;AAC5B,IAAI,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,EAAiB;AAChD,MAAM,MAAM,aAAA,GAAgBC,cAAS,EAAE;AACvC;AACA,MAAM,MAAM,eAAA,GAAkB,gBAAgBC,cAAA,GAAYC,uBAAkB;;AAE5E,MAAM,MAAM,eAAA,GAAkB,CAAC,KAAK,KAAqB;AACzD;AACA;AACA;AACA,QAAQ,MAAM,OAAA,GAAU,cAAc,CAAC,OAAA;;AAEvC,QAAQ,MAAM,SAAA,GAAY,OAAO,EAAE,SAAS,EAAE,IAAI,GAAG,OAAO,CAAC;;AAE7D,QAAQ,MAAM,aAAA,GAAgB,KAAK,CAAC,SAAS,EAAE;AAC/C,QAAQ,IAAI,CAAC,aAAa,EAAE;AAC5B,UAAU,MAAM,MAAA,GAASC,QAAI,CAAC,EAAE,GAAG,cAAc,CAAC,OAAO,EAAE,GAAG,EAAE,OAAA,EAAS,CAAC;AAC1E,UAAU,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC;AACjC;;AAEA,QAAQ,IAAI,CAAC,cAAc,CAAC,Q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M,MAAM,OAAA,GAAU,oBAAoB;AAC1C,QAAQ;AACR,UAAU,OAAO,EAAE,eAAe;AAClC,UAAU,OAAO,EAAE,eAAe;AAClC,UAAU,QAAQ,EAAE,UAAU;AAC9B,UAAU,MAAM,EAAE,KAAK;AACvB,SAAS;AACT,QAAQ,cAAA;AACR,QAAQ,SAAS;AACjB,QAAQ,IAAI;AACZ,OAAO;;AAEP,MAAM,OAAO,CAAC,OAAA,GAAoC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC;AACnE,KAAK;;AAEL,IAAIC,6BAAkB,CAAC,aAAa,CAAC;;AAErC;AACA,IAAI,MAAM,CAAC,cAAc,CAAC,KAAK,EAAE,UAAU,EAAE;AAC7C,MAAM,KAAK,EAAE,aAAa;AAC1B,MAAM,UAAU,EAAE,KAAK;AACvB,MAAM,QAAQ,EAAE,IAAI;AACpB,MAAM,YAAY,EAAE,IAAI;AACxB,KAAK,CAAC;AACN,GAAG,CAAC;AACJ;;;;"}
@@ -8,6 +8,7 @@ const options = require('./options.js');
8
8
  const request = require('./request.js');
9
9
  const scopeUtils = require('./scope-utils.js');
10
10
  const sdk = require('./sdk.js');
11
+ const copyExecutionContext = require('./utils/copyExecutionContext.js');
11
12
 
12
13
  /**
13
14
  * Wrapper for Cloudflare handlers.
@@ -31,7 +32,9 @@ function withSentry(
31
32
  if ('fetch' in handler && typeof handler.fetch === 'function' && !instrument.isInstrumented(handler.fetch)) {
32
33
  handler.fetch = new Proxy(handler.fetch, {
33
34
  apply(target, thisArg, args) {
34
- const [request$1, env, context] = args;
35
+ const [request$1, env, ctx] = args;
36
+ const context = copyExecutionContext.copyExecutionContext(ctx);
37
+ args[2] = context;
35
38
 
36
39
  const options$1 = options.getFinalOptions(optionsCallback(env), env);
37
40
 
@@ -65,7 +68,10 @@ function withSentry(
65
68
  if ('scheduled' in handler && typeof handler.scheduled === 'function' && !instrument.isInstrumented(handler.scheduled)) {
66
69
  handler.scheduled = new Proxy(handler.scheduled, {
67
70
  apply(target, thisArg, args) {
68
- const [event, env, context] = args;
71
+ const [event, env, ctx] = args;
72
+ const context = copyExecutionContext.copyExecutionContext(ctx);
73
+ args[2] = context;
74
+
69
75
  return core.withIsolationScope(isolationScope => {
70
76
  const options$1 = options.getFinalOptions(optionsCallback(env), env);
71
77
  const waitUntil = context.waitUntil.bind(context);
@@ -108,7 +114,10 @@ function withSentry(
108
114
  if ('email' in handler && typeof handler.email === 'function' && !instrument.isInstrumented(handler.email)) {
109
115
  handler.email = new Proxy(handler.email, {
110
116
  apply(target, thisArg, args) {
111
- const [emailMessage, env, context] = args;
117
+ const [emailMessage, env, ctx] = args;
118
+ const context = copyExecutionContext.copyExecutionContext(ctx);
119
+ args[2] = context;
120
+
112
121
  return core.withIsolationScope(isolationScope => {
113
122
  const options$1 = options.getFinalOptions(optionsCallback(env), env);
114
123
  const waitUntil = context.waitUntil.bind(context);
@@ -149,7 +158,9 @@ function withSentry(
149
158
  if ('queue' in handler && typeof handler.queue === 'function' && !instrument.isInstrumented(handler.queue)) {
150
159
  handler.queue = new Proxy(handler.queue, {
151
160
  apply(target, thisArg, args) {
152
- const [batch, env, context] = args;
161
+ const [batch, env, ctx] = args;
162
+ const context = copyExecutionContext.copyExecutionContext(ctx);
163
+ args[2] = context;
153
164
 
154
165
  return core.withIsolationScope(isolationScope => {
155
166
  const options$1 = options.getFinalOptions(optionsCallback(env), env);
@@ -199,7 +210,9 @@ function withSentry(
199
210
  if ('tail' in handler && typeof handler.tail === 'function' && !instrument.isInstrumented(handler.tail)) {
200
211
  handler.tail = new Proxy(handler.tail, {
201
212
  apply(target, thisArg, args) {
202
- const [, env, context] = args;
213
+ const [, env, ctx] = args;
214
+ const context = copyExecutionContext.copyExecutionContext(ctx);
215
+ args[2] = context;
203
216
 
204
217
  return core.withIsolationScope(async isolationScope => {
205
218
  const options$1 = options.getFinalOptions(optionsCallback(env), env);
@@ -1 +1 @@
1
- {"version":3,"file":"handler.js","sources":["../../src/handler.ts"],"sourcesContent":["import {\n captureException,\n flush,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n startSpan,\n withIsolationScope,\n} from '@sentry/core';\nimport { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport type { CloudflareOptions } from './client';\nimport { isInstrumented, markAsInstrumented } from './instrument';\nimport { getHonoIntegration } from './integrations/hono';\nimport { getFinalOptions } from './options';\nimport { wrapRequestHandler } from './request';\nimport { addCloudResourceContext } from './scope-utils';\nimport { init } from './sdk';\n\n/**\n * Wrapper for Cloudflare handlers.\n *\n * Initializes the SDK and wraps the handler with Sentry instrumentation.\n *\n * Automatically instruments the `fetch` method of the handler.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param handler {ExportedHandler} The handler to wrap.\n * @returns The wrapped handler.\n */\n// eslint-disable-next-line complexity\nexport function withSentry<Env = unknown, QueueHandlerMessage = unknown, CfHostMetadata = unknown>(\n optionsCallback: (env: Env) => CloudflareOptions,\n handler: ExportedHandler<Env, QueueHandlerMessage, CfHostMetadata>,\n): ExportedHandler<Env, QueueHandlerMessage, CfHostMetadata> {\n setAsyncLocalStorageAsyncContextStrategy();\n\n try {\n if ('fetch' in handler && typeof handler.fetch === 'function' && !isInstrumented(handler.fetch)) {\n handler.fetch = new Proxy(handler.fetch, {\n apply(target, thisArg, args: Parameters<ExportedHandlerFetchHandler<Env, CfHostMetadata>>) {\n const [request, env, context] = args;\n\n const options = getFinalOptions(optionsCallback(env), env);\n\n return wrapRequestHandler({ options, request, context }, () => target.apply(thisArg, args));\n },\n });\n\n markAsInstrumented(handler.fetch);\n }\n\n /* Hono does not reach the catch block of the fetch handler and captureException needs to be called in the hono errorHandler */\n if (\n 'onError' in handler &&\n 'errorHandler' in handler &&\n typeof handler.errorHandler === 'function' &&\n !isInstrumented(handler.errorHandler)\n ) {\n handler.errorHandler = new Proxy(handler.errorHandler, {\n apply(target, thisArg, args) {\n const [err] = args;\n\n getHonoIntegration()?.handleHonoException(err);\n\n return Reflect.apply(target, thisArg, args);\n },\n });\n\n markAsInstrumented(handler.errorHandler);\n }\n\n if ('scheduled' in handler && typeof handler.scheduled === 'function' && !isInstrumented(handler.scheduled)) {\n handler.scheduled = new Proxy(handler.scheduled, {\n apply(target, thisArg, args: Parameters<ExportedHandlerScheduledHandler<Env>>) {\n const [event, env, context] = args;\n return withIsolationScope(isolationScope => {\n const options = getFinalOptions(optionsCallback(env), env);\n const waitUntil = context.waitUntil.bind(context);\n\n const client = init({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return startSpan(\n {\n op: 'faas.cron',\n name: `Scheduled Cron ${event.cron}`,\n attributes: {\n 'faas.cron': event.cron,\n 'faas.time': new Date(event.scheduledTime).toISOString(),\n 'faas.trigger': 'timer',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.scheduled',\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'task',\n },\n },\n async () => {\n try {\n return await (target.apply(thisArg, args) as ReturnType<typeof target>);\n } catch (e) {\n captureException(e, { mechanism: { handled: false, type: 'auto.faas.cloudflare.scheduled' } });\n throw e;\n } finally {\n waitUntil(flush(2000));\n }\n },\n );\n });\n },\n });\n\n markAsInstrumented(handler.scheduled);\n }\n\n if ('email' in handler && typeof handler.email === 'function' && !isInstrumented(handler.email)) {\n handler.email = new Proxy(handler.email, {\n apply(target, thisArg, args: Parameters<EmailExportedHandler<Env>>) {\n const [emailMessage, env, context] = args;\n return withIsolationScope(isolationScope => {\n const options = getFinalOptions(optionsCallback(env), env);\n const waitUntil = context.waitUntil.bind(context);\n\n const client = init({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return startSpan(\n {\n op: 'faas.email',\n name: `Handle Email ${emailMessage.to}`,\n attributes: {\n 'faas.trigger': 'email',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.email',\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'task',\n },\n },\n async () => {\n try {\n return await (target.apply(thisArg, args) as ReturnType<typeof target>);\n } catch (e) {\n captureException(e, { mechanism: { handled: false, type: 'auto.faas.cloudflare.email' } });\n throw e;\n } finally {\n waitUntil(flush(2000));\n }\n },\n );\n });\n },\n });\n\n markAsInstrumented(handler.email);\n }\n\n if ('queue' in handler && typeof handler.queue === 'function' && !isInstrumented(handler.queue)) {\n handler.queue = new Proxy(handler.queue, {\n apply(target, thisArg, args: Parameters<ExportedHandlerQueueHandler<Env, QueueHandlerMessage>>) {\n const [batch, env, context] = args;\n\n return withIsolationScope(isolationScope => {\n const options = getFinalOptions(optionsCallback(env), env);\n const waitUntil = context.waitUntil.bind(context);\n\n const client = init({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return startSpan(\n {\n op: 'faas.queue',\n name: `process ${batch.queue}`,\n attributes: {\n 'faas.trigger': 'pubsub',\n 'messaging.destination.name': batch.queue,\n 'messaging.system': 'cloudflare',\n 'messaging.batch.message_count': batch.messages.length,\n 'messaging.message.retry.count': batch.messages.reduce(\n (acc, message) => acc + message.attempts - 1,\n 0,\n ),\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'queue.process',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.queue',\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'task',\n },\n },\n async () => {\n try {\n return await (target.apply(thisArg, args) as ReturnType<typeof target>);\n } catch (e) {\n captureException(e, { mechanism: { handled: false, type: 'auto.faas.cloudflare.queue' } });\n throw e;\n } finally {\n waitUntil(flush(2000));\n }\n },\n );\n });\n },\n });\n\n markAsInstrumented(handler.queue);\n }\n\n if ('tail' in handler && typeof handler.tail === 'function' && !isInstrumented(handler.tail)) {\n handler.tail = new Proxy(handler.tail, {\n apply(target, thisArg, args: Parameters<ExportedHandlerTailHandler<Env>>) {\n const [, env, context] = args;\n\n return withIsolationScope(async isolationScope => {\n const options = getFinalOptions(optionsCallback(env), env);\n\n const waitUntil = context.waitUntil.bind(context);\n\n const client = init({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n try {\n return await (target.apply(thisArg, args) as ReturnType<typeof target>);\n } catch (e) {\n captureException(e, { mechanism: { handled: false, type: 'auto.faas.cloudflare.tail' } });\n throw e;\n } finally {\n waitUntil(flush(2000));\n }\n });\n },\n });\n\n markAsInstrumented(handler.tail);\n }\n\n // This is here because Miniflare sometimes cannot get instrumented\n } catch {\n // Do not console anything here, we don't want to spam the console with errors\n }\n\n return handler;\n}\n"],"names":["setAsyncLocalStorageAsyncContextStrategy","isInstrumented","request","options","getFinalOptions","wrapRequestHandler","markAsInstrumented","getHonoIntegration","withIsolationScope","init","addCloudResourceContext","startSpan","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","captureException","flush","SEMANTIC_ATTRIBUTE_SENTRY_OP"],"mappings":";;;;;;;;;;;AAkBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,UAAU;AAC1B,EAAE,eAAe;AACjB,EAAE,OAAO;AACT,EAA6D;AAC7D,EAAEA,8CAAwC,EAAE;;AAE5C,EAAE,IAAI;AACN,IAAI,IAAI,OAAA,IAAW,WAAW,OAAO,OAAO,CAAC,KAAA,KAAU,UAAA,IAAc,CAACC,yBAAc,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;AACrG,MAAM,OAAO,CAAC,KAAA,GAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE;AAC/C,QAAQ,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,EAAgE;AACnG,UAAU,MAAM,CAACC,SAAO,EAAE,GAAG,EAAE,OAAO,CAAA,GAAI,I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TRIBUTE_SENTRY_ORIGIN,\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n startSpan,\n withIsolationScope,\n} from '@sentry/core';\nimport { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport type { CloudflareOptions } from './client';\nimport { isInstrumented, markAsInstrumented } from './instrument';\nimport { getHonoIntegration } from './integrations/hono';\nimport { getFinalOptions } from './options';\nimport { wrapRequestHandler } from './request';\nimport { addCloudResourceContext } from './scope-utils';\nimport { init } from './sdk';\nimport { copyExecutionContext } from './utils/copyExecutionContext';\n\n/**\n * Wrapper for Cloudflare handlers.\n *\n * Initializes the SDK and wraps the handler with Sentry instrumentation.\n *\n * Automatically instruments the `fetch` method of the handler.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param handler {ExportedHandler} The handler to wrap.\n * @returns The wrapped handler.\n */\n// eslint-disable-next-line complexity\nexport function withSentry<Env = unknown, QueueHandlerMessage = unknown, CfHostMetadata = unknown>(\n optionsCallback: (env: Env) => CloudflareOptions,\n handler: ExportedHandler<Env, QueueHandlerMessage, CfHostMetadata>,\n): ExportedHandler<Env, QueueHandlerMessage, CfHostMetadata> {\n setAsyncLocalStorageAsyncContextStrategy();\n\n try {\n if ('fetch' in handler && typeof handler.fetch === 'function' && !isInstrumented(handler.fetch)) {\n handler.fetch = new Proxy(handler.fetch, {\n apply(target, thisArg, args: Parameters<ExportedHandlerFetchHandler<Env, CfHostMetadata>>) {\n const [request, env, ctx] = args;\n const context = copyExecutionContext(ctx);\n args[2] = context;\n\n const options = getFinalOptions(optionsCallback(env), env);\n\n return wrapRequestHandler({ options, request, context }, () => target.apply(thisArg, args));\n },\n });\n\n markAsInstrumented(handler.fetch);\n }\n\n /* Hono does not reach the catch block of the fetch handler and captureException needs to be called in the hono errorHandler */\n if (\n 'onError' in handler &&\n 'errorHandler' in handler &&\n typeof handler.errorHandler === 'function' &&\n !isInstrumented(handler.errorHandler)\n ) {\n handler.errorHandler = new Proxy(handler.errorHandler, {\n apply(target, thisArg, args) {\n const [err] = args;\n\n getHonoIntegration()?.handleHonoException(err);\n\n return Reflect.apply(target, thisArg, args);\n },\n });\n\n markAsInstrumented(handler.errorHandler);\n }\n\n if ('scheduled' in handler && typeof handler.scheduled === 'function' && !isInstrumented(handler.scheduled)) {\n handler.scheduled = new Proxy(handler.scheduled, {\n apply(target, thisArg, args: Parameters<ExportedHandlerScheduledHandler<Env>>) {\n const [event, env, ctx] = args;\n const context = copyExecutionContext(ctx);\n args[2] = context;\n\n return withIsolationScope(isolationScope => {\n const options = getFinalOptions(optionsCallback(env), env);\n const waitUntil = context.waitUntil.bind(context);\n\n const client = init({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return startSpan(\n {\n op: 'faas.cron',\n name: `Scheduled Cron ${event.cron}`,\n attributes: {\n 'faas.cron': event.cron,\n 'faas.time': new Date(event.scheduledTime).toISOString(),\n 'faas.trigger': 'timer',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.scheduled',\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'task',\n },\n },\n async () => {\n try {\n return await (target.apply(thisArg, args) as ReturnType<typeof target>);\n } catch (e) {\n captureException(e, { mechanism: { handled: false, type: 'auto.faas.cloudflare.scheduled' } });\n throw e;\n } finally {\n waitUntil(flush(2000));\n }\n },\n );\n });\n },\n });\n\n markAsInstrumented(handler.scheduled);\n }\n\n if ('email' in handler && typeof handler.email === 'function' && !isInstrumented(handler.email)) {\n handler.email = new Proxy(handler.email, {\n apply(target, thisArg, args: Parameters<EmailExportedHandler<Env>>) {\n const [emailMessage, env, ctx] = args;\n const context = copyExecutionContext(ctx);\n args[2] = context;\n\n return withIsolationScope(isolationScope => {\n const options = getFinalOptions(optionsCallback(env), env);\n const waitUntil = context.waitUntil.bind(context);\n\n const client = init({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return startSpan(\n {\n op: 'faas.email',\n name: `Handle Email ${emailMessage.to}`,\n attributes: {\n 'faas.trigger': 'email',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.email',\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'task',\n },\n },\n async () => {\n try {\n return await (target.apply(thisArg, args) as ReturnType<typeof target>);\n } catch (e) {\n captureException(e, { mechanism: { handled: false, type: 'auto.faas.cloudflare.email' } });\n throw e;\n } finally {\n waitUntil(flush(2000));\n }\n },\n );\n });\n },\n });\n\n markAsInstrumented(handler.email);\n }\n\n if ('queue' in handler && typeof handler.queue === 'function' && !isInstrumented(handler.queue)) {\n handler.queue = new Proxy(handler.queue, {\n apply(target, thisArg, args: Parameters<ExportedHandlerQueueHandler<Env, QueueHandlerMessage>>) {\n const [batch, env, ctx] = args;\n const context = copyExecutionContext(ctx);\n args[2] = context;\n\n return withIsolationScope(isolationScope => {\n const options = getFinalOptions(optionsCallback(env), env);\n const waitUntil = context.waitUntil.bind(context);\n\n const client = init({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return startSpan(\n {\n op: 'faas.queue',\n name: `process ${batch.queue}`,\n attributes: {\n 'faas.trigger': 'pubsub',\n 'messaging.destination.name': batch.queue,\n 'messaging.system': 'cloudflare',\n 'messaging.batch.message_count': batch.messages.length,\n 'messaging.message.retry.count': batch.messages.reduce(\n (acc, message) => acc + message.attempts - 1,\n 0,\n ),\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'queue.process',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.queue',\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'task',\n },\n },\n async () => {\n try {\n return await (target.apply(thisArg, args) as ReturnType<typeof target>);\n } catch (e) {\n captureException(e, { mechanism: { handled: false, type: 'auto.faas.cloudflare.queue' } });\n throw e;\n } finally {\n waitUntil(flush(2000));\n }\n },\n );\n });\n },\n });\n\n markAsInstrumented(handler.queue);\n }\n\n if ('tail' in handler && typeof handler.tail === 'function' && !isInstrumented(handler.tail)) {\n handler.tail = new Proxy(handler.tail, {\n apply(target, thisArg, args: Parameters<ExportedHandlerTailHandler<Env>>) {\n const [, env, ctx] = args;\n const context = copyExecutionContext(ctx);\n args[2] = context;\n\n return withIsolationScope(async isolationScope => {\n const options = getFinalOptions(optionsCallback(env), env);\n\n const waitUntil = context.waitUntil.bind(context);\n\n const client = init({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n try {\n return await (target.apply(thisArg, args) as ReturnType<typeof target>);\n } catch (e) {\n captureException(e, { mechanism: { handled: false, type: 'auto.faas.cloudflare.tail' } });\n throw e;\n } finally {\n waitUntil(flush(2000));\n }\n });\n },\n });\n\n markAsInstrumented(handler.tail);\n }\n\n // This is here because Miniflare sometimes cannot get instrumented\n } catch {\n // Do not console anything here, we don't want to spam the console with errors\n }\n\n return handler;\n}\n"],"names":["setAsyncLocalStorageAsyncContextStrategy","isInstrumented","request","copyExecutionContext","options","getFinalOptions","wrapRequestHandler","markAsInstrumented","getHonoIntegration","withIsolationScope","init","addCloudResourceContext","startSpan","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","captureException","flush","SEMANTIC_ATTRIBUTE_SENTRY_OP"],"mappings":";;;;;;;;;;;;AAmBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,UAAU;AAC1B,EAAE,eAAe;AACjB,EAAE,OAAO;AACT,EAA6D;AAC7D,EAAEA,8CAAwC,EAAE;;AAE5C,EAAE,IAAI;AACN,IAAI,IAAI,OAAA,IAAW,WAAW,OAAO,OAAO,CAAC,KAAA,KAAU,UAAA,IAAc,CAACC,yBAAc,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;AACrG,MAAM,OAAO,CAAC,KAAA,GAAQ,IAAI,KAAK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;AAEA,YAAAO,kCAAA,CAAA,cAAA,CAAA;;AAEA,YAAA,IAAA;AACA,cAAA,OAAA,OAAA,MAAA,CAAA,KAAA,CAAA,OAAA,EAAA,IAAA,CAAA,EAAA;AACA,aAAA,CAAA,OAAA,CAAA,EAAA;AACA,cAAAI,qBAAA,CAAA,CAAA,EAAA,EAAA,SAAA,EAAA,EAAA,OAAA,EAAA,KAAA,EAAA,IAAA,EAAA,2BAAA,EAAA,EAAA,CAAA;AACA,cAAA,MAAA,CAAA;AACA,aAAA,SAAA;AACA,cAAA,SAAA,CAAAC,UAAA,CAAA,IAAA,CAAA,CAAA;AACA;AACA,WAAA,CAAA;AACA,SAAA;AACA,OAAA,CAAA;;AAEA,MAAAT,6BAAA,CAAA,OAAA,CAAA,IAAA,CAAA;AACA;;AAEA;AACA,GAAA,CAAA,MAAA;AACA;AACA;;AAEA,EAAA,OAAA,OAAA;AACA;;;;"}
@@ -53,6 +53,7 @@ exports.getSpanDescendants = core.getSpanDescendants;
53
53
  exports.getSpanStatusFromHttpCode = core.getSpanStatusFromHttpCode;
54
54
  exports.getTraceData = core.getTraceData;
55
55
  exports.getTraceMetaTags = core.getTraceMetaTags;
56
+ exports.growthbookIntegration = core.growthbookIntegration;
56
57
  exports.inboundFiltersIntegration = core.inboundFiltersIntegration;
57
58
  exports.instrumentAnthropicAiClient = core.instrumentAnthropicAiClient;
58
59
  exports.instrumentGoogleGenAIClient = core.instrumentGoogleGenAIClient;
@@ -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,69 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+
3
+ /**
4
+ * Creates a new copy of the given execution context, optionally overriding methods.
5
+ *
6
+ * @param {ContextType|void} ctx - The execution context to be copied. Can be of type `ContextType` or `void`.
7
+ * @return {ContextType|void} A new execution context with the same properties and overridden methods if applicable.
8
+ */
9
+ function copyExecutionContext(ctx) {
10
+ if (!ctx) return ctx;
11
+
12
+ const overrides = new Map();
13
+ const contextPrototype = Object.getPrototypeOf(ctx);
14
+ const prototypeMethodNames = Object.getOwnPropertyNames(contextPrototype) ;
15
+ const ownPropertyNames = Object.getOwnPropertyNames(ctx) ;
16
+ const instrumented = new Set(['constructor']);
17
+ const descriptors = [...ownPropertyNames, ...prototypeMethodNames].reduce((prevDescriptors, methodName) => {
18
+ if (instrumented.has(methodName)) return prevDescriptors;
19
+ if (typeof ctx[methodName] !== 'function') return prevDescriptors;
20
+ instrumented.add(methodName);
21
+ const overridableDescriptor = makeOverridableDescriptor(overrides, ctx, methodName);
22
+ return {
23
+ ...prevDescriptors,
24
+ [methodName]: overridableDescriptor,
25
+ };
26
+ }, {});
27
+
28
+ return Object.create(ctx, descriptors);
29
+ }
30
+
31
+ /**
32
+ * Creates a property descriptor that allows overriding of a method on the given context object.
33
+ *
34
+ * This descriptor supports property overriding with functions only. It delegates method calls to
35
+ * the provided store if an override exists or to the original method on the context otherwise.
36
+ *
37
+ * @param {OverridesStore<ContextType>} store - The storage for overridden methods specific to the context type.
38
+ * @param {ContextType} ctx - The context object that contains the method to be overridden.
39
+ * @param {keyof ContextType} method - The method on the context object to create the overridable descriptor for.
40
+ * @return {PropertyDescriptor} A property descriptor enabling the overriding of the specified method.
41
+ */
42
+ function makeOverridableDescriptor(
43
+ store,
44
+ ctx,
45
+ method,
46
+ ) {
47
+ return {
48
+ configurable: true,
49
+ enumerable: true,
50
+ set: newValue => {
51
+ if (typeof newValue == 'function') {
52
+ store.set(method, newValue);
53
+ return;
54
+ }
55
+ Reflect.set(ctx, method, newValue);
56
+ },
57
+
58
+ get: () => {
59
+ if (store.has(method)) return store.get(method);
60
+ const methodFunction = Reflect.get(ctx, method);
61
+ if (typeof methodFunction !== 'function') return methodFunction;
62
+ // We should do bind() to make sure that the method is bound to the context object - otherwise it will not work
63
+ return methodFunction.bind(ctx);
64
+ },
65
+ };
66
+ }
67
+
68
+ exports.copyExecutionContext = copyExecutionContext;
69
+ //# sourceMappingURL=copyExecutionContext.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"copyExecutionContext.js","sources":["../../../src/utils/copyExecutionContext.ts"],"sourcesContent":["import { type DurableObjectState, type ExecutionContext } from '@cloudflare/workers-types';\n\ntype ContextType = ExecutionContext | DurableObjectState;\ntype OverridesStore<T extends ContextType> = Map<keyof T, (...args: unknown[]) => unknown>;\n\n/**\n * Creates a new copy of the given execution context, optionally overriding methods.\n *\n * @param {ContextType|void} ctx - The execution context to be copied. Can be of type `ContextType` or `void`.\n * @return {ContextType|void} A new execution context with the same properties and overridden methods if applicable.\n */\nexport function copyExecutionContext<T extends ContextType>(ctx: T): T {\n if (!ctx) return ctx;\n\n const overrides: OverridesStore<T> = new Map();\n const contextPrototype = Object.getPrototypeOf(ctx);\n const prototypeMethodNames = Object.getOwnPropertyNames(contextPrototype) as unknown as (keyof T)[];\n const ownPropertyNames = Object.getOwnPropertyNames(ctx) as unknown as (keyof T)[];\n const instrumented = new Set<unknown>(['constructor']);\n const descriptors = [...ownPropertyNames, ...prototypeMethodNames].reduce((prevDescriptors, methodName) => {\n if (instrumented.has(methodName)) return prevDescriptors;\n if (typeof ctx[methodName] !== 'function') return prevDescriptors;\n instrumented.add(methodName);\n const overridableDescriptor = makeOverridableDescriptor(overrides, ctx, methodName);\n return {\n ...prevDescriptors,\n [methodName]: overridableDescriptor,\n };\n }, {});\n\n return Object.create(ctx, descriptors);\n}\n\n/**\n * Creates a property descriptor that allows overriding of a method on the given context object.\n *\n * This descriptor supports property overriding with functions only. It delegates method calls to\n * the provided store if an override exists or to the original method on the context otherwise.\n *\n * @param {OverridesStore<ContextType>} store - The storage for overridden methods specific to the context type.\n * @param {ContextType} ctx - The context object that contains the method to be overridden.\n * @param {keyof ContextType} method - The method on the context object to create the overridable descriptor for.\n * @return {PropertyDescriptor} A property descriptor enabling the overriding of the specified method.\n */\nfunction makeOverridableDescriptor<T extends ContextType>(\n store: OverridesStore<T>,\n ctx: T,\n method: keyof T,\n): PropertyDescriptor {\n return {\n configurable: true,\n enumerable: true,\n set: newValue => {\n if (typeof newValue == 'function') {\n store.set(method, newValue);\n return;\n }\n Reflect.set(ctx, method, newValue);\n },\n\n get: () => {\n if (store.has(method)) return store.get(method);\n const methodFunction = Reflect.get(ctx, method);\n if (typeof methodFunction !== 'function') return methodFunction;\n // We should do bind() to make sure that the method is bound to the context object - otherwise it will not work\n return methodFunction.bind(ctx);\n },\n };\n}\n"],"names":[],"mappings":";;AAKA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,oBAAoB,CAAwB,GAAG,EAAQ;AACvE,EAAE,IAAI,CAAC,GAAG,EAAE,OAAO,GAAG;;AAEtB,EAAE,MAAM,SAAS,GAAsB,IAAI,GAAG,EAAE;AAChD,EAAE,MAAM,mBAAmB,MAAM,CAAC,cAAc,CAAC,GAAG,CAAC;AACrD,EAAE,MAAM,uBAAuB,MAAM,CAAC,mBAAmB,CAAC,gBAAgB,CAAA;AAC1E,EAAE,MAAM,mBAAmB,MAAM,CAAC,mBAAmB,CAAC,GAAG,CAAA;AACzD,EAAE,MAAM,eAAe,IAAI,GAAG,CAAU,CAAC,aAAa,CAAC,CAAC;AACxD,EAAE,MAAM,WAAA,GAAc,CAAC,GAAG,gBAAgB,EAAE,GAAG,oBAAoB,CAAC,CAAC,MAAM,CAAC,CAAC,eAAe,EAAE,UAAU,KAAK;AAC7G,IAAI,IAAI,YAAY,CAAC,GAAG,CAAC,UAAU,CAAC,EAA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AAG;AACH;;;;"}
@@ -4,6 +4,7 @@ const core = require('@sentry/core');
4
4
  const async = require('./async.js');
5
5
  const scopeUtils = require('./scope-utils.js');
6
6
  const sdk = require('./sdk.js');
7
+ const copyExecutionContext = require('./utils/copyExecutionContext.js');
7
8
 
8
9
  const UUID_REGEX = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i;
9
10
 
@@ -130,6 +131,9 @@ function instrumentWorkflowWithSentry
130
131
  return new Proxy(WorkFlowClass, {
131
132
  construct(target, args, newTarget) {
132
133
  const [ctx, env] = args;
134
+ const context = copyExecutionContext.copyExecutionContext(ctx);
135
+ args[0] = context;
136
+
133
137
  const options = optionsCallback(env);
134
138
  const instance = Reflect.construct(target, args, newTarget) ;
135
139
  return new Proxy(instance, {
@@ -152,10 +156,10 @@ function instrumentWorkflowWithSentry
152
156
  return await obj.run.call(
153
157
  obj,
154
158
  event,
155
- new WrappedWorkflowStep(event.instanceId, ctx, options, step),
159
+ new WrappedWorkflowStep(event.instanceId, context, options, step),
156
160
  );
157
161
  } finally {
158
- ctx.waitUntil(core.flush(2000));
162
+ context.waitUntil(core.flush(2000));
159
163
  }
160
164
  });
161
165
  });
@@ -1 +1 @@
1
- {"version":3,"file":"workflows.js","sources":["../../src/workflows.ts"],"sourcesContent":["import type { PropagationContext } from '@sentry/core';\nimport {\n captureException,\n flush,\n getCurrentScope,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n startSpan,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type {\n WorkflowEntrypoint,\n WorkflowEvent,\n WorkflowSleepDuration,\n WorkflowStep,\n WorkflowStepConfig,\n WorkflowStepEvent,\n WorkflowTimeoutDuration,\n} from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport type { CloudflareOptions } from './client';\nimport { addCloudResourceContext } from './scope-utils';\nimport { init } from './sdk';\n\nconst UUID_REGEX = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i;\n\n/**\n * Hashes a string to a UUID using SHA-1.\n */\nexport async function deterministicTraceIdFromInstanceId(instanceId: string): Promise<string> {\n const buf = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(instanceId));\n return (\n Array.from(new Uint8Array(buf))\n // We only need the first 16 bytes for the 32 characters\n .slice(0, 16)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('')\n );\n}\n\nasync function propagationContextFromInstanceId(instanceId: string): Promise<PropagationContext> {\n const traceId = UUID_REGEX.test(instanceId)\n ? instanceId.replace(/-/g, '')\n : await deterministicTraceIdFromInstanceId(instanceId);\n\n // Derive sampleRand from last 4 characters of the random UUID\n //\n // We cannot store any state between workflow steps, so we derive the\n // sampleRand from the traceId itself. This ensures that the sampling is\n // consistent across all steps in the same workflow instance.\n const sampleRand = parseInt(traceId.slice(-4), 16) / 0xffff;\n\n return {\n traceId,\n sampleRand,\n };\n}\n\nclass WrappedWorkflowStep implements WorkflowStep {\n public constructor(\n private _instanceId: string,\n private _ctx: ExecutionContext,\n private _options: CloudflareOptions,\n private _step: WorkflowStep,\n ) {}\n\n public async do<T extends Rpc.Serializable<T>>(name: string, callback: () => Promise<T>): Promise<T>;\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n config: WorkflowStepConfig,\n callback: () => Promise<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n configOrCallback: WorkflowStepConfig | (() => Promise<T>),\n maybeCallback?: () => Promise<T>,\n ): Promise<T> {\n // Capture the current scope, so parent span (e.g., a startSpan surrounding step.do) is preserved\n const scopeForStep = getCurrentScope();\n\n const userCallback = (maybeCallback || configOrCallback) as () => Promise<T>;\n const config = typeof configOrCallback === 'function' ? undefined : configOrCallback;\n\n const instrumentedCallback: () => Promise<T> = async () => {\n return startSpan(\n {\n op: 'function.step.do',\n name,\n scope: scopeForStep,\n attributes: {\n 'cloudflare.workflow.timeout': config?.timeout,\n 'cloudflare.workflow.retries.backoff': config?.retries?.backoff,\n 'cloudflare.workflow.retries.delay': config?.retries?.delay,\n 'cloudflare.workflow.retries.limit': config?.retries?.limit,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.workflow',\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'task',\n },\n },\n async span => {\n try {\n const result = await userCallback();\n span.setStatus({ code: 1 });\n return result;\n } catch (error) {\n captureException(error, { mechanism: { handled: true, type: 'auto.faas.cloudflare.workflow' } });\n throw error;\n } finally {\n this._ctx.waitUntil(flush(2000));\n }\n },\n );\n };\n\n return config ? this._step.do(name, config, instrumentedCallback) : this._step.do(name, instrumentedCallback);\n }\n\n public async sleep(name: string, duration: WorkflowSleepDuration): Promise<void> {\n return this._step.sleep(name, duration);\n }\n\n public async sleepUntil(name: string, timestamp: Date | number): Promise<void> {\n return this._step.sleepUntil(name, timestamp);\n }\n\n public async waitForEvent<T extends Rpc.Serializable<T>>(\n name: string,\n options: { type: string; timeout?: WorkflowTimeoutDuration | number },\n ): Promise<WorkflowStepEvent<T>> {\n return this._step.waitForEvent<T>(name, options);\n }\n}\n\n/**\n * Instruments a Cloudflare Workflow class with Sentry.\n *\n * @example\n * ```typescript\n * const InstrumentedWorkflow = instrumentWorkflowWithSentry(\n * (env) => ({ dsn: env.SENTRY_DSN }),\n * MyWorkflowClass\n * );\n *\n * export default InstrumentedWorkflow;\n * ```\n *\n * @param optionsCallback - Function that returns Sentry options to initialize Sentry\n * @param WorkflowClass - The workflow class to instrument\n * @returns Instrumented workflow class with the same interface\n */\nexport function instrumentWorkflowWithSentry<\n E, // Environment type\n P, // Payload type\n T extends WorkflowEntrypoint<E, P>, // WorkflowEntrypoint type\n C extends new (ctx: ExecutionContext, env: E) => T, // Constructor type of the WorkflowEntrypoint class\n>(optionsCallback: (env: E) => CloudflareOptions, WorkFlowClass: C): C {\n return new Proxy(WorkFlowClass, {\n construct(target: C, args: [ctx: ExecutionContext, env: E], newTarget) {\n const [ctx, env] = args;\n const options = optionsCallback(env);\n const instance = Reflect.construct(target, args, newTarget) as T;\n return new Proxy(instance, {\n get(obj, prop, receiver) {\n if (prop === 'run') {\n return async function (event: WorkflowEvent<P>, step: WorkflowStep): Promise<unknown> {\n setAsyncLocalStorageAsyncContextStrategy();\n\n return withIsolationScope(async isolationScope => {\n const client = init({ ...options, enableDedupe: false });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return withScope(async scope => {\n const propagationContext = await propagationContextFromInstanceId(event.instanceId);\n scope.setPropagationContext(propagationContext);\n\n try {\n return await obj.run.call(\n obj,\n event,\n new WrappedWorkflowStep(event.instanceId, ctx, options, step),\n );\n } finally {\n ctx.waitUntil(flush(2000));\n }\n });\n });\n };\n }\n return Reflect.get(obj, prop, receiver);\n },\n });\n },\n });\n}\n"],"names":["getCurrentScope","startSpan","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","captureException","flush","setAsyncLocalStorageAsyncContextStrategy","withIsolationScope","init","addCloudResourceContext","withScope"],"mappings":";;;;;;;AAyBA,MAAM,UAAA,GAAa,qEAAqE;;AAExF;AACA;AACA;AACO,eAAe,kCAAkC,CAAC,UAAU,EAA2B;AAC9F,EAAE,MAAM,MAAM,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;AACvF,EAAE;AACF,IAAI,KAAK,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,GAAG,CAAC;AAClC;AACA,OAAO,KAAK,CAAC,CAAC,EAAE,EAAE;AAClB,OAAO,GAAG,CAAC,CAAA,IAAK,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,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AAK,CAAC,UAAU,CAAC;AACrG,kBAAkB,KAAK,CAAC,qBAAqB,CAAC,kBAAkB,CAAC;;AAEjE,kBAAkB,IAAI;AACtB,oBAAoB,OAAO,MAAM,GAAG,CAAC,GAAG,CAAC,IAAI;AAC7C,sBAAsB,GAAG;AACzB,sBAAsB,KAAK;AAC3B,sBAAsB,IAAI,mBAAmB,CAAC,KAAK,CAAC,UAAU,EAAE,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC;AACnF,qBAAqB;AACrB,4BAA4B;AAC5B,oBAAoB,GAAG,CAAC,SAAS,CAACL,UAAK,CAAC,IAAI,CAAC,CAAC;AAC9C;AACA,iBAAiB,CAAC;AAClB,eAAe,CAAC;AAChB,aAAa;AACb;AACA,UAAU,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,QAAQ,CAAC;AACjD,SAAS;AACT,OAAO,CAAC;AACR,KAAK;AACL,GAAG,CAAC;AACJ;;;;;"}
1
+ {"version":3,"file":"workflows.js","sources":["../../src/workflows.ts"],"sourcesContent":["import type { PropagationContext } from '@sentry/core';\nimport {\n captureException,\n flush,\n getCurrentScope,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n startSpan,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type {\n WorkflowEntrypoint,\n WorkflowEvent,\n WorkflowSleepDuration,\n WorkflowStep,\n WorkflowStepConfig,\n WorkflowStepEvent,\n WorkflowTimeoutDuration,\n} from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport type { CloudflareOptions } from './client';\nimport { addCloudResourceContext } from './scope-utils';\nimport { init } from './sdk';\nimport { copyExecutionContext } from './utils/copyExecutionContext';\n\nconst UUID_REGEX = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i;\n\n/**\n * Hashes a string to a UUID using SHA-1.\n */\nexport async function deterministicTraceIdFromInstanceId(instanceId: string): Promise<string> {\n const buf = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(instanceId));\n return (\n Array.from(new Uint8Array(buf))\n // We only need the first 16 bytes for the 32 characters\n .slice(0, 16)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('')\n );\n}\n\nasync function propagationContextFromInstanceId(instanceId: string): Promise<PropagationContext> {\n const traceId = UUID_REGEX.test(instanceId)\n ? instanceId.replace(/-/g, '')\n : await deterministicTraceIdFromInstanceId(instanceId);\n\n // Derive sampleRand from last 4 characters of the random UUID\n //\n // We cannot store any state between workflow steps, so we derive the\n // sampleRand from the traceId itself. This ensures that the sampling is\n // consistent across all steps in the same workflow instance.\n const sampleRand = parseInt(traceId.slice(-4), 16) / 0xffff;\n\n return {\n traceId,\n sampleRand,\n };\n}\n\nclass WrappedWorkflowStep implements WorkflowStep {\n public constructor(\n private _instanceId: string,\n private _ctx: ExecutionContext,\n private _options: CloudflareOptions,\n private _step: WorkflowStep,\n ) {}\n\n public async do<T extends Rpc.Serializable<T>>(name: string, callback: () => Promise<T>): Promise<T>;\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n config: WorkflowStepConfig,\n callback: () => Promise<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n configOrCallback: WorkflowStepConfig | (() => Promise<T>),\n maybeCallback?: () => Promise<T>,\n ): Promise<T> {\n // Capture the current scope, so parent span (e.g., a startSpan surrounding step.do) is preserved\n const scopeForStep = getCurrentScope();\n\n const userCallback = (maybeCallback || configOrCallback) as () => Promise<T>;\n const config = typeof configOrCallback === 'function' ? undefined : configOrCallback;\n\n const instrumentedCallback: () => Promise<T> = async () => {\n return startSpan(\n {\n op: 'function.step.do',\n name,\n scope: scopeForStep,\n attributes: {\n 'cloudflare.workflow.timeout': config?.timeout,\n 'cloudflare.workflow.retries.backoff': config?.retries?.backoff,\n 'cloudflare.workflow.retries.delay': config?.retries?.delay,\n 'cloudflare.workflow.retries.limit': config?.retries?.limit,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.workflow',\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'task',\n },\n },\n async span => {\n try {\n const result = await userCallback();\n span.setStatus({ code: 1 });\n return result;\n } catch (error) {\n captureException(error, { mechanism: { handled: true, type: 'auto.faas.cloudflare.workflow' } });\n throw error;\n } finally {\n this._ctx.waitUntil(flush(2000));\n }\n },\n );\n };\n\n return config ? this._step.do(name, config, instrumentedCallback) : this._step.do(name, instrumentedCallback);\n }\n\n public async sleep(name: string, duration: WorkflowSleepDuration): Promise<void> {\n return this._step.sleep(name, duration);\n }\n\n public async sleepUntil(name: string, timestamp: Date | number): Promise<void> {\n return this._step.sleepUntil(name, timestamp);\n }\n\n public async waitForEvent<T extends Rpc.Serializable<T>>(\n name: string,\n options: { type: string; timeout?: WorkflowTimeoutDuration | number },\n ): Promise<WorkflowStepEvent<T>> {\n return this._step.waitForEvent<T>(name, options);\n }\n}\n\n/**\n * Instruments a Cloudflare Workflow class with Sentry.\n *\n * @example\n * ```typescript\n * const InstrumentedWorkflow = instrumentWorkflowWithSentry(\n * (env) => ({ dsn: env.SENTRY_DSN }),\n * MyWorkflowClass\n * );\n *\n * export default InstrumentedWorkflow;\n * ```\n *\n * @param optionsCallback - Function that returns Sentry options to initialize Sentry\n * @param WorkflowClass - The workflow class to instrument\n * @returns Instrumented workflow class with the same interface\n */\nexport function instrumentWorkflowWithSentry<\n E, // Environment type\n P, // Payload type\n T extends WorkflowEntrypoint<E, P>, // WorkflowEntrypoint type\n C extends new (ctx: ExecutionContext, env: E) => T, // Constructor type of the WorkflowEntrypoint class\n>(optionsCallback: (env: E) => CloudflareOptions, WorkFlowClass: C): C {\n return new Proxy(WorkFlowClass, {\n construct(target: C, args: [ctx: ExecutionContext, env: E], newTarget) {\n const [ctx, env] = args;\n const context = copyExecutionContext(ctx);\n args[0] = context;\n\n const options = optionsCallback(env);\n const instance = Reflect.construct(target, args, newTarget) as T;\n return new Proxy(instance, {\n get(obj, prop, receiver) {\n if (prop === 'run') {\n return async function (event: WorkflowEvent<P>, step: WorkflowStep): Promise<unknown> {\n setAsyncLocalStorageAsyncContextStrategy();\n\n return withIsolationScope(async isolationScope => {\n const client = init({ ...options, enableDedupe: false });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return withScope(async scope => {\n const propagationContext = await propagationContextFromInstanceId(event.instanceId);\n scope.setPropagationContext(propagationContext);\n\n try {\n return await obj.run.call(\n obj,\n event,\n new WrappedWorkflowStep(event.instanceId, context, options, step),\n );\n } finally {\n context.waitUntil(flush(2000));\n }\n });\n });\n };\n }\n return Reflect.get(obj, prop, receiver);\n },\n });\n },\n });\n}\n"],"names":["getCurrentScope","startSpan","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","captureException","flush","copyExecutionContext","setAsyncLocalStorageAsyncContextStrategy","withIsolationScope","init","addCloudResourceContext","withScope"],"mappings":";;;;;;;;AA0BA,MAAM,UAAA,GAAa,qEAAqE;;AAExF;AACA;AACA;AACO,eAAe,kCAAkC,CAAC,UAAU,EAA2B;AAC9F,EAAE,MAAM,MAAM,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;AACvF,EAAE;AACF,IAAI,KAAK,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,GAAG,CAAC;AAClC;AACA,OAAO,KAAK,CAAC,CAAC,EAAE,EAAE;AAClB,OAAO,GAAG,CAAC,CAAA,IAAK,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC;AAC/C,OAAO,IAAI,CAAC,EAAE;AACd;AACA;;AAEA,eAAe,gCAAgC,CAAC,UAAU,EAAuC;AACjG,EAAE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AC,KAAK,CAAC,UAAU,CAAC;AACrG,kBAAkB,KAAK,CAAC,qBAAqB,CAAC,kBAAkB,CAAC;;AAEjE,kBAAkB,IAAI;AACtB,oBAAoB,OAAO,MAAM,GAAG,CAAC,GAAG,CAAC,IAAI;AAC7C,sBAAsB,GAAG;AACzB,sBAAsB,KAAK;AAC3B,sBAAsB,IAAI,mBAAmB,CAAC,KAAK,CAAC,UAAU,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC;AACvF,qBAAqB;AACrB,4BAA4B;AAC5B,oBAAoB,OAAO,CAAC,SAAS,CAACN,UAAK,CAAC,IAAI,CAAC,CAAC;AAClD;AACA,iBAAiB,CAAC;AAClB,eAAe,CAAC;AAChB,aAAa;AACb;AACA,UAAU,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,QAAQ,CAAC;AACjD,SAAS;AACT,OAAO,CAAC;AACR,KAAK;AACL,GAAG,CAAC;AACJ;;;;;"}
@@ -4,6 +4,7 @@ import { isInstrumented, markAsInstrumented } from './instrument.js';
4
4
  import { getFinalOptions } from './options.js';
5
5
  import { wrapRequestHandler } from './request.js';
6
6
  import { init } from './sdk.js';
7
+ import { copyExecutionContext } from './utils/copyExecutionContext.js';
7
8
 
8
9
  /* eslint-disable @typescript-eslint/unbound-method */
9
10
 
@@ -168,8 +169,9 @@ function instrumentDurableObjectWithSentry
168
169
 
169
170
  (optionsCallback, DurableObjectClass) {
170
171
  return new Proxy(DurableObjectClass, {
171
- construct(target, [context, env]) {
172
+ construct(target, [ctx, env]) {
172
173
  setAsyncLocalStorageAsyncContextStrategy();
174
+ const context = copyExecutionContext(ctx);
173
175
 
174
176
  const options = getFinalOptions(optionsCallback(env), env);
175
177
 
@@ -1 +1 @@
1
- {"version":3,"file":"durableobject.js","sources":["../../src/durableobject.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/unbound-method */\nimport {\n type Scope,\n captureException,\n flush,\n getClient,\n isThenable,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n startSpan,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type { DurableObject } from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport type { CloudflareOptions } from './client';\nimport { isInstrumented, markAsInstrumented } from './instrument';\nimport { getFinalOptions } from './options';\nimport { wrapRequestHandler } from './request';\nimport { init } from './sdk';\n\ntype MethodWrapperOptions = {\n spanName?: string;\n spanOp?: string;\n options: CloudflareOptions;\n context: ExecutionContext | DurableObjectState;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype OriginalMethod = (...args: any[]) => any;\n\nfunction wrapMethodWithSentry<T extends OriginalMethod>(\n wrapperOptions: MethodWrapperOptions,\n handler: T,\n callback?: (...args: Parameters<T>) => void,\n noMark?: true,\n): T {\n if (isInstrumented(handler)) {\n return handler;\n }\n\n if (!noMark) {\n markAsInstrumented(handler);\n }\n\n return new Proxy(handler, {\n apply(target, thisArg, args: Parameters<T>) {\n const currentClient = getClient();\n // if a client is already set, use withScope, otherwise use withIsolationScope\n const sentryWithScope = currentClient ? withScope : withIsolationScope;\n\n const wrappedFunction = (scope: Scope): unknown => {\n // In certain situations, the passed context can become undefined.\n // For example, for Astro while prerendering pages at build time.\n // see: https://github.com/getsentry/sentry-javascript/issues/13217\n const context = wrapperOptions.context as ExecutionContext | undefined;\n\n const waitUntil = context?.waitUntil?.bind?.(context);\n\n const currentClient = scope.getClient();\n if (!currentClient) {\n const client = init({ ...wrapperOptions.options, ctx: context });\n scope.setClient(client);\n }\n\n if (!wrapperOptions.spanName) {\n try {\n if (callback) {\n callback(...args);\n }\n const result = Reflect.apply(target, thisArg, args);\n\n if (isThenable(result)) {\n return result.then(\n (res: unknown) => {\n waitUntil?.(flush(2000));\n return res;\n },\n (e: unknown) => {\n captureException(e, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object',\n handled: false,\n },\n });\n waitUntil?.(flush(2000));\n throw e;\n },\n );\n } else {\n waitUntil?.(flush(2000));\n return result;\n }\n } catch (e) {\n captureException(e, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object',\n handled: false,\n },\n });\n waitUntil?.(flush(2000));\n throw e;\n }\n }\n\n const attributes = wrapperOptions.spanOp\n ? {\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: wrapperOptions.spanOp,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.durable_object',\n }\n : {};\n\n return startSpan({ name: wrapperOptions.spanName, attributes }, () => {\n try {\n const result = Reflect.apply(target, thisArg, args);\n\n if (isThenable(result)) {\n return result.then(\n (res: unknown) => {\n waitUntil?.(flush(2000));\n return res;\n },\n (e: unknown) => {\n captureException(e, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object',\n handled: false,\n },\n });\n waitUntil?.(flush(2000));\n throw e;\n },\n );\n } else {\n waitUntil?.(flush(2000));\n return result;\n }\n } catch (e) {\n captureException(e, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object',\n handled: false,\n },\n });\n waitUntil?.(flush(2000));\n throw e;\n }\n });\n };\n\n return sentryWithScope(wrappedFunction);\n },\n });\n}\n\n/**\n * Instruments a Durable Object class to capture errors and performance data.\n *\n * Instruments the following methods:\n * - fetch\n * - alarm\n * - webSocketMessage\n * - webSocketClose\n * - webSocketError\n *\n * as well as any other public RPC methods on the Durable Object instance.\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, [context, env]) {\n setAsyncLocalStorageAsyncContextStrategy();\n\n const options = getFinalOptions(optionsCallback(env), env);\n\n const obj = new target(context, env);\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' && !isInstrumented(obj.fetch)) {\n obj.fetch = new Proxy(obj.fetch, {\n apply(target, thisArg, args) {\n return wrapRequestHandler({ options, request: args[0], context }, () =>\n Reflect.apply(target, thisArg, args),\n );\n },\n });\n\n markAsInstrumented(obj.fetch);\n }\n\n if (obj.alarm && typeof obj.alarm === 'function') {\n obj.alarm = wrapMethodWithSentry({ options, context, spanName: 'alarm' }, obj.alarm);\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 for (const method of Object.getOwnPropertyNames(obj)) {\n if (\n method === 'fetch' ||\n method === 'alarm' ||\n method === 'webSocketError' ||\n method === 'webSocketClose' ||\n method === 'webSocketMessage'\n ) {\n continue;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n const value = (obj as any)[method] as unknown;\n if (typeof value === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n (obj as any)[method] = wrapMethodWithSentry(\n { options, context, spanName: method, spanOp: 'rpc' },\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n value as (...args: any[]) => any,\n );\n }\n }\n\n // Store context and options on the instance for prototype methods to access\n Object.defineProperty(obj, '__SENTRY_CONTEXT__', {\n value: context,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n\n Object.defineProperty(obj, '__SENTRY_OPTIONS__', {\n value: options,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n\n if (options?.instrumentPrototypeMethods) {\n instrumentPrototype(target, options.instrumentPrototypeMethods);\n }\n\n return obj;\n },\n });\n}\n\nfunction instrumentPrototype<T extends NewableFunction>(target: T, methodsToInstrument: boolean | string[]): void {\n const proto = target.prototype;\n\n // Get all methods from the prototype chain\n const methodNames = new Set<string>();\n let current = proto;\n\n while (current && current !== Object.prototype) {\n Object.getOwnPropertyNames(current).forEach(name => {\n if (name !== 'constructor' && typeof (current as Record<string, unknown>)[name] === 'function') {\n methodNames.add(name);\n }\n });\n current = Object.getPrototypeOf(current);\n }\n\n // Create a set for efficient lookups when methodsToInstrument is an array\n const methodsToInstrumentSet = Array.isArray(methodsToInstrument) ? new Set(methodsToInstrument) : null;\n\n // Instrument each method on the prototype\n methodNames.forEach(methodName => {\n const originalMethod = (proto as Record<string, unknown>)[methodName];\n\n if (!originalMethod || isInstrumented(originalMethod)) {\n return;\n }\n\n // If methodsToInstrument is an array, only instrument methods in that set\n if (methodsToInstrumentSet && !methodsToInstrumentSet.has(methodName)) {\n return;\n }\n\n // Create a wrapper that gets context/options from the instance at runtime\n const wrappedMethod = function (this: any, ...args: any[]): unknown {\n const thisWithSentry = this as {\n __SENTRY_CONTEXT__: DurableObjectState;\n __SENTRY_OPTIONS__: CloudflareOptions;\n };\n const instanceContext = thisWithSentry.__SENTRY_CONTEXT__;\n const instanceOptions = thisWithSentry.__SENTRY_OPTIONS__;\n\n if (!instanceOptions) {\n // Fallback to original method if no Sentry data found\n return (originalMethod as (...args: any[]) => any).apply(this, args);\n }\n\n // Use the existing wrapper but with instance-specific context/options\n const wrapper = wrapMethodWithSentry(\n {\n options: instanceOptions,\n context: instanceContext,\n spanName: methodName,\n spanOp: 'rpc',\n },\n originalMethod as (...args: any[]) => any,\n undefined,\n true, // noMark = true since we'll mark the prototype method\n );\n\n return (wrapper as (...args: any[]) => any).apply(this, args);\n };\n\n markAsInstrumented(wrappedMethod);\n\n // Replace the prototype method\n Object.defineProperty(proto, methodName, {\n value: wrappedMethod,\n enumerable: false,\n writable: true,\n configurable: true,\n });\n });\n}\n"],"names":[],"mappings":";;;;;;;AAAA;;AA+BA,SAAS,oBAAoB;AAC7B,EAAE,cAAc;AAChB,EAAE,OAAO;AACT,EAAE,QAAQ;AACV,EAAE,MAAM;AACR,EAAK;AACL,EAAE,IAAI,cAAc,CAAC,OAAO,CAAC,EAAE;AAC/B,IAAI,OAAO,OAAO;AAClB;;AAEA,EAAE,IAAI,CAAC,MAAM,EAAE;AACf,IAAI,kBAAkB,CAAC,OAAO,CAAC;AAC/B;;AAEA,EAAE,OAAO,IAAI,KAAK,CAAC,OAAO,EAAE;AAC5B,IAAI,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,EAAiB;AAChD,MAAM,MAAM,aAAA,GAAgB,SAAS,EAAE;AACvC;AACA,MAAM,MAAM,eAAA,GAAkB,gBAAgB,SAAA,GAAY,kBAAkB;;AAE5E,MAAM,MAAM,eAAA,GAAkB,CAAC,KAAK,KAAqB;AACzD;AACA;AACA;AACA,QAAQ,MAAM,OAAA,GAAU,cAAc,CAAC,OAAA;;AAEvC,QAAQ,MAAM,SAAA,GAAY,OAAO,EAAE,SAAS,EAAE,IAAI,GAAG,OAAO,CAAC;;AAE7D,Q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AC/D,MAAM,MAAM,eAAA,GAAkB,cAAc,CAAC,kBAAkB;;AAE/D,MAAM,IAAI,CAAC,eAAe,EAAE;AAC5B;AACA,QAAQ,OAAO,CAAC,cAAA,GAA2C,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC;AAC5E;;AAEA;AACA,MAAM,MAAM,OAAA,GAAU,oBAAoB;AAC1C,QAAQ;AACR,UAAU,OAAO,EAAE,eAAe;AAClC,UAAU,OAAO,EAAE,eAAe;AAClC,UAAU,QAAQ,EAAE,UAAU;AAC9B,UAAU,MAAM,EAAE,KAAK;AACvB,SAAS;AACT,QAAQ,cAAA;AACR,QAAQ,SAAS;AACjB,QAAQ,IAAI;AACZ,OAAO;;AAEP,MAAM,OAAO,CAAC,OAAA,GAAoC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC;AACnE,KAAK;;AAEL,IAAI,kBAAkB,CAAC,aAAa,CAAC;;AAErC;AACA,IAAI,MAAM,CAAC,cAAc,CAAC,KAAK,EAAE,UAAU,EAAE;AAC7C,MAAM,KAAK,EAAE,aAAa;AAC1B,MAAM,UAAU,EAAE,KAAK;AACvB,MAAM,QAAQ,EAAE,IAAI;AACpB,MAAM,YAAY,EAAE,IAAI;AACxB,KAAK,CAAC;AACN,GAAG,CAAC;AACJ;;;;"}
1
+ {"version":3,"file":"durableobject.js","sources":["../../src/durableobject.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/unbound-method */\nimport {\n type Scope,\n captureException,\n flush,\n getClient,\n isThenable,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n startSpan,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type { DurableObject } from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport type { CloudflareOptions } from './client';\nimport { isInstrumented, markAsInstrumented } from './instrument';\nimport { getFinalOptions } from './options';\nimport { wrapRequestHandler } from './request';\nimport { init } from './sdk';\nimport { copyExecutionContext } from './utils/copyExecutionContext';\n\ntype MethodWrapperOptions = {\n spanName?: string;\n spanOp?: string;\n options: CloudflareOptions;\n context: ExecutionContext | DurableObjectState;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype OriginalMethod = (...args: any[]) => any;\n\nfunction wrapMethodWithSentry<T extends OriginalMethod>(\n wrapperOptions: MethodWrapperOptions,\n handler: T,\n callback?: (...args: Parameters<T>) => void,\n noMark?: true,\n): T {\n if (isInstrumented(handler)) {\n return handler;\n }\n\n if (!noMark) {\n markAsInstrumented(handler);\n }\n\n return new Proxy(handler, {\n apply(target, thisArg, args: Parameters<T>) {\n const currentClient = getClient();\n // if a client is already set, use withScope, otherwise use withIsolationScope\n const sentryWithScope = currentClient ? withScope : withIsolationScope;\n\n const wrappedFunction = (scope: Scope): unknown => {\n // In certain situations, the passed context can become undefined.\n // For example, for Astro while prerendering pages at build time.\n // see: https://github.com/getsentry/sentry-javascript/issues/13217\n const context = wrapperOptions.context as ExecutionContext | undefined;\n\n const waitUntil = context?.waitUntil?.bind?.(context);\n\n const currentClient = scope.getClient();\n if (!currentClient) {\n const client = init({ ...wrapperOptions.options, ctx: context });\n scope.setClient(client);\n }\n\n if (!wrapperOptions.spanName) {\n try {\n if (callback) {\n callback(...args);\n }\n const result = Reflect.apply(target, thisArg, args);\n\n if (isThenable(result)) {\n return result.then(\n (res: unknown) => {\n waitUntil?.(flush(2000));\n return res;\n },\n (e: unknown) => {\n captureException(e, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object',\n handled: false,\n },\n });\n waitUntil?.(flush(2000));\n throw e;\n },\n );\n } else {\n waitUntil?.(flush(2000));\n return result;\n }\n } catch (e) {\n captureException(e, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object',\n handled: false,\n },\n });\n waitUntil?.(flush(2000));\n throw e;\n }\n }\n\n const attributes = wrapperOptions.spanOp\n ? {\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: wrapperOptions.spanOp,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.durable_object',\n }\n : {};\n\n return startSpan({ name: wrapperOptions.spanName, attributes }, () => {\n try {\n const result = Reflect.apply(target, thisArg, args);\n\n if (isThenable(result)) {\n return result.then(\n (res: unknown) => {\n waitUntil?.(flush(2000));\n return res;\n },\n (e: unknown) => {\n captureException(e, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object',\n handled: false,\n },\n });\n waitUntil?.(flush(2000));\n throw e;\n },\n );\n } else {\n waitUntil?.(flush(2000));\n return result;\n }\n } catch (e) {\n captureException(e, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object',\n handled: false,\n },\n });\n waitUntil?.(flush(2000));\n throw e;\n }\n });\n };\n\n return sentryWithScope(wrappedFunction);\n },\n });\n}\n\n/**\n * Instruments a Durable Object class to capture errors and performance data.\n *\n * Instruments the following methods:\n * - fetch\n * - alarm\n * - webSocketMessage\n * - webSocketClose\n * - webSocketError\n *\n * as well as any other public RPC methods on the Durable Object instance.\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 = copyExecutionContext(ctx);\n\n const options = getFinalOptions(optionsCallback(env), env);\n\n const obj = new target(context, env);\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' && !isInstrumented(obj.fetch)) {\n obj.fetch = new Proxy(obj.fetch, {\n apply(target, thisArg, args) {\n return wrapRequestHandler({ options, request: args[0], context }, () =>\n Reflect.apply(target, thisArg, args),\n );\n },\n });\n\n markAsInstrumented(obj.fetch);\n }\n\n if (obj.alarm && typeof obj.alarm === 'function') {\n obj.alarm = wrapMethodWithSentry({ options, context, spanName: 'alarm' }, obj.alarm);\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 for (const method of Object.getOwnPropertyNames(obj)) {\n if (\n method === 'fetch' ||\n method === 'alarm' ||\n method === 'webSocketError' ||\n method === 'webSocketClose' ||\n method === 'webSocketMessage'\n ) {\n continue;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n const value = (obj as any)[method] as unknown;\n if (typeof value === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n (obj as any)[method] = wrapMethodWithSentry(\n { options, context, spanName: method, spanOp: 'rpc' },\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n value as (...args: any[]) => any,\n );\n }\n }\n\n // Store context and options on the instance for prototype methods to access\n Object.defineProperty(obj, '__SENTRY_CONTEXT__', {\n value: context,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n\n Object.defineProperty(obj, '__SENTRY_OPTIONS__', {\n value: options,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n\n if (options?.instrumentPrototypeMethods) {\n instrumentPrototype(target, options.instrumentPrototypeMethods);\n }\n\n return obj;\n },\n });\n}\n\nfunction instrumentPrototype<T extends NewableFunction>(target: T, methodsToInstrument: boolean | string[]): void {\n const proto = target.prototype;\n\n // Get all methods from the prototype chain\n const methodNames = new Set<string>();\n let current = proto;\n\n while (current && current !== Object.prototype) {\n Object.getOwnPropertyNames(current).forEach(name => {\n if (name !== 'constructor' && typeof (current as Record<string, unknown>)[name] === 'function') {\n methodNames.add(name);\n }\n });\n current = Object.getPrototypeOf(current);\n }\n\n // Create a set for efficient lookups when methodsToInstrument is an array\n const methodsToInstrumentSet = Array.isArray(methodsToInstrument) ? new Set(methodsToInstrument) : null;\n\n // Instrument each method on the prototype\n methodNames.forEach(methodName => {\n const originalMethod = (proto as Record<string, unknown>)[methodName];\n\n if (!originalMethod || isInstrumented(originalMethod)) {\n return;\n }\n\n // If methodsToInstrument is an array, only instrument methods in that set\n if (methodsToInstrumentSet && !methodsToInstrumentSet.has(methodName)) {\n return;\n }\n\n // Create a wrapper that gets context/options from the instance at runtime\n const wrappedMethod = function (this: any, ...args: any[]): unknown {\n const thisWithSentry = this as {\n __SENTRY_CONTEXT__: DurableObjectState;\n __SENTRY_OPTIONS__: CloudflareOptions;\n };\n const instanceContext = thisWithSentry.__SENTRY_CONTEXT__;\n const instanceOptions = thisWithSentry.__SENTRY_OPTIONS__;\n\n if (!instanceOptions) {\n // Fallback to original method if no Sentry data found\n return (originalMethod as (...args: any[]) => any).apply(this, args);\n }\n\n // Use the existing wrapper but with instance-specific context/options\n const wrapper = wrapMethodWithSentry(\n {\n options: instanceOptions,\n context: instanceContext,\n spanName: methodName,\n spanOp: 'rpc',\n },\n originalMethod as (...args: any[]) => any,\n undefined,\n true, // noMark = true since we'll mark the prototype method\n );\n\n return (wrapper as (...args: any[]) => any).apply(this, args);\n };\n\n markAsInstrumented(wrappedMethod);\n\n // Replace the prototype method\n Object.defineProperty(proto, methodName, {\n value: wrappedMethod,\n enumerable: false,\n writable: true,\n configurable: true,\n });\n });\n}\n"],"names":[],"mappings":";;;;;;;;AAAA;;AAgCA,SAAS,oBAAoB;AAC7B,EAAE,cAAc;AAChB,EAAE,OAAO;AACT,EAAE,QAAQ;AACV,EAAE,MAAM;AACR,EAAK;AACL,EAAE,IAAI,cAAc,CAAC,OAAO,CAAC,EAAE;AAC/B,IAAI,OAAO,OAAO;AAClB;;AAEA,EAAE,IAAI,CAAC,MAAM,EAAE;AACf,IAAI,kBAAkB,CAAC,OAAO,CAAC;AAC/B;;AAEA,EAAE,OAAO,IAAI,KAAK,CAAC,OAAO,EAAE;AAC5B,IAAI,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,EAAiB;AAChD,MAAM,MAAM,aAAA,GAAgB,SAAS,EAAE;AACvC;AACA,MAAM,MAAM,eAAA,GAAkB,gBAAgB,SAAA,GAAY,kBAAkB;;AAE5E,MAAM,MAAM,eAAA,GAAkB,CAAC,KAAK,KAAqB;AACzD;AACA;AACA;AACA,QAAQ,MAAM,OAAA,GAAU,cAAc,CAAC,OAAA;;AAEvC,QAAQ,MAAM,SAAA,GAAY,OAAO,EAAE,SAAS,EAAE,IAAI,GAAG,OAAO,CAAC;;AAE7D,QAAQ,MAAM,aAAA,GAAgB,KAAK,CAAC,SAAS,EAAE;AAC/C,QAAQ,IAAI,CAAC,aAAa,EAAE;AAC5B,UAAU,MAAM,MAAA,GAAS,IAAI,CAAC,EAAE,GAAG,cAAc,CAAC,OAAO,EAAE,GAAG,EAAE,OAAA,EAAS,CAAC;AAC1E,UAAU,KAAK,CAAC,SAAS,C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C5E;;AAEA;AACA,MAAM,MAAM,OAAA,GAAU,oBAAoB;AAC1C,QAAQ;AACR,UAAU,OAAO,EAAE,eAAe;AAClC,UAAU,OAAO,EAAE,eAAe;AAClC,UAAU,QAAQ,EAAE,UAAU;AAC9B,UAAU,MAAM,EAAE,KAAK;AACvB,SAAS;AACT,QAAQ,cAAA;AACR,QAAQ,SAAS;AACjB,QAAQ,IAAI;AACZ,OAAO;;AAEP,MAAM,OAAO,CAAC,OAAA,GAAoC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC;AACnE,KAAK;;AAEL,IAAI,kBAAkB,CAAC,aAAa,CAAC;;AAErC;AACA,IAAI,MAAM,CAAC,cAAc,CAAC,KAAK,EAAE,UAAU,EAAE;AAC7C,MAAM,KAAK,EAAE,aAAa;AAC1B,MAAM,UAAU,EAAE,KAAK;AACvB,MAAM,QAAQ,EAAE,IAAI;AACpB,MAAM,YAAY,EAAE,IAAI;AACxB,KAAK,CAAC;AACN,GAAG,CAAC;AACJ;;;;"}
@@ -6,6 +6,7 @@ import { getFinalOptions } from './options.js';
6
6
  import { wrapRequestHandler } from './request.js';
7
7
  import { addCloudResourceContext } from './scope-utils.js';
8
8
  import { init } from './sdk.js';
9
+ import { copyExecutionContext } from './utils/copyExecutionContext.js';
9
10
 
10
11
  /**
11
12
  * Wrapper for Cloudflare handlers.
@@ -29,7 +30,9 @@ function withSentry(
29
30
  if ('fetch' in handler && typeof handler.fetch === 'function' && !isInstrumented(handler.fetch)) {
30
31
  handler.fetch = new Proxy(handler.fetch, {
31
32
  apply(target, thisArg, args) {
32
- const [request, env, context] = args;
33
+ const [request, env, ctx] = args;
34
+ const context = copyExecutionContext(ctx);
35
+ args[2] = context;
33
36
 
34
37
  const options = getFinalOptions(optionsCallback(env), env);
35
38
 
@@ -63,7 +66,10 @@ function withSentry(
63
66
  if ('scheduled' in handler && typeof handler.scheduled === 'function' && !isInstrumented(handler.scheduled)) {
64
67
  handler.scheduled = new Proxy(handler.scheduled, {
65
68
  apply(target, thisArg, args) {
66
- const [event, env, context] = args;
69
+ const [event, env, ctx] = args;
70
+ const context = copyExecutionContext(ctx);
71
+ args[2] = context;
72
+
67
73
  return withIsolationScope(isolationScope => {
68
74
  const options = getFinalOptions(optionsCallback(env), env);
69
75
  const waitUntil = context.waitUntil.bind(context);
@@ -106,7 +112,10 @@ function withSentry(
106
112
  if ('email' in handler && typeof handler.email === 'function' && !isInstrumented(handler.email)) {
107
113
  handler.email = new Proxy(handler.email, {
108
114
  apply(target, thisArg, args) {
109
- const [emailMessage, env, context] = args;
115
+ const [emailMessage, env, ctx] = args;
116
+ const context = copyExecutionContext(ctx);
117
+ args[2] = context;
118
+
110
119
  return withIsolationScope(isolationScope => {
111
120
  const options = getFinalOptions(optionsCallback(env), env);
112
121
  const waitUntil = context.waitUntil.bind(context);
@@ -147,7 +156,9 @@ function withSentry(
147
156
  if ('queue' in handler && typeof handler.queue === 'function' && !isInstrumented(handler.queue)) {
148
157
  handler.queue = new Proxy(handler.queue, {
149
158
  apply(target, thisArg, args) {
150
- const [batch, env, context] = args;
159
+ const [batch, env, ctx] = args;
160
+ const context = copyExecutionContext(ctx);
161
+ args[2] = context;
151
162
 
152
163
  return withIsolationScope(isolationScope => {
153
164
  const options = getFinalOptions(optionsCallback(env), env);
@@ -197,7 +208,9 @@ function withSentry(
197
208
  if ('tail' in handler && typeof handler.tail === 'function' && !isInstrumented(handler.tail)) {
198
209
  handler.tail = new Proxy(handler.tail, {
199
210
  apply(target, thisArg, args) {
200
- const [, env, context] = args;
211
+ const [, env, ctx] = args;
212
+ const context = copyExecutionContext(ctx);
213
+ args[2] = context;
201
214
 
202
215
  return withIsolationScope(async isolationScope => {
203
216
  const options = getFinalOptions(optionsCallback(env), env);
@@ -1 +1 @@
1
- {"version":3,"file":"handler.js","sources":["../../src/handler.ts"],"sourcesContent":["import {\n captureException,\n flush,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n startSpan,\n withIsolationScope,\n} from '@sentry/core';\nimport { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport type { CloudflareOptions } from './client';\nimport { isInstrumented, markAsInstrumented } from './instrument';\nimport { getHonoIntegration } from './integrations/hono';\nimport { getFinalOptions } from './options';\nimport { wrapRequestHandler } from './request';\nimport { addCloudResourceContext } from './scope-utils';\nimport { init } from './sdk';\n\n/**\n * Wrapper for Cloudflare handlers.\n *\n * Initializes the SDK and wraps the handler with Sentry instrumentation.\n *\n * Automatically instruments the `fetch` method of the handler.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param handler {ExportedHandler} The handler to wrap.\n * @returns The wrapped handler.\n */\n// eslint-disable-next-line complexity\nexport function withSentry<Env = unknown, QueueHandlerMessage = unknown, CfHostMetadata = unknown>(\n optionsCallback: (env: Env) => CloudflareOptions,\n handler: ExportedHandler<Env, QueueHandlerMessage, CfHostMetadata>,\n): ExportedHandler<Env, QueueHandlerMessage, CfHostMetadata> {\n setAsyncLocalStorageAsyncContextStrategy();\n\n try {\n if ('fetch' in handler && typeof handler.fetch === 'function' && !isInstrumented(handler.fetch)) {\n handler.fetch = new Proxy(handler.fetch, {\n apply(target, thisArg, args: Parameters<ExportedHandlerFetchHandler<Env, CfHostMetadata>>) {\n const [request, env, context] = args;\n\n const options = getFinalOptions(optionsCallback(env), env);\n\n return wrapRequestHandler({ options, request, context }, () => target.apply(thisArg, args));\n },\n });\n\n markAsInstrumented(handler.fetch);\n }\n\n /* Hono does not reach the catch block of the fetch handler and captureException needs to be called in the hono errorHandler */\n if (\n 'onError' in handler &&\n 'errorHandler' in handler &&\n typeof handler.errorHandler === 'function' &&\n !isInstrumented(handler.errorHandler)\n ) {\n handler.errorHandler = new Proxy(handler.errorHandler, {\n apply(target, thisArg, args) {\n const [err] = args;\n\n getHonoIntegration()?.handleHonoException(err);\n\n return Reflect.apply(target, thisArg, args);\n },\n });\n\n markAsInstrumented(handler.errorHandler);\n }\n\n if ('scheduled' in handler && typeof handler.scheduled === 'function' && !isInstrumented(handler.scheduled)) {\n handler.scheduled = new Proxy(handler.scheduled, {\n apply(target, thisArg, args: Parameters<ExportedHandlerScheduledHandler<Env>>) {\n const [event, env, context] = args;\n return withIsolationScope(isolationScope => {\n const options = getFinalOptions(optionsCallback(env), env);\n const waitUntil = context.waitUntil.bind(context);\n\n const client = init({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return startSpan(\n {\n op: 'faas.cron',\n name: `Scheduled Cron ${event.cron}`,\n attributes: {\n 'faas.cron': event.cron,\n 'faas.time': new Date(event.scheduledTime).toISOString(),\n 'faas.trigger': 'timer',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.scheduled',\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'task',\n },\n },\n async () => {\n try {\n return await (target.apply(thisArg, args) as ReturnType<typeof target>);\n } catch (e) {\n captureException(e, { mechanism: { handled: false, type: 'auto.faas.cloudflare.scheduled' } });\n throw e;\n } finally {\n waitUntil(flush(2000));\n }\n },\n );\n });\n },\n });\n\n markAsInstrumented(handler.scheduled);\n }\n\n if ('email' in handler && typeof handler.email === 'function' && !isInstrumented(handler.email)) {\n handler.email = new Proxy(handler.email, {\n apply(target, thisArg, args: Parameters<EmailExportedHandler<Env>>) {\n const [emailMessage, env, context] = args;\n return withIsolationScope(isolationScope => {\n const options = getFinalOptions(optionsCallback(env), env);\n const waitUntil = context.waitUntil.bind(context);\n\n const client = init({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return startSpan(\n {\n op: 'faas.email',\n name: `Handle Email ${emailMessage.to}`,\n attributes: {\n 'faas.trigger': 'email',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.email',\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'task',\n },\n },\n async () => {\n try {\n return await (target.apply(thisArg, args) as ReturnType<typeof target>);\n } catch (e) {\n captureException(e, { mechanism: { handled: false, type: 'auto.faas.cloudflare.email' } });\n throw e;\n } finally {\n waitUntil(flush(2000));\n }\n },\n );\n });\n },\n });\n\n markAsInstrumented(handler.email);\n }\n\n if ('queue' in handler && typeof handler.queue === 'function' && !isInstrumented(handler.queue)) {\n handler.queue = new Proxy(handler.queue, {\n apply(target, thisArg, args: Parameters<ExportedHandlerQueueHandler<Env, QueueHandlerMessage>>) {\n const [batch, env, context] = args;\n\n return withIsolationScope(isolationScope => {\n const options = getFinalOptions(optionsCallback(env), env);\n const waitUntil = context.waitUntil.bind(context);\n\n const client = init({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return startSpan(\n {\n op: 'faas.queue',\n name: `process ${batch.queue}`,\n attributes: {\n 'faas.trigger': 'pubsub',\n 'messaging.destination.name': batch.queue,\n 'messaging.system': 'cloudflare',\n 'messaging.batch.message_count': batch.messages.length,\n 'messaging.message.retry.count': batch.messages.reduce(\n (acc, message) => acc + message.attempts - 1,\n 0,\n ),\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'queue.process',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.queue',\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'task',\n },\n },\n async () => {\n try {\n return await (target.apply(thisArg, args) as ReturnType<typeof target>);\n } catch (e) {\n captureException(e, { mechanism: { handled: false, type: 'auto.faas.cloudflare.queue' } });\n throw e;\n } finally {\n waitUntil(flush(2000));\n }\n },\n );\n });\n },\n });\n\n markAsInstrumented(handler.queue);\n }\n\n if ('tail' in handler && typeof handler.tail === 'function' && !isInstrumented(handler.tail)) {\n handler.tail = new Proxy(handler.tail, {\n apply(target, thisArg, args: Parameters<ExportedHandlerTailHandler<Env>>) {\n const [, env, context] = args;\n\n return withIsolationScope(async isolationScope => {\n const options = getFinalOptions(optionsCallback(env), env);\n\n const waitUntil = context.waitUntil.bind(context);\n\n const client = init({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n try {\n return await (target.apply(thisArg, args) as ReturnType<typeof target>);\n } catch (e) {\n captureException(e, { mechanism: { handled: false, type: 'auto.faas.cloudflare.tail' } });\n throw e;\n } finally {\n waitUntil(flush(2000));\n }\n });\n },\n });\n\n markAsInstrumented(handler.tail);\n }\n\n // This is here because Miniflare sometimes cannot get instrumented\n } catch {\n // Do not console anything here, we don't want to spam the console with errors\n }\n\n return handler;\n}\n"],"names":[],"mappings":";;;;;;;;;AAkBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,UAAU;AAC1B,EAAE,eAAe;AACjB,EAAE,OAAO;AACT,EAA6D;AAC7D,EAAE,wCAAwC,EAAE;;AAE5C,EAAE,IAAI;AACN,IAAI,IAAI,OAAA,IAAW,WAAW,OAAO,OAAO,CAAC,KAAA,KAAU,UAAA,IAAc,CAAC,cAAc,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;AACrG,MAAM,OAAO,CAAC,KAAA,GAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE;AAC/C,QAAQ,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,EAAgE;AACnG,UAAU,MAAM,CAAC,OAAO,EAAE,GAAG,EAAE,OAAO,CAAA,GAAI,IAAI;;AAE9C,UAAU,MAAM,OAAA,GAAU,eAAe,CAAC,eAAe,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC;;AAEpE,UAAU,OAAO,kBAAkB,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,OAAA,EAAS,EAAE,MAAM,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;AACrG,SAAS;AACT,OAAO,CAAC;;AAER,MAAM,kBAAkB,CAAC,OAAO,CAAC,KAAK,CAAC;AACv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AA,CAAA;;AAEA,YAAA,MAAA,MAAA,GAAA,IAAA,CAAA,EAAA,GAAA,OAAA,EAAA,GAAA,EAAA,OAAA,EAAA,CAAA;AACA,YAAA,cAAA,CAAA,SAAA,CAAA,MAAA,CAAA;;AAEA,YAAA,uBAAA,CAAA,cAAA,CAAA;;AAEA,YAAA,IAAA;AACA,cAAA,OAAA,OAAA,MAAA,CAAA,KAAA,CAAA,OAAA,EAAA,IAAA,CAAA,EAAA;AACA,aAAA,CAAA,OAAA,CAAA,EAAA;AACA,cAAA,gBAAA,CAAA,CAAA,EAAA,EAAA,SAAA,EAAA,EAAA,OAAA,EAAA,KAAA,EAAA,IAAA,EAAA,2BAAA,EAAA,EAAA,CAAA;AACA,cAAA,MAAA,CAAA;AACA,aAAA,SAAA;AACA,cAAA,SAAA,CAAA,KAAA,CAAA,IAAA,CAAA,CAAA;AACA;AACA,WAAA,CAAA;AACA,SAAA;AACA,OAAA,CAAA;;AAEA,MAAA,kBAAA,CAAA,OAAA,CAAA,IAAA,CAAA;AACA;;AAEA;AACA,GAAA,CAAA,MAAA;AACA;AACA;;AAEA,EAAA,OAAA,OAAA;AACA;;;;"}
1
+ {"version":3,"file":"handler.js","sources":["../../src/handler.ts"],"sourcesContent":["import {\n captureException,\n flush,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n startSpan,\n withIsolationScope,\n} from '@sentry/core';\nimport { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport type { CloudflareOptions } from './client';\nimport { isInstrumented, markAsInstrumented } from './instrument';\nimport { getHonoIntegration } from './integrations/hono';\nimport { getFinalOptions } from './options';\nimport { wrapRequestHandler } from './request';\nimport { addCloudResourceContext } from './scope-utils';\nimport { init } from './sdk';\nimport { copyExecutionContext } from './utils/copyExecutionContext';\n\n/**\n * Wrapper for Cloudflare handlers.\n *\n * Initializes the SDK and wraps the handler with Sentry instrumentation.\n *\n * Automatically instruments the `fetch` method of the handler.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param handler {ExportedHandler} The handler to wrap.\n * @returns The wrapped handler.\n */\n// eslint-disable-next-line complexity\nexport function withSentry<Env = unknown, QueueHandlerMessage = unknown, CfHostMetadata = unknown>(\n optionsCallback: (env: Env) => CloudflareOptions,\n handler: ExportedHandler<Env, QueueHandlerMessage, CfHostMetadata>,\n): ExportedHandler<Env, QueueHandlerMessage, CfHostMetadata> {\n setAsyncLocalStorageAsyncContextStrategy();\n\n try {\n if ('fetch' in handler && typeof handler.fetch === 'function' && !isInstrumented(handler.fetch)) {\n handler.fetch = new Proxy(handler.fetch, {\n apply(target, thisArg, args: Parameters<ExportedHandlerFetchHandler<Env, CfHostMetadata>>) {\n const [request, env, ctx] = args;\n const context = copyExecutionContext(ctx);\n args[2] = context;\n\n const options = getFinalOptions(optionsCallback(env), env);\n\n return wrapRequestHandler({ options, request, context }, () => target.apply(thisArg, args));\n },\n });\n\n markAsInstrumented(handler.fetch);\n }\n\n /* Hono does not reach the catch block of the fetch handler and captureException needs to be called in the hono errorHandler */\n if (\n 'onError' in handler &&\n 'errorHandler' in handler &&\n typeof handler.errorHandler === 'function' &&\n !isInstrumented(handler.errorHandler)\n ) {\n handler.errorHandler = new Proxy(handler.errorHandler, {\n apply(target, thisArg, args) {\n const [err] = args;\n\n getHonoIntegration()?.handleHonoException(err);\n\n return Reflect.apply(target, thisArg, args);\n },\n });\n\n markAsInstrumented(handler.errorHandler);\n }\n\n if ('scheduled' in handler && typeof handler.scheduled === 'function' && !isInstrumented(handler.scheduled)) {\n handler.scheduled = new Proxy(handler.scheduled, {\n apply(target, thisArg, args: Parameters<ExportedHandlerScheduledHandler<Env>>) {\n const [event, env, ctx] = args;\n const context = copyExecutionContext(ctx);\n args[2] = context;\n\n return withIsolationScope(isolationScope => {\n const options = getFinalOptions(optionsCallback(env), env);\n const waitUntil = context.waitUntil.bind(context);\n\n const client = init({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return startSpan(\n {\n op: 'faas.cron',\n name: `Scheduled Cron ${event.cron}`,\n attributes: {\n 'faas.cron': event.cron,\n 'faas.time': new Date(event.scheduledTime).toISOString(),\n 'faas.trigger': 'timer',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.scheduled',\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'task',\n },\n },\n async () => {\n try {\n return await (target.apply(thisArg, args) as ReturnType<typeof target>);\n } catch (e) {\n captureException(e, { mechanism: { handled: false, type: 'auto.faas.cloudflare.scheduled' } });\n throw e;\n } finally {\n waitUntil(flush(2000));\n }\n },\n );\n });\n },\n });\n\n markAsInstrumented(handler.scheduled);\n }\n\n if ('email' in handler && typeof handler.email === 'function' && !isInstrumented(handler.email)) {\n handler.email = new Proxy(handler.email, {\n apply(target, thisArg, args: Parameters<EmailExportedHandler<Env>>) {\n const [emailMessage, env, ctx] = args;\n const context = copyExecutionContext(ctx);\n args[2] = context;\n\n return withIsolationScope(isolationScope => {\n const options = getFinalOptions(optionsCallback(env), env);\n const waitUntil = context.waitUntil.bind(context);\n\n const client = init({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return startSpan(\n {\n op: 'faas.email',\n name: `Handle Email ${emailMessage.to}`,\n attributes: {\n 'faas.trigger': 'email',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.email',\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'task',\n },\n },\n async () => {\n try {\n return await (target.apply(thisArg, args) as ReturnType<typeof target>);\n } catch (e) {\n captureException(e, { mechanism: { handled: false, type: 'auto.faas.cloudflare.email' } });\n throw e;\n } finally {\n waitUntil(flush(2000));\n }\n },\n );\n });\n },\n });\n\n markAsInstrumented(handler.email);\n }\n\n if ('queue' in handler && typeof handler.queue === 'function' && !isInstrumented(handler.queue)) {\n handler.queue = new Proxy(handler.queue, {\n apply(target, thisArg, args: Parameters<ExportedHandlerQueueHandler<Env, QueueHandlerMessage>>) {\n const [batch, env, ctx] = args;\n const context = copyExecutionContext(ctx);\n args[2] = context;\n\n return withIsolationScope(isolationScope => {\n const options = getFinalOptions(optionsCallback(env), env);\n const waitUntil = context.waitUntil.bind(context);\n\n const client = init({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return startSpan(\n {\n op: 'faas.queue',\n name: `process ${batch.queue}`,\n attributes: {\n 'faas.trigger': 'pubsub',\n 'messaging.destination.name': batch.queue,\n 'messaging.system': 'cloudflare',\n 'messaging.batch.message_count': batch.messages.length,\n 'messaging.message.retry.count': batch.messages.reduce(\n (acc, message) => acc + message.attempts - 1,\n 0,\n ),\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'queue.process',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.queue',\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'task',\n },\n },\n async () => {\n try {\n return await (target.apply(thisArg, args) as ReturnType<typeof target>);\n } catch (e) {\n captureException(e, { mechanism: { handled: false, type: 'auto.faas.cloudflare.queue' } });\n throw e;\n } finally {\n waitUntil(flush(2000));\n }\n },\n );\n });\n },\n });\n\n markAsInstrumented(handler.queue);\n }\n\n if ('tail' in handler && typeof handler.tail === 'function' && !isInstrumented(handler.tail)) {\n handler.tail = new Proxy(handler.tail, {\n apply(target, thisArg, args: Parameters<ExportedHandlerTailHandler<Env>>) {\n const [, env, ctx] = args;\n const context = copyExecutionContext(ctx);\n args[2] = context;\n\n return withIsolationScope(async isolationScope => {\n const options = getFinalOptions(optionsCallback(env), env);\n\n const waitUntil = context.waitUntil.bind(context);\n\n const client = init({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n try {\n return await (target.apply(thisArg, args) as ReturnType<typeof target>);\n } catch (e) {\n captureException(e, { mechanism: { handled: false, type: 'auto.faas.cloudflare.tail' } });\n throw e;\n } finally {\n waitUntil(flush(2000));\n }\n });\n },\n });\n\n markAsInstrumented(handler.tail);\n }\n\n // This is here because Miniflare sometimes cannot get instrumented\n } catch {\n // Do not console anything here, we don't want to spam the console with errors\n }\n\n return handler;\n}\n"],"names":[],"mappings":";;;;;;;;;;AAmBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,UAAU;AAC1B,EAAE,eAAe;AACjB,EAAE,OAAO;AACT,EAA6D;AAC7D,EAAE,wCAAwC,EAAE;;AAE5C,EAAE,IAAI;AACN,IAAI,IAAI,OAAA,IAAW,WAAW,OAAO,OAAO,CAAC,KAAA,KAAU,UAAA,IAAc,CAAC,cAAc,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;AACrG,MAAM,OAAO,CAAC,KAAA,GAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE;AAC/C,QAAQ,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,EAAgE;AACnG,UAAU,MAAM,CAAC,OAAO,EAAE,GAAG,EAAE,GAAG,CAAA,GAAI,IAAI;AAC1C,UAAU,MAAM,OAAA,GAAU,oBAAoB,CAAC,GAAG,CAAC;AACnD,UAAU,IAAI,CAAC,CAAC,CAAA,GAAI,OAAO;;AAE3B,UAAU,MAAM,OAAA,GAAU,eAAe,CAAC,eAAe,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC;;AAEpE,UAAU,OAAO,kBAAkB,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,OAAA,EAAS,EAAE,MAAM,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;AACrG,SAAS;AACT,OAAO,CAAC;;AAER,MAAM,kBAAkB,CAAC,OAAO,CAAC,KAAK,CAAC;AACvC;;AAEA;AACA,IAAI;AACJ,MAAM,SAAA,IAAa,OAAA;AAC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IC_ATTRIBUTE_SENTRY_SOURCE, Scope, addBreadcrumb, addEventProcessor, addIntegration, captureCheckIn, captureConsoleIntegration, captureEvent, captureException, captureFeedback, captureMessage, close, consoleIntegration, consoleLoggingIntegration, continueTrace, createConsolaReporter, createTransport, dedupeIntegration, eventFiltersIntegration, extraErrorDataIntegration, featureFlagsIntegration, flush, functionToStringIntegration, getActiveSpan, getClient, getCurrentScope, getGlobalScope, getIsolationScope, getRootSpan, getSpanDescendants, getSpanStatusFromHttpCode, getTraceData, getTraceMetaTags, inboundFiltersIntegration, instrumentAnthropicAiClient, instrumentGoogleGenAIClient, instrumentOpenAiClient, instrumentSupabaseClient, isEnabled, isInitialized, lastEventId, linkedErrorsIntegration, logger, moduleMetadataIntegration, requestDataIntegration, rewriteFramesIntegration, setContext, setCurrentClient, setExtra, setExtras, setHttpStatus, setMeasurement, setTag, setTags, setUser, spanToBaggageHeader, spanToJSON, spanToTraceHeader, startInactiveSpan, startNewTrace, startSpan, startSpanManual, supabaseIntegration, suppressTracing, trpcMiddleware, updateSpanName, withActiveSpan, withIsolationScope, withMonitor, withScope, wrapMcpServerWithSentry, zodErrorsIntegration } from '@sentry/core';
1
+ export { SDK_VERSION, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, Scope, addBreadcrumb, addEventProcessor, addIntegration, captureCheckIn, captureConsoleIntegration, captureEvent, captureException, captureFeedback, captureMessage, close, consoleIntegration, consoleLoggingIntegration, continueTrace, createConsolaReporter, createTransport, dedupeIntegration, eventFiltersIntegration, extraErrorDataIntegration, featureFlagsIntegration, flush, functionToStringIntegration, getActiveSpan, getClient, getCurrentScope, getGlobalScope, getIsolationScope, getRootSpan, getSpanDescendants, getSpanStatusFromHttpCode, getTraceData, getTraceMetaTags, growthbookIntegration, inboundFiltersIntegration, instrumentAnthropicAiClient, instrumentGoogleGenAIClient, instrumentOpenAiClient, instrumentSupabaseClient, isEnabled, isInitialized, lastEventId, linkedErrorsIntegration, logger, moduleMetadataIntegration, requestDataIntegration, rewriteFramesIntegration, setContext, setCurrentClient, setExtra, setExtras, setHttpStatus, setMeasurement, setTag, setTags, setUser, spanToBaggageHeader, spanToJSON, spanToTraceHeader, startInactiveSpan, startNewTrace, startSpan, startSpanManual, supabaseIntegration, suppressTracing, trpcMiddleware, updateSpanName, withActiveSpan, withIsolationScope, withMonitor, withScope, wrapMcpServerWithSentry, zodErrorsIntegration } from '@sentry/core';
2
2
  export { withSentry } from './handler.js';
3
3
  export { instrumentDurableObjectWithSentry } from './durableobject.js';
4
4
  export { sentryPagesPlugin } from './pages-plugin.js';
@@ -1 +1 @@
1
- {"type":"module","version":"10.19.0","sideEffects":false}
1
+ {"type":"module","version":"10.21.0-alpha.0","sideEffects":false}
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Creates a new copy of the given execution context, optionally overriding methods.
3
+ *
4
+ * @param {ContextType|void} ctx - The execution context to be copied. Can be of type `ContextType` or `void`.
5
+ * @return {ContextType|void} A new execution context with the same properties and overridden methods if applicable.
6
+ */
7
+ function copyExecutionContext(ctx) {
8
+ if (!ctx) return ctx;
9
+
10
+ const overrides = new Map();
11
+ const contextPrototype = Object.getPrototypeOf(ctx);
12
+ const prototypeMethodNames = Object.getOwnPropertyNames(contextPrototype) ;
13
+ const ownPropertyNames = Object.getOwnPropertyNames(ctx) ;
14
+ const instrumented = new Set(['constructor']);
15
+ const descriptors = [...ownPropertyNames, ...prototypeMethodNames].reduce((prevDescriptors, methodName) => {
16
+ if (instrumented.has(methodName)) return prevDescriptors;
17
+ if (typeof ctx[methodName] !== 'function') return prevDescriptors;
18
+ instrumented.add(methodName);
19
+ const overridableDescriptor = makeOverridableDescriptor(overrides, ctx, methodName);
20
+ return {
21
+ ...prevDescriptors,
22
+ [methodName]: overridableDescriptor,
23
+ };
24
+ }, {});
25
+
26
+ return Object.create(ctx, descriptors);
27
+ }
28
+
29
+ /**
30
+ * Creates a property descriptor that allows overriding of a method on the given context object.
31
+ *
32
+ * This descriptor supports property overriding with functions only. It delegates method calls to
33
+ * the provided store if an override exists or to the original method on the context otherwise.
34
+ *
35
+ * @param {OverridesStore<ContextType>} store - The storage for overridden methods specific to the context type.
36
+ * @param {ContextType} ctx - The context object that contains the method to be overridden.
37
+ * @param {keyof ContextType} method - The method on the context object to create the overridable descriptor for.
38
+ * @return {PropertyDescriptor} A property descriptor enabling the overriding of the specified method.
39
+ */
40
+ function makeOverridableDescriptor(
41
+ store,
42
+ ctx,
43
+ method,
44
+ ) {
45
+ return {
46
+ configurable: true,
47
+ enumerable: true,
48
+ set: newValue => {
49
+ if (typeof newValue == 'function') {
50
+ store.set(method, newValue);
51
+ return;
52
+ }
53
+ Reflect.set(ctx, method, newValue);
54
+ },
55
+
56
+ get: () => {
57
+ if (store.has(method)) return store.get(method);
58
+ const methodFunction = Reflect.get(ctx, method);
59
+ if (typeof methodFunction !== 'function') return methodFunction;
60
+ // We should do bind() to make sure that the method is bound to the context object - otherwise it will not work
61
+ return methodFunction.bind(ctx);
62
+ },
63
+ };
64
+ }
65
+
66
+ export { copyExecutionContext };
67
+ //# sourceMappingURL=copyExecutionContext.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"copyExecutionContext.js","sources":["../../../src/utils/copyExecutionContext.ts"],"sourcesContent":["import { type DurableObjectState, type ExecutionContext } from '@cloudflare/workers-types';\n\ntype ContextType = ExecutionContext | DurableObjectState;\ntype OverridesStore<T extends ContextType> = Map<keyof T, (...args: unknown[]) => unknown>;\n\n/**\n * Creates a new copy of the given execution context, optionally overriding methods.\n *\n * @param {ContextType|void} ctx - The execution context to be copied. Can be of type `ContextType` or `void`.\n * @return {ContextType|void} A new execution context with the same properties and overridden methods if applicable.\n */\nexport function copyExecutionContext<T extends ContextType>(ctx: T): T {\n if (!ctx) return ctx;\n\n const overrides: OverridesStore<T> = new Map();\n const contextPrototype = Object.getPrototypeOf(ctx);\n const prototypeMethodNames = Object.getOwnPropertyNames(contextPrototype) as unknown as (keyof T)[];\n const ownPropertyNames = Object.getOwnPropertyNames(ctx) as unknown as (keyof T)[];\n const instrumented = new Set<unknown>(['constructor']);\n const descriptors = [...ownPropertyNames, ...prototypeMethodNames].reduce((prevDescriptors, methodName) => {\n if (instrumented.has(methodName)) return prevDescriptors;\n if (typeof ctx[methodName] !== 'function') return prevDescriptors;\n instrumented.add(methodName);\n const overridableDescriptor = makeOverridableDescriptor(overrides, ctx, methodName);\n return {\n ...prevDescriptors,\n [methodName]: overridableDescriptor,\n };\n }, {});\n\n return Object.create(ctx, descriptors);\n}\n\n/**\n * Creates a property descriptor that allows overriding of a method on the given context object.\n *\n * This descriptor supports property overriding with functions only. It delegates method calls to\n * the provided store if an override exists or to the original method on the context otherwise.\n *\n * @param {OverridesStore<ContextType>} store - The storage for overridden methods specific to the context type.\n * @param {ContextType} ctx - The context object that contains the method to be overridden.\n * @param {keyof ContextType} method - The method on the context object to create the overridable descriptor for.\n * @return {PropertyDescriptor} A property descriptor enabling the overriding of the specified method.\n */\nfunction makeOverridableDescriptor<T extends ContextType>(\n store: OverridesStore<T>,\n ctx: T,\n method: keyof T,\n): PropertyDescriptor {\n return {\n configurable: true,\n enumerable: true,\n set: newValue => {\n if (typeof newValue == 'function') {\n store.set(method, newValue);\n return;\n }\n Reflect.set(ctx, method, newValue);\n },\n\n get: () => {\n if (store.has(method)) return store.get(method);\n const methodFunction = Reflect.get(ctx, method);\n if (typeof methodFunction !== 'function') return methodFunction;\n // We should do bind() to make sure that the method is bound to the context object - otherwise it will not work\n return methodFunction.bind(ctx);\n },\n };\n}\n"],"names":[],"mappings":"AAKA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,oBAAoB,CAAwB,GAAG,EAAQ;AACvE,EAAE,IAAI,CAAC,GAAG,EAAE,OAAO,GAAG;;AAEtB,EAAE,MAAM,SAAS,GAAsB,IAAI,GAAG,EAAE;A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AAQ;AACR;AACA,MAAM,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,CAAC;AACxC,KAAK;;AAEL,IAAI,GAAG,EAAE,MAAM;AACf,MAAM,IAAI,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,OAAO,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC;AACrD,MAAM,MAAM,cAAA,GAAiB,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC;AACrD,MAAM,IAAI,OAAO,cAAA,KAAmB,UAAU,EAAE,OAAO,cAAc;AACrE;AACA,MAAM,OAAO,cAAc,CAAC,IAAI,CAAC,GAAG,CAAC;AACrC,KAAK;AACL,GAAG;AACH;;;;"}
@@ -2,6 +2,7 @@ import { withIsolationScope, withScope, flush, getCurrentScope, startSpan, SEMAN
2
2
  import { setAsyncLocalStorageAsyncContextStrategy } from './async.js';
3
3
  import { addCloudResourceContext } from './scope-utils.js';
4
4
  import { init } from './sdk.js';
5
+ import { copyExecutionContext } from './utils/copyExecutionContext.js';
5
6
 
6
7
  const UUID_REGEX = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i;
7
8
 
@@ -128,6 +129,9 @@ function instrumentWorkflowWithSentry
128
129
  return new Proxy(WorkFlowClass, {
129
130
  construct(target, args, newTarget) {
130
131
  const [ctx, env] = args;
132
+ const context = copyExecutionContext(ctx);
133
+ args[0] = context;
134
+
131
135
  const options = optionsCallback(env);
132
136
  const instance = Reflect.construct(target, args, newTarget) ;
133
137
  return new Proxy(instance, {
@@ -150,10 +154,10 @@ function instrumentWorkflowWithSentry
150
154
  return await obj.run.call(
151
155
  obj,
152
156
  event,
153
- new WrappedWorkflowStep(event.instanceId, ctx, options, step),
157
+ new WrappedWorkflowStep(event.instanceId, context, options, step),
154
158
  );
155
159
  } finally {
156
- ctx.waitUntil(flush(2000));
160
+ context.waitUntil(flush(2000));
157
161
  }
158
162
  });
159
163
  });
@@ -1 +1 @@
1
- {"version":3,"file":"workflows.js","sources":["../../src/workflows.ts"],"sourcesContent":["import type { PropagationContext } from '@sentry/core';\nimport {\n captureException,\n flush,\n getCurrentScope,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n startSpan,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type {\n WorkflowEntrypoint,\n WorkflowEvent,\n WorkflowSleepDuration,\n WorkflowStep,\n WorkflowStepConfig,\n WorkflowStepEvent,\n WorkflowTimeoutDuration,\n} from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport type { CloudflareOptions } from './client';\nimport { addCloudResourceContext } from './scope-utils';\nimport { init } from './sdk';\n\nconst UUID_REGEX = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i;\n\n/**\n * Hashes a string to a UUID using SHA-1.\n */\nexport async function deterministicTraceIdFromInstanceId(instanceId: string): Promise<string> {\n const buf = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(instanceId));\n return (\n Array.from(new Uint8Array(buf))\n // We only need the first 16 bytes for the 32 characters\n .slice(0, 16)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('')\n );\n}\n\nasync function propagationContextFromInstanceId(instanceId: string): Promise<PropagationContext> {\n const traceId = UUID_REGEX.test(instanceId)\n ? instanceId.replace(/-/g, '')\n : await deterministicTraceIdFromInstanceId(instanceId);\n\n // Derive sampleRand from last 4 characters of the random UUID\n //\n // We cannot store any state between workflow steps, so we derive the\n // sampleRand from the traceId itself. This ensures that the sampling is\n // consistent across all steps in the same workflow instance.\n const sampleRand = parseInt(traceId.slice(-4), 16) / 0xffff;\n\n return {\n traceId,\n sampleRand,\n };\n}\n\nclass WrappedWorkflowStep implements WorkflowStep {\n public constructor(\n private _instanceId: string,\n private _ctx: ExecutionContext,\n private _options: CloudflareOptions,\n private _step: WorkflowStep,\n ) {}\n\n public async do<T extends Rpc.Serializable<T>>(name: string, callback: () => Promise<T>): Promise<T>;\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n config: WorkflowStepConfig,\n callback: () => Promise<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n configOrCallback: WorkflowStepConfig | (() => Promise<T>),\n maybeCallback?: () => Promise<T>,\n ): Promise<T> {\n // Capture the current scope, so parent span (e.g., a startSpan surrounding step.do) is preserved\n const scopeForStep = getCurrentScope();\n\n const userCallback = (maybeCallback || configOrCallback) as () => Promise<T>;\n const config = typeof configOrCallback === 'function' ? undefined : configOrCallback;\n\n const instrumentedCallback: () => Promise<T> = async () => {\n return startSpan(\n {\n op: 'function.step.do',\n name,\n scope: scopeForStep,\n attributes: {\n 'cloudflare.workflow.timeout': config?.timeout,\n 'cloudflare.workflow.retries.backoff': config?.retries?.backoff,\n 'cloudflare.workflow.retries.delay': config?.retries?.delay,\n 'cloudflare.workflow.retries.limit': config?.retries?.limit,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.workflow',\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'task',\n },\n },\n async span => {\n try {\n const result = await userCallback();\n span.setStatus({ code: 1 });\n return result;\n } catch (error) {\n captureException(error, { mechanism: { handled: true, type: 'auto.faas.cloudflare.workflow' } });\n throw error;\n } finally {\n this._ctx.waitUntil(flush(2000));\n }\n },\n );\n };\n\n return config ? this._step.do(name, config, instrumentedCallback) : this._step.do(name, instrumentedCallback);\n }\n\n public async sleep(name: string, duration: WorkflowSleepDuration): Promise<void> {\n return this._step.sleep(name, duration);\n }\n\n public async sleepUntil(name: string, timestamp: Date | number): Promise<void> {\n return this._step.sleepUntil(name, timestamp);\n }\n\n public async waitForEvent<T extends Rpc.Serializable<T>>(\n name: string,\n options: { type: string; timeout?: WorkflowTimeoutDuration | number },\n ): Promise<WorkflowStepEvent<T>> {\n return this._step.waitForEvent<T>(name, options);\n }\n}\n\n/**\n * Instruments a Cloudflare Workflow class with Sentry.\n *\n * @example\n * ```typescript\n * const InstrumentedWorkflow = instrumentWorkflowWithSentry(\n * (env) => ({ dsn: env.SENTRY_DSN }),\n * MyWorkflowClass\n * );\n *\n * export default InstrumentedWorkflow;\n * ```\n *\n * @param optionsCallback - Function that returns Sentry options to initialize Sentry\n * @param WorkflowClass - The workflow class to instrument\n * @returns Instrumented workflow class with the same interface\n */\nexport function instrumentWorkflowWithSentry<\n E, // Environment type\n P, // Payload type\n T extends WorkflowEntrypoint<E, P>, // WorkflowEntrypoint type\n C extends new (ctx: ExecutionContext, env: E) => T, // Constructor type of the WorkflowEntrypoint class\n>(optionsCallback: (env: E) => CloudflareOptions, WorkFlowClass: C): C {\n return new Proxy(WorkFlowClass, {\n construct(target: C, args: [ctx: ExecutionContext, env: E], newTarget) {\n const [ctx, env] = args;\n const options = optionsCallback(env);\n const instance = Reflect.construct(target, args, newTarget) as T;\n return new Proxy(instance, {\n get(obj, prop, receiver) {\n if (prop === 'run') {\n return async function (event: WorkflowEvent<P>, step: WorkflowStep): Promise<unknown> {\n setAsyncLocalStorageAsyncContextStrategy();\n\n return withIsolationScope(async isolationScope => {\n const client = init({ ...options, enableDedupe: false });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return withScope(async scope => {\n const propagationContext = await propagationContextFromInstanceId(event.instanceId);\n scope.setPropagationContext(propagationContext);\n\n try {\n return await obj.run.call(\n obj,\n event,\n new WrappedWorkflowStep(event.instanceId, ctx, options, step),\n );\n } finally {\n ctx.waitUntil(flush(2000));\n }\n });\n });\n };\n }\n return Reflect.get(obj, prop, receiver);\n },\n });\n },\n });\n}\n"],"names":[],"mappings":";;;;;AAyBA,MAAM,UAAA,GAAa,qEAAqE;;AAExF;AACA;AACA;AACO,eAAe,kCAAkC,CAAC,UAAU,EAA2B;AAC9F,EAAE,MAAM,MAAM,MAAM,MAA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BAAkB,CAAC,MAAM,kBAAkB;AAChE,gBAAgB,MAAM,MAAA,GAAS,IAAI,CAAC,EAAE,GAAG,OAAO,EAAE,YAAY,EAAE,KAAA,EAAO,CAAC;AACxE,gBAAgB,cAAc,CAAC,SAAS,CAAC,MAAM,CAAC;;AAEhD,gBAAgB,uBAAuB,CAAC,cAAc,CAAC;;AAEvD,gBAAgB,OAAO,SAAS,CAAC,MAAM,SAAS;AAChD,kBAAkB,MAAM,qBAAqB,MAAM,gCAAgC,CAAC,KAAK,CAAC,UAAU,CAAC;AACrG,kBAAkB,KAAK,CAAC,qBAAqB,CAAC,kBAAkB,CAAC;;AAEjE,kBAAkB,IAAI;AACtB,oBAAoB,OAAO,MAAM,GAAG,CAAC,GAAG,CAAC,IAAI;AAC7C,sBAAsB,GAAG;AACzB,sBAAsB,KAAK;AAC3B,sBAAsB,IAAI,mBAAmB,CAAC,KAAK,CAAC,UAAU,EAAE,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC;AACnF,qBAAqB;AACrB,4BAA4B;AAC5B,oBAAoB,GAAG,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AAC9C;AACA,iBAAiB,CAAC;AAClB,eAAe,CAAC;AAChB,aAAa;AACb;AACA,UAAU,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,QAAQ,CAAC;AACjD,SAAS;AACT,OAAO,CAAC;AACR,KAAK;AACL,GAAG,CAAC;AACJ;;;;"}
1
+ {"version":3,"file":"workflows.js","sources":["../../src/workflows.ts"],"sourcesContent":["import type { PropagationContext } from '@sentry/core';\nimport {\n captureException,\n flush,\n getCurrentScope,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n startSpan,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type {\n WorkflowEntrypoint,\n WorkflowEvent,\n WorkflowSleepDuration,\n WorkflowStep,\n WorkflowStepConfig,\n WorkflowStepEvent,\n WorkflowTimeoutDuration,\n} from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport type { CloudflareOptions } from './client';\nimport { addCloudResourceContext } from './scope-utils';\nimport { init } from './sdk';\nimport { copyExecutionContext } from './utils/copyExecutionContext';\n\nconst UUID_REGEX = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i;\n\n/**\n * Hashes a string to a UUID using SHA-1.\n */\nexport async function deterministicTraceIdFromInstanceId(instanceId: string): Promise<string> {\n const buf = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(instanceId));\n return (\n Array.from(new Uint8Array(buf))\n // We only need the first 16 bytes for the 32 characters\n .slice(0, 16)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('')\n );\n}\n\nasync function propagationContextFromInstanceId(instanceId: string): Promise<PropagationContext> {\n const traceId = UUID_REGEX.test(instanceId)\n ? instanceId.replace(/-/g, '')\n : await deterministicTraceIdFromInstanceId(instanceId);\n\n // Derive sampleRand from last 4 characters of the random UUID\n //\n // We cannot store any state between workflow steps, so we derive the\n // sampleRand from the traceId itself. This ensures that the sampling is\n // consistent across all steps in the same workflow instance.\n const sampleRand = parseInt(traceId.slice(-4), 16) / 0xffff;\n\n return {\n traceId,\n sampleRand,\n };\n}\n\nclass WrappedWorkflowStep implements WorkflowStep {\n public constructor(\n private _instanceId: string,\n private _ctx: ExecutionContext,\n private _options: CloudflareOptions,\n private _step: WorkflowStep,\n ) {}\n\n public async do<T extends Rpc.Serializable<T>>(name: string, callback: () => Promise<T>): Promise<T>;\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n config: WorkflowStepConfig,\n callback: () => Promise<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n configOrCallback: WorkflowStepConfig | (() => Promise<T>),\n maybeCallback?: () => Promise<T>,\n ): Promise<T> {\n // Capture the current scope, so parent span (e.g., a startSpan surrounding step.do) is preserved\n const scopeForStep = getCurrentScope();\n\n const userCallback = (maybeCallback || configOrCallback) as () => Promise<T>;\n const config = typeof configOrCallback === 'function' ? undefined : configOrCallback;\n\n const instrumentedCallback: () => Promise<T> = async () => {\n return startSpan(\n {\n op: 'function.step.do',\n name,\n scope: scopeForStep,\n attributes: {\n 'cloudflare.workflow.timeout': config?.timeout,\n 'cloudflare.workflow.retries.backoff': config?.retries?.backoff,\n 'cloudflare.workflow.retries.delay': config?.retries?.delay,\n 'cloudflare.workflow.retries.limit': config?.retries?.limit,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.workflow',\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'task',\n },\n },\n async span => {\n try {\n const result = await userCallback();\n span.setStatus({ code: 1 });\n return result;\n } catch (error) {\n captureException(error, { mechanism: { handled: true, type: 'auto.faas.cloudflare.workflow' } });\n throw error;\n } finally {\n this._ctx.waitUntil(flush(2000));\n }\n },\n );\n };\n\n return config ? this._step.do(name, config, instrumentedCallback) : this._step.do(name, instrumentedCallback);\n }\n\n public async sleep(name: string, duration: WorkflowSleepDuration): Promise<void> {\n return this._step.sleep(name, duration);\n }\n\n public async sleepUntil(name: string, timestamp: Date | number): Promise<void> {\n return this._step.sleepUntil(name, timestamp);\n }\n\n public async waitForEvent<T extends Rpc.Serializable<T>>(\n name: string,\n options: { type: string; timeout?: WorkflowTimeoutDuration | number },\n ): Promise<WorkflowStepEvent<T>> {\n return this._step.waitForEvent<T>(name, options);\n }\n}\n\n/**\n * Instruments a Cloudflare Workflow class with Sentry.\n *\n * @example\n * ```typescript\n * const InstrumentedWorkflow = instrumentWorkflowWithSentry(\n * (env) => ({ dsn: env.SENTRY_DSN }),\n * MyWorkflowClass\n * );\n *\n * export default InstrumentedWorkflow;\n * ```\n *\n * @param optionsCallback - Function that returns Sentry options to initialize Sentry\n * @param WorkflowClass - The workflow class to instrument\n * @returns Instrumented workflow class with the same interface\n */\nexport function instrumentWorkflowWithSentry<\n E, // Environment type\n P, // Payload type\n T extends WorkflowEntrypoint<E, P>, // WorkflowEntrypoint type\n C extends new (ctx: ExecutionContext, env: E) => T, // Constructor type of the WorkflowEntrypoint class\n>(optionsCallback: (env: E) => CloudflareOptions, WorkFlowClass: C): C {\n return new Proxy(WorkFlowClass, {\n construct(target: C, args: [ctx: ExecutionContext, env: E], newTarget) {\n const [ctx, env] = args;\n const context = copyExecutionContext(ctx);\n args[0] = context;\n\n const options = optionsCallback(env);\n const instance = Reflect.construct(target, args, newTarget) as T;\n return new Proxy(instance, {\n get(obj, prop, receiver) {\n if (prop === 'run') {\n return async function (event: WorkflowEvent<P>, step: WorkflowStep): Promise<unknown> {\n setAsyncLocalStorageAsyncContextStrategy();\n\n return withIsolationScope(async isolationScope => {\n const client = init({ ...options, enableDedupe: false });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return withScope(async scope => {\n const propagationContext = await propagationContextFromInstanceId(event.instanceId);\n scope.setPropagationContext(propagationContext);\n\n try {\n return await obj.run.call(\n obj,\n event,\n new WrappedWorkflowStep(event.instanceId, context, options, step),\n );\n } finally {\n context.waitUntil(flush(2000));\n }\n });\n });\n };\n }\n return Reflect.get(obj, prop, receiver);\n },\n });\n },\n });\n}\n"],"names":[],"mappings":";;;;;;AA0BA,MAAM,UAAA,GAAa,qEAAqE;;AAExF;AACA;AACA;AACO,eAAe,kCAAkC,CAAC,UAAU,EAA2B;AAC9F,EAAE,MAAM,MAAM,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;AACvF,EAAE;AACF,IAAI,KAAK,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,GAAG,CAAC;AAClC;AACA,OAAO,KAAK,CAAC,CAAC,EAAE,EAAE;AAClB,OAAO,GAAG,CAAC,CAAA,IAAK,CAAC,CAAC,QAAQ,CAA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E,CAAC,GAAG,CAAC,CAyG1E"}
1
+ {"version":3,"file":"durableobject.d.ts","sourceRoot":"","sources":["../../src/durableobject.ts"],"names":[],"mappings":";AAaA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAExD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AA6IlD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,wBAAgB,iCAAiC,CAC/C,CAAC,EACD,CAAC,SAAS,aAAa,CAAC,CAAC,CAAC,EAC1B,CAAC,SAAS,KAAK,KAAK,EAAE,kBAAkB,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,EACtD,eAAe,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,iBAAiB,EAAE,kBAAkB,EAAE,CAAC,GAAG,CAAC,CA0G1E"}
@@ -1 +1 @@
1
- {"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../../src/handler.ts"],"names":[],"mappings":";AAUA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAQlD;;;;;;;;;;GAUG;AAEH,wBAAgB,UAAU,CAAC,GAAG,GAAG,OAAO,EAAE,mBAAmB,GAAG,OAAO,EAAE,cAAc,GAAG,OAAO,EAC/F,eAAe,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,iBAAiB,EAChD,OAAO,EAAE,eAAe,CAAC,GAAG,EAAE,mBAAmB,EAAE,cAAc,CAAC,GACjE,eAAe,CAAC,GAAG,EAAE,mBAAmB,EAAE,cAAc,CAAC,CAgN3D"}
1
+ {"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../../src/handler.ts"],"names":[],"mappings":";AAUA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AASlD;;;;;;;;;;GAUG;AAEH,wBAAgB,UAAU,CAAC,GAAG,GAAG,OAAO,EAAE,mBAAmB,GAAG,OAAO,EAAE,cAAc,GAAG,OAAO,EAC/F,eAAe,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,iBAAiB,EAChD,OAAO,EAAE,eAAe,CAAC,GAAG,EAAE,mBAAmB,EAAE,cAAc,CAAC,GACjE,eAAe,CAAC,GAAG,EAAE,mBAAmB,EAAE,cAAc,CAAC,CA4N3D"}
@@ -1,6 +1,6 @@
1
1
  export type { Breadcrumb, BreadcrumbHint, PolymorphicRequest, RequestEventData, SdkInfo, Event, EventHint, ErrorEvent, Exception, FeatureFlagsIntegration, Session, SeverityLevel, Span, StackFrame, Stacktrace, Thread, User, } from '@sentry/core';
2
2
  export type { CloudflareOptions } from './client';
3
- export { addEventProcessor, addBreadcrumb, addIntegration, captureException, captureEvent, captureMessage, captureFeedback, close, createTransport, lastEventId, flush, getClient, isInitialized, isEnabled, getCurrentScope, getGlobalScope, getIsolationScope, setCurrentClient, Scope, SDK_VERSION, setContext, setExtra, setExtras, setTag, setTags, setUser, getSpanStatusFromHttpCode, setHttpStatus, withScope, withIsolationScope, captureCheckIn, withMonitor, setMeasurement, getActiveSpan, getRootSpan, getTraceData, getTraceMetaTags, startSpan, startInactiveSpan, startSpanManual, startNewTrace, suppressTracing, withActiveSpan, getSpanDescendants, continueTrace, functionToStringIntegration, inboundFiltersIntegration, instrumentOpenAiClient, instrumentGoogleGenAIClient, instrumentAnthropicAiClient, eventFiltersIntegration, linkedErrorsIntegration, requestDataIntegration, extraErrorDataIntegration, dedupeIntegration, rewriteFramesIntegration, captureConsoleIntegration, moduleMetadataIntegration, supabaseIntegration, instrumentSupabaseClient, zodErrorsIntegration, consoleIntegration, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, trpcMiddleware, spanToJSON, spanToTraceHeader, spanToBaggageHeader, updateSpanName, wrapMcpServerWithSentry, consoleLoggingIntegration, createConsolaReporter, featureFlagsIntegration, logger, } from '@sentry/core';
3
+ export { addEventProcessor, addBreadcrumb, addIntegration, captureException, captureEvent, captureMessage, captureFeedback, close, createTransport, lastEventId, flush, getClient, isInitialized, isEnabled, getCurrentScope, getGlobalScope, getIsolationScope, setCurrentClient, Scope, SDK_VERSION, setContext, setExtra, setExtras, setTag, setTags, setUser, getSpanStatusFromHttpCode, setHttpStatus, withScope, withIsolationScope, captureCheckIn, withMonitor, setMeasurement, getActiveSpan, getRootSpan, getTraceData, getTraceMetaTags, startSpan, startInactiveSpan, startSpanManual, startNewTrace, suppressTracing, withActiveSpan, getSpanDescendants, continueTrace, functionToStringIntegration, inboundFiltersIntegration, instrumentOpenAiClient, instrumentGoogleGenAIClient, instrumentAnthropicAiClient, eventFiltersIntegration, linkedErrorsIntegration, requestDataIntegration, extraErrorDataIntegration, dedupeIntegration, rewriteFramesIntegration, captureConsoleIntegration, moduleMetadataIntegration, supabaseIntegration, instrumentSupabaseClient, zodErrorsIntegration, consoleIntegration, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, trpcMiddleware, spanToJSON, spanToTraceHeader, spanToBaggageHeader, updateSpanName, wrapMcpServerWithSentry, consoleLoggingIntegration, createConsolaReporter, featureFlagsIntegration, growthbookIntegration, logger, } from '@sentry/core';
4
4
  export { withSentry } from './handler';
5
5
  export { instrumentDurableObjectWithSentry } from './durableobject';
6
6
  export { sentryPagesPlugin } from './pages-plugin';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,UAAU,EACV,cAAc,EACd,kBAAkB,EAClB,gBAAgB,EAChB,OAAO,EACP,KAAK,EACL,SAAS,EACT,UAAU,EACV,SAAS,EACT,uBAAuB,EACvB,OAAO,EACP,aAAa,EACb,IAAI,EAC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,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAEnD,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAE/C,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAC5C,OAAO,EAAE,sBAAsB,EAAE,MAAM,OAAO,CAAC;AAE/C,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AACtE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD,OAAO,EAAE,sBAAsB,EAAE,MAAM,MAAM,CAAC;AAE9C,OAAO,EAAE,4BAA4B,EAAE,MAAM,aAAa,CAAC;AAE3D,OAAO,EAAE,wCAAwC,EAAE,MAAM,SAAS,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,UAAU,EACV,cAAc,EACd,kBAAkB,EAClB,gBAAgB,EAChB,OAAO,EACP,KAAK,EACL,SAAS,EACT,UAAU,EACV,SAAS,EACT,uBAAuB,EACvB,OAAO,EACP,aAAa,EACb,IAAI,EACJ,UAAU,EACV,UAAU,EACV,MAAM,EACN,IAAI,GACL,MAAM,cAAc,CAAC;AAEtB,YAAY,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAElD,OAAO,EACL,iBAAiB,EACjB,aAAa,EACb,cAAc,EACd,gBAAgB,EAChB,YAAY,EACZ,cAAc,EACd,eAAe,EACf,KAAK,EACL,eAAe,EACf,WAAW,EACX,KAAK,EACL,SAAS,EACT,aAAa,EACb,SAAS,EACT,eAAe,EACf,cAAc,EACd,iBAAiB,EACjB,gBAAgB,EAChB,KAAK,EACL,WAAW,EACX,UAAU,EACV,QAAQ,EACR,SAAS,EACT,MAAM,EACN,OAAO,EACP,OAAO,EACP,yBAAyB,EACzB,aAAa,EACb,SAAS,EACT,kBAAkB,EAClB,cAAc,EACd,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,EAAE,MAAM,SAAS,CAAC"}
@@ -0,0 +1,11 @@
1
+ import { type DurableObjectState, type ExecutionContext } from '@cloudflare/workers-types';
2
+ type ContextType = ExecutionContext | DurableObjectState;
3
+ /**
4
+ * Creates a new copy of the given execution context, optionally overriding methods.
5
+ *
6
+ * @param {ContextType|void} ctx - The execution context to be copied. Can be of type `ContextType` or `void`.
7
+ * @return {ContextType|void} A new execution context with the same properties and overridden methods if applicable.
8
+ */
9
+ export declare function copyExecutionContext<T extends ContextType>(ctx: T): T;
10
+ export {};
11
+ //# sourceMappingURL=copyExecutionContext.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"copyExecutionContext.d.ts","sourceRoot":"","sources":["../../../src/utils/copyExecutionContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,kBAAkB,EAAE,KAAK,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAE3F,KAAK,WAAW,GAAG,gBAAgB,GAAG,kBAAkB,CAAC;AAGzD;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,CAAC,SAAS,WAAW,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAoBrE"}
@@ -1 +1 @@
1
- {"version":3,"file":"workflows.d.ts","sourceRoot":"","sources":["../../src/workflows.ts"],"names":[],"mappings":";AAWA,OAAO,KAAK,EACV,kBAAkB,EAOnB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAMlD;;GAEG;AACH,wBAAsB,kCAAkC,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAS5F;AA8FD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,4BAA4B,CAC1C,CAAC,EAAE,mBAAmB;AACtB,CAAC,EAAE,eAAe;AAClB,CAAC,SAAS,kBAAkB,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,0BAA0B;AAC9D,CAAC,SAAS,KAAK,GAAG,EAAE,gBAAgB,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,EAClD,eAAe,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,iBAAiB,EAAE,aAAa,EAAE,CAAC,GAAG,CAAC,CAwCrE"}
1
+ {"version":3,"file":"workflows.d.ts","sourceRoot":"","sources":["../../src/workflows.ts"],"names":[],"mappings":";AAWA,OAAO,KAAK,EACV,kBAAkB,EAOnB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAOlD;;GAEG;AACH,wBAAsB,kCAAkC,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAS5F;AA8FD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,4BAA4B,CAC1C,CAAC,EAAE,mBAAmB;AACtB,CAAC,EAAE,eAAe;AAClB,CAAC,SAAS,kBAAkB,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,0BAA0B;AAC9D,CAAC,SAAS,KAAK,GAAG,EAAE,gBAAgB,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,EAClD,eAAe,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,iBAAiB,EAAE,aAAa,EAAE,CAAC,GAAG,CAAC,CA2CrE"}
@@ -1,6 +1,6 @@
1
1
  export { Breadcrumb, BreadcrumbHint, PolymorphicRequest, RequestEventData, SdkInfo, Event, EventHint, ErrorEvent, Exception, FeatureFlagsIntegration, Session, SeverityLevel, Span, StackFrame, Stacktrace, Thread, User, } from '@sentry/core';
2
2
  export { CloudflareOptions } from './client';
3
- export { addEventProcessor, addBreadcrumb, addIntegration, captureException, captureEvent, captureMessage, captureFeedback, close, createTransport, lastEventId, flush, getClient, isInitialized, isEnabled, getCurrentScope, getGlobalScope, getIsolationScope, setCurrentClient, Scope, SDK_VERSION, setContext, setExtra, setExtras, setTag, setTags, setUser, getSpanStatusFromHttpCode, setHttpStatus, withScope, withIsolationScope, captureCheckIn, withMonitor, setMeasurement, getActiveSpan, getRootSpan, getTraceData, getTraceMetaTags, startSpan, startInactiveSpan, startSpanManual, startNewTrace, suppressTracing, withActiveSpan, getSpanDescendants, continueTrace, functionToStringIntegration, inboundFiltersIntegration, instrumentOpenAiClient, instrumentGoogleGenAIClient, instrumentAnthropicAiClient, eventFiltersIntegration, linkedErrorsIntegration, requestDataIntegration, extraErrorDataIntegration, dedupeIntegration, rewriteFramesIntegration, captureConsoleIntegration, moduleMetadataIntegration, supabaseIntegration, instrumentSupabaseClient, zodErrorsIntegration, consoleIntegration, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, trpcMiddleware, spanToJSON, spanToTraceHeader, spanToBaggageHeader, updateSpanName, wrapMcpServerWithSentry, consoleLoggingIntegration, createConsolaReporter, featureFlagsIntegration, logger, } from '@sentry/core';
3
+ export { addEventProcessor, addBreadcrumb, addIntegration, captureException, captureEvent, captureMessage, captureFeedback, close, createTransport, lastEventId, flush, getClient, isInitialized, isEnabled, getCurrentScope, getGlobalScope, getIsolationScope, setCurrentClient, Scope, SDK_VERSION, setContext, setExtra, setExtras, setTag, setTags, setUser, getSpanStatusFromHttpCode, setHttpStatus, withScope, withIsolationScope, captureCheckIn, withMonitor, setMeasurement, getActiveSpan, getRootSpan, getTraceData, getTraceMetaTags, startSpan, startInactiveSpan, startSpanManual, startNewTrace, suppressTracing, withActiveSpan, getSpanDescendants, continueTrace, functionToStringIntegration, inboundFiltersIntegration, instrumentOpenAiClient, instrumentGoogleGenAIClient, instrumentAnthropicAiClient, eventFiltersIntegration, linkedErrorsIntegration, requestDataIntegration, extraErrorDataIntegration, dedupeIntegration, rewriteFramesIntegration, captureConsoleIntegration, moduleMetadataIntegration, supabaseIntegration, instrumentSupabaseClient, zodErrorsIntegration, consoleIntegration, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, trpcMiddleware, spanToJSON, spanToTraceHeader, spanToBaggageHeader, updateSpanName, wrapMcpServerWithSentry, consoleLoggingIntegration, createConsolaReporter, featureFlagsIntegration, growthbookIntegration, logger, } from '@sentry/core';
4
4
  export { withSentry } from './handler';
5
5
  export { instrumentDurableObjectWithSentry } from './durableobject';
6
6
  export { sentryPagesPlugin } from './pages-plugin';
@@ -0,0 +1,11 @@
1
+ import { DurableObjectState, ExecutionContext } from '@cloudflare/workers-types';
2
+ type ContextType = ExecutionContext | DurableObjectState;
3
+ /**
4
+ * Creates a new copy of the given execution context, optionally overriding methods.
5
+ *
6
+ * @param {ContextType|void} ctx - The execution context to be copied. Can be of type `ContextType` or `void`.
7
+ * @return {ContextType|void} A new execution context with the same properties and overridden methods if applicable.
8
+ */
9
+ export declare function copyExecutionContext<T extends ContextType>(ctx: T): T;
10
+ export {};
11
+ //# sourceMappingURL=copyExecutionContext.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sentry/cloudflare",
3
- "version": "10.19.0",
3
+ "version": "10.21.0-alpha.0",
4
4
  "description": "Official Sentry SDK for Cloudflare Workers and Pages",
5
5
  "repository": "git://github.com/getsentry/sentry-javascript.git",
6
6
  "homepage": "https://github.com/getsentry/sentry-javascript/tree/master/packages/cloudflare",
@@ -50,7 +50,7 @@
50
50
  },
51
51
  "dependencies": {
52
52
  "@opentelemetry/api": "^1.9.0",
53
- "@sentry/core": "10.19.0"
53
+ "@sentry/core": "10.21.0-alpha.0"
54
54
  },
55
55
  "peerDependencies": {
56
56
  "@cloudflare/workers-types": "^4.x"