@sentry/cloudflare 11.13.0 → 11.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/build/cjs/dev/baseSdk.js.map +1 -1
  2. package/build/cjs/dev/client.js +17 -2
  3. package/build/cjs/dev/client.js.map +1 -1
  4. package/build/cjs/dev/durableobject.js.map +1 -1
  5. package/build/cjs/dev/options.js +1 -0
  6. package/build/cjs/dev/options.js.map +1 -1
  7. package/build/cjs/dev/orchestrion-deferred-channels.js +6 -2
  8. package/build/cjs/dev/orchestrion-deferred-channels.js.map +1 -1
  9. package/build/cjs/dev/vite/autoInstrument.js +5 -1
  10. package/build/cjs/dev/vite/autoInstrument.js.map +1 -1
  11. package/build/cjs/dev/vite/index.js.map +1 -1
  12. package/build/cjs/dev/vite/transform.js +12 -13
  13. package/build/cjs/dev/vite/transform.js.map +1 -1
  14. package/build/cjs/dev/vite/wranglerConfig.js +2 -0
  15. package/build/cjs/dev/vite/wranglerConfig.js.map +1 -1
  16. package/build/cjs/prod/baseSdk.js.map +1 -1
  17. package/build/cjs/prod/client.js +17 -2
  18. package/build/cjs/prod/client.js.map +1 -1
  19. package/build/cjs/prod/durableobject.js.map +1 -1
  20. package/build/cjs/prod/options.js +1 -0
  21. package/build/cjs/prod/options.js.map +1 -1
  22. package/build/cjs/prod/orchestrion-deferred-channels.js +6 -2
  23. package/build/cjs/prod/orchestrion-deferred-channels.js.map +1 -1
  24. package/build/cjs/prod/vite/autoInstrument.js +5 -1
  25. package/build/cjs/prod/vite/autoInstrument.js.map +1 -1
  26. package/build/cjs/prod/vite/index.js.map +1 -1
  27. package/build/cjs/prod/vite/transform.js +12 -13
  28. package/build/cjs/prod/vite/transform.js.map +1 -1
  29. package/build/cjs/prod/vite/wranglerConfig.js +2 -0
  30. package/build/cjs/prod/vite/wranglerConfig.js.map +1 -1
  31. package/build/esm/dev/baseSdk.js.map +1 -1
  32. package/build/esm/dev/client.js +18 -3
  33. package/build/esm/dev/client.js.map +1 -1
  34. package/build/esm/dev/durableobject.js.map +1 -1
  35. package/build/esm/dev/options.js +1 -0
  36. package/build/esm/dev/options.js.map +1 -1
  37. package/build/esm/dev/orchestrion-deferred-channels.js +7 -3
  38. package/build/esm/dev/orchestrion-deferred-channels.js.map +1 -1
  39. package/build/esm/dev/package.json +1 -1
  40. package/build/esm/dev/vite/autoInstrument.js +5 -1
  41. package/build/esm/dev/vite/autoInstrument.js.map +1 -1
  42. package/build/esm/dev/vite/index.js.map +1 -1
  43. package/build/esm/dev/vite/transform.js +12 -13
  44. package/build/esm/dev/vite/transform.js.map +1 -1
  45. package/build/esm/dev/vite/wranglerConfig.js +2 -0
  46. package/build/esm/dev/vite/wranglerConfig.js.map +1 -1
  47. package/build/esm/prod/baseSdk.js.map +1 -1
  48. package/build/esm/prod/client.js +18 -3
  49. package/build/esm/prod/client.js.map +1 -1
  50. package/build/esm/prod/durableobject.js.map +1 -1
  51. package/build/esm/prod/options.js +1 -0
  52. package/build/esm/prod/options.js.map +1 -1
  53. package/build/esm/prod/orchestrion-deferred-channels.js +7 -3
  54. package/build/esm/prod/orchestrion-deferred-channels.js.map +1 -1
  55. package/build/esm/prod/package.json +1 -1
  56. package/build/esm/prod/vite/autoInstrument.js +5 -1
  57. package/build/esm/prod/vite/autoInstrument.js.map +1 -1
  58. package/build/esm/prod/vite/index.js.map +1 -1
  59. package/build/esm/prod/vite/transform.js +12 -13
  60. package/build/esm/prod/vite/transform.js.map +1 -1
  61. package/build/esm/prod/vite/wranglerConfig.js +2 -0
  62. package/build/esm/prod/vite/wranglerConfig.js.map +1 -1
  63. package/build/types/baseSdk.d.ts.map +1 -1
  64. package/build/types/client.d.ts +8 -0
  65. package/build/types/client.d.ts.map +1 -1
  66. package/build/types/durableobject.d.ts.map +1 -1
  67. package/build/types/options.d.ts.map +1 -1
  68. package/build/types/orchestrion-deferred-channels.d.ts.map +1 -1
  69. package/build/types/vite/autoInstrument.d.ts.map +1 -1
  70. package/build/types/vite/index.d.ts +3 -0
  71. package/build/types/vite/index.d.ts.map +1 -1
  72. package/build/types/vite/transform.d.ts +12 -2
  73. package/build/types/vite/transform.d.ts.map +1 -1
  74. package/build/types/vite/wranglerConfig.d.ts +8 -0
  75. package/build/types/vite/wranglerConfig.d.ts.map +1 -1
  76. package/package.json +5 -5
@@ -1,10 +1,12 @@
1
1
  const require_runtime = require("../_virtual/_rolldown/runtime.js");
2
2
  const require_wranglerConfig = require("./wranglerConfig.js");
3
3
  const require_workerEntrypoint = require("./workerEntrypoint.js");
4
+ let _sentry_core = require("@sentry/core");
4
5
  let magic_string = require("magic-string");
5
6
  magic_string = require_runtime.__toESM(magic_string);
6
7
  // src/vite/transform.ts
7
8
  const MERGED_OPTIONS_IDENTIFIER = "__SENTRY_OPTIONS__";
9
+ const WORKER_INFO_GLOBAL = "__SENTRY_CLOUDFLARE_WORKER__";
8
10
  function isCallToMethod(node, methodName) {
9
11
  if (node.type !== "CallExpression") return false;
10
12
  const callee = node.callee;
@@ -39,8 +41,9 @@ const WRAPPER_METHODS = {
39
41
  * {@link TransformResult.wrappedClasses}.
40
42
  *
41
43
  * Exported (rather than inlined into the plugin) so it can be unit-tested with a
42
- * plain AST and no Vite context. Returns `undefined` when nothing was wrapped and
43
- * there are no already-manually-wrapped classes to report.
44
+ * plain AST and no Vite context. Returns `undefined` when nothing was wrapped,
45
+ * there are no already-manually-wrapped classes to report, and there is no
46
+ * {@link TransformContext.workerInfo} to store.
44
47
  */
45
48
  function applyAutoInstrumentTransforms(code, ast, ctx) {
46
49
  const ms = new magic_string.default(code);
@@ -63,17 +66,13 @@ function applyAutoInstrumentTransforms(code, ast, ctx) {
63
66
  const { wrappedClasses } = state;
64
67
  for (const node of ast.body) if (node.type === "ExportNamedDeclaration") handleNamedExport(node, ctx, state);
65
68
  for (const node of ast.body) if (node.type === "ExportDefaultDeclaration") wrapDefaultExport(node, ctx, state);
66
- if (!state.needsImport) {
67
- if (wrappedClasses.size === 0) return void 0;
68
- return {
69
- code,
70
- map: ms.generateMap({ hires: true }),
71
- wrappedClasses
72
- };
69
+ if (state.needsImport) {
70
+ if (sameWorkerBindings.length > 0) ms.prepend(buildMergedOptionsDeclaration(sameWorkerBindings, ctx.optionsFn, state));
71
+ if (ctx.optionsImport) ms.prepend(ctx.optionsImport);
72
+ ms.prepend(`import * as __SENTRY__ from '${ctx.sentryModule ?? "@sentry/cloudflare"}';\n`);
73
73
  }
74
- if (sameWorkerBindings.length > 0) ms.prepend(buildMergedOptionsDeclaration(sameWorkerBindings, ctx.optionsFn, state));
75
- if (ctx.optionsImport) ms.prepend(ctx.optionsImport);
76
- ms.prepend(`import * as __SENTRY__ from '${ctx.sentryModule ?? "@sentry/cloudflare"}';\n`);
74
+ if (ctx.workerInfo?.name || ctx.workerInfo?.compatibilityDate) ms.prepend(`globalThis.${WORKER_INFO_GLOBAL} = ${JSON.stringify(ctx.workerInfo)};\n`);
75
+ else if (!state.needsImport && wrappedClasses.size === 0) return;
77
76
  return {
78
77
  code: ms.toString(),
79
78
  map: ms.generateMap({ hires: true }),
@@ -88,7 +87,7 @@ function applyAutoInstrumentTransforms(code, ast, ctx) {
88
87
  function buildMergedOptionsDeclaration(sameWorkerBindings, optionsFn, state) {
89
88
  const bindingNames = sameWorkerBindings.filter(({ className }) => state.autoWrapped.has(className)).map(({ bindingName }) => bindingName);
90
89
  if (!bindingNames.length) return `const ${MERGED_OPTIONS_IDENTIFIER} = ${optionsFn};\n`;
91
- const names = bindingNames.map((name) => JSON.stringify(name)).join(", ");
90
+ const names = bindingNames.map((name) => (0, _sentry_core.stringifyForCodeInjection)(name)).join(", ");
92
91
  return `const ${MERGED_OPTIONS_IDENTIFIER} = (env) => { const opts = (${optionsFn})(env); return { ...opts, rpcTracePropagationBindings: [${names}, ...(opts?.rpcTracePropagationBindings ?? [])] }; };\n`;
93
92
  }
94
93
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"transform.js","names":["MagicString","detectWorkerEntrypointClasses","DEFAULT_EXPORT"],"sources":["../../../../src/vite/transform.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport MagicString from 'magic-string';\nimport { DEFAULT_EXPORT, type ExportName, type SameWorkerBinding } from './wranglerConfig';\nimport { detectWorkerEntrypointClasses } from './workerEntrypoint';\n\nconst MERGED_OPTIONS_IDENTIFIER = '__SENTRY_OPTIONS__';\n\n// ---------------------------------------------------------------------------\n// Minimal ESTree node types for the AST nodes we inspect.\n// ---------------------------------------------------------------------------\n\nexport interface BaseNode {\n type: string;\n start: number;\n end: number;\n}\n\nexport interface ProgramBody {\n body: BaseNode[];\n}\n\ninterface IdentifierNode extends BaseNode {\n name: string;\n}\n\ninterface CalleeNode {\n type: string;\n name?: string;\n property?: { type: string; name?: string };\n}\n\ninterface CallExpressionNode extends BaseNode {\n callee?: CalleeNode;\n}\n\ninterface ClassDeclarationNode extends BaseNode {\n id?: IdentifierNode | null;\n}\n\ninterface ExportDefaultNode extends BaseNode {\n declaration: BaseNode;\n}\n\ninterface ExportSpecifierNode extends BaseNode {\n local?: { type: string; name?: string };\n exported?: { type: string; name?: string };\n}\n\ninterface ExportNamedNode extends BaseNode {\n declaration?: BaseNode | null;\n source?: BaseNode | null;\n specifiers?: ExportSpecifierNode[];\n}\n\ninterface VariableDeclaratorNode {\n id?: { type: string; name?: string };\n init?: BaseNode | null;\n}\n\ninterface VariableDeclarationNode extends BaseNode {\n declarations?: VariableDeclaratorNode[];\n}\n\ninterface ImportDeclarationNode extends BaseNode {\n specifiers?: Array<{ local?: { type: string; name?: string } }>;\n}\n\nfunction isCallToMethod(node: BaseNode, methodName: string): boolean {\n if (node.type !== 'CallExpression') return false;\n const callee = (node as CallExpressionNode).callee;\n if (!callee) return false;\n if (callee.type === 'Identifier' && callee.name === methodName) return true;\n return (\n callee.type === 'MemberExpression' && callee.property?.type === 'Identifier' && callee.property.name === methodName\n );\n}\n\n/**\n * The kind of Sentry wrapper to apply to an exported class.\n *\n * `durableObject` and `workflow` are keyed by name from the wrangler config\n * (`durable_objects.bindings`, `workflows`), since those class names are\n * authoritative there. `workerEntrypoint` is different: a worker's own\n * entrypoints aren't enumerated in its config, so they're detected structurally\n * (a class extending `WorkerEntrypoint` from `cloudflare:workers`), with the\n * config providing only a fallback for self-bound entrypoints whose base class\n * lives in another module.\n */\nexport type ClassWrapperKind = 'durableObject' | 'agent' | 'workflow' | 'workerEntrypoint';\n\n/** Specifier name a `export { default as X } from '...'` re-export uses for the source's default. */\nconst DEFAULT_IMPORT = 'default';\n\n/**\n * The `@sentry/cloudflare` helper each wrapper kind emits. All share the same\n * `(optionsCallback, Class)` signature. `WorkerEntrypoint` classes use\n * `withSentry`, which runtime-detects the class type and routes accordingly.\n */\nconst WRAPPER_METHODS: Record<ClassWrapperKind, string> = {\n durableObject: 'instrumentDurableObjectWithSentry',\n agent: 'instrumentAgentWithSentry',\n workflow: 'instrumentWorkflowWithSentry',\n workerEntrypoint: 'withSentry',\n};\n\nexport interface TransformContext {\n /**\n * Exported class name → the kind of Sentry wrapper to apply. Populated from\n * the wrangler config, so the transform can wrap by name without resolving\n * each class's base type.\n */\n classWrappers: Map<string, ClassWrapperKind>;\n /**\n * Local class names detected as `agents` Agents. An Agent is configured as a Durable Object in\n * wrangler, so this upgrades those entries from `durableObject` to `agent`.\n */\n agentClasses?: ReadonlySet<string>;\n optionsFn: string;\n /** Import statement prepended when `optionsFn` references a separate module. */\n optionsImport?: string;\n /** Module the generated code imports `withSentry` and the class wrappers from. Defaults to `@sentry/cloudflare`. */\n sentryModule?: string;\n /** @see {@link import('./wranglerConfig').WranglerConfig.sameWorkerBindings} */\n sameWorkerBindings?: readonly SameWorkerBinding[];\n}\n\nexport interface TransformResult {\n code: string;\n map: ReturnType<MagicString['generateMap']>;\n /**\n * The configured class names that were actually wrapped. Lets the plugin warn\n * about configured classes it could not find, instead of silently leaving\n * them uninstrumented.\n */\n wrappedClasses: Set<string>;\n}\n\n/**\n * Rewrite the worker entry source to wrap its default export with `withSentry`\n * and any configured class export with its matching Sentry wrapper (see\n * {@link TransformContext.classWrappers}, e.g. Durable Object classes with\n * `instrumentDurableObjectWithSentry`).\n *\n * Handles `export class MyDO {}`, the specifier form (`class MyDO {}` …\n * `export { MyDO }` / `export { Foo as MyDO }`), and classes that live in\n * another module (`import { MyDO } from './do'; export { MyDO }` or\n * `export { MyDO } from './do'`). Only star re-exports (`export * from './do'`)\n * are left alone — the plugin warns about those via\n * {@link TransformResult.wrappedClasses}.\n *\n * Exported (rather than inlined into the plugin) so it can be unit-tested with a\n * plain AST and no Vite context. Returns `undefined` when nothing was wrapped and\n * there are no already-manually-wrapped classes to report.\n */\nexport function applyAutoInstrumentTransforms(\n code: string,\n ast: ProgramBody,\n ctx: TransformContext,\n): TransformResult | undefined {\n const ms = new MagicString(code);\n const topLevelClasses = collectTopLevelClasses(ast);\n const sameWorkerBindings = ctx.sameWorkerBindings ?? [];\n const state: TransformState = {\n ms,\n needsImport: false,\n wrappedClasses: new Set<string>(),\n topLevelClasses,\n wrappedLocals: new Map<string, string>(),\n classWrappers: ctx.classWrappers,\n agentClasses: ctx.agentClasses ?? new Set<string>(),\n workerEntrypointClasses: detectWorkerEntrypointClasses(ast),\n // The identifier must be chosen before wrapping, which bindings survive is only known after.\n optionsFn: sameWorkerBindings.length > 0 ? MERGED_OPTIONS_IDENTIFIER : ctx.optionsFn,\n autoWrapped: new Set<ExportName>(),\n manuallyWrappedLocals: collectManuallyWrappedLocals(ast),\n declaringStatements: collectDeclaringStatements(ast),\n };\n const { wrappedClasses } = state;\n\n // Named exports first, regardless of source order: the default-export handler\n // needs to know which local bindings a named export already wrapped, so it can\n // skip a class that is both exported by name and re-exported as default (which\n // would otherwise wrap it twice).\n for (const node of ast.body) {\n if (node.type === 'ExportNamedDeclaration') {\n handleNamedExport(node, ctx, state);\n }\n }\n for (const node of ast.body) {\n if (node.type === 'ExportDefaultDeclaration') {\n wrapDefaultExport(node as ExportDefaultNode, ctx, state);\n }\n }\n\n if (!state.needsImport) {\n // Nothing was rewritten. Still surface any classes found already wrapped\n // manually (via `wrappedClasses`) so the caller doesn't warn about them;\n // return undefined only when there was nothing to report either.\n if (wrappedClasses.size === 0) return undefined;\n return { code, map: ms.generateMap({ hires: true }), wrappedClasses };\n }\n\n // `prepend` inserts before earlier prepends, yielding: Sentry import, options import, declaration.\n if (sameWorkerBindings.length > 0) {\n ms.prepend(buildMergedOptionsDeclaration(sameWorkerBindings, ctx.optionsFn, state));\n }\n if (ctx.optionsImport) ms.prepend(ctx.optionsImport);\n ms.prepend(`import * as __SENTRY__ from '${ctx.sentryModule ?? '@sentry/cloudflare'}';\\n`);\n\n return {\n code: ms.toString(),\n map: ms.generateMap({ hires: true }),\n wrappedClasses,\n };\n}\n\ninterface TransformState {\n ms: MagicString;\n needsImport: boolean;\n wrappedClasses: Set<string>;\n /**\n * Top-level class declarations, exported or not, so specifier exports like\n * `export { MyDO }` can locate the class they refer to.\n */\n topLevelClasses: Map<string, ClassDeclarationNode>;\n /**\n * Local class name → the binding holding its wrapper, so two exports of the same class share one\n * wrapper and a default export of it can be re-pointed.\n */\n wrappedLocals: Map<string, string>;\n /** Class name → wrapper kind, keyed by the *exported* name (from config). */\n classWrappers: Map<string, ClassWrapperKind>;\n /** Local class names detected as `agents` Agents (see {@link TransformContext.agentClasses}). */\n agentClasses: ReadonlySet<string>;\n /**\n * Local class names detected as `WorkerEntrypoint` subclasses in this module,\n * so they can be wrapped without a config entry.\n */\n workerEntrypointClasses: Set<string>;\n optionsFn: string;\n /**\n * Export names wrapped by this transform, so their options can be extended with\n * `rpcTracePropagationBindings`. Hand-wrapped exports stay out, they keep the options they were\n * wrapped with. `wrappedClasses` counts both.\n */\n autoWrapped: Set<ExportName>;\n /**\n * Top-level bindings already assigned an `instrument*WithSentry(...)` result\n * (`const MyDO = instrumentDurableObjectWithSentry(...)`). Exporting one by\n * specifier must report it as wrapped rather than wrap it a second time.\n */\n manuallyWrappedLocals: Set<string>;\n /** Top-level binding name → the statement that declares it. */\n declaringStatements: Map<string, BaseNode>;\n}\n\n/**\n * Builds the callback that merges same-worker binding names into `rpcTracePropagationBindings` at\n * runtime, the options object only exists once the callback runs with `env`. Only bindings whose\n * class this transform wrapped survive, a hand-wrapped class runs on its own options.\n */\nfunction buildMergedOptionsDeclaration(\n sameWorkerBindings: readonly SameWorkerBinding[],\n optionsFn: string,\n state: TransformState,\n): string {\n const bindingNames = sameWorkerBindings\n .filter(({ className }) => state.autoWrapped.has(className))\n .map(({ bindingName }) => bindingName);\n\n if (!bindingNames.length) {\n return `const ${MERGED_OPTIONS_IDENTIFIER} = ${optionsFn};\\n`;\n }\n\n const names = bindingNames.map(name => JSON.stringify(name)).join(', ');\n return (\n `const ${MERGED_OPTIONS_IDENTIFIER} = (env) => { ` +\n `const opts = (${optionsFn})(env); ` +\n `return { ...opts, rpcTracePropagationBindings: [${names}, ...(opts?.rpcTracePropagationBindings ?? [])] }; };\\n`\n );\n}\n\n/**\n * Resolve the wrapper kind for a class export.\n *\n * Config (`classWrappers`) wins — it's authoritative for Durable Objects and\n * Workflows, and provides the self-binding fallback for WorkerEntrypoints whose\n * base class this module can't see. Otherwise a structurally-detected\n * `WorkerEntrypoint` subclass (matched by its *local* name) gets wrapped with\n * `withSentry`.\n *\n * `localName` is the binding **in this module** the export refers to, and must be\n * left undefined for `export { X } from '...'`: there the specifier's name belongs\n * to the source module, so matching it against anything detected here would wrap a\n * class that merely shares a name.\n *\n * The one case where config is refined rather than obeyed is an `agents` Agent:\n * it *is* a Durable Object, so wrangler can only ever describe it as one, and\n * only the detected base chain distinguishes the two.\n */\nfunction resolveWrapperKind(\n exportedName: string,\n localName: string | undefined,\n state: TransformState,\n): ClassWrapperKind | undefined {\n const configured = state.classWrappers.get(exportedName);\n\n if (\n configured === 'durableObject' &&\n ((localName && state.agentClasses.has(localName)) || state.agentClasses.has(exportedName))\n ) {\n return 'agent';\n }\n\n if (configured) return configured;\n if (localName && state.workerEntrypointClasses.has(localName)) return 'workerEntrypoint';\n return undefined;\n}\n\n/**\n * Top-level `const X = instrument*WithSentry(...)` bindings — a hand-wrapped class that is exported\n * separately (`export { X }`) rather than inline.\n */\nfunction collectManuallyWrappedLocals(ast: ProgramBody): Set<string> {\n const wrapperMethods = Object.values(WRAPPER_METHODS);\n const locals = new Set<string>();\n\n for (const node of ast.body) {\n const declaration = declarationOf(node);\n if (declaration?.type !== 'VariableDeclaration') continue;\n for (const declarator of (declaration as VariableDeclarationNode).declarations ?? []) {\n const name = declarator.id?.type === 'Identifier' ? declarator.id.name : undefined;\n const init = declarator.init;\n if (name && init && wrapperMethods.some(method => isCallToMethod(init, method))) {\n locals.add(name);\n }\n }\n }\n\n return locals;\n}\n\nfunction collectDeclaringStatements(ast: ProgramBody): Map<string, BaseNode> {\n const statements = new Map<string, BaseNode>();\n for (const node of ast.body) {\n const declaration = declarationOf(node);\n if (!declaration) continue;\n const ids =\n declaration.type === 'VariableDeclaration'\n ? ((declaration as VariableDeclarationNode).declarations ?? []).map(declarator => declarator.id)\n : declaration.type === 'ImportDeclaration'\n ? ((declaration as ImportDeclarationNode).specifiers ?? []).map(specifier => specifier.local)\n : [(declaration as ClassDeclarationNode).id];\n for (const id of ids) {\n if (id?.type === 'Identifier' && id.name) statements.set(id.name, node);\n }\n }\n return statements;\n}\n\nfunction collectTopLevelClasses(ast: ProgramBody): Map<string, ClassDeclarationNode> {\n const classes = new Map<string, ClassDeclarationNode>();\n for (const node of ast.body) {\n const declaration = declarationOf(node);\n if (declaration?.type !== 'ClassDeclaration') continue;\n const classNode = declaration as ClassDeclarationNode;\n if (classNode.id?.name) classes.set(classNode.id.name, classNode);\n }\n return classes;\n}\n\n/** The declaration a top-level statement makes, looking through `export` (`export const x = ...`). */\nfunction declarationOf(node: BaseNode): BaseNode | null | undefined {\n return node.type === 'ExportNamedDeclaration' ? (node as ExportNamedNode).declaration : node;\n}\n\nfunction wrapDefaultExport(node: ExportDefaultNode, ctx: TransformContext, state: TransformState): void {\n const decl = node.declaration;\n\n // Already wrapped — leave it alone\n if (isCallToMethod(decl, 'withSentry')) return;\n\n // `export default Foo` where `Foo` is a local class already wrapped by a named\n // export (e.g. a self-bound WorkerEntrypoint also used as the default handler).\n // Wrapping again would produce `withSentry(withSentry(...))`, so the default\n // export is re-pointed at the wrapper binding the named export created.\n if (decl.type === 'Identifier') {\n const wrappedName = state.wrappedLocals.get((decl as IdentifierNode).name);\n if (wrappedName) {\n state.ms.overwrite(decl.start, decl.end, wrappedName);\n state.autoWrapped.add(DEFAULT_EXPORT);\n return;\n }\n }\n\n // MagicString positions are always relative to the original source. Only the `export default`\n // keywords are replaced, so parentheses around the expression stay.\n const source = state.ms.original;\n const keywordsEnd = exportDefaultKeywordsEnd(source, node.start);\n const declaredName =\n decl.type === 'ClassDeclaration' || decl.type === 'FunctionDeclaration'\n ? (decl as ClassDeclarationNode).id?.name\n : undefined;\n\n // As with `export { handler as default }`, the export is set in two steps: bound as-is where the\n // original statement set it, then rebound at the end of the module to the wrapper, which sees\n // methods added in between. See `wrapDefaultSpecifier`.\n let wrapped = '__SENTRY_DEFAULT_EXPORT__';\n if (declaredName) {\n // `export default class Handler {}`: the declaration stays, so `Handler` stays bound in the module.\n state.ms.remove(node.start, decl.start);\n state.ms.appendLeft(node.end, `\\nvar __SENTRY_DEFAULT_EXPORT__ = ${declaredName};`);\n wrapped = declaredName;\n } else if (isAnonymousFunctionOrClass(decl)) {\n // As a property value, the class or function gets the name `default`, as `export default` gives it.\n const hasSemicolon = source[node.end - 1] === ';';\n state.ms.overwrite(node.start, keywordsEnd, 'var __SENTRY_DEFAULT_EXPORT__ = { default:');\n state.ms.appendLeft(hasSemicolon ? node.end - 1 : node.end, hasSemicolon ? ' }.default' : ' }.default;');\n } else {\n state.ms.overwrite(node.start, keywordsEnd, 'var __SENTRY_DEFAULT_EXPORT__ =');\n }\n state.ms.appendLeft(node.end, '\\nexport { __SENTRY_DEFAULT_EXPORT__ as default };');\n state.ms.append(`\\n__SENTRY_DEFAULT_EXPORT__ = __SENTRY__.withSentry(${state.optionsFn}, ${wrapped});`);\n state.needsImport = true;\n state.autoWrapped.add(DEFAULT_EXPORT);\n}\n\n/**\n * Offset just past the `default` keyword of the `export default` statement at `start`. Comments can\n * sit between `export`, `default` and the expression, and may themselves contain the word `default`.\n */\nfunction exportDefaultKeywordsEnd(source: string, start: number): number {\n let index = start + 'export'.length;\n while (index < source.length && !source.startsWith('default', index)) {\n if (source.startsWith('//', index)) {\n const lineEnd = source.indexOf('\\n', index);\n index = lineEnd === -1 ? source.length : lineEnd;\n } else if (source.startsWith('/*', index)) {\n const commentEnd = source.indexOf('*/', index + 2);\n index = commentEnd === -1 ? source.length : commentEnd + 2;\n } else {\n index++;\n }\n }\n return index + 'default'.length;\n}\n\nfunction isAnonymousFunctionOrClass(node: BaseNode): boolean {\n if (node.type === 'ArrowFunctionExpression') return true;\n const isFunctionOrClass = [\n 'FunctionExpression',\n 'FunctionDeclaration',\n 'ClassExpression',\n 'ClassDeclaration',\n ].includes(node.type);\n return isFunctionOrClass && !(node as ClassDeclarationNode).id;\n}\n\nfunction handleNamedExport(node: ExportNamedNode, ctx: TransformContext, state: TransformState): void {\n const decl = node.declaration;\n\n // ---- Manually wrapped class export ----\n // `export const MyDO = instrumentDurableObjectWithSentry(...)` — count it\n // as wrapped so the plugin doesn't warn about it, but leave it alone.\n if (decl?.type === 'VariableDeclaration') {\n collectManuallyWrappedClassExports(decl, ctx, state);\n return;\n }\n\n // ---- Named class export matching a configured binding ----\n if (decl?.type === 'ClassDeclaration') {\n wrapInlineClassExport(node, decl, ctx, state);\n return;\n }\n\n // ---- Specifier export (`export { Foo as MyDO }`, `export { MyDO } from './do'`) ----\n wrapSpecifierExports(node, ctx, state);\n}\n\nfunction collectManuallyWrappedClassExports(\n varDecl: VariableDeclarationNode,\n ctx: TransformContext,\n state: TransformState,\n): void {\n for (const declarator of varDecl.declarations ?? []) {\n const name = declarator.id?.type === 'Identifier' ? declarator.id.name : undefined;\n const kind = name ? ctx.classWrappers.get(name) : undefined;\n if (!name || !kind || !declarator.init) continue;\n\n // A hand-wrapped Agent is configured as a Durable Object, so accept either helper there —\n // otherwise an already-instrumented Agent would be reported as unwrapped.\n const accepted =\n kind === 'durableObject' ? [WRAPPER_METHODS.durableObject, WRAPPER_METHODS.agent] : [WRAPPER_METHODS[kind]];\n\n if (accepted.some(method => isCallToMethod(declarator.init as BaseNode, method))) {\n state.wrappedClasses.add(name);\n }\n }\n}\n\nfunction wrapInlineClassExport(\n exportNode: ExportNamedNode,\n classDecl: ClassDeclarationNode,\n ctx: TransformContext,\n state: TransformState,\n): void {\n const classId = classDecl.id;\n // Inline export: the exported name and the local class name are the same.\n const kind = classId ? resolveWrapperKind(classId.name, classId.name, state) : undefined;\n if (!classId || !kind) return;\n\n const className = classId.name;\n\n // Strip the `export ` keyword\n state.ms.overwrite(exportNode.start, classDecl.start, '');\n\n const wrappedName = wrapLocalClass(className, classDecl, kind, state);\n state.ms.appendLeft(exportNode.end, `export { ${wrappedName} as ${className} };\\n`);\n\n state.wrappedClasses.add(className);\n state.autoWrapped.add(className);\n}\n\n/**\n * Wrap a class declared in this module and return the binding that holds the wrapper.\n *\n * The declaration is left exactly as written. Only the *export* has to become the wrapper, so the\n * wrapper gets its own binding and the export is aliased to it, the same shape as the documented\n * manual `instrument*WithSentry` pattern and the cross-module re-export path below. Renaming the\n * declaration instead (`class __SENTRY_ORIGINAL_MyAgent__`) would also rename what the class reports\n * as `Function.prototype.name`, which libraries read to identify the user's class: `@cloudflare/think`\n * hands `this.constructor.name` to the AI SDK as the telemetry `functionId`, and that surfaced as a\n * `gen_ai.invoke_agent __SENTRY_ORIGINAL_MyAgent__` span.\n */\nfunction wrapLocalClass(\n localName: string,\n localClass: ClassDeclarationNode,\n kind: ClassWrapperKind,\n state: TransformState,\n): string {\n const existing = state.wrappedLocals.get(localName);\n if (existing) return existing;\n\n const wrappedName = `__SENTRY_WRAPPED_${localName}__`;\n state.wrappedLocals.set(localName, wrappedName);\n state.ms.appendLeft(\n localClass.end,\n `\\nconst ${wrappedName} = __SENTRY__.${WRAPPER_METHODS[kind]}(${state.optionsFn}, ${localName});\\n`,\n );\n state.needsImport = true;\n return wrappedName;\n}\n\n/**\n * Wrap the configured classes an `export { ... }` statement names.\n *\n * Each such specifier is re-pointed at a binding holding the wrapper, which means rebuilding the\n * statement; specifiers this plugin has no business touching are carried over verbatim. For a class\n * declared in this module the wrapper binding follows the declaration (see {@link wrapLocalClass}).\n * A class that lives in **another** module — imported and re-exported, or re-exported directly — is\n * first bound under a private name, since an import binding cannot be reassigned and the `from` form\n * has no local binding at all.\n */\nfunction wrapSpecifierExports(node: ExportNamedNode, ctx: TransformContext, state: TransformState): void {\n const specifiers = node.specifiers ?? [];\n if (specifiers.length === 0) return;\n\n const sourceLiteral = node.source ? state.ms.original.slice(node.source.start, node.source.end) : undefined;\n\n const prelude: string[] = [];\n const wrappedPairs: string[] = [];\n const kept: string[] = [];\n\n for (const specifier of specifiers) {\n const pair = wrapSpecifier(specifier, sourceLiteral, ctx, state, prelude);\n if (pair) {\n wrappedPairs.push(pair);\n } else {\n kept.push(state.ms.original.slice(specifier.start, specifier.end));\n }\n }\n\n if (wrappedPairs.length === 0) return;\n\n const statements = [...prelude, `export { ${wrappedPairs.join(', ')} };`];\n if (kept.length > 0) {\n const clause = `export { ${kept.join(', ')} }`;\n statements.push(sourceLiteral ? `${clause} from ${sourceLiteral};` : `${clause};`);\n }\n state.ms.overwrite(node.start, node.end, statements.join('\\n'));\n}\n\n/**\n * `export { handler as default }`, the form bundlers emit for a default export. The export is set\n * in two steps. Right after `handler` is declared, it is bound to `handler` as-is, so a circular\n * import that reads it during module evaluation gets the handler, as before the transform. At the\n * end of the module, it is rebound to the wrapper, so a handler assigned or given methods later is\n * wrapped as it ends up. The binding is a `var`: a read before `handler` is declared gets\n * `undefined`, as it would from the bundler's own `var`, where a `const` would throw and stop the\n * Worker from starting.\n */\nfunction wrapDefaultSpecifier(localName: string, state: TransformState): string | undefined {\n if (state.manuallyWrappedLocals.has(localName)) return undefined;\n\n // Same as `export default Foo`: re-point at the wrapper a named export already made.\n const wrappedName = state.wrappedLocals.get(localName);\n if (wrappedName) {\n state.autoWrapped.add(DEFAULT_EXPORT);\n return `${wrappedName} as default`;\n }\n\n const declaringStatement = state.declaringStatements.get(localName);\n if (declaringStatement) {\n state.ms.appendLeft(declaringStatement.end, `\\nvar __SENTRY_DEFAULT_EXPORT__ = ${localName};`);\n }\n state.ms.append(\n `\\n${declaringStatement ? '' : 'var '}__SENTRY_DEFAULT_EXPORT__ = __SENTRY__.withSentry(${state.optionsFn}, ${localName});`,\n );\n state.needsImport = true;\n state.autoWrapped.add(DEFAULT_EXPORT);\n return '__SENTRY_DEFAULT_EXPORT__ as default';\n}\n\n/**\n * `export { default } from './handler'`. The handler may already be wrapped in its own module,\n * which this transform cannot see, so the emitted guard returns such a handler as-is.\n *\n * The original re-export is a live binding to the handler module's export, but the wrapper is not\n * set until this module's body runs. A circular import that reads the default export before then\n * gets `undefined` instead of the handler. The binding is a `var` so that the read does not throw,\n * as a `const` would, and stop the Worker from starting. See `wrapDefaultSpecifier`.\n */\nfunction wrapDefaultReexport(\n localName: string,\n sourceLiteral: string,\n state: TransformState,\n prelude: string[],\n): string {\n const target = '__SENTRY_REEXPORT_default__';\n prelude.push(\n localName === DEFAULT_IMPORT\n ? `import ${target} from ${sourceLiteral};`\n : `import { ${localName} as ${target} } from ${sourceLiteral};`,\n `var __SENTRY_DEFAULT_EXPORT__ = __SENTRY__._INTERNAL_wrapUnlessInstrumented(__SENTRY__.withSentry, ${state.optionsFn}, ${target});`,\n );\n state.needsImport = true;\n state.autoWrapped.add(DEFAULT_EXPORT);\n return '__SENTRY_DEFAULT_EXPORT__ as default';\n}\n\n/**\n * Handle one export specifier, returning the `Wrapped as Exported` pair to emit for a class that\n * gets wrapped. The import/wrapper statements a cross-module pair depends on are pushed onto\n * `prelude`; a local class's wrapper binding is emitted after its declaration instead.\n *\n * Returns `undefined` when the specifier can stay exactly as written: it doesn't name a configured\n * class, or the binding is already hand-wrapped.\n */\nfunction wrapSpecifier(\n specifier: ExportSpecifierNode,\n sourceLiteral: string | undefined,\n ctx: TransformContext,\n state: TransformState,\n prelude: string[],\n): string | undefined {\n const exportedName =\n specifier.type === 'ExportSpecifier' && specifier.exported?.type === 'Identifier'\n ? specifier.exported.name\n : undefined;\n const localName = specifier.local?.type === 'Identifier' ? specifier.local.name : undefined;\n // With a `from` clause the specifier names an export of the *source* module, not a binding here.\n const kind = exportedName\n ? resolveWrapperKind(exportedName, sourceLiteral ? undefined : localName, state)\n : undefined;\n\n if (!exportedName || !localName) return undefined;\n if (!kind) {\n if (exportedName !== DEFAULT_IMPORT) return undefined;\n return sourceLiteral\n ? wrapDefaultReexport(localName, sourceLiteral, state, prelude)\n : wrapDefaultSpecifier(localName, state);\n }\n\n // Without a `from` clause the specifier points at a module-local binding.\n if (!sourceLiteral) {\n const localClass = state.topLevelClasses.get(localName);\n\n if (localClass?.id) {\n const wrappedName = wrapLocalClass(localName, localClass, kind, state);\n state.wrappedClasses.add(exportedName);\n return `${wrappedName} as ${exportedName}`;\n }\n\n if (state.manuallyWrappedLocals.has(localName)) {\n state.wrappedClasses.add(exportedName);\n return undefined;\n }\n }\n\n // The class comes from another module: bind it under a private name (for the `from` form, which\n // has no local binding at all), wrap that, and export the wrapper under the configured name.\n let target = localName;\n\n if (sourceLiteral) {\n target = `__SENTRY_REEXPORT_${exportedName}__`;\n prelude.push(\n localName === DEFAULT_IMPORT\n ? `import ${target} from ${sourceLiteral};`\n : `import { ${localName} as ${target} } from ${sourceLiteral};`,\n );\n }\n\n const wrappedName = `__SENTRY_WRAPPED_${exportedName}__`;\n\n // The class may already be hand-wrapped in its own module, which this transform cannot see. The\n // emitted guard returns such a class as-is instead of nesting a second wrapper around it.\n prelude.push(\n `const ${wrappedName} = __SENTRY__._INTERNAL_wrapUnlessInstrumented(__SENTRY__.${WRAPPER_METHODS[kind]}, ${state.optionsFn}, ${target});`,\n );\n state.wrappedClasses.add(exportedName);\n state.autoWrapped.add(exportedName);\n state.needsImport = true;\n\n return `${wrappedName} as ${exportedName}`;\n}\n"],"mappings":";;;;;;AAKA,MAAM,4BAA4B;AA8DlC,SAAS,eAAe,MAAgB,YAA6B;CACnE,IAAI,KAAK,SAAS,kBAAkB,OAAO;CAC3C,MAAM,SAAU,KAA4B;CAC5C,IAAI,CAAC,QAAQ,OAAO;CACpB,IAAI,OAAO,SAAS,gBAAgB,OAAO,SAAS,YAAY,OAAO;CACvE,OACE,OAAO,SAAS,sBAAsB,OAAO,UAAU,SAAS,gBAAgB,OAAO,SAAS,SAAS;AAE7G;;AAgBA,MAAM,iBAAiB;;;;;;AAOvB,MAAM,kBAAoD;CACxD,eAAe;CACf,OAAO;CACP,UAAU;CACV,kBAAkB;AACpB;;;;;;;;;;;;;;;;;;AAmDA,SAAgB,8BACd,MACA,KACA,KAC6B;CAC7B,MAAM,KAAK,IAAIA,aAAAA,QAAY,IAAI;CAC/B,MAAM,kBAAkB,uBAAuB,GAAG;CAClD,MAAM,qBAAqB,IAAI,sBAAsB,CAAC;CACtD,MAAM,QAAwB;EAC5B;EACA,aAAa;EACb,gCAAgB,IAAI,IAAY;EAChC;EACA,+BAAe,IAAI,IAAoB;EACvC,eAAe,IAAI;EACnB,cAAc,IAAI,gCAAgB,IAAI,IAAY;EAClD,yBAAyBC,yBAAAA,8BAA8B,GAAG;EAE1D,WAAW,mBAAmB,SAAS,IAAI,4BAA4B,IAAI;EAC3E,6BAAa,IAAI,IAAgB;EACjC,uBAAuB,6BAA6B,GAAG;EACvD,qBAAqB,2BAA2B,GAAG;CACrD;CACA,MAAM,EAAE,mBAAmB;CAM3B,KAAK,MAAM,QAAQ,IAAI,MACrB,IAAI,KAAK,SAAS,0BAChB,kBAAkB,MAAM,KAAK,KAAK;CAGtC,KAAK,MAAM,QAAQ,IAAI,MACrB,IAAI,KAAK,SAAS,4BAChB,kBAAkB,MAA2B,KAAK,KAAK;CAI3D,IAAI,CAAC,MAAM,a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AAc,gBAAgB,KAAA,IAAY,WAAW,KAAK,IAC7E,KAAA;CAEJ,IAAI,CAAC,gBAAgB,CAAC,WAAW,OAAO,KAAA;CACxC,IAAI,CAAC,MAAM;EACT,IAAI,iBAAiB,gBAAgB,OAAO,KAAA;EAC5C,OAAO,gBACH,oBAAoB,WAAW,eAAe,OAAO,OAAO,IAC5D,qBAAqB,WAAW,KAAK;CAC3C;CAGA,IAAI,CAAC,eAAe;EAClB,MAAM,aAAa,MAAM,gBAAgB,IAAI,SAAS;EAEtD,IAAI,YAAY,IAAI;GAClB,MAAM,cAAc,eAAe,WAAW,YAAY,MAAM,KAAK;GACrE,MAAM,eAAe,IAAI,YAAY;GACrC,OAAO,GAAG,YAAY,MAAM;EAC9B;EAEA,IAAI,MAAM,sBAAsB,IAAI,SAAS,GAAG;GAC9C,MAAM,eAAe,IAAI,YAAY;GACrC;EACF;CACF;CAIA,IAAI,SAAS;CAEb,IAAI,eAAe;EACjB,SAAS,qBAAqB,aAAa;EAC3C,QAAQ,KACN,cAAc,iBACV,UAAU,OAAO,QAAQ,cAAc,KACvC,YAAY,UAAU,MAAM,OAAO,UAAU,cAAc,EACjE;CACF;CAEA,MAAM,cAAc,oBAAoB,aAAa;CAIrD,QAAQ,KACN,SAAS,YAAY,4DAA4D,gBAAgB,MAAM,IAAI,MAAM,UAAU,IAAI,OAAO,GACxI;CACA,MAAM,eAAe,IAAI,YAAY;CACrC,MAAM,YAAY,IAAI,YAAY;CAClC,MAAM,cAAc;CAEpB,OAAO,GAAG,YAAY,MAAM;AAC9B"}
1
+ {"version":3,"file":"transform.js","names":["MagicString","detectWorkerEntrypointClasses","stringifyForCodeInjection","DEFAULT_EXPORT"],"sources":["../../../../src/vite/transform.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport MagicString from 'magic-string';\nimport { DEFAULT_EXPORT, type ExportName, type SameWorkerBinding } from './wranglerConfig';\nimport { detectWorkerEntrypointClasses } from './workerEntrypoint';\nimport { stringifyForCodeInjection } from '@sentry/core';\n\nconst MERGED_OPTIONS_IDENTIFIER = '__SENTRY_OPTIONS__';\n\n// Read by `CloudflareClient` for the default `serverName` and the runtime version.\nconst WORKER_INFO_GLOBAL = '__SENTRY_CLOUDFLARE_WORKER__';\n\n// ---------------------------------------------------------------------------\n// Minimal ESTree node types for the AST nodes we inspect.\n// ---------------------------------------------------------------------------\n\nexport interface BaseNode {\n type: string;\n start: number;\n end: number;\n}\n\nexport interface ProgramBody {\n body: BaseNode[];\n}\n\ninterface IdentifierNode extends BaseNode {\n name: string;\n}\n\ninterface CalleeNode {\n type: string;\n name?: string;\n property?: { type: string; name?: string };\n}\n\ninterface CallExpressionNode extends BaseNode {\n callee?: CalleeNode;\n}\n\ninterface ClassDeclarationNode extends BaseNode {\n id?: IdentifierNode | null;\n}\n\ninterface ExportDefaultNode extends BaseNode {\n declaration: BaseNode;\n}\n\ninterface ExportSpecifierNode extends BaseNode {\n local?: { type: string; name?: string };\n exported?: { type: string; name?: string };\n}\n\ninterface ExportNamedNode extends BaseNode {\n declaration?: BaseNode | null;\n source?: BaseNode | null;\n specifiers?: ExportSpecifierNode[];\n}\n\ninterface VariableDeclaratorNode {\n id?: { type: string; name?: string };\n init?: BaseNode | null;\n}\n\ninterface VariableDeclarationNode extends BaseNode {\n declarations?: VariableDeclaratorNode[];\n}\n\ninterface ImportDeclarationNode extends BaseNode {\n specifiers?: Array<{ local?: { type: string; name?: string } }>;\n}\n\nfunction isCallToMethod(node: BaseNode, methodName: string): boolean {\n if (node.type !== 'CallExpression') return false;\n const callee = (node as CallExpressionNode).callee;\n if (!callee) return false;\n if (callee.type === 'Identifier' && callee.name === methodName) return true;\n return (\n callee.type === 'MemberExpression' && callee.property?.type === 'Identifier' && callee.property.name === methodName\n );\n}\n\n/**\n * The kind of Sentry wrapper to apply to an exported class.\n *\n * `durableObject` and `workflow` are keyed by name from the wrangler config\n * (`durable_objects.bindings`, `workflows`), since those class names are\n * authoritative there. `workerEntrypoint` is different: a worker's own\n * entrypoints aren't enumerated in its config, so they're detected structurally\n * (a class extending `WorkerEntrypoint` from `cloudflare:workers`), with the\n * config providing only a fallback for self-bound entrypoints whose base class\n * lives in another module.\n */\nexport type ClassWrapperKind = 'durableObject' | 'agent' | 'workflow' | 'workerEntrypoint';\n\n/** Specifier name a `export { default as X } from '...'` re-export uses for the source's default. */\nconst DEFAULT_IMPORT = 'default';\n\n/**\n * The `@sentry/cloudflare` helper each wrapper kind emits. All share the same\n * `(optionsCallback, Class)` signature. `WorkerEntrypoint` classes use\n * `withSentry`, which runtime-detects the class type and routes accordingly.\n */\nconst WRAPPER_METHODS: Record<ClassWrapperKind, string> = {\n durableObject: 'instrumentDurableObjectWithSentry',\n agent: 'instrumentAgentWithSentry',\n workflow: 'instrumentWorkflowWithSentry',\n workerEntrypoint: 'withSentry',\n};\n\nexport interface TransformContext {\n /**\n * Exported class name → the kind of Sentry wrapper to apply. Populated from\n * the wrangler config, so the transform can wrap by name without resolving\n * each class's base type.\n */\n classWrappers: Map<string, ClassWrapperKind>;\n /**\n * Local class names detected as `agents` Agents. An Agent is configured as a Durable Object in\n * wrangler, so this upgrades those entries from `durableObject` to `agent`.\n */\n agentClasses?: ReadonlySet<string>;\n optionsFn: string;\n /** Import statement prepended when `optionsFn` references a separate module. */\n optionsImport?: string;\n /** Module the generated code imports `withSentry` and the class wrappers from. Defaults to `@sentry/cloudflare`. */\n sentryModule?: string;\n /** @see {@link import('./wranglerConfig').WranglerConfig.sameWorkerBindings} */\n sameWorkerBindings?: readonly SameWorkerBinding[];\n /**\n * The Worker name and compatibility date, stored on `globalThis` as the default `serverName` and\n * the runtime version. The entry stores them also when nothing is wrapped, so hand-wrapped\n * handlers get them too.\n */\n workerInfo?: { name?: string; compatibilityDate?: string };\n}\n\nexport interface TransformResult {\n code: string;\n map: ReturnType<MagicString['generateMap']>;\n /**\n * The configured class names that were actually wrapped. Lets the plugin warn\n * about configured classes it could not find, instead of silently leaving\n * them uninstrumented.\n */\n wrappedClasses: Set<string>;\n}\n\n/**\n * Rewrite the worker entry source to wrap its default export with `withSentry`\n * and any configured class export with its matching Sentry wrapper (see\n * {@link TransformContext.classWrappers}, e.g. Durable Object classes with\n * `instrumentDurableObjectWithSentry`).\n *\n * Handles `export class MyDO {}`, the specifier form (`class MyDO {}` …\n * `export { MyDO }` / `export { Foo as MyDO }`), and classes that live in\n * another module (`import { MyDO } from './do'; export { MyDO }` or\n * `export { MyDO } from './do'`). Only star re-exports (`export * from './do'`)\n * are left alone — the plugin warns about those via\n * {@link TransformResult.wrappedClasses}.\n *\n * Exported (rather than inlined into the plugin) so it can be unit-tested with a\n * plain AST and no Vite context. Returns `undefined` when nothing was wrapped,\n * there are no already-manually-wrapped classes to report, and there is no\n * {@link TransformContext.workerInfo} to store.\n */\nexport function applyAutoInstrumentTransforms(\n code: string,\n ast: ProgramBody,\n ctx: TransformContext,\n): TransformResult | undefined {\n const ms = new MagicString(code);\n const topLevelClasses = collectTopLevelClasses(ast);\n const sameWorkerBindings = ctx.sameWorkerBindings ?? [];\n const state: TransformState = {\n ms,\n needsImport: false,\n wrappedClasses: new Set<string>(),\n topLevelClasses,\n wrappedLocals: new Map<string, string>(),\n classWrappers: ctx.classWrappers,\n agentClasses: ctx.agentClasses ?? new Set<string>(),\n workerEntrypointClasses: detectWorkerEntrypointClasses(ast),\n // The identifier must be chosen before wrapping, which bindings survive is only known after.\n optionsFn: sameWorkerBindings.length > 0 ? MERGED_OPTIONS_IDENTIFIER : ctx.optionsFn,\n autoWrapped: new Set<ExportName>(),\n manuallyWrappedLocals: collectManuallyWrappedLocals(ast),\n declaringStatements: collectDeclaringStatements(ast),\n };\n const { wrappedClasses } = state;\n\n // Named exports first, regardless of source order: the default-export handler\n // needs to know which local bindings a named export already wrapped, so it can\n // skip a class that is both exported by name and re-exported as default (which\n // would otherwise wrap it twice).\n for (const node of ast.body) {\n if (node.type === 'ExportNamedDeclaration') {\n handleNamedExport(node, ctx, state);\n }\n }\n for (const node of ast.body) {\n if (node.type === 'ExportDefaultDeclaration') {\n wrapDefaultExport(node as ExportDefaultNode, ctx, state);\n }\n }\n\n if (state.needsImport) {\n // `prepend` inserts before earlier prepends, yielding: Sentry import, options import, declaration.\n if (sameWorkerBindings.length > 0) {\n ms.prepend(buildMergedOptionsDeclaration(sameWorkerBindings, ctx.optionsFn, state));\n }\n if (ctx.optionsImport) ms.prepend(ctx.optionsImport);\n ms.prepend(`import * as __SENTRY__ from '${ctx.sentryModule ?? '@sentry/cloudflare'}';\\n`);\n }\n\n if (ctx.workerInfo?.name || ctx.workerInfo?.compatibilityDate) {\n ms.prepend(`globalThis.${WORKER_INFO_GLOBAL} = ${JSON.stringify(ctx.workerInfo)};\\n`);\n } else if (!state.needsImport && wrappedClasses.size === 0) {\n // Nothing was rewritten. Classes found already wrapped manually are still\n // reported (via `wrappedClasses`) so the caller doesn't warn about them.\n return undefined;\n }\n\n return {\n code: ms.toString(),\n map: ms.generateMap({ hires: true }),\n wrappedClasses,\n };\n}\n\ninterface TransformState {\n ms: MagicString;\n needsImport: boolean;\n wrappedClasses: Set<string>;\n /**\n * Top-level class declarations, exported or not, so specifier exports like\n * `export { MyDO }` can locate the class they refer to.\n */\n topLevelClasses: Map<string, ClassDeclarationNode>;\n /**\n * Local class name → the binding holding its wrapper, so two exports of the same class share one\n * wrapper and a default export of it can be re-pointed.\n */\n wrappedLocals: Map<string, string>;\n /** Class name → wrapper kind, keyed by the *exported* name (from config). */\n classWrappers: Map<string, ClassWrapperKind>;\n /** Local class names detected as `agents` Agents (see {@link TransformContext.agentClasses}). */\n agentClasses: ReadonlySet<string>;\n /**\n * Local class names detected as `WorkerEntrypoint` subclasses in this module,\n * so they can be wrapped without a config entry.\n */\n workerEntrypointClasses: Set<string>;\n optionsFn: string;\n /**\n * Export names wrapped by this transform, so their options can be extended with\n * `rpcTracePropagationBindings`. Hand-wrapped exports stay out, they keep the options they were\n * wrapped with. `wrappedClasses` counts both.\n */\n autoWrapped: Set<ExportName>;\n /**\n * Top-level bindings already assigned an `instrument*WithSentry(...)` result\n * (`const MyDO = instrumentDurableObjectWithSentry(...)`). Exporting one by\n * specifier must report it as wrapped rather than wrap it a second time.\n */\n manuallyWrappedLocals: Set<string>;\n /** Top-level binding name → the statement that declares it. */\n declaringStatements: Map<string, BaseNode>;\n}\n\n/**\n * Builds the callback that merges same-worker binding names into `rpcTracePropagationBindings` at\n * runtime, the options object only exists once the callback runs with `env`. Only bindings whose\n * class this transform wrapped survive, a hand-wrapped class runs on its own options.\n */\nfunction buildMergedOptionsDeclaration(\n sameWorkerBindings: readonly SameWorkerBinding[],\n optionsFn: string,\n state: TransformState,\n): string {\n const bindingNames = sameWorkerBindings\n .filter(({ className }) => state.autoWrapped.has(className))\n .map(({ bindingName }) => bindingName);\n\n if (!bindingNames.length) {\n return `const ${MERGED_OPTIONS_IDENTIFIER} = ${optionsFn};\\n`;\n }\n\n const names = bindingNames.map(name => stringifyForCodeInjection(name)).join(', ');\n return (\n `const ${MERGED_OPTIONS_IDENTIFIER} = (env) => { ` +\n `const opts = (${optionsFn})(env); ` +\n `return { ...opts, rpcTracePropagationBindings: [${names}, ...(opts?.rpcTracePropagationBindings ?? [])] }; };\\n`\n );\n}\n\n/**\n * Resolve the wrapper kind for a class export.\n *\n * Config (`classWrappers`) wins — it's authoritative for Durable Objects and\n * Workflows, and provides the self-binding fallback for WorkerEntrypoints whose\n * base class this module can't see. Otherwise a structurally-detected\n * `WorkerEntrypoint` subclass (matched by its *local* name) gets wrapped with\n * `withSentry`.\n *\n * `localName` is the binding **in this module** the export refers to, and must be\n * left undefined for `export { X } from '...'`: there the specifier's name belongs\n * to the source module, so matching it against anything detected here would wrap a\n * class that merely shares a name.\n *\n * The one case where config is refined rather than obeyed is an `agents` Agent:\n * it *is* a Durable Object, so wrangler can only ever describe it as one, and\n * only the detected base chain distinguishes the two.\n */\nfunction resolveWrapperKind(\n exportedName: string,\n localName: string | undefined,\n state: TransformState,\n): ClassWrapperKind | undefined {\n const configured = state.classWrappers.get(exportedName);\n\n if (\n configured === 'durableObject' &&\n ((localName && state.agentClasses.has(localName)) || state.agentClasses.has(exportedName))\n ) {\n return 'agent';\n }\n\n if (configured) return configured;\n if (localName && state.workerEntrypointClasses.has(localName)) return 'workerEntrypoint';\n return undefined;\n}\n\n/**\n * Top-level `const X = instrument*WithSentry(...)` bindings — a hand-wrapped class that is exported\n * separately (`export { X }`) rather than inline.\n */\nfunction collectManuallyWrappedLocals(ast: ProgramBody): Set<string> {\n const wrapperMethods = Object.values(WRAPPER_METHODS);\n const locals = new Set<string>();\n\n for (const node of ast.body) {\n const declaration = declarationOf(node);\n if (declaration?.type !== 'VariableDeclaration') continue;\n for (const declarator of (declaration as VariableDeclarationNode).declarations ?? []) {\n const name = declarator.id?.type === 'Identifier' ? declarator.id.name : undefined;\n const init = declarator.init;\n if (name && init && wrapperMethods.some(method => isCallToMethod(init, method))) {\n locals.add(name);\n }\n }\n }\n\n return locals;\n}\n\nfunction collectDeclaringStatements(ast: ProgramBody): Map<string, BaseNode> {\n const statements = new Map<string, BaseNode>();\n for (const node of ast.body) {\n const declaration = declarationOf(node);\n if (!declaration) continue;\n const ids =\n declaration.type === 'VariableDeclaration'\n ? ((declaration as VariableDeclarationNode).declarations ?? []).map(declarator => declarator.id)\n : declaration.type === 'ImportDeclaration'\n ? ((declaration as ImportDeclarationNode).specifiers ?? []).map(specifier => specifier.local)\n : [(declaration as ClassDeclarationNode).id];\n for (const id of ids) {\n if (id?.type === 'Identifier' && id.name) statements.set(id.name, node);\n }\n }\n return statements;\n}\n\nfunction collectTopLevelClasses(ast: ProgramBody): Map<string, ClassDeclarationNode> {\n const classes = new Map<string, ClassDeclarationNode>();\n for (const node of ast.body) {\n const declaration = declarationOf(node);\n if (declaration?.type !== 'ClassDeclaration') continue;\n const classNode = declaration as ClassDeclarationNode;\n if (classNode.id?.name) classes.set(classNode.id.name, classNode);\n }\n return classes;\n}\n\n/** The declaration a top-level statement makes, looking through `export` (`export const x = ...`). */\nfunction declarationOf(node: BaseNode): BaseNode | null | undefined {\n return node.type === 'ExportNamedDeclaration' ? (node as ExportNamedNode).declaration : node;\n}\n\nfunction wrapDefaultExport(node: ExportDefaultNode, ctx: TransformContext, state: TransformState): void {\n const decl = node.declaration;\n\n // Already wrapped — leave it alone\n if (isCallToMethod(decl, 'withSentry')) return;\n\n // `export default Foo` where `Foo` is a local class already wrapped by a named\n // export (e.g. a self-bound WorkerEntrypoint also used as the default handler).\n // Wrapping again would produce `withSentry(withSentry(...))`, so the default\n // export is re-pointed at the wrapper binding the named export created.\n if (decl.type === 'Identifier') {\n const wrappedName = state.wrappedLocals.get((decl as IdentifierNode).name);\n if (wrappedName) {\n state.ms.overwrite(decl.start, decl.end, wrappedName);\n state.autoWrapped.add(DEFAULT_EXPORT);\n return;\n }\n }\n\n // MagicString positions are always relative to the original source. Only the `export default`\n // keywords are replaced, so parentheses around the expression stay.\n const source = state.ms.original;\n const keywordsEnd = exportDefaultKeywordsEnd(source, node.start);\n const declaredName =\n decl.type === 'ClassDeclaration' || decl.type === 'FunctionDeclaration'\n ? (decl as ClassDeclarationNode).id?.name\n : undefined;\n\n // As with `export { handler as default }`, the export is set in two steps: bound as-is where the\n // original statement set it, then rebound at the end of the module to the wrapper, which sees\n // methods added in between. See `wrapDefaultSpecifier`.\n let wrapped = '__SENTRY_DEFAULT_EXPORT__';\n if (declaredName) {\n // `export default class Handler {}`: the declaration stays, so `Handler` stays bound in the module.\n state.ms.remove(node.start, decl.start);\n state.ms.appendLeft(node.end, `\\nvar __SENTRY_DEFAULT_EXPORT__ = ${declaredName};`);\n wrapped = declaredName;\n } else if (isAnonymousFunctionOrClass(decl)) {\n // As a property value, the class or function gets the name `default`, as `export default` gives it.\n const hasSemicolon = source[node.end - 1] === ';';\n state.ms.overwrite(node.start, keywordsEnd, 'var __SENTRY_DEFAULT_EXPORT__ = { default:');\n state.ms.appendLeft(hasSemicolon ? node.end - 1 : node.end, hasSemicolon ? ' }.default' : ' }.default;');\n } else {\n state.ms.overwrite(node.start, keywordsEnd, 'var __SENTRY_DEFAULT_EXPORT__ =');\n }\n state.ms.appendLeft(node.end, '\\nexport { __SENTRY_DEFAULT_EXPORT__ as default };');\n state.ms.append(`\\n__SENTRY_DEFAULT_EXPORT__ = __SENTRY__.withSentry(${state.optionsFn}, ${wrapped});`);\n state.needsImport = true;\n state.autoWrapped.add(DEFAULT_EXPORT);\n}\n\n/**\n * Offset just past the `default` keyword of the `export default` statement at `start`. Comments can\n * sit between `export`, `default` and the expression, and may themselves contain the word `default`.\n */\nfunction exportDefaultKeywordsEnd(source: string, start: number): number {\n let index = start + 'export'.length;\n while (index < source.length && !source.startsWith('default', index)) {\n if (source.startsWith('//', index)) {\n const lineEnd = source.indexOf('\\n', index);\n index = lineEnd === -1 ? source.length : lineEnd;\n } else if (source.startsWith('/*', index)) {\n const commentEnd = source.indexOf('*/', index + 2);\n index = commentEnd === -1 ? source.length : commentEnd + 2;\n } else {\n index++;\n }\n }\n return index + 'default'.length;\n}\n\nfunction isAnonymousFunctionOrClass(node: BaseNode): boolean {\n if (node.type === 'ArrowFunctionExpression') return true;\n const isFunctionOrClass = [\n 'FunctionExpression',\n 'FunctionDeclaration',\n 'ClassExpression',\n 'ClassDeclaration',\n ].includes(node.type);\n return isFunctionOrClass && !(node as ClassDeclarationNode).id;\n}\n\nfunction handleNamedExport(node: ExportNamedNode, ctx: TransformContext, state: TransformState): void {\n const decl = node.declaration;\n\n // ---- Manually wrapped class export ----\n // `export const MyDO = instrumentDurableObjectWithSentry(...)` — count it\n // as wrapped so the plugin doesn't warn about it, but leave it alone.\n if (decl?.type === 'VariableDeclaration') {\n collectManuallyWrappedClassExports(decl, ctx, state);\n return;\n }\n\n // ---- Named class export matching a configured binding ----\n if (decl?.type === 'ClassDeclaration') {\n wrapInlineClassExport(node, decl, ctx, state);\n return;\n }\n\n // ---- Specifier export (`export { Foo as MyDO }`, `export { MyDO } from './do'`) ----\n wrapSpecifierExports(node, ctx, state);\n}\n\nfunction collectManuallyWrappedClassExports(\n varDecl: VariableDeclarationNode,\n ctx: TransformContext,\n state: TransformState,\n): void {\n for (const declarator of varDecl.declarations ?? []) {\n const name = declarator.id?.type === 'Identifier' ? declarator.id.name : undefined;\n const kind = name ? ctx.classWrappers.get(name) : undefined;\n if (!name || !kind || !declarator.init) continue;\n\n // A hand-wrapped Agent is configured as a Durable Object, so accept either helper there —\n // otherwise an already-instrumented Agent would be reported as unwrapped.\n const accepted =\n kind === 'durableObject' ? [WRAPPER_METHODS.durableObject, WRAPPER_METHODS.agent] : [WRAPPER_METHODS[kind]];\n\n if (accepted.some(method => isCallToMethod(declarator.init as BaseNode, method))) {\n state.wrappedClasses.add(name);\n }\n }\n}\n\nfunction wrapInlineClassExport(\n exportNode: ExportNamedNode,\n classDecl: ClassDeclarationNode,\n ctx: TransformContext,\n state: TransformState,\n): void {\n const classId = classDecl.id;\n // Inline export: the exported name and the local class name are the same.\n const kind = classId ? resolveWrapperKind(classId.name, classId.name, state) : undefined;\n if (!classId || !kind) return;\n\n const className = classId.name;\n\n // Strip the `export ` keyword\n state.ms.overwrite(exportNode.start, classDecl.start, '');\n\n const wrappedName = wrapLocalClass(className, classDecl, kind, state);\n state.ms.appendLeft(exportNode.end, `export { ${wrappedName} as ${className} };\\n`);\n\n state.wrappedClasses.add(className);\n state.autoWrapped.add(className);\n}\n\n/**\n * Wrap a class declared in this module and return the binding that holds the wrapper.\n *\n * The declaration is left exactly as written. Only the *export* has to become the wrapper, so the\n * wrapper gets its own binding and the export is aliased to it, the same shape as the documented\n * manual `instrument*WithSentry` pattern and the cross-module re-export path below. Renaming the\n * declaration instead (`class __SENTRY_ORIGINAL_MyAgent__`) would also rename what the class reports\n * as `Function.prototype.name`, which libraries read to identify the user's class: `@cloudflare/think`\n * hands `this.constructor.name` to the AI SDK as the telemetry `functionId`, and that surfaced as a\n * `gen_ai.invoke_agent __SENTRY_ORIGINAL_MyAgent__` span.\n */\nfunction wrapLocalClass(\n localName: string,\n localClass: ClassDeclarationNode,\n kind: ClassWrapperKind,\n state: TransformState,\n): string {\n const existing = state.wrappedLocals.get(localName);\n if (existing) return existing;\n\n const wrappedName = `__SENTRY_WRAPPED_${localName}__`;\n state.wrappedLocals.set(localName, wrappedName);\n state.ms.appendLeft(\n localClass.end,\n `\\nconst ${wrappedName} = __SENTRY__.${WRAPPER_METHODS[kind]}(${state.optionsFn}, ${localName});\\n`,\n );\n state.needsImport = true;\n return wrappedName;\n}\n\n/**\n * Wrap the configured classes an `export { ... }` statement names.\n *\n * Each such specifier is re-pointed at a binding holding the wrapper, which means rebuilding the\n * statement; specifiers this plugin has no business touching are carried over verbatim. For a class\n * declared in this module the wrapper binding follows the declaration (see {@link wrapLocalClass}).\n * A class that lives in **another** module — imported and re-exported, or re-exported directly — is\n * first bound under a private name, since an import binding cannot be reassigned and the `from` form\n * has no local binding at all.\n */\nfunction wrapSpecifierExports(node: ExportNamedNode, ctx: TransformContext, state: TransformState): void {\n const specifiers = node.specifiers ?? [];\n if (specifiers.length === 0) return;\n\n const sourceLiteral = node.source ? state.ms.original.slice(node.source.start, node.source.end) : undefined;\n\n const prelude: string[] = [];\n const wrappedPairs: string[] = [];\n const kept: string[] = [];\n\n for (const specifier of specifiers) {\n const pair = wrapSpecifier(specifier, sourceLiteral, ctx, state, prelude);\n if (pair) {\n wrappedPairs.push(pair);\n } else {\n kept.push(state.ms.original.slice(specifier.start, specifier.end));\n }\n }\n\n if (wrappedPairs.length === 0) return;\n\n const statements = [...prelude, `export { ${wrappedPairs.join(', ')} };`];\n if (kept.length > 0) {\n const clause = `export { ${kept.join(', ')} }`;\n statements.push(sourceLiteral ? `${clause} from ${sourceLiteral};` : `${clause};`);\n }\n state.ms.overwrite(node.start, node.end, statements.join('\\n'));\n}\n\n/**\n * `export { handler as default }`, the form bundlers emit for a default export. The export is set\n * in two steps. Right after `handler` is declared, it is bound to `handler` as-is, so a circular\n * import that reads it during module evaluation gets the handler, as before the transform. At the\n * end of the module, it is rebound to the wrapper, so a handler assigned or given methods later is\n * wrapped as it ends up. The binding is a `var`: a read before `handler` is declared gets\n * `undefined`, as it would from the bundler's own `var`, where a `const` would throw and stop the\n * Worker from starting.\n */\nfunction wrapDefaultSpecifier(localName: string, state: TransformState): string | undefined {\n if (state.manuallyWrappedLocals.has(localName)) return undefined;\n\n // Same as `export default Foo`: re-point at the wrapper a named export already made.\n const wrappedName = state.wrappedLocals.get(localName);\n if (wrappedName) {\n state.autoWrapped.add(DEFAULT_EXPORT);\n return `${wrappedName} as default`;\n }\n\n const declaringStatement = state.declaringStatements.get(localName);\n if (declaringStatement) {\n state.ms.appendLeft(declaringStatement.end, `\\nvar __SENTRY_DEFAULT_EXPORT__ = ${localName};`);\n }\n state.ms.append(\n `\\n${declaringStatement ? '' : 'var '}__SENTRY_DEFAULT_EXPORT__ = __SENTRY__.withSentry(${state.optionsFn}, ${localName});`,\n );\n state.needsImport = true;\n state.autoWrapped.add(DEFAULT_EXPORT);\n return '__SENTRY_DEFAULT_EXPORT__ as default';\n}\n\n/**\n * `export { default } from './handler'`. The handler may already be wrapped in its own module,\n * which this transform cannot see, so the emitted guard returns such a handler as-is.\n *\n * The original re-export is a live binding to the handler module's export, but the wrapper is not\n * set until this module's body runs. A circular import that reads the default export before then\n * gets `undefined` instead of the handler. The binding is a `var` so that the read does not throw,\n * as a `const` would, and stop the Worker from starting. See `wrapDefaultSpecifier`.\n */\nfunction wrapDefaultReexport(\n localName: string,\n sourceLiteral: string,\n state: TransformState,\n prelude: string[],\n): string {\n const target = '__SENTRY_REEXPORT_default__';\n prelude.push(\n localName === DEFAULT_IMPORT\n ? `import ${target} from ${sourceLiteral};`\n : `import { ${localName} as ${target} } from ${sourceLiteral};`,\n `var __SENTRY_DEFAULT_EXPORT__ = __SENTRY__._INTERNAL_wrapUnlessInstrumented(__SENTRY__.withSentry, ${state.optionsFn}, ${target});`,\n );\n state.needsImport = true;\n state.autoWrapped.add(DEFAULT_EXPORT);\n return '__SENTRY_DEFAULT_EXPORT__ as default';\n}\n\n/**\n * Handle one export specifier, returning the `Wrapped as Exported` pair to emit for a class that\n * gets wrapped. The import/wrapper statements a cross-module pair depends on are pushed onto\n * `prelude`; a local class's wrapper binding is emitted after its declaration instead.\n *\n * Returns `undefined` when the specifier can stay exactly as written: it doesn't name a configured\n * class, or the binding is already hand-wrapped.\n */\nfunction wrapSpecifier(\n specifier: ExportSpecifierNode,\n sourceLiteral: string | undefined,\n ctx: TransformContext,\n state: TransformState,\n prelude: string[],\n): string | undefined {\n const exportedName =\n specifier.type === 'ExportSpecifier' && specifier.exported?.type === 'Identifier'\n ? specifier.exported.name\n : undefined;\n const localName = specifier.local?.type === 'Identifier' ? specifier.local.name : undefined;\n // With a `from` clause the specifier names an export of the *source* module, not a binding here.\n const kind = exportedName\n ? resolveWrapperKind(exportedName, sourceLiteral ? undefined : localName, state)\n : undefined;\n\n if (!exportedName || !localName) return undefined;\n if (!kind) {\n if (exportedName !== DEFAULT_IMPORT) return undefined;\n return sourceLiteral\n ? wrapDefaultReexport(localName, sourceLiteral, state, prelude)\n : wrapDefaultSpecifier(localName, state);\n }\n\n // Without a `from` clause the specifier points at a module-local binding.\n if (!sourceLiteral) {\n const localClass = state.topLevelClasses.get(localName);\n\n if (localClass?.id) {\n const wrappedName = wrapLocalClass(localName, localClass, kind, state);\n state.wrappedClasses.add(exportedName);\n return `${wrappedName} as ${exportedName}`;\n }\n\n if (state.manuallyWrappedLocals.has(localName)) {\n state.wrappedClasses.add(exportedName);\n return undefined;\n }\n }\n\n // The class comes from another module: bind it under a private name (for the `from` form, which\n // has no local binding at all), wrap that, and export the wrapper under the configured name.\n let target = localName;\n\n if (sourceLiteral) {\n target = `__SENTRY_REEXPORT_${exportedName}__`;\n prelude.push(\n localName === DEFAULT_IMPORT\n ? `import ${target} from ${sourceLiteral};`\n : `import { ${localName} as ${target} } from ${sourceLiteral};`,\n );\n }\n\n const wrappedName = `__SENTRY_WRAPPED_${exportedName}__`;\n\n // The class may already be hand-wrapped in its own module, which this transform cannot see. The\n // emitted guard returns such a class as-is instead of nesting a second wrapper around it.\n prelude.push(\n `const ${wrappedName} = __SENTRY__._INTERNAL_wrapUnlessInstrumented(__SENTRY__.${WRAPPER_METHODS[kind]}, ${state.optionsFn}, ${target});`,\n );\n state.wrappedClasses.add(exportedName);\n state.autoWrapped.add(exportedName);\n state.needsImport = true;\n\n return `${wrappedName} as ${exportedName}`;\n}\n"],"mappings":";;;;;;;AAMA,MAAM,4BAA4B;AAGlC,MAAM,qBAAqB;AA8D3B,SAAS,eAAe,MAAgB,YAA6B;CACnE,IAAI,KAAK,SAAS,kBAAkB,OAAO;CAC3C,MAAM,SAAU,KAA4B;CAC5C,IAAI,CAAC,QAAQ,OAAO;CACpB,IAAI,OAAO,SAAS,gBAAgB,OAAO,SAAS,YAAY,OAAO;CACvE,OACE,OAAO,SAAS,sBAAsB,OAAO,UAAU,SAAS,gBAAgB,OAAO,SAAS,SAAS;AAE7G;;AAgBA,MAAM,iBAAiB;;;;;;AAOvB,MAAM,kBAAoD;CACxD,eAAe;CACf,OAAO;CACP,UAAU;CACV,kBAAkB;AACpB;;;;;;;;;;;;;;;;;;;AA0DA,SAAgB,8BACd,MACA,KACA,KAC6B;CAC7B,MAAM,KAAK,IAAIA,aAAAA,QAAY,IAAI;CAC/B,MAAM,kBAAkB,uBAAuB,GAAG;CAClD,MAAM,qBAAqB,IAAI,sBAAsB,CAAC;CACtD,MAAM,QAAwB;EAC5B;EACA,aAAa;EACb,gCAAgB,IAAI,IAAY;EAChC;EACA,+BAAe,IAAI,IAAoB;EACvC,eAAe,IAAI;EACnB,cAAc,IAAI,gCAAgB,IAAI,IAAY;EAClD,yBAAyBC,yBAAAA,8BAA8B,GAAG;EAE1D,WAAW,mBAAmB,SAAS,IAAI,4BAA4B,IAAI;EAC3E,6BAAa,IAAI,IAAgB;EACjC,uBAAuB,6BAA6B,GAAG;EACvD,qBAAqB,2BAA2B,GAAG;CACrD;CACA,MAAM,EAAE,mBAAmB;CAM3B,KAAK,MAAM,QAA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 function resolveWranglerConfig(root, explicitPath) {
40
40
  const configDir = (0, node_path.dirname)(resolvedConfigPath);
41
41
  return {
42
42
  config: {
43
+ name: raw.name,
44
+ compatibilityDate: raw.compatibility_date,
43
45
  main: raw.main && ENTRY_FILE_REGEX.test(raw.main) ? (0, node_path.resolve)(configDir, raw.main) : raw.main,
44
46
  durableObjects: collectClassBindings(raw.durable_objects?.bindings),
45
47
  workflows: collectClassBindings(raw.workflows),
@@ -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":";;;;AA+BA,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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AM,WAAW,QAAQ;CAAW,CAAC;CAI9E,KAAK,MAAM,WAAW,IAAI,YAAY,CAAC,GAErC,IAAI,IAAI,QAAQ,SAAS,YAAY,IAAI,QAAQ,OAAO,QAAQ,YAAY,UAC1E,SAAS,KAAK;EACZ,aAAa,QAAQ;EACrB,WAAW,OAAO,QAAQ,eAAe,WAAW,QAAQ,aAAa;CAC3E,CAAC;CAIL,OAAO;AACT;;;;;;;AAQA,SAAS,qBACP,UAC4C;CAC5C,MAAM,SAAqD,CAAC;CAC5D,MAAM,iCAAiB,IAAI,IAAY;CACvC,KAAK,MAAM,WAAW,YAAY,CAAC,GAAG;EACpC,IAAI,OAAO,SAAS,eAAe,YAAY,QAAQ,eAAe,eAAe,IAAI,QAAQ,UAAU,GACzG;EAEF,eAAe,IAAI,QAAQ,UAAU;EACrC,OAAO,KAAK;GAAE,MAAM,QAAQ;GAAM,WAAW,QAAQ;EAAW,CAAC;CACnE;CACA,OAAO;AACT"}
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,IAAI,IAAI,IAAI,IAAI;GACvF,gBAAgB,qBAAqB,IAAI,iBAAiB,QAAQ;GAClE,WAAW,qBAAqB,IAAI,SAAS;GAC7C,mBAAmB,4BAA4B,GAAG;GAClD,oBAAoB,0BAA0B,GAAG;EACnD;EACA,YAAY;EACZ;CACF;AACF;;;;;;;AAQA,SAAS,4BAA4B,KAAgC;CACnE,IAAI,CAAC,IAAI,MACP,OAAO,CAAC;CAEV,MAAM,8BAAc,IAAI,IAAY;CACpC,KAAK,MAAM,WAAW,IAAI,YAAY,CAAC,GACrC,IAAI,SAAS,YAAY,IAAI,QAAQ,OAAO,QAAQ,eAAe,UACjE,YAAY,IAAI,QAAQ,UAAU;CAGtC,OAAO,CAAC,GAAG,WAAW;AACxB;;;;;AAMA,SAAS,0BAA0B,KAA2C;CAC5E,MAAM,WAAgC,CAAC;CAEvC,KAAK,MAAM,WAAW,IAAI,iBAAiB,YAAY,CAAC,GACtD,IAAI,OAAO,SAAS,SAAS,YAAY,OAAO,QAAQ,eAAe,YAAY,CAAC,QAAQ,aAC1F,SAAS,KAAK;EAAE,aAAa,QAAQ;EAAM,WAAW,QAAQ;CAAW,CAAC;CAI9E,KAAK,MAAM,WAAW,IAAI,YAAY,CAAC,GAErC,IAAI,IAAI,QAAQ,SAAS,YAAY,IAAI,QAAQ,OAAO,QAAQ,YAAY,UAC1E,SAAS,KAAK;EACZ,aAAa,QAAQ;EACrB,WAAW,OAAO,QAAQ,eAAe,WAAW,QAAQ,aAAa;CAC3E,CAAC;CAIL,OAAO;AACT;;;;;;;AAQA,SAAS,qBACP,UAC4C;CAC5C,MAAM,SAAqD,CAAC;CAC5D,MAAM,iCAAiB,IAAI,IAAY;CACvC,KAAK,MAAM,WAAW,YAAY,CAAC,GAAG;EACpC,IAAI,OAAO,SAAS,eAAe,YAAY,QAAQ,eAAe,eAAe,IAAI,QAAQ,UAAU,GACzG;EAEF,eAAe,IAAI,QAAQ,UAAU;EACrC,OAAO,KAAK;GAAE,MAAM,QAAQ;GAAM,WAAW,QAAQ;EAAW,CAAC;CACnE;CACA,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"baseSdk.js","names":["GLOBAL_OBJ","dedupeIntegration","eventFiltersIntegration","functionToStringIntegration","conversationIdIntegration","linkedErrorsIntegration","fetchIntegration","httpServerIntegration","requestDataIntegration","consoleIntegration","getCachedClient","_INTERNAL_isClientClosed","DEBUG_BUILD","debug","getCurrentScope","setCurrentClient","makeFlushLock","stackParserFromStackParserOptions","defaultStackParser","getIntegrationsToSetup","makeCloudflareTransport","initAndBind","CloudflareClient","cacheClient","safeCallback"],"sources":["../../../src/baseSdk.ts"],"sourcesContent":["import type { Integration } from '@sentry/core';\nimport { _INTERNAL_isClientClosed, debug, getCurrentScope, safeCallback, setCurrentClient } from '@sentry/core';\nimport {\n consoleIntegration,\n conversationIdIntegration,\n dedupeIntegration,\n eventFiltersIntegration,\n functionToStringIntegration,\n getIntegrationsToSetup,\n GLOBAL_OBJ,\n initAndBind,\n linkedErrorsIntegration,\n requestDataIntegration,\n stackParserFromStackParserOptions,\n} from '@sentry/core';\nimport type { CloudflareClientOptions, CloudflareOptions } from './client';\nimport { CloudflareClient } from './client';\nimport { makeFlushLock } from './flush';\nimport { cacheClient, getCachedClient } from './clientCache';\nimport { DEBUG_BUILD } from './debug-build';\nimport { fetchIntegration } from './integrations/fetch';\nimport { httpServerIntegration } from './integrations/httpServer';\nimport { INTEGRATION_NAME as SPOTLIGHT_INTEGRATION_NAME, spotlightIntegration } from './integrations/spotlight';\nimport { makeCloudflareTransport } from './transport';\nimport { defaultStackParser } from './vendor/stacktrace';\n\n/**\n * Instantiate the channel-subscriber factories the `@sentry/cloudflare/vite`\n * plugin registered on the global marker. The plugin splices a small snippet\n * into each instrumented module that `.set`s its factory here (keyed by module\n * name), so the marker holds one factory per package actually bundled.\n *\n * The marker is read directly instead of importing the factories, so a worker\n * built without the plugin — where the channels never fire — ships none of this\n * code.\n */\nfunction getRegisteredChannelIntegrations(): Integration[] {\n const registered = GLOBAL_OBJ.__SENTRY_ORCHESTRION__?.integrations;\n\n return registered ? [...registered.values()].map(factory => factory()) : [];\n}\n\n/**\n * Get the default integrations for the Cloudflare SDK.\n * These also work on Workers-compatible runtimes without the `nodejs_compat` compatibility flag.\n */\nexport function getDefaultIntegrations(options: CloudflareOptions): Integration[] {\n return [\n // The Dedupe integration should not be used in workflows because we want to\n // capture all step failures, even if they are the same error.\n ...(options.enableDedupe === false ? [] : [dedupeIntegration()]),\n eventFiltersIntegration(),\n functionToStringIntegration(),\n conversationIdIntegration(),\n linkedErrorsIntegration(),\n fetchIntegration(),\n httpServerIntegration(),\n requestDataIntegration(),\n consoleIntegration(),\n // The orchestrion diagnostics-channel subscribers (mysql, pg, …). The\n // `@sentry/cloudflare/vite` plugin injects the channels at build time and,\n // next to each, a snippet that registers the matching subscriber factory on\n // the global marker. Read from there instead of importing them so bundles\n // built without the plugin — where the channels would never fire — don't\n // ship the code.\n ...getRegisteredChannelIntegrations(),\n ];\n}\n\n/**\n * Initializes the Cloudflare SDK without setting up an OpenTelemetry tracer provider.\n *\n * Kept separate from `sdk.ts` so `@sentry/cloudflare/request` can load without Node.js-only\n * dependencies on runtimes such as Shopify Oxygen.\n *\n * The client is cached and reused across invocations within the same isolate,\n * unless `cacheClient: false` is passed. This avoids the\n * per-invocation cost of constructing a new client, and it is what makes\n * Durable Object telemetry reliable: a per-invocation client is disposed at\n * the end of the handler, and in a Durable Object there is no `waitUntil`\n * boundary that reliably extends execution, so spans/events that end after\n * disposal would otherwise be lost.\n */\nexport function initBaseSdk(options: CloudflareOptions): CloudflareClient | undefined {\n const cached = getCachedClient();\n const cacheEnabled = options.cacheClient !== false;\n\n // A closed client drops all data. `close()` marks the client before it\n // flushes, so this also skips a client that is still closing.\n if (cacheEnabled && cached && !_INTERNAL_isClientClosed(cached)) {\n if (DEBUG_BUILD && cached.getOptions().dsn !== options.dsn) {\n debug.warn(\n '[Sentry] init() was called with a different DSN than the cached client of this isolate; the cached client keeps its DSN. Pass `cacheClient: false` for per-invocation options.',\n );\n }\n getCurrentScope().update(options.initialScope);\n setCurrentClient(cached);\n return cached;\n }\n\n // `false` or a custom list turns off the SDK defaults, late-loaded ones\n // included, unless an SDK built the list from the defaults.\n const usesSdkDefaults = options.defaultIntegrations === undefined || !!options._extendsDefaultIntegrations;\n if (options.defaultIntegrations === undefined) {\n options.defaultIntegrations = getDefaultIntegrations(options);\n }\n\n // A cached client outlives any single invocation, so binding it to one\n // invocation's flush lock would make later flushes wait on that invocation's\n // waitUntil work forever. Eager delivery replaces the flush lock's purpose.\n const invocationContext = options.ctx;\n const flushLock = !cacheEnabled && invocationContext ? makeFlushLock(invocationContext) : undefined;\n delete options.ctx;\n\n const clientOptions: CloudflareClientOptions = {\n ...options,\n cacheClient: cacheEnabled,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n integrations: getIntegrationsToSetup(options),\n transport: options.transport || makeCloudflareTransport,\n flushLock,\n };\n\n /*! rollup-include-development-only */\n if (options.spotlight && !clientOptions.integrations.some(({ name }) => name === SPOTLIGHT_INTEGRATION_NAME)) {\n clientOptions.integrations.push(\n spotlightIntegration({\n sidecarUrl: typeof options.spotlight === 'string' ? options.spotlight : undefined,\n }),\n );\n }\n /*! rollup-include-development-only-end */\n\n if (!cacheEnabled) {\n // `cacheClient: false` asks for a new client on each call, so replacing\n // the bound client is expected here and must not warn.\n getCurrentScope().setClient(undefined);\n }\n\n const client = initAndBind(CloudflareClient, clientOptions) as CloudflareClient;\n\n if (cacheEnabled && client) {\n cacheClient(client);\n }\n\n // An instrumented module that first evaluates AFTER this init (e.g. a driver\n // lazily required on first use) stores its subscriber factory on the global\n // marker too late for the default-integrations snapshot above. Its injected\n // snippet emits this event right after storing the factory, so install the\n // integration on the live client here, with the same rules as the defaults.\n // `addIntegration` dedupes by integration name, so an integration the user\n // configured stays in place.\n const userIntegrations = options.integrations;\n client.on('orchestrion.module-injected', moduleName => {\n const factory = GLOBAL_OBJ.__SENTRY_ORCHESTRION__?.integrations?.get(moduleName);\n if (!usesSdkDefaults || !factory) {\n return;\n }\n\n const integration = factory();\n if (typeof userIntegrations !== 'function') {\n client.addIntegration(integration);\n return;\n }\n\n // Pass the late default through the user's `integrations` function, so a\n // filter that removed it at init removes it here too. This calls the\n // function again, once for each late module. If the function throws, skip\n // the integration, so the module load that emitted the event still works.\n const kept = safeCallback(\n DEBUG_BUILD ? 'Error in the `integrations` function, skipping a late-loaded integration:' : '',\n () =>\n getIntegrationsToSetup({ defaultIntegrations: [integration], integrations: userIntegrations }).find(\n ({ name }) => name === integration.name,\n ),\n () => undefined,\n );\n if (kept) {\n client.addIntegration(kept);\n }\n });\n\n return client;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAoCA,SAAS,mCAAkD;CACzD,MAAM,aAAaA,aAAAA,WAAW,wBAAwB;CAEtD,OAAO,aAAa,CAAC,GAAG,WAAW,OAAO,CAAC,CAAC,CAAC,KAAI,YAAW,QAAQ,CAAC,IAAI,CAAC;AAC5E;;;;;AAMA,SAAgB,uBAAuB,SAA2C;CAChF,OAAO;EAGL,GAAI,QAAQ,iBAAiB,QAAQ,CAAC,IAAI,EAAA,GAACC,aAAAA,kBAAAA,CAAkB,CAAC;GAC9DC,GAAAA,aAAAA,wBAAAA,CAAwB;GACxBC,GAAAA,aAAAA,4BAAAA,CAA4B;GAC5BC,GAAAA,aAAAA,0BAAAA,CAA0B;GAC1BC,GAAAA,aAAAA,wBAAAA,CAAwB;EACxBC,cAAAA,iBAAiB;EACjBC,mBAAAA,sBAAsB;GACtBC,GAAAA,aAAAA,uBAAAA,CAAuB;GACvBC,GAAAA,aAAAA,mBAAAA,CAAmB;EAOnB,GAAG,iCAAiC;CACtC;AACF;;;;;;;;;;;;;;;AAgBA,SAAgB,YAAY,SAA0D;CACpF,MAAM,SAASC,oBAAAA,gBAAgB;CAC/B,MAAM,eAAe,QAAQ,gBAAgB;CAI7C,IAAI,gBAAgB,UAAU,EAAA,GAACC,aAAAA,yBAAAA,CAAyB,MAAM,GAAG;EAC/D,IAAIC,oBAAAA,eAAe,OAAO,WAAW,CAAC,CAAC,QAAQ,QAAQ,KACrDC,aAAAA,MAAM,KACJ,gLACF;EAEFC,CAAAA,GAAAA,aAAAA,gBAAAA,CAAgB,CAAC,CAAC,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,IACrC,SACI,KAAA,CACR;EACA,IAAI,MACF,OAAO,eAAe,IAAI;CAE9B,CAAC;CAED,OAAO;AACT"}
1
+ {"version":3,"file":"baseSdk.js","names":["GLOBAL_OBJ","dedupeIntegration","eventFiltersIntegration","functionToStringIntegration","conversationIdIntegration","linkedErrorsIntegration","fetchIntegration","httpServerIntegration","requestDataIntegration","consoleIntegration","getCachedClient","_INTERNAL_isClientClosed","DEBUG_BUILD","debug","getCurrentScope","setCurrentClient","makeFlushLock","stackParserFromStackParserOptions","defaultStackParser","getIntegrationsToSetup","makeCloudflareTransport","initAndBind","CloudflareClient","cacheClient","safeCallback"],"sources":["../../../src/baseSdk.ts"],"sourcesContent":["import type { Integration } from '@sentry/core';\nimport { _INTERNAL_isClientClosed, debug, getCurrentScope, safeCallback, setCurrentClient } from '@sentry/core';\nimport {\n consoleIntegration,\n conversationIdIntegration,\n dedupeIntegration,\n eventFiltersIntegration,\n functionToStringIntegration,\n getIntegrationsToSetup,\n GLOBAL_OBJ,\n initAndBind,\n linkedErrorsIntegration,\n requestDataIntegration,\n stackParserFromStackParserOptions,\n} from '@sentry/core';\nimport type { CloudflareClientOptions, CloudflareOptions } from './client';\nimport { CloudflareClient } from './client';\nimport { makeFlushLock } from './flush';\nimport { cacheClient, getCachedClient } from './clientCache';\nimport { DEBUG_BUILD } from './debug-build';\nimport { fetchIntegration } from './integrations/fetch';\nimport { httpServerIntegration } from './integrations/httpServer';\nimport { INTEGRATION_NAME as SPOTLIGHT_INTEGRATION_NAME, spotlightIntegration } from './integrations/spotlight';\nimport { makeCloudflareTransport } from './transport';\nimport { defaultStackParser } from './vendor/stacktrace';\n\n/**\n * Instantiate the channel-subscriber factories the `@sentry/cloudflare/vite`\n * plugin registered on the global marker. The plugin splices a small snippet\n * into each instrumented module that `.set`s its factory here (keyed by module\n * name), so the marker holds one factory per package actually bundled.\n *\n * The marker is read directly instead of importing the factories, so a worker\n * built without the plugin — where the channels never fire — ships none of this\n * code.\n */\nfunction getRegisteredChannelIntegrations(): Integration[] {\n const registered = GLOBAL_OBJ.__SENTRY_ORCHESTRION__?.integrations;\n\n return registered ? [...registered.values()].map(factory => factory()) : [];\n}\n\n/**\n * Get the default integrations for the Cloudflare SDK.\n * These also work on Workers-compatible runtimes without the `nodejs_compat` compatibility flag.\n */\nexport function getDefaultIntegrations(options: CloudflareOptions): Integration[] {\n return [\n // The Dedupe integration should not be used in workflows because we want to\n // capture all step failures, even if they are the same error.\n ...(options.enableDedupe === false ? [] : [dedupeIntegration()]),\n eventFiltersIntegration(),\n functionToStringIntegration(),\n conversationIdIntegration(),\n linkedErrorsIntegration(),\n fetchIntegration(),\n httpServerIntegration(),\n requestDataIntegration(),\n consoleIntegration(),\n // The orchestrion diagnostics-channel subscribers (mysql, pg, …). The\n // `@sentry/cloudflare/vite` plugin injects the channels at build time and,\n // next to each, a snippet that registers the matching subscriber factory on\n // the global marker. Read from there instead of importing them so bundles\n // built without the plugin — where the channels would never fire — don't\n // ship the code.\n ...getRegisteredChannelIntegrations(),\n ];\n}\n\n/**\n * Initializes the Cloudflare SDK without setting up an OpenTelemetry tracer provider.\n *\n * Kept separate from `sdk.ts` so `@sentry/cloudflare/request` can load without Node.js-only\n * dependencies on runtimes such as Shopify Oxygen.\n *\n * The client is cached and reused across invocations within the same isolate,\n * unless `cacheClient: false` is passed. This avoids the\n * per-invocation cost of constructing a new client, and it is what makes\n * Durable Object telemetry reliable: a per-invocation client is disposed at\n * the end of the handler, and in a Durable Object there is no `waitUntil`\n * boundary that reliably extends execution, so spans/events that end after\n * disposal would otherwise be lost.\n */\nexport function initBaseSdk(options: CloudflareOptions): CloudflareClient | undefined {\n const cached = getCachedClient();\n // oxlint-disable-next-line typescript/no-deprecated\n const cacheEnabled = options.cacheClient !== false;\n\n // A closed client drops all data. `close()` marks the client before it\n // flushes, so this also skips a client that is still closing.\n if (cacheEnabled && cached && !_INTERNAL_isClientClosed(cached)) {\n if (DEBUG_BUILD && cached.getOptions().dsn !== options.dsn) {\n debug.warn(\n '[Sentry] init() was called with a different DSN than the cached client of this isolate; the cached client keeps its DSN. Pass `cacheClient: false` for per-invocation options.',\n );\n }\n getCurrentScope().update(options.initialScope);\n setCurrentClient(cached);\n return cached;\n }\n\n // `false` or a custom list turns off the SDK defaults, late-loaded ones\n // included, unless an SDK built the list from the defaults.\n const usesSdkDefaults = options.defaultIntegrations === undefined || !!options._extendsDefaultIntegrations;\n if (options.defaultIntegrations === undefined) {\n options.defaultIntegrations = getDefaultIntegrations(options);\n }\n\n // A cached client outlives any single invocation, so binding it to one\n // invocation's flush lock would make later flushes wait on that invocation's\n // waitUntil work forever. Eager delivery replaces the flush lock's purpose.\n const invocationContext = options.ctx;\n const flushLock = !cacheEnabled && invocationContext ? makeFlushLock(invocationContext) : undefined;\n delete options.ctx;\n\n const clientOptions: CloudflareClientOptions = {\n ...options,\n // oxlint-disable-next-line typescript/no-deprecated\n cacheClient: cacheEnabled,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n integrations: getIntegrationsToSetup(options),\n transport: options.transport || makeCloudflareTransport,\n flushLock,\n };\n\n /*! rollup-include-development-only */\n if (options.spotlight && !clientOptions.integrations.some(({ name }) => name === SPOTLIGHT_INTEGRATION_NAME)) {\n clientOptions.integrations.push(\n spotlightIntegration({\n sidecarUrl: typeof options.spotlight === 'string' ? options.spotlight : undefined,\n }),\n );\n }\n /*! rollup-include-development-only-end */\n\n if (!cacheEnabled) {\n // `cacheClient: false` asks for a new client on each call, so replacing\n // the bound client is expected here and must not warn.\n getCurrentScope().setClient(undefined);\n }\n\n const client = initAndBind(CloudflareClient, clientOptions) as CloudflareClient;\n\n if (cacheEnabled && client) {\n cacheClient(client);\n }\n\n // An instrumented module that first evaluates AFTER this init (e.g. a driver\n // lazily required on first use) stores its subscriber factory on the global\n // marker too late for the default-integrations snapshot above. Its injected\n // snippet emits this event right after storing the factory, so install the\n // integration on the live client here, with the same rules as the defaults.\n // `addIntegration` dedupes by integration name, so an integration the user\n // configured stays in place.\n const userIntegrations = options.integrations;\n client.on('orchestrion.module-injected', moduleName => {\n const factory = GLOBAL_OBJ.__SENTRY_ORCHESTRION__?.integrations?.get(moduleName);\n if (!usesSdkDefaults || !factory) {\n return;\n }\n\n const integration = factory();\n if (typeof userIntegrations !== 'function') {\n client.addIntegration(integration);\n return;\n }\n\n // Pass the late default through the user's `integrations` function, so a\n // filter that removed it at init removes it here too. This calls the\n // function again, once for each late module. If the function throws, skip\n // the integration, so the module load that emitted the event still works.\n const kept = safeCallback(\n DEBUG_BUILD ? 'Error in the `integrations` function, skipping a late-loaded integration:' : '',\n () =>\n getIntegrationsToSetup({ defaultIntegrations: [integration], integrations: userIntegrations }).find(\n ({ name }) => name === integration.name,\n ),\n () => undefined,\n );\n if (kept) {\n client.addIntegration(kept);\n }\n });\n\n return client;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAoCA,SAAS,mCAAkD;CACzD,MAAM,aAAaA,aAAAA,WAAW,wBAAwB;CAEtD,OAAO,aAAa,CAAC,GAAG,WAAW,OAAO,CAAC,CAAC,CAAC,KAAI,YAAW,QAAQ,CAAC,IAAI,CAAC;AAC5E;;;;;AAMA,SAAgB,uBAAuB,SAA2C;CAChF,OAAO;EAGL,GAAI,QAAQ,iBAAiB,QAAQ,CAAC,IAAI,EAAA,GAACC,aAAAA,kBAAAA,CAAkB,CAAC;GAC9DC,GAAAA,aAAAA,wBAAAA,CAAwB;GACxBC,GAAAA,aAAAA,4BAAAA,CAA4B;GAC5BC,GAAAA,aAAAA,0BAAAA,CAA0B;GAC1BC,GAAAA,aAAAA,wBAAAA,CAAwB;EACxBC,cAAAA,iBAAiB;EACjBC,mBAAAA,sBAAsB;GACtBC,GAAAA,aAAAA,uBAAAA,CAAuB;GACvBC,GAAAA,aAAAA,mBAAAA,CAAmB;EAOnB,GAAG,iCAAiC;CACtC;AACF;;;;;;;;;;;;;;;AAgBA,SAAgB,YAAY,SAA0D;CACpF,MAAM,SAASC,oBAAAA,gBAAg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C5B,IAAI,OAAO,qBAAqB,YAAY;GAC1C,OAAO,eAAe,WAAW;GACjC;EACF;EAMA,MAAM,QAAA,GAAOwB,aAAAA,aAAAA,CACXZ,oBAAAA,cAAc,8EAA8E,WAAA,GAE1FO,aAAAA,uBAAAA,CAAuB;GAAE,qBAAqB,CAAC,WAAW;GAAG,cAAc;EAAiB,CAAC,CAAC,CAAC,MAC5F,EAAE,WAAW,SAAS,YAAY,IACrC,SACI,KAAA,CACR;EACA,IAAI,MACF,OAAO,eAAe,IAAI;CAE9B,CAAC;CAED,OAAO;AACT"}
@@ -19,10 +19,15 @@ var CloudflareClient = class extends _sentry_core_server.ServerRuntimeClient {
19
19
  (0, _sentry_core.applySdkMetadata)(options, "cloudflare");
20
20
  options._metadata = options._metadata || {};
21
21
  const { flushLock, ...serverOptions } = options;
22
+ const workerInfo = _sentry_core.GLOBAL_OBJ.__SENTRY_CLOUDFLARE_WORKER__;
22
23
  const clientOptions = {
23
24
  ...serverOptions,
24
25
  platform: "javascript",
25
- runtime: { name: "cloudflare" },
26
+ runtime: {
27
+ name: "cloudflare",
28
+ version: workerInfo?.compatibilityDate
29
+ },
30
+ serverName: serverOptions.serverName ?? workerInfo?.name,
26
31
  _flushInterval: 0
27
32
  };
28
33
  if ((typeof __SENTRY_TRACING__ === "undefined" || __SENTRY_TRACING__) && clientOptions.traceLifecycle !== "static" && !clientOptions.integrations.some((i) => i.name === SPAN_STREAMING_INTEGRATION_NAME)) clientOptions.integrations.push((0, _sentry_core.spanStreamingIntegration)({ flushOnSegmentEnd: false }));
@@ -33,6 +38,7 @@ var CloudflareClient = class extends _sentry_core_server.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 _sentry_core_server.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 _sentry_core_server.ServerRuntimeClient {
160
171
  this.on("afterEnvelope", () => {
161
172
  const transport = this.getTransport();
162
173
  const invocationState = require_invocationContext.getInvocationState();
163
- if (!transport || this._inBoundaryFlush || invocationState && !invocationState.flushPointReached) return;
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":["ServerRuntimeClient","applySdkMetadata","spanStreamingIntegration","DEBUG_BUILD","debug","spanIsSampled","_INTERNAL_clearAiProviderSkips","getInvocationState","_INTERNAL_flushLogsBuffer","_INTERNAL_flushMetricsBuffer","getInvocationWaitUntil"],"sources":["../../../src/client.ts"],"sourcesContent":["import type { CheckIn, ClientOptions, MonitorConfig, Options, Scope, TracePropagationTargets } from '@sentry/core';\nimport {\n _INTERNAL_clearAiProviderSkips,\n _INTERNAL_flushLogsBuffer,\n _INTERNAL_flushMetricsBuffer,\n applySdkMetadata,\n debug,\n spanIsSampled,\n spanStreamingIntegration,\n} from '@sentry/core';\nimport type { ServerRuntimeClientOptions } from '@sentry/core/server';\nimport { ServerRuntimeClient } from '@sentry/core/server';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { ExecutionContextCompat } from './executionContext';\nimport type { makeFlushLock } from './flush';\nimport type { CloudflareTransportOptions } from './transport';\nimport { getInvocationState, getInvocationWaitUntil } from './utils/invocationContext';\n\ndeclare const __SENTRY_TRACING__: boolean;\n\nconst SPAN_STREAMING_INTEGRATION_NAME = 'SpanStreaming';\n\n/**\n * The Sentry Cloudflare SDK Client.\n *\n * @see CloudflareClientOptions for documentation on configuration options.\n * @see ServerRuntimeClient for usage documentation.\n */\nexport class CloudflareClient extends ServerRuntimeClient {\n private readonly _flushLock: ReturnType<typeof makeFlushLock> | void;\n private _pendingSpans: Set<string> = new Set();\n private _spanCompletionPromise: Promise<void> | null = null;\n private _resolveSpanCompletion: (() => void) | null = null;\n\n private _unsubscribeSpanStart: (() => void) | null = null;\n private _unsubscribeSpanEnd: (() => void) | null = null;\n\n // True while a boundary `flush()` is draining; envelopes created by that drain ride it\n // and must not each start their own eager transport flush.\n private _inBoundaryFlush = false;\n\n // Eager drains still sending. Outside an instrumented invocation (e.g. Astro on Pages) they have no `waitUntil`,\n // so `flush()` awaits them, or the response can end first and the runtime cancels their fetches.\n private readonly _pendingEagerDrains = new Set<Promise<void>>();\n\n /**\n * Whether this client is a cached, cross-invocation client (`cacheClient`).\n * Cached clients are never disposed at an invocation boundary, so their spans/events\n * are delivered eagerly instead of waiting for a per-invocation flush.\n */\n public readonly isCachedClient: boolean;\n\n /**\n * Creates a new Cloudflare SDK instance.\n * @param options Configuration options for this SDK.\n */\n public constructor(options: CloudflareClientOptions) {\n applySdkMetadata(options, 'cloudflare');\n options._metadata = options._metadata || {};\n const { flushLock, ...serverOptions } = options;\n\n const clientOptions: ServerRuntimeClientOptions = {\n ...serverOptions,\n platform: 'javascript',\n // TODO: Grab version information\n runtime: { name: 'cloudflare' },\n // TODO: Add server name\n _flushInterval: 0,\n };\n\n // workerd can't unref timers, so the default 500ms segment-end flush timer holds every\n // Durable Object invocation open (and billed) until it fires, sampled or not. The boundary\n // flush and the eager drain already deliver streamed spans here.\n if (\n (typeof __SENTRY_TRACING__ === 'undefined' || __SENTRY_TRACING__) &&\n clientOptions.traceLifecycle !== 'static' &&\n !clientOptions.integrations.some(i => i.name === SPAN_STREAMING_INTEGRATION_NAME)\n ) {\n clientOptions.integrations.push(spanStreamingIntegration({ flushOnSegmentEnd: false }));\n }\n\n super(clientOptions);\n this._flushLock = flushLock;\n this.isCachedClient = options.cacheClient === true;\n\n // Track span lifecycle to know when to flush. Skipped for cached clients\n // (`cacheClient`): they are never disposed, so spans that end after\n // a flush are still delivered. Per-invocation clients are disposed right after\n // the boundary flush, so the flush must wait for open spans to end otherwise\n // their transaction never gets emitted.\n if (!this.isCachedClient) {\n this._unsubscribeSpanStart = this.on('spanStart', span => {\n const spanId = span.spanContext().spanId;\n DEBUG_BUILD && debug.log('[CloudflareClient] Span started:', spanId);\n\n // Negatively sampled spans never emit spanEnd,\n // so tracking them would cause _pendingSpans to grow unboundedly.\n // We should fix the inconsistent behavior for NonRecordingSpans in the future but\n // for now, we just ignore them.\n if (!spanIsSampled(span)) {\n return;\n }\n\n this._pendingSpans.add(spanId);\n\n if (!this._spanCompletionPromise) {\n this._spanCompletionPromise = new Promise(resolve => {\n this._resolveSpanCompletion = resolve;\n });\n }\n });\n\n this._unsubscribeSpanEnd = this.on('spanEnd', span => {\n const spanId = span.spanContext().spanId;\n DEBUG_BUILD && debug.log('[CloudflareClient] Span ended:', spanId);\n this._pendingSpans.delete(spanId);\n\n // If no more pending spans, resolve the completion promise\n if (this._pendingSpans.size === 0 && this._resolveSpanCompletion) {\n DEBUG_BUILD && debug.log('[CloudflareClient] All spans completed, preparing to flush');\n this._resolveSpanCompletion();\n this._resetSpanCompletionPromise();\n }\n });\n }\n }\n\n /**\n * Flushes pending operations and ensures all data is processed.\n *\n * Each phase waits at most `timeout`: the flush lock of a per-invocation client, pending spans, event\n * processing and the transport drain. So a flush can take a small multiple of `timeout`, which stays well\n * below Cloudflare's 30 second `waitUntil` limit for the timeouts the SDK uses. Sends still pending when\n * the drain times out are aborted.\n *\n * @param {number} [timeout] - Maximum time in milliseconds for each phase of the flush.\n * @return {Promise<boolean>} A promise that resolves to a boolean indicating whether the flush operation was successful.\n */\n public async flush(timeout?: number): Promise<boolean> {\n // Wait for user waitUntil-registered work to settle before draining, so events\n // captured in that work are still in the buffer. Without this the final flush\n // can drain (and the client be disposed) before background captures land.\n //\n // Only per-invocation clients (`cacheClient: false`) have a flush lock; remove this with them in v12.\n // The wait is bounded by `timeout` because a user `waitUntil` task that outlives the invocation\n // would otherwise keep the flush from draining until the runtime cancels it.\n if (this._flushLock) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n this._flushLock.finalize(),\n ...(timeout ? [new Promise<void>(resolve => (timer = setTimeout(resolve, timeout)))] : []),\n ]);\n clearTimeout(timer);\n }\n\n if (this._pendingSpans.size > 0 && this._spanCompletionPromise) {\n DEBUG_BUILD &&\n debug.log('[CloudflareClient] Waiting for', this._pendingSpans.size, 'pending spans to complete...');\n\n const timeoutMs = timeout ?? 5000;\n const spanCompletionRace = Promise.race([\n this._spanCompletionPromise,\n new Promise(resolve =>\n setTimeout(() => {\n DEBUG_BUILD &&\n debug.log('[CloudflareClient] Span completion timeout after', timeoutMs, 'ms, flushing anyway');\n resolve(undefined);\n }, timeoutMs),\n ),\n ]);\n\n await spanCompletionRace;\n }\n\n // Envelopes created while this flush drains (log/metric/span buffers turning into\n // envelopes on the `flush` emit) ride its own transport drain; without the flag each\n // of them would also start an eager drain and a `waitUntil` registration.\n this._inBoundaryFlush = true;\n let flushed: boolean;\n try {\n flushed = await super.flush(timeout);\n } finally {\n this._inBoundaryFlush = false;\n }\n\n // Each eager drain is bounded by its own transport flush timeout.\n await Promise.all(this._pendingEagerDrains);\n\n return flushed;\n }\n\n /**\n * Sends the check-in at once instead of holding it for the flush at the end of the invocation.\n * An `in_progress` check-in of a run that is longer than the check-in margin would otherwise\n * reach Sentry too late, and Sentry would mark the run as missed.\n */\n public override captureCheckIn(checkIn: CheckIn, monitorConfig?: MonitorConfig, scope?: Scope): string {\n const checkInId = super.captureCheckIn(checkIn, monitorConfig, scope);\n const transport = this.getTransport();\n if (transport) {\n this._registerWithInvocationWaitUntil(transport.flush(2000));\n }\n return checkInId;\n }\n\n /**\n * Disposes of the client and releases all resources.\n *\n * This method clears all Cloudflare-specific state in addition to the base client cleanup.\n * It unsubscribes from span lifecycle events and clears pending span tracking.\n *\n * Call this method after flushing to allow the client to be garbage collected.\n * After calling dispose(), the client should not be used anymore.\n */\n public override dispose(): void {\n DEBUG_BUILD && debug.log('[CloudflareClient] Disposing client...');\n\n super.dispose();\n\n if (this._unsubscribeSpanStart) {\n this._unsubscribeSpanStart();\n this._unsubscribeSpanStart = null;\n }\n if (this._unsubscribeSpanEnd) {\n this._unsubscribeSpanEnd();\n this._unsubscribeSpanEnd = null;\n }\n\n this._resetSpanCompletionPromise();\n (this as unknown as { _flushLock: ReturnType<typeof makeFlushLock> | void })._flushLock = undefined;\n }\n\n /** @inheritDoc */\n protected override _setupIntegrations(): void {\n // Clear AI provider skip registrations before setting up integrations.\n // The registry is module-global and Cloudflare calls `init()` per request, so without this a\n // single `ai` SDK call would suppress direct `env.AI.run` spans for the rest of the isolate's\n // life. Mirrors the same reset in the Node client.\n _INTERNAL_clearAiProviderSkips();\n super._setupIntegrations();\n\n // Registered after the integrations on purpose: the flush-point marker must run\n // after core and the span buffer have turned their buffers into envelopes on the\n // same `flush` emit (so those envelopes ride the boundary drain instead of starting\n // eager ones), and the eager span handler relies on `spanStreamingIntegration`\n // having already buffered the span that triggers it.\n if (this.isCachedClient) {\n // Marks the invocation's natural flush point: anything captured from now on\n // (post-response `waitUntil` work, detached continuations) has no later flush\n // to ride and is delivered eagerly by the hooks below.\n this.on('flush', () => {\n const invocationState = getInvocationState();\n if (invocationState) {\n invocationState.flushPointReached = true;\n }\n });\n this._setupEagerEnvelopeDelivery();\n this._setupEagerBufferDelivery();\n }\n }\n\n /**\n * Resets the span completion promise and resolve function.\n */\n private _resetSpanCompletionPromise(): void {\n this._pendingSpans.clear();\n this._spanCompletionPromise = null;\n this._resolveSpanCompletion = null;\n }\n\n /**\n * Drains the transport after an envelope has been accepted past the invocation's\n * flush point. The transport queues request producers until `flush()`; before the\n * flush point the boundary `flush()` drains everything, but envelopes created after\n * it (post-response `waitUntil` work, detached continuations) have no later flush to\n * ride. The drain is registered with the invocation's `waitUntil` to keep the fetch\n * alive; outside any instrumented invocation it always runs.\n */\n private _setupEagerEnvelopeDelivery(): void {\n this.on('afterEnvelope', () => {\n const transport = this.getTransport();\n const invocationState = getInvocationState();\n\n if (!transport || this._inBoundaryFlush || (invocationState && !invocationState.flushPointReached)) {\n return;\n }\n\n this._registerWithInvocationWaitUntil(transport.flush(2000));\n });\n }\n\n /**\n * Turns spans, logs and metrics captured past the invocation's flush point into\n * envelopes. Before the flush point the boundary `flush()` drains their buffers; after\n * it (or outside any instrumented invocation) nothing else would: the log/metric idle\n * timer is disabled for this runtime (`_flushInterval: 0`) and the span buffer's own 5s\n * timer fires outside any invocation, where the runtime suspends the send. Each capture\n * drains only its own bucket (the ended span's trace, the log buffer, the metric\n * buffer), so a fan-out of concurrent traces stays one envelope per trace. RPC method\n * spans never reach this path: `wrapMethodWithSentry` runs the boundary flush after the\n * method span has ended, so only work past that (e.g. detached continuations) lands here.\n */\n private _setupEagerBufferDelivery(): void {\n this.on('afterSpanEnd', span => {\n // The trace id must come from the span, not the current scope: `continueTrace`\n // writes the propagation context to the *current* scope, so the forked\n // isolation scope's propagation context carries a different trace id and\n // flushing by it silently no-ops.\n const traceId = span.spanContext().traceId;\n this._eagerDrain(() => this.emit('flushTraceSpans', traceId));\n });\n this.on('afterCaptureLog', () => this._eagerDrain(() => _INTERNAL_flushLogsBuffer(this)));\n this.on('afterCaptureMetric', () => this._eagerDrain(() => _INTERNAL_flushMetricsBuffer(this)));\n }\n\n /**\n * Runs `drain` unless the owning invocation has not reached its flush point yet\n * (before it the boundary `flush()` delivers the buffers).\n */\n private _eagerDrain(drain: () => void): void {\n const invocationState = getInvocationState();\n\n if (invocationState && !invocationState.flushPointReached) {\n return;\n }\n\n drain();\n }\n\n /**\n * Attaches a promise to the `waitUntil` of the invocation that owns the current\n * async context, so the runtime keeps the send alive after the response is returned.\n * Outside any instrumented invocation (or where the context has no `waitUntil`,\n * e.g. Astro prerendering) only the next `flush()` waits for the send.\n */\n private _registerWithInvocationWaitUntil(promise: PromiseLike<unknown>): void {\n const pending = Promise.resolve(promise).then(\n () => undefined,\n () => undefined,\n );\n this._pendingEagerDrains.add(pending);\n void pending.then(() => this._pendingEagerDrains.delete(pending));\n\n const invocationState = getInvocationState();\n const waitUntil = invocationState && getInvocationWaitUntil(invocationState);\n if (!waitUntil) {\n return;\n }\n\n try {\n waitUntil(pending);\n } catch {\n // The owning invocation already ended; the send races isolate teardown either way.\n }\n }\n}\n\ninterface BaseCloudflareOptions {\n /**\n * @ignore Used internally to disable the deDupeIntegration for workflows.\n * @hidden Used internally to disable the deDupeIntegration for workflows.\n * @default true\n */\n enableDedupe?: boolean;\n\n /**\n * @ignore Used internally by SDKs that build `defaultIntegrations` from the Cloudflare defaults.\n * @hidden Used internally by SDKs that build `defaultIntegrations` from the Cloudflare defaults.\n *\n * Marks the `defaultIntegrations` list as an extension of the SDK defaults, so the SDK also adds\n * the integrations of instrumented modules that load after `init()`.\n * @default false\n */\n _extendsDefaultIntegrations?: boolean;\n\n /**\n * The Cloudflare SDK is not OpenTelemetry native. By default (`false`) it does not set up a tracer\n * provider; spans are emitted via the SDK's own instrumentation and scopes are isolated with\n * AsyncLocalStorage.\n *\n * Set this to `true` to opt into the OpenTelemetry compatibility tracer, which captures spans\n * emitted via `@opentelemetry/api`. Big caveat: it does not handle custom context, always working\n * off the current scope. This is good enough for many, but not all, integrations.\n *\n * @default false\n */\n enableOpenTelemetrySetup?: boolean;\n\n /**\n * The bindings on `env` that outgoing RPC calls propagate trace context to.\n *\n * Strings match a binding name exactly, regular expressions match by pattern. An empty array\n * (the default) propagates to nothing.\n *\n * RPC has no headers to carry trace context, so the SDK appends it as a trailing argument to\n * every RPC method call on a matching binding. Only a Sentry-instrumented receiver strips that\n * argument again. Anywhere else it arrives as a real argument and changes what the method was\n * called with, so list only the bindings whose receiver you know runs Sentry.\n *\n * Propagation over `stub.fetch()` and service binding `fetch()` uses HTTP headers and is not\n * affected by this option.\n *\n * Strings match a binding name exactly, regular expressions match by pattern. Both match\n * case-insensitively.\n *\n * When you build with the Sentry Cloudflare Vite plugin, bindings that resolve to *this* worker\n * (its own Durable Objects, its self service bindings) are added for you, because the plugin\n * instruments those receivers itself. Whatever you list here is added on top of them.\n *\n * @default []\n * @example\n * ```ts\n * // Propagate to `env.ORDERS` and every `env.SVC_*` binding\n * export default Sentry.withSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * rpcTracePropagationBindings: ['ORDERS', /^SVC_/],\n * }),\n * handler,\n * );\n * ```\n */\n rpcTracePropagationBindings?: TracePropagationTargets;\n\n /**\n * The Queue producer bindings on `env` that outgoing messages propagate trace context to.\n *\n * Cloudflare Queues has no message headers, so the SDK adds the producer's `sentry-trace` to\n * plain-object message bodies under `__sentry_queue_trace__`. Arrays, binary data and other\n * non-plain values are sent unchanged. A Sentry-instrumented consumer removes that field before\n * your queue handler runs and links its `queue.process` span to every producer in the batch.\n * Anywhere else the field arrives as part of the message body, so list only the queues whose\n * consumer you know runs Sentry.\n *\n * The field adds about 80 bytes to each message. Cloudflare rejects messages over 128 KB, so a\n * message close to that limit can fail to send once propagation is enabled.\n *\n * Strings match a binding name exactly, regular expressions match by pattern. Both match\n * case-insensitively.\n *\n * @default []\n * @example\n * ```ts\n * // Propagate to `env.BILLING_QUEUE` and every `env.JOBS_*` binding\n * export default Sentry.withSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * queueTracePropagationBindings: ['BILLING_QUEUE', /^JOBS_/],\n * }),\n * handler,\n * );\n * ```\n */\n queueTracePropagationBindings?: TracePropagationTargets;\n\n /**\n * Table names that should stay instrumented even though they match a reserved prefix used by\n * Durable Object frameworks for their internal SQLite tables: `cf_` (`agents`, `partyserver`, ...)\n * and `pi_` (pi-durable in the `PiHarness` of `agents`).\n *\n * By default, `exec` queries against tables with these prefixes are treated as framework noise and\n * no `db.query` span is created for them. If one of your own tables happens to use such a prefix,\n * add it here to opt it back into instrumentation, or add `/^pi_/` to see the statements of\n * pi-durable. Entries are matched against each table name in the\n * query summary — strings must match exactly, while regular expressions give you prefix/pattern\n * matching.\n *\n * @default []\n * @example\n * ```ts\n * export default Sentry.withSentry(\n * (env) => ({\n * dsn: env.SENTRY_DSN,\n * durableObjectSqlSpanAllowlist: ['cf_my_table', /^cf_reports_/],\n * }),\n * handler,\n * );\n * ```\n */\n durableObjectSqlSpanAllowlist?: Array<string | RegExp>;\n\n /**\n * KV keys that should stay instrumented even though they match a reserved prefix used by Durable\n * Object frameworks (`agents`, `partyserver`, ...) for their internal storage entries.\n *\n * By default, KV reads/writes (`get`, `put`, `delete`, `list`) of `cf_`- or `__ps_`-prefixed keys\n * are treated as framework noise and no `durable_object_storage_*` span is created for them,\n * mirroring how `cf_`-prefixed SQL tables are handled (see {@link durableObjectSqlSpanAllowlist}).\n * If one of your own keys happens to use such a prefix, add it here to opt it back into\n * instrumentation. Strings must match exactly, while regular expressions give you prefix/pattern\n * matching.\n *\n * @default []\n * @example\n * ```ts\n * export default Sentry.withSentry(\n * (env) => ({\n * dsn: env.SENTRY_DSN,\n * durableObjectStorageSpanAllowlist: ['cf_my_key', /^cf_reports_/],\n * }),\n * handler,\n * );\n * ```\n */\n durableObjectStorageSpanAllowlist?: Array<string | RegExp>;\n\n /**\n * Sets an optional server name (device name).\n *\n * This is useful for identifying which server or instance is sending events.\n */\n serverName?: string;\n\n /**\n * If you use Spotlight by Sentry during development, use\n * this option to forward captured Sentry events to Spotlight.\n *\n * Either set it to true, or provide a specific Spotlight Sidecar URL.\n *\n * More details: https://spotlightjs.com/\n *\n * IMPORTANT: Only set this option to `true` while developing, not in production!\n */\n spotlight?: boolean | string;\n\n /**\n * Cache the client and reuse it across invocations within the same isolate.\n *\n * The SDK creates one client per isolate and reuses it for all requests/DO\n * handlers in that isolate. This avoids the per-invocation cost of\n * constructing a new client.\n *\n * Since a cached client outlives any single invocation, data captured after an\n * invocation's flush point (post-response `waitUntil` work, detached background\n * work) is delivered eagerly instead of waiting for a flush that never comes.\n *\n * The first `init()` in an isolate decides the cached client's options; later\n * `init()` calls with different options (e.g. another DSN) reuse the cached client\n * unchanged (a debug warning is logged for a DSN change). Use `cacheClient: false`\n * when options must differ per invocation.\n *\n * When disabled, a new client is created per invocation and disposed after the\n * handler completes.\n *\n * @default true\n */\n cacheClient?: boolean;\n\n /**\n * A function that receives the response of a `fetch` handler and the request it answers, and\n * returns whether the response body is still being produced after the handler returns.\n *\n * For `true`, the SDK keeps the `http.server` span open until the body has been sent, so spans\n * created while the body streams stay inside the request. It does this by passing the body through\n * a `TransformStream`. For `false`, the SDK ends the span when the handler returns and sends the\n * response unchanged. For `undefined` or any other value, the SDK decides: Server-Sent Events,\n * NDJSON and `application/stream+json` responses, and `text/plain` and `text/x-component`\n * responses without a `Content-Length` header count as streamed. HTML does not, so return `true`\n * for pages that are rendered with streamed SSR.\n *\n * The function must be synchronous and must not read the response body. Use the status, the\n * headers and the request URL.\n *\n * @example\n * ```ts\n * // src/instrument.server.ts\n * import { defineCloudflareOptions } from '@sentry/cloudflare';\n *\n * export default defineCloudflareOptions(env => ({\n * dsn: env.SENTRY_DSN,\n * isStreamingResponse: response =>\n * response.headers.get('content-type')?.startsWith('text/html') ? true : undefined,\n * }));\n * ```\n */\n isStreamingResponse?: (response: Response, request: Request) => boolean | undefined;\n}\n\n/**\n * Configuration options for the Sentry Cloudflare SDK\n *\n * @see @sentry/core Options for more information.\n */\nexport interface CloudflareOptions extends Options<CloudflareTransportOptions>, BaseCloudflareOptions {\n ctx?: ExecutionContextCompat;\n\n /**\n * A URL to send this server's own envelopes to instead of the Sentry ingest URL. To serve the managed tunnel for the\n * browser, use `serveTunnelIntegration`.\n */\n tunnel?: string;\n}\n\n/**\n * Configuration options for the Sentry Cloudflare SDK Client class\n *\n * @see CloudflareClient for more information.\n */\nexport interface CloudflareClientOptions extends ClientOptions<CloudflareTransportOptions>, BaseCloudflareOptions {\n flushLock?: ReturnType<typeof makeFlushLock>;\n}\n"],"mappings":";;;;;AAoBA,MAAM,kCAAkC;;;;;;;AAQxC,IAAa,mBAAb,cAAsCA,oBAAAA,oBAAoB;;;;;CA4BjD,YAAY,SAAkC;EACnDC,CAAAA,GAAAA,aAAAA,iBAAAA,CAAiB,SAAS,YAAY;EACtC,QAAQ,YAAY,QAAQ,aAAa,CAAC;EAC1C,MAAM,EAAE,WAAW,GAAG,kBAAkB;EAExC,MAAM,gBAA4C;GAChD,GAAG;GACH,UAAU;GAEV,SAAS,EAAE,MAAM,aAAa;GAE9B,gBAAgB;EAClB;EAKA,KACG,OAAO,uBAAuB,eAAe,uBAC9C,cAAc,mBAAmB,YACjC,CAAC,cAAc,aAAa,MAAK,MAAK,EAAE,SAAS,+BAA+B,GAEhF,cAAc,aAAa,MAAA,GAAKC,aAAAA,yBAAAA,CAAyB,EAAE,mBAAmB,MAAM,CAAC,CAAC;EAGxF,MAAM,aAAa;EAnDrB,KAAQ,gCAA6B,IAAI,IAAI;EAC7C,KAAQ,yBAA+C;EACvD,KAAQ,yBAA8C;EAEtD,KAAQ,wBAA6C;EACrD,KAAQ,sBAA2C;EAInD,KAAQ,mBAAmB;EAI3B,KAAiB,sCAAsB,IAAI,IAAmB;EAuC5D,KAAK,aAAa;EAClB,KAAK,iBAAiB,QAAQ,gBAAgB;EAO9C,IAAI,CAAC,KAAK,gBAAgB;GACxB,KAAK,wBAAwB,KAAK,GAAG,cAAa,SAAQ;IACxD,MAAM,SAAS,KAAK,YAAY,CAAC,CAAC;IAClCC,oBAAAA,eAAeC,aAAAA,MAAM,IAAI,oCAAoC,MAAM;IAMnE,IAAI,EAAA,GAACC,aAAAA,cAAAA,CAAc,IAAI,GACrB;IAGF,KAAK,cAAc,IAAI,MAAM;IAE7B,IAAI,CAAC,KAAK,wBACR,K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,OAAO,CAAC;EAC9D,CAAC;EACD,KAAK,GAAG,yBAAyB,KAAK,mBAAA,GAAkBC,aAAAA,0BAAAA,CAA0B,IAAI,CAAC,CAAC;EACxF,KAAK,GAAG,4BAA4B,KAAK,mBAAA,GAAkBC,aAAAA,6BAAAA,CAA6B,IAAI,CAAC,CAAC;CAChG;;;;;CAMQ,YAAY,OAAyB;EAC3C,MAAM,kBAAkBF,0BAAAA,mBAAmB;EAE3C,IAAI,mBAAmB,CAAC,gBAAgB,mBACtC;EAGF,MAAM;CACR;;;;;;;CAQQ,iCAAiC,SAAqC;EAC5E,MAAM,UAAU,QAAQ,QAAQ,OAAO,CAAC,CAAC,WACjC,KAAA,SACA,KAAA,CACR;EACA,KAAK,oBAAoB,IAAI,OAAO;EAC/B,QAAQ,WAAW,KAAK,oBAAoB,OAAO,OAAO,CAAC;EAEhE,MAAM,kBAAkBA,0BAAAA,mBAAmB;EAC3C,MAAM,YAAY,mBAAmBG,0BAAAA,uBAAuB,eAAe;EAC3E,IAAI,CAAC,WACH;EAGF,IAAI;GACF,UAAU,OAAO;EACnB,QAAQ,CAER;CACF;AACF"}
1
+ {"version":3,"file":"client.js","names":["ServerRuntimeClient","applySdkMetadata","GLOBAL_OBJ","spanStreamingIntegration","DEBUG_BUILD","debug","spanIsSampled","_INTERNAL_clearAiProviderSkips","getInvocationState","_INTERNAL_flushLogsBuffer","_INTERNAL_flushMetricsBuffer","getInvocationWaitUntil"],"sources":["../../../src/client.ts"],"sourcesContent":["import type { CheckIn, ClientOptions, MonitorConfig, Options, Scope, TracePropagationTargets } from '@sentry/core';\nimport {\n _INTERNAL_clearAiProviderSkips,\n _INTERNAL_flushLogsBuffer,\n _INTERNAL_flushMetricsBuffer,\n applySdkMetadata,\n debug,\n GLOBAL_OBJ,\n spanIsSampled,\n spanStreamingIntegration,\n} from '@sentry/core';\nimport type { ServerRuntimeClientOptions } from '@sentry/core/server';\nimport { ServerRuntimeClient } from '@sentry/core/server';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { ExecutionContextCompat } from './executionContext';\nimport type { makeFlushLock } from './flush';\nimport type { CloudflareTransportOptions } from './transport';\nimport { getInvocationState, getInvocationWaitUntil } from './utils/invocationContext';\n\ndeclare const __SENTRY_TRACING__: boolean;\n\nconst SPAN_STREAMING_INTEGRATION_NAME = 'SpanStreaming';\n\ntype GlobalWithWorkerInfo = typeof GLOBAL_OBJ & {\n /**\n * The `name` and `compatibility_date` of the wrangler config. Only set when the Worker is built\n * with `sentryCloudflareVitePlugin`.\n */\n __SENTRY_CLOUDFLARE_WORKER__?: { name?: string; compatibilityDate?: string };\n};\n\n/**\n * The Sentry Cloudflare SDK Client.\n *\n * @see CloudflareClientOptions for documentation on configuration options.\n * @see ServerRuntimeClient for usage documentation.\n */\nexport class CloudflareClient extends ServerRuntimeClient {\n private readonly _flushLock: ReturnType<typeof makeFlushLock> | void;\n private _pendingSpans: Set<string> = new Set();\n private _spanCompletionPromise: Promise<void> | null = null;\n private _resolveSpanCompletion: (() => void) | null = null;\n\n private _unsubscribeSpanStart: (() => void) | null = null;\n private _unsubscribeSpanEnd: (() => void) | null = null;\n\n // True while a boundary `flush()` is draining; envelopes created by that drain ride it\n // and must not each start their own eager transport flush.\n private _inBoundaryFlush = false;\n\n // 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,cAAsCA,oBAAAA,oBAAoB;;;;;CAgCjD,YAAY,S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