@sentry/cloudflare 11.13.0 → 11.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/build/cjs/dev/baseSdk.js.map +1 -1
  2. package/build/cjs/dev/client.js +17 -2
  3. package/build/cjs/dev/client.js.map +1 -1
  4. package/build/cjs/dev/durableobject.js.map +1 -1
  5. package/build/cjs/dev/options.js +1 -0
  6. package/build/cjs/dev/options.js.map +1 -1
  7. package/build/cjs/dev/orchestrion-deferred-channels.js +6 -2
  8. package/build/cjs/dev/orchestrion-deferred-channels.js.map +1 -1
  9. package/build/cjs/dev/vite/autoInstrument.js +5 -1
  10. package/build/cjs/dev/vite/autoInstrument.js.map +1 -1
  11. package/build/cjs/dev/vite/index.js.map +1 -1
  12. package/build/cjs/dev/vite/transform.js +12 -13
  13. package/build/cjs/dev/vite/transform.js.map +1 -1
  14. package/build/cjs/dev/vite/wranglerConfig.js +2 -0
  15. package/build/cjs/dev/vite/wranglerConfig.js.map +1 -1
  16. package/build/cjs/prod/baseSdk.js.map +1 -1
  17. package/build/cjs/prod/client.js +17 -2
  18. package/build/cjs/prod/client.js.map +1 -1
  19. package/build/cjs/prod/durableobject.js.map +1 -1
  20. package/build/cjs/prod/options.js +1 -0
  21. package/build/cjs/prod/options.js.map +1 -1
  22. package/build/cjs/prod/orchestrion-deferred-channels.js +6 -2
  23. package/build/cjs/prod/orchestrion-deferred-channels.js.map +1 -1
  24. package/build/cjs/prod/vite/autoInstrument.js +5 -1
  25. package/build/cjs/prod/vite/autoInstrument.js.map +1 -1
  26. package/build/cjs/prod/vite/index.js.map +1 -1
  27. package/build/cjs/prod/vite/transform.js +12 -13
  28. package/build/cjs/prod/vite/transform.js.map +1 -1
  29. package/build/cjs/prod/vite/wranglerConfig.js +2 -0
  30. package/build/cjs/prod/vite/wranglerConfig.js.map +1 -1
  31. package/build/esm/dev/baseSdk.js.map +1 -1
  32. package/build/esm/dev/client.js +18 -3
  33. package/build/esm/dev/client.js.map +1 -1
  34. package/build/esm/dev/durableobject.js.map +1 -1
  35. package/build/esm/dev/options.js +1 -0
  36. package/build/esm/dev/options.js.map +1 -1
  37. package/build/esm/dev/orchestrion-deferred-channels.js +7 -3
  38. package/build/esm/dev/orchestrion-deferred-channels.js.map +1 -1
  39. package/build/esm/dev/package.json +1 -1
  40. package/build/esm/dev/vite/autoInstrument.js +5 -1
  41. package/build/esm/dev/vite/autoInstrument.js.map +1 -1
  42. package/build/esm/dev/vite/index.js.map +1 -1
  43. package/build/esm/dev/vite/transform.js +12 -13
  44. package/build/esm/dev/vite/transform.js.map +1 -1
  45. package/build/esm/dev/vite/wranglerConfig.js +2 -0
  46. package/build/esm/dev/vite/wranglerConfig.js.map +1 -1
  47. package/build/esm/prod/baseSdk.js.map +1 -1
  48. package/build/esm/prod/client.js +18 -3
  49. package/build/esm/prod/client.js.map +1 -1
  50. package/build/esm/prod/durableobject.js.map +1 -1
  51. package/build/esm/prod/options.js +1 -0
  52. package/build/esm/prod/options.js.map +1 -1
  53. package/build/esm/prod/orchestrion-deferred-channels.js +7 -3
  54. package/build/esm/prod/orchestrion-deferred-channels.js.map +1 -1
  55. package/build/esm/prod/package.json +1 -1
  56. package/build/esm/prod/vite/autoInstrument.js +5 -1
  57. package/build/esm/prod/vite/autoInstrument.js.map +1 -1
  58. package/build/esm/prod/vite/index.js.map +1 -1
  59. package/build/esm/prod/vite/transform.js +12 -13
  60. package/build/esm/prod/vite/transform.js.map +1 -1
  61. package/build/esm/prod/vite/wranglerConfig.js +2 -0
  62. package/build/esm/prod/vite/wranglerConfig.js.map +1 -1
  63. package/build/types/baseSdk.d.ts.map +1 -1
  64. package/build/types/client.d.ts +8 -0
  65. package/build/types/client.d.ts.map +1 -1
  66. package/build/types/durableobject.d.ts.map +1 -1
  67. package/build/types/options.d.ts.map +1 -1
  68. package/build/types/orchestrion-deferred-channels.d.ts.map +1 -1
  69. package/build/types/vite/autoInstrument.d.ts.map +1 -1
  70. package/build/types/vite/index.d.ts +3 -0
  71. package/build/types/vite/index.d.ts.map +1 -1
  72. package/build/types/vite/transform.d.ts +12 -2
  73. package/build/types/vite/transform.d.ts.map +1 -1
  74. package/build/types/vite/wranglerConfig.d.ts +8 -0
  75. package/build/types/vite/wranglerConfig.d.ts.map +1 -1
  76. package/package.json +5 -5
@@ -1 +1 @@
1
- {"version":3,"file":"durableobject.js","names":["setAsyncLocalStorageAsyncContextStrategyForWorker","getFinalOptions","instrumentContext","instrumentEnv","withConstructionIsolationScope","init","flushDeferredChannelEvents","instrumentDurableObjectHandlers","getInstrumented","markAsInstrumented","wrapMethodWithSentry","RPC","hasRpcMeta","getIsolationScope","getDefaultIsolationScope","isObjectLike","startNewTrace","instrumentCloudflareAgent"],"sources":["../../../src/durableobject.ts"],"sourcesContent":["/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/unbound-method */\nimport { RPC } from '@sentry/conventions/op';\nimport { getDefaultIsolationScope, getIsolationScope, isObjectLike, startNewTrace } from '@sentry/core';\nimport type { DurableObject } from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategyForWorker } from './utils/asyncContextStrategy';\nimport type { CloudflareOptions } from './client';\nimport { getInstrumented, markAsInstrumented } from './instrument';\nimport { instrumentDurableObjectHandlers } from './instrumentations/instrumentDurableObjectHandlers';\nimport { instrumentEnv } from './instrumentations/worker/instrumentEnv';\nimport { getFinalOptions } from './options';\nimport { flushDeferredChannelEvents } from './orchestrion-deferred-channels';\nimport { init } from './sdk';\nimport { instrumentContext } from './utils/instrumentContext';\nimport { withConstructionIsolationScope } from './utils/invocationScope';\nimport { hasRpcMeta } from './utils/rpcMeta';\nimport { instrumentCloudflareAgent } from './instrumentations/agents';\nimport type { DefaultEnv, ResolveEnv, StrictCloudflareOptions } from './types';\nimport { type UncheckedMethod, wrapMethodWithSentry } from './wrapMethodWithSentry';\n\n/**\n * The instrumented context passed between the shared construction helpers.\n *\n * This is intentionally `any` rather than `ReturnType<typeof instrumentContext<DurableObjectState>>`.\n * A concrete `DurableObjectState` here forces `tsc` to structurally relate its `storage: SqlStorage`\n * graph against the `ExecutionContext | InstrumentedDurableObjectState` parameter of\n * `wrapMethodWithSentry`, while the RPC-branded `DurableObject` from `cloudflare:workers` is also in\n * scope. That union comparison explodes (1296×1296) and hangs the type build. The original inline\n * implementation avoided this only incidentally, because `ctx` reached it as `any` through the Proxy\n * `construct` trap. Keeping the shared context `any` preserves that behavior.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InstrumentedDurableObjectContext = any;\n\n/**\n * Constructs a Durable Object instance and instruments its built-in handler methods\n * (`fetch`, `alarm`, `webSocketMessage`, `webSocketClose`, `webSocketError`).\n *\n * This is the shared construction path used by both {@link instrumentDurableObjectWithSentry}\n * and {@link instrumentAgentWithSentry}. It intentionally does NOT apply the RPC prototype-method\n * instrumentation — callers apply that last via {@link finalizeWithRpcInstrumentation}, after any\n * additional per-instance instrumentation has been layered onto the returned object.\n *\n * @internal\n */\nexport function constructInstrumentedDurableObject<E, T extends DurableObject<E>>(\n target: new (state: DurableObjectState, env: E) => T,\n ctx: DurableObjectState,\n env: E,\n newTarget: NewableFunction,\n optionsCallback: (env: E) => CloudflareOptions,\n): {\n obj: T;\n options: CloudflareOptions;\n context: InstrumentedDurableObjectContext;\n frameworkManagedMethods: ReadonlySet<string>;\n} {\n setAsyncLocalStorageAsyncContextStrategyForWorker();\n const options = getFinalOptions(optionsCallback(env), env);\n // See InstrumentedDurableObjectContext — `ctx` is widened to `any` so the concrete\n // `DurableObjectState` type never enters the checker's relation graph in this module.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const context = instrumentContext(ctx as any);\n const instrumentedEnv = instrumentEnv(env as Record<string, unknown>, options);\n\n const prototype = (newTarget as unknown as { prototype?: object }).prototype ?? target.prototype;\n const cachedFrameworkManagedMethods = frameworkManagedMethodsCache.get(prototype);\n const methodsBeforeConstruction = cachedFrameworkManagedMethods\n ? undefined\n : resolveMethodsBeforeFirstConstruction(prototype);\n\n // Pass `newTarget` so that subclasses of the instrumented class (e.g. the wrapper classes\n // created by wrangler's local dev tooling or `@cloudflare/vitest-pool-workers`) keep their\n // own prototype — otherwise subclass methods disappear and `instanceof` checks break.\n const obj = withConstructionIsolationScope(() => {\n // The constructor can already use instrumented libraries, e.g. open a pi-durable Harness in\n // `blockConcurrencyWhile`. Their channel integrations only subscribe in `init()`, and an isolate\n // that runs only this Durable Object has no earlier handler that called it. A per-invocation\n // client (`cacheClient: false`) would have no invocation to flush it, so it waits for one.\n if (options.cacheClient !== false) {\n init({ ...options });\n flushDeferredChannelEvents();\n }\n return Reflect.construct(target, [context, instrumentedEnv], newTarget) as T;\n });\n\n const frameworkManagedMethods = resolveFrameworkManagedMethods(\n prototype,\n obj,\n methodsBeforeConstruction,\n cachedFrameworkManagedMethods,\n );\n\n instrumentDurableObjectHandlers(obj, options, context);\n\n return { obj, options, context, frameworkManagedMethods };\n}\n\nconst frameworkManagedMethodsCache = new WeakMap<object, ReadonlySet<string>>();\nconst methodsBeforeFirstConstructionCache = new WeakMap<object, Map<string, unknown>>();\n\n/**\n * Collects the prototype's methods as they were before any instance was constructed.\n *\n * A constructor can throw after a framework has already installed its wrappers (the `agents` SDK\n * wraps `@callable()` methods before storage initialization, which can fail). The next construction\n * would then see those wrappers as the originals and treat the methods as unmanaged, so the methods\n * collected on the first attempt are kept until a construction succeeds.\n */\nfunction resolveMethodsBeforeFirstConstruction(prototype: object): Map<string, unknown> {\n let methods = methodsBeforeFirstConstructionCache.get(prototype);\n\n if (!methods) {\n methods = resolvePrototypeMethods(prototype);\n methodsBeforeFirstConstructionCache.set(prototype, methods);\n }\n\n return methods;\n}\n\n/**\n * Collects the methods visible from a prototype, using normal property lookup precedence.\n * Methods inherited from `Object.prototype` are excluded because they cannot be Durable Object RPC methods.\n */\nfunction resolvePrototypeMethods(prototype: object | null): Map<string, unknown> {\n const methods = new Map<string, unknown>();\n\n for (let current = prototype; current && current !== Object.prototype; current = Object.getPrototypeOf(current)) {\n for (const name of Object.getOwnPropertyNames(current)) {\n // The first occurrence wins, mirroring what a property lookup on the instance would find\n if (name === 'constructor' || methods.has(name)) {\n continue;\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(current, name);\n\n if (descriptor && typeof descriptor.value === 'function') {\n methods.set(name, descriptor.value);\n }\n }\n }\n\n return methods;\n}\n\n/**\n * Finds methods that a framework replaced while constructing the first instance.\n *\n * Some frameworks register methods by function identity, so replacing one of their wrappers would\n * break dispatch. The result is cached because frameworks commonly install their wrappers only\n * once; later constructions would no longer reveal which methods they manage.\n */\nfunction resolveFrameworkManagedMethods(\n prototype: object,\n obj: object,\n methodsBeforeConstruction: Map<string, unknown> | undefined,\n cached: ReadonlySet<string> | undefined,\n): ReadonlySet<string> {\n if (cached) {\n return cached;\n }\n\n const methodsAfterConstruction = resolvePrototypeMethods(Object.getPrototypeOf(obj) as object);\n const managed = new Set<string>();\n\n for (const [name, method] of methodsAfterConstruction) {\n const before = methodsBeforeConstruction?.get(name);\n\n if (before && before !== method) {\n managed.add(name);\n }\n }\n\n frameworkManagedMethodsCache.set(prototype, managed);\n methodsBeforeFirstConstructionCache.delete(prototype);\n\n return managed;\n}\n\ntype RpcInstanceState = {\n options: CloudflareOptions;\n context: InstrumentedDurableObjectContext;\n /** Per-instance cache of the instrumented method wrappers, keyed by method name. Created on first use. */\n instrumentedMethods?: Map<string, UncheckedMethod>;\n};\n\n/**\n * Method names the runtime never dispatches over RPC, so wrapping them buys no tracing.\n *\n * Mirrors `isReservedName` in workerd (`src/workerd/api/worker-rpc.c++`): the runtime rejects these\n * before any property lookup happens. `fetch`, `alarm` and the `webSocket*` handlers are also\n * instrumented per-instance as own properties, and `constructor` is on every prototype.\n */\nconst RESERVED_RPC_METHOD_NAMES: ReadonlySet<string> = new Set([\n 'constructor',\n 'fetch',\n 'connect',\n 'alarm',\n 'webSocketMessage',\n 'webSocketClose',\n 'webSocketError',\n 'dup',\n]);\n\n// Prototype wrappers are shared by all instances, while SDK options and traced method caches are not.\nconst rpcInstanceStates = new WeakMap<object, RpcInstanceState>();\n\n/**\n * Instruments a constructed Durable Object's RPC methods.\n *\n * RPC methods are wrapped on the prototype because Cloudflare dispatches them with the Durable\n * Object instance as the receiver. This preserves native private-field access and keeps the methods\n * visible to Cloudflare's RPC dispatcher. Built-in handlers, Agent handlers, and methods managed by\n * another framework are left untouched.\n *\n * Call this after all per-instance instrumentation has been applied.\n *\n * @param obj The constructed Durable Object instance.\n * @param options The resolved SDK options for this instance.\n * @param context The instrumented execution context for this instance.\n * @param excludedMethods Method names owned by another framework and therefore not safe to wrap.\n * @returns The same Durable Object instance, with eligible prototype methods instrumented.\n * @internal\n */\nexport function finalizeWithRpcInstrumentation<T extends object>(\n obj: T,\n options: CloudflareOptions,\n context: InstrumentedDurableObjectContext,\n excludedMethods?: ReadonlySet<string>,\n): T {\n rpcInstanceStates.set(obj, { options, context });\n\n instrumentPrototypeRpcMethods(obj, excludedMethods);\n\n return obj;\n}\n\n/**\n * Returns a prototype method when it is eligible for RPC instrumentation.\n */\nfunction getRpcMethodDescriptor(\n obj: object,\n prototype: object,\n methodName: string,\n excludedMethods?: ReadonlySet<string>,\n): PropertyDescriptor | undefined {\n if (\n RESERVED_RPC_METHOD_NAMES.has(methodName) ||\n Object.prototype.hasOwnProperty.call(obj, methodName) ||\n excludedMethods?.has(methodName)\n ) {\n return undefined;\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(prototype, methodName);\n\n if (!descriptor || typeof descriptor.value !== 'function' || getInstrumented(descriptor.value)) {\n return undefined;\n }\n\n return descriptor;\n}\n\n/**\n * Wraps eligible methods on the instance's prototype chain once per class.\n */\nfunction instrumentPrototypeRpcMethods(obj: object, excludedMethods?: ReadonlySet<string>): void {\n let prototype: object | null = Object.getPrototypeOf(obj);\n\n while (prototype && prototype !== Object.prototype) {\n for (const methodName of Object.getOwnPropertyNames(prototype)) {\n const descriptor = getRpcMethodDescriptor(obj, prototype, methodName, excludedMethods);\n\n if (!descriptor) {\n continue;\n }\n\n const wrapped = createRpcPrototypeWrapper(methodName, descriptor.value as UncheckedMethod);\n\n try {\n Object.defineProperty(prototype, methodName, { ...descriptor, value: wrapped });\n } catch {}\n\n // Only the wrapper is marked, not the original method: `wrapMethodWithSentry` resolves\n // through the same global map and must not resolve the original to this wrapper,\n // which would recurse.\n markAsInstrumented(wrapped);\n }\n\n prototype = Object.getPrototypeOf(prototype);\n }\n}\n\n/**\n * Returns the instance's instrumented wrapper for an RPC method, creating it on first use.\n */\nfunction getInstrumentedRpcMethod(\n state: RpcInstanceState,\n methodName: string,\n originalMethod: UncheckedMethod,\n): UncheckedMethod {\n const instrumentedMethods = (state.instrumentedMethods ??= new Map());\n let instrumented = instrumentedMethods.get(methodName);\n\n if (!instrumented) {\n instrumented = wrapMethodWithSentry(\n {\n options: state.options,\n context: state.context,\n spanName: rpcMeta => (rpcMeta ? methodName : undefined),\n spanOp: RPC,\n origin: 'auto.faas.cloudflare.durable_object',\n },\n originalMethod,\n undefined,\n true,\n );\n instrumentedMethods.set(methodName, instrumented);\n }\n\n return instrumented;\n}\n\n/**\n * Creates a prototype wrapper that instruments external RPC calls.\n *\n * The wrapper looks up SDK state from its receiver, allowing one prototype function to serve every\n * instance. A call carrying Sentry metadata continues that trace in an `rpc` span. A call without it\n * still gets a client, so its errors, logs and metrics are captured, but no span. Calls the instance\n * makes to its own methods run the original method directly. The original function name and arity\n * are preserved because frameworks may inspect them for dispatch.\n */\nfunction createRpcPrototypeWrapper(methodName: string, originalMethod: UncheckedMethod): UncheckedMethod {\n const wrapper = function (this: unknown, ...args: unknown[]): unknown {\n const traced = hasRpcMeta(args);\n\n // workerd dispatches an incoming RPC call outside any async context, so a call made on any other\n // isolation scope comes from the instance itself (`this.helper()` inside `fetch`, `alarm`,\n // another RPC method or async work the constructor started). Check that before touching\n // per-instance state.\n if (!traced && getIsolationScope() !== getDefaultIsolationScope()) {\n return Reflect.apply(originalMethod, this, args);\n }\n\n const state = isObjectLike(this) ? rpcInstanceStates.get(this) : undefined;\n\n if (!state) {\n return Reflect.apply(originalMethod, this, args);\n }\n\n const instrumented = getInstrumentedRpcMethod(state, methodName, originalMethod);\n\n if (traced) {\n return Reflect.apply(instrumented, this, args);\n }\n\n // Unlike a WorkerEntrypoint, a Durable Object instance is long-lived and serves overlapping\n // calls. Without a new trace, every untraced call would share the trace of the default scope.\n return startNewTrace(() => Reflect.apply(instrumented, this, args));\n };\n\n Object.defineProperties(wrapper, {\n name: { value: originalMethod.name, configurable: true },\n length: { value: originalMethod.length, configurable: true },\n });\n\n return wrapper as UncheckedMethod;\n}\n\n/**\n * Instruments a Durable Object class to capture errors and performance data.\n *\n * Instruments the following methods by default:\n * - fetch\n * - alarm\n * - webSocketMessage\n * - webSocketClose\n * - webSocketError\n *\n * RPC methods (prototype methods) are instrumented too: an incoming trace continues into them, and\n * errors, logs and metrics are captured whether or not the caller propagates a trace.\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 Env = DefaultEnv,\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends DurableObject<any> = DurableObject<Env>,\n // oxlint-disable-next-line typescript/no-explicit-any\n C extends new (state: DurableObjectState, env: any) => T = new (state: DurableObjectState, env: any) => T,\n O = unknown,\n>(optionsCallback: (env: ResolveEnv<C, Env>) => StrictCloudflareOptions<O>, DurableObjectClass: C): C {\n const InstrumentedClass = new Proxy(DurableObjectClass, {\n construct(target, [ctx, env], newTarget) {\n const { obj, options, context, frameworkManagedMethods } = constructInstrumentedDurableObject(\n target,\n ctx,\n env,\n newTarget,\n optionsCallback,\n );\n\n return finalizeWithRpcInstrumentation(obj, options, context, frameworkManagedMethods);\n },\n });\n // Recognizable for `_INTERNAL_wrapUnlessInstrumented`, so auto-instrumentation never nests wrappers.\n markAsInstrumented(InstrumentedClass);\n return InstrumentedClass;\n}\n\n/**\n * Instruments a Cloudflare [`agents`](https://www.npmjs.com/package/agents) Agent class with Sentry.\n *\n * An `Agent` is a Durable Object under the hood, so this applies the same instrumentation as\n * {@link instrumentDurableObjectWithSentry} (request transactions, `alarm`, WebSocket handlers, RPC\n * trace propagation, SQL spans) and additionally captures Agent-specific telemetry via\n * `instrumentCloudflareAgent`:\n *\n * - **Callable RPC spans** — a span (op `rpc`) for each `@callable()` method invoked over WebSocket.\n * - **Breadcrumbs** — for every Agent observability event (`rpc`, `state:update`, `connect`,\n * `disconnect`, `schedule:*`, `queue:*`, `workflow:*`, `email:*`, `mcp:*`, ...).\n *\n * Cloudflare Workers cannot auto-instrument, so the Agent class must be wrapped manually.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param AgentClass The Agent class to instrument.\n * @returns The instrumented Agent class.\n *\n * @example\n * ```ts\n * import { Agent, callable, routeAgentRequest } from 'agents';\n * import * as Sentry from '@sentry/cloudflare';\n *\n * class MyAgentBase extends Agent<Env> {\n * @callable()\n * async greet(name: string): Promise<string> {\n * return `Hello, ${name}!`;\n * }\n * }\n *\n * export const MyAgent = Sentry.instrumentAgentWithSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * }),\n * MyAgentBase,\n * );\n * ```\n */\nexport function instrumentAgentWithSentry<\n Env = DefaultEnv,\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends DurableObject<any> = DurableObject<Env>,\n // oxlint-disable-next-line typescript/no-explicit-any\n C extends new (state: DurableObjectState, env: any) => T = new (state: DurableObjectState, env: any) => T,\n O = unknown,\n>(optionsCallback: (env: ResolveEnv<C, Env>) => StrictCloudflareOptions<O>, AgentClass: C): C {\n const InstrumentedClass = new Proxy(AgentClass, {\n construct(target, [ctx, env], newTarget) {\n const { obj, options, context, frameworkManagedMethods } = constructInstrumentedDurableObject(\n target,\n ctx,\n env,\n newTarget,\n optionsCallback,\n );\n\n instrumentCloudflareAgent(obj);\n\n // Apply RPC prototype-method instrumentation last, so the Agent-specific own-property\n // handlers we just installed are excluded from RPC method tracing. Methods the Agent\n // framework installed itself are excluded too — `instrumentCloudflareAgent` traces those by\n // wrapping the dispatch instead of the method.\n return finalizeWithRpcInstrumentation(obj, options, context, frameworkManagedMethods);\n },\n });\n markAsInstrumented(InstrumentedClass);\n return InstrumentedClass;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,mCACd,QACA,KACA,KACA,WACA,iBAMA;CACAA,6BAAAA,kDAAkD;CAClD,MAAM,UAAUC,gBAAAA,gBAAgB,gBAAgB,GAAG,GAAG,GAAG;CAIzD,MAAM,UAAUC,0BAAAA,kBAAkB,GAAU;CAC5C,MAAM,kBAAkBC,sBAAAA,cAAc,KAAgC,OAAO;CAE7E,MAAM,YAAa,UAAgD,aAAa,OAAO;CACvF,MAAM,gCAAgC,6BAA6B,IAAI,SAAS;CAChF,MAAM,4BAA4B,gCAC9B,KAAA,IACA,sCAAsC,SAAS;CAKnD,MAAM,MAAMC,wBAAAA,qCAAqC;EAK/C,IAAI,QAAQ,gBAAgB,OAAO;GACjCC,YAAAA,KAAK,EAAE,GAAG,QAAQ,CAAC;GACnBC,sCAAAA,2BAA2B;EAC7B;EACA,OAAO,QAAQ,UAAU,QAAQ,CAAC,SAAS,eAAe,GAAG,SAAS;CACxE,CAAC;CAED,MAAM,0BAA0B,+BAC9B,WACA,KACA,2BACA,6BACF;CAEAC,wCAAAA,gCAAgC,KAAK,SAAS,OAAO;CAErD,OAAO;EAAE;EAAK;EAAS;EAAS;CAAwB;AAC1D;AAEA,MAAM,+CAA+B,IAAI,QA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W;EACvC,MAAM,EAAE,KAAK,SAAS,SAAS,4BAA4B,mCACzD,QACA,KACA,KACA,WACA,eACF;EAEAQ,cAAAA,0BAA0B,GAAG;EAM7B,OAAO,+BAA+B,KAAK,SAAS,SAAS,uBAAuB;CACtF,EACF,CAAC;CACDR,mBAAAA,mBAAmB,iBAAiB;CACpC,OAAO;AACT"}
1
+ {"version":3,"file":"durableobject.js","names":["setAsyncLocalStorageAsyncContextStrategyForWorker","getFinalOptions","instrumentContext","instrumentEnv","withConstructionIsolationScope","init","flushDeferredChannelEvents","instrumentDurableObjectHandlers","getInstrumented","markAsInstrumented","wrapMethodWithSentry","RPC","hasRpcMeta","getIsolationScope","getDefaultIsolationScope","isObjectLike","startNewTrace","instrumentCloudflareAgent"],"sources":["../../../src/durableobject.ts"],"sourcesContent":["/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/unbound-method */\nimport { RPC } from '@sentry/conventions/op';\nimport { getDefaultIsolationScope, getIsolationScope, isObjectLike, startNewTrace } from '@sentry/core';\nimport type { DurableObject } from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategyForWorker } from './utils/asyncContextStrategy';\nimport type { CloudflareOptions } from './client';\nimport { getInstrumented, markAsInstrumented } from './instrument';\nimport { instrumentDurableObjectHandlers } from './instrumentations/instrumentDurableObjectHandlers';\nimport { instrumentEnv } from './instrumentations/worker/instrumentEnv';\nimport { getFinalOptions } from './options';\nimport { flushDeferredChannelEvents } from './orchestrion-deferred-channels';\nimport { init } from './sdk';\nimport { instrumentContext } from './utils/instrumentContext';\nimport { withConstructionIsolationScope } from './utils/invocationScope';\nimport { hasRpcMeta } from './utils/rpcMeta';\nimport { instrumentCloudflareAgent } from './instrumentations/agents';\nimport type { DefaultEnv, ResolveEnv, StrictCloudflareOptions } from './types';\nimport { type UncheckedMethod, wrapMethodWithSentry } from './wrapMethodWithSentry';\n\n/**\n * The instrumented context passed between the shared construction helpers.\n *\n * This is intentionally `any` rather than `ReturnType<typeof instrumentContext<DurableObjectState>>`.\n * A concrete `DurableObjectState` here forces `tsc` to structurally relate its `storage: SqlStorage`\n * graph against the `ExecutionContext | InstrumentedDurableObjectState` parameter of\n * `wrapMethodWithSentry`, while the RPC-branded `DurableObject` from `cloudflare:workers` is also in\n * scope. That union comparison explodes (1296×1296) and hangs the type build. The original inline\n * implementation avoided this only incidentally, because `ctx` reached it as `any` through the Proxy\n * `construct` trap. Keeping the shared context `any` preserves that behavior.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InstrumentedDurableObjectContext = any;\n\n/**\n * Constructs a Durable Object instance and instruments its built-in handler methods\n * (`fetch`, `alarm`, `webSocketMessage`, `webSocketClose`, `webSocketError`).\n *\n * This is the shared construction path used by both {@link instrumentDurableObjectWithSentry}\n * and {@link instrumentAgentWithSentry}. It intentionally does NOT apply the RPC prototype-method\n * instrumentation — callers apply that last via {@link finalizeWithRpcInstrumentation}, after any\n * additional per-instance instrumentation has been layered onto the returned object.\n *\n * @internal\n */\nexport function constructInstrumentedDurableObject<E, T extends DurableObject<E>>(\n target: new (state: DurableObjectState, env: E) => T,\n ctx: DurableObjectState,\n env: E,\n newTarget: NewableFunction,\n optionsCallback: (env: E) => CloudflareOptions,\n): {\n obj: T;\n options: CloudflareOptions;\n context: InstrumentedDurableObjectContext;\n frameworkManagedMethods: ReadonlySet<string>;\n} {\n setAsyncLocalStorageAsyncContextStrategyForWorker();\n const options = getFinalOptions(optionsCallback(env), env);\n // See InstrumentedDurableObjectContext — `ctx` is widened to `any` so the concrete\n // `DurableObjectState` type never enters the checker's relation graph in this module.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const context = instrumentContext(ctx as any);\n const instrumentedEnv = instrumentEnv(env as Record<string, unknown>, options);\n\n const prototype = (newTarget as unknown as { prototype?: object }).prototype ?? target.prototype;\n const cachedFrameworkManagedMethods = frameworkManagedMethodsCache.get(prototype);\n const methodsBeforeConstruction = cachedFrameworkManagedMethods\n ? undefined\n : resolveMethodsBeforeFirstConstruction(prototype);\n\n // Pass `newTarget` so that subclasses of the instrumented class (e.g. the wrapper classes\n // created by wrangler's local dev tooling or `@cloudflare/vitest-pool-workers`) keep their\n // own prototype — otherwise subclass methods disappear and `instanceof` checks break.\n const obj = withConstructionIsolationScope(() => {\n // The constructor can already use instrumented libraries, e.g. open a pi-durable Harness in\n // `blockConcurrencyWhile`. Their channel integrations only subscribe in `init()`, and an isolate\n // that runs only this Durable Object has no earlier handler that called it. A per-invocation\n // client (`cacheClient: false`) would have no invocation to flush it, so it waits for one.\n // oxlint-disable-next-line typescript/no-deprecated\n if (options.cacheClient !== false) {\n init({ ...options });\n flushDeferredChannelEvents();\n }\n return Reflect.construct(target, [context, instrumentedEnv], newTarget) as T;\n });\n\n const frameworkManagedMethods = resolveFrameworkManagedMethods(\n prototype,\n obj,\n methodsBeforeConstruction,\n cachedFrameworkManagedMethods,\n );\n\n instrumentDurableObjectHandlers(obj, options, context);\n\n return { obj, options, context, frameworkManagedMethods };\n}\n\nconst frameworkManagedMethodsCache = new WeakMap<object, ReadonlySet<string>>();\nconst methodsBeforeFirstConstructionCache = new WeakMap<object, Map<string, unknown>>();\n\n/**\n * Collects the prototype's methods as they were before any instance was constructed.\n *\n * A constructor can throw after a framework has already installed its wrappers (the `agents` SDK\n * wraps `@callable()` methods before storage initialization, which can fail). The next construction\n * would then see those wrappers as the originals and treat the methods as unmanaged, so the methods\n * collected on the first attempt are kept until a construction succeeds.\n */\nfunction resolveMethodsBeforeFirstConstruction(prototype: object): Map<string, unknown> {\n let methods = methodsBeforeFirstConstructionCache.get(prototype);\n\n if (!methods) {\n methods = resolvePrototypeMethods(prototype);\n methodsBeforeFirstConstructionCache.set(prototype, methods);\n }\n\n return methods;\n}\n\n/**\n * Collects the methods visible from a prototype, using normal property lookup precedence.\n * Methods inherited from `Object.prototype` are excluded because they cannot be Durable Object RPC methods.\n */\nfunction resolvePrototypeMethods(prototype: object | null): Map<string, unknown> {\n const methods = new Map<string, unknown>();\n\n for (let current = prototype; current && current !== Object.prototype; current = Object.getPrototypeOf(current)) {\n for (const name of Object.getOwnPropertyNames(current)) {\n // The first occurrence wins, mirroring what a property lookup on the instance would find\n if (name === 'constructor' || methods.has(name)) {\n continue;\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(current, name);\n\n if (descriptor && typeof descriptor.value === 'function') {\n methods.set(name, descriptor.value);\n }\n }\n }\n\n return methods;\n}\n\n/**\n * Finds methods that a framework replaced while constructing the first instance.\n *\n * Some frameworks register methods by function identity, so replacing one of their wrappers would\n * break dispatch. The result is cached because frameworks commonly install their wrappers only\n * once; later constructions would no longer reveal which methods they manage.\n */\nfunction resolveFrameworkManagedMethods(\n prototype: object,\n obj: object,\n methodsBeforeConstruction: Map<string, unknown> | undefined,\n cached: ReadonlySet<string> | undefined,\n): ReadonlySet<string> {\n if (cached) {\n return cached;\n }\n\n const methodsAfterConstruction = resolvePrototypeMethods(Object.getPrototypeOf(obj) as object);\n const managed = new Set<string>();\n\n for (const [name, method] of methodsAfterConstruction) {\n const before = methodsBeforeConstruction?.get(name);\n\n if (before && before !== method) {\n managed.add(name);\n }\n }\n\n frameworkManagedMethodsCache.set(prototype, managed);\n methodsBeforeFirstConstructionCache.delete(prototype);\n\n return managed;\n}\n\ntype RpcInstanceState = {\n options: CloudflareOptions;\n context: InstrumentedDurableObjectContext;\n /** Per-instance cache of the instrumented method wrappers, keyed by method name. Created on first use. */\n instrumentedMethods?: Map<string, UncheckedMethod>;\n};\n\n/**\n * Method names the runtime never dispatches over RPC, so wrapping them buys no tracing.\n *\n * Mirrors `isReservedName` in workerd (`src/workerd/api/worker-rpc.c++`): the runtime rejects these\n * before any property lookup happens. `fetch`, `alarm` and the `webSocket*` handlers are also\n * instrumented per-instance as own properties, and `constructor` is on every prototype.\n */\nconst RESERVED_RPC_METHOD_NAMES: ReadonlySet<string> = new Set([\n 'constructor',\n 'fetch',\n 'connect',\n 'alarm',\n 'webSocketMessage',\n 'webSocketClose',\n 'webSocketError',\n 'dup',\n]);\n\n// Prototype wrappers are shared by all instances, while SDK options and traced method caches are not.\nconst rpcInstanceStates = new WeakMap<object, RpcInstanceState>();\n\n/**\n * Instruments a constructed Durable Object's RPC methods.\n *\n * RPC methods are wrapped on the prototype because Cloudflare dispatches them with the Durable\n * Object instance as the receiver. This preserves native private-field access and keeps the methods\n * visible to Cloudflare's RPC dispatcher. Built-in handlers, Agent handlers, and methods managed by\n * another framework are left untouched.\n *\n * Call this after all per-instance instrumentation has been applied.\n *\n * @param obj The constructed Durable Object instance.\n * @param options The resolved SDK options for this instance.\n * @param context The instrumented execution context for this instance.\n * @param excludedMethods Method names owned by another framework and therefore not safe to wrap.\n * @returns The same Durable Object instance, with eligible prototype methods instrumented.\n * @internal\n */\nexport function finalizeWithRpcInstrumentation<T extends object>(\n obj: T,\n options: CloudflareOptions,\n context: InstrumentedDurableObjectContext,\n excludedMethods?: ReadonlySet<string>,\n): T {\n rpcInstanceStates.set(obj, { options, context });\n\n instrumentPrototypeRpcMethods(obj, excludedMethods);\n\n return obj;\n}\n\n/**\n * Returns a prototype method when it is eligible for RPC instrumentation.\n */\nfunction getRpcMethodDescriptor(\n obj: object,\n prototype: object,\n methodName: string,\n excludedMethods?: ReadonlySet<string>,\n): PropertyDescriptor | undefined {\n if (\n RESERVED_RPC_METHOD_NAMES.has(methodName) ||\n Object.prototype.hasOwnProperty.call(obj, methodName) ||\n excludedMethods?.has(methodName)\n ) {\n return undefined;\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(prototype, methodName);\n\n if (!descriptor || typeof descriptor.value !== 'function' || getInstrumented(descriptor.value)) {\n return undefined;\n }\n\n return descriptor;\n}\n\n/**\n * Wraps eligible methods on the instance's prototype chain once per class.\n */\nfunction instrumentPrototypeRpcMethods(obj: object, excludedMethods?: ReadonlySet<string>): void {\n let prototype: object | null = Object.getPrototypeOf(obj);\n\n while (prototype && prototype !== Object.prototype) {\n for (const methodName of Object.getOwnPropertyNames(prototype)) {\n const descriptor = getRpcMethodDescriptor(obj, prototype, methodName, excludedMethods);\n\n if (!descriptor) {\n continue;\n }\n\n const wrapped = createRpcPrototypeWrapper(methodName, descriptor.value as UncheckedMethod);\n\n try {\n Object.defineProperty(prototype, methodName, { ...descriptor, value: wrapped });\n } catch {}\n\n // Only the wrapper is marked, not the original method: `wrapMethodWithSentry` resolves\n // through the same global map and must not resolve the original to this wrapper,\n // which would recurse.\n markAsInstrumented(wrapped);\n }\n\n prototype = Object.getPrototypeOf(prototype);\n }\n}\n\n/**\n * Returns the instance's instrumented wrapper for an RPC method, creating it on first use.\n */\nfunction getInstrumentedRpcMethod(\n state: RpcInstanceState,\n methodName: string,\n originalMethod: UncheckedMethod,\n): UncheckedMethod {\n const instrumentedMethods = (state.instrumentedMethods ??= new Map());\n let instrumented = instrumentedMethods.get(methodName);\n\n if (!instrumented) {\n instrumented = wrapMethodWithSentry(\n {\n options: state.options,\n context: state.context,\n spanName: rpcMeta => (rpcMeta ? methodName : undefined),\n spanOp: RPC,\n origin: 'auto.faas.cloudflare.durable_object',\n },\n originalMethod,\n undefined,\n true,\n );\n instrumentedMethods.set(methodName, instrumented);\n }\n\n return instrumented;\n}\n\n/**\n * Creates a prototype wrapper that instruments external RPC calls.\n *\n * The wrapper looks up SDK state from its receiver, allowing one prototype function to serve every\n * instance. A call carrying Sentry metadata continues that trace in an `rpc` span. A call without it\n * still gets a client, so its errors, logs and metrics are captured, but no span. Calls the instance\n * makes to its own methods run the original method directly. The original function name and arity\n * are preserved because frameworks may inspect them for dispatch.\n */\nfunction createRpcPrototypeWrapper(methodName: string, originalMethod: UncheckedMethod): UncheckedMethod {\n const wrapper = function (this: unknown, ...args: unknown[]): unknown {\n const traced = hasRpcMeta(args);\n\n // workerd dispatches an incoming RPC call outside any async context, so a call made on any other\n // isolation scope comes from the instance itself (`this.helper()` inside `fetch`, `alarm`,\n // another RPC method or async work the constructor started). Check that before touching\n // per-instance state.\n if (!traced && getIsolationScope() !== getDefaultIsolationScope()) {\n return Reflect.apply(originalMethod, this, args);\n }\n\n const state = isObjectLike(this) ? rpcInstanceStates.get(this) : undefined;\n\n if (!state) {\n return Reflect.apply(originalMethod, this, args);\n }\n\n const instrumented = getInstrumentedRpcMethod(state, methodName, originalMethod);\n\n if (traced) {\n return Reflect.apply(instrumented, this, args);\n }\n\n // Unlike a WorkerEntrypoint, a Durable Object instance is long-lived and serves overlapping\n // calls. Without a new trace, every untraced call would share the trace of the default scope.\n return startNewTrace(() => Reflect.apply(instrumented, this, args));\n };\n\n Object.defineProperties(wrapper, {\n name: { value: originalMethod.name, configurable: true },\n length: { value: originalMethod.length, configurable: true },\n });\n\n return wrapper as UncheckedMethod;\n}\n\n/**\n * Instruments a Durable Object class to capture errors and performance data.\n *\n * Instruments the following methods by default:\n * - fetch\n * - alarm\n * - webSocketMessage\n * - webSocketClose\n * - webSocketError\n *\n * RPC methods (prototype methods) are instrumented too: an incoming trace continues into them, and\n * errors, logs and metrics are captured whether or not the caller propagates a trace.\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 Env = DefaultEnv,\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends DurableObject<any> = DurableObject<Env>,\n // oxlint-disable-next-line typescript/no-explicit-any\n C extends new (state: DurableObjectState, env: any) => T = new (state: DurableObjectState, env: any) => T,\n O = unknown,\n>(optionsCallback: (env: ResolveEnv<C, Env>) => StrictCloudflareOptions<O>, DurableObjectClass: C): C {\n const InstrumentedClass = new Proxy(DurableObjectClass, {\n construct(target, [ctx, env], newTarget) {\n const { obj, options, context, frameworkManagedMethods } = constructInstrumentedDurableObject(\n target,\n ctx,\n env,\n newTarget,\n optionsCallback,\n );\n\n return finalizeWithRpcInstrumentation(obj, options, context, frameworkManagedMethods);\n },\n });\n // Recognizable for `_INTERNAL_wrapUnlessInstrumented`, so auto-instrumentation never nests wrappers.\n markAsInstrumented(InstrumentedClass);\n return InstrumentedClass;\n}\n\n/**\n * Instruments a Cloudflare [`agents`](https://www.npmjs.com/package/agents) Agent class with Sentry.\n *\n * An `Agent` is a Durable Object under the hood, so this applies the same instrumentation as\n * {@link instrumentDurableObjectWithSentry} (request transactions, `alarm`, WebSocket handlers, RPC\n * trace propagation, SQL spans) and additionally captures Agent-specific telemetry via\n * `instrumentCloudflareAgent`:\n *\n * - **Callable RPC spans** — a span (op `rpc`) for each `@callable()` method invoked over WebSocket.\n * - **Breadcrumbs** — for every Agent observability event (`rpc`, `state:update`, `connect`,\n * `disconnect`, `schedule:*`, `queue:*`, `workflow:*`, `email:*`, `mcp:*`, ...).\n *\n * Cloudflare Workers cannot auto-instrument, so the Agent class must be wrapped manually.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param AgentClass The Agent class to instrument.\n * @returns The instrumented Agent class.\n *\n * @example\n * ```ts\n * import { Agent, callable, routeAgentRequest } from 'agents';\n * import * as Sentry from '@sentry/cloudflare';\n *\n * class MyAgentBase extends Agent<Env> {\n * @callable()\n * async greet(name: string): Promise<string> {\n * return `Hello, ${name}!`;\n * }\n * }\n *\n * export const MyAgent = Sentry.instrumentAgentWithSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * }),\n * MyAgentBase,\n * );\n * ```\n */\nexport function instrumentAgentWithSentry<\n Env = DefaultEnv,\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends DurableObject<any> = DurableObject<Env>,\n // oxlint-disable-next-line typescript/no-explicit-any\n C extends new (state: DurableObjectState, env: any) => T = new (state: DurableObjectState, env: any) => T,\n O = unknown,\n>(optionsCallback: (env: ResolveEnv<C, Env>) => StrictCloudflareOptions<O>, AgentClass: C): C {\n const InstrumentedClass = new Proxy(AgentClass, {\n construct(target, [ctx, env], newTarget) {\n const { obj, options, context, frameworkManagedMethods } = constructInstrumentedDurableObject(\n target,\n ctx,\n env,\n newTarget,\n optionsCallback,\n );\n\n instrumentCloudflareAgent(obj);\n\n // Apply RPC prototype-method instrumentation last, so the Agent-specific own-property\n // handlers we just installed are excluded from RPC method tracing. Methods the Agent\n // framework installed itself are excluded too — `instrumentCloudflareAgent` traces those by\n // wrapping the dispatch instead of the method.\n return finalizeWithRpcInstrumentation(obj, options, context, frameworkManagedMethods);\n },\n });\n markAsInstrumented(InstrumentedClass);\n return InstrumentedClass;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,mCACd,QACA,KACA,KACA,WACA,iBAMA;CACAA,6BAAAA,kDAAkD;CAClD,MAAM,UAAUC,gBAAAA,gBAAgB,gBAAgB,GAAG,GAAG,GAAG;CAIzD,MAAM,UAAUC,0BAAAA,kBAAkB,GAAU;CAC5C,MAAM,kBAAkBC,sBAAAA,cAAc,KAAgC,OAAO;CAE7E,MAAM,YAAa,UAAgD,aAAa,OAAO;CACvF,MAAM,gCAAgC,6BAA6B,IAAI,SAAS;CAChF,MAAM,4BAA4B,gCAC9B,KAAA,IACA,sCAAsC,SAAS;CAKnD,MAAM,MAAMC,wBAAAA,qCAAqC;EAM/C,IAAI,QAAQ,gBAAgB,OAAO;GACjCC,YAAAA,KAAK,EAAE,GAAG,QAAQ,CAAC;GACnBC,sCAAAA,2BAA2B;EAC7B;EACA,OAAO,QAAQ,UAAU,QAAQ,CAAC,SAAS,eAAe,GAAG,SAAS;CACxE,CAAC;CAED,MAAM,0BAA0B,+BAC9B,WACA,KACA,2BACA,6BACF;CAEAC,wCAAAA,gCAAgC,KAAK,SAAS,OAAO;CAErD,OAAO;EAAE;EAAK;EAAS;EAAS;CAAwB;AAC1D;AAEA,MA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AAC,KAAK,MAAM,WAAW;EACvC,MAAM,EAAE,KAAK,SAAS,SAAS,4BAA4B,mCACzD,QACA,KACA,KACA,WACA,eACF;EAEAQ,cAAAA,0BAA0B,GAAG;EAM7B,OAAO,+BAA+B,KAAK,SAAS,SAAS,uBAAuB;CACtF,EACF,CAAC;CACDR,mBAAAA,mBAAmB,iBAAiB;CACpC,OAAO;AACT"}
@@ -32,6 +32,7 @@ function getFinalOptions(userOptions = {}, env) {
32
32
  ...userOptions,
33
33
  dsn: userOptions.dsn ?? getEnvVar(env, "SENTRY_DSN"),
34
34
  environment: userOptions.environment ?? getEnvVar(env, "SENTRY_ENVIRONMENT"),
35
+ serverName: userOptions.serverName ?? getEnvVar(env, "SENTRY_NAME"),
35
36
  tracesSampleRate: isFinite(tracesSampleRate) ? tracesSampleRate : void 0,
36
37
  debug: userOptions.debug ?? (0, _sentry_core.envToBool)(getEnvVar(env, "SENTRY_DEBUG")),
37
38
  tunnel: userOptions.tunnel ?? getEnvVar(env, "SENTRY_TUNNEL"),
@@ -1 +1 @@
1
- {"version":3,"file":"options.js","names":["isObjectLike","envToBool"],"sources":["../../../src/options.ts"],"sourcesContent":["import { isObjectLike, envToBool } from '@sentry/core';\nimport type { CloudflareOptions } from './client';\n\n/**\n * Cloudflare's version metadata binding structure.\n * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/version-metadata/\n */\ninterface CfVersionMetadata {\n id: string;\n tag?: string;\n timestamp?: string;\n}\n\n/**\n * Checks if the value is a valid CF_VERSION_METADATA binding.\n */\nfunction isVersionMetadata(value: unknown): value is CfVersionMetadata {\n return isObjectLike(value) && 'id' in value && typeof value.id === 'string';\n}\n\nfunction getEnvVar<T extends Record<string, unknown>>(env: unknown, varName: keyof T): string | undefined {\n return isObjectLike(env) && varName in env && typeof (env as T)[varName] === 'string'\n ? ((env as T)[varName] as string)\n : undefined;\n}\n\n/**\n * Merges the options passed in from the user with the options we read from\n * the Cloudflare `env` environment variable object.\n *\n * Release is determined with the following priority (highest to lowest):\n * 1. User-provided release option\n * 2. SENTRY_RELEASE environment variable\n * 3. CF_VERSION_METADATA.id binding (if configured in the wrangler config)\n *\n * @param userOptions - The options passed in from the user.\n * @param env - The environment variables.\n *\n * @returns The final options.\n */\nexport function getFinalOptions(userOptions: CloudflareOptions = {}, env: unknown): CloudflareOptions {\n if (!isObjectLike(env)) {\n return userOptions;\n }\n\n // Priority: userOptions.release > SENTRY_RELEASE > CF_VERSION_METADATA.id\n const release =\n 'SENTRY_RELEASE' in env && typeof env.SENTRY_RELEASE === 'string'\n ? env.SENTRY_RELEASE\n : 'CF_VERSION_METADATA' in env && isVersionMetadata(env.CF_VERSION_METADATA)\n ? env.CF_VERSION_METADATA.id\n : undefined;\n\n const tracesSampleRate =\n userOptions.tracesSampleRate ?? parseFloat(getEnvVar(env, 'SENTRY_TRACES_SAMPLE_RATE') ?? '');\n\n // Spotlight precedence (mirrors node-core's getSpotlightConfig):\n // - false or explicit string from options: use as-is\n // - true: enable, but prefer a custom URL from the env var if set\n // - undefined: defer entirely to the env var (bool or URL)\n /*! rollup-include-development-only */\n const spotlight = getSpotlightFromEnv(userOptions.spotlight, getEnvVar(env, 'SENTRY_SPOTLIGHT'));\n /*! rollup-include-development-only-end */\n\n return {\n release,\n ...userOptions,\n dsn: userOptions.dsn ?? getEnvVar(env, 'SENTRY_DSN'),\n environment: userOptions.environment ?? getEnvVar(env, 'SENTRY_ENVIRONMENT'),\n tracesSampleRate: isFinite(tracesSampleRate) ? tracesSampleRate : undefined,\n debug: userOptions.debug ?? envToBool(getEnvVar(env, 'SENTRY_DEBUG')),\n tunnel: userOptions.tunnel ?? getEnvVar(env, 'SENTRY_TUNNEL'),\n traceLifecycle: userOptions.traceLifecycle ?? getTraceLifecycleFromEnv(getEnvVar(env, 'SENTRY_TRACE_LIFECYCLE')),\n /*! rollup-include-development-only */\n spotlight,\n /*! rollup-include-development-only-end */\n };\n}\n\n/**\n * Resolve the spotlight option from a user-supplied value and an env binding string.\n * Mirrors node-core's `getSpotlightConfig` precedence:\n * - `false` or explicit string from options → use as-is\n * - `true` → enable, but prefer a custom URL from the env var if set\n * - `undefined` → defer entirely to the env var (bool or URL)\n */\nfunction getSpotlightFromEnv(\n optionsSpotlight: boolean | string | undefined,\n envVar: string | undefined,\n): boolean | string | undefined {\n if (optionsSpotlight === false) {\n return false;\n }\n if (typeof optionsSpotlight === 'string') {\n return optionsSpotlight;\n }\n\n // optionsSpotlight is true or undefined\n const envBool = envToBool(envVar, { strict: true });\n const envUrl = envBool === null && envVar ? envVar : undefined;\n\n return optionsSpotlight === true\n ? (envUrl ?? true) // true: use env URL if present, otherwise true\n : (envBool ?? envUrl); // undefined: use env var (bool or URL)\n}\n\nfunction getTraceLifecycleFromEnv(envVar: string | undefined): 'static' | 'stream' | undefined {\n return envVar === 'stream' || envVar === 'static' ? envVar : undefined;\n}\n"],"mappings":";;;;;AAgBA,SAAS,kBAAkB,OAA4C;CACrE,QAAA,GAAOA,aAAAA,aAAAA,CAAa,KAAK,KAAK,QAAQ,SAAS,OAAO,MAAM,OAAO;AACrE;AAEA,SAAS,UAA6C,KAAc,SAAsC;CACxG,QAAA,GAAOA,aAAAA,aAAAA,CAAa,GAAG,KAAK,WAAW,OAAO,OAAQ,IAAU,aAAa,WACvE,IAAU,WACZ,KAAA;AACN;;;;;;;;;;;;;;;AAgBA,SAAgB,gBAAgB,cAAiC,CAAC,GAAG,KAAiC;CACpG,IAAI,EAAA,GAACA,aAAAA,aAAAA,CAAa,GAAG,GACnB,OAAO;CAIT,MAAM,UACJ,oBAAoB,OAAO,OAAO,IAAI,mBAAmB,WACrD,IAAI,iBACJ,yBAAyB,OAAO,kBAAkB,IAAI,mBAAmB,IACvE,IAAI,oBAAoB,KACxB,KAAA;CAER,MAAM,mBACJ,YAAY,oBAAoB,WAAW,UAAU,KAAK,2BAA2B,KAAK,EAAE;CAM9F,OAAO;EACL;EACA,GAAG;EACH,KAAK,YAAY,OAAO,UAAU,KAAK,YAAY;EACnD,aAAa,YAAY,eAAe,UAAU,KAAK,oBAAoB;EAC3E,kBAAkB,SAAS,gBAAgB,IAAI,mBAAmB,KAAA;EAClE,OAAO,YAAY,UAAA,GAASC,aAAAA,UAAAA,CAAU,UAAU,KAAK,cAAc,CAAC;EACpE,QAAQ,YAAY,UAAU,UAAU,KAAK,eAAe;EAC5D,gBAAgB,YAAY,kBAAkB,yBAAyB,UAAU,KAAK,wBAAwB,CAAC;CAC/G;AACJ;AA6BA,SAAS,yBAAyB,QAA6D;CAC7F,OAAO,WAAW,YAAY,WAAW,WAAW,SAAS,KAAA;AAC/D"}
1
+ {"version":3,"file":"options.js","names":["isObjectLike","envToBool"],"sources":["../../../src/options.ts"],"sourcesContent":["import { isObjectLike, envToBool } from '@sentry/core';\nimport type { CloudflareOptions } from './client';\n\n/**\n * Cloudflare's version metadata binding structure.\n * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/version-metadata/\n */\ninterface CfVersionMetadata {\n id: string;\n tag?: string;\n timestamp?: string;\n}\n\n/**\n * Checks if the value is a valid CF_VERSION_METADATA binding.\n */\nfunction isVersionMetadata(value: unknown): value is CfVersionMetadata {\n return isObjectLike(value) && 'id' in value && typeof value.id === 'string';\n}\n\nfunction getEnvVar<T extends Record<string, unknown>>(env: unknown, varName: keyof T): string | undefined {\n return isObjectLike(env) && varName in env && typeof (env as T)[varName] === 'string'\n ? ((env as T)[varName] as string)\n : undefined;\n}\n\n/**\n * Merges the options passed in from the user with the options we read from\n * the Cloudflare `env` environment variable object.\n *\n * Release is determined with the following priority (highest to lowest):\n * 1. User-provided release option\n * 2. SENTRY_RELEASE environment variable\n * 3. CF_VERSION_METADATA.id binding (if configured in the wrangler config)\n *\n * @param userOptions - The options passed in from the user.\n * @param env - The environment variables.\n *\n * @returns The final options.\n */\nexport function getFinalOptions(userOptions: CloudflareOptions = {}, env: unknown): CloudflareOptions {\n if (!isObjectLike(env)) {\n return userOptions;\n }\n\n // Priority: userOptions.release > SENTRY_RELEASE > CF_VERSION_METADATA.id\n const release =\n 'SENTRY_RELEASE' in env && typeof env.SENTRY_RELEASE === 'string'\n ? env.SENTRY_RELEASE\n : 'CF_VERSION_METADATA' in env && isVersionMetadata(env.CF_VERSION_METADATA)\n ? env.CF_VERSION_METADATA.id\n : undefined;\n\n const tracesSampleRate =\n userOptions.tracesSampleRate ?? parseFloat(getEnvVar(env, 'SENTRY_TRACES_SAMPLE_RATE') ?? '');\n\n // Spotlight precedence (mirrors node-core's getSpotlightConfig):\n // - false or explicit string from options: use as-is\n // - true: enable, but prefer a custom URL from the env var if set\n // - undefined: defer entirely to the env var (bool or URL)\n /*! rollup-include-development-only */\n const spotlight = getSpotlightFromEnv(userOptions.spotlight, getEnvVar(env, 'SENTRY_SPOTLIGHT'));\n /*! rollup-include-development-only-end */\n\n return {\n release,\n ...userOptions,\n dsn: userOptions.dsn ?? getEnvVar(env, 'SENTRY_DSN'),\n environment: userOptions.environment ?? getEnvVar(env, 'SENTRY_ENVIRONMENT'),\n serverName: userOptions.serverName ?? getEnvVar(env, 'SENTRY_NAME'),\n tracesSampleRate: isFinite(tracesSampleRate) ? tracesSampleRate : undefined,\n debug: userOptions.debug ?? envToBool(getEnvVar(env, 'SENTRY_DEBUG')),\n tunnel: userOptions.tunnel ?? getEnvVar(env, 'SENTRY_TUNNEL'),\n traceLifecycle: userOptions.traceLifecycle ?? getTraceLifecycleFromEnv(getEnvVar(env, 'SENTRY_TRACE_LIFECYCLE')),\n /*! rollup-include-development-only */\n spotlight,\n /*! rollup-include-development-only-end */\n };\n}\n\n/**\n * Resolve the spotlight option from a user-supplied value and an env binding string.\n * Mirrors node-core's `getSpotlightConfig` precedence:\n * - `false` or explicit string from options → use as-is\n * - `true` → enable, but prefer a custom URL from the env var if set\n * - `undefined` → defer entirely to the env var (bool or URL)\n */\nfunction getSpotlightFromEnv(\n optionsSpotlight: boolean | string | undefined,\n envVar: string | undefined,\n): boolean | string | undefined {\n if (optionsSpotlight === false) {\n return false;\n }\n if (typeof optionsSpotlight === 'string') {\n return optionsSpotlight;\n }\n\n // optionsSpotlight is true or undefined\n const envBool = envToBool(envVar, { strict: true });\n const envUrl = envBool === null && envVar ? envVar : undefined;\n\n return optionsSpotlight === true\n ? (envUrl ?? true) // true: use env URL if present, otherwise true\n : (envBool ?? envUrl); // undefined: use env var (bool or URL)\n}\n\nfunction getTraceLifecycleFromEnv(envVar: string | undefined): 'static' | 'stream' | undefined {\n return envVar === 'stream' || envVar === 'static' ? envVar : undefined;\n}\n"],"mappings":";;;;;AAgBA,SAAS,kBAAkB,OAA4C;CACrE,QAAA,GAAOA,aAAAA,aAAAA,CAAa,KAAK,KAAK,QAAQ,SAAS,OAAO,MAAM,OAAO;AACrE;AAEA,SAAS,UAA6C,KAAc,SAAsC;CACxG,QAAA,GAAOA,aAAAA,aAAAA,CAAa,GAAG,KAAK,WAAW,OAAO,OAAQ,IAAU,aAAa,WACvE,IAAU,WACZ,KAAA;AACN;;;;;;;;;;;;;;;AAgBA,SAAgB,gBAAgB,cAAiC,CAAC,GAAG,KAAiC;CACpG,IAAI,EAAA,GAACA,aAAAA,aAAAA,CAAa,GAAG,GACnB,OAAO;CAIT,MAAM,UACJ,oBAAoB,OAAO,OAAO,IAAI,mBAAmB,WACrD,IAAI,iBACJ,yBAAyB,OAAO,kBAAkB,IAAI,mBAAmB,IACvE,IAAI,oBAAoB,KACxB,KAAA;CAER,MAAM,mBACJ,YAAY,oBAAoB,WAAW,UAAU,KAAK,2BAA2B,KAAK,EAAE;CAM9F,OAAO;EACL;EACA,GAAG;EACH,KAAK,YAAY,OAAO,UAAU,KAAK,YAAY;EACnD,aAAa,YAAY,eAAe,UAAU,KAAK,oBAAoB;EAC3E,YAAY,YAAY,cAAc,UAAU,KAAK,aAAa;EAClE,kBAAkB,SAAS,gBAAgB,IAAI,mBAAmB,KAAA;EAClE,OAAO,YAAY,UAAA,GAASC,aAAAA,UAAAA,CAAU,UAAU,KAAK,cAAc,CAAC;EACpE,QAAQ,YAAY,UAAU,UAAU,KAAK,eAAe;EAC5D,gBAAgB,YAAY,kBAAkB,yBAAyB,UAAU,KAAK,wBAAwB,CAAC;CAC/G;AACJ;AA6BA,SAAS,yBAAyB,QAA6D;CAC7F,OAAO,WAAW,YAAY,WAAW,WAAW,SAAS,KAAA;AAC/D"}
@@ -14,8 +14,11 @@ let _sentry_core = require("@sentry/core");
14
14
  * runtimes without `nodejs_compat` — there the queue is always empty (no channels were ever
15
15
  * injected) and the flush is a no-op.
16
16
  */
17
- const deferred = [];
18
17
  const DEFERRED = Symbol("sentryOrchestrionDeferred");
18
+ function getDeferredEvents() {
19
+ const marker = _sentry_core.GLOBAL_OBJ.__SENTRY_ORCHESTRION__ ?? (_sentry_core.GLOBAL_OBJ.__SENTRY_ORCHESTRION__ = {});
20
+ return marker.deferredChannelEvents ?? (marker.deferredChannelEvents = []);
21
+ }
19
22
  /** workerd's global-scope guard is the only error we degrade on; anything else is a real fault. */
20
23
  function isGlobalScopeError(error) {
21
24
  return error instanceof Error && /within global scope/.test(error.message);
@@ -24,7 +27,7 @@ function isGlobalScopeError(error) {
24
27
  function deferChannelEvent(channel, ctx) {
25
28
  if (ctx[DEFERRED]) return;
26
29
  ctx[DEFERRED] = true;
27
- deferred.push({
30
+ getDeferredEvents().push({
28
31
  channel,
29
32
  ctx,
30
33
  hadError: "error" in ctx
@@ -38,6 +41,7 @@ function deferChannelEvent(channel, ctx) {
38
41
  * and re-entrant calls are no-ops.
39
42
  */
40
43
  function flushDeferredChannelEvents() {
44
+ const deferred = getDeferredEvents();
41
45
  if (deferred.length === 0) return;
42
46
  const pending = deferred.splice(0, deferred.length);
43
47
  for (const { channel, ctx, hadError } of pending) try {
@@ -1 +1 @@
1
- {"version":3,"file":"orchestrion-deferred-channels.js","names":["DEBUG_BUILD","debug"],"sources":["../../../src/orchestrion-deferred-channels.ts"],"sourcesContent":["/**\n * Deferral for orchestrion channel events that could not be published when they occurred.\n *\n * On workerd, `channel.publish()`/`runStores()` throw at module/global scope, so a library\n * instantiated at module scope (`const app = new Hono()`) cannot emit its wrapping event\n * there. {@link ./orchestrion-diagnostics-channel} defers those events here;\n * {@link flushDeferredChannelEvents} emits them once a request is being handled (where\n * publish works) and the SDK's `init()` has registered subscribers.\n *\n * This module imports NO `node:*` builtin, so it is safe to pull into the request wrapper on\n * runtimes without `nodejs_compat` — there the queue is always empty (no channels were ever\n * injected) and the flush is a no-op.\n */\nimport { debug } from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build';\n\ntype Ctx = Record<string, unknown>;\n\n// The minimal slice of a `node:diagnostics_channel` TracingChannel we emit on. Declared locally\n// (rather than imported from `node:diagnostics_channel`) so this module's graph carries no `node:`\n// specifier — `wrapRequestHandler` must load on runtimes without `nodejs_compat`, and the\n// module-graph test forbids any `node:` import reachable from it.\ninterface PublishableTracingChannel {\n start: { publish(ctx: Ctx): void };\n end: { publish(ctx: Ctx): void };\n error: { publish(ctx: Ctx): void };\n}\n\ninterface DeferredChannelEvent {\n channel: PublishableTracingChannel;\n ctx: Ctx;\n hadError: boolean;\n}\n\nconst deferred: DeferredChannelEvent[] = [];\nconst DEFERRED = Symbol('sentryOrchestrionDeferred');\n\n/** workerd's global-scope guard is the only error we degrade on; anything else is a real fault. */\nexport function isGlobalScopeError(error: unknown): boolean {\n return error instanceof Error && /within global scope/.test(error.message);\n}\n\n/** Queue a channel event that could not be published now, at most once per context object. */\nexport function deferChannelEvent(channel: PublishableTracingChannel, ctx: Ctx): void {\n if ((ctx as Record<symbol, unknown>)[DEFERRED]) {\n return;\n }\n (ctx as Record<symbol, unknown>)[DEFERRED] = true;\n deferred.push({ channel, ctx, hadError: 'error' in ctx });\n}\n\n/**\n * Emit every deferred channel event via the real channel. Called at the top of the request\n * handler, after `init()` has subscribed. Uses bare `start`/`end` publish (never `runStores`),\n * so no `bindStore` producer runs and no span is parented to this request — only the plain\n * subscribers (the instance patchers) fire. Idempotent: it drains the queue, so later requests\n * and re-entrant calls are no-ops.\n */\nexport function flushDeferredChannelEvents(): void {\n if (deferred.length === 0) {\n return;\n }\n const pending = deferred.splice(0, deferred.length);\n for (const { channel, ctx, hadError } of pending) {\n try {\n channel.start.publish(ctx);\n if (hadError) {\n channel.error.publish(ctx);\n }\n channel.end.publish(ctx);\n } catch (error) {\n DEBUG_BUILD && debug.warn('[orchestrion] failed to emit a deferred channel event', error);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkCA,MAAM,WAAmC,CAAC;AAC1C,MAAM,WAAW,OAAO,2BAA2B;;AAGnD,SAAgB,mBAAmB,OAAyB;CAC1D,OAAO,iBAAiB,SAAS,sBAAsB,KAAK,MAAM,OAAO;AAC3E;;AAGA,SAAgB,kBAAkB,SAAoC,KAAgB;CACpF,IAAK,IAAgC,WACnC;CAED,IAAgC,YAAY;CAC7C,SAAS,KAAK;EAAE;EAAS;EAAK,UAAU,WAAW;CAAI,CAAC;AAC1D;;;;;;;;AASA,SAAgB,6BAAmC;CACjD,IAAI,SAAS,WAAW,GACtB;CAEF,MAAM,UAAU,SAAS,OAAO,GAAG,SAAS,MAAM;CAClD,KAAK,MAAM,EAAE,SAAS,KAAK,cAAc,SACvC,IAAI;EACF,QAAQ,MAAM,QAAQ,GAAG;EACzB,IAAI,UACF,QAAQ,MAAM,QAAQ,GAAG;EAE3B,QAAQ,IAAI,QAAQ,GAAG;CACzB,SAAS,OAAO;EACdA,oBAAAA,eAAeC,aAAAA,MAAM,KAAK,yDAAyD,KAAK;CAC1F;AAEJ"}
1
+ {"version":3,"file":"orchestrion-deferred-channels.js","names":["GLOBAL_OBJ","DEBUG_BUILD","debug"],"sources":["../../../src/orchestrion-deferred-channels.ts"],"sourcesContent":["/**\n * Deferral for orchestrion channel events that could not be published when they occurred.\n *\n * On workerd, `channel.publish()`/`runStores()` throw at module/global scope, so a library\n * instantiated at module scope (`const app = new Hono()`) cannot emit its wrapping event\n * there. {@link ./orchestrion-diagnostics-channel} defers those events here;\n * {@link flushDeferredChannelEvents} emits them once a request is being handled (where\n * publish works) and the SDK's `init()` has registered subscribers.\n *\n * This module imports NO `node:*` builtin, so it is safe to pull into the request wrapper on\n * runtimes without `nodejs_compat` — there the queue is always empty (no channels were ever\n * injected) and the flush is a no-op.\n */\nimport { debug, GLOBAL_OBJ } from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build';\n\ntype Ctx = Record<string, unknown>;\n\n// The minimal slice of a `node:diagnostics_channel` TracingChannel we emit on. Declared locally\n// (rather than imported from `node:diagnostics_channel`) so this module's graph carries no `node:`\n// specifier — `wrapRequestHandler` must load on runtimes without `nodejs_compat`, and the\n// module-graph test forbids any `node:` import reachable from it.\ninterface PublishableTracingChannel {\n start: { publish(ctx: Ctx): void };\n end: { publish(ctx: Ctx): void };\n error: { publish(ctx: Ctx): void };\n}\n\ninterface DeferredChannelEvent {\n channel: PublishableTracingChannel;\n ctx: Ctx;\n hadError: boolean;\n}\n\nconst DEFERRED = Symbol('sentryOrchestrionDeferred');\n\n// The queue is on the global marker, not in this module: a bundle can hold both builds of this module. A transformed\n// CommonJS package (`express`) `require`s the facade, so it defers through the CommonJS build, while the request\n// wrapper that flushes is usually the ES module build.\nfunction getDeferredEvents(): DeferredChannelEvent[] {\n const marker = (GLOBAL_OBJ.__SENTRY_ORCHESTRION__ ??= {});\n return (marker.deferredChannelEvents ??= []) as DeferredChannelEvent[];\n}\n\n/** workerd's global-scope guard is the only error we degrade on; anything else is a real fault. */\nexport function isGlobalScopeError(error: unknown): boolean {\n return error instanceof Error && /within global scope/.test(error.message);\n}\n\n/** Queue a channel event that could not be published now, at most once per context object. */\nexport function deferChannelEvent(channel: PublishableTracingChannel, ctx: Ctx): void {\n if ((ctx as Record<symbol, unknown>)[DEFERRED]) {\n return;\n }\n (ctx as Record<symbol, unknown>)[DEFERRED] = true;\n getDeferredEvents().push({ channel, ctx, hadError: 'error' in ctx });\n}\n\n/**\n * Emit every deferred channel event via the real channel. Called at the top of the request\n * handler, after `init()` has subscribed. Uses bare `start`/`end` publish (never `runStores`),\n * so no `bindStore` producer runs and no span is parented to this request — only the plain\n * subscribers (the instance patchers) fire. Idempotent: it drains the queue, so later requests\n * and re-entrant calls are no-ops.\n */\nexport function flushDeferredChannelEvents(): void {\n const deferred = getDeferredEvents();\n if (deferred.length === 0) {\n return;\n }\n const pending = deferred.splice(0, deferred.length);\n for (const { channel, ctx, hadError } of pending) {\n try {\n channel.start.publish(ctx);\n if (hadError) {\n channel.error.publish(ctx);\n }\n channel.end.publish(ctx);\n } catch (error) {\n DEBUG_BUILD && debug.warn('[orchestrion] failed to emit a deferred channel event', error);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkCA,MAAM,WAAW,OAAO,2BAA2B;AAKnD,SAAS,oBAA4C;CACnD,MAAM,SAAUA,aAAAA,WAAW,2BAAXA,aAAAA,WAAW,yBAA2B,CAAC;CACvD,OAAQ,OAAO,0BAAP,OAAO,wBAA0B,CAAC;AAC5C;;AAGA,SAAgB,mBAAmB,OAAyB;CAC1D,OAAO,iBAAiB,SAAS,sBAAsB,KAAK,MAAM,OAAO;AAC3E;;AAGA,SAAgB,kBAAkB,SAAoC,KAAgB;CACpF,IAAK,IAAgC,WACnC;CAED,IAAgC,YAAY;CAC7C,kBAAkB,CAAC,CAAC,KAAK;EAAE;EAAS;EAAK,UAAU,WAAW;CAAI,CAAC;AACrE;;;;;;;;AASA,SAAgB,6BAAmC;CACjD,MAAM,WAAW,kBAAkB;CACnC,IAAI,SAAS,WAAW,GACtB;CAEF,MAAM,UAAU,SAAS,OAAO,GAAG,SAAS,MAAM;CAClD,KAAK,MAAM,EAAE,SAAS,KAAK,cAAc,SACvC,IAAI;EACF,QAAQ,MAAM,QAAQ,GAAG;EACzB,IAAI,UACF,QAAQ,MAAM,QAAQ,GAAG;EAE3B,QAAQ,IAAI,QAAQ,GAAG;CACzB,SAAS,OAAO;EACdC,oBAAAA,eAAeC,aAAAA,MAAM,KAAK,yDAAyD,KAAK;CAC1F;AAEJ"}
@@ -116,7 +116,11 @@ function sentryCloudflareAutoInstrumentPlugin(options = {}) {
116
116
  optionsFn,
117
117
  optionsImport,
118
118
  sameWorkerBindings: wranglerConfig.sameWorkerBindings,
119
- sentryModule
119
+ sentryModule,
120
+ workerInfo: {
121
+ name: wranglerConfig.name,
122
+ compatibilityDate: wranglerConfig.compatibilityDate
123
+ }
120
124
  });
121
125
  const wrappedClasses = result?.wrappedClasses ?? /* @__PURE__ */ new Set();
122
126
  const missing = [...classWrappers.keys()].filter((name) => !wrappedClasses.has(name));
@@ -1 +1 @@
1
- {"version":3,"file":"autoInstrument.js","names":["resolveWranglerConfig","basename","isAbsolute","resolveInstrumentFile","dirname","createIdResolver","collectAgentCandidates","detectAgentClasses","buildOptionsImport","ENV_FALLBACK_OPTIONS_FN","applyAutoInstrumentTransforms"],"sources":["../../../../src/vite/autoInstrument.ts"],"sourcesContent":["import { basename, dirname, isAbsolute } from 'node:path';\nimport { createIdResolver, type ResolvedConfig } from 'vite';\nimport { collectAgentCandidates, detectAgentClasses, type ModuleResolver } from './agentClass';\nimport { buildOptionsImport, ENV_FALLBACK_OPTIONS_FN, resolveInstrumentFile } from './instrumentFile';\nimport { applyAutoInstrumentTransforms, type BaseNode, type ClassWrapperKind, type ProgramBody } from './transform';\nimport { resolveWranglerConfig, type WranglerConfig } from './wranglerConfig';\n\n// Vite normalizes module IDs to posix separators even on Windows, while\n// `path.resolve` yields backslashes there — normalize before comparing.\nfunction normalizePath(path: string): string {\n return path.replace(/\\\\/g, '/');\n}\n\n// Extensions the entry-module match may tolerate swapping (e.g. wrangler's\n// `main` says `.ts` but the served module is `.js`). Anything else — `.css`,\n// `.html`, … — sharing the entry's basename must never be treated as the entry.\nconst JS_EXTENSION_REGEX = /\\.[cm]?[jt]sx?$/;\n\n// Re-exports everything the generated code uses, and adds the Next.js span handling and OpenTelemetry context.\nconst NEXTJS_CLOUDFLARE_MODULE = '@sentry/nextjs/cloudflare';\n\n/**\n * Whether `@sentry/nextjs/cloudflare` resolves from `importer`. Vite throws instead of returning `null` when\n * `@sentry/nextjs` is installed in a version without that entry.\n */\nasync function resolvesNextjsCloudflare(resolver: ModuleResolver, importer: string): Promise<boolean> {\n try {\n return !!(await resolver.resolve?.(NEXTJS_CLOUDFLARE_MODULE, importer));\n } catch {\n return false;\n }\n}\n\n/**\n * Whether the module re-exports everything from another module of its own file, as the shim\n * `@sentry/tanstackstart-react` loads for the server entry does (`export * from \"<entry>?sentry-tunnel-original\"`).\n * That module is transformed as the entry too, and its classes are wrapped there.\n */\nfunction reexportsAllFromSameFile(ast: ProgramBody, normalizedId: string): boolean {\n return ast.body.some(node => {\n if (node.type !== 'ExportAllDeclaration') return false;\n const { exported, source } = node as BaseNode & { exported?: unknown; source?: { value?: unknown } };\n const value = source?.value;\n return !exported && typeof value === 'string' && normalizePath(value.replace(/[?#].*$/, '')) === normalizedId;\n });\n}\n\ntype TransformContext = ModuleResolver & {\n warn?(msg: string): void;\n environment?: Parameters<ReturnType<typeof createIdResolver>>[0];\n};\n\nexport function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPath?: string } = {}) {\n let wranglerConfig: WranglerConfig | undefined;\n let entryFilePath: string | undefined;\n // A `main` that is not a file path (a package export or virtual module).\n let entrySpecifier: string | undefined;\n let wranglerConfigPath: string | undefined;\n let resolveId: ReturnType<typeof createIdResolver> | undefined;\n // Each environment resolves with its own conditions, so the entry may differ between them.\n const resolvedEntries = new Map<string, Promise<string | undefined>>();\n\n let instrumentFilePath: string | undefined;\n let isVinext = false;\n\n function resolveEntrySpecifier(ctx: TransformContext, specifier: string): Promise<string | undefined> {\n const environment = ctx.environment;\n if (!environment || !resolveId) return Promise.resolve(undefined);\n\n let entry = resolvedEntries.get(environment.name);\n if (!entry) {\n // Resolved from the wrangler config, as wrangler does. Without an importer, Vite's resolver\n // tries the specifier as a path below the root first.\n entry = resolveId(environment, specifier, wranglerConfigPath)\n .catch(() => undefined)\n .then(id => {\n if (!id) {\n ctx.warn?.(\n `[sentry] Could not resolve the wrangler \\`main\\` \"${specifier}\". Auto-instrumentation disabled.`,\n );\n return undefined;\n }\n return normalizePath(id.replace(/[?#].*$/, ''));\n });\n resolvedEntries.set(environment.name, entry);\n }\n return entry;\n }\n\n return {\n name: 'sentry-cloudflare-auto-instrument',\n\n configResolved(config: {\n root: string;\n plugins?: readonly { name?: string }[];\n logger?: { warn(msg: string): void };\n }): void {\n isVinext = config.plugins?.some(plugin => plugin.name?.startsWith('vinext:')) ?? false;\n\n const result = resolveWranglerConfig(config.root, options.wranglerConfigPath);\n if (!result) {\n // An explicit path that fails is a misconfiguration worth naming;\n // without one, hint at the option so custom-named configs (e.g. a\n // `configPath` handed to @cloudflare/vite-plugin) are discoverable.\n config.logger?.warn(\n options.wranglerConfigPath\n ? `[sentry] Could not find or parse the wrangler config \"${basename(options.wranglerConfigPath)}\" ` +\n '(resolved against the Vite root) — auto-instrumentation disabled.'\n : '[sentry] No parseable wrangler config found — auto-instrumentation disabled. ' +\n 'Set `wranglerConfigPath` if your config uses a custom name.',\n );\n return;\n }\n\n wranglerConfig = result.config;\n const main = wranglerConfig.main;\n if (main && isAbsolute(main)) {\n // Normalize separators so the entry-module comparison holds on Windows.\n entryFilePath = normalizePath(main);\n instrumentFilePath = resolveInstrumentFile(dirname(main));\n } else if (main) {\n entrySpecifier = main;\n wranglerConfigPath = result.configPath;\n // Not `this.resolve()`: Rollup's commonjs resolver loads the module it resolves, so a\n // resolve of the entry from the entry's own `transform` never finishes.\n resolveId = createIdResolver(config as ResolvedConfig);\n // A package entry has no project directory of its own.\n instrumentFilePath = resolveInstrumentFile(result.configDir);\n }\n },\n\n async transform(\n this: TransformContext,\n code: string,\n id: string,\n ): Promise<{ code: string; map: unknown } | undefined> {\n if (!wranglerConfig || (!entryFilePath && !entrySpecifier)) return undefined;\n\n // The worker entry never belongs to the client (browser) environment.\n // Skipping it keeps a same-basename sibling (e.g. a `src/index.tsx`\n // client entry next to a `src/index.ts` worker) out of the browser bundle.\n if (this.environment?.name === 'client') return undefined;\n\n const entryPath = entrySpecifier ? await resolveEntrySpecifier(this, entrySpecifier) : entryFilePath;\n if (!entryPath) return undefined;\n\n // Vite may append query/hash params to the module ID.\n const normalizedId = normalizePath(id.replace(/[?#].*$/, ''));\n if (normalizedId !== entryPath) {\n // Tolerate a differing JS-flavored extension (e.g. `.js` vs `.ts`).\n if (!JS_EXTENSION_REGEX.test(normalizedId) || !JS_EXTENSION_REGEX.test(entryPath)) return undefined;\n if (normalizedId.replace(JS_EXTENSION_REGEX, '') !== entryPath.replace(JS_EXTENSION_REGEX, '')) {\n return undefined;\n }\n }\n\n let ast: ProgramBody;\n try {\n ast = this.parse(code);\n } catch {\n // Raw TypeScript or syntax error — esbuild hasn't run yet (unlikely)\n // or the file is genuinely broken. Either way, skip silently.\n return undefined;\n }\n\n const classWrappers = new Map<string, ClassWrapperKind>();\n for (const { className } of wranglerConfig.durableObjects) {\n classWrappers.set(className, 'durableObject');\n }\n for (const { className } of wranglerConfig.workflows) {\n classWrappers.set(className, 'workflow');\n }\n for (const className of wranglerConfig.workerEntrypoints) {\n classWrappers.set(className, 'workerEntrypoint');\n }\n\n // An `agents` Agent is a Durable Object, so wrangler lists it among the DO bindings and only\n // its base-class chain tells the two apart. Detection walks the module graph (base classes\n // usually live in their own file), so it is limited to the configured DO classes.\n //\n // Only `resolve` is handed over — never `load`: awaiting `load()` from inside a transform\n // hook deadlocks the build, since the module can't finish loading while this transform is\n // still pending. `agentClass` reads sibling modules off disk instead.\n const agentCandidates = collectAgentCandidates(\n ast,\n [...classWrappers].filter(([, kind]) => kind === 'durableObject').map(([name]) => name),\n );\n const agentClasses =\n agentCandidates.size > 0\n ? await detectAgentClasses(ast, normalizedId, agentCandidates, {\n parse: code => this.parse(code),\n resolve: this.resolve ? (source, importer) => this.resolve!(source, importer) : undefined,\n })\n : undefined;\n\n // A vinext app with `@sentry/nextjs` installed gets `withSentry` of `@sentry/nextjs/cloudflare`.\n const sentryModule =\n isVinext && (await resolvesNextjsCloudflare(this, normalizedId)) ? NEXTJS_CLOUDFLARE_MODULE : undefined;\n\n const { optionsFn, importStmt: optionsImport } = instrumentFilePath\n ? buildOptionsImport(entryPath, instrumentFilePath)\n : { optionsFn: ENV_FALLBACK_OPTIONS_FN, importStmt: undefined };\n\n // No registration import is injected here: the orchestrion plugin's\n // subscribe-injection makes each bundled package self-register its channel\n // subscriber on the global marker, so wrapping the entry with `withSentry`\n // is all this plugin needs to do.\n const result = applyAutoInstrumentTransforms(code, ast, {\n classWrappers,\n agentClasses,\n optionsFn,\n optionsImport,\n sameWorkerBindings: wranglerConfig.sameWorkerBindings,\n sentryModule,\n });\n\n const wrappedClasses = result?.wrappedClasses ?? new Set<string>();\n const missing = [...classWrappers.keys()].filter(name => !wrappedClasses.has(name));\n if (missing.length > 0 && !reexportsAllFromSameFile(ast, normalizedId)) {\n this.warn?.(\n `[sentry] Could not auto-instrument ${missing.join(', ')}. ` +\n 'The worker entry has no export matching them. ' +\n 'Star re-exports (`export * from \"./do\"`) are not matched. ' +\n 'Export them by name or wrap them manually with corresponding `instrument*WithSentry` helpers.',\n );\n }\n\n return result ?? undefined;\n },\n };\n}\n"],"mappings":";;;;;;;AASA,SAAS,cAAc,MAAsB;CAC3C,OAAO,KAAK,QAAQ,OAAO,GAAG;AAChC;AAKA,MAAM,qBAAqB;AAG3B,MAAM,2BAA2B;;;;;AAMjC,eAAe,yBAAyB,UAA0B,UAAoC;CACpG,IAAI;EACF,OAAO,CAAC,CAAE,MAAM,SAAS,UAAU,0BAA0B,QAAQ;CACvE,QAAQ;EACN,OAAO;CACT;AACF;;;;;;AAOA,SAAS,yBAAyB,KAAkB,cAA+B;CACjF,OAAO,IAAI,KAAK,MAAK,SAAQ;EAC3B,IAAI,KAAK,SAAS,wBAAwB,OAAO;EACjD,MAAM,EAAE,UAAU,WAAW;EAC7B,MAAM,QAAQ,QAAQ;EACtB,OAAO,CAAC,YAAY,OAAO,UAAU,YAAY,cAAc,MAAM,QAAQ,WAAW,EAAE,CAAC,MAAM;CACnG,CAAC;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Q,aAAa,KAAK,QAAS,QAAQ,QAAQ,IAAI,KAAA;GAClF,CAAC,IACD,KAAA;GAGN,MAAM,eACJ,YAAa,MAAM,yBAAyB,MAAM,YAAY,IAAK,2BAA2B,KAAA;GAEhG,MAAM,EAAE,WAAW,YAAY,kBAAkB,qBAC7CC,uBAAAA,mBAAmB,WAAW,kBAAkB,IAChD;IAAE,WAAWC,uBAAAA;IAAyB,YAAY,KAAA;GAAU;GAMhE,MAAM,SAASC,kBAAAA,8BAA8B,MAAM,KAAK;IACtD;IACA;IACA;IACA;IACA,oBAAoB,eAAe;IACnC;GACF,CAAC;GAED,MAAM,iBAAiB,QAAQ,kCAAkB,IAAI,IAAY;GACjE,MAAM,UAAU,CAAC,GAAG,cAAc,KAAK,CAAC,CAAC,CAAC,QAAO,SAAQ,CAAC,eAAe,IAAI,IAAI,CAAC;GAClF,IAAI,QAAQ,SAAS,KAAK,CAAC,yBAAyB,KAAK,YAAY,GACnE,KAAK,OACH,sCAAsC,QAAQ,KAAK,IAAI,EAAE,4MAI3D;GAGF,OAAO,UAAU,KAAA;EACnB;CACF;AACF"}
1
+ {"version":3,"file":"autoInstrument.js","names":["resolveWranglerConfig","basename","isAbsolute","resolveInstrumentFile","dirname","createIdResolver","collectAgentCandidates","detectAgentClasses","buildOptionsImport","ENV_FALLBACK_OPTIONS_FN","applyAutoInstrumentTransforms"],"sources":["../../../../src/vite/autoInstrument.ts"],"sourcesContent":["import { basename, dirname, isAbsolute } from 'node:path';\nimport { createIdResolver, type ResolvedConfig } from 'vite';\nimport { collectAgentCandidates, detectAgentClasses, type ModuleResolver } from './agentClass';\nimport { buildOptionsImport, ENV_FALLBACK_OPTIONS_FN, resolveInstrumentFile } from './instrumentFile';\nimport { applyAutoInstrumentTransforms, type BaseNode, type ClassWrapperKind, type ProgramBody } from './transform';\nimport { resolveWranglerConfig, type WranglerConfig } from './wranglerConfig';\n\n// Vite normalizes module IDs to posix separators even on Windows, while\n// `path.resolve` yields backslashes there — normalize before comparing.\nfunction normalizePath(path: string): string {\n return path.replace(/\\\\/g, '/');\n}\n\n// Extensions the entry-module match may tolerate swapping (e.g. wrangler's\n// `main` says `.ts` but the served module is `.js`). Anything else — `.css`,\n// `.html`, … — sharing the entry's basename must never be treated as the entry.\nconst JS_EXTENSION_REGEX = /\\.[cm]?[jt]sx?$/;\n\n// Re-exports everything the generated code uses, and adds the Next.js span handling and OpenTelemetry context.\nconst NEXTJS_CLOUDFLARE_MODULE = '@sentry/nextjs/cloudflare';\n\n/**\n * Whether `@sentry/nextjs/cloudflare` resolves from `importer`. Vite throws instead of returning `null` when\n * `@sentry/nextjs` is installed in a version without that entry.\n */\nasync function resolvesNextjsCloudflare(resolver: ModuleResolver, importer: string): Promise<boolean> {\n try {\n return !!(await resolver.resolve?.(NEXTJS_CLOUDFLARE_MODULE, importer));\n } catch {\n return false;\n }\n}\n\n/**\n * Whether the module re-exports everything from another module of its own file, as the shim\n * `@sentry/tanstackstart-react` loads for the server entry does (`export * from \"<entry>?sentry-tunnel-original\"`).\n * That module is transformed as the entry too, and its classes are wrapped there.\n */\nfunction reexportsAllFromSameFile(ast: ProgramBody, normalizedId: string): boolean {\n return ast.body.some(node => {\n if (node.type !== 'ExportAllDeclaration') return false;\n const { exported, source } = node as BaseNode & { exported?: unknown; source?: { value?: unknown } };\n const value = source?.value;\n return !exported && typeof value === 'string' && normalizePath(value.replace(/[?#].*$/, '')) === normalizedId;\n });\n}\n\ntype TransformContext = ModuleResolver & {\n warn?(msg: string): void;\n environment?: Parameters<ReturnType<typeof createIdResolver>>[0];\n};\n\nexport function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPath?: string } = {}) {\n let wranglerConfig: WranglerConfig | undefined;\n let entryFilePath: string | undefined;\n // A `main` that is not a file path (a package export or virtual module).\n let entrySpecifier: string | undefined;\n let wranglerConfigPath: string | undefined;\n let resolveId: ReturnType<typeof createIdResolver> | undefined;\n // Each environment resolves with its own conditions, so the entry may differ between them.\n const resolvedEntries = new Map<string, Promise<string | undefined>>();\n\n let instrumentFilePath: string | undefined;\n let isVinext = false;\n\n function resolveEntrySpecifier(ctx: TransformContext, specifier: string): Promise<string | undefined> {\n const environment = ctx.environment;\n if (!environment || !resolveId) return Promise.resolve(undefined);\n\n let entry = resolvedEntries.get(environment.name);\n if (!entry) {\n // Resolved from the wrangler config, as wrangler does. Without an importer, Vite's resolver\n // tries the specifier as a path below the root first.\n entry = resolveId(environment, specifier, wranglerConfigPath)\n .catch(() => undefined)\n .then(id => {\n if (!id) {\n ctx.warn?.(\n `[sentry] Could not resolve the wrangler \\`main\\` \"${specifier}\". Auto-instrumentation disabled.`,\n );\n return undefined;\n }\n return normalizePath(id.replace(/[?#].*$/, ''));\n });\n resolvedEntries.set(environment.name, entry);\n }\n return entry;\n }\n\n return {\n name: 'sentry-cloudflare-auto-instrument',\n\n configResolved(config: {\n root: string;\n plugins?: readonly { name?: string }[];\n logger?: { warn(msg: string): void };\n }): void {\n isVinext = config.plugins?.some(plugin => plugin.name?.startsWith('vinext:')) ?? false;\n\n const result = resolveWranglerConfig(config.root, options.wranglerConfigPath);\n if (!result) {\n // An explicit path that fails is a misconfiguration worth naming;\n // without one, hint at the option so custom-named configs (e.g. a\n // `configPath` handed to @cloudflare/vite-plugin) are discoverable.\n config.logger?.warn(\n options.wranglerConfigPath\n ? `[sentry] Could not find or parse the wrangler config \"${basename(options.wranglerConfigPath)}\" ` +\n '(resolved against the Vite root) — auto-instrumentation disabled.'\n : '[sentry] No parseable wrangler config found — auto-instrumentation disabled. ' +\n 'Set `wranglerConfigPath` if your config uses a custom name.',\n );\n return;\n }\n\n wranglerConfig = result.config;\n const main = wranglerConfig.main;\n if (main && isAbsolute(main)) {\n // Normalize separators so the entry-module comparison holds on Windows.\n entryFilePath = normalizePath(main);\n instrumentFilePath = resolveInstrumentFile(dirname(main));\n } else if (main) {\n entrySpecifier = main;\n wranglerConfigPath = result.configPath;\n // Not `this.resolve()`: Rollup's commonjs resolver loads the module it resolves, so a\n // resolve of the entry from the entry's own `transform` never finishes.\n resolveId = createIdResolver(config as ResolvedConfig);\n // A package entry has no project directory of its own.\n instrumentFilePath = resolveInstrumentFile(result.configDir);\n }\n },\n\n async transform(\n this: TransformContext,\n code: string,\n id: string,\n ): Promise<{ code: string; map: unknown } | undefined> {\n if (!wranglerConfig || (!entryFilePath && !entrySpecifier)) return undefined;\n\n // The worker entry never belongs to the client (browser) environment.\n // Skipping it keeps a same-basename sibling (e.g. a `src/index.tsx`\n // client entry next to a `src/index.ts` worker) out of the browser bundle.\n if (this.environment?.name === 'client') return undefined;\n\n const entryPath = entrySpecifier ? await resolveEntrySpecifier(this, entrySpecifier) : entryFilePath;\n if (!entryPath) return undefined;\n\n // Vite may append query/hash params to the module ID.\n const normalizedId = normalizePath(id.replace(/[?#].*$/, ''));\n if (normalizedId !== entryPath) {\n // Tolerate a differing JS-flavored extension (e.g. `.js` vs `.ts`).\n if (!JS_EXTENSION_REGEX.test(normalizedId) || !JS_EXTENSION_REGEX.test(entryPath)) return undefined;\n if (normalizedId.replace(JS_EXTENSION_REGEX, '') !== entryPath.replace(JS_EXTENSION_REGEX, '')) {\n return undefined;\n }\n }\n\n let ast: ProgramBody;\n try {\n ast = this.parse(code);\n } catch {\n // Raw TypeScript or syntax error — esbuild hasn't run yet (unlikely)\n // or the file is genuinely broken. Either way, skip silently.\n return undefined;\n }\n\n const classWrappers = new Map<string, ClassWrapperKind>();\n for (const { className } of wranglerConfig.durableObjects) {\n classWrappers.set(className, 'durableObject');\n }\n for (const { className } of wranglerConfig.workflows) {\n classWrappers.set(className, 'workflow');\n }\n for (const className of wranglerConfig.workerEntrypoints) {\n classWrappers.set(className, 'workerEntrypoint');\n }\n\n // An `agents` Agent is a Durable Object, so wrangler lists it among the DO bindings and only\n // its base-class chain tells the two apart. Detection walks the module graph (base classes\n // usually live in their own file), so it is limited to the configured DO classes.\n //\n // Only `resolve` is handed over — never `load`: awaiting `load()` from inside a transform\n // hook deadlocks the build, since the module can't finish loading while this transform is\n // still pending. `agentClass` reads sibling modules off disk instead.\n const agentCandidates = collectAgentCandidates(\n ast,\n [...classWrappers].filter(([, kind]) => kind === 'durableObject').map(([name]) => name),\n );\n const agentClasses =\n agentCandidates.size > 0\n ? await detectAgentClasses(ast, normalizedId, agentCandidates, {\n parse: code => this.parse(code),\n resolve: this.resolve ? (source, importer) => this.resolve!(source, importer) : undefined,\n })\n : undefined;\n\n // A vinext app with `@sentry/nextjs` installed gets `withSentry` of `@sentry/nextjs/cloudflare`.\n const sentryModule =\n isVinext && (await resolvesNextjsCloudflare(this, normalizedId)) ? NEXTJS_CLOUDFLARE_MODULE : undefined;\n\n const { optionsFn, importStmt: optionsImport } = instrumentFilePath\n ? buildOptionsImport(entryPath, instrumentFilePath)\n : { optionsFn: ENV_FALLBACK_OPTIONS_FN, importStmt: undefined };\n\n // No registration import is injected here: the orchestrion plugin's\n // subscribe-injection makes each bundled package self-register its channel\n // subscriber on the global marker, so wrapping the entry with `withSentry`\n // is all this plugin needs to do.\n const result = applyAutoInstrumentTransforms(code, ast, {\n classWrappers,\n agentClasses,\n optionsFn,\n optionsImport,\n sameWorkerBindings: wranglerConfig.sameWorkerBindings,\n sentryModule,\n workerInfo: { name: wranglerConfig.name, compatibilityDate: wranglerConfig.compatibilityDate },\n });\n\n const wrappedClasses = result?.wrappedClasses ?? new Set<string>();\n const missing = [...classWrappers.keys()].filter(name => !wrappedClasses.has(name));\n if (missing.length > 0 && !reexportsAllFromSameFile(ast, normalizedId)) {\n this.warn?.(\n `[sentry] Could not auto-instrument ${missing.join(', ')}. ` +\n 'The worker entry has no export matching them. ' +\n 'Star re-exports (`export * from \"./do\"`) are not matched. ' +\n 'Export them by name or wrap them manually with corresponding `instrument*WithSentry` helpers.',\n );\n }\n\n return result ?? undefined;\n },\n };\n}\n"],"mappings":";;;;;;;AASA,SAAS,cAAc,MAAsB;CAC3C,OAAO,KAAK,QAAQ,OAAO,GAAG;AAChC;AAKA,MAAM,qBAAqB;AAG3B,MAA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entryMastraObservabilityProviderPlugin","sentryCloudflareAutoInstrumentPlugin"],"sources":["../../../../src/vite/index.ts"],"sourcesContent":["// Published ESM-only via the `@sentry/cloudflare/vite` subpath export:\n// `@sentry/server-utils/orchestrion/vite` exposes no `require` condition, so a\n// CJS entry here would fail at resolution time (ERR_PACKAGE_PATH_NOT_EXPORTED).\n// The CJS rollup variant still emits this file, but `package.json` doesn't\n// expose it — same setup as `@sentry/server-utils/orchestrion/vite` itself.\nimport { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';\nimport { sentryCloudflareAutoInstrumentPlugin } from './autoInstrument';\nimport { sentryMastraObservabilityProviderPlugin } from './mastraObservability';\n\n/**\n * Options for {@link sentryCloudflareVitePlugin}.\n */\nexport interface SentryCloudflareVitePluginOptions {\n /**\n * Path to the wrangler config, relative to the Vite root (or absolute).\n * Set this when your config doesn't use a default name — e.g. when you\n * pass `configPath: './wrangler.agent.jsonc'` to `@cloudflare/vite-plugin`,\n * which the Sentry plugin cannot see. When set, only this file is read\n * (no default-name probing), and a warning is emitted if it is missing or\n * unparseable.\n *\n * @default undefined (probes `wrangler.json`, `wrangler.jsonc`, `wrangler.toml` at the Vite root)\n */\n wranglerConfigPath?: string;\n /**\n * Build-time automatic instrumentation of supported dependencies (e.g.\n * database clients like `mysql`) so the Sentry Cloudflare SDK can trace them\n * without monkey-patching, which wouldn't work in workerd anyway.\n *\n * When enabled, the plugin injects `diagnostics_channel.tracingChannel` calls\n * into the bundled packages and, next to each, a snippet that registers the\n * matching Sentry channel-subscriber factory on the global marker, which the\n * SDK picks up in `Sentry.withSentry()`. Both `vite build` and `vite dev` are\n * instrumented. Set to `false` to opt out.\n *\n * @default true\n */\n buildTimeInstrumentation?: boolean;\n /**\n * Automatically wraps your Worker at build time so you don't have to edit\n * your entry: the plugin reads your wrangler config, wraps the default\n * export with `Sentry.withSentry()` (sourcing options from a co-located\n * `instrument.*` file, falling back to env), and wraps any configured\n * Durable Object class with `instrumentDurableObjectWithSentry`. Both\n * `vite build` and `vite dev` are instrumented. Already-wrapped entries are\n * left alone, so this is safe alongside manual instrumentation. Set to\n * `false` to opt out.\n *\n * The plugin also adds the bindings that resolve to the wrapped classes (this worker's own\n * Durable Objects and self service bindings) to `rpcTracePropagationBindings`. Bindings to\n * other workers stay opt-in, their receivers may not run Sentry.\n *\n * @default true\n */\n autoInstrumentation?: boolean;\n}\n\n/**\n * Sentry Vite plugin for Cloudflare Workers.\n *\n * Add this plugin to your Vite configuration to enable additional Sentry\n * instrumentation for Cloudflare Workers built with Vite.\n *\n * By default, the plugin\n * - build-time instruments supported dependencies (such as database clients) so\n * they are traced without changing your application code — opt out with\n * `buildTimeInstrumentation: false`, and\n * - wraps your Worker entry (and any Durable Object, Workflow or\n * WorkerEntrypoint class in your wrangler config) with the matching Sentry\n * helper — opt out with `autoInstrumentation: false` and call\n * `Sentry.withSentry()` yourself.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { cloudflare } from '@cloudflare/vite-plugin';\n * import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite';\n * import { defineConfig } from 'vite';\n *\n * export default defineConfig({\n * plugins: [cloudflare(), sentryCloudflareVitePlugin()],\n * });\n * ```\n */\nexport function sentryCloudflareVitePlugin(options: SentryCloudflareVitePluginOptions = {}): Array<{ name: string }> {\n return [\n sentryOrchestrionPlugin({\n buildTimeInstrumentation: options.buildTimeInstrumentation,\n // Route the injected `tracingChannel` imports through the workerd-safe façade so a\n // dependency wrapped at module scope (`const app = new Hono()`) doesn't throw on workerd.\n dcModule: '@sentry/cloudflare/orchestrion-diagnostics-channel',\n transformOptimizedDeps: true,\n // `flueIntegration` needs Flue's own `instrument()`, which a bundled worker can't resolve.\n selfProvidedModules: ['@flue/runtime'],\n }),\n sentryMastraObservabilityProviderPlugin(),\n ...(options.autoInstrumentation !== false\n ? [sentryCloudflareAutoInstrumentPlugin({ wranglerConfigPath: options.wranglerConfigPath })]\n : []),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoFA,SAAgB,2BAA2B,UAA6C,CAAC,GAA4B;CACnH,OAAO;GACLA,GAAAA,sCAAAA,wBAAAA,CAAwB;GACtB,0BAA0B,QAAQ;GAGlC,UAAU;GACV,wBAAwB;GAExB,qBAAqB,CAAC,eAAe;EACvC,CAAC;EACDC,4BAAAA,wCAAwC;EACxC,GAAI,QAAQ,wBAAwB,QAChC,CAACC,uBAAAA,qCAAqC,EAAE,oBAAoB,QAAQ,mBAAmB,CAAC,CAAC,IACzF,CAAC;CACP;AACF"}
1
+ {"version":3,"file":"index.js","names":["sentryOrchestrionPlugin","sentryMastraObservabilityProviderPlugin","sentryCloudflareAutoInstrumentPlugin"],"sources":["../../../../src/vite/index.ts"],"sourcesContent":["// Published ESM-only via the `@sentry/cloudflare/vite` subpath export:\n// `@sentry/server-utils/orchestrion/vite` exposes no `require` condition, so a\n// CJS entry here would fail at resolution time (ERR_PACKAGE_PATH_NOT_EXPORTED).\n// The CJS rollup variant still emits this file, but `package.json` doesn't\n// expose it — same setup as `@sentry/server-utils/orchestrion/vite` itself.\nimport { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';\nimport { sentryCloudflareAutoInstrumentPlugin } from './autoInstrument';\nimport { sentryMastraObservabilityProviderPlugin } from './mastraObservability';\n\n/**\n * Options for {@link sentryCloudflareVitePlugin}.\n */\nexport interface SentryCloudflareVitePluginOptions {\n /**\n * Path to the wrangler config, relative to the Vite root (or absolute).\n * Set this when your config doesn't use a default name — e.g. when you\n * pass `configPath: './wrangler.agent.jsonc'` to `@cloudflare/vite-plugin`,\n * which the Sentry plugin cannot see. When set, only this file is read\n * (no default-name probing), and a warning is emitted if it is missing or\n * unparseable.\n *\n * @default undefined (probes `wrangler.json`, `wrangler.jsonc`, `wrangler.toml` at the Vite root)\n */\n wranglerConfigPath?: string;\n /**\n * Build-time automatic instrumentation of supported dependencies (e.g.\n * database clients like `mysql`) so the Sentry Cloudflare SDK can trace them\n * without monkey-patching, which wouldn't work in workerd anyway.\n *\n * When enabled, the plugin injects `diagnostics_channel.tracingChannel` calls\n * into the bundled packages and, next to each, a snippet that registers the\n * matching Sentry channel-subscriber factory on the global marker, which the\n * SDK picks up in `Sentry.withSentry()`. Both `vite build` and `vite dev` are\n * instrumented. Set to `false` to opt out.\n *\n * @default true\n */\n buildTimeInstrumentation?: boolean;\n /**\n * Automatically wraps your Worker at build time so you don't have to edit\n * your entry: the plugin reads your wrangler config, wraps the default\n * export with `Sentry.withSentry()` (sourcing options from a co-located\n * `instrument.*` file, falling back to env), and wraps any configured\n * Durable Object class with `instrumentDurableObjectWithSentry`. Both\n * `vite build` and `vite dev` are instrumented. Already-wrapped entries are\n * left alone, so this is safe alongside manual instrumentation. Set to\n * `false` to opt out.\n *\n * The plugin also adds the bindings that resolve to the wrapped classes (this worker's own\n * Durable Objects and self service bindings) to `rpcTracePropagationBindings`. Bindings to\n * other workers stay opt-in, their receivers may not run Sentry.\n *\n * The plugin also sets the `name` of your wrangler config as the default `serverName` and the\n * `compatibility_date` as the runtime version, also for handlers you wrap yourself.\n *\n * @default true\n */\n autoInstrumentation?: boolean;\n}\n\n/**\n * Sentry Vite plugin for Cloudflare Workers.\n *\n * Add this plugin to your Vite configuration to enable additional Sentry\n * instrumentation for Cloudflare Workers built with Vite.\n *\n * By default, the plugin\n * - build-time instruments supported dependencies (such as database clients) so\n * they are traced without changing your application code — opt out with\n * `buildTimeInstrumentation: false`, and\n * - wraps your Worker entry (and any Durable Object, Workflow or\n * WorkerEntrypoint class in your wrangler config) with the matching Sentry\n * helper — opt out with `autoInstrumentation: false` and call\n * `Sentry.withSentry()` yourself.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { cloudflare } from '@cloudflare/vite-plugin';\n * import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite';\n * import { defineConfig } from 'vite';\n *\n * export default defineConfig({\n * plugins: [cloudflare(), sentryCloudflareVitePlugin()],\n * });\n * ```\n */\nexport function sentryCloudflareVitePlugin(options: SentryCloudflareVitePluginOptions = {}): Array<{ name: string }> {\n return [\n sentryOrchestrionPlugin({\n buildTimeInstrumentation: options.buildTimeInstrumentation,\n // Route the injected `tracingChannel` imports through the workerd-safe façade so a\n // dependency wrapped at module scope (`const app = new Hono()`) doesn't throw on workerd.\n dcModule: '@sentry/cloudflare/orchestrion-diagnostics-channel',\n transformOptimizedDeps: true,\n // `flueIntegration` needs Flue's own `instrument()`, which a bundled worker can't resolve.\n selfProvidedModules: ['@flue/runtime'],\n }),\n sentryMastraObservabilityProviderPlugin(),\n ...(options.autoInstrumentation !== false\n ? [sentryCloudflareAutoInstrumentPlugin({ wranglerConfigPath: options.wranglerConfigPath })]\n : []),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuFA,SAAgB,2BAA2B,UAA6C,CAAC,GAA4B;CACnH,OAAO;GACLA,GAAAA,sCAAAA,wBAAAA,CAAwB;GACtB,0BAA0B,QAAQ;GAGlC,UAAU;GACV,wBAAwB;GAExB,qBAAqB,CAAC,eAAe;EACvC,CAAC;EACDC,4BAAAA,wCAAwC;EACxC,GAAI,QAAQ,wBAAwB,QAChC,CAACC,uBAAAA,qCAAqC,EAAE,oBAAoB,QAAQ,mBAAmB,CAAC,CAAC,IACzF,CAAC;CACP;AACF"}
@@ -1,10 +1,12 @@
1
1
  const require_runtime = require("../_virtual/_rolldown/runtime.js");
2
2
  const require_wranglerConfig = require("./wranglerConfig.js");
3
3
  const require_workerEntrypoint = require("./workerEntrypoint.js");
4
+ let _sentry_core = require("@sentry/core");
4
5
  let magic_string = require("magic-string");
5
6
  magic_string = require_runtime.__toESM(magic_string);
6
7
  // src/vite/transform.ts
7
8
  const MERGED_OPTIONS_IDENTIFIER = "__SENTRY_OPTIONS__";
9
+ const WORKER_INFO_GLOBAL = "__SENTRY_CLOUDFLARE_WORKER__";
8
10
  function isCallToMethod(node, methodName) {
9
11
  if (node.type !== "CallExpression") return false;
10
12
  const callee = node.callee;
@@ -39,8 +41,9 @@ const WRAPPER_METHODS = {
39
41
  * {@link TransformResult.wrappedClasses}.
40
42
  *
41
43
  * Exported (rather than inlined into the plugin) so it can be unit-tested with a
42
- * plain AST and no Vite context. Returns `undefined` when nothing was wrapped and
43
- * there are no already-manually-wrapped classes to report.
44
+ * plain AST and no Vite context. Returns `undefined` when nothing was wrapped,
45
+ * there are no already-manually-wrapped classes to report, and there is no
46
+ * {@link TransformContext.workerInfo} to store.
44
47
  */
45
48
  function applyAutoInstrumentTransforms(code, ast, ctx) {
46
49
  const ms = new magic_string.default(code);
@@ -63,17 +66,13 @@ function applyAutoInstrumentTransforms(code, ast, ctx) {
63
66
  const { wrappedClasses } = state;
64
67
  for (const node of ast.body) if (node.type === "ExportNamedDeclaration") handleNamedExport(node, ctx, state);
65
68
  for (const node of ast.body) if (node.type === "ExportDefaultDeclaration") wrapDefaultExport(node, ctx, state);
66
- if (!state.needsImport) {
67
- if (wrappedClasses.size === 0) return void 0;
68
- return {
69
- code,
70
- map: ms.generateMap({ hires: true }),
71
- wrappedClasses
72
- };
69
+ if (state.needsImport) {
70
+ if (sameWorkerBindings.length > 0) ms.prepend(buildMergedOptionsDeclaration(sameWorkerBindings, ctx.optionsFn, state));
71
+ if (ctx.optionsImport) ms.prepend(ctx.optionsImport);
72
+ ms.prepend(`import * as __SENTRY__ from '${ctx.sentryModule ?? "@sentry/cloudflare"}';\n`);
73
73
  }
74
- if (sameWorkerBindings.length > 0) ms.prepend(buildMergedOptionsDeclaration(sameWorkerBindings, ctx.optionsFn, state));
75
- if (ctx.optionsImport) ms.prepend(ctx.optionsImport);
76
- ms.prepend(`import * as __SENTRY__ from '${ctx.sentryModule ?? "@sentry/cloudflare"}';\n`);
74
+ if (ctx.workerInfo?.name || ctx.workerInfo?.compatibilityDate) ms.prepend(`globalThis.${WORKER_INFO_GLOBAL} = ${JSON.stringify(ctx.workerInfo)};\n`);
75
+ else if (!state.needsImport && wrappedClasses.size === 0) return;
77
76
  return {
78
77
  code: ms.toString(),
79
78
  map: ms.generateMap({ hires: true }),
@@ -88,7 +87,7 @@ function applyAutoInstrumentTransforms(code, ast, ctx) {
88
87
  function buildMergedOptionsDeclaration(sameWorkerBindings, optionsFn, state) {
89
88
  const bindingNames = sameWorkerBindings.filter(({ className }) => state.autoWrapped.has(className)).map(({ bindingName }) => bindingName);
90
89
  if (!bindingNames.length) return `const ${MERGED_OPTIONS_IDENTIFIER} = ${optionsFn};\n`;
91
- const names = bindingNames.map((name) => JSON.stringify(name)).join(", ");
90
+ const names = bindingNames.map((name) => (0, _sentry_core.stringifyForCodeInjection)(name)).join(", ");
92
91
  return `const ${MERGED_OPTIONS_IDENTIFIER} = (env) => { const opts = (${optionsFn})(env); return { ...opts, rpcTracePropagationBindings: [${names}, ...(opts?.rpcTracePropagationBindings ?? [])] }; };\n`;
93
92
  }
94
93
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"transform.js","names":["MagicString","detectWorkerEntrypointClasses","DEFAULT_EXPORT"],"sources":["../../../../src/vite/transform.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport MagicString from 'magic-string';\nimport { DEFAULT_EXPORT, type ExportName, type SameWorkerBinding } from './wranglerConfig';\nimport { detectWorkerEntrypointClasses } from './workerEntrypoint';\n\nconst MERGED_OPTIONS_IDENTIFIER = '__SENTRY_OPTIONS__';\n\n// ---------------------------------------------------------------------------\n// Minimal ESTree node types for the AST nodes we inspect.\n// ---------------------------------------------------------------------------\n\nexport interface BaseNode {\n type: string;\n start: number;\n end: number;\n}\n\nexport interface ProgramBody {\n body: BaseNode[];\n}\n\ninterface IdentifierNode extends BaseNode {\n name: string;\n}\n\ninterface CalleeNode {\n type: string;\n name?: string;\n property?: { type: string; name?: string };\n}\n\ninterface CallExpressionNode extends BaseNode {\n callee?: CalleeNode;\n}\n\ninterface ClassDeclarationNode extends BaseNode {\n id?: IdentifierNode | null;\n}\n\ninterface ExportDefaultNode extends BaseNode {\n declaration: BaseNode;\n}\n\ninterface ExportSpecifierNode extends BaseNode {\n local?: { type: string; name?: string };\n exported?: { type: string; name?: string };\n}\n\ninterface ExportNamedNode extends BaseNode {\n declaration?: BaseNode | null;\n source?: BaseNode | null;\n specifiers?: ExportSpecifierNode[];\n}\n\ninterface VariableDeclaratorNode {\n id?: { type: string; name?: string };\n init?: BaseNode | null;\n}\n\ninterface VariableDeclarationNode extends BaseNode {\n declarations?: VariableDeclaratorNode[];\n}\n\ninterface ImportDeclarationNode extends BaseNode {\n specifiers?: Array<{ local?: { type: string; name?: string } }>;\n}\n\nfunction isCallToMethod(node: BaseNode, methodName: string): boolean {\n if (node.type !== 'CallExpression') return false;\n const callee = (node as CallExpressionNode).callee;\n if (!callee) return false;\n if (callee.type === 'Identifier' && callee.name === methodName) return true;\n return (\n callee.type === 'MemberExpression' && callee.property?.type === 'Identifier' && callee.property.name === methodName\n );\n}\n\n/**\n * The kind of Sentry wrapper to apply to an exported class.\n *\n * `durableObject` and `workflow` are keyed by name from the wrangler config\n * (`durable_objects.bindings`, `workflows`), since those class names are\n * authoritative there. `workerEntrypoint` is different: a worker's own\n * entrypoints aren't enumerated in its config, so they're detected structurally\n * (a class extending `WorkerEntrypoint` from `cloudflare:workers`), with the\n * config providing only a fallback for self-bound entrypoints whose base class\n * lives in another module.\n */\nexport type ClassWrapperKind = 'durableObject' | 'agent' | 'workflow' | 'workerEntrypoint';\n\n/** Specifier name a `export { default as X } from '...'` re-export uses for the source's default. */\nconst DEFAULT_IMPORT = 'default';\n\n/**\n * The `@sentry/cloudflare` helper each wrapper kind emits. All share the same\n * `(optionsCallback, Class)` signature. `WorkerEntrypoint` classes use\n * `withSentry`, which runtime-detects the class type and routes accordingly.\n */\nconst WRAPPER_METHODS: Record<ClassWrapperKind, string> = {\n durableObject: 'instrumentDurableObjectWithSentry',\n agent: 'instrumentAgentWithSentry',\n workflow: 'instrumentWorkflowWithSentry',\n workerEntrypoint: 'withSentry',\n};\n\nexport interface TransformContext {\n /**\n * Exported class name → the kind of Sentry wrapper to apply. Populated from\n * the wrangler config, so the transform can wrap by name without resolving\n * each class's base type.\n */\n classWrappers: Map<string, ClassWrapperKind>;\n /**\n * Local class names detected as `agents` Agents. An Agent is configured as a Durable Object in\n * wrangler, so this upgrades those entries from `durableObject` to `agent`.\n */\n agentClasses?: ReadonlySet<string>;\n optionsFn: string;\n /** Import statement prepended when `optionsFn` references a separate module. */\n optionsImport?: string;\n /** Module the generated code imports `withSentry` and the class wrappers from. Defaults to `@sentry/cloudflare`. */\n sentryModule?: string;\n /** @see {@link import('./wranglerConfig').WranglerConfig.sameWorkerBindings} */\n sameWorkerBindings?: readonly SameWorkerBinding[];\n}\n\nexport interface TransformResult {\n code: string;\n map: ReturnType<MagicString['generateMap']>;\n /**\n * The configured class names that were actually wrapped. Lets the plugin warn\n * about configured classes it could not find, instead of silently leaving\n * them uninstrumented.\n */\n wrappedClasses: Set<string>;\n}\n\n/**\n * Rewrite the worker entry source to wrap its default export with `withSentry`\n * and any configured class export with its matching Sentry wrapper (see\n * {@link TransformContext.classWrappers}, e.g. Durable Object classes with\n * `instrumentDurableObjectWithSentry`).\n *\n * Handles `export class MyDO {}`, the specifier form (`class MyDO {}` …\n * `export { MyDO }` / `export { Foo as MyDO }`), and classes that live in\n * another module (`import { MyDO } from './do'; export { MyDO }` or\n * `export { MyDO } from './do'`). Only star re-exports (`export * from './do'`)\n * are left alone — the plugin warns about those via\n * {@link TransformResult.wrappedClasses}.\n *\n * Exported (rather than inlined into the plugin) so it can be unit-tested with a\n * plain AST and no Vite context. Returns `undefined` when nothing was wrapped and\n * there are no already-manually-wrapped classes to report.\n */\nexport function applyAutoInstrumentTransforms(\n code: string,\n ast: ProgramBody,\n ctx: TransformContext,\n): TransformResult | undefined {\n const ms = new MagicString(code);\n const topLevelClasses = collectTopLevelClasses(ast);\n const sameWorkerBindings = ctx.sameWorkerBindings ?? [];\n const state: TransformState = {\n ms,\n needsImport: false,\n wrappedClasses: new Set<string>(),\n topLevelClasses,\n wrappedLocals: new Map<string, string>(),\n classWrappers: ctx.classWrappers,\n agentClasses: ctx.agentClasses ?? new Set<string>(),\n workerEntrypointClasses: detectWorkerEntrypointClasses(ast),\n // The identifier must be chosen before wrapping, which bindings survive is only known after.\n optionsFn: sameWorkerBindings.length > 0 ? MERGED_OPTIONS_IDENTIFIER : ctx.optionsFn,\n autoWrapped: new Set<ExportName>(),\n manuallyWrappedLocals: collectManuallyWrappedLocals(ast),\n declaringStatements: collectDeclaringStatements(ast),\n };\n const { wrappedClasses } = state;\n\n // Named exports first, regardless of source order: the default-export handler\n // needs to know which local bindings a named export already wrapped, so it can\n // skip a class that is both exported by name and re-exported as default (which\n // would otherwise wrap it twice).\n for (const node of ast.body) {\n if (node.type === 'ExportNamedDeclaration') {\n handleNamedExport(node, ctx, state);\n }\n }\n for (const node of ast.body) {\n if (node.type === 'ExportDefaultDeclaration') {\n wrapDefaultExport(node as ExportDefaultNode, ctx, state);\n }\n }\n\n if (!state.needsImport) {\n // Nothing was rewritten. Still surface any classes found already wrapped\n // manually (via `wrappedClasses`) so the caller doesn't warn about them;\n // return undefined only when there was nothing to report either.\n if (wrappedClasses.size === 0) return undefined;\n return { code, map: ms.generateMap({ hires: true }), wrappedClasses };\n }\n\n // `prepend` inserts before earlier prepends, yielding: Sentry import, options import, declaration.\n if (sameWorkerBindings.length > 0) {\n ms.prepend(buildMergedOptionsDeclaration(sameWorkerBindings, ctx.optionsFn, state));\n }\n if (ctx.optionsImport) ms.prepend(ctx.optionsImport);\n ms.prepend(`import * as __SENTRY__ from '${ctx.sentryModule ?? '@sentry/cloudflare'}';\\n`);\n\n return {\n code: ms.toString(),\n map: ms.generateMap({ hires: true }),\n wrappedClasses,\n };\n}\n\ninterface TransformState {\n ms: MagicString;\n needsImport: boolean;\n wrappedClasses: Set<string>;\n /**\n * Top-level class declarations, exported or not, so specifier exports like\n * `export { MyDO }` can locate the class they refer to.\n */\n topLevelClasses: Map<string, ClassDeclarationNode>;\n /**\n * Local class name → the binding holding its wrapper, so two exports of the same class share one\n * wrapper and a default export of it can be re-pointed.\n */\n wrappedLocals: Map<string, string>;\n /** Class name → wrapper kind, keyed by the *exported* name (from config). */\n classWrappers: Map<string, ClassWrapperKind>;\n /** Local class names detected as `agents` Agents (see {@link TransformContext.agentClasses}). */\n agentClasses: ReadonlySet<string>;\n /**\n * Local class names detected as `WorkerEntrypoint` subclasses in this module,\n * so they can be wrapped without a config entry.\n */\n workerEntrypointClasses: Set<string>;\n optionsFn: string;\n /**\n * Export names wrapped by this transform, so their options can be extended with\n * `rpcTracePropagationBindings`. Hand-wrapped exports stay out, they keep the options they were\n * wrapped with. `wrappedClasses` counts both.\n */\n autoWrapped: Set<ExportName>;\n /**\n * Top-level bindings already assigned an `instrument*WithSentry(...)` result\n * (`const MyDO = instrumentDurableObjectWithSentry(...)`). Exporting one by\n * specifier must report it as wrapped rather than wrap it a second time.\n */\n manuallyWrappedLocals: Set<string>;\n /** Top-level binding name → the statement that declares it. */\n declaringStatements: Map<string, BaseNode>;\n}\n\n/**\n * Builds the callback that merges same-worker binding names into `rpcTracePropagationBindings` at\n * runtime, the options object only exists once the callback runs with `env`. Only bindings whose\n * class this transform wrapped survive, a hand-wrapped class runs on its own options.\n */\nfunction buildMergedOptionsDeclaration(\n sameWorkerBindings: readonly SameWorkerBinding[],\n optionsFn: string,\n state: TransformState,\n): string {\n const bindingNames = sameWorkerBindings\n .filter(({ className }) => state.autoWrapped.has(className))\n .map(({ bindingName }) => bindingName);\n\n if (!bindingNames.length) {\n return `const ${MERGED_OPTIONS_IDENTIFIER} = ${optionsFn};\\n`;\n }\n\n const names = bindingNames.map(name => JSON.stringify(name)).join(', ');\n return (\n `const ${MERGED_OPTIONS_IDENTIFIER} = (env) => { ` +\n `const opts = (${optionsFn})(env); ` +\n `return { ...opts, rpcTracePropagationBindings: [${names}, ...(opts?.rpcTracePropagationBindings ?? [])] }; };\\n`\n );\n}\n\n/**\n * Resolve the wrapper kind for a class export.\n *\n * Config (`classWrappers`) wins — it's authoritative for Durable Objects and\n * Workflows, and provides the self-binding fallback for WorkerEntrypoints whose\n * base class this module can't see. Otherwise a structurally-detected\n * `WorkerEntrypoint` subclass (matched by its *local* name) gets wrapped with\n * `withSentry`.\n *\n * `localName` is the binding **in this module** the export refers to, and must be\n * left undefined for `export { X } from '...'`: there the specifier's name belongs\n * to the source module, so matching it against anything detected here would wrap a\n * class that merely shares a name.\n *\n * The one case where config is refined rather than obeyed is an `agents` Agent:\n * it *is* a Durable Object, so wrangler can only ever describe it as one, and\n * only the detected base chain distinguishes the two.\n */\nfunction resolveWrapperKind(\n exportedName: string,\n localName: string | undefined,\n state: TransformState,\n): ClassWrapperKind | undefined {\n const configured = state.classWrappers.get(exportedName);\n\n if (\n configured === 'durableObject' &&\n ((localName && state.agentClasses.has(localName)) || state.agentClasses.has(exportedName))\n ) {\n return 'agent';\n }\n\n if (configured) return configured;\n if (localName && state.workerEntrypointClasses.has(localName)) return 'workerEntrypoint';\n return undefined;\n}\n\n/**\n * Top-level `const X = instrument*WithSentry(...)` bindings — a hand-wrapped class that is exported\n * separately (`export { X }`) rather than inline.\n */\nfunction collectManuallyWrappedLocals(ast: ProgramBody): Set<string> {\n const wrapperMethods = Object.values(WRAPPER_METHODS);\n const locals = new Set<string>();\n\n for (const node of ast.body) {\n const declaration = declarationOf(node);\n if (declaration?.type !== 'VariableDeclaration') continue;\n for (const declarator of (declaration as VariableDeclarationNode).declarations ?? []) {\n const name = declarator.id?.type === 'Identifier' ? declarator.id.name : undefined;\n const init = declarator.init;\n if (name && init && wrapperMethods.some(method => isCallToMethod(init, method))) {\n locals.add(name);\n }\n }\n }\n\n return locals;\n}\n\nfunction collectDeclaringStatements(ast: ProgramBody): Map<string, BaseNode> {\n const statements = new Map<string, BaseNode>();\n for (const node of ast.body) {\n const declaration = declarationOf(node);\n if (!declaration) continue;\n const ids =\n declaration.type === 'VariableDeclaration'\n ? ((declaration as VariableDeclarationNode).declarations ?? []).map(declarator => declarator.id)\n : declaration.type === 'ImportDeclaration'\n ? ((declaration as ImportDeclarationNode).specifiers ?? []).map(specifier => specifier.local)\n : [(declaration as ClassDeclarationNode).id];\n for (const id of ids) {\n if (id?.type === 'Identifier' && id.name) statements.set(id.name, node);\n }\n }\n return statements;\n}\n\nfunction collectTopLevelClasses(ast: ProgramBody): Map<string, ClassDeclarationNode> {\n const classes = new Map<string, ClassDeclarationNode>();\n for (const node of ast.body) {\n const declaration = declarationOf(node);\n if (declaration?.type !== 'ClassDeclaration') continue;\n const classNode = declaration as ClassDeclarationNode;\n if (classNode.id?.name) classes.set(classNode.id.name, classNode);\n }\n return classes;\n}\n\n/** The declaration a top-level statement makes, looking through `export` (`export const x = ...`). */\nfunction declarationOf(node: BaseNode): BaseNode | null | undefined {\n return node.type === 'ExportNamedDeclaration' ? (node as ExportNamedNode).declaration : node;\n}\n\nfunction wrapDefaultExport(node: ExportDefaultNode, ctx: TransformContext, state: TransformState): void {\n const decl = node.declaration;\n\n // Already wrapped — leave it alone\n if (isCallToMethod(decl, 'withSentry')) return;\n\n // `export default Foo` where `Foo` is a local class already wrapped by a named\n // export (e.g. a self-bound WorkerEntrypoint also used as the default handler).\n // Wrapping again would produce `withSentry(withSentry(...))`, so the default\n // export is re-pointed at the wrapper binding the named export created.\n if (decl.type === 'Identifier') {\n const wrappedName = state.wrappedLocals.get((decl as IdentifierNode).name);\n if (wrappedName) {\n state.ms.overwrite(decl.start, decl.end, wrappedName);\n state.autoWrapped.add(DEFAULT_EXPORT);\n return;\n }\n }\n\n // MagicString positions are always relative to the original source. Only the `export default`\n // keywords are replaced, so parentheses around the expression stay.\n const source = state.ms.original;\n const keywordsEnd = exportDefaultKeywordsEnd(source, node.start);\n const declaredName =\n decl.type === 'ClassDeclaration' || decl.type === 'FunctionDeclaration'\n ? (decl as ClassDeclarationNode).id?.name\n : undefined;\n\n // As with `export { handler as default }`, the export is set in two steps: bound as-is where the\n // original statement set it, then rebound at the end of the module to the wrapper, which sees\n // methods added in between. See `wrapDefaultSpecifier`.\n let wrapped = '__SENTRY_DEFAULT_EXPORT__';\n if (declaredName) {\n // `export default class Handler {}`: the declaration stays, so `Handler` stays bound in the module.\n state.ms.remove(node.start, decl.start);\n state.ms.appendLeft(node.end, `\\nvar __SENTRY_DEFAULT_EXPORT__ = ${declaredName};`);\n wrapped = declaredName;\n } else if (isAnonymousFunctionOrClass(decl)) {\n // As a property value, the class or function gets the name `default`, as `export default` gives it.\n const hasSemicolon = source[node.end - 1] === ';';\n state.ms.overwrite(node.start, keywordsEnd, 'var __SENTRY_DEFAULT_EXPORT__ = { default:');\n state.ms.appendLeft(hasSemicolon ? node.end - 1 : node.end, hasSemicolon ? ' }.default' : ' }.default;');\n } else {\n state.ms.overwrite(node.start, keywordsEnd, 'var __SENTRY_DEFAULT_EXPORT__ =');\n }\n state.ms.appendLeft(node.end, '\\nexport { __SENTRY_DEFAULT_EXPORT__ as default };');\n state.ms.append(`\\n__SENTRY_DEFAULT_EXPORT__ = __SENTRY__.withSentry(${state.optionsFn}, ${wrapped});`);\n state.needsImport = true;\n state.autoWrapped.add(DEFAULT_EXPORT);\n}\n\n/**\n * Offset just past the `default` keyword of the `export default` statement at `start`. Comments can\n * sit between `export`, `default` and the expression, and may themselves contain the word `default`.\n */\nfunction exportDefaultKeywordsEnd(source: string, start: number): number {\n let index = start + 'export'.length;\n while (index < source.length && !source.startsWith('default', index)) {\n if (source.startsWith('//', index)) {\n const lineEnd = source.indexOf('\\n', index);\n index = lineEnd === -1 ? source.length : lineEnd;\n } else if (source.startsWith('/*', index)) {\n const commentEnd = source.indexOf('*/', index + 2);\n index = commentEnd === -1 ? source.length : commentEnd + 2;\n } else {\n index++;\n }\n }\n return index + 'default'.length;\n}\n\nfunction isAnonymousFunctionOrClass(node: BaseNode): boolean {\n if (node.type === 'ArrowFunctionExpression') return true;\n const isFunctionOrClass = [\n 'FunctionExpression',\n 'FunctionDeclaration',\n 'ClassExpression',\n 'ClassDeclaration',\n ].includes(node.type);\n return isFunctionOrClass && !(node as ClassDeclarationNode).id;\n}\n\nfunction handleNamedExport(node: ExportNamedNode, ctx: TransformContext, state: TransformState): void {\n const decl = node.declaration;\n\n // ---- Manually wrapped class export ----\n // `export const MyDO = instrumentDurableObjectWithSentry(...)` — count it\n // as wrapped so the plugin doesn't warn about it, but leave it alone.\n if (decl?.type === 'VariableDeclaration') {\n collectManuallyWrappedClassExports(decl, ctx, state);\n return;\n }\n\n // ---- Named class export matching a configured binding ----\n if (decl?.type === 'ClassDeclaration') {\n wrapInlineClassExport(node, decl, ctx, state);\n return;\n }\n\n // ---- Specifier export (`export { Foo as MyDO }`, `export { MyDO } from './do'`) ----\n wrapSpecifierExports(node, ctx, state);\n}\n\nfunction collectManuallyWrappedClassExports(\n varDecl: VariableDeclarationNode,\n ctx: TransformContext,\n state: TransformState,\n): void {\n for (const declarator of varDecl.declarations ?? []) {\n const name = declarator.id?.type === 'Identifier' ? declarator.id.name : undefined;\n const kind = name ? ctx.classWrappers.get(name) : undefined;\n if (!name || !kind || !declarator.init) continue;\n\n // A hand-wrapped Agent is configured as a Durable Object, so accept either helper there —\n // otherwise an already-instrumented Agent would be reported as unwrapped.\n const accepted =\n kind === 'durableObject' ? [WRAPPER_METHODS.durableObject, WRAPPER_METHODS.agent] : [WRAPPER_METHODS[kind]];\n\n if (accepted.some(method => isCallToMethod(declarator.init as BaseNode, method))) {\n state.wrappedClasses.add(name);\n }\n }\n}\n\nfunction wrapInlineClassExport(\n exportNode: ExportNamedNode,\n classDecl: ClassDeclarationNode,\n ctx: TransformContext,\n state: TransformState,\n): void {\n const classId = classDecl.id;\n // Inline export: the exported name and the local class name are the same.\n const kind = classId ? resolveWrapperKind(classId.name, classId.name, state) : undefined;\n if (!classId || !kind) return;\n\n const className = classId.name;\n\n // Strip the `export ` keyword\n state.ms.overwrite(exportNode.start, classDecl.start, '');\n\n const wrappedName = wrapLocalClass(className, classDecl, kind, state);\n state.ms.appendLeft(exportNode.end, `export { ${wrappedName} as ${className} };\\n`);\n\n state.wrappedClasses.add(className);\n state.autoWrapped.add(className);\n}\n\n/**\n * Wrap a class declared in this module and return the binding that holds the wrapper.\n *\n * The declaration is left exactly as written. Only the *export* has to become the wrapper, so the\n * wrapper gets its own binding and the export is aliased to it, the same shape as the documented\n * manual `instrument*WithSentry` pattern and the cross-module re-export path below. Renaming the\n * declaration instead (`class __SENTRY_ORIGINAL_MyAgent__`) would also rename what the class reports\n * as `Function.prototype.name`, which libraries read to identify the user's class: `@cloudflare/think`\n * hands `this.constructor.name` to the AI SDK as the telemetry `functionId`, and that surfaced as a\n * `gen_ai.invoke_agent __SENTRY_ORIGINAL_MyAgent__` span.\n */\nfunction wrapLocalClass(\n localName: string,\n localClass: ClassDeclarationNode,\n kind: ClassWrapperKind,\n state: TransformState,\n): string {\n const existing = state.wrappedLocals.get(localName);\n if (existing) return existing;\n\n const wrappedName = `__SENTRY_WRAPPED_${localName}__`;\n state.wrappedLocals.set(localName, wrappedName);\n state.ms.appendLeft(\n localClass.end,\n `\\nconst ${wrappedName} = __SENTRY__.${WRAPPER_METHODS[kind]}(${state.optionsFn}, ${localName});\\n`,\n );\n state.needsImport = true;\n return wrappedName;\n}\n\n/**\n * Wrap the configured classes an `export { ... }` statement names.\n *\n * Each such specifier is re-pointed at a binding holding the wrapper, which means rebuilding the\n * statement; specifiers this plugin has no business touching are carried over verbatim. For a class\n * declared in this module the wrapper binding follows the declaration (see {@link wrapLocalClass}).\n * A class that lives in **another** module — imported and re-exported, or re-exported directly — is\n * first bound under a private name, since an import binding cannot be reassigned and the `from` form\n * has no local binding at all.\n */\nfunction wrapSpecifierExports(node: ExportNamedNode, ctx: TransformContext, state: TransformState): void {\n const specifiers = node.specifiers ?? [];\n if (specifiers.length === 0) return;\n\n const sourceLiteral = node.source ? state.ms.original.slice(node.source.start, node.source.end) : undefined;\n\n const prelude: string[] = [];\n const wrappedPairs: string[] = [];\n const kept: string[] = [];\n\n for (const specifier of specifiers) {\n const pair = wrapSpecifier(specifier, sourceLiteral, ctx, state, prelude);\n if (pair) {\n wrappedPairs.push(pair);\n } else {\n kept.push(state.ms.original.slice(specifier.start, specifier.end));\n }\n }\n\n if (wrappedPairs.length === 0) return;\n\n const statements = [...prelude, `export { ${wrappedPairs.join(', ')} };`];\n if (kept.length > 0) {\n const clause = `export { ${kept.join(', ')} }`;\n statements.push(sourceLiteral ? `${clause} from ${sourceLiteral};` : `${clause};`);\n }\n state.ms.overwrite(node.start, node.end, statements.join('\\n'));\n}\n\n/**\n * `export { handler as default }`, the form bundlers emit for a default export. The export is set\n * in two steps. Right after `handler` is declared, it is bound to `handler` as-is, so a circular\n * import that reads it during module evaluation gets the handler, as before the transform. At the\n * end of the module, it is rebound to the wrapper, so a handler assigned or given methods later is\n * wrapped as it ends up. The binding is a `var`: a read before `handler` is declared gets\n * `undefined`, as it would from the bundler's own `var`, where a `const` would throw and stop the\n * Worker from starting.\n */\nfunction wrapDefaultSpecifier(localName: string, state: TransformState): string | undefined {\n if (state.manuallyWrappedLocals.has(localName)) return undefined;\n\n // Same as `export default Foo`: re-point at the wrapper a named export already made.\n const wrappedName = state.wrappedLocals.get(localName);\n if (wrappedName) {\n state.autoWrapped.add(DEFAULT_EXPORT);\n return `${wrappedName} as default`;\n }\n\n const declaringStatement = state.declaringStatements.get(localName);\n if (declaringStatement) {\n state.ms.appendLeft(declaringStatement.end, `\\nvar __SENTRY_DEFAULT_EXPORT__ = ${localName};`);\n }\n state.ms.append(\n `\\n${declaringStatement ? '' : 'var '}__SENTRY_DEFAULT_EXPORT__ = __SENTRY__.withSentry(${state.optionsFn}, ${localName});`,\n );\n state.needsImport = true;\n state.autoWrapped.add(DEFAULT_EXPORT);\n return '__SENTRY_DEFAULT_EXPORT__ as default';\n}\n\n/**\n * `export { default } from './handler'`. The handler may already be wrapped in its own module,\n * which this transform cannot see, so the emitted guard returns such a handler as-is.\n *\n * The original re-export is a live binding to the handler module's export, but the wrapper is not\n * set until this module's body runs. A circular import that reads the default export before then\n * gets `undefined` instead of the handler. The binding is a `var` so that the read does not throw,\n * as a `const` would, and stop the Worker from starting. See `wrapDefaultSpecifier`.\n */\nfunction wrapDefaultReexport(\n localName: string,\n sourceLiteral: string,\n state: TransformState,\n prelude: string[],\n): string {\n const target = '__SENTRY_REEXPORT_default__';\n prelude.push(\n localName === DEFAULT_IMPORT\n ? `import ${target} from ${sourceLiteral};`\n : `import { ${localName} as ${target} } from ${sourceLiteral};`,\n `var __SENTRY_DEFAULT_EXPORT__ = __SENTRY__._INTERNAL_wrapUnlessInstrumented(__SENTRY__.withSentry, ${state.optionsFn}, ${target});`,\n );\n state.needsImport = true;\n state.autoWrapped.add(DEFAULT_EXPORT);\n return '__SENTRY_DEFAULT_EXPORT__ as default';\n}\n\n/**\n * Handle one export specifier, returning the `Wrapped as Exported` pair to emit for a class that\n * gets wrapped. The import/wrapper statements a cross-module pair depends on are pushed onto\n * `prelude`; a local class's wrapper binding is emitted after its declaration instead.\n *\n * Returns `undefined` when the specifier can stay exactly as written: it doesn't name a configured\n * class, or the binding is already hand-wrapped.\n */\nfunction wrapSpecifier(\n specifier: ExportSpecifierNode,\n sourceLiteral: string | undefined,\n ctx: TransformContext,\n state: TransformState,\n prelude: string[],\n): string | undefined {\n const exportedName =\n specifier.type === 'ExportSpecifier' && specifier.exported?.type === 'Identifier'\n ? specifier.exported.name\n : undefined;\n const localName = specifier.local?.type === 'Identifier' ? specifier.local.name : undefined;\n // With a `from` clause the specifier names an export of the *source* module, not a binding here.\n const kind = exportedName\n ? resolveWrapperKind(exportedName, sourceLiteral ? undefined : localName, state)\n : undefined;\n\n if (!exportedName || !localName) return undefined;\n if (!kind) {\n if (exportedName !== DEFAULT_IMPORT) return undefined;\n return sourceLiteral\n ? wrapDefaultReexport(localName, sourceLiteral, state, prelude)\n : wrapDefaultSpecifier(localName, state);\n }\n\n // Without a `from` clause the specifier points at a module-local binding.\n if (!sourceLiteral) {\n const localClass = state.topLevelClasses.get(localName);\n\n if (localClass?.id) {\n const wrappedName = wrapLocalClass(localName, localClass, kind, state);\n state.wrappedClasses.add(exportedName);\n return `${wrappedName} as ${exportedName}`;\n }\n\n if (state.manuallyWrappedLocals.has(localName)) {\n state.wrappedClasses.add(exportedName);\n return undefined;\n }\n }\n\n // The class comes from another module: bind it under a private name (for the `from` form, which\n // has no local binding at all), wrap that, and export the wrapper under the configured name.\n let target = localName;\n\n if (sourceLiteral) {\n target = `__SENTRY_REEXPORT_${exportedName}__`;\n prelude.push(\n localName === DEFAULT_IMPORT\n ? `import ${target} from ${sourceLiteral};`\n : `import { ${localName} as ${target} } from ${sourceLiteral};`,\n );\n }\n\n const wrappedName = `__SENTRY_WRAPPED_${exportedName}__`;\n\n // The class may already be hand-wrapped in its own module, which this transform cannot see. The\n // emitted guard returns such a class as-is instead of nesting a second wrapper around it.\n prelude.push(\n `const ${wrappedName} = __SENTRY__._INTERNAL_wrapUnlessInstrumented(__SENTRY__.${WRAPPER_METHODS[kind]}, ${state.optionsFn}, ${target});`,\n );\n state.wrappedClasses.add(exportedName);\n state.autoWrapped.add(exportedName);\n state.needsImport = true;\n\n return `${wrappedName} as ${exportedName}`;\n}\n"],"mappings":";;;;;;AAKA,MAAM,4BAA4B;AA8DlC,SAAS,eAAe,MAAgB,YAA6B;CACnE,IAAI,KAAK,SAAS,kBAAkB,OAAO;CAC3C,MAAM,SAAU,KAA4B;CAC5C,IAAI,CAAC,QAAQ,OAAO;CACpB,IAAI,OAAO,SAAS,gBAAgB,OAAO,SAAS,YAAY,OAAO;CACvE,OACE,OAAO,SAAS,sBAAsB,OAAO,UAAU,SAAS,gBAAgB,OAAO,SAAS,SAAS;AAE7G;;AAgBA,MAAM,iBAAiB;;;;;;AAOvB,MAAM,kBAAoD;CACxD,eAAe;CACf,OAAO;CACP,UAAU;CACV,kBAAkB;AACpB;;;;;;;;;;;;;;;;;;AAmDA,SAAgB,8BACd,MACA,KACA,KAC6B;CAC7B,MAAM,KAAK,IAAIA,aAAAA,QAAY,IAAI;CAC/B,MAAM,kBAAkB,uBAAuB,GAA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Q,KACN,cAAc,iBACV,UAAU,OAAO,QAAQ,cAAc,KACvC,YAAY,UAAU,MAAM,OAAO,UAAU,cAAc,EACjE;CACF;CAEA,MAAM,cAAc,oBAAoB,aAAa;CAIrD,QAAQ,KACN,SAAS,YAAY,4DAA4D,gBAAgB,MAAM,IAAI,MAAM,UAAU,IAAI,OAAO,GACxI;CACA,MAAM,eAAe,IAAI,YAAY;CACrC,MAAM,YAAY,IAAI,YAAY;CAClC,MAAM,cAAc;CAEpB,OAAO,GAAG,YAAY,MAAM;AAC9B"}
1
+ {"version":3,"file":"transform.js","names":["MagicString","detectWorkerEntrypointClasses","stringifyForCodeInjection","DEFAULT_EXPORT"],"sources":["../../../../src/vite/transform.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport MagicString from 'magic-string';\nimport { DEFAULT_EXPORT, type ExportName, type SameWorkerBinding } from './wranglerConfig';\nimport { detectWorkerEntrypointClasses } from './workerEntrypoint';\nimport { stringifyForCodeInjection } from '@sentry/core';\n\nconst MERGED_OPTIONS_IDENTIFIER = '__SENTRY_OPTIONS__';\n\n// Read by `CloudflareClient` for the default `serverName` and the runtime version.\nconst WORKER_INFO_GLOBAL = '__SENTRY_CLOUDFLARE_WORKER__';\n\n// ---------------------------------------------------------------------------\n// Minimal ESTree node types for the AST nodes we inspect.\n// ---------------------------------------------------------------------------\n\nexport interface BaseNode {\n type: string;\n start: number;\n end: number;\n}\n\nexport interface ProgramBody {\n body: BaseNode[];\n}\n\ninterface IdentifierNode extends BaseNode {\n name: string;\n}\n\ninterface CalleeNode {\n type: string;\n name?: string;\n property?: { type: string; name?: string };\n}\n\ninterface CallExpressionNode extends BaseNode {\n callee?: CalleeNode;\n}\n\ninterface ClassDeclarationNode extends BaseNode {\n id?: IdentifierNode | null;\n}\n\ninterface ExportDefaultNode extends BaseNode {\n declaration: BaseNode;\n}\n\ninterface ExportSpecifierNode extends BaseNode {\n local?: { type: string; name?: string };\n exported?: { type: string; name?: string };\n}\n\ninterface ExportNamedNode extends BaseNode {\n declaration?: BaseNode | null;\n source?: BaseNode | null;\n specifiers?: ExportSpecifierNode[];\n}\n\ninterface VariableDeclaratorNode {\n id?: { type: string; name?: string };\n init?: BaseNode | null;\n}\n\ninterface VariableDeclarationNode extends BaseNode {\n declarations?: VariableDeclaratorNode[];\n}\n\ninterface ImportDeclarationNode extends BaseNode {\n specifiers?: Array<{ local?: { type: string; name?: string } }>;\n}\n\nfunction isCallToMethod(node: BaseNode, methodName: string): boolean {\n if (node.type !== 'CallExpression') return false;\n const callee = (node as CallExpressionNode).callee;\n if (!callee) return false;\n if (callee.type === 'Identifier' && callee.name === methodName) return true;\n return (\n callee.type === 'MemberExpression' && callee.property?.type === 'Identifier' && callee.property.name === methodName\n );\n}\n\n/**\n * The kind of Sentry wrapper to apply to an exported class.\n *\n * `durableObject` and `workflow` are keyed by name from the wrangler config\n * (`durable_objects.bindings`, `workflows`), since those class names are\n * authoritative there. `workerEntrypoint` is different: a worker's own\n * entrypoints aren't enumerated in its config, so they're detected structurally\n * (a class extending `WorkerEntrypoint` from `cloudflare:workers`), with the\n * config providing only a fallback for self-bound entrypoints whose base class\n * lives in another module.\n */\nexport type ClassWrapperKind = 'durableObject' | 'agent' | 'workflow' | 'workerEntrypoint';\n\n/** Specifier name a `export { default as X } from '...'` re-export uses for the source's default. */\nconst DEFAULT_IMPORT = 'default';\n\n/**\n * The `@sentry/cloudflare` helper each wrapper kind emits. All share the same\n * `(optionsCallback, Class)` signature. `WorkerEntrypoint` classes use\n * `withSentry`, which runtime-detects the class type and routes accordingly.\n */\nconst WRAPPER_METHODS: Record<ClassWrapperKind, string> = {\n durableObject: 'instrumentDurableObjectWithSentry',\n agent: 'instrumentAgentWithSentry',\n workflow: 'instrumentWorkflowWithSentry',\n workerEntrypoint: 'withSentry',\n};\n\nexport interface TransformContext {\n /**\n * Exported class name → the kind of Sentry wrapper to apply. Populated from\n * the wrangler config, so the transform can wrap by name without resolving\n * each class's base type.\n */\n classWrappers: Map<string, ClassWrapperKind>;\n /**\n * Local class names detected as `agents` Agents. An Agent is configured as a Durable Object in\n * wrangler, so this upgrades those entries from `durableObject` to `agent`.\n */\n agentClasses?: ReadonlySet<string>;\n optionsFn: string;\n /** Import statement prepended when `optionsFn` references a separate module. */\n optionsImport?: string;\n /** Module the generated code imports `withSentry` and the class wrappers from. Defaults to `@sentry/cloudflare`. */\n sentryModule?: string;\n /** @see {@link import('./wranglerConfig').WranglerConfig.sameWorkerBindings} */\n sameWorkerBindings?: readonly SameWorkerBinding[];\n /**\n * The Worker name and compatibility date, stored on `globalThis` as the default `serverName` and\n * the runtime version. The entry stores them also when nothing is wrapped, so hand-wrapped\n * handlers get them too.\n */\n workerInfo?: { name?: string; compatibilityDate?: string };\n}\n\nexport interface TransformResult {\n code: string;\n map: ReturnType<MagicString['generateMap']>;\n /**\n * The configured class names that were actually wrapped. Lets the plugin warn\n * about configured classes it could not find, instead of silently leaving\n * them uninstrumented.\n */\n wrappedClasses: Set<string>;\n}\n\n/**\n * Rewrite the worker entry source to wrap its default export with `withSentry`\n * and any configured class export with its matching Sentry wrapper (see\n * {@link TransformContext.classWrappers}, e.g. Durable Object classes with\n * `instrumentDurableObjectWithSentry`).\n *\n * Handles `export class MyDO {}`, the specifier form (`class MyDO {}` …\n * `export { MyDO }` / `export { Foo as MyDO }`), and classes that live in\n * another module (`import { MyDO } from './do'; export { MyDO }` or\n * `export { MyDO } from './do'`). Only star re-exports (`export * from './do'`)\n * are left alone — the plugin warns about those via\n * {@link TransformResult.wrappedClasses}.\n *\n * Exported (rather than inlined into the plugin) so it can be unit-tested with a\n * plain AST and no Vite context. Returns `undefined` when nothing was wrapped,\n * there are no already-manually-wrapped classes to report, and there is no\n * {@link TransformContext.workerInfo} to store.\n */\nexport function applyAutoInstrumentTransforms(\n code: string,\n ast: ProgramBody,\n ctx: TransformContext,\n): TransformResult | undefined {\n const ms = new MagicString(code);\n const topLevelClasses = collectTopLevelClasses(ast);\n const sameWorkerBindings = ctx.sameWorkerBindings ?? [];\n const state: TransformState = {\n ms,\n needsImport: false,\n wrappedClasses: new Set<string>(),\n topLevelClasses,\n wrappedLocals: new Map<string, string>(),\n classWrappers: ctx.classWrappers,\n agentClasses: ctx.agentClasses ?? new Set<string>(),\n workerEntrypointClasses: detectWorkerEntrypointClasses(ast),\n // The identifier must be chosen before wrapping, which bindings survive is only known after.\n optionsFn: sameWorkerBindings.length > 0 ? MERGED_OPTIONS_IDENTIFIER : ctx.optionsFn,\n autoWrapped: new Set<ExportName>(),\n manuallyWrappedLocals: collectManuallyWrappedLocals(ast),\n declaringStatements: collectDeclaringStatements(ast),\n };\n const { wrappedClasses } = state;\n\n // Named exports first, regardless of source order: the default-export handler\n // needs to know which local bindings a named export already wrapped, so it can\n // skip a class that is both exported by name and re-exported as default (which\n // would otherwise wrap it twice).\n for (const node of ast.body) {\n if (node.type === 'ExportNamedDeclaration') {\n handleNamedExport(node, ctx, state);\n }\n }\n for (const node of ast.body) {\n if (node.type === 'ExportDefaultDeclaration') {\n wrapDefaultExport(node as ExportDefaultNode, ctx, state);\n }\n }\n\n if (state.needsImport) {\n // `prepend` inserts before earlier prepends, yielding: Sentry import, options import, declaration.\n if (sameWorkerBindings.length > 0) {\n ms.prepend(buildMergedOptionsDeclaration(sameWorkerBindings, ctx.optionsFn, state));\n }\n if (ctx.optionsImport) ms.prepend(ctx.optionsImport);\n ms.prepend(`import * as __SENTRY__ from '${ctx.sentryModule ?? '@sentry/cloudflare'}';\\n`);\n }\n\n if (ctx.workerInfo?.name || ctx.workerInfo?.compatibilityDate) {\n ms.prepend(`globalThis.${WORKER_INFO_GLOBAL} = ${JSON.stringify(ctx.workerInfo)};\\n`);\n } else if (!state.needsImport && wrappedClasses.size === 0) {\n // Nothing was rewritten. Classes found already wrapped manually are still\n // reported (via `wrappedClasses`) so the caller doesn't warn about them.\n return undefined;\n }\n\n return {\n code: ms.toString(),\n map: ms.generateMap({ hires: true }),\n wrappedClasses,\n };\n}\n\ninterface TransformState {\n ms: MagicString;\n needsImport: boolean;\n wrappedClasses: Set<string>;\n /**\n * Top-level class declarations, exported or not, so specifier exports like\n * `export { MyDO }` can locate the class they refer to.\n */\n topLevelClasses: Map<string, ClassDeclarationNode>;\n /**\n * Local class name → the binding holding its wrapper, so two exports of the same class share one\n * wrapper and a default export of it can be re-pointed.\n */\n wrappedLocals: Map<string, string>;\n /** Class name → wrapper kind, keyed by the *exported* name (from config). */\n classWrappers: Map<string, ClassWrapperKind>;\n /** Local class names detected as `agents` Agents (see {@link TransformContext.agentClasses}). */\n agentClasses: ReadonlySet<string>;\n /**\n * Local class names detected as `WorkerEntrypoint` subclasses in this module,\n * so they can be wrapped without a config entry.\n */\n workerEntrypointClasses: Set<string>;\n optionsFn: string;\n /**\n * Export names wrapped by this transform, so their options can be extended with\n * `rpcTracePropagationBindings`. Hand-wrapped exports stay out, they keep the options they were\n * wrapped with. `wrappedClasses` counts both.\n */\n autoWrapped: Set<ExportName>;\n /**\n * Top-level bindings already assigned an `instrument*WithSentry(...)` result\n * (`const MyDO = instrumentDurableObjectWithSentry(...)`). Exporting one by\n * specifier must report it as wrapped rather than wrap it a second time.\n */\n manuallyWrappedLocals: Set<string>;\n /** Top-level binding name → the statement that declares it. */\n declaringStatements: Map<string, BaseNode>;\n}\n\n/**\n * Builds the callback that merges same-worker binding names into `rpcTracePropagationBindings` at\n * runtime, the options object only exists once the callback runs with `env`. Only bindings whose\n * class this transform wrapped survive, a hand-wrapped class runs on its own options.\n */\nfunction buildMergedOptionsDeclaration(\n sameWorkerBindings: readonly SameWorkerBinding[],\n optionsFn: string,\n state: TransformState,\n): string {\n const bindingNames = sameWorkerBindings\n .filter(({ className }) => state.autoWrapped.has(className))\n .map(({ bindingName }) => bindingName);\n\n if (!bindingNames.length) {\n return `const ${MERGED_OPTIONS_IDENTIFIER} = ${optionsFn};\\n`;\n }\n\n const names = bindingNames.map(name => stringifyForCodeInjection(name)).join(', ');\n return (\n `const ${MERGED_OPTIONS_IDENTIFIER} = (env) => { ` +\n `const opts = (${optionsFn})(env); ` +\n `return { ...opts, rpcTracePropagationBindings: [${names}, ...(opts?.rpcTracePropagationBindings ?? [])] }; };\\n`\n );\n}\n\n/**\n * Resolve the wrapper kind for a class export.\n *\n * Config (`classWrappers`) wins — it's authoritative for Durable Objects and\n * Workflows, and provides the self-binding fallback for WorkerEntrypoints whose\n * base class this module can't see. Otherwise a structurally-detected\n * `WorkerEntrypoint` subclass (matched by its *local* name) gets wrapped with\n * `withSentry`.\n *\n * `localName` is the binding **in this module** the export refers to, and must be\n * left undefined for `export { X } from '...'`: there the specifier's name belongs\n * to the source module, so matching it against anything detected here would wrap a\n * class that merely shares a name.\n *\n * The one case where config is refined rather than obeyed is an `agents` Agent:\n * it *is* a Durable Object, so wrangler can only ever describe it as one, and\n * only the detected base chain distinguishes the two.\n */\nfunction resolveWrapperKind(\n exportedName: string,\n localName: string | undefined,\n state: TransformState,\n): ClassWrapperKind | undefined {\n const configured = state.classWrappers.get(exportedName);\n\n if (\n configured === 'durableObject' &&\n ((localName && state.agentClasses.has(localName)) || state.agentClasses.has(exportedName))\n ) {\n return 'agent';\n }\n\n if (configured) return configured;\n if (localName && state.workerEntrypointClasses.has(localName)) return 'workerEntrypoint';\n return undefined;\n}\n\n/**\n * Top-level `const X = instrument*WithSentry(...)` bindings — a hand-wrapped class that is exported\n * separately (`export { X }`) rather than inline.\n */\nfunction collectManuallyWrappedLocals(ast: ProgramBody): Set<string> {\n const wrapperMethods = Object.values(WRAPPER_METHODS);\n const locals = new Set<string>();\n\n for (const node of ast.body) {\n const declaration = declarationOf(node);\n if (declaration?.type !== 'VariableDeclaration') continue;\n for (const declarator of (declaration as VariableDeclarationNode).declarations ?? []) {\n const name = declarator.id?.type === 'Identifier' ? declarator.id.name : undefined;\n const init = declarator.init;\n if (name && init && wrapperMethods.some(method => isCallToMethod(init, method))) {\n locals.add(name);\n }\n }\n }\n\n return locals;\n}\n\nfunction collectDeclaringStatements(ast: ProgramBody): Map<string, BaseNode> {\n const statements = new Map<string, BaseNode>();\n for (const node of ast.body) {\n const declaration = declarationOf(node);\n if (!declaration) continue;\n const ids =\n declaration.type === 'VariableDeclaration'\n ? ((declaration as VariableDeclarationNode).declarations ?? []).map(declarator => declarator.id)\n : declaration.type === 'ImportDeclaration'\n ? ((declaration as ImportDeclarationNode).specifiers ?? []).map(specifier => specifier.local)\n : [(declaration as ClassDeclarationNode).id];\n for (const id of ids) {\n if (id?.type === 'Identifier' && id.name) statements.set(id.name, node);\n }\n }\n return statements;\n}\n\nfunction collectTopLevelClasses(ast: ProgramBody): Map<string, ClassDeclarationNode> {\n const classes = new Map<string, ClassDeclarationNode>();\n for (const node of ast.body) {\n const declaration = declarationOf(node);\n if (declaration?.type !== 'ClassDeclaration') continue;\n const classNode = declaration as ClassDeclarationNode;\n if (classNode.id?.name) classes.set(classNode.id.name, classNode);\n }\n return classes;\n}\n\n/** The declaration a top-level statement makes, looking through `export` (`export const x = ...`). */\nfunction declarationOf(node: BaseNode): BaseNode | null | undefined {\n return node.type === 'ExportNamedDeclaration' ? (node as ExportNamedNode).declaration : node;\n}\n\nfunction wrapDefaultExport(node: ExportDefaultNode, ctx: TransformContext, state: TransformState): void {\n const decl = node.declaration;\n\n // Already wrapped — leave it alone\n if (isCallToMethod(decl, 'withSentry')) return;\n\n // `export default Foo` where `Foo` is a local class already wrapped by a named\n // export (e.g. a self-bound WorkerEntrypoint also used as the default handler).\n // Wrapping again would produce `withSentry(withSentry(...))`, so the default\n // export is re-pointed at the wrapper binding the named export created.\n if (decl.type === 'Identifier') {\n const wrappedName = state.wrappedLocals.get((decl as IdentifierNode).name);\n if (wrappedName) {\n state.ms.overwrite(decl.start, decl.end, wrappedName);\n state.autoWrapped.add(DEFAULT_EXPORT);\n return;\n }\n }\n\n // MagicString positions are always relative to the original source. Only the `export default`\n // keywords are replaced, so parentheses around the expression stay.\n const source = state.ms.original;\n const keywordsEnd = exportDefaultKeywordsEnd(source, node.start);\n const declaredName =\n decl.type === 'ClassDeclaration' || decl.type === 'FunctionDeclaration'\n ? (decl as ClassDeclarationNode).id?.name\n : undefined;\n\n // As with `export { handler as default }`, the export is set in two steps: bound as-is where the\n // original statement set it, then rebound at the end of the module to the wrapper, which sees\n // methods added in between. See `wrapDefaultSpecifier`.\n let wrapped = '__SENTRY_DEFAULT_EXPORT__';\n if (declaredName) {\n // `export default class Handler {}`: the declaration stays, so `Handler` stays bound in the module.\n state.ms.remove(node.start, decl.start);\n state.ms.appendLeft(node.end, `\\nvar __SENTRY_DEFAULT_EXPORT__ = ${declaredName};`);\n wrapped = declaredName;\n } else if (isAnonymousFunctionOrClass(decl)) {\n // As a property value, the class or function gets the name `default`, as `export default` gives it.\n const hasSemicolon = source[node.end - 1] === ';';\n state.ms.overwrite(node.start, keywordsEnd, 'var __SENTRY_DEFAULT_EXPORT__ = { default:');\n state.ms.appendLeft(hasSemicolon ? node.end - 1 : node.end, hasSemicolon ? ' }.default' : ' }.default;');\n } else {\n state.ms.overwrite(node.start, keywordsEnd, 'var __SENTRY_DEFAULT_EXPORT__ =');\n }\n state.ms.appendLeft(node.end, '\\nexport { __SENTRY_DEFAULT_EXPORT__ as default };');\n state.ms.append(`\\n__SENTRY_DEFAULT_EXPORT__ = __SENTRY__.withSentry(${state.optionsFn}, ${wrapped});`);\n state.needsImport = true;\n state.autoWrapped.add(DEFAULT_EXPORT);\n}\n\n/**\n * Offset just past the `default` keyword of the `export default` statement at `start`. Comments can\n * sit between `export`, `default` and the expression, and may themselves contain the word `default`.\n */\nfunction exportDefaultKeywordsEnd(source: string, start: number): number {\n let index = start + 'export'.length;\n while (index < source.length && !source.startsWith('default', index)) {\n if (source.startsWith('//', index)) {\n const lineEnd = source.indexOf('\\n', index);\n index = lineEnd === -1 ? source.length : lineEnd;\n } else if (source.startsWith('/*', index)) {\n const commentEnd = source.indexOf('*/', index + 2);\n index = commentEnd === -1 ? source.length : commentEnd + 2;\n } else {\n index++;\n }\n }\n return index + 'default'.length;\n}\n\nfunction isAnonymousFunctionOrClass(node: BaseNode): boolean {\n if (node.type === 'ArrowFunctionExpression') return true;\n const isFunctionOrClass = [\n 'FunctionExpression',\n 'FunctionDeclaration',\n 'ClassExpression',\n 'ClassDeclaration',\n ].includes(node.type);\n return isFunctionOrClass && !(node as ClassDeclarationNode).id;\n}\n\nfunction handleNamedExport(node: ExportNamedNode, ctx: TransformContext, state: TransformState): void {\n const decl = node.declaration;\n\n // ---- Manually wrapped class export ----\n // `export const MyDO = instrumentDurableObjectWithSentry(...)` — count it\n // as wrapped so the plugin doesn't warn about it, but leave it alone.\n if (decl?.type === 'VariableDeclaration') {\n collectManuallyWrappedClassExports(decl, ctx, state);\n return;\n }\n\n // ---- Named class export matching a configured binding ----\n if (decl?.type === 'ClassDeclaration') {\n wrapInlineClassExport(node, decl, ctx, state);\n return;\n }\n\n // ---- Specifier export (`export { Foo as MyDO }`, `export { MyDO } from './do'`) ----\n wrapSpecifierExports(node, ctx, state);\n}\n\nfunction collectManuallyWrappedClassExports(\n varDecl: VariableDeclarationNode,\n ctx: TransformContext,\n state: TransformState,\n): void {\n for (const declarator of varDecl.declarations ?? []) {\n const name = declarator.id?.type === 'Identifier' ? declarator.id.name : undefined;\n const kind = name ? ctx.classWrappers.get(name) : undefined;\n if (!name || !kind || !declarator.init) continue;\n\n // A hand-wrapped Agent is configured as a Durable Object, so accept either helper there —\n // otherwise an already-instrumented Agent would be reported as unwrapped.\n const accepted =\n kind === 'durableObject' ? [WRAPPER_METHODS.durableObject, WRAPPER_METHODS.agent] : [WRAPPER_METHODS[kind]];\n\n if (accepted.some(method => isCallToMethod(declarator.init as BaseNode, method))) {\n state.wrappedClasses.add(name);\n }\n }\n}\n\nfunction wrapInlineClassExport(\n exportNode: ExportNamedNode,\n classDecl: ClassDeclarationNode,\n ctx: TransformContext,\n state: TransformState,\n): void {\n const classId = classDecl.id;\n // Inline export: the exported name and the local class name are the same.\n const kind = classId ? resolveWrapperKind(classId.name, classId.name, state) : undefined;\n if (!classId || !kind) return;\n\n const className = classId.name;\n\n // Strip the `export ` keyword\n state.ms.overwrite(exportNode.start, classDecl.start, '');\n\n const wrappedName = wrapLocalClass(className, classDecl, kind, state);\n state.ms.appendLeft(exportNode.end, `export { ${wrappedName} as ${className} };\\n`);\n\n state.wrappedClasses.add(className);\n state.autoWrapped.add(className);\n}\n\n/**\n * Wrap a class declared in this module and return the binding that holds the wrapper.\n *\n * The declaration is left exactly as written. Only the *export* has to become the wrapper, so the\n * wrapper gets its own binding and the export is aliased to it, the same shape as the documented\n * manual `instrument*WithSentry` pattern and the cross-module re-export path below. Renaming the\n * declaration instead (`class __SENTRY_ORIGINAL_MyAgent__`) would also rename what the class reports\n * as `Function.prototype.name`, which libraries read to identify the user's class: `@cloudflare/think`\n * hands `this.constructor.name` to the AI SDK as the telemetry `functionId`, and that surfaced as a\n * `gen_ai.invoke_agent __SENTRY_ORIGINAL_MyAgent__` span.\n */\nfunction wrapLocalClass(\n localName: string,\n localClass: ClassDeclarationNode,\n kind: ClassWrapperKind,\n state: TransformState,\n): string {\n const existing = state.wrappedLocals.get(localName);\n if (existing) return existing;\n\n const wrappedName = `__SENTRY_WRAPPED_${localName}__`;\n state.wrappedLocals.set(localName, wrappedName);\n state.ms.appendLeft(\n localClass.end,\n `\\nconst ${wrappedName} = __SENTRY__.${WRAPPER_METHODS[kind]}(${state.optionsFn}, ${localName});\\n`,\n );\n state.needsImport = true;\n return wrappedName;\n}\n\n/**\n * Wrap the configured classes an `export { ... }` statement names.\n *\n * Each such specifier is re-pointed at a binding holding the wrapper, which means rebuilding the\n * statement; specifiers this plugin has no business touching are carried over verbatim. For a class\n * declared in this module the wrapper binding follows the declaration (see {@link wrapLocalClass}).\n * A class that lives in **another** module — imported and re-exported, or re-exported directly — is\n * first bound under a private name, since an import binding cannot be reassigned and the `from` form\n * has no local binding at all.\n */\nfunction wrapSpecifierExports(node: ExportNamedNode, ctx: TransformContext, state: TransformState): void {\n const specifiers = node.specifiers ?? [];\n if (specifiers.length === 0) return;\n\n const sourceLiteral = node.source ? state.ms.original.slice(node.source.start, node.source.end) : undefined;\n\n const prelude: string[] = [];\n const wrappedPairs: string[] = [];\n const kept: string[] = [];\n\n for (const specifier of specifiers) {\n const pair = wrapSpecifier(specifier, sourceLiteral, ctx, state, prelude);\n if (pair) {\n wrappedPairs.push(pair);\n } else {\n kept.push(state.ms.original.slice(specifier.start, specifier.end));\n }\n }\n\n if (wrappedPairs.length === 0) return;\n\n const statements = [...prelude, `export { ${wrappedPairs.join(', ')} };`];\n if (kept.length > 0) {\n const clause = `export { ${kept.join(', ')} }`;\n statements.push(sourceLiteral ? `${clause} from ${sourceLiteral};` : `${clause};`);\n }\n state.ms.overwrite(node.start, node.end, statements.join('\\n'));\n}\n\n/**\n * `export { handler as default }`, the form bundlers emit for a default export. The export is set\n * in two steps. Right after `handler` is declared, it is bound to `handler` as-is, so a circular\n * import that reads it during module evaluation gets the handler, as before the transform. At the\n * end of the module, it is rebound to the wrapper, so a handler assigned or given methods later is\n * wrapped as it ends up. The binding is a `var`: a read before `handler` is declared gets\n * `undefined`, as it would from the bundler's own `var`, where a `const` would throw and stop the\n * Worker from starting.\n */\nfunction wrapDefaultSpecifier(localName: string, state: TransformState): string | undefined {\n if (state.manuallyWrappedLocals.has(localName)) return undefined;\n\n // Same as `export default Foo`: re-point at the wrapper a named export already made.\n const wrappedName = state.wrappedLocals.get(localName);\n if (wrappedName) {\n state.autoWrapped.add(DEFAULT_EXPORT);\n return `${wrappedName} as default`;\n }\n\n const declaringStatement = state.declaringStatements.get(localName);\n if (declaringStatement) {\n state.ms.appendLeft(declaringStatement.end, `\\nvar __SENTRY_DEFAULT_EXPORT__ = ${localName};`);\n }\n state.ms.append(\n `\\n${declaringStatement ? '' : 'var '}__SENTRY_DEFAULT_EXPORT__ = __SENTRY__.withSentry(${state.optionsFn}, ${localName});`,\n );\n state.needsImport = true;\n state.autoWrapped.add(DEFAULT_EXPORT);\n return '__SENTRY_DEFAULT_EXPORT__ as default';\n}\n\n/**\n * `export { default } from './handler'`. The handler may already be wrapped in its own module,\n * which this transform cannot see, so the emitted guard returns such a handler as-is.\n *\n * The original re-export is a live binding to the handler module's export, but the wrapper is not\n * set until this module's body runs. A circular import that reads the default export before then\n * gets `undefined` instead of the handler. The binding is a `var` so that the read does not throw,\n * as a `const` would, and stop the Worker from starting. See `wrapDefaultSpecifier`.\n */\nfunction wrapDefaultReexport(\n localName: string,\n sourceLiteral: string,\n state: TransformState,\n prelude: string[],\n): string {\n const target = '__SENTRY_REEXPORT_default__';\n prelude.push(\n localName === DEFAULT_IMPORT\n ? `import ${target} from ${sourceLiteral};`\n : `import { ${localName} as ${target} } from ${sourceLiteral};`,\n `var __SENTRY_DEFAULT_EXPORT__ = __SENTRY__._INTERNAL_wrapUnlessInstrumented(__SENTRY__.withSentry, ${state.optionsFn}, ${target});`,\n );\n state.needsImport = true;\n state.autoWrapped.add(DEFAULT_EXPORT);\n return '__SENTRY_DEFAULT_EXPORT__ as default';\n}\n\n/**\n * Handle one export specifier, returning the `Wrapped as Exported` pair to emit for a class that\n * gets wrapped. The import/wrapper statements a cross-module pair depends on are pushed onto\n * `prelude`; a local class's wrapper binding is emitted after its declaration instead.\n *\n * Returns `undefined` when the specifier can stay exactly as written: it doesn't name a configured\n * class, or the binding is already hand-wrapped.\n */\nfunction wrapSpecifier(\n specifier: ExportSpecifierNode,\n sourceLiteral: string | undefined,\n ctx: TransformContext,\n state: TransformState,\n prelude: string[],\n): string | undefined {\n const exportedName =\n specifier.type === 'ExportSpecifier' && specifier.exported?.type === 'Identifier'\n ? specifier.exported.name\n : undefined;\n const localName = specifier.local?.type === 'Identifier' ? specifier.local.name : undefined;\n // With a `from` clause the specifier names an export of the *source* module, not a binding here.\n const kind = exportedName\n ? resolveWrapperKind(exportedName, sourceLiteral ? undefined : localName, state)\n : undefined;\n\n if (!exportedName || !localName) return undefined;\n if (!kind) {\n if (exportedName !== DEFAULT_IMPORT) return undefined;\n return sourceLiteral\n ? wrapDefaultReexport(localName, sourceLiteral, state, prelude)\n : wrapDefaultSpecifier(localName, state);\n }\n\n // Without a `from` clause the specifier points at a module-local binding.\n if (!sourceLiteral) {\n const localClass = state.topLevelClasses.get(localName);\n\n if (localClass?.id) {\n const wrappedName = wrapLocalClass(localName, localClass, kind, state);\n state.wrappedClasses.add(exportedName);\n return `${wrappedName} as ${exportedName}`;\n }\n\n if (state.manuallyWrappedLocals.has(localName)) {\n state.wrappedClasses.add(exportedName);\n return undefined;\n }\n }\n\n // The class comes from another module: bind it under a private name (for the `from` form, which\n // has no local binding at all), wrap that, and export the wrapper under the configured name.\n let target = localName;\n\n if (sourceLiteral) {\n target = `__SENTRY_REEXPORT_${exportedName}__`;\n prelude.push(\n localName === DEFAULT_IMPORT\n ? `import ${target} from ${sourceLiteral};`\n : `import { ${localName} as ${target} } from ${sourceLiteral};`,\n );\n }\n\n const wrappedName = `__SENTRY_WRAPPED_${exportedName}__`;\n\n // The class may already be hand-wrapped in its own module, which this transform cannot see. The\n // emitted guard returns such a class as-is instead of nesting a second wrapper around it.\n prelude.push(\n `const ${wrappedName} = __SENTRY__._INTERNAL_wrapUnlessInstrumented(__SENTRY__.${WRAPPER_METHODS[kind]}, ${state.optionsFn}, ${target});`,\n );\n state.wrappedClasses.add(exportedName);\n state.autoWrapped.add(exportedName);\n state.needsImport = true;\n\n return `${wrappedName} as ${exportedName}`;\n}\n"],"mappings":";;;;;;;AAMA,MAAM,4BAA4B;AAGlC,MAAM,qBAAqB;AA8D3B,SAAS,eAAe,MAAgB,YAA6B;CACnE,IAAI,KAAK,SAAS,kBAAkB,OAAO;CAC3C,MAAM,SAAU,KAA4B;CAC5C,IAAI,CAAC,QAAQ,OAAO;CACpB,IAAI,OAAO,SAAS,gBAAgB,OAAO,SAAS,YAAY,OAAO;CACvE,OACE,OAAO,SAAS,sBAAsB,OAAO,UAAU,SAAS,gBAAgB,OAAO,SAAS,SAAS;AAE7G;;AAgBA,MAAM,iBAAiB;;;;;;AAOvB,MAAM,kBAAoD;CACxD,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AY,MAAM,KAAK;GACrE,MAAM,eAAe,IAAI,YAAY;GACrC,OAAO,GAAG,YAAY,MAAM;EAC9B;EAEA,IAAI,MAAM,sBAAsB,IAAI,SAAS,GAAG;GAC9C,MAAM,eAAe,IAAI,YAAY;GACrC;EACF;CACF;CAIA,IAAI,SAAS;CAEb,IAAI,eAAe;EACjB,SAAS,qBAAqB,aAAa;EAC3C,QAAQ,KACN,cAAc,iBACV,UAAU,OAAO,QAAQ,cAAc,KACvC,YAAY,UAAU,MAAM,OAAO,UAAU,cAAc,EACjE;CACF;CAEA,MAAM,cAAc,oBAAoB,aAAa;CAIrD,QAAQ,KACN,SAAS,YAAY,4DAA4D,gBAAgB,MAAM,IAAI,MAAM,UAAU,IAAI,OAAO,GACxI;CACA,MAAM,eAAe,IAAI,YAAY;CACrC,MAAM,YAAY,IAAI,YAAY;CAClC,MAAM,cAAc;CAEpB,OAAO,GAAG,YAAY,MAAM;AAC9B"}
@@ -40,6 +40,8 @@ function resolveWranglerConfig(root, explicitPath) {
40
40
  const configDir = (0, node_path.dirname)(resolvedConfigPath);
41
41
  return {
42
42
  config: {
43
+ name: raw.name,
44
+ compatibilityDate: raw.compatibility_date,
43
45
  main: raw.main && ENTRY_FILE_REGEX.test(raw.main) ? (0, node_path.resolve)(configDir, raw.main) : raw.main,
44
46
  durableObjects: collectClassBindings(raw.durable_objects?.bindings),
45
47
  workflows: collectClassBindings(raw.workflows),