@sentry/cloudflare 11.13.0 → 11.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cjs/dev/baseSdk.js.map +1 -1
- package/build/cjs/dev/client.js +17 -2
- 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/orchestrion-deferred-channels.js +6 -2
- package/build/cjs/dev/orchestrion-deferred-channels.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 +17 -2
- 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/orchestrion-deferred-channels.js +6 -2
- package/build/cjs/prod/orchestrion-deferred-channels.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 +18 -3
- 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/orchestrion-deferred-channels.js +7 -3
- package/build/esm/dev/orchestrion-deferred-channels.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 +18 -3
- 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/orchestrion-deferred-channels.js +7 -3
- package/build/esm/prod/orchestrion-deferred-channels.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 +8 -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/orchestrion-deferred-channels.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":"wranglerConfig.js","names":["resolve","existsSync","unstable_readConfig","dirname"],"sources":["../../../../src/vite/wranglerConfig.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport { type Unstable_Config, unstable_readConfig } from 'wrangler';\n\n/**\n * The slice of the wrangler configuration the auto-instrument plugin cares\n * about.\n */\nexport interface WranglerConfig {\n /**\n * An absolute path when `main` names a JS or TS file, otherwise the\n * original value (a package export or virtual module) for Vite to resolve.\n */\n main?: string;\n durableObjects: Array<{ name: string; className: string }>;\n workflows: Array<{ name: string; className: string }>;\n /**\n * Named `WorkerEntrypoint` exports this worker binds to itself via a service\n * binding (`services[]` whose `service` is this worker's own `name`). Only\n * self-bindings appear here: a service binding's `entrypoint` otherwise names\n * an export on a *different* worker, which this build can't wrap.\n */\n workerEntrypoints: string[];\n /**\n * Bindings whose RPC receiver lives in this worker, so this build instruments it. Not deduped by\n * class, two bindings may point at the same class and both names have to be listed.\n */\n sameWorkerBindings: SameWorkerBinding[];\n}\n\n// Same rule as `@cloudflare/vite-plugin`: only these extensions mark `main` as a file path.\nconst ENTRY_FILE_REGEX = /\\.(?:m?[jt]s|[jt]sx)$/;\n\n/** Stands in for a class name where a binding targets the module's default export. */\nexport const DEFAULT_EXPORT = Symbol('defaultExport');\n\n/** The name a binding or an export is known by, either an exported class name or the default export. */\nexport type ExportName = string | typeof DEFAULT_EXPORT;\n\nexport interface SameWorkerBinding {\n bindingName: string;\n className: ExportName;\n}\n\n/**\n * Locate and resolve the wrangler configuration via wrangler's own\n * `unstable_readConfig` — the API `@cloudflare/vite-plugin` uses.\n *\n * We only locate the file (probing `wrangler.json`, `.jsonc`, `.toml` inside\n * `root` with wrangler's own precedence, since it discovers from `cwd` rather\n * than an arbitrary root); wrangler then parses it and flattens the active\n * environment (honoring `CLOUDFLARE_ENV`). Durable Object and Workflow\n * bindings are the active environment's, matching what the deployed Worker\n * actually binds.\n *\n * Returns `undefined` when no config file is found or it can't be read/parsed\n * (the caller warns and disables auto-instrumentation rather than failing the\n * whole build).\n */\nexport function resolveWranglerConfig(\n root: string,\n explicitPath?: string,\n): { config: WranglerConfig; configPath: string; configDir: string } | undefined {\n const configPath = explicitPath\n ? resolve(root, explicitPath)\n : ['wrangler.json', 'wrangler.jsonc', 'wrangler.toml'].map(name => resolve(root, name)).find(existsSync);\n\n if (!configPath || !existsSync(configPath)) {\n return undefined;\n }\n\n let raw: Unstable_Config;\n try {\n // `hideWarnings` keeps wrangler's config diagnostics (e.g. missing DO\n // migrations) out of the Vite build output.\n raw = unstable_readConfig({ config: configPath }, { hideWarnings: true, preserveOriginalMain: true });\n } catch {\n return undefined;\n }\n\n const resolvedConfigPath = raw.configPath ?? configPath;\n const configDir = dirname(resolvedConfigPath);\n\n return {\n config: {\n main: raw.main && ENTRY_FILE_REGEX.test(raw.main) ? resolve(configDir, raw.main) : raw.main,\n durableObjects: collectClassBindings(raw.durable_objects?.bindings),\n workflows: collectClassBindings(raw.workflows),\n workerEntrypoints: collectSelfBoundEntrypoints(raw),\n sameWorkerBindings: collectSameWorkerBindings(raw),\n },\n configPath: resolvedConfigPath,\n configDir,\n };\n}\n\n/**\n * Collect named `WorkerEntrypoint` exports the worker binds to itself. A service\n * binding's `entrypoint` normally names an export on the *target* worker, so it\n * is only ours when `service` equals this worker's own `name`. Without a `name`\n * there is nothing to match against, so no entrypoints are derivable.\n */\nfunction collectSelfBoundEntrypoints(raw: Unstable_Config): string[] {\n if (!raw.name) {\n return [];\n }\n const entrypoints = new Set<string>();\n for (const binding of raw.services ?? []) {\n if (binding?.service === raw.name && typeof binding.entrypoint === 'string') {\n entrypoints.add(binding.entrypoint);\n }\n }\n return [...entrypoints];\n}\n\n/**\n * Bindings with a `script_name` or naming another worker target a class this build does not wrap,\n * so they are excluded and stay opt-in.\n */\nfunction collectSameWorkerBindings(raw: Unstable_Config): SameWorkerBinding[] {\n const bindings: SameWorkerBinding[] = [];\n\n for (const binding of raw.durable_objects?.bindings ?? []) {\n if (typeof binding?.name === 'string' && typeof binding.class_name === 'string' && !binding.script_name) {\n bindings.push({ bindingName: binding.name, className: binding.class_name });\n }\n }\n\n for (const binding of raw.services ?? []) {\n // A service binding is only ours when `service` names this worker; without a `name` none can be.\n if (raw.name && binding?.service === raw.name && typeof binding.binding === 'string') {\n bindings.push({\n bindingName: binding.binding,\n className: typeof binding.entrypoint === 'string' ? binding.entrypoint : DEFAULT_EXPORT,\n });\n }\n }\n\n return bindings;\n}\n\n/**\n * Map wrangler class bindings (Durable Objects, Workflows — same shape) to the\n * `{ name, className }` the transform needs, skipping duplicates and bindings\n * with a `script_name` (those reference a class exported by a *different*\n * worker, so there is nothing to wrap in this worker's entry file).\n */\nfunction collectClassBindings(\n bindings: ReadonlyArray<{ name: string; class_name?: string; script_name?: string }> | undefined,\n): Array<{ name: string; className: string }> {\n const result: Array<{ name: string; className: string }> = [];\n const seenClassNames = new Set<string>();\n for (const binding of bindings ?? []) {\n if (typeof binding?.class_name !== 'string' || binding.script_name || seenClassNames.has(binding.class_name)) {\n continue;\n }\n seenClassNames.add(binding.class_name);\n result.push({ name: binding.name, className: binding.class_name });\n }\n return result;\n}\n"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"wranglerConfig.js","names":["resolve","existsSync","unstable_readConfig","dirname"],"sources":["../../../../src/vite/wranglerConfig.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport { type Unstable_Config, unstable_readConfig } from 'wrangler';\n\n/**\n * The slice of the wrangler configuration the auto-instrument plugin cares\n * about.\n */\nexport interface WranglerConfig {\n /**\n * The name of the deployed Worker, `<name>-<environment>` for a wrangler environment.\n */\n name?: string;\n /**\n * The `compatibility_date` that selects the workerd behavior of the Worker.\n */\n compatibilityDate?: string;\n /**\n * An absolute path when `main` names a JS or TS file, otherwise the\n * original value (a package export or virtual module) for Vite to resolve.\n */\n main?: string;\n durableObjects: Array<{ name: string; className: string }>;\n workflows: Array<{ name: string; className: string }>;\n /**\n * Named `WorkerEntrypoint` exports this worker binds to itself via a service\n * binding (`services[]` whose `service` is this worker's own `name`). Only\n * self-bindings appear here: a service binding's `entrypoint` otherwise names\n * an export on a *different* worker, which this build can't wrap.\n */\n workerEntrypoints: string[];\n /**\n * Bindings whose RPC receiver lives in this worker, so this build instruments it. Not deduped by\n * class, two bindings may point at the same class and both names have to be listed.\n */\n sameWorkerBindings: SameWorkerBinding[];\n}\n\n// Same rule as `@cloudflare/vite-plugin`: only these extensions mark `main` as a file path.\nconst ENTRY_FILE_REGEX = /\\.(?:m?[jt]s|[jt]sx)$/;\n\n/** Stands in for a class name where a binding targets the module's default export. */\nexport const DEFAULT_EXPORT = Symbol('defaultExport');\n\n/** The name a binding or an export is known by, either an exported class name or the default export. */\nexport type ExportName = string | typeof DEFAULT_EXPORT;\n\nexport interface SameWorkerBinding {\n bindingName: string;\n className: ExportName;\n}\n\n/**\n * Locate and resolve the wrangler configuration via wrangler's own\n * `unstable_readConfig` — the API `@cloudflare/vite-plugin` uses.\n *\n * We only locate the file (probing `wrangler.json`, `.jsonc`, `.toml` inside\n * `root` with wrangler's own precedence, since it discovers from `cwd` rather\n * than an arbitrary root); wrangler then parses it and flattens the active\n * environment (honoring `CLOUDFLARE_ENV`). Durable Object and Workflow\n * bindings are the active environment's, matching what the deployed Worker\n * actually binds.\n *\n * Returns `undefined` when no config file is found or it can't be read/parsed\n * (the caller warns and disables auto-instrumentation rather than failing the\n * whole build).\n */\nexport function resolveWranglerConfig(\n root: string,\n explicitPath?: string,\n): { config: WranglerConfig; configPath: string; configDir: string } | undefined {\n const configPath = explicitPath\n ? resolve(root, explicitPath)\n : ['wrangler.json', 'wrangler.jsonc', 'wrangler.toml'].map(name => resolve(root, name)).find(existsSync);\n\n if (!configPath || !existsSync(configPath)) {\n return undefined;\n }\n\n let raw: Unstable_Config;\n try {\n // `hideWarnings` keeps wrangler's config diagnostics (e.g. missing DO\n // migrations) out of the Vite build output.\n raw = unstable_readConfig({ config: configPath }, { hideWarnings: true, preserveOriginalMain: true });\n } catch {\n return undefined;\n }\n\n const resolvedConfigPath = raw.configPath ?? configPath;\n const configDir = dirname(resolvedConfigPath);\n\n return {\n config: {\n name: raw.name,\n compatibilityDate: raw.compatibility_date,\n main: raw.main && ENTRY_FILE_REGEX.test(raw.main) ? resolve(configDir, raw.main) : raw.main,\n durableObjects: collectClassBindings(raw.durable_objects?.bindings),\n workflows: collectClassBindings(raw.workflows),\n workerEntrypoints: collectSelfBoundEntrypoints(raw),\n sameWorkerBindings: collectSameWorkerBindings(raw),\n },\n configPath: resolvedConfigPath,\n configDir,\n };\n}\n\n/**\n * Collect named `WorkerEntrypoint` exports the worker binds to itself. A service\n * binding's `entrypoint` normally names an export on the *target* worker, so it\n * is only ours when `service` equals this worker's own `name`. Without a `name`\n * there is nothing to match against, so no entrypoints are derivable.\n */\nfunction collectSelfBoundEntrypoints(raw: Unstable_Config): string[] {\n if (!raw.name) {\n return [];\n }\n const entrypoints = new Set<string>();\n for (const binding of raw.services ?? []) {\n if (binding?.service === raw.name && typeof binding.entrypoint === 'string') {\n entrypoints.add(binding.entrypoint);\n }\n }\n return [...entrypoints];\n}\n\n/**\n * Bindings with a `script_name` or naming another worker target a class this build does not wrap,\n * so they are excluded and stay opt-in.\n */\nfunction collectSameWorkerBindings(raw: Unstable_Config): SameWorkerBinding[] {\n const bindings: SameWorkerBinding[] = [];\n\n for (const binding of raw.durable_objects?.bindings ?? []) {\n if (typeof binding?.name === 'string' && typeof binding.class_name === 'string' && !binding.script_name) {\n bindings.push({ bindingName: binding.name, className: binding.class_name });\n }\n }\n\n for (const binding of raw.services ?? []) {\n // A service binding is only ours when `service` names this worker; without a `name` none can be.\n if (raw.name && binding?.service === raw.name && typeof binding.binding === 'string') {\n bindings.push({\n bindingName: binding.binding,\n className: typeof binding.entrypoint === 'string' ? binding.entrypoint : DEFAULT_EXPORT,\n });\n }\n }\n\n return bindings;\n}\n\n/**\n * Map wrangler class bindings (Durable Objects, Workflows — same shape) to the\n * `{ name, className }` the transform needs, skipping duplicates and bindings\n * with a `script_name` (those reference a class exported by a *different*\n * worker, so there is nothing to wrap in this worker's entry file).\n */\nfunction collectClassBindings(\n bindings: ReadonlyArray<{ name: string; class_name?: string; script_name?: string }> | undefined,\n): Array<{ name: string; className: string }> {\n const result: Array<{ name: string; className: string }> = [];\n const seenClassNames = new Set<string>();\n for (const binding of bindings ?? []) {\n if (typeof binding?.class_name !== 'string' || binding.script_name || seenClassNames.has(binding.class_name)) {\n continue;\n }\n seenClassNames.add(binding.class_name);\n result.push({ name: binding.name, className: binding.class_name });\n }\n return result;\n}\n"],"mappings":";;;;AAuCA,MAAM,mBAAmB;;AAGzB,MAAa,iBAAiB,OAAO,eAAe;;;;;;;;;;;;;;;;AAyBpD,SAAgB,sBACd,MACA,cAC+E;CAC/E,MAAM,aAAa,gBAAA,GACfA,UAAAA,QAAAA,CAAQ,MAAM,YAAY,IAC1B;EAAC;EAAiB;EAAkB;CAAe,CAAC,CAAC,KAAI,UAAA,GAAQA,UAAAA,QAAAA,CAAQ,MAAM,IAAI,CAAC,CAAC,CAAC,KAAKC,QAAAA,UAAU;CAEzG,IAAI,CAAC,cAAc,EAAA,GAACA,QAAAA,WAAAA,CAAW,UAAU,GACvC;CAGF,IAAI;CACJ,IAAI;EAGF,OAAA,GAAMC,SAAAA,oBAAAA,CAAoB,EAAE,QAAQ,WAAW,GAAG;GAAE,cAAc;GAAM,sBAAsB;EAAK,CAAC;CACtG,QAAQ;EACN;CACF;CAEA,MAAM,qBAAqB,IAAI,cAAc;CAC7C,MAAM,aAAA,GAAYC,UAAAA,QAAAA,CAAQ,kBAAkB;CAE5C,OAAO;EACL,QAAQ;GACN,MAAM,IAAI;GACV,mBAAmB,IAAI;GACvB,MAAM,IAAI,QAAQ,iBAAiB,KAAK,IAAI,IAAI,KAAA,GAAIH,UAAAA,QAAAA,CAAQ,WAAW,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AAQ;GAAM,WAAW,QAAQ;EAAW,CAAC;CACnE;CACA,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"baseSdk.js","names":[],"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 }) => 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,aAAa,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,CAAC,kBAAkB,CAAC;EAC9D,wBAAwB;EACxB,4BAA4B;EAC5B,0BAA0B;EAC1B,wBAAwB;EACxB,iBAAiB;EACjB,sBAAsB;EACtB,uBAAuB;EACvB,mBAAmB;EAOnB,GAAG,iCAAiC;CACtC;AACF;;;;;;;;;;;;;;;AAgBA,SAAgB,YAAY,SAA0D;CACpF,MAAM,SAAS,gBAAgB;CAC/B,MAAM,eAAe,QAAQ,gBAAgB;CAI7C,IAAI,gBAAgB,UAAU,CAAC,yBAAyB,MAAM,GAAG;EAC/D,IAAI,eAAe,OAAO,WAAW,CAAC,CAAC,QAAQ,QAAQ,KACrD,MAAM,KACJ,gLACF;EAEF,gBAAgB,CAAC,CAAC,OAAO,QAAQ,YAAY;EAC7C,iBAAiB,MAAM;EACvB,OAAO;CACT;CAIA,MAAM,kBAAkB,QAAQ,wBAAwB,KAAA,KAAa,CAAC,CAAC,QAAQ;CAC/E,IAAI,QAAQ,wBAAwB,KAAA,GAClC,QAAQ,sBAAsB,uBAAuB,OAAO;CAM9D,MAAM,oBAAoB,QAAQ;CAClC,MAAM,YAAY,CAAC,gBAAgB,oBAAoB,cAAc,iBAAiB,IAAI,KAAA;CAC1F,OAAO,QAAQ;CAEf,MAAM,gBAAyC;EAC7C,GAAG;EACH,aAAa;EACb,aAAa,kCAAkC,QAAQ,eAAe,kBAAkB;EACxF,cAAc,uBAAuB,OAAO;EAC5C,WAAW,QAAQ,aAAa;EAChC;CACF;;CAGA,IAAI,QAAQ,aAAa,CAAC,cAAc,aAAa,MAAM,EAAE,WAAW,SAAA,WAAmC,GACzG,cAAc,aAAa,KACzB,qBAAqB,EACnB,YAAY,OAAO,QAAQ,cAAc,WAAW,QAAQ,YAAY,KAAA,EAC1E,CAAC,CACH;;CAIF,IAAI,CAAC,cAGH,gBAAgB,CAAC,CAAC,UAAU,KAAA,CAAS;CAGvC,MAAM,SAAS,YAAY,kBAAkB,aAAa;CAE1D,IAAI,gBAAgB,QAClB,YAAY,MAAM;CAUpB,MAAM,mBAAmB,QAAQ;CACjC,OAAO,GAAG,gCAA+B,eAAc;EACrD,MAAM,UAAU,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,OAAO,aACX,cAAc,8EAA8E,UAE1F,uBAAuB;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"}
|
|
1
|
+
{"version":3,"file":"baseSdk.js","names":[],"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,aAAa,WAAW,wBAAwB;CAEtD,OAAO,aAAa,CAAC,GAAG,WAAW,OA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E,CAAC,CACH;;CAIF,IAAI,CAAC,cAGH,gBAAgB,CAAC,CAAC,UAAU,KAAA,CAAS;CAGvC,MAAM,SAAS,YAAY,kBAAkB,aAAa;CAE1D,IAAI,gBAAgB,QAClB,YAAY,MAAM;CAUpB,MAAM,mBAAmB,QAAQ;CACjC,OAAO,GAAG,gCAA+B,eAAc;EACrD,MAAM,UAAU,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,OAAO,aACX,cAAc,8EAA8E,UAE1F,uBAAuB;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/esm/dev/client.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { DEBUG_BUILD } from "./debug-build.js";
|
|
2
2
|
import { getInvocationState, getInvocationWaitUntil } from "./utils/invocationContext.js";
|
|
3
|
-
import { _INTERNAL_clearAiProviderSkips, _INTERNAL_flushLogsBuffer, _INTERNAL_flushMetricsBuffer, applySdkMetadata, debug, spanIsSampled, spanStreamingIntegration } from "@sentry/core";
|
|
3
|
+
import { GLOBAL_OBJ, _INTERNAL_clearAiProviderSkips, _INTERNAL_flushLogsBuffer, _INTERNAL_flushMetricsBuffer, applySdkMetadata, debug, spanIsSampled, spanStreamingIntegration } from "@sentry/core";
|
|
4
4
|
import { ServerRuntimeClient } from "@sentry/core/server";
|
|
5
5
|
// src/client.ts
|
|
6
6
|
const SPAN_STREAMING_INTEGRATION_NAME = "SpanStreaming";
|
|
@@ -19,10 +19,15 @@ var CloudflareClient = class extends ServerRuntimeClient {
|
|
|
19
19
|
applySdkMetadata(options, "cloudflare");
|
|
20
20
|
options._metadata = options._metadata || {};
|
|
21
21
|
const { flushLock, ...serverOptions } = options;
|
|
22
|
+
const workerInfo = 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(spanStreamingIntegration({ flushOnSegmentEnd: false }));
|
|
@@ -33,6 +38,7 @@ var CloudflareClient = class extends ServerRuntimeClient {
|
|
|
33
38
|
this._unsubscribeSpanStart = null;
|
|
34
39
|
this._unsubscribeSpanEnd = null;
|
|
35
40
|
this._inBoundaryFlush = false;
|
|
41
|
+
this._envelopeDuringBoundaryFlush = false;
|
|
36
42
|
this._pendingEagerDrains = /* @__PURE__ */ new Set();
|
|
37
43
|
this._flushLock = flushLock;
|
|
38
44
|
this.isCachedClient = options.cacheClient === true;
|
|
@@ -90,6 +96,11 @@ var CloudflareClient = class extends ServerRuntimeClient {
|
|
|
90
96
|
} finally {
|
|
91
97
|
this._inBoundaryFlush = false;
|
|
92
98
|
}
|
|
99
|
+
if (this._envelopeDuringBoundaryFlush) {
|
|
100
|
+
this._envelopeDuringBoundaryFlush = false;
|
|
101
|
+
const transport = this.getTransport();
|
|
102
|
+
if (transport) this._registerWithInvocationWaitUntil(transport.flush(timeout ?? 2e3));
|
|
103
|
+
}
|
|
93
104
|
await Promise.all(this._pendingEagerDrains);
|
|
94
105
|
return flushed;
|
|
95
106
|
}
|
|
@@ -160,7 +171,11 @@ var CloudflareClient = class extends ServerRuntimeClient {
|
|
|
160
171
|
this.on("afterEnvelope", () => {
|
|
161
172
|
const transport = this.getTransport();
|
|
162
173
|
const invocationState = getInvocationState();
|
|
163
|
-
if (!transport ||
|
|
174
|
+
if (!transport || invocationState && !invocationState.flushPointReached) return;
|
|
175
|
+
if (this._inBoundaryFlush) {
|
|
176
|
+
this._envelopeDuringBoundaryFlush = true;
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
164
179
|
this._registerWithInvocationWaitUntil(transport.flush(2e3));
|
|
165
180
|
});
|
|
166
181
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":[],"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,cAAsC,oBAAoB;;;;;CA4BjD,YAAY,SAAkC;EACnD,iBAAiB,SAAS,YAAY;EACtC,QAAQ,YAAY,QAAQ,aAAa,CAAC;EAC1C,MAAM,EAAE,WAAW,GAAG,kBAAkB;EAExC,MAAM,gB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OAAO;EACnB,QAAQ,CAER;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"client.js","names":[],"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 // Set when an envelope that needs eager delivery is accepted during a boundary flush. The\n // flush's transport drain takes its batch when it starts, so such an envelope can miss it.\n private _envelopeDuringBoundaryFlush = 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 if (this._envelopeDuringBoundaryFlush) {\n this._envelopeDuringBoundaryFlush = false;\n const transport = this.getTransport();\n if (transport) {\n this._registerWithInvocationWaitUntil(transport.flush(timeout ?? 2000));\n }\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 || (invocationState && !invocationState.flushPointReached)) {\n return;\n }\n\n if (this._inBoundaryFlush) {\n this._envelopeDuringBoundaryFlush = true;\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,cAAsC,oBAAoB;;;;;CAgCjD,YAAY,SAAkC;EACnD,iBAAiB,SAAS,YAAY;EACtC,QAAQ,YAAY,QAAQ,aAAa,CAAC;EAC1C,MAAM,EAAE,WAAW,GAAG,kBAAkB;EACxC,MAAM,aAAc,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,KAAK,yBAAyB,EAAE,mBAAmB,MAAM,CAAC,CAAC;EAGxF,MAAM,aAAa;EAzDrB,KAAQ,gCAA6B,IAAI,IAAI;EAC7C,KAAQ,yBAA+C;EACvD,KAAQ,yBAA8C;EAEtD,KAAQ,wBAA6C;EACrD,KAAQ,sBAA2C;EAInD,KAAQ,mBAAmB;EAI3B,KAAQ,+BAA+B;EAIvC,KAAiB,sCAAsB,IAAI,IAAmB;EAyC5D,KAAK,aAAa;EAElB,KAAK,iBAAiB,QAAQ,gBAAgB;EAO9C,IAAI,CAAC,KAAK,gBAAgB;GACxB,KAAK,wBAAwB,KAAK,GAAG,cAAa,SAAQ;IACxD,MAAM,SAAS,KA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;GAEA,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,kBAAkB,0BAA0B,IAAI,CAAC,CAAC;EACxF,KAAK,GAAG,4BAA4B,KAAK,kBAAkB,6BAA6B,IAAI,CAAC,CAAC;CAChG;;;;;CAMQ,YAAY,OAAyB;EAC3C,MAAM,kBAAkB,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,kBAAkB,mBAAmB;EAC3C,MAAM,YAAY,mBAAmB,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":[],"sources":["../../../src/durableobject.ts"],"sourcesContent":["/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/unbound-method */\nimport { RPC } from '@sentry/conventions/op';\nimport { getDefaultIsolationScope, getIsolationScope, isObjectLike, startNewTrace } from '@sentry/core';\nimport type { DurableObject } from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategyForWorker } from './utils/asyncContextStrategy';\nimport type { CloudflareOptions } from './client';\nimport { getInstrumented, markAsInstrumented } from './instrument';\nimport { instrumentDurableObjectHandlers } from './instrumentations/instrumentDurableObjectHandlers';\nimport { instrumentEnv } from './instrumentations/worker/instrumentEnv';\nimport { getFinalOptions } from './options';\nimport { flushDeferredChannelEvents } from './orchestrion-deferred-channels';\nimport { init } from './sdk';\nimport { instrumentContext } from './utils/instrumentContext';\nimport { withConstructionIsolationScope } from './utils/invocationScope';\nimport { hasRpcMeta } from './utils/rpcMeta';\nimport { instrumentCloudflareAgent } from './instrumentations/agents';\nimport type { DefaultEnv, ResolveEnv, StrictCloudflareOptions } from './types';\nimport { type UncheckedMethod, wrapMethodWithSentry } from './wrapMethodWithSentry';\n\n/**\n * The instrumented context passed between the shared construction helpers.\n *\n * This is intentionally `any` rather than `ReturnType<typeof instrumentContext<DurableObjectState>>`.\n * A concrete `DurableObjectState` here forces `tsc` to structurally relate its `storage: SqlStorage`\n * graph against the `ExecutionContext | InstrumentedDurableObjectState` parameter of\n * `wrapMethodWithSentry`, while the RPC-branded `DurableObject` from `cloudflare:workers` is also in\n * scope. That union comparison explodes (1296×1296) and hangs the type build. The original inline\n * implementation avoided this only incidentally, because `ctx` reached it as `any` through the Proxy\n * `construct` trap. Keeping the shared context `any` preserves that behavior.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InstrumentedDurableObjectContext = any;\n\n/**\n * Constructs a Durable Object instance and instruments its built-in handler methods\n * (`fetch`, `alarm`, `webSocketMessage`, `webSocketClose`, `webSocketError`).\n *\n * This is the shared construction path used by both {@link instrumentDurableObjectWithSentry}\n * and {@link instrumentAgentWithSentry}. It intentionally does NOT apply the RPC prototype-method\n * instrumentation — callers apply that last via {@link finalizeWithRpcInstrumentation}, after any\n * additional per-instance instrumentation has been layered onto the returned object.\n *\n * @internal\n */\nexport function constructInstrumentedDurableObject<E, T extends DurableObject<E>>(\n target: new (state: DurableObjectState, env: E) => T,\n ctx: DurableObjectState,\n env: E,\n newTarget: NewableFunction,\n optionsCallback: (env: E) => CloudflareOptions,\n): {\n obj: T;\n options: CloudflareOptions;\n context: InstrumentedDurableObjectContext;\n frameworkManagedMethods: ReadonlySet<string>;\n} {\n setAsyncLocalStorageAsyncContextStrategyForWorker();\n const options = getFinalOptions(optionsCallback(env), env);\n // See InstrumentedDurableObjectContext — `ctx` is widened to `any` so the concrete\n // `DurableObjectState` type never enters the checker's relation graph in this module.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const context = instrumentContext(ctx as any);\n const instrumentedEnv = instrumentEnv(env as Record<string, unknown>, options);\n\n const prototype = (newTarget as unknown as { prototype?: object }).prototype ?? target.prototype;\n const cachedFrameworkManagedMethods = frameworkManagedMethodsCache.get(prototype);\n const methodsBeforeConstruction = cachedFrameworkManagedMethods\n ? undefined\n : resolveMethodsBeforeFirstConstruction(prototype);\n\n // Pass `newTarget` so that subclasses of the instrumented class (e.g. the wrapper classes\n // created by wrangler's local dev tooling or `@cloudflare/vitest-pool-workers`) keep their\n // own prototype — otherwise subclass methods disappear and `instanceof` checks break.\n const obj = withConstructionIsolationScope(() => {\n // The constructor can already use instrumented libraries, e.g. open a pi-durable Harness in\n // `blockConcurrencyWhile`. Their channel integrations only subscribe in `init()`, and an isolate\n // that runs only this Durable Object has no earlier handler that called it. A per-invocation\n // client (`cacheClient: false`) would have no invocation to flush it, so it waits for one.\n if (options.cacheClient !== false) {\n init({ ...options });\n flushDeferredChannelEvents();\n }\n return Reflect.construct(target, [context, instrumentedEnv], newTarget) as T;\n });\n\n const frameworkManagedMethods = resolveFrameworkManagedMethods(\n prototype,\n obj,\n methodsBeforeConstruction,\n cachedFrameworkManagedMethods,\n );\n\n instrumentDurableObjectHandlers(obj, options, context);\n\n return { obj, options, context, frameworkManagedMethods };\n}\n\nconst frameworkManagedMethodsCache = new WeakMap<object, ReadonlySet<string>>();\nconst methodsBeforeFirstConstructionCache = new WeakMap<object, Map<string, unknown>>();\n\n/**\n * Collects the prototype's methods as they were before any instance was constructed.\n *\n * A constructor can throw after a framework has already installed its wrappers (the `agents` SDK\n * wraps `@callable()` methods before storage initialization, which can fail). The next construction\n * would then see those wrappers as the originals and treat the methods as unmanaged, so the methods\n * collected on the first attempt are kept until a construction succeeds.\n */\nfunction resolveMethodsBeforeFirstConstruction(prototype: object): Map<string, unknown> {\n let methods = methodsBeforeFirstConstructionCache.get(prototype);\n\n if (!methods) {\n methods = resolvePrototypeMethods(prototype);\n methodsBeforeFirstConstructionCache.set(prototype, methods);\n }\n\n return methods;\n}\n\n/**\n * Collects the methods visible from a prototype, using normal property lookup precedence.\n * Methods inherited from `Object.prototype` are excluded because they cannot be Durable Object RPC methods.\n */\nfunction resolvePrototypeMethods(prototype: object | null): Map<string, unknown> {\n const methods = new Map<string, unknown>();\n\n for (let current = prototype; current && current !== Object.prototype; current = Object.getPrototypeOf(current)) {\n for (const name of Object.getOwnPropertyNames(current)) {\n // The first occurrence wins, mirroring what a property lookup on the instance would find\n if (name === 'constructor' || methods.has(name)) {\n continue;\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(current, name);\n\n if (descriptor && typeof descriptor.value === 'function') {\n methods.set(name, descriptor.value);\n }\n }\n }\n\n return methods;\n}\n\n/**\n * Finds methods that a framework replaced while constructing the first instance.\n *\n * Some frameworks register methods by function identity, so replacing one of their wrappers would\n * break dispatch. The result is cached because frameworks commonly install their wrappers only\n * once; later constructions would no longer reveal which methods they manage.\n */\nfunction resolveFrameworkManagedMethods(\n prototype: object,\n obj: object,\n methodsBeforeConstruction: Map<string, unknown> | undefined,\n cached: ReadonlySet<string> | undefined,\n): ReadonlySet<string> {\n if (cached) {\n return cached;\n }\n\n const methodsAfterConstruction = resolvePrototypeMethods(Object.getPrototypeOf(obj) as object);\n const managed = new Set<string>();\n\n for (const [name, method] of methodsAfterConstruction) {\n const before = methodsBeforeConstruction?.get(name);\n\n if (before && before !== method) {\n managed.add(name);\n }\n }\n\n frameworkManagedMethodsCache.set(prototype, managed);\n methodsBeforeFirstConstructionCache.delete(prototype);\n\n return managed;\n}\n\ntype RpcInstanceState = {\n options: CloudflareOptions;\n context: InstrumentedDurableObjectContext;\n /** Per-instance cache of the instrumented method wrappers, keyed by method name. Created on first use. */\n instrumentedMethods?: Map<string, UncheckedMethod>;\n};\n\n/**\n * Method names the runtime never dispatches over RPC, so wrapping them buys no tracing.\n *\n * Mirrors `isReservedName` in workerd (`src/workerd/api/worker-rpc.c++`): the runtime rejects these\n * before any property lookup happens. `fetch`, `alarm` and the `webSocket*` handlers are also\n * instrumented per-instance as own properties, and `constructor` is on every prototype.\n */\nconst RESERVED_RPC_METHOD_NAMES: ReadonlySet<string> = new Set([\n 'constructor',\n 'fetch',\n 'connect',\n 'alarm',\n 'webSocketMessage',\n 'webSocketClose',\n 'webSocketError',\n 'dup',\n]);\n\n// Prototype wrappers are shared by all instances, while SDK options and traced method caches are not.\nconst rpcInstanceStates = new WeakMap<object, RpcInstanceState>();\n\n/**\n * Instruments a constructed Durable Object's RPC methods.\n *\n * RPC methods are wrapped on the prototype because Cloudflare dispatches them with the Durable\n * Object instance as the receiver. This preserves native private-field access and keeps the methods\n * visible to Cloudflare's RPC dispatcher. Built-in handlers, Agent handlers, and methods managed by\n * another framework are left untouched.\n *\n * Call this after all per-instance instrumentation has been applied.\n *\n * @param obj The constructed Durable Object instance.\n * @param options The resolved SDK options for this instance.\n * @param context The instrumented execution context for this instance.\n * @param excludedMethods Method names owned by another framework and therefore not safe to wrap.\n * @returns The same Durable Object instance, with eligible prototype methods instrumented.\n * @internal\n */\nexport function finalizeWithRpcInstrumentation<T extends object>(\n obj: T,\n options: CloudflareOptions,\n context: InstrumentedDurableObjectContext,\n excludedMethods?: ReadonlySet<string>,\n): T {\n rpcInstanceStates.set(obj, { options, context });\n\n instrumentPrototypeRpcMethods(obj, excludedMethods);\n\n return obj;\n}\n\n/**\n * Returns a prototype method when it is eligible for RPC instrumentation.\n */\nfunction getRpcMethodDescriptor(\n obj: object,\n prototype: object,\n methodName: string,\n excludedMethods?: ReadonlySet<string>,\n): PropertyDescriptor | undefined {\n if (\n RESERVED_RPC_METHOD_NAMES.has(methodName) ||\n Object.prototype.hasOwnProperty.call(obj, methodName) ||\n excludedMethods?.has(methodName)\n ) {\n return undefined;\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(prototype, methodName);\n\n if (!descriptor || typeof descriptor.value !== 'function' || getInstrumented(descriptor.value)) {\n return undefined;\n }\n\n return descriptor;\n}\n\n/**\n * Wraps eligible methods on the instance's prototype chain once per class.\n */\nfunction instrumentPrototypeRpcMethods(obj: object, excludedMethods?: ReadonlySet<string>): void {\n let prototype: object | null = Object.getPrototypeOf(obj);\n\n while (prototype && prototype !== Object.prototype) {\n for (const methodName of Object.getOwnPropertyNames(prototype)) {\n const descriptor = getRpcMethodDescriptor(obj, prototype, methodName, excludedMethods);\n\n if (!descriptor) {\n continue;\n }\n\n const wrapped = createRpcPrototypeWrapper(methodName, descriptor.value as UncheckedMethod);\n\n try {\n Object.defineProperty(prototype, methodName, { ...descriptor, value: wrapped });\n } catch {}\n\n // Only the wrapper is marked, not the original method: `wrapMethodWithSentry` resolves\n // through the same global map and must not resolve the original to this wrapper,\n // which would recurse.\n markAsInstrumented(wrapped);\n }\n\n prototype = Object.getPrototypeOf(prototype);\n }\n}\n\n/**\n * Returns the instance's instrumented wrapper for an RPC method, creating it on first use.\n */\nfunction getInstrumentedRpcMethod(\n state: RpcInstanceState,\n methodName: string,\n originalMethod: UncheckedMethod,\n): UncheckedMethod {\n const instrumentedMethods = (state.instrumentedMethods ??= new Map());\n let instrumented = instrumentedMethods.get(methodName);\n\n if (!instrumented) {\n instrumented = wrapMethodWithSentry(\n {\n options: state.options,\n context: state.context,\n spanName: rpcMeta => (rpcMeta ? methodName : undefined),\n spanOp: RPC,\n origin: 'auto.faas.cloudflare.durable_object',\n },\n originalMethod,\n undefined,\n true,\n );\n instrumentedMethods.set(methodName, instrumented);\n }\n\n return instrumented;\n}\n\n/**\n * Creates a prototype wrapper that instruments external RPC calls.\n *\n * The wrapper looks up SDK state from its receiver, allowing one prototype function to serve every\n * instance. A call carrying Sentry metadata continues that trace in an `rpc` span. A call without it\n * still gets a client, so its errors, logs and metrics are captured, but no span. Calls the instance\n * makes to its own methods run the original method directly. The original function name and arity\n * are preserved because frameworks may inspect them for dispatch.\n */\nfunction createRpcPrototypeWrapper(methodName: string, originalMethod: UncheckedMethod): UncheckedMethod {\n const wrapper = function (this: unknown, ...args: unknown[]): unknown {\n const traced = hasRpcMeta(args);\n\n // workerd dispatches an incoming RPC call outside any async context, so a call made on any other\n // isolation scope comes from the instance itself (`this.helper()` inside `fetch`, `alarm`,\n // another RPC method or async work the constructor started). Check that before touching\n // per-instance state.\n if (!traced && getIsolationScope() !== getDefaultIsolationScope()) {\n return Reflect.apply(originalMethod, this, args);\n }\n\n const state = isObjectLike(this) ? rpcInstanceStates.get(this) : undefined;\n\n if (!state) {\n return Reflect.apply(originalMethod, this, args);\n }\n\n const instrumented = getInstrumentedRpcMethod(state, methodName, originalMethod);\n\n if (traced) {\n return Reflect.apply(instrumented, this, args);\n }\n\n // Unlike a WorkerEntrypoint, a Durable Object instance is long-lived and serves overlapping\n // calls. Without a new trace, every untraced call would share the trace of the default scope.\n return startNewTrace(() => Reflect.apply(instrumented, this, args));\n };\n\n Object.defineProperties(wrapper, {\n name: { value: originalMethod.name, configurable: true },\n length: { value: originalMethod.length, configurable: true },\n });\n\n return wrapper as UncheckedMethod;\n}\n\n/**\n * Instruments a Durable Object class to capture errors and performance data.\n *\n * Instruments the following methods by default:\n * - fetch\n * - alarm\n * - webSocketMessage\n * - webSocketClose\n * - webSocketError\n *\n * RPC methods (prototype methods) are instrumented too: an incoming trace continues into them, and\n * errors, logs and metrics are captured whether or not the caller propagates a trace.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param DurableObjectClass The Durable Object class to instrument.\n * @returns The instrumented Durable Object class.\n *\n * @example\n * ```ts\n * class MyDurableObjectBase extends DurableObject {\n * constructor(ctx: DurableObjectState, env: Env) {\n * super(ctx, env);\n * }\n * }\n *\n * export const MyDurableObject = instrumentDurableObjectWithSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * }),\n * MyDurableObjectBase,\n * );\n * ```\n */\nexport function instrumentDurableObjectWithSentry<\n Env = DefaultEnv,\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends DurableObject<any> = DurableObject<Env>,\n // oxlint-disable-next-line typescript/no-explicit-any\n C extends new (state: DurableObjectState, env: any) => T = new (state: DurableObjectState, env: any) => T,\n O = unknown,\n>(optionsCallback: (env: ResolveEnv<C, Env>) => StrictCloudflareOptions<O>, DurableObjectClass: C): C {\n const InstrumentedClass = new Proxy(DurableObjectClass, {\n construct(target, [ctx, env], newTarget) {\n const { obj, options, context, frameworkManagedMethods } = constructInstrumentedDurableObject(\n target,\n ctx,\n env,\n newTarget,\n optionsCallback,\n );\n\n return finalizeWithRpcInstrumentation(obj, options, context, frameworkManagedMethods);\n },\n });\n // Recognizable for `_INTERNAL_wrapUnlessInstrumented`, so auto-instrumentation never nests wrappers.\n markAsInstrumented(InstrumentedClass);\n return InstrumentedClass;\n}\n\n/**\n * Instruments a Cloudflare [`agents`](https://www.npmjs.com/package/agents) Agent class with Sentry.\n *\n * An `Agent` is a Durable Object under the hood, so this applies the same instrumentation as\n * {@link instrumentDurableObjectWithSentry} (request transactions, `alarm`, WebSocket handlers, RPC\n * trace propagation, SQL spans) and additionally captures Agent-specific telemetry via\n * `instrumentCloudflareAgent`:\n *\n * - **Callable RPC spans** — a span (op `rpc`) for each `@callable()` method invoked over WebSocket.\n * - **Breadcrumbs** — for every Agent observability event (`rpc`, `state:update`, `connect`,\n * `disconnect`, `schedule:*`, `queue:*`, `workflow:*`, `email:*`, `mcp:*`, ...).\n *\n * Cloudflare Workers cannot auto-instrument, so the Agent class must be wrapped manually.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param AgentClass The Agent class to instrument.\n * @returns The instrumented Agent class.\n *\n * @example\n * ```ts\n * import { Agent, callable, routeAgentRequest } from 'agents';\n * import * as Sentry from '@sentry/cloudflare';\n *\n * class MyAgentBase extends Agent<Env> {\n * @callable()\n * async greet(name: string): Promise<string> {\n * return `Hello, ${name}!`;\n * }\n * }\n *\n * export const MyAgent = Sentry.instrumentAgentWithSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * }),\n * MyAgentBase,\n * );\n * ```\n */\nexport function instrumentAgentWithSentry<\n Env = DefaultEnv,\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends DurableObject<any> = DurableObject<Env>,\n // oxlint-disable-next-line typescript/no-explicit-any\n C extends new (state: DurableObjectState, env: any) => T = new (state: DurableObjectState, env: any) => T,\n O = unknown,\n>(optionsCallback: (env: ResolveEnv<C, Env>) => StrictCloudflareOptions<O>, AgentClass: C): C {\n const InstrumentedClass = new Proxy(AgentClass, {\n construct(target, [ctx, env], newTarget) {\n const { obj, options, context, frameworkManagedMethods } = constructInstrumentedDurableObject(\n target,\n ctx,\n env,\n newTarget,\n optionsCallback,\n );\n\n instrumentCloudflareAgent(obj);\n\n // Apply RPC prototype-method instrumentation last, so the Agent-specific own-property\n // handlers we just installed are excluded from RPC method tracing. Methods the Agent\n // framework installed itself are excluded too — `instrumentCloudflareAgent` traces those by\n // wrapping the dispatch instead of the method.\n return finalizeWithRpcInstrumentation(obj, options, context, frameworkManagedMethods);\n },\n });\n markAsInstrumented(InstrumentedClass);\n return InstrumentedClass;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,mCACd,QACA,KACA,KACA,WACA,iBAMA;CACA,kDAAkD;CAClD,MAAM,UAAU,gBAAgB,gBAAgB,GAAG,GAAG,GAAG;CAIzD,MAAM,UAAU,kBAAkB,GAAU;CAC5C,MAAM,kBAAkB,cAAc,KAAgC,OAAO;CAE7E,MAAM,YAAa,UAAgD,aAAa,OAAO;CACvF,MAAM,gCAAgC,6BAA6B,IAAI,SAAS;CAChF,MAAM,4BAA4B,gCAC9B,KAAA,IACA,sCAAsC,SAAS;CAKnD,MAA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CAED,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;EAEA,0BAA0B,GAAG;EAM7B,OAAO,+BAA+B,KAAK,SAAS,SAAS,uBAAuB;CACtF,EACF,CAAC;CACD,mBAAmB,iBAAiB;CACpC,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"durableobject.js","names":[],"sources":["../../../src/durableobject.ts"],"sourcesContent":["/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/unbound-method */\nimport { RPC } from '@sentry/conventions/op';\nimport { getDefaultIsolationScope, getIsolationScope, isObjectLike, startNewTrace } from '@sentry/core';\nimport type { DurableObject } from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategyForWorker } from './utils/asyncContextStrategy';\nimport type { CloudflareOptions } from './client';\nimport { getInstrumented, markAsInstrumented } from './instrument';\nimport { instrumentDurableObjectHandlers } from './instrumentations/instrumentDurableObjectHandlers';\nimport { instrumentEnv } from './instrumentations/worker/instrumentEnv';\nimport { getFinalOptions } from './options';\nimport { flushDeferredChannelEvents } from './orchestrion-deferred-channels';\nimport { init } from './sdk';\nimport { instrumentContext } from './utils/instrumentContext';\nimport { withConstructionIsolationScope } from './utils/invocationScope';\nimport { hasRpcMeta } from './utils/rpcMeta';\nimport { instrumentCloudflareAgent } from './instrumentations/agents';\nimport type { DefaultEnv, ResolveEnv, StrictCloudflareOptions } from './types';\nimport { type UncheckedMethod, wrapMethodWithSentry } from './wrapMethodWithSentry';\n\n/**\n * The instrumented context passed between the shared construction helpers.\n *\n * This is intentionally `any` rather than `ReturnType<typeof instrumentContext<DurableObjectState>>`.\n * A concrete `DurableObjectState` here forces `tsc` to structurally relate its `storage: SqlStorage`\n * graph against the `ExecutionContext | InstrumentedDurableObjectState` parameter of\n * `wrapMethodWithSentry`, while the RPC-branded `DurableObject` from `cloudflare:workers` is also in\n * scope. That union comparison explodes (1296×1296) and hangs the type build. The original inline\n * implementation avoided this only incidentally, because `ctx` reached it as `any` through the Proxy\n * `construct` trap. Keeping the shared context `any` preserves that behavior.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InstrumentedDurableObjectContext = any;\n\n/**\n * Constructs a Durable Object instance and instruments its built-in handler methods\n * (`fetch`, `alarm`, `webSocketMessage`, `webSocketClose`, `webSocketError`).\n *\n * This is the shared construction path used by both {@link instrumentDurableObjectWithSentry}\n * and {@link instrumentAgentWithSentry}. It intentionally does NOT apply the RPC prototype-method\n * instrumentation — callers apply that last via {@link finalizeWithRpcInstrumentation}, after any\n * additional per-instance instrumentation has been layered onto the returned object.\n *\n * @internal\n */\nexport function constructInstrumentedDurableObject<E, T extends DurableObject<E>>(\n target: new (state: DurableObjectState, env: E) => T,\n ctx: DurableObjectState,\n env: E,\n newTarget: NewableFunction,\n optionsCallback: (env: E) => CloudflareOptions,\n): {\n obj: T;\n options: CloudflareOptions;\n context: InstrumentedDurableObjectContext;\n frameworkManagedMethods: ReadonlySet<string>;\n} {\n setAsyncLocalStorageAsyncContextStrategyForWorker();\n const options = getFinalOptions(optionsCallback(env), env);\n // See InstrumentedDurableObjectContext — `ctx` is widened to `any` so the concrete\n // `DurableObjectState` type never enters the checker's relation graph in this module.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const context = instrumentContext(ctx as any);\n const instrumentedEnv = instrumentEnv(env as Record<string, unknown>, options);\n\n const prototype = (newTarget as unknown as { prototype?: object }).prototype ?? target.prototype;\n const cachedFrameworkManagedMethods = frameworkManagedMethodsCache.get(prototype);\n const methodsBeforeConstruction = cachedFrameworkManagedMethods\n ? undefined\n : resolveMethodsBeforeFirstConstruction(prototype);\n\n // Pass `newTarget` so that subclasses of the instrumented class (e.g. the wrapper classes\n // created by wrangler's local dev tooling or `@cloudflare/vitest-pool-workers`) keep their\n // own prototype — otherwise subclass methods disappear and `instanceof` checks break.\n const obj = withConstructionIsolationScope(() => {\n // The constructor can already use instrumented libraries, e.g. open a pi-durable Harness in\n // `blockConcurrencyWhile`. Their channel integrations only subscribe in `init()`, and an isolate\n // that runs only this Durable Object has no earlier handler that called it. A per-invocation\n // client (`cacheClient: false`) would have no invocation to flush it, so it waits for one.\n // oxlint-disable-next-line typescript/no-deprecated\n if (options.cacheClient !== false) {\n init({ ...options });\n flushDeferredChannelEvents();\n }\n return Reflect.construct(target, [context, instrumentedEnv], newTarget) as T;\n });\n\n const frameworkManagedMethods = resolveFrameworkManagedMethods(\n prototype,\n obj,\n methodsBeforeConstruction,\n cachedFrameworkManagedMethods,\n );\n\n instrumentDurableObjectHandlers(obj, options, context);\n\n return { obj, options, context, frameworkManagedMethods };\n}\n\nconst frameworkManagedMethodsCache = new WeakMap<object, ReadonlySet<string>>();\nconst methodsBeforeFirstConstructionCache = new WeakMap<object, Map<string, unknown>>();\n\n/**\n * Collects the prototype's methods as they were before any instance was constructed.\n *\n * A constructor can throw after a framework has already installed its wrappers (the `agents` SDK\n * wraps `@callable()` methods before storage initialization, which can fail). The next construction\n * would then see those wrappers as the originals and treat the methods as unmanaged, so the methods\n * collected on the first attempt are kept until a construction succeeds.\n */\nfunction resolveMethodsBeforeFirstConstruction(prototype: object): Map<string, unknown> {\n let methods = methodsBeforeFirstConstructionCache.get(prototype);\n\n if (!methods) {\n methods = resolvePrototypeMethods(prototype);\n methodsBeforeFirstConstructionCache.set(prototype, methods);\n }\n\n return methods;\n}\n\n/**\n * Collects the methods visible from a prototype, using normal property lookup precedence.\n * Methods inherited from `Object.prototype` are excluded because they cannot be Durable Object RPC methods.\n */\nfunction resolvePrototypeMethods(prototype: object | null): Map<string, unknown> {\n const methods = new Map<string, unknown>();\n\n for (let current = prototype; current && current !== Object.prototype; current = Object.getPrototypeOf(current)) {\n for (const name of Object.getOwnPropertyNames(current)) {\n // The first occurrence wins, mirroring what a property lookup on the instance would find\n if (name === 'constructor' || methods.has(name)) {\n continue;\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(current, name);\n\n if (descriptor && typeof descriptor.value === 'function') {\n methods.set(name, descriptor.value);\n }\n }\n }\n\n return methods;\n}\n\n/**\n * Finds methods that a framework replaced while constructing the first instance.\n *\n * Some frameworks register methods by function identity, so replacing one of their wrappers would\n * break dispatch. The result is cached because frameworks commonly install their wrappers only\n * once; later constructions would no longer reveal which methods they manage.\n */\nfunction resolveFrameworkManagedMethods(\n prototype: object,\n obj: object,\n methodsBeforeConstruction: Map<string, unknown> | undefined,\n cached: ReadonlySet<string> | undefined,\n): ReadonlySet<string> {\n if (cached) {\n return cached;\n }\n\n const methodsAfterConstruction = resolvePrototypeMethods(Object.getPrototypeOf(obj) as object);\n const managed = new Set<string>();\n\n for (const [name, method] of methodsAfterConstruction) {\n const before = methodsBeforeConstruction?.get(name);\n\n if (before && before !== method) {\n managed.add(name);\n }\n }\n\n frameworkManagedMethodsCache.set(prototype, managed);\n methodsBeforeFirstConstructionCache.delete(prototype);\n\n return managed;\n}\n\ntype RpcInstanceState = {\n options: CloudflareOptions;\n context: InstrumentedDurableObjectContext;\n /** Per-instance cache of the instrumented method wrappers, keyed by method name. Created on first use. */\n instrumentedMethods?: Map<string, UncheckedMethod>;\n};\n\n/**\n * Method names the runtime never dispatches over RPC, so wrapping them buys no tracing.\n *\n * Mirrors `isReservedName` in workerd (`src/workerd/api/worker-rpc.c++`): the runtime rejects these\n * before any property lookup happens. `fetch`, `alarm` and the `webSocket*` handlers are also\n * instrumented per-instance as own properties, and `constructor` is on every prototype.\n */\nconst RESERVED_RPC_METHOD_NAMES: ReadonlySet<string> = new Set([\n 'constructor',\n 'fetch',\n 'connect',\n 'alarm',\n 'webSocketMessage',\n 'webSocketClose',\n 'webSocketError',\n 'dup',\n]);\n\n// Prototype wrappers are shared by all instances, while SDK options and traced method caches are not.\nconst rpcInstanceStates = new WeakMap<object, RpcInstanceState>();\n\n/**\n * Instruments a constructed Durable Object's RPC methods.\n *\n * RPC methods are wrapped on the prototype because Cloudflare dispatches them with the Durable\n * Object instance as the receiver. This preserves native private-field access and keeps the methods\n * visible to Cloudflare's RPC dispatcher. Built-in handlers, Agent handlers, and methods managed by\n * another framework are left untouched.\n *\n * Call this after all per-instance instrumentation has been applied.\n *\n * @param obj The constructed Durable Object instance.\n * @param options The resolved SDK options for this instance.\n * @param context The instrumented execution context for this instance.\n * @param excludedMethods Method names owned by another framework and therefore not safe to wrap.\n * @returns The same Durable Object instance, with eligible prototype methods instrumented.\n * @internal\n */\nexport function finalizeWithRpcInstrumentation<T extends object>(\n obj: T,\n options: CloudflareOptions,\n context: InstrumentedDurableObjectContext,\n excludedMethods?: ReadonlySet<string>,\n): T {\n rpcInstanceStates.set(obj, { options, context });\n\n instrumentPrototypeRpcMethods(obj, excludedMethods);\n\n return obj;\n}\n\n/**\n * Returns a prototype method when it is eligible for RPC instrumentation.\n */\nfunction getRpcMethodDescriptor(\n obj: object,\n prototype: object,\n methodName: string,\n excludedMethods?: ReadonlySet<string>,\n): PropertyDescriptor | undefined {\n if (\n RESERVED_RPC_METHOD_NAMES.has(methodName) ||\n Object.prototype.hasOwnProperty.call(obj, methodName) ||\n excludedMethods?.has(methodName)\n ) {\n return undefined;\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(prototype, methodName);\n\n if (!descriptor || typeof descriptor.value !== 'function' || getInstrumented(descriptor.value)) {\n return undefined;\n }\n\n return descriptor;\n}\n\n/**\n * Wraps eligible methods on the instance's prototype chain once per class.\n */\nfunction instrumentPrototypeRpcMethods(obj: object, excludedMethods?: ReadonlySet<string>): void {\n let prototype: object | null = Object.getPrototypeOf(obj);\n\n while (prototype && prototype !== Object.prototype) {\n for (const methodName of Object.getOwnPropertyNames(prototype)) {\n const descriptor = getRpcMethodDescriptor(obj, prototype, methodName, excludedMethods);\n\n if (!descriptor) {\n continue;\n }\n\n const wrapped = createRpcPrototypeWrapper(methodName, descriptor.value as UncheckedMethod);\n\n try {\n Object.defineProperty(prototype, methodName, { ...descriptor, value: wrapped });\n } catch {}\n\n // Only the wrapper is marked, not the original method: `wrapMethodWithSentry` resolves\n // through the same global map and must not resolve the original to this wrapper,\n // which would recurse.\n markAsInstrumented(wrapped);\n }\n\n prototype = Object.getPrototypeOf(prototype);\n }\n}\n\n/**\n * Returns the instance's instrumented wrapper for an RPC method, creating it on first use.\n */\nfunction getInstrumentedRpcMethod(\n state: RpcInstanceState,\n methodName: string,\n originalMethod: UncheckedMethod,\n): UncheckedMethod {\n const instrumentedMethods = (state.instrumentedMethods ??= new Map());\n let instrumented = instrumentedMethods.get(methodName);\n\n if (!instrumented) {\n instrumented = wrapMethodWithSentry(\n {\n options: state.options,\n context: state.context,\n spanName: rpcMeta => (rpcMeta ? methodName : undefined),\n spanOp: RPC,\n origin: 'auto.faas.cloudflare.durable_object',\n },\n originalMethod,\n undefined,\n true,\n );\n instrumentedMethods.set(methodName, instrumented);\n }\n\n return instrumented;\n}\n\n/**\n * Creates a prototype wrapper that instruments external RPC calls.\n *\n * The wrapper looks up SDK state from its receiver, allowing one prototype function to serve every\n * instance. A call carrying Sentry metadata continues that trace in an `rpc` span. A call without it\n * still gets a client, so its errors, logs and metrics are captured, but no span. Calls the instance\n * makes to its own methods run the original method directly. The original function name and arity\n * are preserved because frameworks may inspect them for dispatch.\n */\nfunction createRpcPrototypeWrapper(methodName: string, originalMethod: UncheckedMethod): UncheckedMethod {\n const wrapper = function (this: unknown, ...args: unknown[]): unknown {\n const traced = hasRpcMeta(args);\n\n // workerd dispatches an incoming RPC call outside any async context, so a call made on any other\n // isolation scope comes from the instance itself (`this.helper()` inside `fetch`, `alarm`,\n // another RPC method or async work the constructor started). Check that before touching\n // per-instance state.\n if (!traced && getIsolationScope() !== getDefaultIsolationScope()) {\n return Reflect.apply(originalMethod, this, args);\n }\n\n const state = isObjectLike(this) ? rpcInstanceStates.get(this) : undefined;\n\n if (!state) {\n return Reflect.apply(originalMethod, this, args);\n }\n\n const instrumented = getInstrumentedRpcMethod(state, methodName, originalMethod);\n\n if (traced) {\n return Reflect.apply(instrumented, this, args);\n }\n\n // Unlike a WorkerEntrypoint, a Durable Object instance is long-lived and serves overlapping\n // calls. Without a new trace, every untraced call would share the trace of the default scope.\n return startNewTrace(() => Reflect.apply(instrumented, this, args));\n };\n\n Object.defineProperties(wrapper, {\n name: { value: originalMethod.name, configurable: true },\n length: { value: originalMethod.length, configurable: true },\n });\n\n return wrapper as UncheckedMethod;\n}\n\n/**\n * Instruments a Durable Object class to capture errors and performance data.\n *\n * Instruments the following methods by default:\n * - fetch\n * - alarm\n * - webSocketMessage\n * - webSocketClose\n * - webSocketError\n *\n * RPC methods (prototype methods) are instrumented too: an incoming trace continues into them, and\n * errors, logs and metrics are captured whether or not the caller propagates a trace.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param DurableObjectClass The Durable Object class to instrument.\n * @returns The instrumented Durable Object class.\n *\n * @example\n * ```ts\n * class MyDurableObjectBase extends DurableObject {\n * constructor(ctx: DurableObjectState, env: Env) {\n * super(ctx, env);\n * }\n * }\n *\n * export const MyDurableObject = instrumentDurableObjectWithSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * }),\n * MyDurableObjectBase,\n * );\n * ```\n */\nexport function instrumentDurableObjectWithSentry<\n Env = DefaultEnv,\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends DurableObject<any> = DurableObject<Env>,\n // oxlint-disable-next-line typescript/no-explicit-any\n C extends new (state: DurableObjectState, env: any) => T = new (state: DurableObjectState, env: any) => T,\n O = unknown,\n>(optionsCallback: (env: ResolveEnv<C, Env>) => StrictCloudflareOptions<O>, DurableObjectClass: C): C {\n const InstrumentedClass = new Proxy(DurableObjectClass, {\n construct(target, [ctx, env], newTarget) {\n const { obj, options, context, frameworkManagedMethods } = constructInstrumentedDurableObject(\n target,\n ctx,\n env,\n newTarget,\n optionsCallback,\n );\n\n return finalizeWithRpcInstrumentation(obj, options, context, frameworkManagedMethods);\n },\n });\n // Recognizable for `_INTERNAL_wrapUnlessInstrumented`, so auto-instrumentation never nests wrappers.\n markAsInstrumented(InstrumentedClass);\n return InstrumentedClass;\n}\n\n/**\n * Instruments a Cloudflare [`agents`](https://www.npmjs.com/package/agents) Agent class with Sentry.\n *\n * An `Agent` is a Durable Object under the hood, so this applies the same instrumentation as\n * {@link instrumentDurableObjectWithSentry} (request transactions, `alarm`, WebSocket handlers, RPC\n * trace propagation, SQL spans) and additionally captures Agent-specific telemetry via\n * `instrumentCloudflareAgent`:\n *\n * - **Callable RPC spans** — a span (op `rpc`) for each `@callable()` method invoked over WebSocket.\n * - **Breadcrumbs** — for every Agent observability event (`rpc`, `state:update`, `connect`,\n * `disconnect`, `schedule:*`, `queue:*`, `workflow:*`, `email:*`, `mcp:*`, ...).\n *\n * Cloudflare Workers cannot auto-instrument, so the Agent class must be wrapped manually.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param AgentClass The Agent class to instrument.\n * @returns The instrumented Agent class.\n *\n * @example\n * ```ts\n * import { Agent, callable, routeAgentRequest } from 'agents';\n * import * as Sentry from '@sentry/cloudflare';\n *\n * class MyAgentBase extends Agent<Env> {\n * @callable()\n * async greet(name: string): Promise<string> {\n * return `Hello, ${name}!`;\n * }\n * }\n *\n * export const MyAgent = Sentry.instrumentAgentWithSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * }),\n * MyAgentBase,\n * );\n * ```\n */\nexport function instrumentAgentWithSentry<\n Env = DefaultEnv,\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends DurableObject<any> = DurableObject<Env>,\n // oxlint-disable-next-line typescript/no-explicit-any\n C extends new (state: DurableObjectState, env: any) => T = new (state: DurableObjectState, env: any) => T,\n O = unknown,\n>(optionsCallback: (env: ResolveEnv<C, Env>) => StrictCloudflareOptions<O>, AgentClass: C): C {\n const InstrumentedClass = new Proxy(AgentClass, {\n construct(target, [ctx, env], newTarget) {\n const { obj, options, context, frameworkManagedMethods } = constructInstrumentedDurableObject(\n target,\n ctx,\n env,\n newTarget,\n optionsCallback,\n );\n\n instrumentCloudflareAgent(obj);\n\n // Apply RPC prototype-method instrumentation last, so the Agent-specific own-property\n // handlers we just installed are excluded from RPC method tracing. Methods the Agent\n // framework installed itself are excluded too — `instrumentCloudflareAgent` traces those by\n // wrapping the dispatch instead of the method.\n return finalizeWithRpcInstrumentation(obj, options, context, frameworkManagedMethods);\n },\n });\n markAsInstrumented(InstrumentedClass);\n return InstrumentedClass;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,mCACd,QACA,KACA,KACA,WACA,iBAMA;CACA,kDAAkD;CAClD,MAAM,UAAU,gBAAgB,gBAAgB,GAAG,GAAG,GAAG;CAIzD,MAAM,UAAU,kBAAkB,GAAU;CAC5C,MAAM,kBAAkB,cAAc,KAAgC,OAAO;CAE7E,MAAM,YAAa,UAAgD,aAAa,OAAO;CACvF,MAAM,gCAAgC,6BAA6B,IAAI,SAAS;CAChF,MAAM,4BAA4B,gCAC9B,KAAA,IACA,sCAAsC,SAAS;CAKnD,MAAM,MAAM,qCAAqC;EAM/C,IAAI,QAAQ,gBAAgB,OAAO;GACjC,KAAK,EAAE,GAAG,QAAQ,CAAC;GACnB,2BAA2B;EAC7B;EACA,OAAO,QAAQ,UAAU,QAAQ,CAAC,SAAS,eAAe,GAAG,SAAS;CACxE,CAAC;CAED,MAAM,0BAA0B,+BAC9B,WACA,KACA,2BACA,6BACF;CAEA,gCAAgC,KAAK,SAAS,OAAO;CAErD,OAAO;EAAE;EAAK;EAAS;EAAS;CAAwB;AAC1D;AAEA,MAAM,+CAA+B,IAAI,QAAqC;AAC9E,MAAM,sDAAsC,IAAI,QAAsC;;;;;;;;;AAUtF,SAAS,sCAAsC,WAAyC;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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 ?? envToBool(getEnvVar(env, "SENTRY_DEBUG")),
|
|
40
41
|
tunnel: userOptions.tunnel ?? getEnvVar(env, "SENTRY_TUNNEL"),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"options.js","names":[],"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,OAAO,aAAa,KAAK,KAAK,QAAQ,SAAS,OAAO,MAAM,OAAO;AACrE;AAEA,SAAS,UAA6C,KAAc,SAAsC;CACxG,OAAO,aAAa,GAAG,KAAK,WAAW,OAAO,OAAQ,IAAU,aAAa,WACvE,IAAU,WACZ,KAAA;AACN;;;;;;;;;;;;;;;AAgBA,SAAgB,gBAAgB,cAAiC,CAAC,GAAG,KAAiC;CACpG,IAAI,CAAC,aAAa,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,SAAS,UAAU,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,UAAU,UAAU,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":[],"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,OAAO,aAAa,KAAK,KAAK,QAAQ,SAAS,OAAO,MAAM,OAAO;AACrE;AAEA,SAAS,UAA6C,KAAc,SAAsC;CACxG,OAAO,aAAa,GAAG,KAAK,WAAW,OAAO,OAAQ,IAAU,aAAa,WACvE,IAAU,WACZ,KAAA;AACN;;;;;;;;;;;;;;;AAgBA,SAAgB,gBAAgB,cAAiC,CAAC,GAAG,KAAiC;CACpG,IAAI,CAAC,aAAa,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,SAAS,UAAU,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,UAAU,UAAU,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,5 +1,5 @@
|
|
|
1
1
|
import { DEBUG_BUILD } from "./debug-build.js";
|
|
2
|
-
import { debug } from "@sentry/core";
|
|
2
|
+
import { GLOBAL_OBJ, debug } from "@sentry/core";
|
|
3
3
|
// src/orchestrion-deferred-channels.ts
|
|
4
4
|
/**
|
|
5
5
|
* Deferral for orchestrion channel events that could not be published when they occurred.
|
|
@@ -14,8 +14,11 @@ import { debug } from "@sentry/core";
|
|
|
14
14
|
* runtimes without `nodejs_compat` — there the queue is always empty (no channels were ever
|
|
15
15
|
* injected) and the flush is a no-op.
|
|
16
16
|
*/
|
|
17
|
-
const deferred = [];
|
|
18
17
|
const DEFERRED = Symbol("sentryOrchestrionDeferred");
|
|
18
|
+
function getDeferredEvents() {
|
|
19
|
+
const marker = GLOBAL_OBJ.__SENTRY_ORCHESTRION__ ?? (GLOBAL_OBJ.__SENTRY_ORCHESTRION__ = {});
|
|
20
|
+
return marker.deferredChannelEvents ?? (marker.deferredChannelEvents = []);
|
|
21
|
+
}
|
|
19
22
|
/** workerd's global-scope guard is the only error we degrade on; anything else is a real fault. */
|
|
20
23
|
function isGlobalScopeError(error) {
|
|
21
24
|
return error instanceof Error && /within global scope/.test(error.message);
|
|
@@ -24,7 +27,7 @@ function isGlobalScopeError(error) {
|
|
|
24
27
|
function deferChannelEvent(channel, ctx) {
|
|
25
28
|
if (ctx[DEFERRED]) return;
|
|
26
29
|
ctx[DEFERRED] = true;
|
|
27
|
-
|
|
30
|
+
getDeferredEvents().push({
|
|
28
31
|
channel,
|
|
29
32
|
ctx,
|
|
30
33
|
hadError: "error" in ctx
|
|
@@ -38,6 +41,7 @@ function deferChannelEvent(channel, ctx) {
|
|
|
38
41
|
* and re-entrant calls are no-ops.
|
|
39
42
|
*/
|
|
40
43
|
function flushDeferredChannelEvents() {
|
|
44
|
+
const deferred = getDeferredEvents();
|
|
41
45
|
if (deferred.length === 0) return;
|
|
42
46
|
const pending = deferred.splice(0, deferred.length);
|
|
43
47
|
for (const { channel, ctx, hadError } of pending) try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"orchestrion-deferred-channels.js","names":[],"sources":["../../../src/orchestrion-deferred-channels.ts"],"sourcesContent":["/**\n * Deferral for orchestrion channel events that could not be published when they occurred.\n *\n * On workerd, `channel.publish()`/`runStores()` throw at module/global scope, so a library\n * instantiated at module scope (`const app = new Hono()`) cannot emit its wrapping event\n * there. {@link ./orchestrion-diagnostics-channel} defers those events here;\n * {@link flushDeferredChannelEvents} emits them once a request is being handled (where\n * publish works) and the SDK's `init()` has registered subscribers.\n *\n * This module imports NO `node:*` builtin, so it is safe to pull into the request wrapper on\n * runtimes without `nodejs_compat` — there the queue is always empty (no channels were ever\n * injected) and the flush is a no-op.\n */\nimport { debug } from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build';\n\ntype Ctx = Record<string, unknown>;\n\n// The minimal slice of a `node:diagnostics_channel` TracingChannel we emit on. Declared locally\n// (rather than imported from `node:diagnostics_channel`) so this module's graph carries no `node:`\n// specifier — `wrapRequestHandler` must load on runtimes without `nodejs_compat`, and the\n// module-graph test forbids any `node:` import reachable from it.\ninterface PublishableTracingChannel {\n start: { publish(ctx: Ctx): void };\n end: { publish(ctx: Ctx): void };\n error: { publish(ctx: Ctx): void };\n}\n\ninterface DeferredChannelEvent {\n channel: PublishableTracingChannel;\n ctx: Ctx;\n hadError: boolean;\n}\n\nconst
|
|
1
|
+
{"version":3,"file":"orchestrion-deferred-channels.js","names":[],"sources":["../../../src/orchestrion-deferred-channels.ts"],"sourcesContent":["/**\n * Deferral for orchestrion channel events that could not be published when they occurred.\n *\n * On workerd, `channel.publish()`/`runStores()` throw at module/global scope, so a library\n * instantiated at module scope (`const app = new Hono()`) cannot emit its wrapping event\n * there. {@link ./orchestrion-diagnostics-channel} defers those events here;\n * {@link flushDeferredChannelEvents} emits them once a request is being handled (where\n * publish works) and the SDK's `init()` has registered subscribers.\n *\n * This module imports NO `node:*` builtin, so it is safe to pull into the request wrapper on\n * runtimes without `nodejs_compat` — there the queue is always empty (no channels were ever\n * injected) and the flush is a no-op.\n */\nimport { debug, GLOBAL_OBJ } from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build';\n\ntype Ctx = Record<string, unknown>;\n\n// The minimal slice of a `node:diagnostics_channel` TracingChannel we emit on. Declared locally\n// (rather than imported from `node:diagnostics_channel`) so this module's graph carries no `node:`\n// specifier — `wrapRequestHandler` must load on runtimes without `nodejs_compat`, and the\n// module-graph test forbids any `node:` import reachable from it.\ninterface PublishableTracingChannel {\n start: { publish(ctx: Ctx): void };\n end: { publish(ctx: Ctx): void };\n error: { publish(ctx: Ctx): void };\n}\n\ninterface DeferredChannelEvent {\n channel: PublishableTracingChannel;\n ctx: Ctx;\n hadError: boolean;\n}\n\nconst DEFERRED = Symbol('sentryOrchestrionDeferred');\n\n// The queue is on the global marker, not in this module: a bundle can hold both builds of this module. A transformed\n// CommonJS package (`express`) `require`s the facade, so it defers through the CommonJS build, while the request\n// wrapper that flushes is usually the ES module build.\nfunction getDeferredEvents(): DeferredChannelEvent[] {\n const marker = (GLOBAL_OBJ.__SENTRY_ORCHESTRION__ ??= {});\n return (marker.deferredChannelEvents ??= []) as DeferredChannelEvent[];\n}\n\n/** workerd's global-scope guard is the only error we degrade on; anything else is a real fault. */\nexport function isGlobalScopeError(error: unknown): boolean {\n return error instanceof Error && /within global scope/.test(error.message);\n}\n\n/** Queue a channel event that could not be published now, at most once per context object. */\nexport function deferChannelEvent(channel: PublishableTracingChannel, ctx: Ctx): void {\n if ((ctx as Record<symbol, unknown>)[DEFERRED]) {\n return;\n }\n (ctx as Record<symbol, unknown>)[DEFERRED] = true;\n getDeferredEvents().push({ channel, ctx, hadError: 'error' in ctx });\n}\n\n/**\n * Emit every deferred channel event via the real channel. Called at the top of the request\n * handler, after `init()` has subscribed. Uses bare `start`/`end` publish (never `runStores`),\n * so no `bindStore` producer runs and no span is parented to this request — only the plain\n * subscribers (the instance patchers) fire. Idempotent: it drains the queue, so later requests\n * and re-entrant calls are no-ops.\n */\nexport function flushDeferredChannelEvents(): void {\n const deferred = getDeferredEvents();\n if (deferred.length === 0) {\n return;\n }\n const pending = deferred.splice(0, deferred.length);\n for (const { channel, ctx, hadError } of pending) {\n try {\n channel.start.publish(ctx);\n if (hadError) {\n channel.error.publish(ctx);\n }\n channel.end.publish(ctx);\n } catch (error) {\n DEBUG_BUILD && debug.warn('[orchestrion] failed to emit a deferred channel event', error);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkCA,MAAM,WAAW,OAAO,2BAA2B;AAKnD,SAAS,oBAA4C;CACnD,MAAM,SAAU,WAAW,2BAAX,WAAW,yBAA2B,CAAC;CACvD,OAAQ,OAAO,0BAAP,OAAO,wBAA0B,CAAC;AAC5C;;AAGA,SAAgB,mBAAmB,OAAyB;CAC1D,OAAO,iBAAiB,SAAS,sBAAsB,KAAK,MAAM,OAAO;AAC3E;;AAGA,SAAgB,kBAAkB,SAAoC,KAAgB;CACpF,IAAK,IAAgC,WACnC;CAED,IAAgC,YAAY;CAC7C,kBAAkB,CAAC,CAAC,KAAK;EAAE;EAAS;EAAK,UAAU,WAAW;CAAI,CAAC;AACrE;;;;;;;;AASA,SAAgB,6BAAmC;CACjD,MAAM,WAAW,kBAAkB;CACnC,IAAI,SAAS,WAAW,GACtB;CAEF,MAAM,UAAU,SAAS,OAAO,GAAG,SAAS,MAAM;CAClD,KAAK,MAAM,EAAE,SAAS,KAAK,cAAc,SACvC,IAAI;EACF,QAAQ,MAAM,QAAQ,GAAG;EACzB,IAAI,UACF,QAAQ,MAAM,QAAQ,GAAG;EAE3B,QAAQ,IAAI,QAAQ,GAAG;CACzB,SAAS,OAAO;EACd,eAAe,MAAM,KAAK,yDAAyD,KAAK;CAC1F;AAEJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"type":"module","version":"11.
|
|
1
|
+
{"type":"module","version":"11.15.0","sideEffects":false}
|
|
@@ -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));
|