@sentry/cloudflare 11.5.0 → 11.6.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 (43) hide show
  1. package/build/cjs/dev/client.js.map +1 -1
  2. package/build/cjs/dev/instrumentations/instrumentSqlStorage.js.map +1 -1
  3. package/build/cjs/dev/utils/internalSqlQuery.js +5 -3
  4. package/build/cjs/dev/utils/internalSqlQuery.js.map +1 -1
  5. package/build/cjs/dev/vite/autoInstrument.js +13 -1
  6. package/build/cjs/dev/vite/autoInstrument.js.map +1 -1
  7. package/build/cjs/dev/vite/transform.js +2 -1
  8. package/build/cjs/dev/vite/transform.js.map +1 -1
  9. package/build/cjs/prod/client.js.map +1 -1
  10. package/build/cjs/prod/instrumentations/instrumentSqlStorage.js.map +1 -1
  11. package/build/cjs/prod/utils/internalSqlQuery.js +5 -3
  12. package/build/cjs/prod/utils/internalSqlQuery.js.map +1 -1
  13. package/build/cjs/prod/vite/autoInstrument.js +13 -1
  14. package/build/cjs/prod/vite/autoInstrument.js.map +1 -1
  15. package/build/cjs/prod/vite/transform.js +2 -1
  16. package/build/cjs/prod/vite/transform.js.map +1 -1
  17. package/build/esm/dev/client.js.map +1 -1
  18. package/build/esm/dev/instrumentations/instrumentSqlStorage.js.map +1 -1
  19. package/build/esm/dev/package.json +1 -1
  20. package/build/esm/dev/utils/internalSqlQuery.js +5 -3
  21. package/build/esm/dev/utils/internalSqlQuery.js.map +1 -1
  22. package/build/esm/dev/vite/autoInstrument.js +13 -1
  23. package/build/esm/dev/vite/autoInstrument.js.map +1 -1
  24. package/build/esm/dev/vite/transform.js +2 -1
  25. package/build/esm/dev/vite/transform.js.map +1 -1
  26. package/build/esm/prod/client.js.map +1 -1
  27. package/build/esm/prod/instrumentations/instrumentSqlStorage.js.map +1 -1
  28. package/build/esm/prod/package.json +1 -1
  29. package/build/esm/prod/utils/internalSqlQuery.js +5 -3
  30. package/build/esm/prod/utils/internalSqlQuery.js.map +1 -1
  31. package/build/esm/prod/vite/autoInstrument.js +13 -1
  32. package/build/esm/prod/vite/autoInstrument.js.map +1 -1
  33. package/build/esm/prod/vite/transform.js +2 -1
  34. package/build/esm/prod/vite/transform.js.map +1 -1
  35. package/build/types/client.d.ts +8 -6
  36. package/build/types/client.d.ts.map +1 -1
  37. package/build/types/utils/internalSqlQuery.d.ts +7 -4
  38. package/build/types/utils/internalSqlQuery.d.ts.map +1 -1
  39. package/build/types/vite/autoInstrument.d.ts +3 -0
  40. package/build/types/vite/autoInstrument.d.ts.map +1 -1
  41. package/build/types/vite/transform.d.ts +2 -0
  42. package/build/types/vite/transform.d.ts.map +1 -1
  43. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sources":["../../../src/client.ts"],"sourcesContent":["import type { ClientOptions, Options, TracePropagationTargets } from '@sentry/core';\nimport {\n _INTERNAL_clearAiProviderSkips,\n _INTERNAL_flushLogsBuffer,\n _INTERNAL_flushMetricsBuffer,\n applySdkMetadata,\n debug,\n spanIsSampled,\n} from '@sentry/core';\nimport type { ServerRuntimeClientOptions } from '@sentry/core/server';\nimport { ServerRuntimeClient } from '@sentry/core/server';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { ExecutionContextCompat } from './executionContext';\nimport type { makeFlushLock } from './flush';\nimport type { CloudflareTransportOptions } from './transport';\nimport { getInvocationState, getInvocationWaitUntil } from './utils/invocationContext';\n\n/**\n * The Sentry Cloudflare SDK Client.\n *\n * @see CloudflareClientOptions for documentation on configuration options.\n * @see ServerRuntimeClient for usage documentation.\n */\nexport class CloudflareClient extends ServerRuntimeClient {\n private readonly _flushLock: ReturnType<typeof makeFlushLock> | void;\n private _pendingSpans: Set<string> = new Set();\n private _spanCompletionPromise: Promise<void> | null = null;\n private _resolveSpanCompletion: (() => void) | null = null;\n\n private _unsubscribeSpanStart: (() => void) | null = null;\n private _unsubscribeSpanEnd: (() => void) | null = null;\n\n // True while a boundary `flush()` is draining; envelopes created by that drain ride it\n // and must not each start their own eager transport flush.\n private _inBoundaryFlush = false;\n\n /**\n * Whether this client is a cached, cross-invocation client (`cacheClient`).\n * Cached clients are never disposed at an invocation boundary, so their spans/events\n * are delivered eagerly instead of waiting for a per-invocation flush.\n */\n public readonly isCachedClient: boolean;\n\n /**\n * Creates a new Cloudflare SDK instance.\n * @param options Configuration options for this SDK.\n */\n public constructor(options: CloudflareClientOptions) {\n applySdkMetadata(options, 'cloudflare');\n options._metadata = options._metadata || {};\n const { flushLock, ...serverOptions } = options;\n\n const clientOptions: ServerRuntimeClientOptions = {\n ...serverOptions,\n platform: 'javascript',\n // TODO: Grab version information\n runtime: { name: 'cloudflare' },\n // TODO: Add server name\n _flushInterval: 0,\n };\n\n super(clientOptions);\n this._flushLock = flushLock;\n this.isCachedClient = options.cacheClient === true;\n\n // Track span lifecycle to know when to flush. Skipped for cached clients\n // (`cacheClient`): they are never disposed, so spans that end after\n // a flush are still delivered. Per-invocation clients are disposed right after\n // the boundary flush, so the flush must wait for open spans to end otherwise\n // their transaction never gets emitted.\n if (!this.isCachedClient) {\n this._unsubscribeSpanStart = this.on('spanStart', span => {\n const spanId = span.spanContext().spanId;\n DEBUG_BUILD && debug.log('[CloudflareClient] Span started:', spanId);\n\n // Negatively sampled spans never emit spanEnd,\n // so tracking them would cause _pendingSpans to grow unboundedly.\n // We should fix the inconsistent behavior for NonRecordingSpans in the future but\n // for now, we just ignore them.\n if (!spanIsSampled(span)) {\n return;\n }\n\n this._pendingSpans.add(spanId);\n\n if (!this._spanCompletionPromise) {\n this._spanCompletionPromise = new Promise(resolve => {\n this._resolveSpanCompletion = resolve;\n });\n }\n });\n\n this._unsubscribeSpanEnd = this.on('spanEnd', span => {\n const spanId = span.spanContext().spanId;\n DEBUG_BUILD && debug.log('[CloudflareClient] Span ended:', spanId);\n this._pendingSpans.delete(spanId);\n\n // If no more pending spans, resolve the completion promise\n if (this._pendingSpans.size === 0 && this._resolveSpanCompletion) {\n DEBUG_BUILD && debug.log('[CloudflareClient] All spans completed, preparing to flush');\n this._resolveSpanCompletion();\n this._resetSpanCompletionPromise();\n }\n });\n }\n }\n\n /**\n * Flushes pending operations and ensures all data is processed.\n *\n * Each phase waits at most `timeout`: the flush lock of a per-invocation client, pending spans, event\n * processing and the transport drain. So a flush can take a small multiple of `timeout`, which stays well\n * below Cloudflare's 30 second `waitUntil` limit for the timeouts the SDK uses. Sends still pending when\n * the drain times out are aborted.\n *\n * @param {number} [timeout] - Maximum time in milliseconds for each phase of the flush.\n * @return {Promise<boolean>} A promise that resolves to a boolean indicating whether the flush operation was successful.\n */\n public async flush(timeout?: number): Promise<boolean> {\n // Wait for user waitUntil-registered work to settle before draining, so events\n // captured in that work are still in the buffer. Without this the final flush\n // can drain (and the client be disposed) before background captures land.\n //\n // Only per-invocation clients (`cacheClient: false`) have a flush lock; remove this with them in v12.\n // The wait is bounded by `timeout` because a user `waitUntil` task that outlives the invocation\n // would otherwise keep the flush from draining until the runtime cancels it.\n if (this._flushLock) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n this._flushLock.finalize(),\n ...(timeout ? [new Promise<void>(resolve => (timer = setTimeout(resolve, timeout)))] : []),\n ]);\n clearTimeout(timer);\n }\n\n if (this._pendingSpans.size > 0 && this._spanCompletionPromise) {\n DEBUG_BUILD &&\n debug.log('[CloudflareClient] Waiting for', this._pendingSpans.size, 'pending spans to complete...');\n\n const timeoutMs = timeout ?? 5000;\n const spanCompletionRace = Promise.race([\n this._spanCompletionPromise,\n new Promise(resolve =>\n setTimeout(() => {\n DEBUG_BUILD &&\n debug.log('[CloudflareClient] Span completion timeout after', timeoutMs, 'ms, flushing anyway');\n resolve(undefined);\n }, timeoutMs),\n ),\n ]);\n\n await spanCompletionRace;\n }\n\n // Envelopes created while this flush drains (log/metric/span buffers turning into\n // envelopes on the `flush` emit) ride its own transport drain; without the flag each\n // of them would also start an eager drain and a `waitUntil` registration.\n this._inBoundaryFlush = true;\n try {\n return await super.flush(timeout);\n } finally {\n this._inBoundaryFlush = false;\n }\n }\n\n /**\n * Disposes of the client and releases all resources.\n *\n * This method clears all Cloudflare-specific state in addition to the base client cleanup.\n * It unsubscribes from span lifecycle events and clears pending span tracking.\n *\n * Call this method after flushing to allow the client to be garbage collected.\n * After calling dispose(), the client should not be used anymore.\n */\n public override dispose(): void {\n DEBUG_BUILD && debug.log('[CloudflareClient] Disposing client...');\n\n super.dispose();\n\n if (this._unsubscribeSpanStart) {\n this._unsubscribeSpanStart();\n this._unsubscribeSpanStart = null;\n }\n if (this._unsubscribeSpanEnd) {\n this._unsubscribeSpanEnd();\n this._unsubscribeSpanEnd = null;\n }\n\n this._resetSpanCompletionPromise();\n (this as unknown as { _flushLock: ReturnType<typeof makeFlushLock> | void })._flushLock = undefined;\n }\n\n /** @inheritDoc */\n protected override _setupIntegrations(): void {\n // Clear AI provider skip registrations before setting up integrations.\n // The registry is module-global and Cloudflare calls `init()` per request, so without this a\n // single `ai` SDK call would suppress direct `env.AI.run` spans for the rest of the isolate's\n // life. Mirrors the same reset in the Node client.\n _INTERNAL_clearAiProviderSkips();\n super._setupIntegrations();\n\n // Registered after the integrations on purpose: the flush-point marker must run\n // after core and the span buffer have turned their buffers into envelopes on the\n // same `flush` emit (so those envelopes ride the boundary drain instead of starting\n // eager ones), and the eager span handler relies on `spanStreamingIntegration`\n // having already buffered the span that triggers it.\n if (this.isCachedClient) {\n // Marks the invocation's natural flush point: anything captured from now on\n // (post-response `waitUntil` work, detached continuations) has no later flush\n // to ride and is delivered eagerly by the hooks below.\n this.on('flush', () => {\n const invocationState = getInvocationState();\n if (invocationState) {\n invocationState.flushPointReached = true;\n }\n });\n this._setupEagerEnvelopeDelivery();\n this._setupEagerBufferDelivery();\n }\n }\n\n /**\n * Resets the span completion promise and resolve function.\n */\n private _resetSpanCompletionPromise(): void {\n this._pendingSpans.clear();\n this._spanCompletionPromise = null;\n this._resolveSpanCompletion = null;\n }\n\n /**\n * Drains the transport after an envelope has been accepted past the invocation's\n * flush point. The transport queues request producers until `flush()`; before the\n * flush point the boundary `flush()` drains everything, but envelopes created after\n * it (post-response `waitUntil` work, detached continuations) have no later flush to\n * ride. The drain is registered with the invocation's `waitUntil` to keep the fetch\n * alive; outside any instrumented invocation it always runs.\n */\n private _setupEagerEnvelopeDelivery(): void {\n this.on('afterEnvelope', () => {\n const transport = this.getTransport();\n const invocationState = getInvocationState();\n\n if (!transport || this._inBoundaryFlush || (invocationState && !invocationState.flushPointReached)) {\n return;\n }\n\n this._registerWithInvocationWaitUntil(transport.flush(2000));\n });\n }\n\n /**\n * Turns spans, logs and metrics captured past the invocation's flush point into\n * envelopes. Before the flush point the boundary `flush()` drains their buffers; after\n * it (or outside any instrumented invocation) nothing else would: the log/metric idle\n * timer is disabled for this runtime (`_flushInterval: 0`) and the span buffer's own 5s\n * timer fires outside any invocation, where the runtime suspends the send. Each capture\n * drains only its own bucket (the ended span's trace, the log buffer, the metric\n * buffer), so a fan-out of concurrent traces stays one envelope per trace. RPC method\n * spans never reach this path: `wrapMethodWithSentry` runs the boundary flush after the\n * method span has ended, so only work past that (e.g. detached continuations) lands here.\n */\n private _setupEagerBufferDelivery(): void {\n this.on('afterSpanEnd', span => {\n // The trace id must come from the span, not the current scope: `continueTrace`\n // writes the propagation context to the *current* scope, so the forked\n // isolation scope's propagation context carries a different trace id and\n // flushing by it silently no-ops.\n const traceId = span.spanContext().traceId;\n this._eagerDrain(() => this.emit('flushTraceSpans', traceId));\n });\n this.on('afterCaptureLog', () => this._eagerDrain(() => _INTERNAL_flushLogsBuffer(this)));\n this.on('afterCaptureMetric', () => this._eagerDrain(() => _INTERNAL_flushMetricsBuffer(this)));\n }\n\n /**\n * Runs `drain` unless the owning invocation has not reached its flush point yet\n * (before it the boundary `flush()` delivers the buffers).\n */\n private _eagerDrain(drain: () => void): void {\n const invocationState = getInvocationState();\n\n if (invocationState && !invocationState.flushPointReached) {\n return;\n }\n\n drain();\n }\n\n /**\n * Attaches a promise to the `waitUntil` of the invocation that owns the current\n * async context, so the runtime keeps the send alive after the response is returned.\n * Outside any instrumented invocation (or where the context has no `waitUntil`,\n * e.g. Astro prerendering) the send is fire-and-forget.\n */\n private _registerWithInvocationWaitUntil(promise: PromiseLike<unknown>): void {\n const invocationState = getInvocationState();\n const waitUntil = invocationState && getInvocationWaitUntil(invocationState);\n if (!waitUntil) {\n return;\n }\n\n try {\n waitUntil(\n Promise.resolve(promise).then(\n () => undefined,\n () => undefined,\n ),\n );\n } catch {\n // The owning invocation already ended; the send races isolate teardown either way.\n }\n }\n}\n\ninterface BaseCloudflareOptions {\n /**\n * @ignore Used internally to disable the deDupeIntegration for workflows.\n * @hidden Used internally to disable the deDupeIntegration for workflows.\n * @default true\n */\n enableDedupe?: boolean;\n\n /**\n * The Cloudflare SDK is not OpenTelemetry native. By default (`false`) it does not set up a tracer\n * provider; spans are emitted via the SDK's own instrumentation and scopes are isolated with\n * AsyncLocalStorage.\n *\n * Set this to `true` to opt into the OpenTelemetry compatibility tracer, which captures spans\n * emitted via `@opentelemetry/api`. Big caveat: it does not handle custom context, always working\n * off the current scope. This is good enough for many, but not all, integrations.\n *\n * @default false\n */\n enableOpenTelemetrySetup?: boolean;\n\n /**\n * The bindings on `env` that outgoing RPC calls propagate trace context to.\n *\n * Strings match a binding name exactly, regular expressions match by pattern. An empty array\n * (the default) propagates to nothing.\n *\n * RPC has no headers to carry trace context, so the SDK appends it as a trailing argument to\n * every RPC method call on a matching binding. Only a Sentry-instrumented receiver strips that\n * argument again. Anywhere else it arrives as a real argument and changes what the method was\n * called with, so list only the bindings whose receiver you know runs Sentry.\n *\n * Propagation over `stub.fetch()` and service binding `fetch()` uses HTTP headers and is not\n * affected by this option.\n *\n * Strings match a binding name exactly, regular expressions match by pattern. Both match\n * case-insensitively.\n *\n * When you build with the Sentry Cloudflare Vite plugin, bindings that resolve to *this* worker\n * (its own Durable Objects, its self service bindings) are added for you, because the plugin\n * instruments those receivers itself. Whatever you list here is added on top of them.\n *\n * @default []\n * @example\n * ```ts\n * // Propagate to `env.ORDERS` and every `env.SVC_*` binding\n * export default Sentry.withSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * rpcTracePropagationBindings: ['ORDERS', /^SVC_/],\n * }),\n * handler,\n * );\n * ```\n */\n rpcTracePropagationBindings?: TracePropagationTargets;\n\n /**\n * Table names that should stay instrumented even though they match the reserved `cf_` prefix used\n * by Durable Object frameworks (`agents`, `partyserver`, ...) for their internal SQLite tables.\n *\n * By default, `exec` queries against `cf_`-prefixed tables are treated as framework noise and no\n * `db.query` span is created for them. If one of your own tables happens to use this prefix, add it\n * here to opt it back into instrumentation. Entries are matched against each table name in the\n * query summary — strings must match exactly, while regular expressions give you prefix/pattern\n * matching.\n *\n * @default []\n * @example\n * ```ts\n * export default Sentry.withSentry(\n * (env) => ({\n * dsn: env.SENTRY_DSN,\n * durableObjectSqlSpanAllowlist: ['cf_my_table', /^cf_reports_/],\n * }),\n * handler,\n * );\n * ```\n */\n durableObjectSqlSpanAllowlist?: Array<string | RegExp>;\n\n /**\n * KV keys that should stay instrumented even though they match a reserved prefix used by Durable\n * Object frameworks (`agents`, `partyserver`, ...) for their internal storage entries.\n *\n * By default, KV reads/writes (`get`, `put`, `delete`, `list`) of `cf_`- or `__ps_`-prefixed keys\n * are treated as framework noise and no `durable_object_storage_*` span is created for them,\n * mirroring how `cf_`-prefixed SQL tables are handled (see {@link durableObjectSqlSpanAllowlist}).\n * If one of your own keys happens to use such a prefix, add it here to opt it back into\n * instrumentation. Strings must match exactly, while regular expressions give you prefix/pattern\n * matching.\n *\n * @default []\n * @example\n * ```ts\n * export default Sentry.withSentry(\n * (env) => ({\n * dsn: env.SENTRY_DSN,\n * durableObjectStorageSpanAllowlist: ['cf_my_key', /^cf_reports_/],\n * }),\n * handler,\n * );\n * ```\n */\n durableObjectStorageSpanAllowlist?: Array<string | RegExp>;\n\n /**\n * Sets an optional server name (device name).\n *\n * This is useful for identifying which server or instance is sending events.\n */\n serverName?: string;\n\n /**\n * If you use Spotlight by Sentry during development, use\n * this option to forward captured Sentry events to Spotlight.\n *\n * Either set it to true, or provide a specific Spotlight Sidecar URL.\n *\n * More details: https://spotlightjs.com/\n *\n * IMPORTANT: Only set this option to `true` while developing, not in production!\n */\n spotlight?: boolean | string;\n\n /**\n * Cache the client and reuse it across invocations within the same isolate.\n *\n * The SDK creates one client per isolate and reuses it for all requests/DO\n * handlers in that isolate. This avoids the per-invocation cost of\n * constructing a new client.\n *\n * Since a cached client outlives any single invocation, data captured after an\n * invocation's flush point (post-response `waitUntil` work, detached background\n * work) is delivered eagerly instead of waiting for a flush that never comes.\n *\n * The first `init()` in an isolate decides the cached client's options; later\n * `init()` calls with different options (e.g. another DSN) reuse the cached client\n * unchanged (a debug warning is logged for a DSN change). Use `cacheClient: false`\n * when options must differ per invocation.\n *\n * When disabled, a new client is created per invocation and disposed after the\n * handler completes.\n *\n * @default true\n */\n cacheClient?: boolean;\n}\n\n/**\n * Configuration options for the Sentry Cloudflare SDK\n *\n * @see @sentry/core Options for more information.\n */\nexport interface CloudflareOptions extends Options<CloudflareTransportOptions>, BaseCloudflareOptions {\n ctx?: ExecutionContextCompat;\n}\n\n/**\n * Configuration options for the Sentry Cloudflare SDK Client class\n *\n * @see CloudflareClient for more information.\n */\nexport interface CloudflareClientOptions extends ClientOptions<CloudflareTransportOptions>, BaseCloudflareOptions {\n flushLock?: ReturnType<typeof makeFlushLock>;\n}\n"],"names":["ServerRuntimeClient","applySdkMetadata","DEBUG_BUILD","debug","spanIsSampled","_INTERNAL_clearAiProviderSkips","getInvocationState","_INTERNAL_flushLogsBuffer","_INTERNAL_flushMetricsBuffer","getInvocationWaitUntil"],"mappings":";;;;;;;AAuBO,MAAM,yBAAyBA,0BAAA,CAAoB;AAAA;AAAA;AAAA;AAAA;AAAA,EAwBjD,YAAY,OAAA,EAAkC;AACnD,IAAAC,qBAAA,CAAiB,SAAS,YAAY,CAAA;AACtC,IAAA,OAAA,CAAQ,SAAA,GAAY,OAAA,CAAQ,SAAA,IAAa,E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BAAgB,CAAA,IAAA,KAAQ;AAK9B,MAAA,MAAM,OAAA,GAAU,IAAA,CAAK,WAAA,EAAY,CAAE,OAAA;AACnC,MAAA,IAAA,CAAK,YAAY,MAAM,IAAA,CAAK,IAAA,CAAK,iBAAA,EAAmB,OAAO,CAAC,CAAA;AAAA,IAC9D,CAAC,CAAA;AACD,IAAA,IAAA,CAAK,EAAA,CAAG,mBAAmB,MAAM,IAAA,CAAK,YAAY,MAAMC,8BAAA,CAA0B,IAAI,CAAC,CAAC,CAAA;AACxF,IAAA,IAAA,CAAK,EAAA,CAAG,sBAAsB,MAAM,IAAA,CAAK,YAAY,MAAMC,iCAAA,CAA6B,IAAI,CAAC,CAAC,CAAA;AAAA,EAChG;AAAA;AAAA;AAAA;AAAA;AAAA,EAMQ,YAAY,KAAA,EAAyB;AAC3C,IAAA,MAAM,kBAAkBF,oCAAA,EAAmB;AAE3C,IAAA,IAAI,eAAA,IAAmB,CAAC,eAAA,CAAgB,iBAAA,EAAmB;AACzD,MAAA;AAAA,IACF;AAEA,IAAA,KAAA,EAAM;AAAA,EACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQQ,iCAAiC,OAAA,EAAqC;AAC5E,IAAA,MAAM,kBAAkBA,oCAAA,EAAmB;AAC3C,IAAA,MAAM,SAAA,GAAY,eAAA,IAAmBG,wCAAA,CAAuB,eAAe,CAAA;AAC3E,IAAA,IAAI,CAAC,SAAA,EAAW;AACd,MAAA;AAAA,IACF;AAEA,IAAA,IAAI;AACF,MAAA,SAAA;AAAA,QACE,OAAA,CAAQ,OAAA,CAAQ,OAAO,CAAA,CAAE,IAAA;AAAA,UACvB,MAAM,KAAA,CAAA;AAAA,UACN,MAAM,KAAA;AAAA;AACR,OACF;AAAA,IACF,CAAA,CAAA,MAAQ;AAAA,IAER;AAAA,EACF;AACF;;;;"}
1
+ {"version":3,"file":"client.js","sources":["../../../src/client.ts"],"sourcesContent":["import type { ClientOptions, Options, TracePropagationTargets } from '@sentry/core';\nimport {\n _INTERNAL_clearAiProviderSkips,\n _INTERNAL_flushLogsBuffer,\n _INTERNAL_flushMetricsBuffer,\n applySdkMetadata,\n debug,\n spanIsSampled,\n} from '@sentry/core';\nimport type { ServerRuntimeClientOptions } from '@sentry/core/server';\nimport { ServerRuntimeClient } from '@sentry/core/server';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { ExecutionContextCompat } from './executionContext';\nimport type { makeFlushLock } from './flush';\nimport type { CloudflareTransportOptions } from './transport';\nimport { getInvocationState, getInvocationWaitUntil } from './utils/invocationContext';\n\n/**\n * The Sentry Cloudflare SDK Client.\n *\n * @see CloudflareClientOptions for documentation on configuration options.\n * @see ServerRuntimeClient for usage documentation.\n */\nexport class CloudflareClient extends ServerRuntimeClient {\n private readonly _flushLock: ReturnType<typeof makeFlushLock> | void;\n private _pendingSpans: Set<string> = new Set();\n private _spanCompletionPromise: Promise<void> | null = null;\n private _resolveSpanCompletion: (() => void) | null = null;\n\n private _unsubscribeSpanStart: (() => void) | null = null;\n private _unsubscribeSpanEnd: (() => void) | null = null;\n\n // True while a boundary `flush()` is draining; envelopes created by that drain ride it\n // and must not each start their own eager transport flush.\n private _inBoundaryFlush = false;\n\n /**\n * Whether this client is a cached, cross-invocation client (`cacheClient`).\n * Cached clients are never disposed at an invocation boundary, so their spans/events\n * are delivered eagerly instead of waiting for a per-invocation flush.\n */\n public readonly isCachedClient: boolean;\n\n /**\n * Creates a new Cloudflare SDK instance.\n * @param options Configuration options for this SDK.\n */\n public constructor(options: CloudflareClientOptions) {\n applySdkMetadata(options, 'cloudflare');\n options._metadata = options._metadata || {};\n const { flushLock, ...serverOptions } = options;\n\n const clientOptions: ServerRuntimeClientOptions = {\n ...serverOptions,\n platform: 'javascript',\n // TODO: Grab version information\n runtime: { name: 'cloudflare' },\n // TODO: Add server name\n _flushInterval: 0,\n };\n\n super(clientOptions);\n this._flushLock = flushLock;\n this.isCachedClient = options.cacheClient === true;\n\n // Track span lifecycle to know when to flush. Skipped for cached clients\n // (`cacheClient`): they are never disposed, so spans that end after\n // a flush are still delivered. Per-invocation clients are disposed right after\n // the boundary flush, so the flush must wait for open spans to end otherwise\n // their transaction never gets emitted.\n if (!this.isCachedClient) {\n this._unsubscribeSpanStart = this.on('spanStart', span => {\n const spanId = span.spanContext().spanId;\n DEBUG_BUILD && debug.log('[CloudflareClient] Span started:', spanId);\n\n // Negatively sampled spans never emit spanEnd,\n // so tracking them would cause _pendingSpans to grow unboundedly.\n // We should fix the inconsistent behavior for NonRecordingSpans in the future but\n // for now, we just ignore them.\n if (!spanIsSampled(span)) {\n return;\n }\n\n this._pendingSpans.add(spanId);\n\n if (!this._spanCompletionPromise) {\n this._spanCompletionPromise = new Promise(resolve => {\n this._resolveSpanCompletion = resolve;\n });\n }\n });\n\n this._unsubscribeSpanEnd = this.on('spanEnd', span => {\n const spanId = span.spanContext().spanId;\n DEBUG_BUILD && debug.log('[CloudflareClient] Span ended:', spanId);\n this._pendingSpans.delete(spanId);\n\n // If no more pending spans, resolve the completion promise\n if (this._pendingSpans.size === 0 && this._resolveSpanCompletion) {\n DEBUG_BUILD && debug.log('[CloudflareClient] All spans completed, preparing to flush');\n this._resolveSpanCompletion();\n this._resetSpanCompletionPromise();\n }\n });\n }\n }\n\n /**\n * Flushes pending operations and ensures all data is processed.\n *\n * Each phase waits at most `timeout`: the flush lock of a per-invocation client, pending spans, event\n * processing and the transport drain. So a flush can take a small multiple of `timeout`, which stays well\n * below Cloudflare's 30 second `waitUntil` limit for the timeouts the SDK uses. Sends still pending when\n * the drain times out are aborted.\n *\n * @param {number} [timeout] - Maximum time in milliseconds for each phase of the flush.\n * @return {Promise<boolean>} A promise that resolves to a boolean indicating whether the flush operation was successful.\n */\n public async flush(timeout?: number): Promise<boolean> {\n // Wait for user waitUntil-registered work to settle before draining, so events\n // captured in that work are still in the buffer. Without this the final flush\n // can drain (and the client be disposed) before background captures land.\n //\n // Only per-invocation clients (`cacheClient: false`) have a flush lock; remove this with them in v12.\n // The wait is bounded by `timeout` because a user `waitUntil` task that outlives the invocation\n // would otherwise keep the flush from draining until the runtime cancels it.\n if (this._flushLock) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n this._flushLock.finalize(),\n ...(timeout ? [new Promise<void>(resolve => (timer = setTimeout(resolve, timeout)))] : []),\n ]);\n clearTimeout(timer);\n }\n\n if (this._pendingSpans.size > 0 && this._spanCompletionPromise) {\n DEBUG_BUILD &&\n debug.log('[CloudflareClient] Waiting for', this._pendingSpans.size, 'pending spans to complete...');\n\n const timeoutMs = timeout ?? 5000;\n const spanCompletionRace = Promise.race([\n this._spanCompletionPromise,\n new Promise(resolve =>\n setTimeout(() => {\n DEBUG_BUILD &&\n debug.log('[CloudflareClient] Span completion timeout after', timeoutMs, 'ms, flushing anyway');\n resolve(undefined);\n }, timeoutMs),\n ),\n ]);\n\n await spanCompletionRace;\n }\n\n // Envelopes created while this flush drains (log/metric/span buffers turning into\n // envelopes on the `flush` emit) ride its own transport drain; without the flag each\n // of them would also start an eager drain and a `waitUntil` registration.\n this._inBoundaryFlush = true;\n try {\n return await super.flush(timeout);\n } finally {\n this._inBoundaryFlush = false;\n }\n }\n\n /**\n * Disposes of the client and releases all resources.\n *\n * This method clears all Cloudflare-specific state in addition to the base client cleanup.\n * It unsubscribes from span lifecycle events and clears pending span tracking.\n *\n * Call this method after flushing to allow the client to be garbage collected.\n * After calling dispose(), the client should not be used anymore.\n */\n public override dispose(): void {\n DEBUG_BUILD && debug.log('[CloudflareClient] Disposing client...');\n\n super.dispose();\n\n if (this._unsubscribeSpanStart) {\n this._unsubscribeSpanStart();\n this._unsubscribeSpanStart = null;\n }\n if (this._unsubscribeSpanEnd) {\n this._unsubscribeSpanEnd();\n this._unsubscribeSpanEnd = null;\n }\n\n this._resetSpanCompletionPromise();\n (this as unknown as { _flushLock: ReturnType<typeof makeFlushLock> | void })._flushLock = undefined;\n }\n\n /** @inheritDoc */\n protected override _setupIntegrations(): void {\n // Clear AI provider skip registrations before setting up integrations.\n // The registry is module-global and Cloudflare calls `init()` per request, so without this a\n // single `ai` SDK call would suppress direct `env.AI.run` spans for the rest of the isolate's\n // life. Mirrors the same reset in the Node client.\n _INTERNAL_clearAiProviderSkips();\n super._setupIntegrations();\n\n // Registered after the integrations on purpose: the flush-point marker must run\n // after core and the span buffer have turned their buffers into envelopes on the\n // same `flush` emit (so those envelopes ride the boundary drain instead of starting\n // eager ones), and the eager span handler relies on `spanStreamingIntegration`\n // having already buffered the span that triggers it.\n if (this.isCachedClient) {\n // Marks the invocation's natural flush point: anything captured from now on\n // (post-response `waitUntil` work, detached continuations) has no later flush\n // to ride and is delivered eagerly by the hooks below.\n this.on('flush', () => {\n const invocationState = getInvocationState();\n if (invocationState) {\n invocationState.flushPointReached = true;\n }\n });\n this._setupEagerEnvelopeDelivery();\n this._setupEagerBufferDelivery();\n }\n }\n\n /**\n * Resets the span completion promise and resolve function.\n */\n private _resetSpanCompletionPromise(): void {\n this._pendingSpans.clear();\n this._spanCompletionPromise = null;\n this._resolveSpanCompletion = null;\n }\n\n /**\n * Drains the transport after an envelope has been accepted past the invocation's\n * flush point. The transport queues request producers until `flush()`; before the\n * flush point the boundary `flush()` drains everything, but envelopes created after\n * it (post-response `waitUntil` work, detached continuations) have no later flush to\n * ride. The drain is registered with the invocation's `waitUntil` to keep the fetch\n * alive; outside any instrumented invocation it always runs.\n */\n private _setupEagerEnvelopeDelivery(): void {\n this.on('afterEnvelope', () => {\n const transport = this.getTransport();\n const invocationState = getInvocationState();\n\n if (!transport || this._inBoundaryFlush || (invocationState && !invocationState.flushPointReached)) {\n return;\n }\n\n this._registerWithInvocationWaitUntil(transport.flush(2000));\n });\n }\n\n /**\n * Turns spans, logs and metrics captured past the invocation's flush point into\n * envelopes. Before the flush point the boundary `flush()` drains their buffers; after\n * it (or outside any instrumented invocation) nothing else would: the log/metric idle\n * timer is disabled for this runtime (`_flushInterval: 0`) and the span buffer's own 5s\n * timer fires outside any invocation, where the runtime suspends the send. Each capture\n * drains only its own bucket (the ended span's trace, the log buffer, the metric\n * buffer), so a fan-out of concurrent traces stays one envelope per trace. RPC method\n * spans never reach this path: `wrapMethodWithSentry` runs the boundary flush after the\n * method span has ended, so only work past that (e.g. detached continuations) lands here.\n */\n private _setupEagerBufferDelivery(): void {\n this.on('afterSpanEnd', span => {\n // The trace id must come from the span, not the current scope: `continueTrace`\n // writes the propagation context to the *current* scope, so the forked\n // isolation scope's propagation context carries a different trace id and\n // flushing by it silently no-ops.\n const traceId = span.spanContext().traceId;\n this._eagerDrain(() => this.emit('flushTraceSpans', traceId));\n });\n this.on('afterCaptureLog', () => this._eagerDrain(() => _INTERNAL_flushLogsBuffer(this)));\n this.on('afterCaptureMetric', () => this._eagerDrain(() => _INTERNAL_flushMetricsBuffer(this)));\n }\n\n /**\n * Runs `drain` unless the owning invocation has not reached its flush point yet\n * (before it the boundary `flush()` delivers the buffers).\n */\n private _eagerDrain(drain: () => void): void {\n const invocationState = getInvocationState();\n\n if (invocationState && !invocationState.flushPointReached) {\n return;\n }\n\n drain();\n }\n\n /**\n * Attaches a promise to the `waitUntil` of the invocation that owns the current\n * async context, so the runtime keeps the send alive after the response is returned.\n * Outside any instrumented invocation (or where the context has no `waitUntil`,\n * e.g. Astro prerendering) the send is fire-and-forget.\n */\n private _registerWithInvocationWaitUntil(promise: PromiseLike<unknown>): void {\n const invocationState = getInvocationState();\n const waitUntil = invocationState && getInvocationWaitUntil(invocationState);\n if (!waitUntil) {\n return;\n }\n\n try {\n waitUntil(\n Promise.resolve(promise).then(\n () => undefined,\n () => undefined,\n ),\n );\n } catch {\n // The owning invocation already ended; the send races isolate teardown either way.\n }\n }\n}\n\ninterface BaseCloudflareOptions {\n /**\n * @ignore Used internally to disable the deDupeIntegration for workflows.\n * @hidden Used internally to disable the deDupeIntegration for workflows.\n * @default true\n */\n enableDedupe?: boolean;\n\n /**\n * The Cloudflare SDK is not OpenTelemetry native. By default (`false`) it does not set up a tracer\n * provider; spans are emitted via the SDK's own instrumentation and scopes are isolated with\n * AsyncLocalStorage.\n *\n * Set this to `true` to opt into the OpenTelemetry compatibility tracer, which captures spans\n * emitted via `@opentelemetry/api`. Big caveat: it does not handle custom context, always working\n * off the current scope. This is good enough for many, but not all, integrations.\n *\n * @default false\n */\n enableOpenTelemetrySetup?: boolean;\n\n /**\n * The bindings on `env` that outgoing RPC calls propagate trace context to.\n *\n * Strings match a binding name exactly, regular expressions match by pattern. An empty array\n * (the default) propagates to nothing.\n *\n * RPC has no headers to carry trace context, so the SDK appends it as a trailing argument to\n * every RPC method call on a matching binding. Only a Sentry-instrumented receiver strips that\n * argument again. Anywhere else it arrives as a real argument and changes what the method was\n * called with, so list only the bindings whose receiver you know runs Sentry.\n *\n * Propagation over `stub.fetch()` and service binding `fetch()` uses HTTP headers and is not\n * affected by this option.\n *\n * Strings match a binding name exactly, regular expressions match by pattern. Both match\n * case-insensitively.\n *\n * When you build with the Sentry Cloudflare Vite plugin, bindings that resolve to *this* worker\n * (its own Durable Objects, its self service bindings) are added for you, because the plugin\n * instruments those receivers itself. Whatever you list here is added on top of them.\n *\n * @default []\n * @example\n * ```ts\n * // Propagate to `env.ORDERS` and every `env.SVC_*` binding\n * export default Sentry.withSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * rpcTracePropagationBindings: ['ORDERS', /^SVC_/],\n * }),\n * handler,\n * );\n * ```\n */\n rpcTracePropagationBindings?: TracePropagationTargets;\n\n /**\n * Table names that should stay instrumented even though they match a reserved prefix used by\n * Durable Object frameworks for their internal SQLite tables: `cf_` (`agents`, `partyserver`, ...)\n * and `pi_` (pi-durable in the `PiHarness` of `agents`).\n *\n * By default, `exec` queries against tables with these prefixes are treated as framework noise and\n * no `db.query` span is created for them. If one of your own tables happens to use such a prefix,\n * add it here to opt it back into instrumentation, or add `/^pi_/` to see the statements of\n * pi-durable. Entries are matched against each table name in the\n * query summary — strings must match exactly, while regular expressions give you prefix/pattern\n * matching.\n *\n * @default []\n * @example\n * ```ts\n * export default Sentry.withSentry(\n * (env) => ({\n * dsn: env.SENTRY_DSN,\n * durableObjectSqlSpanAllowlist: ['cf_my_table', /^cf_reports_/],\n * }),\n * handler,\n * );\n * ```\n */\n durableObjectSqlSpanAllowlist?: Array<string | RegExp>;\n\n /**\n * KV keys that should stay instrumented even though they match a reserved prefix used by Durable\n * Object frameworks (`agents`, `partyserver`, ...) for their internal storage entries.\n *\n * By default, KV reads/writes (`get`, `put`, `delete`, `list`) of `cf_`- or `__ps_`-prefixed keys\n * are treated as framework noise and no `durable_object_storage_*` span is created for them,\n * mirroring how `cf_`-prefixed SQL tables are handled (see {@link durableObjectSqlSpanAllowlist}).\n * If one of your own keys happens to use such a prefix, add it here to opt it back into\n * instrumentation. Strings must match exactly, while regular expressions give you prefix/pattern\n * matching.\n *\n * @default []\n * @example\n * ```ts\n * export default Sentry.withSentry(\n * (env) => ({\n * dsn: env.SENTRY_DSN,\n * durableObjectStorageSpanAllowlist: ['cf_my_key', /^cf_reports_/],\n * }),\n * handler,\n * );\n * ```\n */\n durableObjectStorageSpanAllowlist?: Array<string | RegExp>;\n\n /**\n * Sets an optional server name (device name).\n *\n * This is useful for identifying which server or instance is sending events.\n */\n serverName?: string;\n\n /**\n * If you use Spotlight by Sentry during development, use\n * this option to forward captured Sentry events to Spotlight.\n *\n * Either set it to true, or provide a specific Spotlight Sidecar URL.\n *\n * More details: https://spotlightjs.com/\n *\n * IMPORTANT: Only set this option to `true` while developing, not in production!\n */\n spotlight?: boolean | string;\n\n /**\n * Cache the client and reuse it across invocations within the same isolate.\n *\n * The SDK creates one client per isolate and reuses it for all requests/DO\n * handlers in that isolate. This avoids the per-invocation cost of\n * constructing a new client.\n *\n * Since a cached client outlives any single invocation, data captured after an\n * invocation's flush point (post-response `waitUntil` work, detached background\n * work) is delivered eagerly instead of waiting for a flush that never comes.\n *\n * The first `init()` in an isolate decides the cached client's options; later\n * `init()` calls with different options (e.g. another DSN) reuse the cached client\n * unchanged (a debug warning is logged for a DSN change). Use `cacheClient: false`\n * when options must differ per invocation.\n *\n * When disabled, a new client is created per invocation and disposed after the\n * handler completes.\n *\n * @default true\n */\n cacheClient?: boolean;\n}\n\n/**\n * Configuration options for the Sentry Cloudflare SDK\n *\n * @see @sentry/core Options for more information.\n */\nexport interface CloudflareOptions extends Options<CloudflareTransportOptions>, BaseCloudflareOptions {\n ctx?: ExecutionContextCompat;\n}\n\n/**\n * Configuration options for the Sentry Cloudflare SDK Client class\n *\n * @see CloudflareClient for more information.\n */\nexport interface CloudflareClientOptions extends ClientOptions<CloudflareTransportOptions>, BaseCloudflareOptions {\n flushLock?: ReturnType<typeof makeFlushLock>;\n}\n"],"names":["ServerRuntimeClient","applySdkMetadata","DEBUG_BUILD","debug","spanIsSampled","_INTERNAL_clearAiProviderSkips","getInvocationState","_INTERNAL_flushLogsBuffer","_INTERNAL_flushMetricsBuffer","getInvocationWaitUntil"],"mappings":";;;;;;;AAuBO,MAAM,yBAAyBA,0BAAA,CAAoB;AAAA;AAAA;AAAA;AAAA;AAAA,EAwBjD,YAAY,OAAA,EAAkC;AACnD,IAAAC,qBAAA,CAAiB,SAAS,YAAY,CAAA;AACtC,IAAA,OAAA,CAAQ,SAAA,GAAY,OAAA,CAAQ,SAAA,IAAa,EAAC;AAC1C,IAAA,MAAM,EAAE,SAAA,EAAW,GAAG,aAAA,EAAc,GAAI,OAAA;AAExC,IAAA,MAAM,aAAA,GAA4C;AAAA,MAChD,GAAG,aAAA;AAAA,MACH,QAAA,EAAU,YAAA;AAAA;AAAA,MAEV,OAAA,EAAS,EAAE,IAAA,EAAM,YAAA,EAAa;AAAA;AAAA,MAE9B,cAAA,EAAgB;AAAA,KAClB;AAEA,IAAA,KAAA,CAAM,aAAa,CAAA;AApCrB,IAAA,IAAA,CAAQ,aAAA,uBAAiC,GAAA,EAAI;AAC7C,IAAA,IAAA,CAAQ,sBAAA,GAA+C,IAAA;AACvD,IAAA,IAAA,CAAQ,sBAAA,GAA8C,IAAA;AAEtD,IAAA,IAAA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A;AAAA;AAAA;AAAA,EAMQ,YAAY,KAAA,EAAyB;AAC3C,IAAA,MAAM,kBAAkBF,oCAAA,EAAmB;AAE3C,IAAA,IAAI,eAAA,IAAmB,CAAC,eAAA,CAAgB,iBAAA,EAAmB;AACzD,MAAA;AAAA,IACF;AAEA,IAAA,KAAA,EAAM;AAAA,EACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQQ,iCAAiC,OAAA,EAAqC;AAC5E,IAAA,MAAM,kBAAkBA,oCAAA,EAAmB;AAC3C,IAAA,MAAM,SAAA,GAAY,eAAA,IAAmBG,wCAAA,CAAuB,eAAe,CAAA;AAC3E,IAAA,IAAI,CAAC,SAAA,EAAW;AACd,MAAA;AAAA,IACF;AAEA,IAAA,IAAI;AACF,MAAA,SAAA;AAAA,QACE,OAAA,CAAQ,OAAA,CAAQ,OAAO,CAAA,CAAE,IAAA;AAAA,UACvB,MAAM,KAAA,CAAA;AAAA,UACN,MAAM,KAAA;AAAA;AACR,OACF;AAAA,IACF,CAAA,CAAA,MAAQ;AAAA,IAER;AAAA,EACF;AACF;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentSqlStorage.js","sources":["../../../../src/instrumentations/instrumentSqlStorage.ts"],"sourcesContent":["import type { SqlStorage } from '@cloudflare/workers-types';\nimport { SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { DB_QUERY } from '@sentry/conventions/op';\nimport { getActiveSpan, getClient, hasSpansEnabled, spanIsSampled, startSpan } from '@sentry/core';\nimport { getSqlQuerySummary, sanitizeSqlQuery } from '@sentry/server-utils';\nimport type { CloudflareClientOptions } from '../client';\nimport { mayTargetCloudflareInternalTable, targetsCloudflareInternalTable } from '../utils/internalSqlQuery';\n\nconst SPAN_ATTRIBUTES = {\n [SENTRY_OP]: DB_QUERY,\n [SENTRY_ORIGIN]: 'auto.db.cloudflare.durable_object.sql',\n 'db.system.name': 'cloudflare-durable-object-sql',\n 'db.operation.name': 'exec',\n};\n\n/**\n * Instruments the Durable Object SqlStorage `exec` method with Sentry spans.\n *\n * @param sql - The SqlStorage instance to instrument\n * @returns An instrumented SqlStorage instance\n */\nexport function instrumentSqlStorage(sql: SqlStorage): SqlStorage {\n return new Proxy(sql, {\n get(target, prop, _receiver) {\n const original = Reflect.get(target, prop, target);\n\n if (prop !== 'exec' || typeof original !== 'function') {\n return original;\n }\n\n return function (this: unknown, ...args: unknown[]) {\n const callOriginal = (): ReturnType<SqlStorage['exec']> =>\n (original as (...a: unknown[]) => ReturnType<SqlStorage['exec']>).apply(target, args);\n\n const [query, ...bindings] = args as [string, ...unknown[]];\n\n if (childSpanWillNotBeRecorded() && !mayTargetCloudflareInternalTable(query)) {\n // This span is never sent, so skip the costly sanitize and summary\n // steps. We still start the span so it records its dropped span\n // outcome. A query that may target a `cf_` table takes the full path,\n // because an internal query must start no span.\n return startSpan({ name: 'exec', attributes: SPAN_ATTRIBUTES }, callOriginal);\n }\n\n const sanitizedQuery = sanitizeSqlQuery(query);\n const querySummary = getSqlQuerySummary(sanitizedQuery);\n\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion -- rule false positive: the cast reaches the Cloudflare-only `durableObjectSqlSpanAllowlist`; tsc errors without it\n const allowlist = (getClient()?.getOptions() as CloudflareClientOptions | undefined)\n ?.durableObjectSqlSpanAllowlist;\n\n if (targetsCloudflareInternalTable(querySummary, allowlist, sanitizedQuery)) {\n return callOriginal();\n }\n\n return startSpan(\n {\n name: querySummary || sanitizedQuery,\n attributes: {\n ...SPAN_ATTRIBUTES,\n 'db.query.text': sanitizedQuery,\n 'db.query.summary': querySummary,\n 'cloudflare.durable_object.query.bindings': bindings.length,\n },\n },\n callOriginal,\n );\n };\n },\n });\n}\n\n/**\n * Returns `true` when `startSpan` creates a non-recording span: spans are disabled, or the active span\n * is not sampled. Must agree with `createChildOrRootSpan` and `_startChildSpan` in `@sentry/core`.\n */\nfunction childSpanWillNotBeRecorded(): boolean {\n if (!hasSpansEnabled()) {\n return true;\n }\n\n const activeSpan = getActiveSpan();\n return !!activeSpan && !spanIsSampled(activeSpan);\n}\n"],"names":["SENTRY_OP","DB_QUERY","SENTRY_ORIGIN","mayTargetCloudflareInternalTable","startSpan","sanitizeSqlQuery","getSqlQuerySummary","getClient","targetsCloudflareInternalTable","hasSpansEnabled","getActiveSpan","spanIsSampled"],"mappings":";;;;;;;;AAQA,MAAM,eAAA,GAAkB;AAAA,EACtB,CAACA,oBAAS,GAAGC,WAAA;AAAA,EACb,CAACC,wBAAa,GAAG,uCAAA;AAAA,EACjB,gBAAA,EAAkB,+BAAA;AAAA,EAClB,mBAAA,EAAqB;AACvB,CAAA;AAQO,SAAS,qBAAqB,GAAA,EAA6B;AAChE,EAAA,OAAO,IAAI,MAAM,GAAA,EAAK;AAAA,IACpB,GAAA,CAAI,MAAA,EAAQ,IAAA,EAAM,SAAA,EAAW;AAC3B,MAAA,MAAM,QAAA,GAAW,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,MAAM,MAAM,CAAA;AAEjD,MAAA,IAAI,IAAA,KAAS,MAAA,IAAU,OAAO,QAAA,KAAa,UAAA,EAAY;AACrD,QAAA,OAAO,QAAA;AAAA,MACT;AAEA,MAAA,OAAO,YAA4B,IAAA,EAAiB;AAClD,QAAA,MAAM,YAAA,GAAe,MAClB,QAAA,CAAiE,KAAA,CAAM,QAAQ,IAAI,CAAA;AAEtF,QAAA,MAAM,CAAC,KAAA,EAAO,GAAG,QAAQ,CAAA,GAAI,IAAA;AAE7B,QAAA,IAAI,0BAAA,EAA2B,IAAK,CAACC,iDAAA,CAAiC,KAAK,CAAA,EAAG;AAK5E,UAAA,OAAOC,eAAU,EAAE,IAAA,EAAM,QAAQ,UAAA,EAAY,eAAA,IAAmB,YAAY,CAAA;AAAA,QAC9E;AAEA,QAAA,MAAM,cAAA,GAAiBC,6BAAiB,KAAK,CAAA;AAC7C,QAAA,MAAM,YAAA,GAAeC,+BAAmB,cAAc,CAAA;AAGtD,QAAA,MAAM,SAAA,GAAaC,cAAA,EAAU,EAAG,UAAA,EAAW,EACvC,6BAAA;AAEJ,QAAA,IAAIC,+CAAA,CAA+B,YAAA,EAAc,SAAA,EAAW,cAAc,CAAA,EAAG;AAC3E,UAAA,OAAO,YAAA,EAAa;AAAA,QACtB;AAEA,QAAA,OAAOJ,cAAA;AAAA,UACL;AAAA,YACE,MAAM,YAAA,IAAgB,cAAA;AAAA,YACtB,UAAA,EAAY;AAAA,cACV,GAAG,eAAA;AAAA,cACH,eAAA,EAAiB,cAAA;AAAA,cACjB,kBAAA,EAAoB,YAAA;AAAA,cACpB,4CAA4C,QAAA,CAAS;AAAA;AACvD,WACF;AAAA,UACA;AAAA,SACF;AAAA,MACF,CAAA;AAAA,IACF;AAAA,GACD,CAAA;AACH;AAMA,SAAS,0BAAA,GAAsC;AAC7C,EAAA,IAAI,CAACK,sBAAgB,EAAG;AACtB,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,MAAM,aAAaC,kBAAA,EAAc;AACjC,EAAA,OAAO,CAAC,CAAC,UAAA,IAAc,CAACC,mBAAc,UAAU,CAAA;AAClD;;;;"}
1
+ {"version":3,"file":"instrumentSqlStorage.js","sources":["../../../../src/instrumentations/instrumentSqlStorage.ts"],"sourcesContent":["import type { SqlStorage } from '@cloudflare/workers-types';\nimport { SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { DB_QUERY } from '@sentry/conventions/op';\nimport { getActiveSpan, getClient, hasSpansEnabled, spanIsSampled, startSpan } from '@sentry/core';\nimport { getSqlQuerySummary, sanitizeSqlQuery } from '@sentry/server-utils';\nimport type { CloudflareClientOptions } from '../client';\nimport { mayTargetCloudflareInternalTable, targetsCloudflareInternalTable } from '../utils/internalSqlQuery';\n\nconst SPAN_ATTRIBUTES = {\n [SENTRY_OP]: DB_QUERY,\n [SENTRY_ORIGIN]: 'auto.db.cloudflare.durable_object.sql',\n 'db.system.name': 'cloudflare-durable-object-sql',\n 'db.operation.name': 'exec',\n};\n\n/**\n * Instruments the Durable Object SqlStorage `exec` method with Sentry spans.\n *\n * @param sql - The SqlStorage instance to instrument\n * @returns An instrumented SqlStorage instance\n */\nexport function instrumentSqlStorage(sql: SqlStorage): SqlStorage {\n return new Proxy(sql, {\n get(target, prop, _receiver) {\n const original = Reflect.get(target, prop, target);\n\n if (prop !== 'exec' || typeof original !== 'function') {\n return original;\n }\n\n return function (this: unknown, ...args: unknown[]) {\n const callOriginal = (): ReturnType<SqlStorage['exec']> =>\n (original as (...a: unknown[]) => ReturnType<SqlStorage['exec']>).apply(target, args);\n\n const [query, ...bindings] = args as [string, ...unknown[]];\n\n if (childSpanWillNotBeRecorded() && !mayTargetCloudflareInternalTable(query)) {\n // This span is never sent, so skip the costly sanitize and summary\n // steps. We still start the span so it records its dropped span\n // outcome. A query that may target a `cf_` or `pi_` table takes the full path,\n // because an internal query must start no span.\n return startSpan({ name: 'exec', attributes: SPAN_ATTRIBUTES }, callOriginal);\n }\n\n const sanitizedQuery = sanitizeSqlQuery(query);\n const querySummary = getSqlQuerySummary(sanitizedQuery);\n\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion -- rule false positive: the cast reaches the Cloudflare-only `durableObjectSqlSpanAllowlist`; tsc errors without it\n const allowlist = (getClient()?.getOptions() as CloudflareClientOptions | undefined)\n ?.durableObjectSqlSpanAllowlist;\n\n if (targetsCloudflareInternalTable(querySummary, allowlist, sanitizedQuery)) {\n return callOriginal();\n }\n\n return startSpan(\n {\n name: querySummary || sanitizedQuery,\n attributes: {\n ...SPAN_ATTRIBUTES,\n 'db.query.text': sanitizedQuery,\n 'db.query.summary': querySummary,\n 'cloudflare.durable_object.query.bindings': bindings.length,\n },\n },\n callOriginal,\n );\n };\n },\n });\n}\n\n/**\n * Returns `true` when `startSpan` creates a non-recording span: spans are disabled, or the active span\n * is not sampled. Must agree with `createChildOrRootSpan` and `_startChildSpan` in `@sentry/core`.\n */\nfunction childSpanWillNotBeRecorded(): boolean {\n if (!hasSpansEnabled()) {\n return true;\n }\n\n const activeSpan = getActiveSpan();\n return !!activeSpan && !spanIsSampled(activeSpan);\n}\n"],"names":["SENTRY_OP","DB_QUERY","SENTRY_ORIGIN","mayTargetCloudflareInternalTable","startSpan","sanitizeSqlQuery","getSqlQuerySummary","getClient","targetsCloudflareInternalTable","hasSpansEnabled","getActiveSpan","spanIsSampled"],"mappings":";;;;;;;;AAQA,MAAM,eAAA,GAAkB;AAAA,EACtB,CAACA,oBAAS,GAAGC,WAAA;AAAA,EACb,CAACC,wBAAa,GAAG,uCAAA;AAAA,EACjB,gBAAA,EAAkB,+BAAA;AAAA,EAClB,mBAAA,EAAqB;AACvB,CAAA;AAQO,SAAS,qBAAqB,GAAA,EAA6B;AAChE,EAAA,OAAO,IAAI,MAAM,GAAA,EAAK;AAAA,IACpB,GAAA,CAAI,MAAA,EAAQ,IAAA,EAAM,SAAA,EAAW;AAC3B,MAAA,MAAM,QAAA,GAAW,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,MAAM,MAAM,CAAA;AAEjD,MAAA,IAAI,IAAA,KAAS,MAAA,IAAU,OAAO,QAAA,KAAa,UAAA,EAAY;AACrD,QAAA,OAAO,QAAA;AAAA,MACT;AAEA,MAAA,OAAO,YAA4B,IAAA,EAAiB;AAClD,QAAA,MAAM,YAAA,GAAe,MAClB,QAAA,CAAiE,KAAA,CAAM,QAAQ,IAAI,CAAA;AAEtF,QAAA,MAAM,CAAC,KAAA,EAAO,GAAG,QAAQ,CAAA,GAAI,IAAA;AAE7B,QAAA,IAAI,0BAAA,EAA2B,IAAK,CAACC,iDAAA,CAAiC,KAAK,CAAA,EAAG;AAK5E,UAAA,OAAOC,eAAU,EAAE,IAAA,EAAM,QAAQ,UAAA,EAAY,eAAA,IAAmB,YAAY,CAAA;AAAA,QAC9E;AAEA,QAAA,MAAM,cAAA,GAAiBC,6BAAiB,KAAK,CAAA;AAC7C,QAAA,MAAM,YAAA,GAAeC,+BAAmB,cAAc,CAAA;AAGtD,QAAA,MAAM,SAAA,GAAaC,cAAA,EAAU,EAAG,UAAA,EAAW,EACvC,6BAAA;AAEJ,QAAA,IAAIC,+CAAA,CAA+B,YAAA,EAAc,SAAA,EAAW,cAAc,CAAA,EAAG;AAC3E,UAAA,OAAO,YAAA,EAAa;AAAA,QACtB;AAEA,QAAA,OAAOJ,cAAA;AAAA,UACL;AAAA,YACE,MAAM,YAAA,IAAgB,cAAA;AAAA,YACtB,UAAA,EAAY;AAAA,cACV,GAAG,eAAA;AAAA,cACH,eAAA,EAAiB,cAAA;AAAA,cACjB,kBAAA,EAAoB,YAAA;AAAA,cACpB,4CAA4C,QAAA,CAAS;AAAA;AACvD,WACF;AAAA,UACA;AAAA,SACF;AAAA,MACF,CAAA;AAAA,IACF;AAAA,GACD,CAAA;AACH;AAMA,SAAS,0BAAA,GAAsC;AAC7C,EAAA,IAAI,CAACK,sBAAgB,EAAG;AACtB,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,MAAM,aAAaC,kBAAA,EAAc;AACjC,EAAA,OAAO,CAAC,CAAC,UAAA,IAAc,CAACC,mBAAc,UAAU,CAAA;AAClD;;;;"}
@@ -14,12 +14,14 @@ function targetsCloudflareInternalTable(querySummary, allowlist, queryText) {
14
14
  return tables.some((table) => isCloudflareInternalTable(table, allowlist));
15
15
  }
16
16
  function mayTargetCloudflareInternalTable(query) {
17
- return CF_PREFIX_RE.test(query);
17
+ return INTERNAL_PREFIX_RE.test(query);
18
18
  }
19
- const CF_PREFIX_RE = /\bcf_/i;
19
+ const INTERNAL_TABLE_PREFIXES = ["cf_", "pi_"];
20
+ const INTERNAL_PREFIX_RE = /\b(?:cf|pi)_/i;
20
21
  const CREATE_INDEX_TABLE_RE = /^\s*CREATE\s+(?:UNIQUE\s+)?INDEX(?:\s+IF\s+(?:NOT\s+)?EXISTS)?\s+[^\s(,;)]+\s+ON\s+(?<table>[^\s(,;)]+)/i;
21
22
  function isCloudflareInternalTable(table, allowlist) {
22
- if (!table.toLowerCase().startsWith("cf_")) {
23
+ const name = table.toLowerCase();
24
+ if (!INTERNAL_TABLE_PREFIXES.some((prefix) => name.startsWith(prefix))) {
23
25
  return false;
24
26
  }
25
27
  return !allowlist?.length || !core.stringMatchesSomePattern(table, allowlist, true);
@@ -1 +1 @@
1
- {"version":3,"file":"internalSqlQuery.js","sources":["../../../../src/utils/internalSqlQuery.ts"],"sourcesContent":["import { stringMatchesSomePattern } from '@sentry/core';\n\n/**\n * Cloudflare frameworks that build on Durable Objects (`agents`, `partyserver`, ...) manage their\n * own internal SQLite tables, all namespaced with a `cf_` prefix — e.g. `cf_agents_schedules`,\n * `cf_agent_state`, `cf_ai_chat_stream_chunks`. Queries against them (schedule polling, chat-stream\n * persistence, state bookkeeping) are framework implementation details that otherwise flood traces\n * with dozens of zero-signal `db.query` spans per request. The exact set of tables even varies\n * between framework versions, so we match the reserved prefix rather than an enumerated list.\n *\n * The `cf_` prefix is a reserved convention for framework-managed tables, so user tables should not\n * use it. In case a user table does collide with the prefix, the `durableObjectSqlSpanAllowlist`\n * option lets them opt those tables back into instrumentation.\n *\n * The check operates on the query summary produced by `getSqlQuerySummary` (`{operation} {table} ...`,\n * the same value used as the span name), so table targets are already isolated from the rest of the\n * query. The one exception is `CREATE INDEX`: its summary carries the index name, not the indexed\n * table (upstream OTel convention), so the `cf_` target only appears in the ON clause of the full\n * statement, which `queryText` is needed for.\n */\nexport function targetsCloudflareInternalTable(\n querySummary: string | undefined,\n allowlist?: Array<string | RegExp>,\n queryText?: string,\n): boolean {\n if (!querySummary) {\n return false;\n }\n\n const indexedTable = queryText ? CREATE_INDEX_TABLE_RE.exec(queryText)?.groups?.['table'] : undefined;\n if (indexedTable) {\n return isCloudflareInternalTable(indexedTable, allowlist);\n }\n\n const [, ...tables] = querySummary.split(' ');\n\n return tables.some(table => isCloudflareInternalTable(table, allowlist));\n}\n\n/**\n * Returns `false` when the raw `query` has no word that starts with `cf_`, so it cannot target a\n * Cloudflare internal table. Needs no sanitizing, which makes it cheap enough to run on every query.\n */\nexport function mayTargetCloudflareInternalTable(query: string): boolean {\n return CF_PREFIX_RE.test(query);\n}\n\nconst CF_PREFIX_RE = /\\bcf_/i;\n\n// `CREATE [UNIQUE] INDEX [IF NOT EXISTS] <name> ON <table>` — the IF EXISTS shape mirrors DDL_RE\n// in @sentry/core.\nconst CREATE_INDEX_TABLE_RE =\n /^\\s*CREATE\\s+(?:UNIQUE\\s+)?INDEX(?:\\s+IF\\s+(?:NOT\\s+)?EXISTS)?\\s+[^\\s(,;)]+\\s+ON\\s+(?<table>[^\\s(,;)]+)/i;\n\nfunction isCloudflareInternalTable(table: string, allowlist?: Array<string | RegExp>): boolean {\n if (!table.toLowerCase().startsWith('cf_')) {\n return false;\n }\n\n // A table on the allowlist is treated as a user table and stays instrumented, even though it\n // matches the reserved prefix.\n return !allowlist?.length || !stringMatchesSomePattern(table, allowlist, true);\n}\n"],"names":["stringMatchesSomePattern"],"mappings":";;;;AAoBO,SAAS,8BAAA,CACd,YAAA,EACA,SAAA,EACA,SAAA,EACS;AACT,EAAA,IAAI,CAAC,YAAA,EAAc;AACjB,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,MAAM,YAAA,GAAe,YAAY,qBAAA,CAAsB,IAAA,CAAK,SAAS,CAAA,EAAG,MAAA,GAAS,OAAO,CAAA,GAAI,MAAA;AAC5F,EAAA,IAAI,YAAA,EAAc;AAChB,IAAA,OAAO,yBAAA,CAA0B,cAAc,SAAS,CAAA;AAAA,EAC1D;AAEA,EAAA,MAAM,GAAG,GAAG,MAAM,CAAA,GAAI,YAAA,CAAa,MAAM,GAAG,CAAA;AAE5C,EAAA,OAAO,OAAO,IAAA,CAAK,CAAA,KAAA,KAAS,yBAAA,CAA0B,KAAA,EAAO,SAAS,CAAC,CAAA;AACzE;AAMO,SAAS,iCAAiC,KAAA,EAAwB;AACvE,EAAA,OAAO,YAAA,CAAa,KAAK,KAAK,CAAA;AAChC;AAEA,MAAM,YAAA,GAAe,QAAA;AAIrB,MAAM,qBAAA,GACJ,0GAAA;AAEF,SAAS,yBAAA,CAA0B,OAAe,SAAA,EAA6C;AAC7F,EAAA,IAAI,CAAC,KAAA,CAAM,WAAA,EAAY,CAAE,UAAA,CAAW,KAAK,CAAA,EAAG;AAC1C,IAAA,OAAO,KAAA;AAAA,EACT;AAIA,EAAA,OAAO,CAAC,SAAA,EAAW,MAAA,IAAU,CAACA,6BAAA,CAAyB,KAAA,EAAO,WAAW,IAAI,CAAA;AAC/E;;;;;"}
1
+ {"version":3,"file":"internalSqlQuery.js","sources":["../../../../src/utils/internalSqlQuery.ts"],"sourcesContent":["import { stringMatchesSomePattern } from '@sentry/core';\n\n/**\n * Cloudflare frameworks that build on Durable Objects (`agents`, `partyserver`, ...) manage their\n * own internal SQLite tables, all namespaced with a `cf_` prefix — e.g. `cf_agents_schedules`,\n * `cf_agent_state`, `cf_ai_chat_stream_chunks`. Queries against them (schedule polling, chat-stream\n * persistence, state bookkeeping) are framework implementation details that otherwise flood traces\n * with dozens of zero-signal `db.query` spans per request. The exact set of tables even varies\n * between framework versions, so we match the reserved prefix rather than an enumerated list.\n *\n * The `cf_` prefix is a reserved convention for framework-managed tables, so user tables should not\n * use it. The same goes for `pi_`: the `PiHarness` of `agents` keeps the state of pi-durable in\n * tables with that prefix, and one run writes close to 200 statements. In case a user table does\n * collide with a prefix, the `durableObjectSqlSpanAllowlist` option lets them opt those tables back\n * into instrumentation.\n *\n * The check operates on the query summary produced by `getSqlQuerySummary` (`{operation} {table} ...`,\n * the same value used as the span name), so table targets are already isolated from the rest of the\n * query. The one exception is `CREATE INDEX`: its summary carries the index name, not the indexed\n * table (upstream OTel convention), so the `cf_` target only appears in the ON clause of the full\n * statement, which `queryText` is needed for.\n */\nexport function targetsCloudflareInternalTable(\n querySummary: string | undefined,\n allowlist?: Array<string | RegExp>,\n queryText?: string,\n): boolean {\n if (!querySummary) {\n return false;\n }\n\n const indexedTable = queryText ? CREATE_INDEX_TABLE_RE.exec(queryText)?.groups?.['table'] : undefined;\n if (indexedTable) {\n return isCloudflareInternalTable(indexedTable, allowlist);\n }\n\n const [, ...tables] = querySummary.split(' ');\n\n return tables.some(table => isCloudflareInternalTable(table, allowlist));\n}\n\n/**\n * Returns `false` when the raw `query` has no word that starts with `cf_` or `pi_`, so it cannot\n * target a Cloudflare internal table. Needs no sanitizing, which makes it cheap enough to run on\n * every query.\n */\nexport function mayTargetCloudflareInternalTable(query: string): boolean {\n return INTERNAL_PREFIX_RE.test(query);\n}\n\nconst INTERNAL_TABLE_PREFIXES = ['cf_', 'pi_'];\nconst INTERNAL_PREFIX_RE = /\\b(?:cf|pi)_/i;\n\n// `CREATE [UNIQUE] INDEX [IF NOT EXISTS] <name> ON <table>` — the IF EXISTS shape mirrors DDL_RE\n// in @sentry/core.\nconst CREATE_INDEX_TABLE_RE =\n /^\\s*CREATE\\s+(?:UNIQUE\\s+)?INDEX(?:\\s+IF\\s+(?:NOT\\s+)?EXISTS)?\\s+[^\\s(,;)]+\\s+ON\\s+(?<table>[^\\s(,;)]+)/i;\n\nfunction isCloudflareInternalTable(table: string, allowlist?: Array<string | RegExp>): boolean {\n const name = table.toLowerCase();\n if (!INTERNAL_TABLE_PREFIXES.some(prefix => name.startsWith(prefix))) {\n return false;\n }\n\n // A table on the allowlist is treated as a user table and stays instrumented, even though it\n // matches the reserved prefix.\n return !allowlist?.length || !stringMatchesSomePattern(table, allowlist, true);\n}\n"],"names":["stringMatchesSomePattern"],"mappings":";;;;AAsBO,SAAS,8BAAA,CACd,YAAA,EACA,SAAA,EACA,SAAA,EACS;AACT,EAAA,IAAI,CAAC,YAAA,EAAc;AACjB,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,MAAM,YAAA,GAAe,YAAY,qBAAA,CAAsB,IAAA,CAAK,SAAS,CAAA,EAAG,MAAA,GAAS,OAAO,CAAA,GAAI,MAAA;AAC5F,EAAA,IAAI,YAAA,EAAc;AAChB,IAAA,OAAO,yBAAA,CAA0B,cAAc,SAAS,CAAA;AAAA,EAC1D;AAEA,EAAA,MAAM,GAAG,GAAG,MAAM,CAAA,GAAI,YAAA,CAAa,MAAM,GAAG,CAAA;AAE5C,EAAA,OAAO,OAAO,IAAA,CAAK,CAAA,KAAA,KAAS,yBAAA,CAA0B,KAAA,EAAO,SAAS,CAAC,CAAA;AACzE;AAOO,SAAS,iCAAiC,KAAA,EAAwB;AACvE,EAAA,OAAO,kBAAA,CAAmB,KAAK,KAAK,CAAA;AACtC;AAEA,MAAM,uBAAA,GAA0B,CAAC,KAAA,EAAO,KAAK,CAAA;AAC7C,MAAM,kBAAA,GAAqB,eAAA;AAI3B,MAAM,qBAAA,GACJ,0GAAA;AAEF,SAAS,yBAAA,CAA0B,OAAe,SAAA,EAA6C;AAC7F,EAAA,MAAM,IAAA,GAAO,MAAM,WAAA,EAAY;AAC/B,EAAA,IAAI,CAAC,wBAAwB,IAAA,CAAK,CAAA,MAAA,KAAU,KAAK,UAAA,CAAW,MAAM,CAAC,CAAA,EAAG;AACpE,IAAA,OAAO,KAAA;AAAA,EACT;AAIA,EAAA,OAAO,CAAC,SAAA,EAAW,MAAA,IAAU,CAACA,6BAAA,CAAyB,KAAA,EAAO,WAAW,IAAI,CAAA;AAC/E;;;;;"}
@@ -10,14 +10,24 @@ function normalizePath(path) {
10
10
  return path.replace(/\\/g, "/");
11
11
  }
12
12
  const JS_EXTENSION_REGEX = /\.[cm]?[jt]sx?$/;
13
+ const NEXTJS_CLOUDFLARE_MODULE = "@sentry/nextjs/cloudflare";
14
+ async function resolvesNextjsCloudflare(resolver, importer) {
15
+ try {
16
+ return !!await resolver.resolve?.(NEXTJS_CLOUDFLARE_MODULE, importer);
17
+ } catch {
18
+ return false;
19
+ }
20
+ }
13
21
  function sentryCloudflareAutoInstrumentPlugin(options = {}) {
14
22
  let wranglerConfig$1;
15
23
  let entryFilePath;
16
24
  let optionsFn = instrumentFile.ENV_FALLBACK_OPTIONS_FN;
17
25
  let optionsImport;
26
+ let isVinext = false;
18
27
  return {
19
28
  name: "sentry-cloudflare-auto-instrument",
20
29
  configResolved(config) {
30
+ isVinext = config.plugins?.some((plugin) => plugin.name?.startsWith("vinext:")) ?? false;
21
31
  const result = wranglerConfig.resolveWranglerConfig(config.root, options.wranglerConfigPath);
22
32
  if (!result) {
23
33
  config.logger?.warn(
@@ -72,12 +82,14 @@ function sentryCloudflareAutoInstrumentPlugin(options = {}) {
72
82
  parse: (code2) => this.parse(code2),
73
83
  resolve: this.resolve ? (source, importer) => this.resolve(source, importer) : void 0
74
84
  }) : void 0;
85
+ const sentryModule = isVinext && await resolvesNextjsCloudflare(this, normalizedId) ? NEXTJS_CLOUDFLARE_MODULE : void 0;
75
86
  const result = transform.applyAutoInstrumentTransforms(code, ast, {
76
87
  classWrappers,
77
88
  agentClasses,
78
89
  optionsFn,
79
90
  optionsImport,
80
- sameWorkerBindings: wranglerConfig$1.sameWorkerBindings
91
+ sameWorkerBindings: wranglerConfig$1.sameWorkerBindings,
92
+ sentryModule
81
93
  });
82
94
  const wrappedClasses = result?.wrappedClasses ?? /* @__PURE__ */ new Set();
83
95
  const missing = [...classWrappers.keys()].filter((name) => !wrappedClasses.has(name));
@@ -1 +1 @@
1
- {"version":3,"file":"autoInstrument.js","sources":["../../../../src/vite/autoInstrument.ts"],"sourcesContent":["import { basename } from 'node:path';\nimport { collectAgentCandidates, detectAgentClasses, type ModuleResolver } from './agentClass';\nimport { buildOptionsImport, ENV_FALLBACK_OPTIONS_FN, resolveInstrumentFile } from './instrumentFile';\nimport { applyAutoInstrumentTransforms, 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\nexport function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPath?: string } = {}) {\n let wranglerConfig: WranglerConfig | undefined;\n let entryFilePath: string | undefined;\n\n let optionsFn = ENV_FALLBACK_OPTIONS_FN;\n let optionsImport: string | undefined;\n\n return {\n name: 'sentry-cloudflare-auto-instrument',\n\n configResolved(config: { root: string; logger?: { warn(msg: string): void } }): void {\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 if (wranglerConfig.main) {\n // `main` is already absolute (wrangler resolves it); just normalize\n // separators so the entry-module comparison holds on Windows.\n entryFilePath = normalizePath(wranglerConfig.main);\n }\n\n if (entryFilePath) {\n const instrumentFilePath = resolveInstrumentFile(entryFilePath);\n if (instrumentFilePath) {\n const built = buildOptionsImport(entryFilePath, instrumentFilePath);\n optionsFn = built.optionsFn;\n optionsImport = built.importStmt;\n }\n }\n },\n\n async transform(\n this: ModuleResolver & { warn?(msg: string): void; environment?: { name?: string } },\n code: string,\n id: string,\n ): Promise<{ code: string; map: unknown } | undefined> {\n if (!wranglerConfig || !entryFilePath) 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 // Vite may append query/hash params to the module ID.\n const normalizedId = normalizePath(id.replace(/[?#].*$/, ''));\n if (normalizedId !== entryFilePath) {\n // Tolerate a differing JS-flavored extension (e.g. `.js` vs `.ts`).\n if (!JS_EXTENSION_REGEX.test(normalizedId) || !JS_EXTENSION_REGEX.test(entryFilePath)) return undefined;\n if (normalizedId.replace(JS_EXTENSION_REGEX, '') !== entryFilePath.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 // 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 });\n\n const wrappedClasses = result?.wrappedClasses ?? new Set<string>();\n const missing = [...classWrappers.keys()].filter(name => !wrappedClasses.has(name));\n if (missing.length > 0) {\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"],"names":["wranglerConfig","ENV_FALLBACK_OPTIONS_FN","resolveWranglerConfig","basename","resolveInstrumentFile","buildOptionsImport","collectAgentCandidates","detectAgentClasses","code","applyAutoInstrumentTransforms"],"mappings":";;;;;;;;AAQA,SAAS,cAAc,IAAA,EAAsB;AAC3C,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA;AAChC;AAKA,MAAM,kBAAA,GAAqB,iBAAA;AAEpB,SAAS,oCAAA,CAAqC,OAAA,GAA2C,EAAC,EAAG;AAClG,EAAA,IAAIA,gBAAA;AACJ,EAAA,IAAI,aAAA;AAEJ,EAAA,IAAI,SAAA,GAAYC,sCAAA;AAChB,EAAA,IAAI,aAAA;AAEJ,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,mCAAA;AAAA,IAEN,eAAe,MAAA,EAAsE;AACnF,MAAA,MAAM,MAAA,GAASC,oCAAA,CAAsB,MAAA,CAAO,IAAA,EAAM,QAAQ,kBAAkB,CAAA;AAC5E,MAAA,IAAI,CAAC,MAAA,EAAQ;AAIX,QAAA,MAAA,CAAO,MAAA,EAAQ,IAAA;AAAA,UACb,QAAQ,kBAAA,GACJ,CAAA,sDAAA,EAAyDC,mBAAS,OAAA,CAAQ,kBAAkB,CAAC,CAAA,wEAAA,CAAA,GAE7F;AAAA,SAEN;AACA,QAAA;AAAA,MACF;AAEA,MAAAH,gBAAA,GAAiB,MAAA,CAAO,MAAA;AACxB,MAAA,IAAIA,iBAAe,IAAA,EAAM;AA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AAY;AACjE,MAAA,MAAM,OAAA,GAAU,CAAC,GAAG,aAAA,CAAc,IAAA,EAAM,CAAA,CAAE,MAAA,CAAO,CAAA,IAAA,KAAQ,CAAC,cAAA,CAAe,GAAA,CAAI,IAAI,CAAC,CAAA;AAClF,MAAA,IAAI,OAAA,CAAQ,SAAS,CAAA,EAAG;AACtB,QAAA,IAAA,CAAK,IAAA;AAAA,UACH,CAAA,mCAAA,EAAsC,OAAA,CAAQ,IAAA,CAAK,IAAI,CAAC,CAAA,0MAAA;AAAA,SAI1D;AAAA,MACF;AAEA,MAAA,OAAO,MAAA,IAAU,MAAA;AAAA,IACnB;AAAA,GACF;AACF;;;;"}
1
+ {"version":3,"file":"autoInstrument.js","sources":["../../../../src/vite/autoInstrument.ts"],"sourcesContent":["import { basename } from 'node:path';\nimport { collectAgentCandidates, detectAgentClasses, type ModuleResolver } from './agentClass';\nimport { buildOptionsImport, ENV_FALLBACK_OPTIONS_FN, resolveInstrumentFile } from './instrumentFile';\nimport { applyAutoInstrumentTransforms, 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\nexport function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPath?: string } = {}) {\n let wranglerConfig: WranglerConfig | undefined;\n let entryFilePath: string | undefined;\n\n let optionsFn = ENV_FALLBACK_OPTIONS_FN;\n let optionsImport: string | undefined;\n let isVinext = false;\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 if (wranglerConfig.main) {\n // `main` is already absolute (wrangler resolves it); just normalize\n // separators so the entry-module comparison holds on Windows.\n entryFilePath = normalizePath(wranglerConfig.main);\n }\n\n if (entryFilePath) {\n const instrumentFilePath = resolveInstrumentFile(entryFilePath);\n if (instrumentFilePath) {\n const built = buildOptionsImport(entryFilePath, instrumentFilePath);\n optionsFn = built.optionsFn;\n optionsImport = built.importStmt;\n }\n }\n },\n\n async transform(\n this: ModuleResolver & { warn?(msg: string): void; environment?: { name?: string } },\n code: string,\n id: string,\n ): Promise<{ code: string; map: unknown } | undefined> {\n if (!wranglerConfig || !entryFilePath) 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 // Vite may append query/hash params to the module ID.\n const normalizedId = normalizePath(id.replace(/[?#].*$/, ''));\n if (normalizedId !== entryFilePath) {\n // Tolerate a differing JS-flavored extension (e.g. `.js` vs `.ts`).\n if (!JS_EXTENSION_REGEX.test(normalizedId) || !JS_EXTENSION_REGEX.test(entryFilePath)) return undefined;\n if (normalizedId.replace(JS_EXTENSION_REGEX, '') !== entryFilePath.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 // 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) {\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"],"names":["wranglerConfig","ENV_FALLBACK_OPTIONS_FN","resolveWranglerConfig","basename","resolveInstrumentFile","buildOptionsImport","collectAgentCandidates","detectAgentClasses","code","applyAutoInstrumentTransforms"],"mappings":";;;;;;;;AAQA,SAAS,cAAc,IAAA,EAAsB;AAC3C,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA;AAChC;AAKA,MAAM,kBAAA,GAAqB,iBAAA;AAG3B,MAAM,wBAAA,GAA2B,2BAAA;AAMjC,eAAe,wBAAA,CAAyB,UAA0B,QAAA,EAAoC;AACpG,EAAA,IAAI;AACF,IAAA,OAAO,CAAC,CAAE,MAAM,QAAA,CAAS,OAAA,GAAU,0BAA0B,QAAQ,CAAA;AAAA,EACvE,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF;AAEO,SAAS,oCAAA,CAAqC,OAAA,GAA2C,EAAC,EAAG;AAClG,EAAA,IAAIA,gBAAA;AACJ,EAAA,IAAI,aAAA;AAEJ,EAAA,IAAI,SAAA,GAAYC,sCAAA;AAChB,E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rumentTransforms(code, ast, ctx) {
56
56
  ms.prepend(buildMergedOptionsDeclaration(sameWorkerBindings, ctx.optionsFn, state));
57
57
  }
58
58
  if (ctx.optionsImport) ms.prepend(ctx.optionsImport);
59
- ms.prepend("import * as __SENTRY__ from '@sentry/cloudflare';\n");
59
+ ms.prepend(`import * as __SENTRY__ from '${ctx.sentryModule ?? "@sentry/cloudflare"}';
60
+ `);
60
61
  return {
61
62
  code: ms.toString(),
62
63
  map: ms.generateMap({ hires: true }),
@@ -1 +1 @@
1
- {"version":3,"file":"transform.js","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\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 /** @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 };\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 '@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 (non-exported) class declarations, 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}\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 if (node.type !== 'VariableDeclaration') continue;\n for (const declarator of (node 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 collectTopLevelClasses(ast: ProgramBody): Map<string, ClassDeclarationNode> {\n const classes = new Map<string, ClassDeclarationNode>();\n for (const node of ast.body) {\n if (node.type !== 'ClassDeclaration') continue;\n const classNode = node as ClassDeclarationNode;\n if (classNode.id?.name) classes.set(classNode.id.name, classNode);\n }\n return classes;\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 // `export default <expr>` → `const __SENTRY_DEFAULT_EXPORT__ = <expr>`\n // MagicString positions are always relative to the original source.\n state.ms.overwrite(node.start, decl.start, 'const __SENTRY_DEFAULT_EXPORT__ = ');\n state.ms.append(`\\nexport default __SENTRY__.withSentry(${state.optionsFn}, __SENTRY_DEFAULT_EXPORT__);\\n`);\n state.needsImport = true;\n state.autoWrapped.add(DEFAULT_EXPORT);\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 * 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 || !kind) return undefined;\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"],"names":["MagicString","detectWorkerEntrypointClasses","DEFAULT_EXPORT","wrappedName"],"mappings":";;;;;;AAKA,MAAM,yBAAA,GAA4B,oBAAA;AA0DlC,SAAS,cAAA,CAAe,MAAgB,UAAA,EAA6B;AACnE,EAAA,IAAI,IAAA,CAAK,IAAA,KAAS,gBAAA,EAAkB,OAAO,KAAA;AAC3C,EAAA,MAAM,SAAU,IAAA,CAA4B,MAAA;AAC5C,EAAA,IAAI,CAAC,QAAQ,OAAO,KAAA;AACpB,EAAA,IAAI,OAAO,IAAA,KAAS,YAAA,IAAgB,MAAA,CAAO,IAAA,KAAS,YAAY,OAAO,IAAA;AACvE,EAAA,OACE,MAAA,CAAO,SAAS,kBAAA,IAAsB,MAAA,CAAO,UAAU,IAAA,KAAS,YAAA,IAAgB,MAAA,CAAO,QAAA,CAAS,IAAA,KAAS,UAAA;AAE7G;AAgBA,MAAM,cAAA,GAAiB,SAAA;AAOvB,MAAM,eAAA,GAAoD;AAAA,EACxD,aAAA,EAAe,mCAAA;AAAA,EACf,KAAA,EAAO,2BAAA;AAAA,EACP,QAAA,EAAU,8BAAA;AAAA,EACV,gBAAA,EAAkB;AACp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A,CAAsB,GAAA,CAAI,SAAS,CAAA,EAAG;AAC9C,MAAA,KAAA,CAAM,cAAA,CAAe,IAAI,YAAY,CAAA;AACrC,MAAA,OAAO,MAAA;AAAA,IACT;AAAA,EACF;AAIA,EAAA,IAAI,MAAA,GAAS,SAAA;AAEb,EAAA,IAAI,aAAA,EAAe;AACjB,IAAA,MAAA,GAAS,qBAAqB,YAAY,CAAA,EAAA,CAAA;AAC1C,IAAA,OAAA,CAAQ,IAAA;AAAA,MACN,SAAA,KAAc,cAAA,GACV,CAAA,OAAA,EAAU,MAAM,CAAA,MAAA,EAAS,aAAa,CAAA,CAAA,CAAA,GACtC,CAAA,SAAA,EAAY,SAAS,CAAA,IAAA,EAAO,MAAM,CAAA,QAAA,EAAW,aAAa,CAAA,CAAA;AAAA,KAChE;AAAA,EACF;AAEA,EAAA,MAAM,WAAA,GAAc,oBAAoB,YAAY,CAAA,EAAA,CAAA;AAIpD,EAAA,OAAA,CAAQ,IAAA;AAAA,IACN,CAAA,MAAA,EAAS,WAAW,CAAA,0DAAA,EAA6D,eAAA,CAAgB,IAAI,CAAC,CAAA,EAAA,EAAK,KAAA,CAAM,SAAS,CAAA,EAAA,EAAK,MAAM,CAAA,EAAA;AAAA,GACvI;AACA,EAAA,KAAA,CAAM,cAAA,CAAe,IAAI,YAAY,CAAA;AACrC,EAAA,KAAA,CAAM,WAAA,CAAY,IAAI,YAAY,CAAA;AAClC,EAAA,KAAA,CAAM,WAAA,GAAc,IAAA;AAEpB,EAAA,OAAO,CAAA,EAAG,WAAW,CAAA,IAAA,EAAO,YAAY,CAAA,CAAA;AAC1C;;;;"}
1
+ {"version":3,"file":"transform.js","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\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 };\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 (non-exported) class declarations, 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}\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 if (node.type !== 'VariableDeclaration') continue;\n for (const declarator of (node 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 collectTopLevelClasses(ast: ProgramBody): Map<string, ClassDeclarationNode> {\n const classes = new Map<string, ClassDeclarationNode>();\n for (const node of ast.body) {\n if (node.type !== 'ClassDeclaration') continue;\n const classNode = node as ClassDeclarationNode;\n if (classNode.id?.name) classes.set(classNode.id.name, classNode);\n }\n return classes;\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 // `export default <expr>` → `const __SENTRY_DEFAULT_EXPORT__ = <expr>`\n // MagicString positions are always relative to the original source.\n state.ms.overwrite(node.start, decl.start, 'const __SENTRY_DEFAULT_EXPORT__ = ');\n state.ms.append(`\\nexport default __SENTRY__.withSentry(${state.optionsFn}, __SENTRY_DEFAULT_EXPORT__);\\n`);\n state.needsImport = true;\n state.autoWrapped.add(DEFAULT_EXPORT);\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 * 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 || !kind) return undefined;\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"],"names":["MagicString","detectWorkerEntrypointClasses","DEFAULT_EXPORT","wrappedName"],"mappings":";;;;;;AAKA,MAAM,yBAAA,GAA4B,oBAAA;AA0DlC,SAAS,cAAA,CAAe,MAAgB,UAAA,EAA6B;AACnE,EAAA,IAAI,IAAA,CAAK,IAAA,KAAS,gBAAA,EAAkB,OAAO,KAAA;AAC3C,EAAA,MAAM,SAAU,IAAA,CAA4B,MAAA;AAC5C,EAAA,IAAI,CAAC,QAAQ,OAAO,KAAA;AACpB,EAAA,IAAI,OAAO,IAAA,KAAS,YAAA,IAAgB,MAAA,CAAO,IAAA,KAAS,YAAY,OAAO,IAAA;AACvE,EAAA,OACE,MAAA,CAAO,SAAS,kBAAA,IAAsB,MAAA,CAAO,UAAU,IAAA,KAAS,YAAA,IAAgB,MAAA,CAAO,QAAA,CAAS,IAAA,KAAS,UAAA;AAE7G;AAgBA,MAAM,cAAA,GAAiB,SAAA;AAOvB,MAAM,eAAA,GAAoD;AAAA,EACxD,aAAA,EAAe,mCAAA;AAAA,EACf,KAAA,EAAO,2BAAA;AAAA,EACP,QAAA,EAAU,8BAAA;AAAA,EACV,gBAAA,EAAkB;AACpB,CAAA;AAmDO,SAAS,6BAAA,CACd,IAAA,EACA,GAAA,EACA,GAAA,EAC6B;AAC7B,EAAA,MAAM,EAAA,GAAK,IAAIA,mBAAA,CAAY,IAAI,CAAA;AAC/B,EAAA,MAAM,eAAA,GAAkB,uBAAuB,GAAG,CAAA;AAClD,EAAA,MAAM,kBAAA,GAAqB,GAAA,CAAI,kBAAA,IAAsB,EAAC;AACtD,EAAA,MAAM,KAAA,GAAwB;AAAA,IAC5B,EAAA;AAAA,IACA,WAAA,EAAa,KAAA;AAAA,IACb,cAAA,sBAAoB,GAAA,EAAY;AAAA,IAChC,eAAA;AAAA,IACA,aAAA,sBAAmB,GAAA,EAAoB;AAAA,IACvC,eAAe,GAAA,CAAI,aAAA;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