@sentry/cloudflare 10.68.0 → 10.69.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 (135) hide show
  1. package/build/cjs/client.js +5 -0
  2. package/build/cjs/client.js.map +1 -1
  3. package/build/cjs/durableobject.js +131 -96
  4. package/build/cjs/durableobject.js.map +1 -1
  5. package/build/cjs/index.js +3 -0
  6. package/build/cjs/index.js.map +1 -1
  7. package/build/cjs/instrumentations/agents/index.js +14 -0
  8. package/build/cjs/instrumentations/agents/index.js.map +1 -0
  9. package/build/cjs/instrumentations/agents/instrumentAgentCallableRpc.js +52 -0
  10. package/build/cjs/instrumentations/agents/instrumentAgentCallableRpc.js.map +1 -0
  11. package/build/cjs/instrumentations/agents/instrumentChatAgentConversation.js +31 -0
  12. package/build/cjs/instrumentations/agents/instrumentChatAgentConversation.js.map +1 -0
  13. package/build/cjs/instrumentations/agents/types.js +32 -0
  14. package/build/cjs/instrumentations/agents/types.js.map +1 -0
  15. package/build/cjs/instrumentations/instrumentDurableObjectStorage.js +6 -0
  16. package/build/cjs/instrumentations/instrumentDurableObjectStorage.js.map +1 -1
  17. package/build/cjs/instrumentations/instrumentSqlStorage.js +1 -1
  18. package/build/cjs/instrumentations/instrumentSqlStorage.js.map +1 -1
  19. package/build/cjs/integrations/spotlight.js +64 -0
  20. package/build/cjs/integrations/spotlight.js.map +1 -0
  21. package/build/cjs/nodejs_compat/index.js +5 -2
  22. package/build/cjs/nodejs_compat/index.js.map +1 -1
  23. package/build/cjs/options.js +14 -1
  24. package/build/cjs/options.js.map +1 -1
  25. package/build/cjs/sdk.js +8 -0
  26. package/build/cjs/sdk.js.map +1 -1
  27. package/build/cjs/utils/internalSqlQuery.js +13 -7
  28. package/build/cjs/utils/internalSqlQuery.js.map +1 -1
  29. package/build/cjs/utils/internalStorageKey.js +44 -0
  30. package/build/cjs/utils/internalStorageKey.js.map +1 -0
  31. package/build/cjs/vite/agentClass.js +114 -0
  32. package/build/cjs/vite/agentClass.js.map +1 -0
  33. package/build/cjs/vite/autoInstrument.js +17 -4
  34. package/build/cjs/vite/autoInstrument.js.map +1 -1
  35. package/build/cjs/vite/index.js +1 -1
  36. package/build/cjs/vite/index.js.map +1 -1
  37. package/build/cjs/vite/moduleShape.js +231 -0
  38. package/build/cjs/vite/moduleShape.js.map +1 -0
  39. package/build/cjs/vite/transform.js +6 -1
  40. package/build/cjs/vite/transform.js.map +1 -1
  41. package/build/cjs/vite/wranglerConfig.js +1 -1
  42. package/build/cjs/vite/wranglerConfig.js.map +1 -1
  43. package/build/esm/client.js +6 -1
  44. package/build/esm/client.js.map +1 -1
  45. package/build/esm/durableobject.js +129 -97
  46. package/build/esm/durableobject.js.map +1 -1
  47. package/build/esm/index.js +2 -1
  48. package/build/esm/index.js.map +1 -1
  49. package/build/esm/instrumentations/agents/index.js +12 -0
  50. package/build/esm/instrumentations/agents/index.js.map +1 -0
  51. package/build/esm/instrumentations/agents/instrumentAgentCallableRpc.js +50 -0
  52. package/build/esm/instrumentations/agents/instrumentAgentCallableRpc.js.map +1 -0
  53. package/build/esm/instrumentations/agents/instrumentChatAgentConversation.js +29 -0
  54. package/build/esm/instrumentations/agents/instrumentChatAgentConversation.js.map +1 -0
  55. package/build/esm/instrumentations/agents/types.js +26 -0
  56. package/build/esm/instrumentations/agents/types.js.map +1 -0
  57. package/build/esm/instrumentations/instrumentDurableObjectStorage.js +7 -1
  58. package/build/esm/instrumentations/instrumentDurableObjectStorage.js.map +1 -1
  59. package/build/esm/instrumentations/instrumentSqlStorage.js +1 -1
  60. package/build/esm/instrumentations/instrumentSqlStorage.js.map +1 -1
  61. package/build/esm/integrations/spotlight.js +61 -0
  62. package/build/esm/integrations/spotlight.js.map +1 -0
  63. package/build/esm/nodejs_compat/index.js +2 -1
  64. package/build/esm/nodejs_compat/index.js.map +1 -1
  65. package/build/esm/options.js +14 -1
  66. package/build/esm/options.js.map +1 -1
  67. package/build/esm/package.json +1 -1
  68. package/build/esm/sdk.js +8 -0
  69. package/build/esm/sdk.js.map +1 -1
  70. package/build/esm/utils/internalSqlQuery.js +13 -7
  71. package/build/esm/utils/internalSqlQuery.js.map +1 -1
  72. package/build/esm/utils/internalStorageKey.js +41 -0
  73. package/build/esm/utils/internalStorageKey.js.map +1 -0
  74. package/build/esm/utils/traceLinks.js +1 -1
  75. package/build/esm/vite/agentClass.js +111 -0
  76. package/build/esm/vite/agentClass.js.map +1 -0
  77. package/build/esm/vite/autoInstrument.js +17 -4
  78. package/build/esm/vite/autoInstrument.js.map +1 -1
  79. package/build/esm/vite/index.js +1 -1
  80. package/build/esm/vite/index.js.map +1 -1
  81. package/build/esm/vite/moduleShape.js +227 -0
  82. package/build/esm/vite/moduleShape.js.map +1 -0
  83. package/build/esm/vite/transform.js +6 -1
  84. package/build/esm/vite/transform.js.map +1 -1
  85. package/build/esm/vite/wranglerConfig.js +1 -1
  86. package/build/esm/vite/wranglerConfig.js.map +1 -1
  87. package/build/types/client.d.ts +37 -0
  88. package/build/types/client.d.ts.map +1 -1
  89. package/build/types/durableobject.d.ts +81 -0
  90. package/build/types/durableobject.d.ts.map +1 -1
  91. package/build/types/index.d.ts +2 -1
  92. package/build/types/index.d.ts.map +1 -1
  93. package/build/types/instrumentations/agents/index.d.ts +24 -0
  94. package/build/types/instrumentations/agents/index.d.ts.map +1 -0
  95. package/build/types/instrumentations/agents/instrumentAgentCallableRpc.d.ts +11 -0
  96. package/build/types/instrumentations/agents/instrumentAgentCallableRpc.d.ts.map +1 -0
  97. package/build/types/instrumentations/agents/instrumentChatAgentConversation.d.ts +22 -0
  98. package/build/types/instrumentations/agents/instrumentChatAgentConversation.d.ts.map +1 -0
  99. package/build/types/instrumentations/agents/types.d.ts +49 -0
  100. package/build/types/instrumentations/agents/types.d.ts.map +1 -0
  101. package/build/types/instrumentations/instrumentDurableObjectStorage.d.ts.map +1 -1
  102. package/build/types/integrations/spotlight.d.ts +22 -0
  103. package/build/types/integrations/spotlight.d.ts.map +1 -0
  104. package/build/types/options.d.ts.map +1 -1
  105. package/build/types/sdk.d.ts.map +1 -1
  106. package/build/types/utils/internalSqlQuery.d.ts +4 -2
  107. package/build/types/utils/internalSqlQuery.d.ts.map +1 -1
  108. package/build/types/utils/internalStorageKey.d.ts +22 -0
  109. package/build/types/utils/internalStorageKey.d.ts.map +1 -0
  110. package/build/types/vite/agentClass.d.ts +41 -0
  111. package/build/types/vite/agentClass.d.ts.map +1 -0
  112. package/build/types/vite/autoInstrument.d.ts +7 -6
  113. package/build/types/vite/autoInstrument.d.ts.map +1 -1
  114. package/build/types/vite/index.d.ts +14 -4
  115. package/build/types/vite/index.d.ts.map +1 -1
  116. package/build/types/vite/moduleShape.d.ts +52 -0
  117. package/build/types/vite/moduleShape.d.ts.map +1 -0
  118. package/build/types/vite/transform.d.ts +6 -1
  119. package/build/types/vite/transform.d.ts.map +1 -1
  120. package/build/types-ts3.8/client.d.ts +37 -0
  121. package/build/types-ts3.8/durableobject.d.ts +81 -0
  122. package/build/types-ts3.8/index.d.ts +2 -1
  123. package/build/types-ts3.8/instrumentations/agents/index.d.ts +24 -0
  124. package/build/types-ts3.8/instrumentations/agents/instrumentAgentCallableRpc.d.ts +11 -0
  125. package/build/types-ts3.8/instrumentations/agents/instrumentChatAgentConversation.d.ts +22 -0
  126. package/build/types-ts3.8/instrumentations/agents/types.d.ts +49 -0
  127. package/build/types-ts3.8/integrations/spotlight.d.ts +22 -0
  128. package/build/types-ts3.8/utils/internalSqlQuery.d.ts +4 -2
  129. package/build/types-ts3.8/utils/internalStorageKey.d.ts +22 -0
  130. package/build/types-ts3.8/vite/agentClass.d.ts +41 -0
  131. package/build/types-ts3.8/vite/autoInstrument.d.ts +7 -6
  132. package/build/types-ts3.8/vite/index.d.ts +14 -4
  133. package/build/types-ts3.8/vite/moduleShape.d.ts +52 -0
  134. package/build/types-ts3.8/vite/transform.d.ts +6 -1
  135. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"autoInstrument.js","sources":["../../../src/vite/autoInstrument.ts"],"sourcesContent":["import { buildOptionsImport, ENV_FALLBACK_OPTIONS_FN, resolveInstrumentFile } from './instrumentFile';\nimport { applyAutoInstrumentTransforms, type ClassWrapperKind, type ProgramBody } from './transform';\nimport { resolveWranglerConfig, type WranglerConfig } from './wranglerConfig';\n\n// Vite normalizes module IDs to posix separators even on Windows, while\n// `path.resolve` yields backslashes there — normalize before comparing.\nfunction normalizePath(path: string): string {\n return path.replace(/\\\\/g, '/');\n}\n\n// Extensions the entry-module match may tolerate swapping (e.g. wrangler's\n// `main` says `.ts` but the served module is `.js`). Anything else — `.css`,\n// `.html`, … — sharing the entry's basename must never be treated as the entry.\nconst JS_EXTENSION_REGEX = /\\.[cm]?[jt]sx?$/;\n\nexport function sentryCloudflareAutoInstrumentPlugin() {\n let wranglerConfig: WranglerConfig | undefined;\n let entryFilePath: string | undefined;\n\n let optionsFn = ENV_FALLBACK_OPTIONS_FN;\n let optionsImport: string | undefined;\n\n return {\n name: 'sentry-cloudflare-auto-instrument',\n\n configResolved(config: { root: string; logger?: { warn(msg: string): void } }): void {\n const result = resolveWranglerConfig(config.root);\n if (!result) {\n config.logger?.warn('[sentry] No parseable wrangler config found — auto-instrumentation disabled.');\n return;\n }\n\n wranglerConfig = result.config;\n if (wranglerConfig.main) {\n // `main` is already absolute (wrangler resolves it); just normalize\n // separators so the entry-module comparison holds on Windows.\n entryFilePath = normalizePath(wranglerConfig.main);\n }\n\n if (entryFilePath) {\n const instrumentFilePath = resolveInstrumentFile(entryFilePath);\n if (instrumentFilePath) {\n const built = buildOptionsImport(entryFilePath, instrumentFilePath);\n optionsFn = built.optionsFn;\n optionsImport = built.importStmt;\n }\n }\n },\n\n transform(\n this: { parse(code: string): ProgramBody; warn?(msg: string): void; environment?: { name?: string } },\n code: string,\n id: string,\n ): { code: string; map: unknown } | undefined {\n if (!wranglerConfig || !entryFilePath) return undefined;\n\n // The worker entry never belongs to the client (browser) environment.\n // Skipping it keeps a same-basename sibling (e.g. a `src/index.tsx`\n // client entry next to a `src/index.ts` worker) out of the browser bundle.\n if (this.environment?.name === 'client') return undefined;\n\n // Vite may append query/hash params to the module ID.\n const normalizedId = normalizePath(id.replace(/[?#].*$/, ''));\n if (normalizedId !== entryFilePath) {\n // Tolerate a differing JS-flavored extension (e.g. `.js` vs `.ts`).\n if (!JS_EXTENSION_REGEX.test(normalizedId) || !JS_EXTENSION_REGEX.test(entryFilePath)) return undefined;\n if (normalizedId.replace(JS_EXTENSION_REGEX, '') !== entryFilePath.replace(JS_EXTENSION_REGEX, '')) {\n return undefined;\n }\n }\n\n let ast: ProgramBody;\n try {\n ast = this.parse(code);\n } catch {\n // Raw TypeScript or syntax error — esbuild hasn't run yet (unlikely)\n // or the file is genuinely broken. Either way, skip silently.\n return undefined;\n }\n\n const classWrappers = new Map<string, ClassWrapperKind>();\n for (const { className } of wranglerConfig.durableObjects) {\n classWrappers.set(className, 'durableObject');\n }\n for (const { className } of wranglerConfig.workflows) {\n classWrappers.set(className, 'workflow');\n }\n for (const className of wranglerConfig.workerEntrypoints) {\n classWrappers.set(className, 'workerEntrypoint');\n }\n\n // No registration import is injected here: the orchestrion plugin's\n // subscribe-injection makes each bundled package self-register its channel\n // subscriber on the global marker, so wrapping the entry with `withSentry`\n // is all this plugin needs to do.\n const result = applyAutoInstrumentTransforms(code, ast, {\n classWrappers,\n optionsFn,\n optionsImport,\n });\n\n const wrappedClasses = result?.wrappedClasses ?? new Set<string>();\n const missing = [...classWrappers.keys()].filter(name => !wrappedClasses.has(name));\n if (missing.length > 0) {\n this.warn?.(\n `[sentry] Could not auto-instrument class(es) ${missing.join(', ')}: no matching exported class ` +\n 'declaration found in the worker entry (re-exports from other modules cannot be wrapped ' +\n 'automatically). Wrap them manually with the matching `instrument*WithSentry` helper.',\n );\n }\n\n return result ?? undefined;\n },\n };\n}\n"],"names":[],"mappings":";;;;AAMA,SAAS,cAAc,IAAA,EAAsB;AAC3C,EAAA,OAAO,IAAA,CAAK,OAAA,C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CAAA,IAAA,KAAQ,CAAC,cAAA,CAAe,GAAA,CAAI,IAAI,CAAC,CAAA;AAClF,MAAA,IAAI,OAAA,CAAQ,SAAS,CAAA,EAAG;AACtB,QAAA,IAAA,CAAK,IAAA;AAAA,UACH,CAAA,6CAAA,EAAgD,OAAA,CAAQ,IAAA,CAAK,IAAI,CAAC,CAAA,0MAAA;AAAA,SAGpE;AAAA,MACF;AAEA,MAAA,OAAO,MAAA,IAAU,MAAA;AAAA,IACnB;AAAA,GACF;AACF;;;;"}
1
+ {"version":3,"file":"autoInstrument.js","sources":["../../../src/vite/autoInstrument.ts"],"sourcesContent":["import { basename } from 'node:path';\nimport { collectAgentCandidates, detectAgentClasses, type ModuleResolver } from './agentClass';\nimport { buildOptionsImport, ENV_FALLBACK_OPTIONS_FN, resolveInstrumentFile } from './instrumentFile';\nimport { applyAutoInstrumentTransforms, type ClassWrapperKind, type ProgramBody } from './transform';\nimport { resolveWranglerConfig, type WranglerConfig } from './wranglerConfig';\n\n// Vite normalizes module IDs to posix separators even on Windows, while\n// `path.resolve` yields backslashes there — normalize before comparing.\nfunction normalizePath(path: string): string {\n return path.replace(/\\\\/g, '/');\n}\n\n// Extensions the entry-module match may tolerate swapping (e.g. wrangler's\n// `main` says `.ts` but the served module is `.js`). Anything else — `.css`,\n// `.html`, … — sharing the entry's basename must never be treated as the entry.\nconst JS_EXTENSION_REGEX = /\\.[cm]?[jt]sx?$/;\n\nexport function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPath?: string } = {}) {\n let wranglerConfig: WranglerConfig | undefined;\n let entryFilePath: string | undefined;\n\n let optionsFn = ENV_FALLBACK_OPTIONS_FN;\n let optionsImport: string | undefined;\n\n return {\n name: 'sentry-cloudflare-auto-instrument',\n\n configResolved(config: { root: string; logger?: { warn(msg: string): void } }): void {\n const result = resolveWranglerConfig(config.root, options.wranglerConfigPath);\n if (!result) {\n // An explicit path that fails is a misconfiguration worth naming;\n // without one, hint at the option so custom-named configs (e.g. a\n // `configPath` handed to @cloudflare/vite-plugin) are discoverable.\n config.logger?.warn(\n options.wranglerConfigPath\n ? `[sentry] Could not find or parse the wrangler config \"${basename(options.wranglerConfigPath)}\" ` +\n '(resolved against the Vite root) — auto-instrumentation disabled.'\n : '[sentry] No parseable wrangler config found — auto-instrumentation disabled. ' +\n 'Set `wranglerConfigPath` if your config uses a custom name.',\n );\n return;\n }\n\n wranglerConfig = result.config;\n if (wranglerConfig.main) {\n // `main` is already absolute (wrangler resolves it); just normalize\n // separators so the entry-module comparison holds on Windows.\n entryFilePath = normalizePath(wranglerConfig.main);\n }\n\n if (entryFilePath) {\n const instrumentFilePath = resolveInstrumentFile(entryFilePath);\n if (instrumentFilePath) {\n const built = buildOptionsImport(entryFilePath, instrumentFilePath);\n optionsFn = built.optionsFn;\n optionsImport = built.importStmt;\n }\n }\n },\n\n async transform(\n this: ModuleResolver & { warn?(msg: string): void; environment?: { name?: string } },\n code: string,\n id: string,\n ): Promise<{ code: string; map: unknown } | undefined> {\n if (!wranglerConfig || !entryFilePath) return undefined;\n\n // The worker entry never belongs to the client (browser) environment.\n // Skipping it keeps a same-basename sibling (e.g. a `src/index.tsx`\n // client entry next to a `src/index.ts` worker) out of the browser bundle.\n if (this.environment?.name === 'client') return undefined;\n\n // Vite may append query/hash params to the module ID.\n const normalizedId = normalizePath(id.replace(/[?#].*$/, ''));\n if (normalizedId !== entryFilePath) {\n // Tolerate a differing JS-flavored extension (e.g. `.js` vs `.ts`).\n if (!JS_EXTENSION_REGEX.test(normalizedId) || !JS_EXTENSION_REGEX.test(entryFilePath)) return undefined;\n if (normalizedId.replace(JS_EXTENSION_REGEX, '') !== entryFilePath.replace(JS_EXTENSION_REGEX, '')) {\n return undefined;\n }\n }\n\n let ast: ProgramBody;\n try {\n ast = this.parse(code);\n } catch {\n // Raw TypeScript or syntax error — esbuild hasn't run yet (unlikely)\n // or the file is genuinely broken. Either way, skip silently.\n return undefined;\n }\n\n const classWrappers = new Map<string, ClassWrapperKind>();\n for (const { className } of wranglerConfig.durableObjects) {\n classWrappers.set(className, 'durableObject');\n }\n for (const { className } of wranglerConfig.workflows) {\n classWrappers.set(className, 'workflow');\n }\n for (const className of wranglerConfig.workerEntrypoints) {\n classWrappers.set(className, 'workerEntrypoint');\n }\n\n // An `agents` Agent is a Durable Object, so wrangler lists it among the DO bindings and only\n // its base-class chain tells the two apart. Detection walks the module graph (base classes\n // usually live in their own file), so it is limited to the configured DO classes.\n //\n // Only `resolve` is handed over — never `load`: awaiting `load()` from inside a transform\n // hook deadlocks the build, since the module can't finish loading while this transform is\n // still pending. `agentClass` reads sibling modules off disk instead.\n const agentCandidates = collectAgentCandidates(\n ast,\n [...classWrappers].filter(([, kind]) => kind === 'durableObject').map(([name]) => name),\n );\n const agentClasses =\n agentCandidates.size > 0\n ? await detectAgentClasses(ast, normalizedId, agentCandidates, {\n parse: code => this.parse(code),\n resolve: this.resolve ? (source, importer) => this.resolve!(source, importer) : undefined,\n })\n : undefined;\n\n // No registration import is injected here: the orchestrion plugin's\n // subscribe-injection makes each bundled package self-register its channel\n // subscriber on the global marker, so wrapping the entry with `withSentry`\n // is all this plugin needs to do.\n const result = applyAutoInstrumentTransforms(code, ast, {\n classWrappers,\n agentClasses,\n optionsFn,\n optionsImport,\n });\n\n const wrappedClasses = result?.wrappedClasses ?? new Set<string>();\n const missing = [...classWrappers.keys()].filter(name => !wrappedClasses.has(name));\n if (missing.length > 0) {\n this.warn?.(\n `[sentry] Could not auto-instrument class(es) ${missing.join(', ')}: no matching exported class ` +\n 'declaration found in the worker entry (re-exports from other modules cannot be wrapped ' +\n 'automatically). Wrap them manually with the matching `instrument*WithSentry` helper.',\n );\n }\n\n return result ?? undefined;\n },\n };\n}\n"],"names":["code"],"mappings":";;;;;;AAQA,SAAS,cAAc,IAAA,EAAsB;AAC3C,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA;AAChC;AAKA,MAAM,kBAAA,GAAqB,iBAAA;AAEpB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AAAA,OACxF;AACA,MAAA,MAAM,YAAA,GACJ,gBAAgB,IAAA,GAAO,CAAA,GACnB,MAAM,kBAAA,CAAmB,GAAA,EAAK,cAAc,eAAA,EAAiB;AAAA,QAC3D,KAAA,EAAO,CAAAA,KAAAA,KAAQ,IAAA,CAAK,MAAMA,KAAI,CAAA;AAAA,QAC9B,OAAA,EAAS,IAAA,CAAK,OAAA,GAAU,CAAC,MAAA,EAAQ,aAAa,IAAA,CAAK,OAAA,CAAS,MAAA,EAAQ,QAAQ,CAAA,GAAI;AAAA,OACjF,CAAA,GACD,MAAA;AAMN,MAAA,MAAM,MAAA,GAAS,6BAAA,CAA8B,IAAA,EAAM,GAAA,EAAK;AAAA,QACtD,aAAA;AAAA,QACA,YAAA;AAAA,QACA,SAAA;AAAA,QACA;AAAA,OACD,CAAA;AAED,MAAA,MAAM,cAAA,GAAiB,MAAA,EAAQ,cAAA,oBAAkB,IAAI,GAAA,EAAY;AACjE,MAAA,MAAM,OAAA,GAAU,CAAC,GAAG,aAAA,CAAc,IAAA,EAAM,CAAA,CAAE,MAAA,CAAO,CAAA,IAAA,KAAQ,CAAC,cAAA,CAAe,GAAA,CAAI,IAAI,CAAC,CAAA;AAClF,MAAA,IAAI,OAAA,CAAQ,SAAS,CAAA,EAAG;AACtB,QAAA,IAAA,CAAK,IAAA;AAAA,UACH,CAAA,6CAAA,EAAgD,OAAA,CAAQ,IAAA,CAAK,IAAI,CAAC,CAAA,0MAAA;AAAA,SAGpE;AAAA,MACF;AAEA,MAAA,OAAO,MAAA,IAAU,MAAA;AAAA,IACnB;AAAA,GACF;AACF;;;;"}
@@ -4,7 +4,7 @@ import { sentryCloudflareAutoInstrumentPlugin } from './autoInstrument.js';
4
4
  function sentryCloudflareVitePlugin(options = {}) {
5
5
  return [
6
6
  ...options._experimental?.useDiagnosticsChannelInjection ? [sentryOrchestrionPlugin({ injectChannelSubscribers: true })] : [],
7
- ...options._experimental?.autoInstrumentation ? [sentryCloudflareAutoInstrumentPlugin()] : []
7
+ ...options._experimental?.autoInstrumentation ? [sentryCloudflareAutoInstrumentPlugin({ wranglerConfigPath: options.wranglerConfigPath })] : []
8
8
  ];
9
9
  }
10
10
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../src/vite/index.ts"],"sourcesContent":["// Published ESM-only via the `@sentry/cloudflare/vite` subpath export:\n// `@sentry/server-utils/orchestrion/vite` exposes no `require` condition, so a\n// CJS entry here would fail at resolution time (ERR_PACKAGE_PATH_NOT_EXPORTED).\n// The CJS rollup variant still emits this file, but `package.json` doesn't\n// expose it — same setup as `@sentry/server-utils/orchestrion/vite` itself.\nimport { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';\nimport { sentryCloudflareAutoInstrumentPlugin } from './autoInstrument';\n\n/**\n * Options for {@link sentryCloudflareVitePlugin}.\n */\nexport interface SentryCloudflareVitePluginOptions {\n /**\n * Experimental options that may change or be removed without notice.\n */\n _experimental?: {\n /**\n * Enables build-time automatic instrumentation of supported dependencies\n * (e.g. database clients like `mysql`) so the Sentry Cloudflare SDK can\n * trace them without monkey-patching, which wouldn't work in workerd anyway.\n *\n * When enabled, the plugin injects `diagnostics_channel.tracingChannel`\n * calls into the bundled packages and, next to each, a snippet that\n * registers the matching Sentry channel-subscriber factory on the global\n * marker, which the SDK picks up in `Sentry.withSentry()`. Both `vite build`\n * and `vite dev` are instrumented.\n *\n * @default false\n * @experimental May change or be removed in any release.\n */\n useDiagnosticsChannelInjection?: boolean;\n /**\n * Automatically wraps your Worker at build time so you don't have to edit\n * your entry: the plugin reads your wrangler config, wraps the default\n * export with `Sentry.withSentry()` (sourcing options from a co-located\n * `instrument.*` file, falling back to env), and wraps any configured\n * Durable Object class with `instrumentDurableObjectWithSentry`. Both\n * `vite build` and `vite dev` are instrumented.\n *\n * @default false\n * @experimental May change or be removed in any release.\n */\n autoInstrumentation?: boolean;\n };\n}\n\n/**\n * Sentry Vite plugin for Cloudflare Workers.\n *\n * Add this plugin to your Vite configuration to enable additional Sentry\n * instrumentation for Cloudflare Workers built with Vite. Configure the Sentry\n * SDK in your Worker as usual with `Sentry.withSentry()`.\n *\n * Currently, the only functionality is the experimental\n * `_experimental.useDiagnosticsChannelInjection` option, which traces supported\n * dependencies (such as database clients) without changing your application\n * code. Without it, the plugin is a no-op.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { cloudflare } from '@cloudflare/vite-plugin';\n * import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite';\n * import { defineConfig } from 'vite';\n *\n * export default defineConfig({\n * plugins: [\n * cloudflare(),\n * sentryCloudflareVitePlugin({\n * _experimental: {\n * useDiagnosticsChannelInjection: true,\n * },\n * }),\n * ],\n * });\n * ```\n */\nexport function sentryCloudflareVitePlugin(options: SentryCloudflareVitePluginOptions = {}) {\n return [\n ...(options._experimental?.useDiagnosticsChannelInjection\n ? [sentryOrchestrionPlugin({ injectChannelSubscribers: true })]\n : []),\n ...(options._experimental?.autoInstrumentation ? [sentryCloudflareAutoInstrumentPlugin()] : []),\n ];\n}\n"],"names":[],"mappings":";;;AA6EO,SAAS,0BAAA,CAA2B,OAAA,GAA6C,EAAC,EAAG;AAC1F,EAAA,OAAO;AAAA,IACL,GAAI,OAAA,CAAQ,aAAA,EAAe,8BAAA,GACvB,CAAC,uBAAA,CAAwB,EAAE,wBAAA,EAA0B,IAAA,EAAM,CAAC,CAAA,GAC5D,EAAC;AAAA,IACL,GAAI,QAAQ,aAAA,EAAe,mBAAA,GAAsB,CAAC,oCAAA,EAAsC,IAAI;AAAC,GAC/F;AACF;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../../../src/vite/index.ts"],"sourcesContent":["// Published ESM-only via the `@sentry/cloudflare/vite` subpath export:\n// `@sentry/server-utils/orchestrion/vite` exposes no `require` condition, so a\n// CJS entry here would fail at resolution time (ERR_PACKAGE_PATH_NOT_EXPORTED).\n// The CJS rollup variant still emits this file, but `package.json` doesn't\n// expose it — same setup as `@sentry/server-utils/orchestrion/vite` itself.\nimport { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';\nimport { sentryCloudflareAutoInstrumentPlugin } from './autoInstrument';\n\n/**\n * Options for {@link sentryCloudflareVitePlugin}.\n */\nexport interface SentryCloudflareVitePluginOptions {\n /**\n * Path to the wrangler config, relative to the Vite root (or absolute).\n * Set this when your config doesn't use a default name — e.g. when you\n * pass `configPath: './wrangler.agent.jsonc'` to `@cloudflare/vite-plugin`,\n * which the Sentry plugin cannot see. When set, only this file is read\n * (no default-name probing), and a warning is emitted if it is missing or\n * unparseable.\n *\n * @default undefined (probes `wrangler.json`, `wrangler.jsonc`, `wrangler.toml` at the Vite root)\n */\n wranglerConfigPath?: string;\n /**\n * Experimental options that may change or be removed without notice.\n */\n _experimental?: {\n /**\n * Enables build-time automatic instrumentation of supported dependencies\n * (e.g. database clients like `mysql`) so the Sentry Cloudflare SDK can\n * trace them without monkey-patching, which wouldn't work in workerd anyway.\n *\n * When enabled, the plugin injects `diagnostics_channel.tracingChannel`\n * calls into the bundled packages and, next to each, a snippet that\n * registers the matching Sentry channel-subscriber factory on the global\n * marker, which the SDK picks up in `Sentry.withSentry()`. Both `vite build`\n * and `vite dev` are instrumented.\n *\n * @default false\n * @experimental May change or be removed in any release.\n */\n useDiagnosticsChannelInjection?: boolean;\n /**\n * Automatically wraps your Worker at build time so you don't have to edit\n * your entry: the plugin reads your wrangler config, wraps the default\n * export with `Sentry.withSentry()` (sourcing options from a co-located\n * `instrument.*` file, falling back to env), and wraps any configured\n * Durable Object class with `instrumentDurableObjectWithSentry`. Both\n * `vite build` and `vite dev` are instrumented.\n *\n * @default false\n * @experimental May change or be removed in any release.\n */\n autoInstrumentation?: boolean;\n };\n}\n\n/**\n * Sentry Vite plugin for Cloudflare Workers.\n *\n * Add this plugin to your Vite configuration to enable additional Sentry\n * instrumentation for Cloudflare Workers built with Vite. Configure the Sentry\n * SDK in your Worker as usual with `Sentry.withSentry()`.\n *\n * Currently, the only functionality is the experimental\n * `_experimental.useDiagnosticsChannelInjection` option, which traces supported\n * dependencies (such as database clients) without changing your application\n * code. Without it, the plugin is a no-op.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { cloudflare } from '@cloudflare/vite-plugin';\n * import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite';\n * import { defineConfig } from 'vite';\n *\n * export default defineConfig({\n * plugins: [\n * cloudflare(),\n * sentryCloudflareVitePlugin({\n * _experimental: {\n * useDiagnosticsChannelInjection: true,\n * },\n * }),\n * ],\n * });\n * ```\n */\nexport function sentryCloudflareVitePlugin(options: SentryCloudflareVitePluginOptions = {}) {\n return [\n ...(options._experimental?.useDiagnosticsChannelInjection\n ? [sentryOrchestrionPlugin({ injectChannelSubscribers: true })]\n : []),\n ...(options._experimental?.autoInstrumentation\n ? [sentryCloudflareAutoInstrumentPlugin({ wranglerConfigPath: options.wranglerConfigPath })]\n : []),\n ];\n}\n"],"names":[],"mappings":";;;AAwFO,SAAS,0BAAA,CAA2B,OAAA,GAA6C,EAAC,EAAG;AAC1F,EAAA,OAAO;AAAA,IACL,GAAI,OAAA,CAAQ,aAAA,EAAe,8BAAA,GACvB,CAAC,uBAAA,CAAwB,EAAE,wBAAA,EAA0B,IAAA,EAAM,CAAC,CAAA,GAC5D,EAAC;AAAA,IACL,GAAI,OAAA,CAAQ,aAAA,EAAe,mBAAA,GACvB,CAAC,oCAAA,CAAqC,EAAE,kBAAA,EAAoB,OAAA,CAAQ,kBAAA,EAAoB,CAAC,IACzF;AAAC,GACP;AACF;;;;"}
@@ -0,0 +1,227 @@
1
+ const DEFAULT_EXPORT = "default";
2
+ function emptyShape() {
3
+ return {
4
+ classes: /* @__PURE__ */ new Map(),
5
+ imports: /* @__PURE__ */ new Map(),
6
+ namespaces: /* @__PURE__ */ new Map(),
7
+ reexports: /* @__PURE__ */ new Map(),
8
+ localExports: /* @__PURE__ */ new Map(),
9
+ starExports: []
10
+ };
11
+ }
12
+ function shapeFromAst(ast) {
13
+ const shape = emptyShape();
14
+ for (const node of ast.body) {
15
+ switch (node.type) {
16
+ case "ClassDeclaration":
17
+ addAstClass(shape, node);
18
+ break;
19
+ case "ImportDeclaration":
20
+ addAstImports(shape, node);
21
+ break;
22
+ case "ExportNamedDeclaration":
23
+ addAstNamedExport(shape, node);
24
+ break;
25
+ case "ExportDefaultDeclaration": {
26
+ const decl = node.declaration;
27
+ if (decl.type === "ClassDeclaration" || decl.type === "ClassExpression") {
28
+ shape.defaultExportIsClass = true;
29
+ shape.defaultExportSuper = superRefFromNode(decl.superClass);
30
+ addAstClass(shape, decl);
31
+ } else if (decl.type === "Identifier") {
32
+ shape.defaultExportName = decl.name;
33
+ }
34
+ break;
35
+ }
36
+ case "ExportAllDeclaration": {
37
+ const starNode = node;
38
+ const source = starNode.exported ? void 0 : asString(starNode.source?.value);
39
+ if (source) shape.starExports.push(source);
40
+ break;
41
+ }
42
+ }
43
+ }
44
+ return shape;
45
+ }
46
+ function superRefFromNode(superClass) {
47
+ if (!superClass) return void 0;
48
+ if (superClass.type === "Identifier") {
49
+ return { kind: "identifier", name: superClass.name };
50
+ }
51
+ if (superClass.type === "MemberExpression") {
52
+ const member = superClass;
53
+ const object = member.object?.type === "Identifier" ? member.object.name : void 0;
54
+ const property = member.property?.name;
55
+ if (object && property) return { kind: "member", object, property };
56
+ }
57
+ return void 0;
58
+ }
59
+ function addAstClass(shape, classNode) {
60
+ if (classNode.id?.name) shape.classes.set(classNode.id.name, superRefFromNode(classNode.superClass));
61
+ }
62
+ function addAstImports(shape, node) {
63
+ const source = asString(node.source?.value);
64
+ if (!source) return;
65
+ for (const specifier of node.specifiers ?? []) {
66
+ const local = specifier.local?.name;
67
+ if (!local) continue;
68
+ if (specifier.type === "ImportSpecifier" && specifier.imported?.name) {
69
+ shape.imports.set(local, { source, imported: specifier.imported.name });
70
+ } else if (specifier.type === "ImportDefaultSpecifier") {
71
+ shape.imports.set(local, { source, imported: DEFAULT_EXPORT });
72
+ } else if (specifier.type === "ImportNamespaceSpecifier") {
73
+ shape.namespaces.set(local, source);
74
+ }
75
+ }
76
+ }
77
+ function addAstNamedExport(shape, node) {
78
+ if (node.declaration?.type === "ClassDeclaration") {
79
+ addAstClass(shape, node.declaration);
80
+ return;
81
+ }
82
+ const source = asString(node.source?.value);
83
+ for (const specifier of node.specifiers ?? []) {
84
+ const exported = specifier.exported?.name;
85
+ const local = specifier.local?.name;
86
+ if (!exported || !local) continue;
87
+ if (source) {
88
+ shape.reexports.set(exported, { source, imported: local });
89
+ } else {
90
+ shape.localExports.set(exported, local);
91
+ }
92
+ }
93
+ }
94
+ function shapeFromSource(rawCode) {
95
+ const code = stripComments(rawCode);
96
+ const shape = emptyShape();
97
+ const CLASS_RE = /\b(?:export\s+(?:default\s+)?)?(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)([^{]*)\{/g;
98
+ for (const match of code.matchAll(CLASS_RE)) {
99
+ const className = match[1];
100
+ const isDefault = /\bexport\s+default\b/.test(match[0]);
101
+ const superRef = superRefFromHeader(match[2] ?? "");
102
+ shape.classes.set(className, superRef);
103
+ if (isDefault) {
104
+ shape.defaultExportIsClass = true;
105
+ shape.defaultExportSuper = superRef;
106
+ }
107
+ }
108
+ const defaultExprMatch = /\bexport\s+default\s+([A-Za-z_$][\w$]*)\s*;/.exec(code);
109
+ if (defaultExprMatch && !shape.defaultExportIsClass) {
110
+ shape.defaultExportName = defaultExprMatch[1];
111
+ }
112
+ for (const match of code.matchAll(/\bexport\s*\*\s*from\s*['"]([^'"]+)['"]/g)) {
113
+ if (match[1]) shape.starExports.push(match[1]);
114
+ }
115
+ for (const match of code.matchAll(/\bexport\s*\{([^}]*)\}\s*(?:from\s*['"]([^'"]+)['"])?/g)) {
116
+ const source = match[2];
117
+ for (const { imported, local } of parseSpecifierList(match[1] ?? "")) {
118
+ if (source) {
119
+ shape.reexports.set(local, { source, imported });
120
+ } else {
121
+ shape.localExports.set(local, imported);
122
+ }
123
+ }
124
+ }
125
+ for (const match of code.matchAll(/\bimport\s+([^'";]+?)\s+from\s*['"]([^'"]+)['"]/g)) {
126
+ addSourceImports(shape, match[1] ?? "", match[2]);
127
+ }
128
+ return shape;
129
+ }
130
+ function superRefFromHeader(header) {
131
+ const withoutParams = stripLeadingGenerics(header);
132
+ const match = /\bextends\s+([A-Za-z_$][\w$]*)\s*(?:\.\s*([A-Za-z_$][\w$]*))?/.exec(withoutParams);
133
+ if (!match) return void 0;
134
+ return match[2] ? { kind: "member", object: match[1], property: match[2] } : { kind: "identifier", name: match[1] };
135
+ }
136
+ function stripLeadingGenerics(header) {
137
+ const start = header.indexOf("<");
138
+ if (start === -1 || header.slice(0, start).trim() !== "") return header;
139
+ let depth = 0;
140
+ for (let i = start; i < header.length; i++) {
141
+ const char = header[i];
142
+ if (char === "<") depth++;
143
+ else if (char === ">") {
144
+ depth--;
145
+ if (depth === 0) return header.slice(i + 1);
146
+ }
147
+ }
148
+ return header;
149
+ }
150
+ function parseSpecifierList(clause) {
151
+ const specifiers = [];
152
+ for (const rawPart of clause.split(",")) {
153
+ const part = rawPart.trim().replace(/^type\s+/, "");
154
+ if (!part) continue;
155
+ const aliased = /^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/.exec(part);
156
+ if (aliased) {
157
+ specifiers.push({ imported: aliased[1], local: aliased[2] });
158
+ } else if (/^[A-Za-z_$][\w$]*$/.test(part)) {
159
+ specifiers.push({ imported: part, local: part });
160
+ }
161
+ }
162
+ return specifiers;
163
+ }
164
+ function addSourceImports(shape, clause, source) {
165
+ if (/^type\s/.test(clause.trim())) return;
166
+ const namespaceMatch = /\*\s*as\s+([A-Za-z_$][\w$]*)/.exec(clause);
167
+ if (namespaceMatch) {
168
+ shape.namespaces.set(namespaceMatch[1], source);
169
+ }
170
+ const bracesMatch = /\{([^}]*)\}/.exec(clause);
171
+ if (bracesMatch) {
172
+ for (const { imported, local } of parseSpecifierList(bracesMatch[1] ?? "")) {
173
+ shape.imports.set(local, { source, imported });
174
+ }
175
+ }
176
+ const defaultMatch = /^\s*([A-Za-z_$][\w$]*)\s*(?:,|$)/.exec(clause);
177
+ if (defaultMatch) {
178
+ shape.imports.set(defaultMatch[1], { source, imported: DEFAULT_EXPORT });
179
+ }
180
+ }
181
+ function stripComments(code) {
182
+ let result = "";
183
+ let index = 0;
184
+ while (index < code.length) {
185
+ const char = code[index];
186
+ const next = code[index + 1];
187
+ if (char === "/" && next === "/") {
188
+ while (index < code.length && code[index] !== "\n") index++;
189
+ continue;
190
+ }
191
+ if (char === "/" && next === "*") {
192
+ index += 2;
193
+ while (index < code.length && !(code[index] === "*" && code[index + 1] === "/")) index++;
194
+ index += 2;
195
+ result += " ";
196
+ continue;
197
+ }
198
+ if (char === '"' || char === "'" || char === "`") {
199
+ const quote = char;
200
+ result += char;
201
+ index++;
202
+ while (index < code.length) {
203
+ const inner = code[index];
204
+ result += inner;
205
+ index++;
206
+ if (inner === "\\") {
207
+ if (index < code.length) {
208
+ result += code[index];
209
+ index++;
210
+ }
211
+ continue;
212
+ }
213
+ if (inner === quote) break;
214
+ }
215
+ continue;
216
+ }
217
+ result += char;
218
+ index++;
219
+ }
220
+ return result;
221
+ }
222
+ function asString(value) {
223
+ return typeof value === "string" && value ? value : void 0;
224
+ }
225
+
226
+ export { DEFAULT_EXPORT, shapeFromAst, shapeFromSource };
227
+ //# sourceMappingURL=moduleShape.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"moduleShape.js","sources":["../../../src/vite/moduleShape.ts"],"sourcesContent":["import type { BaseNode, ProgramBody } from './transform';\n\n// ---------------------------------------------------------------------------\n// Minimal ESTree node shapes for structural Agent detection.\n// ---------------------------------------------------------------------------\n\ninterface IdentifierNode extends BaseNode {\n name: string;\n}\n\ninterface ClassNode extends BaseNode {\n id?: IdentifierNode | null;\n superClass?: BaseNode | null;\n}\n\ninterface MemberExpressionNode extends BaseNode {\n object?: { type: string; name?: string };\n property?: { type: string; name?: string };\n}\n\ninterface ImportSpecifierNode {\n type: string;\n imported?: { type: string; name?: string };\n local?: { type: string; name?: string };\n}\n\ninterface ImportDeclarationNode extends BaseNode {\n source?: { value?: unknown };\n specifiers?: ImportSpecifierNode[];\n}\n\ninterface ExportSpecifierNode {\n type: string;\n local?: { type: string; name?: string };\n exported?: { type: string; name?: string };\n}\n\ninterface ExportNamedNode extends BaseNode {\n declaration?: BaseNode | null;\n source?: { value?: unknown } | null;\n specifiers?: ExportSpecifierNode[];\n}\n\ninterface ExportDefaultNode extends BaseNode {\n declaration: BaseNode;\n}\n\ninterface ExportAllNode extends BaseNode {\n source?: { value?: unknown };\n exported?: { type: string; name?: string } | null;\n}\n\n/** Binding name used for a module's default export. */\nexport const DEFAULT_EXPORT = 'default';\n\n/** A resolved superclass reference: a bare identifier or a `ns.Member` expression. */\nexport type SuperRef = { kind: 'identifier'; name: string } | { kind: 'member'; object: string; property: string };\n\n/** The declarations of a single module that binding resolution needs. */\nexport interface ModuleShape {\n /** Top-level class names → their superclass reference (absent when the class has no `extends`). */\n classes: Map<string, SuperRef | undefined>;\n /** Local binding name → the import it came from (`imported` is `default` for a default import). */\n imports: Map<string, { source: string; imported: string }>;\n /** Local binding name → module specifier, for `import * as ns from '...'`. */\n namespaces: Map<string, string>;\n /** Exported name → the re-export it came from, for `export { x as y } from '...'`. */\n reexports: Map<string, { source: string; imported: string }>;\n /** Exported name → local binding name, for `export { x as y }` without a source. */\n localExports: Map<string, string>;\n /** Module specifiers of bare `export * from '...'` declarations. */\n starExports: string[];\n /** `export default <Identifier>` — the local name it refers to. */\n defaultExportName?: string;\n /** True when the module's default export is a class declaration/expression. */\n defaultExportIsClass?: boolean;\n /** Superclass of an anonymous `export default class extends X`. */\n defaultExportSuper?: SuperRef;\n}\n\nfunction emptyShape(): ModuleShape {\n return {\n classes: new Map(),\n imports: new Map(),\n namespaces: new Map(),\n reexports: new Map(),\n localExports: new Map(),\n starExports: [],\n };\n}\n\n// ---------------------------------------------------------------------------\n// Shape from a parsed AST (used for the entry module)\n// ---------------------------------------------------------------------------\n\n/** Collect the shape of a module from its parsed AST — used for the already-parsed entry module. */\nexport function shapeFromAst(ast: ProgramBody): ModuleShape {\n const shape = emptyShape();\n\n for (const node of ast.body) {\n switch (node.type) {\n case 'ClassDeclaration':\n addAstClass(shape, node as ClassNode);\n break;\n case 'ImportDeclaration':\n addAstImports(shape, node as ImportDeclarationNode);\n break;\n case 'ExportNamedDeclaration':\n addAstNamedExport(shape, node as ExportNamedNode);\n break;\n case 'ExportDefaultDeclaration': {\n const decl = (node as ExportDefaultNode).declaration;\n if (decl.type === 'ClassDeclaration' || decl.type === 'ClassExpression') {\n shape.defaultExportIsClass = true;\n shape.defaultExportSuper = superRefFromNode((decl as ClassNode).superClass);\n // `export default class Foo {}` also binds `Foo` locally.\n addAstClass(shape, decl as ClassNode);\n } else if (decl.type === 'Identifier') {\n shape.defaultExportName = (decl as IdentifierNode).name;\n }\n break;\n }\n case 'ExportAllDeclaration': {\n const starNode = node as ExportAllNode;\n // `export * as ns from '...'` binds a namespace object, not the individual exports.\n const source = starNode.exported ? undefined : asString(starNode.source?.value);\n if (source) shape.starExports.push(source);\n break;\n }\n }\n }\n\n return shape;\n}\n\nfunction superRefFromNode(superClass: BaseNode | null | undefined): SuperRef | undefined {\n if (!superClass) return undefined;\n\n if (superClass.type === 'Identifier') {\n return { kind: 'identifier', name: (superClass as IdentifierNode).name };\n }\n\n if (superClass.type === 'MemberExpression') {\n const member = superClass as MemberExpressionNode;\n const object = member.object?.type === 'Identifier' ? member.object.name : undefined;\n const property = member.property?.name;\n if (object && property) return { kind: 'member', object, property };\n }\n\n return undefined;\n}\n\nfunction addAstClass(shape: ModuleShape, classNode: ClassNode): void {\n if (classNode.id?.name) shape.classes.set(classNode.id.name, superRefFromNode(classNode.superClass));\n}\n\nfunction addAstImports(shape: ModuleShape, node: ImportDeclarationNode): void {\n const source = asString(node.source?.value);\n if (!source) return;\n\n for (const specifier of node.specifiers ?? []) {\n const local = specifier.local?.name;\n if (!local) continue;\n\n if (specifier.type === 'ImportSpecifier' && specifier.imported?.name) {\n shape.imports.set(local, { source, imported: specifier.imported.name });\n } else if (specifier.type === 'ImportDefaultSpecifier') {\n shape.imports.set(local, { source, imported: DEFAULT_EXPORT });\n } else if (specifier.type === 'ImportNamespaceSpecifier') {\n shape.namespaces.set(local, source);\n }\n }\n}\n\nfunction addAstNamedExport(shape: ModuleShape, node: ExportNamedNode): void {\n if (node.declaration?.type === 'ClassDeclaration') {\n addAstClass(shape, node.declaration as ClassNode);\n return;\n }\n\n const source = asString(node.source?.value);\n for (const specifier of node.specifiers ?? []) {\n const exported = specifier.exported?.name;\n const local = specifier.local?.name;\n if (!exported || !local) continue;\n\n if (source) {\n shape.reexports.set(exported, { source, imported: local });\n } else {\n shape.localExports.set(exported, local);\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Shape from raw source (used for sibling modules read off disk)\n// ---------------------------------------------------------------------------\n\n/**\n * Extract the module shape from **unprocessed source**.\n *\n * Sibling modules are read straight from disk (the plugin context's `load()` would deadlock inside a\n * transform hook), so they may still be TypeScript — which no JS parser will accept. Only\n * import/export statements and `class X extends Y` headers matter here, and those are\n * declaration-level syntax a scan can pick out reliably; class bodies, type annotations and generics\n * are irrelevant and simply skipped.\n */\nexport function shapeFromSource(rawCode: string): ModuleShape {\n const code = stripComments(rawCode);\n const shape = emptyShape();\n\n // `class X extends Y {` / `class X<T> extends Y<T> {`, optionally exported and/or abstract.\n const CLASS_RE = /\\b(?:export\\s+(?:default\\s+)?)?(?:abstract\\s+)?class\\s+([A-Za-z_$][\\w$]*)([^{]*)\\{/g;\n for (const match of code.matchAll(CLASS_RE)) {\n const className = match[1]!;\n const isDefault = /\\bexport\\s+default\\b/.test(match[0]);\n const superRef = superRefFromHeader(match[2] ?? '');\n\n shape.classes.set(className, superRef);\n if (isDefault) {\n shape.defaultExportIsClass = true;\n shape.defaultExportSuper = superRef;\n }\n }\n\n // `export default Identifier;`\n const defaultExprMatch = /\\bexport\\s+default\\s+([A-Za-z_$][\\w$]*)\\s*;/.exec(code);\n if (defaultExprMatch && !shape.defaultExportIsClass) {\n shape.defaultExportName = defaultExprMatch[1];\n }\n\n // `export * from '...'` (but not `export * as ns from '...'`).\n for (const match of code.matchAll(/\\bexport\\s*\\*\\s*from\\s*['\"]([^'\"]+)['\"]/g)) {\n if (match[1]) shape.starExports.push(match[1]);\n }\n\n // `export { a, b as c } from '...'` and `export { a, b as c }`.\n for (const match of code.matchAll(/\\bexport\\s*\\{([^}]*)\\}\\s*(?:from\\s*['\"]([^'\"]+)['\"])?/g)) {\n const source = match[2];\n for (const { imported, local } of parseSpecifierList(match[1] ?? '')) {\n // In an export clause the first name is local and the alias is the exported name.\n if (source) {\n shape.reexports.set(local, { source, imported });\n } else {\n shape.localExports.set(local, imported);\n }\n }\n }\n\n // `import Default, { a as b }, * as ns from '...'` in its various shapes.\n for (const match of code.matchAll(/\\bimport\\s+([^'\";]+?)\\s+from\\s*['\"]([^'\"]+)['\"]/g)) {\n addSourceImports(shape, match[1] ?? '', match[2]!);\n }\n\n return shape;\n}\n\n/** Pull the superclass out of the text between a class name and its body. */\nfunction superRefFromHeader(header: string): SuperRef | undefined {\n // The header still carries the class's own generic parameter list (`<T extends S>`), whose\n // constraint `extends` would otherwise be mistaken for the superclass clause. Strip a leading\n // balanced `<...>` first, then read the (possibly dotted) base name. Trailing generic args on the\n // base (`extends Agent<Env>`) stop the match naturally.\n const withoutParams = stripLeadingGenerics(header);\n const match = /\\bextends\\s+([A-Za-z_$][\\w$]*)\\s*(?:\\.\\s*([A-Za-z_$][\\w$]*))?/.exec(withoutParams);\n if (!match) return undefined;\n\n return match[2] ? { kind: 'member', object: match[1]!, property: match[2] } : { kind: 'identifier', name: match[1]! };\n}\n\n/**\n * Remove a leading `<...>` generic parameter list, honoring nesting (`<T extends Map<K, V>>`).\n * Anything after the balanced close — the superclass clause — is returned unchanged. When the\n * header doesn't start with `<` (no generics), it is returned as-is.\n */\nfunction stripLeadingGenerics(header: string): string {\n const start = header.indexOf('<');\n // Only treat it as a parameter list when `<` is the first meaningful token — a `<` appearing\n // later is part of the superclass's own generic args and must be left alone.\n if (start === -1 || header.slice(0, start).trim() !== '') return header;\n\n let depth = 0;\n for (let i = start; i < header.length; i++) {\n const char = header[i];\n if (char === '<') depth++;\n else if (char === '>') {\n depth--;\n if (depth === 0) return header.slice(i + 1);\n }\n }\n // Unbalanced `<` — fall back to the untouched header rather than dropping the superclass.\n return header;\n}\n\n/** Parse `a, b as c` into `{ imported: 'b', local: 'c' }` pairs (type-only specifiers dropped). */\nfunction parseSpecifierList(clause: string): Array<{ imported: string; local: string }> {\n const specifiers: Array<{ imported: string; local: string }> = [];\n\n for (const rawPart of clause.split(',')) {\n const part = rawPart.trim().replace(/^type\\s+/, '');\n if (!part) continue;\n\n const aliased = /^([A-Za-z_$][\\w$]*)\\s+as\\s+([A-Za-z_$][\\w$]*)$/.exec(part);\n if (aliased) {\n specifiers.push({ imported: aliased[1]!, local: aliased[2]! });\n } else if (/^[A-Za-z_$][\\w$]*$/.test(part)) {\n specifiers.push({ imported: part, local: part });\n }\n }\n\n return specifiers;\n}\n\nfunction addSourceImports(shape: ModuleShape, clause: string, source: string): void {\n // Type-only imports never contribute a runtime base class.\n if (/^type\\s/.test(clause.trim())) return;\n\n const namespaceMatch = /\\*\\s*as\\s+([A-Za-z_$][\\w$]*)/.exec(clause);\n if (namespaceMatch) {\n shape.namespaces.set(namespaceMatch[1]!, source);\n }\n\n const bracesMatch = /\\{([^}]*)\\}/.exec(clause);\n if (bracesMatch) {\n for (const { imported, local } of parseSpecifierList(bracesMatch[1] ?? '')) {\n shape.imports.set(local, { source, imported });\n }\n }\n\n // A leading bare identifier (before any brace/star) is the default import.\n const defaultMatch = /^\\s*([A-Za-z_$][\\w$]*)\\s*(?:,|$)/.exec(clause);\n if (defaultMatch) {\n shape.imports.set(defaultMatch[1]!, { source, imported: DEFAULT_EXPORT });\n }\n}\n\n/** Remove line and block comments, leaving string literals (module specifiers) intact. */\nfunction stripComments(code: string): string {\n let result = '';\n let index = 0;\n\n while (index < code.length) {\n const char = code[index]!;\n const next = code[index + 1];\n\n if (char === '/' && next === '/') {\n while (index < code.length && code[index] !== '\\n') index++;\n continue;\n }\n\n if (char === '/' && next === '*') {\n index += 2;\n while (index < code.length && !(code[index] === '*' && code[index + 1] === '/')) index++;\n index += 2;\n // Keep a separator so `*/class` doesn't fuse into one token.\n result += ' ';\n continue;\n }\n\n if (char === '\"' || char === \"'\" || char === '`') {\n const quote = char;\n result += char;\n index++;\n while (index < code.length) {\n const inner = code[index]!;\n result += inner;\n index++;\n if (inner === '\\\\') {\n if (index < code.length) {\n result += code[index]!;\n index++;\n }\n continue;\n }\n if (inner === quote) break;\n }\n continue;\n }\n\n result += char;\n index++;\n }\n\n return result;\n}\n\nfunction asString(value: unknown): string | undefined {\n return typeof value === 'string' && value ? value : undefined;\n}\n"],"names":[],"mappings":"AAqDO,MAAM,cAAA,GAAiB;AA2B9B,SAAS,UAAA,GAA0B;AACjC,EAAA,OAAO;AAAA,IACL,OAAA,sBAAa,GAAA,EAAI;AAAA,IACjB,OAAA,sBAAa,GAAA,EAAI;AAAA,IACjB,UAAA,sBAAgB,GAAA,EAAI;AAAA,IACpB,SAAA,sBAAe,GAAA,EAAI;AAAA,IACnB,YAAA,sBAAkB,GAAA,EAAI;AAAA,IACtB,aAAa;AAAC,GAChB;AACF;AAOO,SAAS,aAAa,GAAA,EAA+B;AAC1D,EAAA,MAAM,QAAQ,UAAA,EAAW;AAEzB,EAAA,KAAA,MAAW,IAAA,IAAQ,IAAI,IAAA,EAAM;AAC3B,IAAA,QAAQ,KAAK,IAAA;AAAM,MACjB,KAAK,kBAAA;AACH,QAAA,WAAA,CAAY,OAAO,IAAiB,CAAA;AACpC,QAAA;AAAA,MACF,KAAK,mBAAA;AACH,QAAA,aAAA,CAAc,OAAO,IAA6B,CAAA;AAClD,QAAA;AAAA,MACF,KAAK,wBAAA;AACH,QAAA,iBAAA,CAAkB,OAAO,IAAuB,CAAA;AAChD,QAA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AO,SAAS,GAAA,EAAK;AAChD,MAAA,MAAM,KAAA,GAAQ,IAAA;AACd,MAAA,MAAA,IAAU,IAAA;AACV,MAAA,KAAA,EAAA;AACA,MAAA,OAAO,KAAA,GAAQ,KAAK,MAAA,EAAQ;AAC1B,QAAA,MAAM,KAAA,GAAQ,KAAK,KAAK,CAAA;AACxB,QAAA,MAAA,IAAU,KAAA;AACV,QAAA,KAAA,EAAA;AACA,QAAA,IAAI,UAAU,IAAA,EAAM;AAClB,UAAA,IAAI,KAAA,GAAQ,KAAK,MAAA,EAAQ;AACvB,YAAA,MAAA,IAAU,KAAK,KAAK,CAAA;AACpB,YAAA,KAAA,EAAA;AAAA,UACF;AACA,UAAA;AAAA,QACF;AACA,QAAA,IAAI,UAAU,KAAA,EAAO;AAAA,MACvB;AACA,MAAA;AAAA,IACF;AAEA,IAAA,MAAA,IAAU,IAAA;AACV,IAAA,KAAA,EAAA;AAAA,EACF;AAEA,EAAA,OAAO,MAAA;AACT;AAEA,SAAS,SAAS,KAAA,EAAoC;AACpD,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,GAAQ,KAAA,GAAQ,MAAA;AACtD;;;;"}
@@ -10,6 +10,7 @@ function isCallToMethod(node, methodName) {
10
10
  }
11
11
  const WRAPPER_METHODS = {
12
12
  durableObject: "instrumentDurableObjectWithSentry",
13
+ agent: "instrumentAgentWithSentry",
13
14
  workflow: "instrumentWorkflowWithSentry",
14
15
  workerEntrypoint: "withSentry"
15
16
  };
@@ -23,6 +24,7 @@ function applyAutoInstrumentTransforms(code, ast, ctx) {
23
24
  topLevelClasses,
24
25
  renamedLocals: /* @__PURE__ */ new Set(),
25
26
  classWrappers: ctx.classWrappers,
27
+ agentClasses: ctx.agentClasses ?? /* @__PURE__ */ new Set(),
26
28
  workerEntrypointClasses: detectWorkerEntrypointClasses(ast)
27
29
  };
28
30
  const { wrappedClasses } = state;
@@ -50,6 +52,7 @@ function applyAutoInstrumentTransforms(code, ast, ctx) {
50
52
  }
51
53
  function resolveWrapperKind(exportedName, localName, state) {
52
54
  const configured = state.classWrappers.get(exportedName);
55
+ if (configured === "durableObject" && localName && state.agentClasses.has(localName)) return "agent";
53
56
  if (configured) return configured;
54
57
  if (localName && state.workerEntrypointClasses.has(localName)) return "workerEntrypoint";
55
58
  return void 0;
@@ -92,7 +95,9 @@ function collectManuallyWrappedClassExports(varDecl, ctx, state) {
92
95
  for (const declarator of varDecl.declarations ?? []) {
93
96
  const name = declarator.id?.type === "Identifier" ? declarator.id.name : void 0;
94
97
  const kind = name ? ctx.classWrappers.get(name) : void 0;
95
- if (name && kind && declarator.init && isCallToMethod(declarator.init, WRAPPER_METHODS[kind])) {
98
+ if (!name || !kind || !declarator.init) continue;
99
+ const accepted = kind === "durableObject" ? [WRAPPER_METHODS.durableObject, WRAPPER_METHODS.agent] : [WRAPPER_METHODS[kind]];
100
+ if (accepted.some((method) => isCallToMethod(declarator.init, method))) {
96
101
  state.wrappedClasses.add(name);
97
102
  }
98
103
  }
@@ -1 +1 @@
1
- {"version":3,"file":"transform.js","sources":["../../../src/vite/transform.ts"],"sourcesContent":["import MagicString from 'magic-string';\nimport { detectWorkerEntrypointClasses } from './workerEntrypoint';\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 {\n type: string;\n local?: { type: string; name?: string };\n exported?: { type: string; name?: string };\n}\n\ninterface ExportNamedNode extends BaseNode {\n declaration?: BaseNode | null;\n source?: unknown;\n specifiers?: ExportSpecifierNode[];\n}\n\ninterface VariableDeclaratorNode {\n id?: { type: string; name?: string };\n init?: BaseNode | null;\n}\n\ninterface VariableDeclarationNode extends BaseNode {\n declarations?: VariableDeclaratorNode[];\n}\n\nfunction isCallToMethod(node: BaseNode, methodName: string): boolean {\n if (node.type !== 'CallExpression') return false;\n const callee = (node as CallExpressionNode).callee;\n if (!callee) return false;\n if (callee.type === 'Identifier' && callee.name === methodName) return true;\n return (\n callee.type === 'MemberExpression' && callee.property?.type === 'Identifier' && callee.property.name === methodName\n );\n}\n\n/**\n * The kind of Sentry wrapper to apply to an exported class.\n *\n * `durableObject` and `workflow` are keyed by name from the wrangler config\n * (`durable_objects.bindings`, `workflows`), since those class names are\n * authoritative there. `workerEntrypoint` is different: a worker's own\n * entrypoints aren't enumerated in its config, so they're detected structurally\n * (a class extending `WorkerEntrypoint` from `cloudflare:workers`), with the\n * config providing only a fallback for self-bound entrypoints whose base class\n * lives in another module.\n */\nexport type ClassWrapperKind = 'durableObject' | 'workflow' | 'workerEntrypoint';\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 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 optionsFn: string;\n /** Import statement prepended when `optionsFn` references a separate module. */\n optionsImport?: 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 both `export class MyDO {}` and the specifier form\n * (`class MyDO {}` … `export { MyDO }` / `export { Foo as MyDO }`).\n * Re-exports from other modules (`export { MyDO } from './do'`) cannot be\n * wrapped here and are left alone — the plugin warns about them 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 state: TransformState = {\n ms,\n needsImport: false,\n wrappedClasses: new Set<string>(),\n topLevelClasses,\n renamedLocals: new Set<string>(),\n classWrappers: ctx.classWrappers,\n workerEntrypointClasses: detectWorkerEntrypointClasses(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 as ExportNamedNode, 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 if (ctx.optionsImport) ms.prepend(ctx.optionsImport);\n ms.prepend(\"import * as __SENTRY__ from '@sentry/cloudflare';\\n\");\n\n return {\n code: ms.toString(),\n map: ms.generateMap({ hires: true }),\n wrappedClasses,\n };\n}\n\ninterface TransformState {\n ms: MagicString;\n needsImport: boolean;\n wrappedClasses: Set<string>;\n /**\n * Top-level (non-exported) class declarations, so specifier exports like\n * `export { MyDO }` can locate the class they refer to.\n */\n topLevelClasses: Map<string, ClassDeclarationNode>;\n /**\n * Local class names already renamed + wrapped, so two specifiers pointing at\n * the same class don't produce duplicate bindings.\n */\n renamedLocals: Set<string>;\n /** Class name → wrapper kind, keyed by the *exported* name (from config). */\n classWrappers: Map<string, ClassWrapperKind>;\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}\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 */\nfunction resolveWrapperKind(\n exportedName: string,\n localName: string | undefined,\n state: TransformState,\n): ClassWrapperKind | undefined {\n const configured = state.classWrappers.get(exportedName);\n if (configured) return configured;\n if (localName && state.workerEntrypointClasses.has(localName)) return 'workerEntrypoint';\n return undefined;\n}\n\nfunction collectTopLevelClasses(ast: ProgramBody): Map<string, ClassDeclarationNode> {\n const classes = new Map<string, ClassDeclarationNode>();\n for (const node of ast.body) {\n if (node.type !== 'ClassDeclaration') continue;\n const classNode = node as ClassDeclarationNode;\n if (classNode.id?.name) classes.set(classNode.id.name, classNode);\n }\n return classes;\n}\n\nfunction wrapDefaultExport(node: ExportDefaultNode, ctx: TransformContext, state: TransformState): void {\n const decl = node.declaration;\n\n // Already wrapped — leave it alone\n if (isCallToMethod(decl, 'withSentry')) return;\n\n // `export default Foo` where `Foo` is a local class already wrapped by a named\n // export (e.g. a self-bound WorkerEntrypoint also used as the default handler).\n // Wrapping again would produce `withSentry(withSentry(...))`.\n if (decl.type === 'Identifier' && state.renamedLocals.has((decl as IdentifierNode).name)) return;\n\n // `export default <expr>` → `const __SENTRY_DEFAULT_EXPORT__ = <expr>`\n // MagicString positions are always relative to the original source.\n state.ms.overwrite(node.start, decl.start, 'const __SENTRY_DEFAULT_EXPORT__ = ');\n state.ms.append(`\\nexport default __SENTRY__.withSentry(${ctx.optionsFn}, __SENTRY_DEFAULT_EXPORT__);\\n`);\n state.needsImport = true;\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 as VariableDeclarationNode, ctx, state);\n return;\n }\n\n // ---- Named class export matching a configured binding ----\n if (decl?.type === 'ClassDeclaration') {\n wrapInlineClassExport(node, decl as ClassDeclarationNode, ctx, state);\n return;\n }\n\n // ---- Specifier export of a local class (`export { Foo as MyDO }`) ----\n // Re-exports from another module carry a `source` — nothing local to wrap.\n if (node.source) return;\n for (const specifier of node.specifiers ?? []) {\n wrapSpecifierExport(specifier, ctx, state);\n }\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 && isCallToMethod(declarator.init, WRAPPER_METHODS[kind])) {\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 const renamedClass = `__SENTRY_ORIGINAL_${className}__`;\n\n // Strip the `export ` keyword\n state.ms.overwrite(exportNode.start, classDecl.start, '');\n\n // Rename the class to avoid a duplicate binding\n state.ms.overwrite(classId.start, classId.end, renamedClass);\n\n // Insert the wrapped re-export after the class body\n state.ms.appendLeft(\n exportNode.end,\n `\\nexport const ${className} = __SENTRY__.${WRAPPER_METHODS[kind]}(${ctx.optionsFn}, ${renamedClass});\\n`,\n );\n\n state.wrappedClasses.add(className);\n state.renamedLocals.add(className);\n state.needsImport = true;\n}\n\nfunction wrapSpecifierExport(specifier: ExportSpecifierNode, ctx: TransformContext, state: TransformState): void {\n if (specifier.type !== 'ExportSpecifier' || specifier.exported?.type !== 'Identifier') return;\n const exportedName = specifier.exported.name;\n if (!exportedName) return;\n\n const localName = specifier.local?.type === 'Identifier' ? specifier.local.name : undefined;\n const kind = resolveWrapperKind(exportedName, localName, state);\n if (!kind) return;\n\n const localClass = localName ? state.topLevelClasses.get(localName) : undefined;\n if (!localName || !localClass?.id) return;\n\n state.wrappedClasses.add(exportedName);\n state.needsImport = true;\n if (state.renamedLocals.has(localName)) return;\n state.renamedLocals.add(localName);\n\n const renamedClass = `__SENTRY_ORIGINAL_${localName}__`;\n state.ms.overwrite(localClass.id.start, localClass.id.end, renamedClass);\n // The existing `export { ... }` statement keeps exporting the (now\n // wrapped) `localName` binding, so the wrapper is NOT exported here.\n state.ms.appendLeft(\n localClass.end,\n `\\nconst ${localName} = __SENTRY__.${WRAPPER_METHODS[kind]}(${ctx.optionsFn}, ${renamedClass});\\n`,\n );\n}\n"],"names":[],"mappings":";;;AA4DA,SAAS,cAAA,CAAe,MAAgB,UAAA,EAA6B;AACnE,EAAA,IAAI,IAAA,CAAK,IAAA,KAAS,gBAAA,EAAkB,OAAO,KAAA;AAC3C,EAAA,MAAM,SAAU,IAAA,CAA4B,MAAA;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AAG,UAAA;AAAA,IACP,UAAA,CAAW,GAAA;AAAA,IACX;AAAA,MAAA,EAAW,SAAS,iBAAiB,eAAA,CAAgB,IAAI,CAAC,CAAA,CAAA,EAAI,GAAA,CAAI,SAAS,CAAA,EAAA,EAAK,YAAY,CAAA;AAAA;AAAA,GAC9F;AACF;;;;"}
1
+ {"version":3,"file":"transform.js","sources":["../../../src/vite/transform.ts"],"sourcesContent":["import MagicString from 'magic-string';\nimport { detectWorkerEntrypointClasses } from './workerEntrypoint';\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 {\n type: string;\n local?: { type: string; name?: string };\n exported?: { type: string; name?: string };\n}\n\ninterface ExportNamedNode extends BaseNode {\n declaration?: BaseNode | null;\n source?: unknown;\n specifiers?: ExportSpecifierNode[];\n}\n\ninterface VariableDeclaratorNode {\n id?: { type: string; name?: string };\n init?: BaseNode | null;\n}\n\ninterface VariableDeclarationNode extends BaseNode {\n declarations?: VariableDeclaratorNode[];\n}\n\nfunction isCallToMethod(node: BaseNode, methodName: string): boolean {\n if (node.type !== 'CallExpression') return false;\n const callee = (node as CallExpressionNode).callee;\n if (!callee) return false;\n if (callee.type === 'Identifier' && callee.name === methodName) return true;\n return (\n callee.type === 'MemberExpression' && callee.property?.type === 'Identifier' && callee.property.name === methodName\n );\n}\n\n/**\n * The kind of Sentry wrapper to apply to an exported class.\n *\n * `durableObject` and `workflow` are keyed by name from the wrangler config\n * (`durable_objects.bindings`, `workflows`), since those class names are\n * authoritative there. `workerEntrypoint` is different: a worker's own\n * entrypoints aren't enumerated in its config, so they're detected structurally\n * (a class extending `WorkerEntrypoint` from `cloudflare:workers`), with the\n * config providing only a fallback for self-bound entrypoints whose base class\n * lives in another module.\n */\nexport type ClassWrapperKind = 'durableObject' | 'agent' | 'workflow' | 'workerEntrypoint';\n\n/**\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}\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 both `export class MyDO {}` and the specifier form\n * (`class MyDO {}` … `export { MyDO }` / `export { Foo as MyDO }`).\n * Re-exports from other modules (`export { MyDO } from './do'`) cannot be\n * wrapped here and are left alone — the plugin warns about them 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 state: TransformState = {\n ms,\n needsImport: false,\n wrappedClasses: new Set<string>(),\n topLevelClasses,\n renamedLocals: new Set<string>(),\n classWrappers: ctx.classWrappers,\n agentClasses: ctx.agentClasses ?? new Set<string>(),\n workerEntrypointClasses: detectWorkerEntrypointClasses(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 as ExportNamedNode, 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 if (ctx.optionsImport) ms.prepend(ctx.optionsImport);\n ms.prepend(\"import * as __SENTRY__ from '@sentry/cloudflare';\\n\");\n\n return {\n code: ms.toString(),\n map: ms.generateMap({ hires: true }),\n wrappedClasses,\n };\n}\n\ninterface TransformState {\n ms: MagicString;\n needsImport: boolean;\n wrappedClasses: Set<string>;\n /**\n * Top-level (non-exported) class declarations, so specifier exports like\n * `export { MyDO }` can locate the class they refer to.\n */\n topLevelClasses: Map<string, ClassDeclarationNode>;\n /**\n * Local class names already renamed + wrapped, so two specifiers pointing at\n * the same class don't produce duplicate bindings.\n */\n renamedLocals: Set<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}\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 * 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 if (configured === 'durableObject' && localName && state.agentClasses.has(localName)) return 'agent';\n if (configured) return configured;\n if (localName && state.workerEntrypointClasses.has(localName)) return 'workerEntrypoint';\n return undefined;\n}\n\nfunction collectTopLevelClasses(ast: ProgramBody): Map<string, ClassDeclarationNode> {\n const classes = new Map<string, ClassDeclarationNode>();\n for (const node of ast.body) {\n if (node.type !== 'ClassDeclaration') continue;\n const classNode = node as ClassDeclarationNode;\n if (classNode.id?.name) classes.set(classNode.id.name, classNode);\n }\n return classes;\n}\n\nfunction wrapDefaultExport(node: ExportDefaultNode, ctx: TransformContext, state: TransformState): void {\n const decl = node.declaration;\n\n // Already wrapped — leave it alone\n if (isCallToMethod(decl, 'withSentry')) return;\n\n // `export default Foo` where `Foo` is a local class already wrapped by a named\n // export (e.g. a self-bound WorkerEntrypoint also used as the default handler).\n // Wrapping again would produce `withSentry(withSentry(...))`.\n if (decl.type === 'Identifier' && state.renamedLocals.has((decl as IdentifierNode).name)) return;\n\n // `export default <expr>` → `const __SENTRY_DEFAULT_EXPORT__ = <expr>`\n // MagicString positions are always relative to the original source.\n state.ms.overwrite(node.start, decl.start, 'const __SENTRY_DEFAULT_EXPORT__ = ');\n state.ms.append(`\\nexport default __SENTRY__.withSentry(${ctx.optionsFn}, __SENTRY_DEFAULT_EXPORT__);\\n`);\n state.needsImport = true;\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 as VariableDeclarationNode, ctx, state);\n return;\n }\n\n // ---- Named class export matching a configured binding ----\n if (decl?.type === 'ClassDeclaration') {\n wrapInlineClassExport(node, decl as ClassDeclarationNode, ctx, state);\n return;\n }\n\n // ---- Specifier export of a local class (`export { Foo as MyDO }`) ----\n // Re-exports from another module carry a `source` — nothing local to wrap.\n if (node.source) return;\n for (const specifier of node.specifiers ?? []) {\n wrapSpecifierExport(specifier, ctx, state);\n }\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 const renamedClass = `__SENTRY_ORIGINAL_${className}__`;\n\n // Strip the `export ` keyword\n state.ms.overwrite(exportNode.start, classDecl.start, '');\n\n // Rename the class to avoid a duplicate binding\n state.ms.overwrite(classId.start, classId.end, renamedClass);\n\n // Insert the wrapped re-export after the class body\n state.ms.appendLeft(\n exportNode.end,\n `\\nexport const ${className} = __SENTRY__.${WRAPPER_METHODS[kind]}(${ctx.optionsFn}, ${renamedClass});\\n`,\n );\n\n state.wrappedClasses.add(className);\n state.renamedLocals.add(className);\n state.needsImport = true;\n}\n\nfunction wrapSpecifierExport(specifier: ExportSpecifierNode, ctx: TransformContext, state: TransformState): void {\n if (specifier.type !== 'ExportSpecifier' || specifier.exported?.type !== 'Identifier') return;\n const exportedName = specifier.exported.name;\n if (!exportedName) return;\n\n const localName = specifier.local?.type === 'Identifier' ? specifier.local.name : undefined;\n const kind = resolveWrapperKind(exportedName, localName, state);\n if (!kind) return;\n\n const localClass = localName ? state.topLevelClasses.get(localName) : undefined;\n if (!localName || !localClass?.id) return;\n\n state.wrappedClasses.add(exportedName);\n state.needsImport = true;\n if (state.renamedLocals.has(localName)) return;\n state.renamedLocals.add(localName);\n\n const renamedClass = `__SENTRY_ORIGINAL_${localName}__`;\n state.ms.overwrite(localClass.id.start, localClass.id.end, renamedClass);\n // The existing `export { ... }` statement keeps exporting the (now\n // wrapped) `localName` binding, so the wrapper is NOT exported here.\n state.ms.appendLeft(\n localClass.end,\n `\\nconst ${localName} = __SENTRY__.${WRAPPER_METHODS[kind]}(${ctx.optionsFn}, ${renamedClass});\\n`,\n );\n}\n"],"names":[],"mappings":";;;AA4DA,SAAS,cAAA,CAAe,MAAgB,U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B,GAAA,CAAI,SAAS,CAAA,GAAI,MAAA;AACtE,EAAA,IAAI,CAAC,SAAA,IAAa,CAAC,UAAA,EAAY,EAAA,EAAI;AAEnC,EAAA,KAAA,CAAM,cAAA,CAAe,IAAI,YAAY,CAAA;AACrC,EAAA,KAAA,CAAM,WAAA,GAAc,IAAA;AACpB,EAAA,IAAI,KAAA,CAAM,aAAA,CAAc,GAAA,CAAI,SAAS,CAAA,EAAG;AACxC,EAAA,KAAA,CAAM,aAAA,CAAc,IAAI,SAAS,CAAA;AAEjC,EAAA,MAAM,YAAA,GAAe,qBAAqB,SAAS,CAAA,EAAA,CAAA;AACnD,EAAA,KAAA,CAAM,EAAA,CAAG,UAAU,UAAA,CAAW,EAAA,CAAG,OAAO,UAAA,CAAW,EAAA,CAAG,KAAK,YAAY,CAAA;AAGvE,EAAA,KAAA,CAAM,EAAA,CAAG,UAAA;AAAA,IACP,UAAA,CAAW,GAAA;AAAA,IACX;AAAA,MAAA,EAAW,SAAS,iBAAiB,eAAA,CAAgB,IAAI,CAAC,CAAA,CAAA,EAAI,GAAA,CAAI,SAAS,CAAA,EAAA,EAAK,YAAY,CAAA;AAAA;AAAA,GAC9F;AACF;;;;"}
@@ -3,7 +3,7 @@ import { resolve, dirname } from 'node:path';
3
3
  import { unstable_readConfig } from 'wrangler';
4
4
 
5
5
  function resolveWranglerConfig(root, explicitPath) {
6
- const configPath = ["wrangler.json", "wrangler.jsonc", "wrangler.toml"].map((name) => resolve(root, name)).find(existsSync);
6
+ const configPath = explicitPath ? resolve(root, explicitPath) : ["wrangler.json", "wrangler.jsonc", "wrangler.toml"].map((name) => resolve(root, name)).find(existsSync);
7
7
  if (!configPath || !existsSync(configPath)) {
8
8
  return void 0;
9
9
  }
@@ -1 +1 @@
1
- {"version":3,"file":"wranglerConfig.js","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. `main` is an absolute path (wrangler resolves it against the config\n * file's directory).\n */\nexport interface WranglerConfig {\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\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, flattens the active\n * environment (honoring `CLOUDFLARE_ENV`), and resolves `main` to an absolute\n * path. Durable Object and Workflow bindings are the active environment's,\n * matching what the deployed Worker 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; 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 });\n } catch {\n return undefined;\n }\n\n return {\n config: {\n main: raw.main,\n durableObjects: collectClassBindings(raw.durable_objects?.bindings),\n workflows: collectClassBindings(raw.workflows),\n workerEntrypoints: collectSelfBoundEntrypoints(raw),\n },\n configDir: dirname(raw.configPath ?? configPath),\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 * 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"],"names":[],"mappings":";;;;AAqCO,SAAS,qBAAA,CACd,MACA,YAAA,EAC2D;AAC3D,EAAA,MAAM,aAEF,CAAC,eAAA,EAAiB,gBAAA,EAAkB,eAAe,CAAA,CAAE,GAAA,CAAI,UAAQ,OAAA,CAAQ,IAAA,EAAM,IAAI,CAAC,CAAA,CAAE,KAAK,UAAU,CAAA;AAEzG,EAAA,IAAI,CAAC,UAAA,IAAc,CAAC,UAAA,CAAW,UAAU,CAAA,EAAG;AAC1C,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,IAAI,GAAA;AACJ,EAAA,IAAI;AAGF,IAAA,GAAA,GAAM,mBAAA,CAAoB,EAAE,MAAA,EAAQ,UAAA,IAAc,EAAE,YAAA,EAAc,MAAM,CAAA;AAAA,EAC1E,CAAA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C,IAAA,MAAA,CAAO,IAAA,CAAK,EAAE,IAAA,EAAM,OAAA,CAAQ,MAAM,SAAA,EAAW,OAAA,CAAQ,YAAY,CAAA;AAAA,EACnE;AACA,EAAA,OAAO,MAAA;AACT;;;;"}
1
+ {"version":3,"file":"wranglerConfig.js","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. `main` is an absolute path (wrangler resolves it against the config\n * file's directory).\n */\nexport interface WranglerConfig {\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\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, flattens the active\n * environment (honoring `CLOUDFLARE_ENV`), and resolves `main` to an absolute\n * path. Durable Object and Workflow bindings are the active environment's,\n * matching what the deployed Worker 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; 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 });\n } catch {\n return undefined;\n }\n\n return {\n config: {\n main: raw.main,\n durableObjects: collectClassBindings(raw.durable_objects?.bindings),\n workflows: collectClassBindings(raw.workflows),\n workerEntrypoints: collectSelfBoundEntrypoints(raw),\n },\n configDir: dirname(raw.configPath ?? configPath),\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 * 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"],"names":[],"mappings":";;;;AAqCO,SAAS,qBAAA,CACd,MACA,YAAA,EAC2D;AAC3D,EAAA,MAAM,aAAa,YAAA,GACf,OAAA,CAAQ,MAAM,YAAY,CAAA,GAC1B,CAAC,eAAA,EAAiB,gBAAA,EAAkB,eAAe,CAAA,CAAE,GAAA,CAAI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AA,MAAM,SAAqD,EAAC;AAC5D,EAAA,MAAM,cAAA,uBAAqB,GAAA,EAAY;AACvC,EAAA,KAAA,MAAW,OAAA,IAAW,QAAA,IAAY,EAAC,EAAG;AACpC,IAAA,IAAI,OAAO,OAAA,EAAS,UAAA,KAAe,QAAA,IAAY,OAAA,CAAQ,eAAe,cAAA,CAAe,GAAA,CAAI,OAAA,CAAQ,UAAU,CAAA,EAAG;AAC5G,MAAA;AAAA,IACF;AACA,IAAA,cAAA,CAAe,GAAA,CAAI,QAAQ,UAAU,CAAA;AACrC,IAAA,MAAA,CAAO,IAAA,CAAK,EAAE,IAAA,EAAM,OAAA,CAAQ,MAAM,SAAA,EAAW,OAAA,CAAQ,YAAY,CAAA;AAAA,EACnE;AACA,EAAA,OAAO,MAAA;AACT;;;;"}
@@ -41,6 +41,8 @@ export declare class CloudflareClient extends ServerRuntimeClient {
41
41
  * After calling dispose(), the client should not be used anymore.
42
42
  */
43
43
  dispose(): void;
44
+ /** @inheritDoc */
45
+ protected _setupIntegrations(): void;
44
46
  /**
45
47
  * Resets the span completion promise and resolve function.
46
48
  */
@@ -132,6 +134,30 @@ interface BaseCloudflareOptions {
132
134
  * ```
133
135
  */
134
136
  durableObjectSqlSpanAllowlist?: Array<string | RegExp>;
137
+ /**
138
+ * KV keys that should stay instrumented even though they match a reserved prefix used by Durable
139
+ * Object frameworks (`agents`, `partyserver`, ...) for their internal storage entries.
140
+ *
141
+ * By default, KV reads/writes (`get`, `put`, `delete`, `list`) of `cf_`- or `__ps_`-prefixed keys
142
+ * are treated as framework noise and no `durable_object_storage_*` span is created for them,
143
+ * mirroring how `cf_`-prefixed SQL tables are handled (see {@link durableObjectSqlSpanAllowlist}).
144
+ * If one of your own keys happens to use such a prefix, add it here to opt it back into
145
+ * instrumentation. Strings must match exactly, while regular expressions give you prefix/pattern
146
+ * matching.
147
+ *
148
+ * @default []
149
+ * @example
150
+ * ```ts
151
+ * export default Sentry.withSentry(
152
+ * (env) => ({
153
+ * dsn: env.SENTRY_DSN,
154
+ * durableObjectStorageSpanAllowlist: ['cf_my_key', /^cf_reports_/],
155
+ * }),
156
+ * handler,
157
+ * );
158
+ * ```
159
+ */
160
+ durableObjectStorageSpanAllowlist?: Array<string | RegExp>;
135
161
  /**
136
162
  * @deprecated Use `enableRpcTracePropagation` instead. This option will be removed in a future major version.
137
163
  *
@@ -145,6 +171,17 @@ interface BaseCloudflareOptions {
145
171
  * @default false
146
172
  */
147
173
  instrumentPrototypeMethods?: boolean | string[];
174
+ /**
175
+ * If you use Spotlight by Sentry during development, use
176
+ * this option to forward captured Sentry events to Spotlight.
177
+ *
178
+ * Either set it to true, or provide a specific Spotlight Sidecar URL.
179
+ *
180
+ * More details: https://spotlightjs.com/
181
+ *
182
+ * IMPORTANT: Only set this option to `true` while developing, not in production!
183
+ */
184
+ spotlight?: boolean | string;
148
185
  }
149
186
  /**
150
187
  * Configuration options for the Sentry Cloudflare SDK
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,OAAO,EAA8B,MAAM,cAAc,CAAC;AACvF,OAAO,EAA2B,mBAAmB,EAAiB,MAAM,cAAc,CAAC;AAE3F,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AACjE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7C,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,aAAa,CAAC;AAE9D;;;;;GAKG;AACH,qBAAa,gBAAiB,SAAQ,mBAAmB;IACvD,OAAO,CAAC,QAAQ,CAAC,UAAU,CAA0C;IACrE,OAAO,CAAC,aAAa,CAA0B;IAC/C,OAAO,CAAC,sBAAsB,CAA8B;IAC5D,OAAO,CAAC,sBAAsB,CAA6B;IAE3D,OAAO,CAAC,qBAAqB,CAA6B;IAC1D,OAAO,CAAC,mBAAmB,CAA6B;IAExD;;;O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