@sentry/cloudflare 11.13.0 → 11.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cjs/dev/baseSdk.js.map +1 -1
- package/build/cjs/dev/client.js +6 -1
- package/build/cjs/dev/client.js.map +1 -1
- package/build/cjs/dev/durableobject.js.map +1 -1
- package/build/cjs/dev/options.js +1 -0
- package/build/cjs/dev/options.js.map +1 -1
- package/build/cjs/dev/vite/autoInstrument.js +5 -1
- package/build/cjs/dev/vite/autoInstrument.js.map +1 -1
- package/build/cjs/dev/vite/index.js.map +1 -1
- package/build/cjs/dev/vite/transform.js +12 -13
- package/build/cjs/dev/vite/transform.js.map +1 -1
- package/build/cjs/dev/vite/wranglerConfig.js +2 -0
- package/build/cjs/dev/vite/wranglerConfig.js.map +1 -1
- package/build/cjs/prod/baseSdk.js.map +1 -1
- package/build/cjs/prod/client.js +6 -1
- package/build/cjs/prod/client.js.map +1 -1
- package/build/cjs/prod/durableobject.js.map +1 -1
- package/build/cjs/prod/options.js +1 -0
- package/build/cjs/prod/options.js.map +1 -1
- package/build/cjs/prod/vite/autoInstrument.js +5 -1
- package/build/cjs/prod/vite/autoInstrument.js.map +1 -1
- package/build/cjs/prod/vite/index.js.map +1 -1
- package/build/cjs/prod/vite/transform.js +12 -13
- package/build/cjs/prod/vite/transform.js.map +1 -1
- package/build/cjs/prod/vite/wranglerConfig.js +2 -0
- package/build/cjs/prod/vite/wranglerConfig.js.map +1 -1
- package/build/esm/dev/baseSdk.js.map +1 -1
- package/build/esm/dev/client.js +7 -2
- package/build/esm/dev/client.js.map +1 -1
- package/build/esm/dev/durableobject.js.map +1 -1
- package/build/esm/dev/options.js +1 -0
- package/build/esm/dev/options.js.map +1 -1
- package/build/esm/dev/package.json +1 -1
- package/build/esm/dev/vite/autoInstrument.js +5 -1
- package/build/esm/dev/vite/autoInstrument.js.map +1 -1
- package/build/esm/dev/vite/index.js.map +1 -1
- package/build/esm/dev/vite/transform.js +12 -13
- package/build/esm/dev/vite/transform.js.map +1 -1
- package/build/esm/dev/vite/wranglerConfig.js +2 -0
- package/build/esm/dev/vite/wranglerConfig.js.map +1 -1
- package/build/esm/prod/baseSdk.js.map +1 -1
- package/build/esm/prod/client.js +7 -2
- package/build/esm/prod/client.js.map +1 -1
- package/build/esm/prod/durableobject.js.map +1 -1
- package/build/esm/prod/options.js +1 -0
- package/build/esm/prod/options.js.map +1 -1
- package/build/esm/prod/package.json +1 -1
- package/build/esm/prod/vite/autoInstrument.js +5 -1
- package/build/esm/prod/vite/autoInstrument.js.map +1 -1
- package/build/esm/prod/vite/index.js.map +1 -1
- package/build/esm/prod/vite/transform.js +12 -13
- package/build/esm/prod/vite/transform.js.map +1 -1
- package/build/esm/prod/vite/wranglerConfig.js +2 -0
- package/build/esm/prod/vite/wranglerConfig.js.map +1 -1
- package/build/types/baseSdk.d.ts.map +1 -1
- package/build/types/client.d.ts +7 -0
- package/build/types/client.d.ts.map +1 -1
- package/build/types/durableobject.d.ts.map +1 -1
- package/build/types/options.d.ts.map +1 -1
- package/build/types/vite/autoInstrument.d.ts.map +1 -1
- package/build/types/vite/index.d.ts +3 -0
- package/build/types/vite/index.d.ts.map +1 -1
- package/build/types/vite/transform.d.ts +12 -2
- package/build/types/vite/transform.d.ts.map +1 -1
- package/build/types/vite/wranglerConfig.d.ts +8 -0
- package/build/types/vite/wranglerConfig.d.ts.map +1 -1
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"baseSdk.js","names":["GLOBAL_OBJ","dedupeIntegration","eventFiltersIntegration","functionToStringIntegration","conversationIdIntegration","linkedErrorsIntegration","fetchIntegration","httpServerIntegration","requestDataIntegration","consoleIntegration","getCachedClient","_INTERNAL_isClientClosed","DEBUG_BUILD","debug","getCurrentScope","setCurrentClient","makeFlushLock","stackParserFromStackParserOptions","defaultStackParser","getIntegrationsToSetup","makeCloudflareTransport","spotlightIntegration","initAndBind","CloudflareClient","cacheClient","safeCallback"],"sources":["../../../src/baseSdk.ts"],"sourcesContent":["import type { Integration } from '@sentry/core';\nimport { _INTERNAL_isClientClosed, debug, getCurrentScope, safeCallback, setCurrentClient } from '@sentry/core';\nimport {\n consoleIntegration,\n conversationIdIntegration,\n dedupeIntegration,\n eventFiltersIntegration,\n functionToStringIntegration,\n getIntegrationsToSetup,\n GLOBAL_OBJ,\n initAndBind,\n linkedErrorsIntegration,\n requestDataIntegration,\n stackParserFromStackParserOptions,\n} from '@sentry/core';\nimport type { CloudflareClientOptions, CloudflareOptions } from './client';\nimport { CloudflareClient } from './client';\nimport { makeFlushLock } from './flush';\nimport { cacheClient, getCachedClient } from './clientCache';\nimport { DEBUG_BUILD } from './debug-build';\nimport { fetchIntegration } from './integrations/fetch';\nimport { httpServerIntegration } from './integrations/httpServer';\nimport { INTEGRATION_NAME as SPOTLIGHT_INTEGRATION_NAME, spotlightIntegration } from './integrations/spotlight';\nimport { makeCloudflareTransport } from './transport';\nimport { defaultStackParser } from './vendor/stacktrace';\n\n/**\n * Instantiate the channel-subscriber factories the `@sentry/cloudflare/vite`\n * plugin registered on the global marker. The plugin splices a small snippet\n * into each instrumented module that `.set`s its factory here (keyed by module\n * name), so the marker holds one factory per package actually bundled.\n *\n * The marker is read directly instead of importing the factories, so a worker\n * built without the plugin — where the channels never fire — ships none of this\n * code.\n */\nfunction getRegisteredChannelIntegrations(): Integration[] {\n const registered = GLOBAL_OBJ.__SENTRY_ORCHESTRION__?.integrations;\n\n return registered ? [...registered.values()].map(factory => factory()) : [];\n}\n\n/**\n * Get the default integrations for the Cloudflare SDK.\n * These also work on Workers-compatible runtimes without the `nodejs_compat` compatibility flag.\n */\nexport function getDefaultIntegrations(options: CloudflareOptions): Integration[] {\n return [\n // The Dedupe integration should not be used in workflows because we want to\n // capture all step failures, even if they are the same error.\n ...(options.enableDedupe === false ? [] : [dedupeIntegration()]),\n eventFiltersIntegration(),\n functionToStringIntegration(),\n conversationIdIntegration(),\n linkedErrorsIntegration(),\n fetchIntegration(),\n httpServerIntegration(),\n requestDataIntegration(),\n consoleIntegration(),\n // The orchestrion diagnostics-channel subscribers (mysql, pg, …). The\n // `@sentry/cloudflare/vite` plugin injects the channels at build time and,\n // next to each, a snippet that registers the matching subscriber factory on\n // the global marker. Read from there instead of importing them so bundles\n // built without the plugin — where the channels would never fire — don't\n // ship the code.\n ...getRegisteredChannelIntegrations(),\n ];\n}\n\n/**\n * Initializes the Cloudflare SDK without setting up an OpenTelemetry tracer provider.\n *\n * Kept separate from `sdk.ts` so `@sentry/cloudflare/request` can load without Node.js-only\n * dependencies on runtimes such as Shopify Oxygen.\n *\n * The client is cached and reused across invocations within the same isolate,\n * unless `cacheClient: false` is passed. This avoids the\n * per-invocation cost of constructing a new client, and it is what makes\n * Durable Object telemetry reliable: a per-invocation client is disposed at\n * the end of the handler, and in a Durable Object there is no `waitUntil`\n * boundary that reliably extends execution, so spans/events that end after\n * disposal would otherwise be lost.\n */\nexport function initBaseSdk(options: CloudflareOptions): CloudflareClient | undefined {\n const cached = getCachedClient();\n const cacheEnabled = options.cacheClient !== false;\n\n // A closed client drops all data. `close()` marks the client before it\n // flushes, so this also skips a client that is still closing.\n if (cacheEnabled && cached && !_INTERNAL_isClientClosed(cached)) {\n if (DEBUG_BUILD && cached.getOptions().dsn !== options.dsn) {\n debug.warn(\n '[Sentry] init() was called with a different DSN than the cached client of this isolate; the cached client keeps its DSN. Pass `cacheClient: false` for per-invocation options.',\n );\n }\n getCurrentScope().update(options.initialScope);\n setCurrentClient(cached);\n return cached;\n }\n\n // `false` or a custom list turns off the SDK defaults, late-loaded ones\n // included, unless an SDK built the list from the defaults.\n const usesSdkDefaults = options.defaultIntegrations === undefined || !!options._extendsDefaultIntegrations;\n if (options.defaultIntegrations === undefined) {\n options.defaultIntegrations = getDefaultIntegrations(options);\n }\n\n // A cached client outlives any single invocation, so binding it to one\n // invocation's flush lock would make later flushes wait on that invocation's\n // waitUntil work forever. Eager delivery replaces the flush lock's purpose.\n const invocationContext = options.ctx;\n const flushLock = !cacheEnabled && invocationContext ? makeFlushLock(invocationContext) : undefined;\n delete options.ctx;\n\n const clientOptions: CloudflareClientOptions = {\n ...options,\n cacheClient: cacheEnabled,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n integrations: getIntegrationsToSetup(options),\n transport: options.transport || makeCloudflareTransport,\n flushLock,\n };\n\n /*! rollup-include-development-only */\n if (options.spotlight && !clientOptions.integrations.some(({ name }) => name === SPOTLIGHT_INTEGRATION_NAME)) {\n clientOptions.integrations.push(\n spotlightIntegration({\n sidecarUrl: typeof options.spotlight === 'string' ? options.spotlight : undefined,\n }),\n );\n }\n /*! rollup-include-development-only-end */\n\n if (!cacheEnabled) {\n // `cacheClient: false` asks for a new client on each call, so replacing\n // the bound client is expected here and must not warn.\n getCurrentScope().setClient(undefined);\n }\n\n const client = initAndBind(CloudflareClient, clientOptions) as CloudflareClient;\n\n if (cacheEnabled && client) {\n cacheClient(client);\n }\n\n // An instrumented module that first evaluates AFTER this init (e.g. a driver\n // lazily required on first use) stores its subscriber factory on the global\n // marker too late for the default-integrations snapshot above. Its injected\n // snippet emits this event right after storing the factory, so install the\n // integration on the live client here, with the same rules as the defaults.\n // `addIntegration` dedupes by integration name, so an integration the user\n // configured stays in place.\n const userIntegrations = options.integrations;\n client.on('orchestrion.module-injected', moduleName => {\n const factory = GLOBAL_OBJ.__SENTRY_ORCHESTRION__?.integrations?.get(moduleName);\n if (!usesSdkDefaults || !factory) {\n return;\n }\n\n const integration = factory();\n if (typeof userIntegrations !== 'function') {\n client.addIntegration(integration);\n return;\n }\n\n // Pass the late default through the user's `integrations` function, so a\n // filter that removed it at init removes it here too. This calls the\n // function again, once for each late module. If the function throws, skip\n // the integration, so the module load that emitted the event still works.\n const kept = safeCallback(\n DEBUG_BUILD ? 'Error in the `integrations` function, skipping a late-loaded integration:' : '',\n () =>\n getIntegrationsToSetup({ defaultIntegrations: [integration], integrations: userIntegrations }).find(\n ({ name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5F,EAAE,WAAW,SAAS,YAAY,IACrC,SACI,KAAA,CACR;EACA,IAAI,MACF,OAAO,eAAe,IAAI;CAE9B,CAAC;CAED,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"baseSdk.js","names":["GLOBAL_OBJ","dedupeIntegration","eventFiltersIntegration","functionToStringIntegration","conversationIdIntegration","linkedErrorsIntegration","fetchIntegration","httpServerIntegration","requestDataIntegration","consoleIntegration","getCachedClient","_INTERNAL_isClientClosed","DEBUG_BUILD","debug","getCurrentScope","setCurrentClient","makeFlushLock","stackParserFromStackParserOptions","defaultStackParser","getIntegrationsToSetup","makeCloudflareTransport","spotlightIntegration","initAndBind","CloudflareClient","cacheClient","safeCallback"],"sources":["../../../src/baseSdk.ts"],"sourcesContent":["import type { Integration } from '@sentry/core';\nimport { _INTERNAL_isClientClosed, debug, getCurrentScope, safeCallback, setCurrentClient } from '@sentry/core';\nimport {\n consoleIntegration,\n conversationIdIntegration,\n dedupeIntegration,\n eventFiltersIntegration,\n functionToStringIntegration,\n getIntegrationsToSetup,\n GLOBAL_OBJ,\n initAndBind,\n linkedErrorsIntegration,\n requestDataIntegration,\n stackParserFromStackParserOptions,\n} from '@sentry/core';\nimport type { CloudflareClientOptions, CloudflareOptions } from './client';\nimport { CloudflareClient } from './client';\nimport { makeFlushLock } from './flush';\nimport { cacheClient, getCachedClient } from './clientCache';\nimport { DEBUG_BUILD } from './debug-build';\nimport { fetchIntegration } from './integrations/fetch';\nimport { httpServerIntegration } from './integrations/httpServer';\nimport { INTEGRATION_NAME as SPOTLIGHT_INTEGRATION_NAME, spotlightIntegration } from './integrations/spotlight';\nimport { makeCloudflareTransport } from './transport';\nimport { defaultStackParser } from './vendor/stacktrace';\n\n/**\n * Instantiate the channel-subscriber factories the `@sentry/cloudflare/vite`\n * plugin registered on the global marker. The plugin splices a small snippet\n * into each instrumented module that `.set`s its factory here (keyed by module\n * name), so the marker holds one factory per package actually bundled.\n *\n * The marker is read directly instead of importing the factories, so a worker\n * built without the plugin — where the channels never fire — ships none of this\n * code.\n */\nfunction getRegisteredChannelIntegrations(): Integration[] {\n const registered = GLOBAL_OBJ.__SENTRY_ORCHESTRION__?.integrations;\n\n return registered ? [...registered.values()].map(factory => factory()) : [];\n}\n\n/**\n * Get the default integrations for the Cloudflare SDK.\n * These also work on Workers-compatible runtimes without the `nodejs_compat` compatibility flag.\n */\nexport function getDefaultIntegrations(options: CloudflareOptions): Integration[] {\n return [\n // The Dedupe integration should not be used in workflows because we want to\n // capture all step failures, even if they are the same error.\n ...(options.enableDedupe === false ? [] : [dedupeIntegration()]),\n eventFiltersIntegration(),\n functionToStringIntegration(),\n conversationIdIntegration(),\n linkedErrorsIntegration(),\n fetchIntegration(),\n httpServerIntegration(),\n requestDataIntegration(),\n consoleIntegration(),\n // The orchestrion diagnostics-channel subscribers (mysql, pg, …). The\n // `@sentry/cloudflare/vite` plugin injects the channels at build time and,\n // next to each, a snippet that registers the matching subscriber factory on\n // the global marker. Read from there instead of importing them so bundles\n // built without the plugin — where the channels would never fire — don't\n // ship the code.\n ...getRegisteredChannelIntegrations(),\n ];\n}\n\n/**\n * Initializes the Cloudflare SDK without setting up an OpenTelemetry tracer provider.\n *\n * Kept separate from `sdk.ts` so `@sentry/cloudflare/request` can load without Node.js-only\n * dependencies on runtimes such as Shopify Oxygen.\n *\n * The client is cached and reused across invocations within the same isolate,\n * unless `cacheClient: false` is passed. This avoids the\n * per-invocation cost of constructing a new client, and it is what makes\n * Durable Object telemetry reliable: a per-invocation client is disposed at\n * the end of the handler, and in a Durable Object there is no `waitUntil`\n * boundary that reliably extends execution, so spans/events that end after\n * disposal would otherwise be lost.\n */\nexport function initBaseSdk(options: CloudflareOptions): CloudflareClient | undefined {\n const cached = getCachedClient();\n // oxlint-disable-next-line typescript/no-deprecated\n const cacheEnabled = options.cacheClient !== false;\n\n // A closed client drops all data. `close()` marks the client before it\n // flushes, so this also skips a client that is still closing.\n if (cacheEnabled && cached && !_INTERNAL_isClientClosed(cached)) {\n if (DEBUG_BUILD && cached.getOptions().dsn !== options.dsn) {\n debug.warn(\n '[Sentry] init() was called with a different DSN than the cached client of this isolate; the cached client keeps its DSN. Pass `cacheClient: false` for per-invocation options.',\n );\n }\n getCurrentScope().update(options.initialScope);\n setCurrentClient(cached);\n return cached;\n }\n\n // `false` or a custom list turns off the SDK defaults, late-loaded ones\n // included, unless an SDK built the list from the defaults.\n const usesSdkDefaults = options.defaultIntegrations === undefined || !!options._extendsDefaultIntegrations;\n if (options.defaultIntegrations === undefined) {\n options.defaultIntegrations = getDefaultIntegrations(options);\n }\n\n // A cached client outlives any single invocation, so binding it to one\n // invocation's flush lock would make later flushes wait on that invocation's\n // waitUntil work forever. Eager delivery replaces the flush lock's purpose.\n const invocationContext = options.ctx;\n const flushLock = !cacheEnabled && invocationContext ? makeFlushLock(invocationContext) : undefined;\n delete options.ctx;\n\n const clientOptions: CloudflareClientOptions = {\n ...options,\n // oxlint-disable-next-line typescript/no-deprecated\n cacheClient: cacheEnabled,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n integrations: getIntegrationsToSetup(options),\n transport: options.transport || makeCloudflareTransport,\n flushLock,\n };\n\n /*! rollup-include-development-only */\n if (options.spotlight && !clientOptions.integrations.some(({ name }) => name === SPOTLIGHT_INTEGRATION_NAME)) {\n clientOptions.integrations.push(\n spotlightIntegration({\n sidecarUrl: typeof options.spotlight === 'string' ? options.spotlight : undefined,\n }),\n );\n }\n /*! rollup-include-development-only-end */\n\n if (!cacheEnabled) {\n // `cacheClient: false` asks for a new client on each call, so replacing\n // the bound client is expected here and must not warn.\n getCurrentScope().setClient(undefined);\n }\n\n const client = initAndBind(CloudflareClient, clientOptions) as CloudflareClient;\n\n if (cacheEnabled && client) {\n cacheClient(client);\n }\n\n // An instrumented module that first evaluates AFTER this init (e.g. a driver\n // lazily required on first use) stores its subscriber factory on the global\n // marker too late for the default-integrations snapshot above. Its injected\n // snippet emits this event right after storing the factory, so install the\n // integration on the live client here, with the same rules as the defaults.\n // `addIntegration` dedupes by integration name, so an integration the user\n // configured stays in place.\n const userIntegrations = options.integrations;\n client.on('orchestrion.module-injected', moduleName => {\n const factory = GLOBAL_OBJ.__SENTRY_ORCHESTRION__?.integrations?.get(moduleName);\n if (!usesSdkDefaults || !factory) {\n return;\n }\n\n const integration = factory();\n if (typeof userIntegrations !== 'function') {\n client.addIntegration(integration);\n return;\n }\n\n // Pass the late default through the user's `integrations` function, so a\n // filter that removed it at init removes it here too. This calls the\n // function again, once for each late module. If the function throws, skip\n // the integration, so the module load that emitted the event still works.\n const kept = safeCallback(\n DEBUG_BUILD ? 'Error in the `integrations` function, skipping a late-loaded integration:' : '',\n () =>\n getIntegrationsToSetup({ defaultIntegrations: [integration], integrations: userIntegrations }).find(\n ({ name }) => name === integration.name,\n ),\n () => undefined,\n );\n if (kept) {\n client.addIntegration(kept);\n }\n });\n\n return client;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAoCA,SAAS,mCAAkD;CACzD,MAAM,aAAaA,aAAAA,WAAW,wBAAwB;CAEtD,OAAO,aAAa,CAAC,GAAG,WAAW,OAAO,CAAC,CAAC,CAAC,KAAI,YAAW,QAAQ,CAAC,IAAI,CAAC;AAC5E;;;;;AAMA,SAAgB,uBAAuB,SAA2C;CAChF,OAAO;EAGL,GAAI,QAAQ,iBAAiB,QAAQ,CAAC,IAAI,EAAA,GAACC,aAAAA,kBAAAA,CAAkB,CAAC;GAC9DC,GAAAA,aAAAA,wBAAAA,CAAwB;GACxBC,GAAAA,aAAAA,4BAAAA,CAA4B;GAC5BC,GAAAA,aAAAA,0BAAAA,CAA0B;GAC1BC,GAAAA,aAAAA,wBAAAA,CAAwB;EACxBC,cAAAA,iBAAiB;EACjBC,mBAAAA,sBAAsB;GACtBC,GAAAA,aAAAA,uBAAAA,CAAuB;GACvBC,GAAAA,aAAAA,mBAAAA,CAAmB;EAOnB,GAAG,iCAAiC;CACtC;AACF;;;;;;;;;;;;;;;AAgBA,SAAgB,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a;CAE1D,IAAI,gBAAgB,QAClBC,oBAAAA,YAAY,MAAM;CAUpB,MAAM,mBAAmB,QAAQ;CACjC,OAAO,GAAG,gCAA+B,eAAc;EACrD,MAAM,UAAUxB,aAAAA,WAAW,wBAAwB,cAAc,IAAI,UAAU;EAC/E,IAAI,CAAC,mBAAmB,CAAC,SACvB;EAGF,MAAM,cAAc,QAAQ;EAC5B,IAAI,OAAO,qBAAqB,YAAY;GAC1C,OAAO,eAAe,WAAW;GACjC;EACF;EAMA,MAAM,QAAA,GAAOyB,aAAAA,aAAAA,CACXb,oBAAAA,cAAc,8EAA8E,WAAA,GAE1FO,aAAAA,uBAAAA,CAAuB;GAAE,qBAAqB,CAAC,WAAW;GAAG,cAAc;EAAiB,CAAC,CAAC,CAAC,MAC5F,EAAE,WAAW,SAAS,YAAY,IACrC,SACI,KAAA,CACR;EACA,IAAI,MACF,OAAO,eAAe,IAAI;CAE9B,CAAC;CAED,OAAO;AACT"}
|
package/build/cjs/dev/client.js
CHANGED
|
@@ -19,10 +19,15 @@ var CloudflareClient = class extends _sentry_core_server.ServerRuntimeClient {
|
|
|
19
19
|
(0, _sentry_core.applySdkMetadata)(options, "cloudflare");
|
|
20
20
|
options._metadata = options._metadata || {};
|
|
21
21
|
const { flushLock, ...serverOptions } = options;
|
|
22
|
+
const workerInfo = _sentry_core.GLOBAL_OBJ.__SENTRY_CLOUDFLARE_WORKER__;
|
|
22
23
|
const clientOptions = {
|
|
23
24
|
...serverOptions,
|
|
24
25
|
platform: "javascript",
|
|
25
|
-
runtime: {
|
|
26
|
+
runtime: {
|
|
27
|
+
name: "cloudflare",
|
|
28
|
+
version: workerInfo?.compatibilityDate
|
|
29
|
+
},
|
|
30
|
+
serverName: serverOptions.serverName ?? workerInfo?.name,
|
|
26
31
|
_flushInterval: 0
|
|
27
32
|
};
|
|
28
33
|
if ((typeof __SENTRY_TRACING__ === "undefined" || __SENTRY_TRACING__) && clientOptions.traceLifecycle !== "static" && !clientOptions.integrations.some((i) => i.name === SPAN_STREAMING_INTEGRATION_NAME)) clientOptions.integrations.push((0, _sentry_core.spanStreamingIntegration)({ flushOnSegmentEnd: false }));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":["ServerRuntimeClient","applySdkMetadata","spanStreamingIntegration","DEBUG_BUILD","debug","spanIsSampled","_INTERNAL_clearAiProviderSkips","getInvocationState","_INTERNAL_flushLogsBuffer","_INTERNAL_flushMetricsBuffer","getInvocationWaitUntil"],"sources":["../../../src/client.ts"],"sourcesContent":["import type { CheckIn, ClientOptions, MonitorConfig, Options, Scope, TracePropagationTargets } from '@sentry/core';\nimport {\n _INTERNAL_clearAiProviderSkips,\n _INTERNAL_flushLogsBuffer,\n _INTERNAL_flushMetricsBuffer,\n applySdkMetadata,\n debug,\n spanIsSampled,\n spanStreamingIntegration,\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\ndeclare const __SENTRY_TRACING__: boolean;\n\nconst SPAN_STREAMING_INTEGRATION_NAME = 'SpanStreaming';\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 // Eager drains still sending. Outside an instrumented invocation (e.g. Astro on Pages) they have no `waitUntil`,\n // so `flush()` awaits them, or the response can end first and the runtime cancels their fetches.\n private readonly _pendingEagerDrains = new Set<Promise<void>>();\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 // workerd can't unref timers, so the default 500ms segment-end flush timer holds every\n // Durable Object invocation open (and billed) until it fires, sampled or not. The boundary\n // flush and the eager drain already deliver streamed spans here.\n if (\n (typeof __SENTRY_TRACING__ === 'undefined' || __SENTRY_TRACING__) &&\n clientOptions.traceLifecycle !== 'static' &&\n !clientOptions.integrations.some(i => i.name === SPAN_STREAMING_INTEGRATION_NAME)\n ) {\n clientOptions.integrations.push(spanStreamingIntegration({ flushOnSegmentEnd: false }));\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 let flushed: boolean;\n try {\n flushed = await super.flush(timeout);\n } finally {\n this._inBoundaryFlush = false;\n }\n\n // Each eager drain is bounded by its own transport flush timeout.\n await Promise.all(this._pendingEagerDrains);\n\n return flushed;\n }\n\n /**\n * Sends the check-in at once instead of holding it for the flush at the end of the invocation.\n * An `in_progress` check-in of a run that is longer than the check-in margin would otherwise\n * reach Sentry too late, and Sentry would mark the run as missed.\n */\n public override captureCheckIn(checkIn: CheckIn, monitorConfig?: MonitorConfig, scope?: Scope): string {\n const checkInId = super.captureCheckIn(checkIn, monitorConfig, scope);\n const transport = this.getTransport();\n if (transport) {\n this._registerWithInvocationWaitUntil(transport.flush(2000));\n }\n return checkInId;\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) only the next `flush()` waits for the send.\n */\n private _registerWithInvocationWaitUntil(promise: PromiseLike<unknown>): void {\n const pending = Promise.resolve(promise).then(\n () => undefined,\n () => undefined,\n );\n this._pendingEagerDrains.add(pending);\n void pending.then(() => this._pendingEagerDrains.delete(pending));\n\n const invocationState = getInvocationState();\n const waitUntil = invocationState && getInvocationWaitUntil(invocationState);\n if (!waitUntil) {\n return;\n }\n\n try {\n waitUntil(pending);\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 * @ignore Used internally by SDKs that build `defaultIntegrations` from the Cloudflare defaults.\n * @hidden Used internally by SDKs that build `defaultIntegrations` from the Cloudflare defaults.\n *\n * Marks the `defaultIntegrations` list as an extension of the SDK defaults, so the SDK also adds\n * the integrations of instrumented modules that load after `init()`.\n * @default false\n */\n _extendsDefaultIntegrations?: 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 * The Queue producer bindings on `env` that outgoing messages propagate trace context to.\n *\n * Cloudflare Queues has no message headers, so the SDK adds the producer's `sentry-trace` to\n * plain-object message bodies under `__sentry_queue_trace__`. Arrays, binary data and other\n * non-plain values are sent unchanged. A Sentry-instrumented consumer removes that field before\n * your queue handler runs and links its `queue.process` span to every producer in the batch.\n * Anywhere else the field arrives as part of the message body, so list only the queues whose\n * consumer you know runs Sentry.\n *\n * The field adds about 80 bytes to each message. Cloudflare rejects messages over 128 KB, so a\n * message close to that limit can fail to send once propagation is enabled.\n *\n * Strings match a binding name exactly, regular expressions match by pattern. Both match\n * case-insensitively.\n *\n * @default []\n * @example\n * ```ts\n * // Propagate to `env.BILLING_QUEUE` and every `env.JOBS_*` binding\n * export default Sentry.withSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * queueTracePropagationBindings: ['BILLING_QUEUE', /^JOBS_/],\n * }),\n * handler,\n * );\n * ```\n */\n queueTracePropagationBindings?: 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 * A function that receives the response of a `fetch` handler and the request it answers, and\n * returns whether the response body is still being produced after the handler returns.\n *\n * For `true`, the SDK keeps the `http.server` span open until the body has been sent, so spans\n * created while the body streams stay inside the request. It does this by passing the body through\n * a `TransformStream`. For `false`, the SDK ends the span when the handler returns and sends the\n * response unchanged. For `undefined` or any other value, the SDK decides: Server-Sent Events,\n * NDJSON and `application/stream+json` responses, and `text/plain` and `text/x-component`\n * responses without a `Content-Length` header count as streamed. HTML does not, so return `true`\n * for pages that are rendered with streamed SSR.\n *\n * The function must be synchronous and must not read the response body. Use the status, the\n * headers and the request URL.\n *\n * @example\n * ```ts\n * // src/instrument.server.ts\n * import { defineCloudflareOptions } from '@sentry/cloudflare';\n *\n * export default defineCloudflareOptions(env => ({\n * dsn: env.SENTRY_DSN,\n * isStreamingResponse: response =>\n * response.headers.get('content-type')?.startsWith('text/html') ? true : undefined,\n * }));\n * ```\n */\n isStreamingResponse?: (response: Response, request: Request) => boolean | undefined;\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 * A URL to send this server's own envelopes to instead of the Sentry ingest URL. To serve the managed tunnel for the\n * browser, use `serveTunnelIntegration`.\n */\n tunnel?: string;\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"],"mappings":";;;;;AAoBA,MAAM,kCAAkC;;;;;;;AAQxC,IAAa,mBAAb,cAAsCA,oBAAAA,oBAAoB;;;;;CA4BjD,YAAY,SAAkC;EACnDC,CAAAA,GAAAA,aAAAA,iBAAAA,CAAiB,SAAS,YAAY;EACtC,QAAQ,YAAY,QAAQ,aAAa,CAAC;EAC1C,MAAM,EAAE,WAAW,GAAG,kBAAkB;EAExC,MAAM,gBAA4C;GAChD,GAAG;GACH,UAAU;GAEV,SAAS,EAAE,MAAM,aAAa;GAE9B,gBAAgB;EAClB;EAKA,KACG,OAAO,uBAAuB,eAAe,uBAC9C,cAAc,mBA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C;EAEhE,MAAM,kBAAkBA,0BAAAA,mBAAmB;EAC3C,MAAM,YAAY,mBAAmBG,0BAAAA,uBAAuB,eAAe;EAC3E,IAAI,CAAC,WACH;EAGF,IAAI;GACF,UAAU,OAAO;EACnB,QAAQ,CAER;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"client.js","names":["ServerRuntimeClient","applySdkMetadata","GLOBAL_OBJ","spanStreamingIntegration","DEBUG_BUILD","debug","spanIsSampled","_INTERNAL_clearAiProviderSkips","getInvocationState","_INTERNAL_flushLogsBuffer","_INTERNAL_flushMetricsBuffer","getInvocationWaitUntil"],"sources":["../../../src/client.ts"],"sourcesContent":["import type { CheckIn, ClientOptions, MonitorConfig, Options, Scope, TracePropagationTargets } from '@sentry/core';\nimport {\n _INTERNAL_clearAiProviderSkips,\n _INTERNAL_flushLogsBuffer,\n _INTERNAL_flushMetricsBuffer,\n applySdkMetadata,\n debug,\n GLOBAL_OBJ,\n spanIsSampled,\n spanStreamingIntegration,\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\ndeclare const __SENTRY_TRACING__: boolean;\n\nconst SPAN_STREAMING_INTEGRATION_NAME = 'SpanStreaming';\n\ntype GlobalWithWorkerInfo = typeof GLOBAL_OBJ & {\n /**\n * The `name` and `compatibility_date` of the wrangler config. Only set when the Worker is built\n * with `sentryCloudflareVitePlugin`.\n */\n __SENTRY_CLOUDFLARE_WORKER__?: { name?: string; compatibilityDate?: string };\n};\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 // Eager drains still sending. Outside an instrumented invocation (e.g. Astro on Pages) they have no `waitUntil`,\n // so `flush()` awaits them, or the response can end first and the runtime cancels their fetches.\n private readonly _pendingEagerDrains = new Set<Promise<void>>();\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 const workerInfo = (GLOBAL_OBJ as GlobalWithWorkerInfo).__SENTRY_CLOUDFLARE_WORKER__;\n\n const clientOptions: ServerRuntimeClientOptions = {\n ...serverOptions,\n platform: 'javascript',\n // workerd exposes no version at runtime (`navigator.userAgent` is always `Cloudflare-Workers`).\n // The compatibility date selects the workerd behavior of the Worker, so it is the version.\n runtime: { name: 'cloudflare', version: workerInfo?.compatibilityDate },\n serverName: serverOptions.serverName ?? workerInfo?.name,\n _flushInterval: 0,\n };\n\n // workerd can't unref timers, so the default 500ms segment-end flush timer holds every\n // Durable Object invocation open (and billed) until it fires, sampled or not. The boundary\n // flush and the eager drain already deliver streamed spans here.\n if (\n (typeof __SENTRY_TRACING__ === 'undefined' || __SENTRY_TRACING__) &&\n clientOptions.traceLifecycle !== 'static' &&\n !clientOptions.integrations.some(i => i.name === SPAN_STREAMING_INTEGRATION_NAME)\n ) {\n clientOptions.integrations.push(spanStreamingIntegration({ flushOnSegmentEnd: false }));\n }\n\n super(clientOptions);\n this._flushLock = flushLock;\n // oxlint-disable-next-line typescript/no-deprecated\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 let flushed: boolean;\n try {\n flushed = await super.flush(timeout);\n } finally {\n this._inBoundaryFlush = false;\n }\n\n // Each eager drain is bounded by its own transport flush timeout.\n await Promise.all(this._pendingEagerDrains);\n\n return flushed;\n }\n\n /**\n * Sends the check-in at once instead of holding it for the flush at the end of the invocation.\n * An `in_progress` check-in of a run that is longer than the check-in margin would otherwise\n * reach Sentry too late, and Sentry would mark the run as missed.\n */\n public override captureCheckIn(checkIn: CheckIn, monitorConfig?: MonitorConfig, scope?: Scope): string {\n const checkInId = super.captureCheckIn(checkIn, monitorConfig, scope);\n const transport = this.getTransport();\n if (transport) {\n this._registerWithInvocationWaitUntil(transport.flush(2000));\n }\n return checkInId;\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) only the next `flush()` waits for the send.\n */\n private _registerWithInvocationWaitUntil(promise: PromiseLike<unknown>): void {\n const pending = Promise.resolve(promise).then(\n () => undefined,\n () => undefined,\n );\n this._pendingEagerDrains.add(pending);\n void pending.then(() => this._pendingEagerDrains.delete(pending));\n\n const invocationState = getInvocationState();\n const waitUntil = invocationState && getInvocationWaitUntil(invocationState);\n if (!waitUntil) {\n return;\n }\n\n try {\n waitUntil(pending);\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 * @ignore Used internally by SDKs that build `defaultIntegrations` from the Cloudflare defaults.\n * @hidden Used internally by SDKs that build `defaultIntegrations` from the Cloudflare defaults.\n *\n * Marks the `defaultIntegrations` list as an extension of the SDK defaults, so the SDK also adds\n * the integrations of instrumented modules that load after `init()`.\n * @default false\n */\n _extendsDefaultIntegrations?: 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 * The Queue producer bindings on `env` that outgoing messages propagate trace context to.\n *\n * Cloudflare Queues has no message headers, so the SDK adds the producer's `sentry-trace` to\n * plain-object message bodies under `__sentry_queue_trace__`. Arrays, binary data and other\n * non-plain values are sent unchanged. A Sentry-instrumented consumer removes that field before\n * your queue handler runs and links its `queue.process` span to every producer in the batch.\n * Anywhere else the field arrives as part of the message body, so list only the queues whose\n * consumer you know runs Sentry.\n *\n * The field adds about 80 bytes to each message. Cloudflare rejects messages over 128 KB, so a\n * message close to that limit can fail to send once propagation is enabled.\n *\n * Strings match a binding name exactly, regular expressions match by pattern. Both match\n * case-insensitively.\n *\n * @default []\n * @example\n * ```ts\n * // Propagate to `env.BILLING_QUEUE` and every `env.JOBS_*` binding\n * export default Sentry.withSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * queueTracePropagationBindings: ['BILLING_QUEUE', /^JOBS_/],\n * }),\n * handler,\n * );\n * ```\n */\n queueTracePropagationBindings?: 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 * @default the `SENTRY_NAME` variable of `env`, else the `name` of the wrangler config when you\n * build with `sentryCloudflareVitePlugin`\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 // TODO(v12): Remove `cacheClient` and the per-invocation client code paths it enables.\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 * @deprecated `cacheClient` will be removed in the next major version (v12), and the client will always be cached.\n * If you set `cacheClient: false`, please open an issue at https://github.com/getsentry/sentry-javascript/issues\n * and tell us why `cacheClient: true` does not work for your use case.\n */\n cacheClient?: boolean;\n\n /**\n * A function that receives the response of a `fetch` handler and the request it answers, and\n * returns whether the response body is still being produced after the handler returns.\n *\n * For `true`, the SDK keeps the `http.server` span open until the body has been sent, so spans\n * created while the body streams stay inside the request. It does this by passing the body through\n * a `TransformStream`. For `false`, the SDK ends the span when the handler returns and sends the\n * response unchanged. For `undefined` or any other value, the SDK decides: Server-Sent Events,\n * NDJSON and `application/stream+json` responses, and `text/plain` and `text/x-component`\n * responses without a `Content-Length` header count as streamed. HTML does not, so return `true`\n * for pages that are rendered with streamed SSR.\n *\n * The function must be synchronous and must not read the response body. Use the status, the\n * headers and the request URL.\n *\n * @example\n * ```ts\n * // src/instrument.server.ts\n * import { defineCloudflareOptions } from '@sentry/cloudflare';\n *\n * export default defineCloudflareOptions(env => ({\n * dsn: env.SENTRY_DSN,\n * isStreamingResponse: response =>\n * response.headers.get('content-type')?.startsWith('text/html') ? true : undefined,\n * }));\n * ```\n */\n isStreamingResponse?: (response: Response, request: Request) => boolean | undefined;\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 * A URL to send this server's own envelopes to instead of the Sentry ingest URL. To serve the managed tunnel for the\n * browser, use `serveTunnelIntegration`.\n */\n tunnel?: string;\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"],"mappings":";;;;;AAqBA,MAAM,kCAAkC;;;;;;;AAgBxC,IAAa,mBAAb,cAAsCA,oBAAAA,oBAAoB;;;;;CA4BjD,YAAY,SAAkC;EACnDC,CAAAA,GAAAA,aAAAA,iBAAAA,CAAiB,SAAS,YAAY;EACtC,QAAQ,YAAY,QAAQ,aAAa,CAAC;EAC1C,MAAM,EAAE,WAAW,GAAG,kBAAkB;EACxC,MAAM,aAAcC,aAAAA,WAAoC;EAExD,MAAM,gBAA4C;GAChD,GAAG;GACH,UAAU;GAGV,SAAS;IAAE,MAAM;IAAc,SAAS,YAAY;GAAkB;GACtE,YAAY,cAAc,cAAc,YAAY;GACpD,gBAAgB;EAClB;EAKA,KACG,OAAO,uBAAuB,eAAe,uBAC9C,cAAc,mBAAmB,YACjC,CAAC,cAAc,aAAa,MAAK,MAAK,EAAE,SAAS,+BAA+B,GAEhF,cAAc,aAAa,MAAA,GAAKC,aAAAA,yBAAAA,CAAyB,EAAE,mBAAmB,MAAM,CAAC,CAAC;EAGxF,MAAM,aAAa;EArDrB,KAAQ,gCAA6B,IAAI,IAAI;EAC7C,KAAQ,yBAA+C;EACvD,KAAQ,yBAA8C;EAEtD,KAAQ,wBAA6C;EACrD,KAAQ,sBAA2C;EAInD,KAAQ,mBAAmB;EAI3B,KAAiB,sCAAsB,IAAI,IAAmB;EAyC5D,KAAK,aAAa;EAElB,KAAK,iBAAiB,QAAQ,gBAAgB;EAO9C,IAAI,CAAC,KAA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3C,IAAI,CAAC,aAAa,KAAK,oBAAqB,mBAAmB,CAAC,gBAAgB,mBAC9E;GAGF,KAAK,iCAAiC,UAAU,MAAM,GAAI,CAAC;EAC7D,CAAC;CACH;;;;;;;;;;;;CAaQ,4BAAkC;EACxC,KAAK,GAAG,iBAAgB,SAAQ;GAK9B,MAAM,UAAU,KAAK,YAAY,CAAC,CAAC;GACnC,KAAK,kBAAkB,KAAK,KAAK,mBAAmB,OAAO,CAAC;EAC9D,CAAC;EACD,KAAK,GAAG,yBAAyB,KAAK,mBAAA,GAAkBC,aAAAA,0BAAAA,CAA0B,IAAI,CAAC,CAAC;EACxF,KAAK,GAAG,4BAA4B,KAAK,mBAAA,GAAkBC,aAAAA,6BAAAA,CAA6B,IAAI,CAAC,CAAC;CAChG;;;;;CAMQ,YAAY,OAAyB;EAC3C,MAAM,kBAAkBF,0BAAAA,mBAAmB;EAE3C,IAAI,mBAAmB,CAAC,gBAAgB,mBACtC;EAGF,MAAM;CACR;;;;;;;CAQQ,iCAAiC,SAAqC;EAC5E,MAAM,UAAU,QAAQ,QAAQ,OAAO,CAAC,CAAC,WACjC,KAAA,SACA,KAAA,CACR;EACA,KAAK,oBAAoB,IAAI,OAAO;EAC/B,QAAQ,WAAW,KAAK,oBAAoB,OAAO,OAAO,CAAC;EAEhE,MAAM,kBAAkBA,0BAAAA,mBAAmB;EAC3C,MAAM,YAAY,mBAAmBG,0BAAAA,uBAAuB,eAAe;EAC3E,IAAI,CAAC,WACH;EAGF,IAAI;GACF,UAAU,OAAO;EACnB,QAAQ,CAER;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"durableobject.js","names":["setAsyncLocalStorageAsyncContextStrategyForWorker","getFinalOptions","instrumentContext","instrumentEnv","withConstructionIsolationScope","init","flushDeferredChannelEvents","instrumentDurableObjectHandlers","getInstrumented","markAsInstrumented","wrapMethodWithSentry","RPC","hasRpcMeta","getIsolationScope","getDefaultIsolationScope","isObjectLike","startNewTrace","instrumentCloudflareAgent"],"sources":["../../../src/durableobject.ts"],"sourcesContent":["/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/unbound-method */\nimport { RPC } from '@sentry/conventions/op';\nimport { getDefaultIsolationScope, getIsolationScope, isObjectLike, startNewTrace } from '@sentry/core';\nimport type { DurableObject } from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategyForWorker } from './utils/asyncContextStrategy';\nimport type { CloudflareOptions } from './client';\nimport { getInstrumented, markAsInstrumented } from './instrument';\nimport { instrumentDurableObjectHandlers } from './instrumentations/instrumentDurableObjectHandlers';\nimport { instrumentEnv } from './instrumentations/worker/instrumentEnv';\nimport { getFinalOptions } from './options';\nimport { flushDeferredChannelEvents } from './orchestrion-deferred-channels';\nimport { init } from './sdk';\nimport { instrumentContext } from './utils/instrumentContext';\nimport { withConstructionIsolationScope } from './utils/invocationScope';\nimport { hasRpcMeta } from './utils/rpcMeta';\nimport { instrumentCloudflareAgent } from './instrumentations/agents';\nimport type { DefaultEnv, ResolveEnv, StrictCloudflareOptions } from './types';\nimport { type UncheckedMethod, wrapMethodWithSentry } from './wrapMethodWithSentry';\n\n/**\n * The instrumented context passed between the shared construction helpers.\n *\n * This is intentionally `any` rather than `ReturnType<typeof instrumentContext<DurableObjectState>>`.\n * A concrete `DurableObjectState` here forces `tsc` to structurally relate its `storage: SqlStorage`\n * graph against the `ExecutionContext | InstrumentedDurableObjectState` parameter of\n * `wrapMethodWithSentry`, while the RPC-branded `DurableObject` from `cloudflare:workers` is also in\n * scope. That union comparison explodes (1296×1296) and hangs the type build. The original inline\n * implementation avoided this only incidentally, because `ctx` reached it as `any` through the Proxy\n * `construct` trap. Keeping the shared context `any` preserves that behavior.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InstrumentedDurableObjectContext = any;\n\n/**\n * Constructs a Durable Object instance and instruments its built-in handler methods\n * (`fetch`, `alarm`, `webSocketMessage`, `webSocketClose`, `webSocketError`).\n *\n * This is the shared construction path used by both {@link instrumentDurableObjectWithSentry}\n * and {@link instrumentAgentWithSentry}. It intentionally does NOT apply the RPC prototype-method\n * instrumentation — callers apply that last via {@link finalizeWithRpcInstrumentation}, after any\n * additional per-instance instrumentation has been layered onto the returned object.\n *\n * @internal\n */\nexport function constructInstrumentedDurableObject<E, T extends DurableObject<E>>(\n target: new (state: DurableObjectState, env: E) => T,\n ctx: DurableObjectState,\n env: E,\n newTarget: NewableFunction,\n optionsCallback: (env: E) => CloudflareOptions,\n): {\n obj: T;\n options: CloudflareOptions;\n context: InstrumentedDurableObjectContext;\n frameworkManagedMethods: ReadonlySet<string>;\n} {\n setAsyncLocalStorageAsyncContextStrategyForWorker();\n const options = getFinalOptions(optionsCallback(env), env);\n // See InstrumentedDurableObjectContext — `ctx` is widened to `any` so the concrete\n // `DurableObjectState` type never enters the checker's relation graph in this module.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const context = instrumentContext(ctx as any);\n const instrumentedEnv = instrumentEnv(env as Record<string, unknown>, options);\n\n const prototype = (newTarget as unknown as { prototype?: object }).prototype ?? target.prototype;\n const cachedFrameworkManagedMethods = frameworkManagedMethodsCache.get(prototype);\n const methodsBeforeConstruction = cachedFrameworkManagedMethods\n ? undefined\n : resolveMethodsBeforeFirstConstruction(prototype);\n\n // Pass `newTarget` so that subclasses of the instrumented class (e.g. the wrapper classes\n // created by wrangler's local dev tooling or `@cloudflare/vitest-pool-workers`) keep their\n // own prototype — otherwise subclass methods disappear and `instanceof` checks break.\n const obj = withConstructionIsolationScope(() => {\n // The constructor can already use instrumented libraries, e.g. open a pi-durable Harness in\n // `blockConcurrencyWhile`. Their channel integrations only subscribe in `init()`, and an isolate\n // that runs only this Durable Object has no earlier handler that called it. A per-invocation\n // client (`cacheClient: false`) would have no invocation to flush it, so it waits for one.\n if (options.cacheClient !== false) {\n init({ ...options });\n flushDeferredChannelEvents();\n }\n return Reflect.construct(target, [context, instrumentedEnv], newTarget) as T;\n });\n\n const frameworkManagedMethods = resolveFrameworkManagedMethods(\n prototype,\n obj,\n methodsBeforeConstruction,\n cachedFrameworkManagedMethods,\n );\n\n instrumentDurableObjectHandlers(obj, options, context);\n\n return { obj, options, context, frameworkManagedMethods };\n}\n\nconst frameworkManagedMethodsCache = new WeakMap<object, ReadonlySet<string>>();\nconst methodsBeforeFirstConstructionCache = new WeakMap<object, Map<string, unknown>>();\n\n/**\n * Collects the prototype's methods as they were before any instance was constructed.\n *\n * A constructor can throw after a framework has already installed its wrappers (the `agents` SDK\n * wraps `@callable()` methods before storage initialization, which can fail). The next construction\n * would then see those wrappers as the originals and treat the methods as unmanaged, so the methods\n * collected on the first attempt are kept until a construction succeeds.\n */\nfunction resolveMethodsBeforeFirstConstruction(prototype: object): Map<string, unknown> {\n let methods = methodsBeforeFirstConstructionCache.get(prototype);\n\n if (!methods) {\n methods = resolvePrototypeMethods(prototype);\n methodsBeforeFirstConstructionCache.set(prototype, methods);\n }\n\n return methods;\n}\n\n/**\n * Collects the methods visible from a prototype, using normal property lookup precedence.\n * Methods inherited from `Object.prototype` are excluded because they cannot be Durable Object RPC methods.\n */\nfunction resolvePrototypeMethods(prototype: object | null): Map<string, unknown> {\n const methods = new Map<string, unknown>();\n\n for (let current = prototype; current && current !== Object.prototype; current = Object.getPrototypeOf(current)) {\n for (const name of Object.getOwnPropertyNames(current)) {\n // The first occurrence wins, mirroring what a property lookup on the instance would find\n if (name === 'constructor' || methods.has(name)) {\n continue;\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(current, name);\n\n if (descriptor && typeof descriptor.value === 'function') {\n methods.set(name, descriptor.value);\n }\n }\n }\n\n return methods;\n}\n\n/**\n * Finds methods that a framework replaced while constructing the first instance.\n *\n * Some frameworks register methods by function identity, so replacing one of their wrappers would\n * break dispatch. The result is cached because frameworks commonly install their wrappers only\n * once; later constructions would no longer reveal which methods they manage.\n */\nfunction resolveFrameworkManagedMethods(\n prototype: object,\n obj: object,\n methodsBeforeConstruction: Map<string, unknown> | undefined,\n cached: ReadonlySet<string> | undefined,\n): ReadonlySet<string> {\n if (cached) {\n return cached;\n }\n\n const methodsAfterConstruction = resolvePrototypeMethods(Object.getPrototypeOf(obj) as object);\n const managed = new Set<string>();\n\n for (const [name, method] of methodsAfterConstruction) {\n const before = methodsBeforeConstruction?.get(name);\n\n if (before && before !== method) {\n managed.add(name);\n }\n }\n\n frameworkManagedMethodsCache.set(prototype, managed);\n methodsBeforeFirstConstructionCache.delete(prototype);\n\n return managed;\n}\n\ntype RpcInstanceState = {\n options: CloudflareOptions;\n context: InstrumentedDurableObjectContext;\n /** Per-instance cache of the instrumented method wrappers, keyed by method name. Created on first use. */\n instrumentedMethods?: Map<string, UncheckedMethod>;\n};\n\n/**\n * Method names the runtime never dispatches over RPC, so wrapping them buys no tracing.\n *\n * Mirrors `isReservedName` in workerd (`src/workerd/api/worker-rpc.c++`): the runtime rejects these\n * before any property lookup happens. `fetch`, `alarm` and the `webSocket*` handlers are also\n * instrumented per-instance as own properties, and `constructor` is on every prototype.\n */\nconst RESERVED_RPC_METHOD_NAMES: ReadonlySet<string> = new Set([\n 'constructor',\n 'fetch',\n 'connect',\n 'alarm',\n 'webSocketMessage',\n 'webSocketClose',\n 'webSocketError',\n 'dup',\n]);\n\n// Prototype wrappers are shared by all instances, while SDK options and traced method caches are not.\nconst rpcInstanceStates = new WeakMap<object, RpcInstanceState>();\n\n/**\n * Instruments a constructed Durable Object's RPC methods.\n *\n * RPC methods are wrapped on the prototype because Cloudflare dispatches them with the Durable\n * Object instance as the receiver. This preserves native private-field access and keeps the methods\n * visible to Cloudflare's RPC dispatcher. Built-in handlers, Agent handlers, and methods managed by\n * another framework are left untouched.\n *\n * Call this after all per-instance instrumentation has been applied.\n *\n * @param obj The constructed Durable Object instance.\n * @param options The resolved SDK options for this instance.\n * @param context The instrumented execution context for this instance.\n * @param excludedMethods Method names owned by another framework and therefore not safe to wrap.\n * @returns The same Durable Object instance, with eligible prototype methods instrumented.\n * @internal\n */\nexport function finalizeWithRpcInstrumentation<T extends object>(\n obj: T,\n options: CloudflareOptions,\n context: InstrumentedDurableObjectContext,\n excludedMethods?: ReadonlySet<string>,\n): T {\n rpcInstanceStates.set(obj, { options, context });\n\n instrumentPrototypeRpcMethods(obj, excludedMethods);\n\n return obj;\n}\n\n/**\n * Returns a prototype method when it is eligible for RPC instrumentation.\n */\nfunction getRpcMethodDescriptor(\n obj: object,\n prototype: object,\n methodName: string,\n excludedMethods?: ReadonlySet<string>,\n): PropertyDescriptor | undefined {\n if (\n RESERVED_RPC_METHOD_NAMES.has(methodName) ||\n Object.prototype.hasOwnProperty.call(obj, methodName) ||\n excludedMethods?.has(methodName)\n ) {\n return undefined;\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(prototype, methodName);\n\n if (!descriptor || typeof descriptor.value !== 'function' || getInstrumented(descriptor.value)) {\n return undefined;\n }\n\n return descriptor;\n}\n\n/**\n * Wraps eligible methods on the instance's prototype chain once per class.\n */\nfunction instrumentPrototypeRpcMethods(obj: object, excludedMethods?: ReadonlySet<string>): void {\n let prototype: object | null = Object.getPrototypeOf(obj);\n\n while (prototype && prototype !== Object.prototype) {\n for (const methodName of Object.getOwnPropertyNames(prototype)) {\n const descriptor = getRpcMethodDescriptor(obj, prototype, methodName, excludedMethods);\n\n if (!descriptor) {\n continue;\n }\n\n const wrapped = createRpcPrototypeWrapper(methodName, descriptor.value as UncheckedMethod);\n\n try {\n Object.defineProperty(prototype, methodName, { ...descriptor, value: wrapped });\n } catch {}\n\n // Only the wrapper is marked, not the original method: `wrapMethodWithSentry` resolves\n // through the same global map and must not resolve the original to this wrapper,\n // which would recurse.\n markAsInstrumented(wrapped);\n }\n\n prototype = Object.getPrototypeOf(prototype);\n }\n}\n\n/**\n * Returns the instance's instrumented wrapper for an RPC method, creating it on first use.\n */\nfunction getInstrumentedRpcMethod(\n state: RpcInstanceState,\n methodName: string,\n originalMethod: UncheckedMethod,\n): UncheckedMethod {\n const instrumentedMethods = (state.instrumentedMethods ??= new Map());\n let instrumented = instrumentedMethods.get(methodName);\n\n if (!instrumented) {\n instrumented = wrapMethodWithSentry(\n {\n options: state.options,\n context: state.context,\n spanName: rpcMeta => (rpcMeta ? methodName : undefined),\n spanOp: RPC,\n origin: 'auto.faas.cloudflare.durable_object',\n },\n originalMethod,\n undefined,\n true,\n );\n instrumentedMethods.set(methodName, instrumented);\n }\n\n return instrumented;\n}\n\n/**\n * Creates a prototype wrapper that instruments external RPC calls.\n *\n * The wrapper looks up SDK state from its receiver, allowing one prototype function to serve every\n * instance. A call carrying Sentry metadata continues that trace in an `rpc` span. A call without it\n * still gets a client, so its errors, logs and metrics are captured, but no span. Calls the instance\n * makes to its own methods run the original method directly. The original function name and arity\n * are preserved because frameworks may inspect them for dispatch.\n */\nfunction createRpcPrototypeWrapper(methodName: string, originalMethod: UncheckedMethod): UncheckedMethod {\n const wrapper = function (this: unknown, ...args: unknown[]): unknown {\n const traced = hasRpcMeta(args);\n\n // workerd dispatches an incoming RPC call outside any async context, so a call made on any other\n // isolation scope comes from the instance itself (`this.helper()` inside `fetch`, `alarm`,\n // another RPC method or async work the constructor started). Check that before touching\n // per-instance state.\n if (!traced && getIsolationScope() !== getDefaultIsolationScope()) {\n return Reflect.apply(originalMethod, this, args);\n }\n\n const state = isObjectLike(this) ? rpcInstanceStates.get(this) : undefined;\n\n if (!state) {\n return Reflect.apply(originalMethod, this, args);\n }\n\n const instrumented = getInstrumentedRpcMethod(state, methodName, originalMethod);\n\n if (traced) {\n return Reflect.apply(instrumented, this, args);\n }\n\n // Unlike a WorkerEntrypoint, a Durable Object instance is long-lived and serves overlapping\n // calls. Without a new trace, every untraced call would share the trace of the default scope.\n return startNewTrace(() => Reflect.apply(instrumented, this, args));\n };\n\n Object.defineProperties(wrapper, {\n name: { value: originalMethod.name, configurable: true },\n length: { value: originalMethod.length, configurable: true },\n });\n\n return wrapper as UncheckedMethod;\n}\n\n/**\n * Instruments a Durable Object class to capture errors and performance data.\n *\n * Instruments the following methods by default:\n * - fetch\n * - alarm\n * - webSocketMessage\n * - webSocketClose\n * - webSocketError\n *\n * RPC methods (prototype methods) are instrumented too: an incoming trace continues into them, and\n * errors, logs and metrics are captured whether or not the caller propagates a trace.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param DurableObjectClass The Durable Object class to instrument.\n * @returns The instrumented Durable Object class.\n *\n * @example\n * ```ts\n * class MyDurableObjectBase extends DurableObject {\n * constructor(ctx: DurableObjectState, env: Env) {\n * super(ctx, env);\n * }\n * }\n *\n * export const MyDurableObject = instrumentDurableObjectWithSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * }),\n * MyDurableObjectBase,\n * );\n * ```\n */\nexport function instrumentDurableObjectWithSentry<\n Env = DefaultEnv,\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends DurableObject<any> = DurableObject<Env>,\n // oxlint-disable-next-line typescript/no-explicit-any\n C extends new (state: DurableObjectState, env: any) => T = new (state: DurableObjectState, env: any) => T,\n O = unknown,\n>(optionsCallback: (env: ResolveEnv<C, Env>) => StrictCloudflareOptions<O>, DurableObjectClass: C): C {\n const InstrumentedClass = new Proxy(DurableObjectClass, {\n construct(target, [ctx, env], newTarget) {\n const { obj, options, context, frameworkManagedMethods } = constructInstrumentedDurableObject(\n target,\n ctx,\n env,\n newTarget,\n optionsCallback,\n );\n\n return finalizeWithRpcInstrumentation(obj, options, context, frameworkManagedMethods);\n },\n });\n // Recognizable for `_INTERNAL_wrapUnlessInstrumented`, so auto-instrumentation never nests wrappers.\n markAsInstrumented(InstrumentedClass);\n return InstrumentedClass;\n}\n\n/**\n * Instruments a Cloudflare [`agents`](https://www.npmjs.com/package/agents) Agent class with Sentry.\n *\n * An `Agent` is a Durable Object under the hood, so this applies the same instrumentation as\n * {@link instrumentDurableObjectWithSentry} (request transactions, `alarm`, WebSocket handlers, RPC\n * trace propagation, SQL spans) and additionally captures Agent-specific telemetry via\n * `instrumentCloudflareAgent`:\n *\n * - **Callable RPC spans** — a span (op `rpc`) for each `@callable()` method invoked over WebSocket.\n * - **Breadcrumbs** — for every Agent observability event (`rpc`, `state:update`, `connect`,\n * `disconnect`, `schedule:*`, `queue:*`, `workflow:*`, `email:*`, `mcp:*`, ...).\n *\n * Cloudflare Workers cannot auto-instrument, so the Agent class must be wrapped manually.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param AgentClass The Agent class to instrument.\n * @returns The instrumented Agent class.\n *\n * @example\n * ```ts\n * import { Agent, callable, routeAgentRequest } from 'agents';\n * import * as Sentry from '@sentry/cloudflare';\n *\n * class MyAgentBase extends Agent<Env> {\n * @callable()\n * async greet(name: string): Promise<string> {\n * return `Hello, ${name}!`;\n * }\n * }\n *\n * export const MyAgent = Sentry.instrumentAgentWithSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * }),\n * MyAgentBase,\n * );\n * ```\n */\nexport function instrumentAgentWithSentry<\n Env = DefaultEnv,\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends DurableObject<any> = DurableObject<Env>,\n // oxlint-disable-next-line typescript/no-explicit-any\n C extends new (state: DurableObjectState, env: any) => T = new (state: DurableObjectState, env: any) => T,\n O = unknown,\n>(optionsCallback: (env: ResolveEnv<C, Env>) => StrictCloudflareOptions<O>, AgentClass: C): C {\n const InstrumentedClass = new Proxy(AgentClass, {\n construct(target, [ctx, env], newTarget) {\n const { obj, options, context, frameworkManagedMethods } = constructInstrumentedDurableObject(\n target,\n ctx,\n env,\n newTarget,\n optionsCallback,\n );\n\n instrumentCloudflareAgent(obj);\n\n // Apply RPC prototype-method instrumentation last, so the Agent-specific own-property\n // handlers we just installed are excluded from RPC method tracing. Methods the Agent\n // framework installed itself are excluded too — `instrumentCloudflareAgent` traces those by\n // wrapping the dispatch instead of the method.\n return finalizeWithRpcInstrumentation(obj, options, context, frameworkManagedMethods);\n },\n });\n markAsInstrumented(InstrumentedClass);\n return InstrumentedClass;\n}\n"],"mappings":";;;;;;;;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Ac,MAAM,IAAI;EAK/C,QAAA,GAAOC,aAAAA,cAAAA,OAAoB,QAAQ,MAAM,cAAc,MAAM,IAAI,CAAC;CACpE;CAEA,OAAO,iBAAiB,SAAS;EAC/B,MAAM;GAAE,OAAO,eAAe;GAAM,cAAc;EAAK;EACvD,QAAQ;GAAE,OAAO,eAAe;GAAQ,cAAc;EAAK;CAC7D,CAAC;CAED,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,SAAgB,kCAOd,iBAA0E,oBAA0B;CACpG,MAAM,oBAAoB,IAAI,MAAM,oBAAoB,EACtD,UAAU,QAAQ,CAAC,KAAK,MAAM,WAAW;EACvC,MAAM,EAAE,KAAK,SAAS,SAAS,4BAA4B,mCACzD,QACA,KACA,KACA,WACA,eACF;EAEA,OAAO,+BAA+B,KAAK,SAAS,SAAS,uBAAuB;CACtF,EACF,CAAC;CAEDP,mBAAAA,mBAAmB,iBAAiB;CACpC,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,SAAgB,0BAOd,iBAA0E,YAAkB;CAC5F,MAAM,oBAAoB,IAAI,MAAM,YAAY,EAC9C,UAAU,QAAQ,CAAC,KAAK,MAAM,WAAW;EACvC,MAAM,EAAE,KAAK,SAAS,SAAS,4BAA4B,mCACzD,QACA,KACA,KACA,WACA,eACF;EAEAQ,cAAAA,0BAA0B,GAAG;EAM7B,OAAO,+BAA+B,KAAK,SAAS,SAAS,uBAAuB;CACtF,EACF,CAAC;CACDR,mBAAAA,mBAAmB,iBAAiB;CACpC,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"durableobject.js","names":["setAsyncLocalStorageAsyncContextStrategyForWorker","getFinalOptions","instrumentContext","instrumentEnv","withConstructionIsolationScope","init","flushDeferredChannelEvents","instrumentDurableObjectHandlers","getInstrumented","markAsInstrumented","wrapMethodWithSentry","RPC","hasRpcMeta","getIsolationScope","getDefaultIsolationScope","isObjectLike","startNewTrace","instrumentCloudflareAgent"],"sources":["../../../src/durableobject.ts"],"sourcesContent":["/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/unbound-method */\nimport { RPC } from '@sentry/conventions/op';\nimport { getDefaultIsolationScope, getIsolationScope, isObjectLike, startNewTrace } from '@sentry/core';\nimport type { DurableObject } from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategyForWorker } from './utils/asyncContextStrategy';\nimport type { CloudflareOptions } from './client';\nimport { getInstrumented, markAsInstrumented } from './instrument';\nimport { instrumentDurableObjectHandlers } from './instrumentations/instrumentDurableObjectHandlers';\nimport { instrumentEnv } from './instrumentations/worker/instrumentEnv';\nimport { getFinalOptions } from './options';\nimport { flushDeferredChannelEvents } from './orchestrion-deferred-channels';\nimport { init } from './sdk';\nimport { instrumentContext } from './utils/instrumentContext';\nimport { withConstructionIsolationScope } from './utils/invocationScope';\nimport { hasRpcMeta } from './utils/rpcMeta';\nimport { instrumentCloudflareAgent } from './instrumentations/agents';\nimport type { DefaultEnv, ResolveEnv, StrictCloudflareOptions } from './types';\nimport { type UncheckedMethod, wrapMethodWithSentry } from './wrapMethodWithSentry';\n\n/**\n * The instrumented context passed between the shared construction helpers.\n *\n * This is intentionally `any` rather than `ReturnType<typeof instrumentContext<DurableObjectState>>`.\n * A concrete `DurableObjectState` here forces `tsc` to structurally relate its `storage: SqlStorage`\n * graph against the `ExecutionContext | InstrumentedDurableObjectState` parameter of\n * `wrapMethodWithSentry`, while the RPC-branded `DurableObject` from `cloudflare:workers` is also in\n * scope. That union comparison explodes (1296×1296) and hangs the type build. The original inline\n * implementation avoided this only incidentally, because `ctx` reached it as `any` through the Proxy\n * `construct` trap. Keeping the shared context `any` preserves that behavior.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InstrumentedDurableObjectContext = any;\n\n/**\n * Constructs a Durable Object instance and instruments its built-in handler methods\n * (`fetch`, `alarm`, `webSocketMessage`, `webSocketClose`, `webSocketError`).\n *\n * This is the shared construction path used by both {@link instrumentDurableObjectWithSentry}\n * and {@link instrumentAgentWithSentry}. It intentionally does NOT apply the RPC prototype-method\n * instrumentation — callers apply that last via {@link finalizeWithRpcInstrumentation}, after any\n * additional per-instance instrumentation has been layered onto the returned object.\n *\n * @internal\n */\nexport function constructInstrumentedDurableObject<E, T extends DurableObject<E>>(\n target: new (state: DurableObjectState, env: E) => T,\n ctx: DurableObjectState,\n env: E,\n newTarget: NewableFunction,\n optionsCallback: (env: E) => CloudflareOptions,\n): {\n obj: T;\n options: CloudflareOptions;\n context: InstrumentedDurableObjectContext;\n frameworkManagedMethods: ReadonlySet<string>;\n} {\n setAsyncLocalStorageAsyncContextStrategyForWorker();\n const options = getFinalOptions(optionsCallback(env), env);\n // See InstrumentedDurableObjectContext — `ctx` is widened to `any` so the concrete\n // `DurableObjectState` type never enters the checker's relation graph in this module.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const context = instrumentContext(ctx as any);\n const instrumentedEnv = instrumentEnv(env as Record<string, unknown>, options);\n\n const prototype = (newTarget as unknown as { prototype?: object }).prototype ?? target.prototype;\n const cachedFrameworkManagedMethods = frameworkManagedMethodsCache.get(prototype);\n const methodsBeforeConstruction = cachedFrameworkManagedMethods\n ? undefined\n : resolveMethodsBeforeFirstConstruction(prototype);\n\n // Pass `newTarget` so that subclasses of the instrumented class (e.g. the wrapper classes\n // created by wrangler's local dev tooling or `@cloudflare/vitest-pool-workers`) keep their\n // own prototype — otherwise subclass methods disappear and `instanceof` checks break.\n const obj = withConstructionIsolationScope(() => {\n // The constructor can already use instrumented libraries, e.g. open a pi-durable Harness in\n // `blockConcurrencyWhile`. Their channel integrations only subscribe in `init()`, and an isolate\n // that runs only this Durable Object has no earlier handler that called it. A per-invocation\n // client (`cacheClient: false`) would have no invocation to flush it, so it waits for one.\n // oxlint-disable-next-line typescript/no-deprecated\n if (options.cacheClient !== false) {\n init({ ...options });\n flushDeferredChannelEvents();\n }\n return Reflect.construct(target, [context, instrumentedEnv], newTarget) as T;\n });\n\n const frameworkManagedMethods = resolveFrameworkManagedMethods(\n prototype,\n obj,\n methodsBeforeConstruction,\n cachedFrameworkManagedMethods,\n );\n\n instrumentDurableObjectHandlers(obj, options, context);\n\n return { obj, options, context, frameworkManagedMethods };\n}\n\nconst frameworkManagedMethodsCache = new WeakMap<object, ReadonlySet<string>>();\nconst methodsBeforeFirstConstructionCache = new WeakMap<object, Map<string, unknown>>();\n\n/**\n * Collects the prototype's methods as they were before any instance was constructed.\n *\n * A constructor can throw after a framework has already installed its wrappers (the `agents` SDK\n * wraps `@callable()` methods before storage initialization, which can fail). The next construction\n * would then see those wrappers as the originals and treat the methods as unmanaged, so the methods\n * collected on the first attempt are kept until a construction succeeds.\n */\nfunction resolveMethodsBeforeFirstConstruction(prototype: object): Map<string, unknown> {\n let methods = methodsBeforeFirstConstructionCache.get(prototype);\n\n if (!methods) {\n methods = resolvePrototypeMethods(prototype);\n methodsBeforeFirstConstructionCache.set(prototype, methods);\n }\n\n return methods;\n}\n\n/**\n * Collects the methods visible from a prototype, using normal property lookup precedence.\n * Methods inherited from `Object.prototype` are excluded because they cannot be Durable Object RPC methods.\n */\nfunction resolvePrototypeMethods(prototype: object | null): Map<string, unknown> {\n const methods = new Map<string, unknown>();\n\n for (let current = prototype; current && current !== Object.prototype; current = Object.getPrototypeOf(current)) {\n for (const name of Object.getOwnPropertyNames(current)) {\n // The first occurrence wins, mirroring what a property lookup on the instance would find\n if (name === 'constructor' || methods.has(name)) {\n continue;\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(current, name);\n\n if (descriptor && typeof descriptor.value === 'function') {\n methods.set(name, descriptor.value);\n }\n }\n }\n\n return methods;\n}\n\n/**\n * Finds methods that a framework replaced while constructing the first instance.\n *\n * Some frameworks register methods by function identity, so replacing one of their wrappers would\n * break dispatch. The result is cached because frameworks commonly install their wrappers only\n * once; later constructions would no longer reveal which methods they manage.\n */\nfunction resolveFrameworkManagedMethods(\n prototype: object,\n obj: object,\n methodsBeforeConstruction: Map<string, unknown> | undefined,\n cached: ReadonlySet<string> | undefined,\n): ReadonlySet<string> {\n if (cached) {\n return cached;\n }\n\n const methodsAfterConstruction = resolvePrototypeMethods(Object.getPrototypeOf(obj) as object);\n const managed = new Set<string>();\n\n for (const [name, method] of methodsAfterConstruction) {\n const before = methodsBeforeConstruction?.get(name);\n\n if (before && before !== method) {\n managed.add(name);\n }\n }\n\n frameworkManagedMethodsCache.set(prototype, managed);\n methodsBeforeFirstConstructionCache.delete(prototype);\n\n return managed;\n}\n\ntype RpcInstanceState = {\n options: CloudflareOptions;\n context: InstrumentedDurableObjectContext;\n /** Per-instance cache of the instrumented method wrappers, keyed by method name. Created on first use. */\n instrumentedMethods?: Map<string, UncheckedMethod>;\n};\n\n/**\n * Method names the runtime never dispatches over RPC, so wrapping them buys no tracing.\n *\n * Mirrors `isReservedName` in workerd (`src/workerd/api/worker-rpc.c++`): the runtime rejects these\n * before any property lookup happens. `fetch`, `alarm` and the `webSocket*` handlers are also\n * instrumented per-instance as own properties, and `constructor` is on every prototype.\n */\nconst RESERVED_RPC_METHOD_NAMES: ReadonlySet<string> = new Set([\n 'constructor',\n 'fetch',\n 'connect',\n 'alarm',\n 'webSocketMessage',\n 'webSocketClose',\n 'webSocketError',\n 'dup',\n]);\n\n// Prototype wrappers are shared by all instances, while SDK options and traced method caches are not.\nconst rpcInstanceStates = new WeakMap<object, RpcInstanceState>();\n\n/**\n * Instruments a constructed Durable Object's RPC methods.\n *\n * RPC methods are wrapped on the prototype because Cloudflare dispatches them with the Durable\n * Object instance as the receiver. This preserves native private-field access and keeps the methods\n * visible to Cloudflare's RPC dispatcher. Built-in handlers, Agent handlers, and methods managed by\n * another framework are left untouched.\n *\n * Call this after all per-instance instrumentation has been applied.\n *\n * @param obj The constructed Durable Object instance.\n * @param options The resolved SDK options for this instance.\n * @param context The instrumented execution context for this instance.\n * @param excludedMethods Method names owned by another framework and therefore not safe to wrap.\n * @returns The same Durable Object instance, with eligible prototype methods instrumented.\n * @internal\n */\nexport function finalizeWithRpcInstrumentation<T extends object>(\n obj: T,\n options: CloudflareOptions,\n context: InstrumentedDurableObjectContext,\n excludedMethods?: ReadonlySet<string>,\n): T {\n rpcInstanceStates.set(obj, { options, context });\n\n instrumentPrototypeRpcMethods(obj, excludedMethods);\n\n return obj;\n}\n\n/**\n * Returns a prototype method when it is eligible for RPC instrumentation.\n */\nfunction getRpcMethodDescriptor(\n obj: object,\n prototype: object,\n methodName: string,\n excludedMethods?: ReadonlySet<string>,\n): PropertyDescriptor | undefined {\n if (\n RESERVED_RPC_METHOD_NAMES.has(methodName) ||\n Object.prototype.hasOwnProperty.call(obj, methodName) ||\n excludedMethods?.has(methodName)\n ) {\n return undefined;\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(prototype, methodName);\n\n if (!descriptor || typeof descriptor.value !== 'function' || getInstrumented(descriptor.value)) {\n return undefined;\n }\n\n return descriptor;\n}\n\n/**\n * Wraps eligible methods on the instance's prototype chain once per class.\n */\nfunction instrumentPrototypeRpcMethods(obj: object, excludedMethods?: ReadonlySet<string>): void {\n let prototype: object | null = Object.getPrototypeOf(obj);\n\n while (prototype && prototype !== Object.prototype) {\n for (const methodName of Object.getOwnPropertyNames(prototype)) {\n const descriptor = getRpcMethodDescriptor(obj, prototype, methodName, excludedMethods);\n\n if (!descriptor) {\n continue;\n }\n\n const wrapped = createRpcPrototypeWrapper(methodName, descriptor.value as UncheckedMethod);\n\n try {\n Object.defineProperty(prototype, methodName, { ...descriptor, value: wrapped });\n } catch {}\n\n // Only the wrapper is marked, not the original method: `wrapMethodWithSentry` resolves\n // through the same global map and must not resolve the original to this wrapper,\n // which would recurse.\n markAsInstrumented(wrapped);\n }\n\n prototype = Object.getPrototypeOf(prototype);\n }\n}\n\n/**\n * Returns the instance's instrumented wrapper for an RPC method, creating it on first use.\n */\nfunction getInstrumentedRpcMethod(\n state: RpcInstanceState,\n methodName: string,\n originalMethod: UncheckedMethod,\n): UncheckedMethod {\n const instrumentedMethods = (state.instrumentedMethods ??= new Map());\n let instrumented = instrumentedMethods.get(methodName);\n\n if (!instrumented) {\n instrumented = wrapMethodWithSentry(\n {\n options: state.options,\n context: state.context,\n spanName: rpcMeta => (rpcMeta ? methodName : undefined),\n spanOp: RPC,\n origin: 'auto.faas.cloudflare.durable_object',\n },\n originalMethod,\n undefined,\n true,\n );\n instrumentedMethods.set(methodName, instrumented);\n }\n\n return instrumented;\n}\n\n/**\n * Creates a prototype wrapper that instruments external RPC calls.\n *\n * The wrapper looks up SDK state from its receiver, allowing one prototype function to serve every\n * instance. A call carrying Sentry metadata continues that trace in an `rpc` span. A call without it\n * still gets a client, so its errors, logs and metrics are captured, but no span. Calls the instance\n * makes to its own methods run the original method directly. The original function name and arity\n * are preserved because frameworks may inspect them for dispatch.\n */\nfunction createRpcPrototypeWrapper(methodName: string, originalMethod: UncheckedMethod): UncheckedMethod {\n const wrapper = function (this: unknown, ...args: unknown[]): unknown {\n const traced = hasRpcMeta(args);\n\n // workerd dispatches an incoming RPC call outside any async context, so a call made on any other\n // isolation scope comes from the instance itself (`this.helper()` inside `fetch`, `alarm`,\n // another RPC method or async work the constructor started). Check that before touching\n // per-instance state.\n if (!traced && getIsolationScope() !== getDefaultIsolationScope()) {\n return Reflect.apply(originalMethod, this, args);\n }\n\n const state = isObjectLike(this) ? rpcInstanceStates.get(this) : undefined;\n\n if (!state) {\n return Reflect.apply(originalMethod, this, args);\n }\n\n const instrumented = getInstrumentedRpcMethod(state, methodName, originalMethod);\n\n if (traced) {\n return Reflect.apply(instrumented, this, args);\n }\n\n // Unlike a WorkerEntrypoint, a Durable Object instance is long-lived and serves overlapping\n // calls. Without a new trace, every untraced call would share the trace of the default scope.\n return startNewTrace(() => Reflect.apply(instrumented, this, args));\n };\n\n Object.defineProperties(wrapper, {\n name: { value: originalMethod.name, configurable: true },\n length: { value: originalMethod.length, configurable: true },\n });\n\n return wrapper as UncheckedMethod;\n}\n\n/**\n * Instruments a Durable Object class to capture errors and performance data.\n *\n * Instruments the following methods by default:\n * - fetch\n * - alarm\n * - webSocketMessage\n * - webSocketClose\n * - webSocketError\n *\n * RPC methods (prototype methods) are instrumented too: an incoming trace continues into them, and\n * errors, logs and metrics are captured whether or not the caller propagates a trace.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param DurableObjectClass The Durable Object class to instrument.\n * @returns The instrumented Durable Object class.\n *\n * @example\n * ```ts\n * class MyDurableObjectBase extends DurableObject {\n * constructor(ctx: DurableObjectState, env: Env) {\n * super(ctx, env);\n * }\n * }\n *\n * export const MyDurableObject = instrumentDurableObjectWithSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * }),\n * MyDurableObjectBase,\n * );\n * ```\n */\nexport function instrumentDurableObjectWithSentry<\n Env = DefaultEnv,\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends DurableObject<any> = DurableObject<Env>,\n // oxlint-disable-next-line typescript/no-explicit-any\n C extends new (state: DurableObjectState, env: any) => T = new (state: DurableObjectState, env: any) => T,\n O = unknown,\n>(optionsCallback: (env: ResolveEnv<C, Env>) => StrictCloudflareOptions<O>, DurableObjectClass: C): C {\n const InstrumentedClass = new Proxy(DurableObjectClass, {\n construct(target, [ctx, env], newTarget) {\n const { obj, options, context, frameworkManagedMethods } = constructInstrumentedDurableObject(\n target,\n ctx,\n env,\n newTarget,\n optionsCallback,\n );\n\n return finalizeWithRpcInstrumentation(obj, options, context, frameworkManagedMethods);\n },\n });\n // Recognizable for `_INTERNAL_wrapUnlessInstrumented`, so auto-instrumentation never nests wrappers.\n markAsInstrumented(InstrumentedClass);\n return InstrumentedClass;\n}\n\n/**\n * Instruments a Cloudflare [`agents`](https://www.npmjs.com/package/agents) Agent class with Sentry.\n *\n * An `Agent` is a Durable Object under the hood, so this applies the same instrumentation as\n * {@link instrumentDurableObjectWithSentry} (request transactions, `alarm`, WebSocket handlers, RPC\n * trace propagation, SQL spans) and additionally captures Agent-specific telemetry via\n * `instrumentCloudflareAgent`:\n *\n * - **Callable RPC spans** — a span (op `rpc`) for each `@callable()` method invoked over WebSocket.\n * - **Breadcrumbs** — for every Agent observability event (`rpc`, `state:update`, `connect`,\n * `disconnect`, `schedule:*`, `queue:*`, `workflow:*`, `email:*`, `mcp:*`, ...).\n *\n * Cloudflare Workers cannot auto-instrument, so the Agent class must be wrapped manually.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param AgentClass The Agent class to instrument.\n * @returns The instrumented Agent class.\n *\n * @example\n * ```ts\n * import { Agent, callable, routeAgentRequest } from 'agents';\n * import * as Sentry from '@sentry/cloudflare';\n *\n * class MyAgentBase extends Agent<Env> {\n * @callable()\n * async greet(name: string): Promise<string> {\n * return `Hello, ${name}!`;\n * }\n * }\n *\n * export const MyAgent = Sentry.instrumentAgentWithSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * }),\n * MyAgentBase,\n * );\n * ```\n */\nexport function instrumentAgentWithSentry<\n Env = DefaultEnv,\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends DurableObject<any> = DurableObject<Env>,\n // oxlint-disable-next-line typescript/no-explicit-any\n C extends new (state: DurableObjectState, env: any) => T = new (state: DurableObjectState, env: any) => T,\n O = unknown,\n>(optionsCallback: (env: ResolveEnv<C, Env>) => StrictCloudflareOptions<O>, AgentClass: C): C {\n const InstrumentedClass = new Proxy(AgentClass, {\n construct(target, [ctx, env], newTarget) {\n const { obj, options, context, frameworkManagedMethods } = constructInstrumentedDurableObject(\n target,\n ctx,\n env,\n newTarget,\n optionsCallback,\n );\n\n instrumentCloudflareAgent(obj);\n\n // Apply RPC prototype-method instrumentation last, so the Agent-specific own-property\n // handlers we just installed are excluded from RPC method tracing. Methods the Agent\n // framework installed itself are excluded too — `instrumentCloudflareAgent` traces those by\n // wrapping the dispatch instead of the method.\n return finalizeWithRpcInstrumentation(obj, options, context, frameworkManagedMethods);\n },\n });\n markAsInstrumented(InstrumentedClass);\n return Instrumented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,QACF,OAAO,QAAQ,MAAM,cAAc,MAAM,IAAI;EAK/C,QAAA,GAAOC,aAAAA,cAAAA,OAAoB,QAAQ,MAAM,cAAc,MAAM,IAAI,CAAC;CACpE;CAEA,OAAO,iBAAiB,SAAS;EAC/B,MAAM;GAAE,OAAO,eAAe;GAAM,cAAc;EAAK;EACvD,QAAQ;GAAE,OAAO,eAAe;GAAQ,cAAc;EAAK;CAC7D,CAAC;CAED,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,SAAgB,kCAOd,iBAA0E,oBAA0B;CACpG,MAAM,oBAAoB,IAAI,MAAM,oBAAoB,EACtD,UAAU,QAAQ,CAAC,KAAK,MAAM,WAAW;EACvC,MAAM,EAAE,KAAK,SAAS,SAAS,4BAA4B,mCACzD,QACA,KACA,KACA,WACA,eACF;EAEA,OAAO,+BAA+B,KAAK,SAAS,SAAS,uBAAuB;CACtF,EACF,CAAC;CAEDP,mBAAAA,mBAAmB,iBAAiB;CACpC,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,SAAgB,0BAOd,iBAA0E,YAAkB;CAC5F,MAAM,oBAAoB,IAAI,MAAM,YAAY,EAC9C,UAAU,QAAQ,CAAC,KAAK,MAAM,WAAW;EACvC,MAAM,EAAE,KAAK,SAAS,SAAS,4BAA4B,mCACzD,QACA,KACA,KACA,WACA,eACF;EAEAQ,cAAAA,0BAA0B,GAAG;EAM7B,OAAO,+BAA+B,KAAK,SAAS,SAAS,uBAAuB;CACtF,EACF,CAAC;CACDR,mBAAAA,mBAAmB,iBAAiB;CACpC,OAAO;AACT"}
|
package/build/cjs/dev/options.js
CHANGED
|
@@ -35,6 +35,7 @@ function getFinalOptions(userOptions = {}, env) {
|
|
|
35
35
|
...userOptions,
|
|
36
36
|
dsn: userOptions.dsn ?? getEnvVar(env, "SENTRY_DSN"),
|
|
37
37
|
environment: userOptions.environment ?? getEnvVar(env, "SENTRY_ENVIRONMENT"),
|
|
38
|
+
serverName: userOptions.serverName ?? getEnvVar(env, "SENTRY_NAME"),
|
|
38
39
|
tracesSampleRate: isFinite(tracesSampleRate) ? tracesSampleRate : void 0,
|
|
39
40
|
debug: userOptions.debug ?? (0, _sentry_core.envToBool)(getEnvVar(env, "SENTRY_DEBUG")),
|
|
40
41
|
tunnel: userOptions.tunnel ?? getEnvVar(env, "SENTRY_TUNNEL"),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"options.js","names":["isObjectLike","envToBool"],"sources":["../../../src/options.ts"],"sourcesContent":["import { isObjectLike, envToBool } from '@sentry/core';\nimport type { CloudflareOptions } from './client';\n\n/**\n * Cloudflare's version metadata binding structure.\n * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/version-metadata/\n */\ninterface CfVersionMetadata {\n id: string;\n tag?: string;\n timestamp?: string;\n}\n\n/**\n * Checks if the value is a valid CF_VERSION_METADATA binding.\n */\nfunction isVersionMetadata(value: unknown): value is CfVersionMetadata {\n return isObjectLike(value) && 'id' in value && typeof value.id === 'string';\n}\n\nfunction getEnvVar<T extends Record<string, unknown>>(env: unknown, varName: keyof T): string | undefined {\n return isObjectLike(env) && varName in env && typeof (env as T)[varName] === 'string'\n ? ((env as T)[varName] as string)\n : undefined;\n}\n\n/**\n * Merges the options passed in from the user with the options we read from\n * the Cloudflare `env` environment variable object.\n *\n * Release is determined with the following priority (highest to lowest):\n * 1. User-provided release option\n * 2. SENTRY_RELEASE environment variable\n * 3. CF_VERSION_METADATA.id binding (if configured in the wrangler config)\n *\n * @param userOptions - The options passed in from the user.\n * @param env - The environment variables.\n *\n * @returns The final options.\n */\nexport function getFinalOptions(userOptions: CloudflareOptions = {}, env: unknown): CloudflareOptions {\n if (!isObjectLike(env)) {\n return userOptions;\n }\n\n // Priority: userOptions.release > SENTRY_RELEASE > CF_VERSION_METADATA.id\n const release =\n 'SENTRY_RELEASE' in env && typeof env.SENTRY_RELEASE === 'string'\n ? env.SENTRY_RELEASE\n : 'CF_VERSION_METADATA' in env && isVersionMetadata(env.CF_VERSION_METADATA)\n ? env.CF_VERSION_METADATA.id\n : undefined;\n\n const tracesSampleRate =\n userOptions.tracesSampleRate ?? parseFloat(getEnvVar(env, 'SENTRY_TRACES_SAMPLE_RATE') ?? '');\n\n // Spotlight precedence (mirrors node-core's getSpotlightConfig):\n // - false or explicit string from options: use as-is\n // - true: enable, but prefer a custom URL from the env var if set\n // - undefined: defer entirely to the env var (bool or URL)\n /*! rollup-include-development-only */\n const spotlight = getSpotlightFromEnv(userOptions.spotlight, getEnvVar(env, 'SENTRY_SPOTLIGHT'));\n /*! rollup-include-development-only-end */\n\n return {\n release,\n ...userOptions,\n dsn: userOptions.dsn ?? getEnvVar(env, 'SENTRY_DSN'),\n environment: userOptions.environment ?? getEnvVar(env, 'SENTRY_ENVIRONMENT'),\n tracesSampleRate: isFinite(tracesSampleRate) ? tracesSampleRate : undefined,\n debug: userOptions.debug ?? envToBool(getEnvVar(env, 'SENTRY_DEBUG')),\n tunnel: userOptions.tunnel ?? getEnvVar(env, 'SENTRY_TUNNEL'),\n traceLifecycle: userOptions.traceLifecycle ?? getTraceLifecycleFromEnv(getEnvVar(env, 'SENTRY_TRACE_LIFECYCLE')),\n /*! rollup-include-development-only */\n spotlight,\n /*! rollup-include-development-only-end */\n };\n}\n\n/**\n * Resolve the spotlight option from a user-supplied value and an env binding string.\n * Mirrors node-core's `getSpotlightConfig` precedence:\n * - `false` or explicit string from options → use as-is\n * - `true` → enable, but prefer a custom URL from the env var if set\n * - `undefined` → defer entirely to the env var (bool or URL)\n */\nfunction getSpotlightFromEnv(\n optionsSpotlight: boolean | string | undefined,\n envVar: string | undefined,\n): boolean | string | undefined {\n if (optionsSpotlight === false) {\n return false;\n }\n if (typeof optionsSpotlight === 'string') {\n return optionsSpotlight;\n }\n\n // optionsSpotlight is true or undefined\n const envBool = envToBool(envVar, { strict: true });\n const envUrl = envBool === null && envVar ? envVar : undefined;\n\n return optionsSpotlight === true\n ? (envUrl ?? true) // true: use env URL if present, otherwise true\n : (envBool ?? envUrl); // undefined: use env var (bool or URL)\n}\n\nfunction getTraceLifecycleFromEnv(envVar: string | undefined): 'static' | 'stream' | undefined {\n return envVar === 'stream' || envVar === 'static' ? envVar : undefined;\n}\n"],"mappings":";;;;;AAgBA,SAAS,kBAAkB,OAA4C;CACrE,QAAA,GAAOA,aAAAA,aAAAA,CAAa,KAAK,KAAK,QAAQ,SAAS,OAAO,MAAM,OAAO;AACrE;AAEA,SAAS,UAA6C,KAAc,SAAsC;CACxG,QAAA,GAAOA,aAAAA,aAAAA,CAAa,GAAG,KAAK,WAAW,OAAO,OAAQ,IAAU,aAAa,WACvE,IAAU,WACZ,KAAA;AACN;;;;;;;;;;;;;;;AAgBA,SAAgB,gBAAgB,cAAiC,CAAC,GAAG,KAAiC;CACpG,IAAI,EAAA,GAACA,aAAAA,aAAAA,CAAa,GAAG,GACnB,OAAO;CAIT,MAAM,UACJ,oBAAoB,OAAO,OAAO,IAAI,mBAAmB,WACrD,IAAI,iBACJ,yBAAyB,OAAO,kBAAkB,IAAI,mBAAmB,IACvE,IAAI,oBAAoB,KACxB,KAAA;CAER,MAAM,mBACJ,YAAY,oBAAoB,WAAW,UAAU,KAAK,2BAA2B,KAAK,EAAE;;CAO9F,MAAM,YAAY,oBAAoB,YAAY,WAAW,UAAU,KAAK,kBAAkB,CAAC;;CAG/F,OAAO;EACL;EACA,GAAG;EACH,KAAK,YAAY,OAAO,UAAU,KAAK,YAAY;EACnD,aAAa,YAAY,eAAe,UAAU,KAAK,oBAAoB;EAC3E,kBAAkB,SAAS,gBAAgB,IAAI,mBAAmB,KAAA;EAClE,OAAO,YAAY,UAAA,GAASC,aAAAA,UAAAA,CAAU,UAAU,KAAK,cAAc,CAAC;EACpE,QAAQ,YAAY,UAAU,UAAU,KAAK,eAAe;EAC5D,gBAAgB,YAAY,kBAAkB,yBAAyB,UAAU,KAAK,wBAAwB,CAAC;;EAE/G;CAEF;;AACF;;;;;;;;AASA,SAAS,oBACP,kBACA,QAC8B;CAC9B,IAAI,qBAAqB,OACvB,OAAO;CAET,IAAI,OAAO,qBAAqB,UAC9B,OAAO;CAIT,MAAM,WAAA,GAAUA,aAAAA,UAAAA,CAAU,QAAQ,EAAE,QAAQ,KAAK,CAAC;CAClD,MAAM,SAAS,YAAY,QAAQ,SAAS,SAAS,KAAA;CAErD,OAAO,qBAAqB,OACvB,UAAU,OACV,WAAW;AAClB;AAEA,SAAS,yBAAyB,QAA6D;CAC7F,OAAO,WAAW,YAAY,WAAW,WAAW,SAAS,KAAA;AAC/D"}
|
|
1
|
+
{"version":3,"file":"options.js","names":["isObjectLike","envToBool"],"sources":["../../../src/options.ts"],"sourcesContent":["import { isObjectLike, envToBool } from '@sentry/core';\nimport type { CloudflareOptions } from './client';\n\n/**\n * Cloudflare's version metadata binding structure.\n * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/version-metadata/\n */\ninterface CfVersionMetadata {\n id: string;\n tag?: string;\n timestamp?: string;\n}\n\n/**\n * Checks if the value is a valid CF_VERSION_METADATA binding.\n */\nfunction isVersionMetadata(value: unknown): value is CfVersionMetadata {\n return isObjectLike(value) && 'id' in value && typeof value.id === 'string';\n}\n\nfunction getEnvVar<T extends Record<string, unknown>>(env: unknown, varName: keyof T): string | undefined {\n return isObjectLike(env) && varName in env && typeof (env as T)[varName] === 'string'\n ? ((env as T)[varName] as string)\n : undefined;\n}\n\n/**\n * Merges the options passed in from the user with the options we read from\n * the Cloudflare `env` environment variable object.\n *\n * Release is determined with the following priority (highest to lowest):\n * 1. User-provided release option\n * 2. SENTRY_RELEASE environment variable\n * 3. CF_VERSION_METADATA.id binding (if configured in the wrangler config)\n *\n * @param userOptions - The options passed in from the user.\n * @param env - The environment variables.\n *\n * @returns The final options.\n */\nexport function getFinalOptions(userOptions: CloudflareOptions = {}, env: unknown): CloudflareOptions {\n if (!isObjectLike(env)) {\n return userOptions;\n }\n\n // Priority: userOptions.release > SENTRY_RELEASE > CF_VERSION_METADATA.id\n const release =\n 'SENTRY_RELEASE' in env && typeof env.SENTRY_RELEASE === 'string'\n ? env.SENTRY_RELEASE\n : 'CF_VERSION_METADATA' in env && isVersionMetadata(env.CF_VERSION_METADATA)\n ? env.CF_VERSION_METADATA.id\n : undefined;\n\n const tracesSampleRate =\n userOptions.tracesSampleRate ?? parseFloat(getEnvVar(env, 'SENTRY_TRACES_SAMPLE_RATE') ?? '');\n\n // Spotlight precedence (mirrors node-core's getSpotlightConfig):\n // - false or explicit string from options: use as-is\n // - true: enable, but prefer a custom URL from the env var if set\n // - undefined: defer entirely to the env var (bool or URL)\n /*! rollup-include-development-only */\n const spotlight = getSpotlightFromEnv(userOptions.spotlight, getEnvVar(env, 'SENTRY_SPOTLIGHT'));\n /*! rollup-include-development-only-end */\n\n return {\n release,\n ...userOptions,\n dsn: userOptions.dsn ?? getEnvVar(env, 'SENTRY_DSN'),\n environment: userOptions.environment ?? getEnvVar(env, 'SENTRY_ENVIRONMENT'),\n serverName: userOptions.serverName ?? getEnvVar(env, 'SENTRY_NAME'),\n tracesSampleRate: isFinite(tracesSampleRate) ? tracesSampleRate : undefined,\n debug: userOptions.debug ?? envToBool(getEnvVar(env, 'SENTRY_DEBUG')),\n tunnel: userOptions.tunnel ?? getEnvVar(env, 'SENTRY_TUNNEL'),\n traceLifecycle: userOptions.traceLifecycle ?? getTraceLifecycleFromEnv(getEnvVar(env, 'SENTRY_TRACE_LIFECYCLE')),\n /*! rollup-include-development-only */\n spotlight,\n /*! rollup-include-development-only-end */\n };\n}\n\n/**\n * Resolve the spotlight option from a user-supplied value and an env binding string.\n * Mirrors node-core's `getSpotlightConfig` precedence:\n * - `false` or explicit string from options → use as-is\n * - `true` → enable, but prefer a custom URL from the env var if set\n * - `undefined` → defer entirely to the env var (bool or URL)\n */\nfunction getSpotlightFromEnv(\n optionsSpotlight: boolean | string | undefined,\n envVar: string | undefined,\n): boolean | string | undefined {\n if (optionsSpotlight === false) {\n return false;\n }\n if (typeof optionsSpotlight === 'string') {\n return optionsSpotlight;\n }\n\n // optionsSpotlight is true or undefined\n const envBool = envToBool(envVar, { strict: true });\n const envUrl = envBool === null && envVar ? envVar : undefined;\n\n return optionsSpotlight === true\n ? (envUrl ?? true) // true: use env URL if present, otherwise true\n : (envBool ?? envUrl); // undefined: use env var (bool or URL)\n}\n\nfunction getTraceLifecycleFromEnv(envVar: string | undefined): 'static' | 'stream' | undefined {\n return envVar === 'stream' || envVar === 'static' ? envVar : undefined;\n}\n"],"mappings":";;;;;AAgBA,SAAS,kBAAkB,OAA4C;CACrE,QAAA,GAAOA,aAAAA,aAAAA,CAAa,KAAK,KAAK,QAAQ,SAAS,OAAO,MAAM,OAAO;AACrE;AAEA,SAAS,UAA6C,KAAc,SAAsC;CACxG,QAAA,GAAOA,aAAAA,aAAAA,CAAa,GAAG,KAAK,WAAW,OAAO,OAAQ,IAAU,aAAa,WACvE,IAAU,WACZ,KAAA;AACN;;;;;;;;;;;;;;;AAgBA,SAAgB,gBAAgB,cAAiC,CAAC,GAAG,KAAiC;CACpG,IAAI,EAAA,GAACA,aAAAA,aAAAA,CAAa,GAAG,GACnB,OAAO;CAIT,MAAM,UACJ,oBAAoB,OAAO,OAAO,IAAI,mBAAmB,WACrD,IAAI,iBACJ,yBAAyB,OAAO,kBAAkB,IAAI,mBAAmB,IACvE,IAAI,oBAAoB,KACxB,KAAA;CAER,MAAM,mBACJ,YAAY,oBAAoB,WAAW,UAAU,KAAK,2BAA2B,KAAK,EAAE;;CAO9F,MAAM,YAAY,oBAAoB,YAAY,WAAW,UAAU,KAAK,kBAAkB,CAAC;;CAG/F,OAAO;EACL;EACA,GAAG;EACH,KAAK,YAAY,OAAO,UAAU,KAAK,YAAY;EACnD,aAAa,YAAY,eAAe,UAAU,KAAK,oBAAoB;EAC3E,YAAY,YAAY,cAAc,UAAU,KAAK,aAAa;EAClE,kBAAkB,SAAS,gBAAgB,IAAI,mBAAmB,KAAA;EAClE,OAAO,YAAY,UAAA,GAASC,aAAAA,UAAAA,CAAU,UAAU,KAAK,cAAc,CAAC;EACpE,QAAQ,YAAY,UAAU,UAAU,KAAK,eAAe;EAC5D,gBAAgB,YAAY,kBAAkB,yBAAyB,UAAU,KAAK,wBAAwB,CAAC;;EAE/G;CAEF;;AACF;;;;;;;;AASA,SAAS,oBACP,kBACA,QAC8B;CAC9B,IAAI,qBAAqB,OACvB,OAAO;CAET,IAAI,OAAO,qBAAqB,UAC9B,OAAO;CAIT,MAAM,WAAA,GAAUA,aAAAA,UAAAA,CAAU,QAAQ,EAAE,QAAQ,KAAK,CAAC;CAClD,MAAM,SAAS,YAAY,QAAQ,SAAS,SAAS,KAAA;CAErD,OAAO,qBAAqB,OACvB,UAAU,OACV,WAAW;AAClB;AAEA,SAAS,yBAAyB,QAA6D;CAC7F,OAAO,WAAW,YAAY,WAAW,WAAW,SAAS,KAAA;AAC/D"}
|
|
@@ -116,7 +116,11 @@ function sentryCloudflareAutoInstrumentPlugin(options = {}) {
|
|
|
116
116
|
optionsFn,
|
|
117
117
|
optionsImport,
|
|
118
118
|
sameWorkerBindings: wranglerConfig.sameWorkerBindings,
|
|
119
|
-
sentryModule
|
|
119
|
+
sentryModule,
|
|
120
|
+
workerInfo: {
|
|
121
|
+
name: wranglerConfig.name,
|
|
122
|
+
compatibilityDate: wranglerConfig.compatibilityDate
|
|
123
|
+
}
|
|
120
124
|
});
|
|
121
125
|
const wrappedClasses = result?.wrappedClasses ?? /* @__PURE__ */ new Set();
|
|
122
126
|
const missing = [...classWrappers.keys()].filter((name) => !wrappedClasses.has(name));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"autoInstrument.js","names":["resolveWranglerConfig","basename","isAbsolute","resolveInstrumentFile","dirname","createIdResolver","collectAgentCandidates","detectAgentClasses","buildOptionsImport","ENV_FALLBACK_OPTIONS_FN","applyAutoInstrumentTransforms"],"sources":["../../../../src/vite/autoInstrument.ts"],"sourcesContent":["import { basename, dirname, isAbsolute } from 'node:path';\nimport { createIdResolver, type ResolvedConfig } from 'vite';\nimport { collectAgentCandidates, detectAgentClasses, type ModuleResolver } from './agentClass';\nimport { buildOptionsImport, ENV_FALLBACK_OPTIONS_FN, resolveInstrumentFile } from './instrumentFile';\nimport { applyAutoInstrumentTransforms, type BaseNode, type ClassWrapperKind, type ProgramBody } from './transform';\nimport { resolveWranglerConfig, type WranglerConfig } from './wranglerConfig';\n\n// Vite normalizes module IDs to posix separators even on Windows, while\n// `path.resolve` yields backslashes there — normalize before comparing.\nfunction normalizePath(path: string): string {\n return path.replace(/\\\\/g, '/');\n}\n\n// Extensions the entry-module match may tolerate swapping (e.g. wrangler's\n// `main` says `.ts` but the served module is `.js`). Anything else — `.css`,\n// `.html`, … — sharing the entry's basename must never be treated as the entry.\nconst JS_EXTENSION_REGEX = /\\.[cm]?[jt]sx?$/;\n\n// Re-exports everything the generated code uses, and adds the Next.js span handling and OpenTelemetry context.\nconst NEXTJS_CLOUDFLARE_MODULE = '@sentry/nextjs/cloudflare';\n\n/**\n * Whether `@sentry/nextjs/cloudflare` resolves from `importer`. Vite throws instead of returning `null` when\n * `@sentry/nextjs` is installed in a version without that entry.\n */\nasync function resolvesNextjsCloudflare(resolver: ModuleResolver, importer: string): Promise<boolean> {\n try {\n return !!(await resolver.resolve?.(NEXTJS_CLOUDFLARE_MODULE, importer));\n } catch {\n return false;\n }\n}\n\n/**\n * Whether the module re-exports everything from another module of its own file, as the shim\n * `@sentry/tanstackstart-react` loads for the server entry does (`export * from \"<entry>?sentry-tunnel-original\"`).\n * That module is transformed as the entry too, and its classes are wrapped there.\n */\nfunction reexportsAllFromSameFile(ast: ProgramBody, normalizedId: string): boolean {\n return ast.body.some(node => {\n if (node.type !== 'ExportAllDeclaration') return false;\n const { exported, source } = node as BaseNode & { exported?: unknown; source?: { value?: unknown } };\n const value = source?.value;\n return !exported && typeof value === 'string' && normalizePath(value.replace(/[?#].*$/, '')) === normalizedId;\n });\n}\n\ntype TransformContext = ModuleResolver & {\n warn?(msg: string): void;\n environment?: Parameters<ReturnType<typeof createIdResolver>>[0];\n};\n\nexport function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPath?: string } = {}) {\n let wranglerConfig: WranglerConfig | undefined;\n let entryFilePath: string | undefined;\n // A `main` that is not a file path (a package export or virtual module).\n let entrySpecifier: string | undefined;\n let wranglerConfigPath: string | undefined;\n let resolveId: ReturnType<typeof createIdResolver> | undefined;\n // Each environment resolves with its own conditions, so the entry may differ between them.\n const resolvedEntries = new Map<string, Promise<string | undefined>>();\n\n let instrumentFilePath: string | undefined;\n let isVinext = false;\n\n function resolveEntrySpecifier(ctx: TransformContext, specifier: string): Promise<string | undefined> {\n const environment = ctx.environment;\n if (!environment || !resolveId) return Promise.resolve(undefined);\n\n let entry = resolvedEntries.get(environment.name);\n if (!entry) {\n // Resolved from the wrangler config, as wrangler does. Without an importer, Vite's resolver\n // tries the specifier as a path below the root first.\n entry = resolveId(environment, specifier, wranglerConfigPath)\n .catch(() => undefined)\n .then(id => {\n if (!id) {\n ctx.warn?.(\n `[sentry] Could not resolve the wrangler \\`main\\` \"${specifier}\". Auto-instrumentation disabled.`,\n );\n return undefined;\n }\n return normalizePath(id.replace(/[?#].*$/, ''));\n });\n resolvedEntries.set(environment.name, entry);\n }\n return entry;\n }\n\n return {\n name: 'sentry-cloudflare-auto-instrument',\n\n configResolved(config: {\n root: string;\n plugins?: readonly { name?: string }[];\n logger?: { warn(msg: string): void };\n }): void {\n isVinext = config.plugins?.some(plugin => plugin.name?.startsWith('vinext:')) ?? false;\n\n const result = resolveWranglerConfig(config.root, options.wranglerConfigPath);\n if (!result) {\n // An explicit path that fails is a misconfiguration worth naming;\n // without one, hint at the option so custom-named configs (e.g. a\n // `configPath` handed to @cloudflare/vite-plugin) are discoverable.\n config.logger?.warn(\n options.wranglerConfigPath\n ? `[sentry] Could not find or parse the wrangler config \"${basename(options.wranglerConfigPath)}\" ` +\n '(resolved against the Vite root) — auto-instrumentation disabled.'\n : '[sentry] No parseable wrangler config found — auto-instrumentation disabled. ' +\n 'Set `wranglerConfigPath` if your config uses a custom name.',\n );\n return;\n }\n\n wranglerConfig = result.config;\n const main = wranglerConfig.main;\n if (main && isAbsolute(main)) {\n // Normalize separators so the entry-module comparison holds on Windows.\n entryFilePath = normalizePath(main);\n instrumentFilePath = resolveInstrumentFile(dirname(main));\n } else if (main) {\n entrySpecifier = main;\n wranglerConfigPath = result.configPath;\n // Not `this.resolve()`: Rollup's commonjs resolver loads the module it resolves, so a\n // resolve of the entry from the entry's own `transform` never finishes.\n resolveId = createIdResolver(config as ResolvedConfig);\n // A package entry has no project directory of its own.\n instrumentFilePath = resolveInstrumentFile(result.configDir);\n }\n },\n\n async transform(\n this: TransformContext,\n code: string,\n id: string,\n ): Promise<{ code: string; map: unknown } | undefined> {\n if (!wranglerConfig || (!entryFilePath && !entrySpecifier)) return undefined;\n\n // The worker entry never belongs to the client (browser) environment.\n // Skipping it keeps a same-basename sibling (e.g. a `src/index.tsx`\n // client entry next to a `src/index.ts` worker) out of the browser bundle.\n if (this.environment?.name === 'client') return undefined;\n\n const entryPath = entrySpecifier ? await resolveEntrySpecifier(this, entrySpecifier) : entryFilePath;\n if (!entryPath) return undefined;\n\n // Vite may append query/hash params to the module ID.\n const normalizedId = normalizePath(id.replace(/[?#].*$/, ''));\n if (normalizedId !== entryPath) {\n // Tolerate a differing JS-flavored extension (e.g. `.js` vs `.ts`).\n if (!JS_EXTENSION_REGEX.test(normalizedId) || !JS_EXTENSION_REGEX.test(entryPath)) return undefined;\n if (normalizedId.replace(JS_EXTENSION_REGEX, '') !== entryPath.replace(JS_EXTENSION_REGEX, '')) {\n return undefined;\n }\n }\n\n let ast: ProgramBody;\n try {\n ast = this.parse(code);\n } catch {\n // Raw TypeScript or syntax error — esbuild hasn't run yet (unlikely)\n // or the file is genuinely broken. Either way, skip silently.\n return undefined;\n }\n\n const classWrappers = new Map<string, ClassWrapperKind>();\n for (const { className } of wranglerConfig.durableObjects) {\n classWrappers.set(className, 'durableObject');\n }\n for (const { className } of wranglerConfig.workflows) {\n classWrappers.set(className, 'workflow');\n }\n for (const className of wranglerConfig.workerEntrypoints) {\n classWrappers.set(className, 'workerEntrypoint');\n }\n\n // An `agents` Agent is a Durable Object, so wrangler lists it among the DO bindings and only\n // its base-class chain tells the two apart. Detection walks the module graph (base classes\n // usually live in their own file), so it is limited to the configured DO classes.\n //\n // Only `resolve` is handed over — never `load`: awaiting `load()` from inside a transform\n // hook deadlocks the build, since the module can't finish loading while this transform is\n // still pending. `agentClass` reads sibling modules off disk instead.\n const agentCandidates = collectAgentCandidates(\n ast,\n [...classWrappers].filter(([, kind]) => kind === 'durableObject').map(([name]) => name),\n );\n const agentClasses =\n agentCandidates.size > 0\n ? await detectAgentClasses(ast, normalizedId, agentCandidates, {\n parse: code => this.parse(code),\n resolve: this.resolve ? (source, importer) => this.resolve!(source, importer) : undefined,\n })\n : undefined;\n\n // A vinext app with `@sentry/nextjs` installed gets `withSentry` of `@sentry/nextjs/cloudflare`.\n const sentryModule =\n isVinext && (await resolvesNextjsCloudflare(this, normalizedId)) ? NEXTJS_CLOUDFLARE_MODULE : undefined;\n\n const { optionsFn, importStmt: optionsImport } = instrumentFilePath\n ? buildOptionsImport(entryPath, instrumentFilePath)\n : { optionsFn: ENV_FALLBACK_OPTIONS_FN, importStmt: undefined };\n\n // No registration import is injected here: the orchestrion plugin's\n // subscribe-injection makes each bundled package self-register its channel\n // subscriber on the global marker, so wrapping the entry with `withSentry`\n // is all this plugin needs to do.\n const result = applyAutoInstrumentTransforms(code, ast, {\n classWrappers,\n agentClasses,\n optionsFn,\n optionsImport,\n sameWorkerBindings: wranglerConfig.sameWorkerBindings,\n sentryModule,\n });\n\n const wrappedClasses = result?.wrappedClasses ?? new Set<string>();\n const missing = [...classWrappers.keys()].filter(name => !wrappedClasses.has(name));\n if (missing.length > 0 && !reexportsAllFromSameFile(ast, normalizedId)) {\n this.warn?.(\n `[sentry] Could not auto-instrument ${missing.join(', ')}. ` +\n 'The worker entry has no export matching them. ' +\n 'Star re-exports (`export * from \"./do\"`) are not matched. ' +\n 'Export them by name or wrap them manually with corresponding `instrument*WithSentry` helpers.',\n );\n }\n\n return result ?? undefined;\n },\n };\n}\n"],"mappings":";;;;;;;AASA,SAAS,cAAc,MAAsB;CAC3C,OAAO,KAAK,QAAQ,OAAO,GAAG;AAChC;AAKA,MAAM,qBAAqB;AAG3B,MAAM,2BAA2B;;;;;AAMjC,eAAe,yBAAyB,UAA0B,UAAoC;CACpG,IAAI;EACF,OAAO,CAAC,CAAE,MAAM,SAAS,UAAU,0BAA0B,QAAQ;CACvE,QAAQ;EACN,OAAO;CACT;AACF;;;;;;AAOA,SAAS,yBAAyB,KAAkB,cAA+B;CACjF,OAAO,IAAI,KAAK,MAAK,SAAQ;EAC3B,IAAI,KAAK,SAAS,wBAAwB,OAAO;EACjD,MAAM,EAAE,UAAU,WAAW;EAC7B,MAAM,QAAQ,QAAQ;EACtB,OAAO,CAAC,YAAY,OAAO,UAAU,YAAY,cAAc,MAAM,QAAQ,WAAW,EAAE,CAAC,MAAM;CACnG,CAAC;AACH;AAOA,SAAgB,qCAAqC,UAA2C,CAAC,GAAG;CAClG,IAAI;CACJ,IAAI;CAEJ,IAAI;CACJ,IAAI;CACJ,IAAI;CAEJ,MAAM,kCAAkB,IAAI,IAAyC;CAErE,IAAI;CACJ,IAAI,WAAW;CAEf,SAAS,sBAAsB,KAAuB,WAAgD;EACpG,MAAM,cAAc,IAAI;EACxB,IAAI,CAAC,eAAe,CAAC,WAAW,OAAO,QAAQ,QAAQ,KAAA,CAAS;EAEhE,IAAI,QAAQ,gBAAgB,IAAI,YAAY,IAAI;EAChD,IAAI,CAAC,OAAO;GAGV,QAAQ,UAAU,aAAa,WAAW,kBAAkB,CAAC,CAC1D,YAAY,KAAA,CAAS,CAAC,CACtB,MAAK,OAAM;IACV,IAAI,CAAC,IAAI;KACP,IAAI,OACF,qDAAqD,UAAU,kCACjE;KACA;IACF;IACA,OAAO,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Q,SAAS,KAAK,CAAC,yBAAyB,KAAK,YAAY,GACnE,KAAK,OACH,sCAAsC,QAAQ,KAAK,IAAI,EAAE,4MAI3D;GAGF,OAAO,UAAU,KAAA;EACnB;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"autoInstrument.js","names":["resolveWranglerConfig","basename","isAbsolute","resolveInstrumentFile","dirname","createIdResolver","collectAgentCandidates","detectAgentClasses","buildOptionsImport","ENV_FALLBACK_OPTIONS_FN","applyAutoInstrumentTransforms"],"sources":["../../../../src/vite/autoInstrument.ts"],"sourcesContent":["import { basename, dirname, isAbsolute } from 'node:path';\nimport { createIdResolver, type ResolvedConfig } from 'vite';\nimport { collectAgentCandidates, detectAgentClasses, type ModuleResolver } from './agentClass';\nimport { buildOptionsImport, ENV_FALLBACK_OPTIONS_FN, resolveInstrumentFile } from './instrumentFile';\nimport { applyAutoInstrumentTransforms, type BaseNode, type ClassWrapperKind, type ProgramBody } from './transform';\nimport { resolveWranglerConfig, type WranglerConfig } from './wranglerConfig';\n\n// Vite normalizes module IDs to posix separators even on Windows, while\n// `path.resolve` yields backslashes there — normalize before comparing.\nfunction normalizePath(path: string): string {\n return path.replace(/\\\\/g, '/');\n}\n\n// Extensions the entry-module match may tolerate swapping (e.g. wrangler's\n// `main` says `.ts` but the served module is `.js`). Anything else — `.css`,\n// `.html`, … — sharing the entry's basename must never be treated as the entry.\nconst JS_EXTENSION_REGEX = /\\.[cm]?[jt]sx?$/;\n\n// Re-exports everything the generated code uses, and adds the Next.js span handling and OpenTelemetry context.\nconst NEXTJS_CLOUDFLARE_MODULE = '@sentry/nextjs/cloudflare';\n\n/**\n * Whether `@sentry/nextjs/cloudflare` resolves from `importer`. Vite throws instead of returning `null` when\n * `@sentry/nextjs` is installed in a version without that entry.\n */\nasync function resolvesNextjsCloudflare(resolver: ModuleResolver, importer: string): Promise<boolean> {\n try {\n return !!(await resolver.resolve?.(NEXTJS_CLOUDFLARE_MODULE, importer));\n } catch {\n return false;\n }\n}\n\n/**\n * Whether the module re-exports everything from another module of its own file, as the shim\n * `@sentry/tanstackstart-react` loads for the server entry does (`export * from \"<entry>?sentry-tunnel-original\"`).\n * That module is transformed as the entry too, and its classes are wrapped there.\n */\nfunction reexportsAllFromSameFile(ast: ProgramBody, normalizedId: string): boolean {\n return ast.body.some(node => {\n if (node.type !== 'ExportAllDeclaration') return false;\n const { exported, source } = node as BaseNode & { exported?: unknown; source?: { value?: unknown } };\n const value = source?.value;\n return !exported && typeof value === 'string' && normalizePath(value.replace(/[?#].*$/, '')) === normalizedId;\n });\n}\n\ntype TransformContext = ModuleResolver & {\n warn?(msg: string): void;\n environment?: Parameters<ReturnType<typeof createIdResolver>>[0];\n};\n\nexport function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPath?: string } = {}) {\n let wranglerConfig: WranglerConfig | undefined;\n let entryFilePath: string | undefined;\n // A `main` that is not a file path (a package export or virtual module).\n let entrySpecifier: string | undefined;\n let wranglerConfigPath: string | undefined;\n let resolveId: ReturnType<typeof createIdResolver> | undefined;\n // Each environment resolves with its own conditions, so the entry may differ between them.\n const resolvedEntries = new Map<string, Promise<string | undefined>>();\n\n let instrumentFilePath: string | undefined;\n let isVinext = false;\n\n function resolveEntrySpecifier(ctx: TransformContext, specifier: string): Promise<string | undefined> {\n const environment = ctx.environment;\n if (!environment || !resolveId) return Promise.resolve(undefined);\n\n let entry = resolvedEntries.get(environment.name);\n if (!entry) {\n // Resolved from the wrangler config, as wrangler does. Without an importer, Vite's resolver\n // tries the specifier as a path below the root first.\n entry = resolveId(environment, specifier, wranglerConfigPath)\n .catch(() => undefined)\n .then(id => {\n if (!id) {\n ctx.warn?.(\n `[sentry] Could not resolve the wrangler \\`main\\` \"${specifier}\". Auto-instrumentation disabled.`,\n );\n return undefined;\n }\n return normalizePath(id.replace(/[?#].*$/, ''));\n });\n resolvedEntries.set(environment.name, entry);\n }\n return entry;\n }\n\n return {\n name: 'sentry-cloudflare-auto-instrument',\n\n configResolved(config: {\n root: string;\n plugins?: readonly { name?: string }[];\n logger?: { warn(msg: string): void };\n }): void {\n isVinext = config.plugins?.some(plugin => plugin.name?.startsWith('vinext:')) ?? false;\n\n const result = resolveWranglerConfig(config.root, options.wranglerConfigPath);\n if (!result) {\n // An explicit path that fails is a misconfiguration worth naming;\n // without one, hint at the option so custom-named configs (e.g. a\n // `configPath` handed to @cloudflare/vite-plugin) are discoverable.\n config.logger?.warn(\n options.wranglerConfigPath\n ? `[sentry] Could not find or parse the wrangler config \"${basename(options.wranglerConfigPath)}\" ` +\n '(resolved against the Vite root) — auto-instrumentation disabled.'\n : '[sentry] No parseable wrangler config found — auto-instrumentation disabled. ' +\n 'Set `wranglerConfigPath` if your config uses a custom name.',\n );\n return;\n }\n\n wranglerConfig = result.config;\n const main = wranglerConfig.main;\n if (main && isAbsolute(main)) {\n // Normalize separators so the entry-module comparison holds on Windows.\n entryFilePath = normalizePath(main);\n instrumentFilePath = resolveInstrumentFile(dirname(main));\n } else if (main) {\n entrySpecifier = main;\n wranglerConfigPath = result.configPath;\n // Not `this.resolve()`: Rollup's commonjs resolver loads the module it resolves, so a\n // resolve of the entry from the entry's own `transform` never finishes.\n resolveId = createIdResolver(config as ResolvedConfig);\n // A package entry has no project directory of its own.\n instrumentFilePath = resolveInstrumentFile(result.configDir);\n }\n },\n\n async transform(\n this: TransformContext,\n code: string,\n id: string,\n ): Promise<{ code: string; map: unknown } | undefined> {\n if (!wranglerConfig || (!entryFilePath && !entrySpecifier)) return undefined;\n\n // The worker entry never belongs to the client (browser) environment.\n // Skipping it keeps a same-basename sibling (e.g. a `src/index.tsx`\n // client entry next to a `src/index.ts` worker) out of the browser bundle.\n if (this.environment?.name === 'client') return undefined;\n\n const entryPath = entrySpecifier ? await resolveEntrySpecifier(this, entrySpecifier) : entryFilePath;\n if (!entryPath) return undefined;\n\n // Vite may append query/hash params to the module ID.\n const normalizedId = normalizePath(id.replace(/[?#].*$/, ''));\n if (normalizedId !== entryPath) {\n // Tolerate a differing JS-flavored extension (e.g. `.js` vs `.ts`).\n if (!JS_EXTENSION_REGEX.test(normalizedId) || !JS_EXTENSION_REGEX.test(entryPath)) return undefined;\n if (normalizedId.replace(JS_EXTENSION_REGEX, '') !== entryPath.replace(JS_EXTENSION_REGEX, '')) {\n return undefined;\n }\n }\n\n let ast: ProgramBody;\n try {\n ast = this.parse(code);\n } catch {\n // Raw TypeScript or syntax error — esbuild hasn't run yet (unlikely)\n // or the file is genuinely broken. Either way, skip silently.\n return undefined;\n }\n\n const classWrappers = new Map<string, ClassWrapperKind>();\n for (const { className } of wranglerConfig.durableObjects) {\n classWrappers.set(className, 'durableObject');\n }\n for (const { className } of wranglerConfig.workflows) {\n classWrappers.set(className, 'workflow');\n }\n for (const className of wranglerConfig.workerEntrypoints) {\n classWrappers.set(className, 'workerEntrypoint');\n }\n\n // An `agents` Agent is a Durable Object, so wrangler lists it among the DO bindings and only\n // its base-class chain tells the two apart. Detection walks the module graph (base classes\n // usually live in their own file), so it is limited to the configured DO classes.\n //\n // Only `resolve` is handed over — never `load`: awaiting `load()` from inside a transform\n // hook deadlocks the build, since the module can't finish loading while this transform is\n // still pending. `agentClass` reads sibling modules off disk instead.\n const agentCandidates = collectAgentCandidates(\n ast,\n [...classWrappers].filter(([, kind]) => kind === 'durableObject').map(([name]) => name),\n );\n const agentClasses =\n agentCandidates.size > 0\n ? await detectAgentClasses(ast, normalizedId, agentCandidates, {\n parse: code => this.parse(code),\n resolve: this.resolve ? (source, importer) => this.resolve!(source, importer) : undefined,\n })\n : undefined;\n\n // A vinext app with `@sentry/nextjs` installed gets `withSentry` of `@sentry/nextjs/cloudflare`.\n const sentryModule =\n isVinext && (await resolvesNextjsCloudflare(this, normalizedId)) ? NEXTJS_CLOUDFLARE_MODULE : undefined;\n\n const { optionsFn, importStmt: optionsImport } = instrumentFilePath\n ? buildOptionsImport(entryPath, instrumentFilePath)\n : { optionsFn: ENV_FALLBACK_OPTIONS_FN, importStmt: undefined };\n\n // No registration import is injected here: the orchestrion plugin's\n // subscribe-injection makes each bundled package self-register its channel\n // subscriber on the global marker, so wrapping the entry with `withSentry`\n // is all this plugin needs to do.\n const result = applyAutoInstrumentTransforms(code, ast, {\n classWrappers,\n agentClasses,\n optionsFn,\n optionsImport,\n sameWorkerBindings: wranglerConfig.sameWorkerBindings,\n sentryModule,\n workerInfo: { name: wranglerConfig.name, compatibilityDate: wranglerConfig.compatibilityDate },\n });\n\n const wrappedClasses = result?.wrappedClasses ?? new Set<string>();\n const missing = [...classWrappers.keys()].filter(name => !wrappedClasses.has(name));\n if (missing.length > 0 && !reexportsAllFromSameFile(ast, normalizedId)) {\n this.warn?.(\n `[sentry] Could not auto-instrument ${missing.join(', ')}. ` +\n 'The worker entry has no export matching them. ' +\n 'Star re-exports (`export * from \"./do\"`) are not matched. ' +\n 'Export them by name or wrap them manually with corresponding `instrument*WithSentry` helpers.',\n );\n }\n\n return result ?? undefined;\n },\n };\n}\n"],"mappings":";;;;;;;AASA,SAAS,cAAc,MAAsB;CAC3C,OAAO,KAAK,QAAQ,OAAO,GAAG;AAChC;AAKA,MAAM,qBAAqB;AAG3B,MAAM,2BAA2B;;;;;AAMjC,eAAe,yBAAyB,UAA0B,UAAoC;CACpG,IAAI;EACF,OAAO,CAAC,CAAE,MAAM,SAAS,UAAU,0BAA0B,QAAQ;CACvE,QAAQ;EACN,OAAO;CACT;AACF;;;;;;AAOA,SAAS,yBAAyB,KAAkB,cAA+B;CACjF,OAAO,IAAI,KAAK,MAAK,SAAQ;EAC3B,IAAI,KAAK,SAAS,wBAAwB,OAAO;EACjD,MAAM,EAAE,UAAU,WAAW;EAC7B,MAAM,QAAQ,QAAQ;EACtB,OAAO,CAAC,YAAY,OAAO,UAAU,YAAY,cAAc,MAAM,QAAQ,WAAW,EAAE,CAAC,MAAM;CACnG,CAAC;AACH;AAOA,SAAgB,qCAAqC,UAA2C,CAAC,GAAG;CAClG,IAAI;CACJ,IAAI;CAEJ,IAAI;CACJ,IAAI;CACJ,IAAI;CAEJ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AM,YAAY,IAAK,2BAA2B,KAAA;GAEhG,MAAM,EAAE,WAAW,YAAY,kBAAkB,qBAC7CC,uBAAAA,mBAAmB,WAAW,kBAAkB,IAChD;IAAE,WAAWC,uBAAAA;IAAyB,YAAY,KAAA;GAAU;GAMhE,MAAM,SAASC,kBAAAA,8BAA8B,MAAM,KAAK;IACtD;IACA;IACA;IACA;IACA,oBAAoB,eAAe;IACnC;IACA,YAAY;KAAE,MAAM,eAAe;KAAM,mBAAmB,eAAe;IAAkB;GAC/F,CAAC;GAED,MAAM,iBAAiB,QAAQ,kCAAkB,IAAI,IAAY;GACjE,MAAM,UAAU,CAAC,GAAG,cAAc,KAAK,CAAC,CAAC,CAAC,QAAO,SAAQ,CAAC,eAAe,IAAI,IAAI,CAAC;GAClF,IAAI,QAAQ,SAAS,KAAK,CAAC,yBAAyB,KAAK,YAAY,GACnE,KAAK,OACH,sCAAsC,QAAQ,KAAK,IAAI,EAAE,4MAI3D;GAGF,OAAO,UAAU,KAAA;EACnB;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["sentryOrchestrionPlugin","sentryMastraObservabilityProviderPlugin","sentryCloudflareAutoInstrumentPlugin"],"sources":["../../../../src/vite/index.ts"],"sourcesContent":["// Published ESM-only via the `@sentry/cloudflare/vite` subpath export:\n// `@sentry/server-utils/orchestrion/vite` exposes no `require` condition, so a\n// CJS entry here would fail at resolution time (ERR_PACKAGE_PATH_NOT_EXPORTED).\n// The CJS rollup variant still emits this file, but `package.json` doesn't\n// expose it — same setup as `@sentry/server-utils/orchestrion/vite` itself.\nimport { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';\nimport { sentryCloudflareAutoInstrumentPlugin } from './autoInstrument';\nimport { sentryMastraObservabilityProviderPlugin } from './mastraObservability';\n\n/**\n * Options for {@link sentryCloudflareVitePlugin}.\n */\nexport interface SentryCloudflareVitePluginOptions {\n /**\n * Path to the wrangler config, relative to the Vite root (or absolute).\n * Set this when your config doesn't use a default name — e.g. when you\n * pass `configPath: './wrangler.agent.jsonc'` to `@cloudflare/vite-plugin`,\n * which the Sentry plugin cannot see. When set, only this file is read\n * (no default-name probing), and a warning is emitted if it is missing or\n * unparseable.\n *\n * @default undefined (probes `wrangler.json`, `wrangler.jsonc`, `wrangler.toml` at the Vite root)\n */\n wranglerConfigPath?: string;\n /**\n * Build-time automatic instrumentation of supported dependencies (e.g.\n * database clients like `mysql`) so the Sentry Cloudflare SDK can trace them\n * without monkey-patching, which wouldn't work in workerd anyway.\n *\n * When enabled, the plugin injects `diagnostics_channel.tracingChannel` calls\n * into the bundled packages and, next to each, a snippet that registers the\n * matching Sentry channel-subscriber factory on the global marker, which the\n * SDK picks up in `Sentry.withSentry()`. Both `vite build` and `vite dev` are\n * instrumented. Set to `false` to opt out.\n *\n * @default true\n */\n buildTimeInstrumentation?: boolean;\n /**\n * Automatically wraps your Worker at build time so you don't have to edit\n * your entry: the plugin reads your wrangler config, wraps the default\n * export with `Sentry.withSentry()` (sourcing options from a co-located\n * `instrument.*` file, falling back to env), and wraps any configured\n * Durable Object class with `instrumentDurableObjectWithSentry`. Both\n * `vite build` and `vite dev` are instrumented. Already-wrapped entries are\n * left alone, so this is safe alongside manual instrumentation. Set to\n * `false` to opt out.\n *\n * The plugin also adds the bindings that resolve to the wrapped classes (this worker's own\n * Durable Objects and self service bindings) to `rpcTracePropagationBindings`. Bindings to\n * other workers stay opt-in, their receivers may not run Sentry.\n *\n * @default true\n */\n autoInstrumentation?: boolean;\n}\n\n/**\n * Sentry Vite plugin for Cloudflare Workers.\n *\n * Add this plugin to your Vite configuration to enable additional Sentry\n * instrumentation for Cloudflare Workers built with Vite.\n *\n * By default, the plugin\n * - build-time instruments supported dependencies (such as database clients) so\n * they are traced without changing your application code — opt out with\n * `buildTimeInstrumentation: false`, and\n * - wraps your Worker entry (and any Durable Object, Workflow or\n * WorkerEntrypoint class in your wrangler config) with the matching Sentry\n * helper — opt out with `autoInstrumentation: false` and call\n * `Sentry.withSentry()` yourself.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { cloudflare } from '@cloudflare/vite-plugin';\n * import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite';\n * import { defineConfig } from 'vite';\n *\n * export default defineConfig({\n * plugins: [cloudflare(), sentryCloudflareVitePlugin()],\n * });\n * ```\n */\nexport function sentryCloudflareVitePlugin(options: SentryCloudflareVitePluginOptions = {}): Array<{ name: string }> {\n return [\n sentryOrchestrionPlugin({\n buildTimeInstrumentation: options.buildTimeInstrumentation,\n // Route the injected `tracingChannel` imports through the workerd-safe façade so a\n // dependency wrapped at module scope (`const app = new Hono()`) doesn't throw on workerd.\n dcModule: '@sentry/cloudflare/orchestrion-diagnostics-channel',\n transformOptimizedDeps: true,\n // `flueIntegration` needs Flue's own `instrument()`, which a bundled worker can't resolve.\n selfProvidedModules: ['@flue/runtime'],\n }),\n sentryMastraObservabilityProviderPlugin(),\n ...(options.autoInstrumentation !== false\n ? [sentryCloudflareAutoInstrumentPlugin({ wranglerConfigPath: options.wranglerConfigPath })]\n : []),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.js","names":["sentryOrchestrionPlugin","sentryMastraObservabilityProviderPlugin","sentryCloudflareAutoInstrumentPlugin"],"sources":["../../../../src/vite/index.ts"],"sourcesContent":["// Published ESM-only via the `@sentry/cloudflare/vite` subpath export:\n// `@sentry/server-utils/orchestrion/vite` exposes no `require` condition, so a\n// CJS entry here would fail at resolution time (ERR_PACKAGE_PATH_NOT_EXPORTED).\n// The CJS rollup variant still emits this file, but `package.json` doesn't\n// expose it — same setup as `@sentry/server-utils/orchestrion/vite` itself.\nimport { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';\nimport { sentryCloudflareAutoInstrumentPlugin } from './autoInstrument';\nimport { sentryMastraObservabilityProviderPlugin } from './mastraObservability';\n\n/**\n * Options for {@link sentryCloudflareVitePlugin}.\n */\nexport interface SentryCloudflareVitePluginOptions {\n /**\n * Path to the wrangler config, relative to the Vite root (or absolute).\n * Set this when your config doesn't use a default name — e.g. when you\n * pass `configPath: './wrangler.agent.jsonc'` to `@cloudflare/vite-plugin`,\n * which the Sentry plugin cannot see. When set, only this file is read\n * (no default-name probing), and a warning is emitted if it is missing or\n * unparseable.\n *\n * @default undefined (probes `wrangler.json`, `wrangler.jsonc`, `wrangler.toml` at the Vite root)\n */\n wranglerConfigPath?: string;\n /**\n * Build-time automatic instrumentation of supported dependencies (e.g.\n * database clients like `mysql`) so the Sentry Cloudflare SDK can trace them\n * without monkey-patching, which wouldn't work in workerd anyway.\n *\n * When enabled, the plugin injects `diagnostics_channel.tracingChannel` calls\n * into the bundled packages and, next to each, a snippet that registers the\n * matching Sentry channel-subscriber factory on the global marker, which the\n * SDK picks up in `Sentry.withSentry()`. Both `vite build` and `vite dev` are\n * instrumented. Set to `false` to opt out.\n *\n * @default true\n */\n buildTimeInstrumentation?: boolean;\n /**\n * Automatically wraps your Worker at build time so you don't have to edit\n * your entry: the plugin reads your wrangler config, wraps the default\n * export with `Sentry.withSentry()` (sourcing options from a co-located\n * `instrument.*` file, falling back to env), and wraps any configured\n * Durable Object class with `instrumentDurableObjectWithSentry`. Both\n * `vite build` and `vite dev` are instrumented. Already-wrapped entries are\n * left alone, so this is safe alongside manual instrumentation. Set to\n * `false` to opt out.\n *\n * The plugin also adds the bindings that resolve to the wrapped classes (this worker's own\n * Durable Objects and self service bindings) to `rpcTracePropagationBindings`. Bindings to\n * other workers stay opt-in, their receivers may not run Sentry.\n *\n * The plugin also sets the `name` of your wrangler config as the default `serverName` and the\n * `compatibility_date` as the runtime version, also for handlers you wrap yourself.\n *\n * @default true\n */\n autoInstrumentation?: boolean;\n}\n\n/**\n * Sentry Vite plugin for Cloudflare Workers.\n *\n * Add this plugin to your Vite configuration to enable additional Sentry\n * instrumentation for Cloudflare Workers built with Vite.\n *\n * By default, the plugin\n * - build-time instruments supported dependencies (such as database clients) so\n * they are traced without changing your application code — opt out with\n * `buildTimeInstrumentation: false`, and\n * - wraps your Worker entry (and any Durable Object, Workflow or\n * WorkerEntrypoint class in your wrangler config) with the matching Sentry\n * helper — opt out with `autoInstrumentation: false` and call\n * `Sentry.withSentry()` yourself.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { cloudflare } from '@cloudflare/vite-plugin';\n * import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite';\n * import { defineConfig } from 'vite';\n *\n * export default defineConfig({\n * plugins: [cloudflare(), sentryCloudflareVitePlugin()],\n * });\n * ```\n */\nexport function sentryCloudflareVitePlugin(options: SentryCloudflareVitePluginOptions = {}): Array<{ name: string }> {\n return [\n sentryOrchestrionPlugin({\n buildTimeInstrumentation: options.buildTimeInstrumentation,\n // Route the injected `tracingChannel` imports through the workerd-safe façade so a\n // dependency wrapped at module scope (`const app = new Hono()`) doesn't throw on workerd.\n dcModule: '@sentry/cloudflare/orchestrion-diagnostics-channel',\n transformOptimizedDeps: true,\n // `flueIntegration` needs Flue's own `instrument()`, which a bundled worker can't resolve.\n selfProvidedModules: ['@flue/runtime'],\n }),\n sentryMastraObservabilityProviderPlugin(),\n ...(options.autoInstrumentation !== false\n ? [sentryCloudflareAutoInstrumentPlugin({ wranglerConfigPath: options.wranglerConfigPath })]\n : []),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuFA,SAAgB,2BAA2B,UAA6C,CAAC,GAA4B;CACnH,OAAO;GACLA,GAAAA,sCAAAA,wBAAAA,CAAwB;GACtB,0BAA0B,QAAQ;GAGlC,UAAU;GACV,wBAAwB;GAExB,qBAAqB,CAAC,eAAe;EACvC,CAAC;EACDC,4BAAAA,wCAAwC;EACxC,GAAI,QAAQ,wBAAwB,QAChC,CAACC,uBAAAA,qCAAqC,EAAE,oBAAoB,QAAQ,mBAAmB,CAAC,CAAC,IACzF,CAAC;CACP;AACF"}
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
const require_runtime = require("../_virtual/_rolldown/runtime.js");
|
|
2
2
|
const require_wranglerConfig = require("./wranglerConfig.js");
|
|
3
3
|
const require_workerEntrypoint = require("./workerEntrypoint.js");
|
|
4
|
+
let _sentry_core = require("@sentry/core");
|
|
4
5
|
let magic_string = require("magic-string");
|
|
5
6
|
magic_string = require_runtime.__toESM(magic_string);
|
|
6
7
|
// src/vite/transform.ts
|
|
7
8
|
const MERGED_OPTIONS_IDENTIFIER = "__SENTRY_OPTIONS__";
|
|
9
|
+
const WORKER_INFO_GLOBAL = "__SENTRY_CLOUDFLARE_WORKER__";
|
|
8
10
|
function isCallToMethod(node, methodName) {
|
|
9
11
|
if (node.type !== "CallExpression") return false;
|
|
10
12
|
const callee = node.callee;
|
|
@@ -39,8 +41,9 @@ const WRAPPER_METHODS = {
|
|
|
39
41
|
* {@link TransformResult.wrappedClasses}.
|
|
40
42
|
*
|
|
41
43
|
* Exported (rather than inlined into the plugin) so it can be unit-tested with a
|
|
42
|
-
* plain AST and no Vite context. Returns `undefined` when nothing was wrapped
|
|
43
|
-
* there are no already-manually-wrapped classes to report
|
|
44
|
+
* plain AST and no Vite context. Returns `undefined` when nothing was wrapped,
|
|
45
|
+
* there are no already-manually-wrapped classes to report, and there is no
|
|
46
|
+
* {@link TransformContext.workerInfo} to store.
|
|
44
47
|
*/
|
|
45
48
|
function applyAutoInstrumentTransforms(code, ast, ctx) {
|
|
46
49
|
const ms = new magic_string.default(code);
|
|
@@ -63,17 +66,13 @@ function applyAutoInstrumentTransforms(code, ast, ctx) {
|
|
|
63
66
|
const { wrappedClasses } = state;
|
|
64
67
|
for (const node of ast.body) if (node.type === "ExportNamedDeclaration") handleNamedExport(node, ctx, state);
|
|
65
68
|
for (const node of ast.body) if (node.type === "ExportDefaultDeclaration") wrapDefaultExport(node, ctx, state);
|
|
66
|
-
if (
|
|
67
|
-
if (
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
map: ms.generateMap({ hires: true }),
|
|
71
|
-
wrappedClasses
|
|
72
|
-
};
|
|
69
|
+
if (state.needsImport) {
|
|
70
|
+
if (sameWorkerBindings.length > 0) ms.prepend(buildMergedOptionsDeclaration(sameWorkerBindings, ctx.optionsFn, state));
|
|
71
|
+
if (ctx.optionsImport) ms.prepend(ctx.optionsImport);
|
|
72
|
+
ms.prepend(`import * as __SENTRY__ from '${ctx.sentryModule ?? "@sentry/cloudflare"}';\n`);
|
|
73
73
|
}
|
|
74
|
-
if (
|
|
75
|
-
if (
|
|
76
|
-
ms.prepend(`import * as __SENTRY__ from '${ctx.sentryModule ?? "@sentry/cloudflare"}';\n`);
|
|
74
|
+
if (ctx.workerInfo?.name || ctx.workerInfo?.compatibilityDate) ms.prepend(`globalThis.${WORKER_INFO_GLOBAL} = ${JSON.stringify(ctx.workerInfo)};\n`);
|
|
75
|
+
else if (!state.needsImport && wrappedClasses.size === 0) return;
|
|
77
76
|
return {
|
|
78
77
|
code: ms.toString(),
|
|
79
78
|
map: ms.generateMap({ hires: true }),
|
|
@@ -88,7 +87,7 @@ function applyAutoInstrumentTransforms(code, ast, ctx) {
|
|
|
88
87
|
function buildMergedOptionsDeclaration(sameWorkerBindings, optionsFn, state) {
|
|
89
88
|
const bindingNames = sameWorkerBindings.filter(({ className }) => state.autoWrapped.has(className)).map(({ bindingName }) => bindingName);
|
|
90
89
|
if (!bindingNames.length) return `const ${MERGED_OPTIONS_IDENTIFIER} = ${optionsFn};\n`;
|
|
91
|
-
const names = bindingNames.map((name) =>
|
|
90
|
+
const names = bindingNames.map((name) => (0, _sentry_core.stringifyForCodeInjection)(name)).join(", ");
|
|
92
91
|
return `const ${MERGED_OPTIONS_IDENTIFIER} = (env) => { const opts = (${optionsFn})(env); return { ...opts, rpcTracePropagationBindings: [${names}, ...(opts?.rpcTracePropagationBindings ?? [])] }; };\n`;
|
|
93
92
|
}
|
|
94
93
|
/**
|