@sentry/cloudflare 11.8.0 → 11.10.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 (133) hide show
  1. package/README.md +5 -1
  2. package/build/cjs/dev/baseSdk.js +19 -2
  3. package/build/cjs/dev/baseSdk.js.map +1 -1
  4. package/build/cjs/dev/client.js +17 -0
  5. package/build/cjs/dev/client.js.map +1 -1
  6. package/build/cjs/dev/index.js +42 -0
  7. package/build/cjs/dev/index.js.map +1 -1
  8. package/build/cjs/dev/instrumentations/instrumentSqlStorage.js +1 -1
  9. package/build/cjs/dev/instrumentations/instrumentSqlStorage.js.map +1 -1
  10. package/build/cjs/dev/instrumentations/worker/instrumentEnv.js +7 -0
  11. package/build/cjs/dev/instrumentations/worker/instrumentEnv.js.map +1 -1
  12. package/build/cjs/dev/instrumentations/worker/instrumentKV.js +79 -0
  13. package/build/cjs/dev/instrumentations/worker/instrumentKV.js.map +1 -0
  14. package/build/cjs/dev/instrumentations/worker/instrumentScheduled.js +0 -3
  15. package/build/cjs/dev/instrumentations/worker/instrumentScheduled.js.map +1 -1
  16. package/build/cjs/dev/integrations/cronTriggers.js.map +1 -1
  17. package/build/cjs/dev/integrations/httpServer.js +52 -2
  18. package/build/cjs/dev/integrations/httpServer.js.map +1 -1
  19. package/build/cjs/dev/transport.js +8 -6
  20. package/build/cjs/dev/transport.js.map +1 -1
  21. package/build/cjs/dev/utils/invocationContext.js +2 -2
  22. package/build/cjs/dev/utils/invocationContext.js.map +1 -1
  23. package/build/cjs/dev/utils/isBinding.js +4 -0
  24. package/build/cjs/dev/utils/isBinding.js.map +1 -1
  25. package/build/cjs/dev/vite/transform.js +55 -4
  26. package/build/cjs/dev/vite/transform.js.map +1 -1
  27. package/build/cjs/dev/wrapMethodWithSentry.js.map +1 -1
  28. package/build/cjs/dev/wrapRequestHandlerWithInit.js +72 -49
  29. package/build/cjs/dev/wrapRequestHandlerWithInit.js.map +1 -1
  30. package/build/cjs/prod/baseSdk.js +19 -2
  31. package/build/cjs/prod/baseSdk.js.map +1 -1
  32. package/build/cjs/prod/client.js +17 -0
  33. package/build/cjs/prod/client.js.map +1 -1
  34. package/build/cjs/prod/index.js +42 -0
  35. package/build/cjs/prod/index.js.map +1 -1
  36. package/build/cjs/prod/instrumentations/instrumentSqlStorage.js +1 -1
  37. package/build/cjs/prod/instrumentations/instrumentSqlStorage.js.map +1 -1
  38. package/build/cjs/prod/instrumentations/worker/instrumentEnv.js +7 -0
  39. package/build/cjs/prod/instrumentations/worker/instrumentEnv.js.map +1 -1
  40. package/build/cjs/prod/instrumentations/worker/instrumentKV.js +79 -0
  41. package/build/cjs/prod/instrumentations/worker/instrumentKV.js.map +1 -0
  42. package/build/cjs/prod/instrumentations/worker/instrumentScheduled.js +0 -3
  43. package/build/cjs/prod/instrumentations/worker/instrumentScheduled.js.map +1 -1
  44. package/build/cjs/prod/integrations/cronTriggers.js.map +1 -1
  45. package/build/cjs/prod/integrations/httpServer.js +52 -2
  46. package/build/cjs/prod/integrations/httpServer.js.map +1 -1
  47. package/build/cjs/prod/transport.js +8 -6
  48. package/build/cjs/prod/transport.js.map +1 -1
  49. package/build/cjs/prod/utils/invocationContext.js +2 -2
  50. package/build/cjs/prod/utils/invocationContext.js.map +1 -1
  51. package/build/cjs/prod/utils/isBinding.js +4 -0
  52. package/build/cjs/prod/utils/isBinding.js.map +1 -1
  53. package/build/cjs/prod/vite/transform.js +55 -4
  54. package/build/cjs/prod/vite/transform.js.map +1 -1
  55. package/build/cjs/prod/wrapMethodWithSentry.js.map +1 -1
  56. package/build/cjs/prod/wrapRequestHandlerWithInit.js +72 -49
  57. package/build/cjs/prod/wrapRequestHandlerWithInit.js.map +1 -1
  58. package/build/esm/dev/baseSdk.js +20 -3
  59. package/build/esm/dev/baseSdk.js.map +1 -1
  60. package/build/esm/dev/client.js +18 -1
  61. package/build/esm/dev/client.js.map +1 -1
  62. package/build/esm/dev/index.js +3 -3
  63. package/build/esm/dev/instrumentations/instrumentSqlStorage.js +1 -1
  64. package/build/esm/dev/instrumentations/instrumentSqlStorage.js.map +1 -1
  65. package/build/esm/dev/instrumentations/worker/instrumentEnv.js +8 -1
  66. package/build/esm/dev/instrumentations/worker/instrumentEnv.js.map +1 -1
  67. package/build/esm/dev/instrumentations/worker/instrumentKV.js +77 -0
  68. package/build/esm/dev/instrumentations/worker/instrumentKV.js.map +1 -0
  69. package/build/esm/dev/instrumentations/worker/instrumentScheduled.js +0 -3
  70. package/build/esm/dev/instrumentations/worker/instrumentScheduled.js.map +1 -1
  71. package/build/esm/dev/integrations/cronTriggers.js.map +1 -1
  72. package/build/esm/dev/integrations/httpServer.js +52 -4
  73. package/build/esm/dev/integrations/httpServer.js.map +1 -1
  74. package/build/esm/dev/package.json +1 -1
  75. package/build/esm/dev/transport.js +8 -6
  76. package/build/esm/dev/transport.js.map +1 -1
  77. package/build/esm/dev/utils/invocationContext.js +2 -2
  78. package/build/esm/dev/utils/invocationContext.js.map +1 -1
  79. package/build/esm/dev/utils/isBinding.js +4 -1
  80. package/build/esm/dev/utils/isBinding.js.map +1 -1
  81. package/build/esm/dev/vite/transform.js +55 -4
  82. package/build/esm/dev/vite/transform.js.map +1 -1
  83. package/build/esm/dev/wrapMethodWithSentry.js.map +1 -1
  84. package/build/esm/dev/wrapRequestHandlerWithInit.js +74 -51
  85. package/build/esm/dev/wrapRequestHandlerWithInit.js.map +1 -1
  86. package/build/esm/prod/baseSdk.js +20 -3
  87. package/build/esm/prod/baseSdk.js.map +1 -1
  88. package/build/esm/prod/client.js +18 -1
  89. package/build/esm/prod/client.js.map +1 -1
  90. package/build/esm/prod/index.js +3 -3
  91. package/build/esm/prod/instrumentations/instrumentSqlStorage.js +1 -1
  92. package/build/esm/prod/instrumentations/instrumentSqlStorage.js.map +1 -1
  93. package/build/esm/prod/instrumentations/worker/instrumentEnv.js +8 -1
  94. package/build/esm/prod/instrumentations/worker/instrumentEnv.js.map +1 -1
  95. package/build/esm/prod/instrumentations/worker/instrumentKV.js +77 -0
  96. package/build/esm/prod/instrumentations/worker/instrumentKV.js.map +1 -0
  97. package/build/esm/prod/instrumentations/worker/instrumentScheduled.js +0 -3
  98. package/build/esm/prod/instrumentations/worker/instrumentScheduled.js.map +1 -1
  99. package/build/esm/prod/integrations/cronTriggers.js.map +1 -1
  100. package/build/esm/prod/integrations/httpServer.js +52 -4
  101. package/build/esm/prod/integrations/httpServer.js.map +1 -1
  102. package/build/esm/prod/package.json +1 -1
  103. package/build/esm/prod/transport.js +8 -6
  104. package/build/esm/prod/transport.js.map +1 -1
  105. package/build/esm/prod/utils/invocationContext.js +2 -2
  106. package/build/esm/prod/utils/invocationContext.js.map +1 -1
  107. package/build/esm/prod/utils/isBinding.js +4 -1
  108. package/build/esm/prod/utils/isBinding.js.map +1 -1
  109. package/build/esm/prod/vite/transform.js +55 -4
  110. package/build/esm/prod/vite/transform.js.map +1 -1
  111. package/build/esm/prod/wrapMethodWithSentry.js.map +1 -1
  112. package/build/esm/prod/wrapRequestHandlerWithInit.js +74 -51
  113. package/build/esm/prod/wrapRequestHandlerWithInit.js.map +1 -1
  114. package/build/types/baseSdk.d.ts.map +1 -1
  115. package/build/types/client.d.ts +49 -1
  116. package/build/types/client.d.ts.map +1 -1
  117. package/build/types/index.d.ts +8 -4
  118. package/build/types/index.d.ts.map +1 -1
  119. package/build/types/instrumentations/worker/instrumentEnv.d.ts +1 -0
  120. package/build/types/instrumentations/worker/instrumentEnv.d.ts.map +1 -1
  121. package/build/types/instrumentations/worker/instrumentKV.d.ts +8 -0
  122. package/build/types/instrumentations/worker/instrumentKV.d.ts.map +1 -0
  123. package/build/types/instrumentations/worker/instrumentScheduled.d.ts.map +1 -1
  124. package/build/types/integrations/cronTriggers.d.ts.map +1 -1
  125. package/build/types/integrations/httpServer.d.ts +45 -1
  126. package/build/types/integrations/httpServer.d.ts.map +1 -1
  127. package/build/types/transport.d.ts.map +1 -1
  128. package/build/types/utils/invocationContext.d.ts +3 -2
  129. package/build/types/utils/invocationContext.d.ts.map +1 -1
  130. package/build/types/utils/isBinding.d.ts +6 -1
  131. package/build/types/utils/isBinding.d.ts.map +1 -1
  132. package/build/types/wrapRequestHandlerWithInit.d.ts.map +1 -1
  133. package/package.json +12 -12
@@ -1,13 +1,20 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
 
3
3
  const core = require('@sentry/core');
4
+ const server = require('@sentry/core/server');
5
+ const debugBuild = require('../debug-build.js');
4
6
 
5
7
  const INTEGRATION_NAME = "HttpServer";
6
8
  const _httpServerIntegration = ((options = {}) => {
7
9
  return {
8
10
  name: INTEGRATION_NAME,
9
11
  maxRequestBodySize: options.maxRequestBodySize,
10
- ignoreRequestBody: options.ignoreRequestBody
12
+ ignoreRequestBody: options.ignoreRequestBody,
13
+ ignoreIncomingRequests: options.ignoreIncomingRequests,
14
+ ignoreStaticAssets: options.ignoreStaticAssets ?? true,
15
+ spans: options.spans,
16
+ onSpanCreated: options.onSpanCreated,
17
+ onSpanEnd: options.onSpanEnd
11
18
  };
12
19
  });
13
20
  const httpServerIntegration = core.defineIntegration(_httpServerIntegration);
@@ -24,13 +31,56 @@ async function captureIncomingRequestBody(client, request) {
24
31
  if (request.method === "GET" || request.method === "HEAD" || request.method === "OPTIONS") {
25
32
  return;
26
33
  }
27
- if (integration.ignoreRequestBody?.(request.url, request)) {
34
+ const ignoreRequestBody = integration.ignoreRequestBody;
35
+ if (ignoreRequestBody && // If the filter throws, skip the body so it cannot leak data the filter was meant to hide.
36
+ core.safeCallback(
37
+ debugBuild.DEBUG_BUILD ? "Error in `ignoreRequestBody`, skipping the body:" : "",
38
+ () => ignoreRequestBody(request.url, request),
39
+ () => true
40
+ )) {
28
41
  return;
29
42
  }
30
43
  const isolationScope = core.getIsolationScope();
31
44
  await core.captureBodyFromWinterCGRequest(request, isolationScope, effectiveBodySize);
32
45
  }
46
+ function shouldCreateIncomingRequestSpan(client, request) {
47
+ if (!client) {
48
+ return false;
49
+ }
50
+ const integration = client.getIntegrationByName(INTEGRATION_NAME);
51
+ if (!(integration?.spans ?? core.hasSpansEnabled(client.getOptions()))) {
52
+ return false;
53
+ }
54
+ const urlObject = core.parseStringToURLObject(request.url);
55
+ const urlPath = urlObject ? `${urlObject.pathname}${urlObject.search}` : "/";
56
+ if (integration?.ignoreStaticAssets && request.method === "GET" && server.isStaticAssetRequest(urlPath)) {
57
+ return false;
58
+ }
59
+ const ignoreIncomingRequests = integration?.ignoreIncomingRequests;
60
+ return !(ignoreIncomingRequests && core.safeCallback(
61
+ debugBuild.DEBUG_BUILD ? "Error in `ignoreIncomingRequests`, creating the span:" : "",
62
+ () => ignoreIncomingRequests(urlPath, request),
63
+ () => false
64
+ ));
65
+ }
66
+ function getIncomingRequestSpanHooks(client) {
67
+ const integration = client?.getIntegrationByName(INTEGRATION_NAME);
68
+ return {
69
+ onSpanCreated: (span, request) => core.safeCallback(
70
+ debugBuild.DEBUG_BUILD ? "Error in `onSpanCreated`:" : "",
71
+ () => integration?.onSpanCreated?.(span, request),
72
+ () => void 0
73
+ ),
74
+ onSpanEnd: (span, request, response) => core.safeCallback(
75
+ debugBuild.DEBUG_BUILD ? "Error in `onSpanEnd`:" : "",
76
+ () => integration?.onSpanEnd?.(span, request, response),
77
+ () => void 0
78
+ )
79
+ };
80
+ }
33
81
 
34
82
  exports.captureIncomingRequestBody = captureIncomingRequestBody;
83
+ exports.getIncomingRequestSpanHooks = getIncomingRequestSpanHooks;
35
84
  exports.httpServerIntegration = httpServerIntegration;
85
+ exports.shouldCreateIncomingRequestSpan = shouldCreateIncomingRequestSpan;
36
86
  //# sourceMappingURL=httpServer.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"httpServer.js","sources":["../../../../src/integrations/httpServer.ts"],"sourcesContent":["import type { Client, IntegrationFn, MaxRequestBodySize } from '@sentry/core';\nimport { captureBodyFromWinterCGRequest, defineIntegration, getIsolationScope } from '@sentry/core';\n\nconst INTEGRATION_NAME = 'HttpServer' as const;\n\nexport interface HttpServerIntegrationOptions {\n /**\n * Controls the maximum size of incoming request bodies attached to events.\n *\n * Only applies to requests with textual content types (text/*, application/json,\n * application/x-www-form-urlencoded, application/xml, application/graphql).\n * Binary data is not captured.\n *\n * Available options:\n * - `'none'`: No request bodies will be attached\n * - `'small'`: Request bodies up to 1,000 bytes will be attached\n * - `'medium'`: Request bodies up to 10,000 bytes will be attached (default)\n * - `'always'`: Request bodies will always be attached (up to 1MB limit)\n *\n * @default 'medium'\n */\n maxRequestBodySize?: MaxRequestBodySize;\n\n /**\n * Do not capture the request body for incoming HTTP requests to URLs where the given callback returns `true`.\n * This can be useful for long running requests where the body is not needed, health check endpoints,\n * or requests containing sensitive data that should not be captured.\n *\n * @param url The full URL of the incoming request, including query string, protocol, host, etc.\n * @param request The incoming Request object.\n * @returns `true` to skip body capture for this request, `false` to capture normally.\n *\n * @example\n * ```ts\n * Sentry.httpServerIntegration({\n * ignoreRequestBody: (url) => url.includes('/health') || url.includes('/upload'),\n * })\n * ```\n */\n ignoreRequestBody?: (url: string, request: Request) => boolean;\n}\n\ninterface HttpServerIntegrationInstance {\n name: string;\n maxRequestBodySize: MaxRequestBodySize | undefined;\n ignoreRequestBody?: (url: string, request: Request) => boolean;\n}\n\nconst _httpServerIntegration = ((options: HttpServerIntegrationOptions = {}): HttpServerIntegrationInstance => {\n return {\n name: INTEGRATION_NAME,\n maxRequestBodySize: options.maxRequestBodySize,\n ignoreRequestBody: options.ignoreRequestBody,\n };\n}) satisfies IntegrationFn;\n\n/**\n * Configures incoming HTTP request handling for Cloudflare Workers.\n *\n * This integration controls how incoming HTTP request data is captured,\n * matching the API of `httpServerIntegration` in Node.js.\n *\n * @example\n * ```ts\n * Sentry.init({\n * integrations: [\n * Sentry.httpServerIntegration({\n * maxRequestBodySize: 'medium',\n * ignoreRequestBody: (url) => url.includes('/health'),\n * }),\n * ],\n * });\n * ```\n */\nexport const httpServerIntegration = defineIntegration(_httpServerIntegration);\n\n/**\n * Capture the request body based on the HttpServer integration config.\n * Called internally by `wrapRequestHandler`.\n */\nexport async function captureIncomingRequestBody(client: Client, request: Request): Promise<void> {\n const integration = client.getIntegrationByName<HttpServerIntegrationInstance>(INTEGRATION_NAME);\n\n if (!integration) {\n return;\n }\n\n const configuredBodySize = integration.maxRequestBodySize;\n const effectiveBodySize: MaxRequestBodySize =\n configuredBodySize ??\n (client.getDataCollectionOptions().httpBodies.includes('incomingRequest') ? 'medium' : 'none');\n\n if (effectiveBodySize === 'none') {\n return;\n }\n\n // Skip GET and HEAD requests - they don't have bodies\n // Also skip OPTIONS, even if they may have a body, they might not give a lot of extra value\n if (request.method === 'GET' || request.method === 'HEAD' || request.method === 'OPTIONS') {\n return;\n }\n\n if (integration.ignoreRequestBody?.(request.url, request)) {\n return;\n }\n\n const isolationScope = getIsolationScope();\n await captureBodyFromWinterCGRequest(request, isolationScope, effectiveBodySize);\n}\n"],"names":["defineIntegration","getIsolationScope","captureBodyFromWinterCGRequest"],"mappings":";;;;AAGA,MAAM,gBAAA,GAAmB,YAAA;AA6CzB,MAAM,sBAAA,IAA0B,CAAC,OAAA,GAAwC,EAAC,KAAqC;AAC7G,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,oBAAoB,OAAA,CAAQ,kBAAA;AAAA,IAC5B,mBAAmB,OAAA,CAAQ;AAAA,GAC7B;AACF,CAAA,CAAA;AAoBO,MAAM,qBAAA,GAAwBA,uBAAkB,sBAAsB;AAM7E,eAAsB,0BAAA,CAA2B,QAAgB,OAAA,EAAiC;AAChG,EAAA,MAAM,WAAA,GAAc,MAAA,CAAO,oBAAA,CAAoD,gBAAgB,CAAA;AAE/F,EAAA,IAAI,CAAC,WAAA,EAAa;AAChB,IAAA;AAAA,EACF;AAEA,EAAA,MAAM,qBAAqB,WAAA,CAAY,kBAAA;AACvC,EAAA,MAAM,iBAAA,GACJ,uBACC,MAAA,CAAO,wBAAA,GAA2B,UAAA,CAAW,QAAA,CAAS,iBAAiB,CAAA,GAAI,QAAA,GAAW,MAAA,CAAA;AAEzF,EAAA,IAAI,sBAAsB,MAAA,EAAQ;AAChC,IAAA;AAAA,EACF;AAIA,EAAA,IAAI,OAAA,CAAQ,WAAW,KAAA,IAAS,OAAA,CAAQ,WAAW,MAAA,IAAU,OAAA,CAAQ,WAAW,SAAA,EAAW;AACzF,IAAA;AAAA,EACF;AAEA,EAAA,IAAI,WAAA,CAAY,iBAAA,GAAoB,OAAA,CAAQ,GAAA,EAAK,OAAO,CAAA,EAAG;AACzD,IAAA;AAAA,EACF;AAEA,EAAA,MAAM,iBAAiBC,sBAAA,EAAkB;AACzC,EAAA,MAAMC,mCAAA,CAA+B,OAAA,EAAS,cAAA,EAAgB,iBAAiB,CAAA;AACjF;;;;;"}
1
+ {"version":3,"file":"httpServer.js","sources":["../../../../src/integrations/httpServer.ts"],"sourcesContent":["import type { Client, IntegrationFn, MaxRequestBodySize, Span } from '@sentry/core';\nimport {\n captureBodyFromWinterCGRequest,\n defineIntegration,\n getIsolationScope,\n hasSpansEnabled,\n parseStringToURLObject,\n safeCallback,\n} from '@sentry/core';\nimport type { AssertTrue, CheckServerRequestOptions } from '@sentry/core/server';\nimport { isStaticAssetRequest } from '@sentry/core/server';\nimport { DEBUG_BUILD } from '../debug-build';\n\nconst INTEGRATION_NAME = 'HttpServer' as const;\n\nexport interface HttpServerIntegrationOptions {\n /**\n * Controls the maximum size of incoming request bodies attached to events.\n *\n * Only applies to requests with textual content types (text/*, application/json,\n * application/x-www-form-urlencoded, application/xml, application/graphql).\n * Binary data is not captured.\n *\n * Available options:\n * - `'none'`: No request bodies will be attached\n * - `'small'`: Request bodies up to 1,000 bytes will be attached\n * - `'medium'`: Request bodies up to 10,000 bytes will be attached (default)\n * - `'always'`: Request bodies will always be attached (up to 1MB limit)\n *\n * @default 'medium'\n */\n maxRequestBodySize?: MaxRequestBodySize;\n\n /**\n * Do not capture the request body for incoming HTTP requests to URLs where the given callback returns `true`.\n * This can be useful for long running requests where the body is not needed, health check endpoints,\n * or requests containing sensitive data that should not be captured.\n *\n * @param url The full URL of the incoming request, including query string, protocol, host, etc.\n * @param request The incoming Request object.\n * @returns `true` to skip body capture for this request, `false` to capture normally.\n *\n * @example\n * ```ts\n * Sentry.httpServerIntegration({\n * ignoreRequestBody: (url) => url.includes('/health') || url.includes('/upload'),\n * })\n * ```\n */\n ignoreRequestBody?: (url: string, request: Request) => boolean;\n\n /**\n * Do not create spans for incoming requests whose URL path makes the given callback return `true`.\n *\n * `urlPath` is the path of the request, including the query string. `request` is the incoming\n * {@link Request}. Errors thrown by the handler are still captured.\n */\n ignoreIncomingRequests?: (urlPath: string, request: Request) => boolean;\n\n /**\n * Whether to automatically ignore common static asset requests (favicon.ico, robots.txt, etc.)\n * when creating spans.\n *\n * @default `true`\n */\n ignoreStaticAssets?: boolean;\n\n /**\n * Whether to create spans for incoming requests.\n * Errors are still captured and request data is still attached when this is `false`.\n * Defaults to the client's tracing configuration (`hasSpansEnabled`).\n */\n spans?: boolean;\n\n /**\n * A hook that can be used to mutate the span for incoming requests.\n * This is triggered after the span is created, before the request handler runs.\n */\n onSpanCreated?: (span: Span, request: Request) => void;\n\n /**\n * A hook that can be used to mutate the span one last time before it ends.\n * For a streamed response, this runs when the stream finishes.\n * It is not called when the request handler throws.\n */\n onSpanEnd?: (span: Span, request: Request, response: Response) => void;\n}\n\n// Checks these options against the shared `ServerRequestOptions`. A new\n// shared field fails to compile here, until this integration supports\n// it or lists it as unsupported.\ntype _ServerRequestOptionsCheck = AssertTrue<\n CheckServerRequestOptions<\n HttpServerIntegrationOptions,\n Request,\n Response,\n // Not supported. A worker has no long-lived process to run the timer\n // that flushes session aggregates.\n 'sessions' | 'sessionFlushingDelayMS'\n >\n>;\n\ninterface HttpServerIntegrationInstance extends HttpServerIntegrationOptions {\n name: string;\n maxRequestBodySize: MaxRequestBodySize | undefined;\n}\n\nconst _httpServerIntegration = ((options: HttpServerIntegrationOptions = {}): HttpServerIntegrationInstance => {\n return {\n name: INTEGRATION_NAME,\n maxRequestBodySize: options.maxRequestBodySize,\n ignoreRequestBody: options.ignoreRequestBody,\n ignoreIncomingRequests: options.ignoreIncomingRequests,\n ignoreStaticAssets: options.ignoreStaticAssets ?? true,\n spans: options.spans,\n onSpanCreated: options.onSpanCreated,\n onSpanEnd: options.onSpanEnd,\n };\n}) satisfies IntegrationFn;\n\n/**\n * Configures incoming HTTP request handling for Cloudflare Workers.\n *\n * This integration controls how incoming HTTP request data is captured,\n * matching the API of `httpServerIntegration` in Node.js.\n *\n * @example\n * ```ts\n * Sentry.init({\n * integrations: [\n * Sentry.httpServerIntegration({\n * maxRequestBodySize: 'medium',\n * ignoreRequestBody: (url) => url.includes('/health'),\n * }),\n * ],\n * });\n * ```\n */\nexport const httpServerIntegration = defineIntegration(_httpServerIntegration);\n\n/**\n * Capture the request body based on the HttpServer integration config.\n * Called internally by `wrapRequestHandler`.\n */\nexport async function captureIncomingRequestBody(client: Client, request: Request): Promise<void> {\n const integration = client.getIntegrationByName<HttpServerIntegrationInstance>(INTEGRATION_NAME);\n\n if (!integration) {\n return;\n }\n\n const configuredBodySize = integration.maxRequestBodySize;\n const effectiveBodySize: MaxRequestBodySize =\n configuredBodySize ??\n (client.getDataCollectionOptions().httpBodies.includes('incomingRequest') ? 'medium' : 'none');\n\n if (effectiveBodySize === 'none') {\n return;\n }\n\n // Skip GET and HEAD requests - they don't have bodies\n // Also skip OPTIONS, even if they may have a body, they might not give a lot of extra value\n if (request.method === 'GET' || request.method === 'HEAD' || request.method === 'OPTIONS') {\n return;\n }\n\n const ignoreRequestBody = integration.ignoreRequestBody;\n if (\n ignoreRequestBody &&\n // If the filter throws, skip the body so it cannot leak data the filter was meant to hide.\n safeCallback(\n DEBUG_BUILD ? 'Error in `ignoreRequestBody`, skipping the body:' : '',\n () => ignoreRequestBody(request.url, request),\n () => true,\n )\n ) {\n return;\n }\n\n const isolationScope = getIsolationScope();\n await captureBodyFromWinterCGRequest(request, isolationScope, effectiveBodySize);\n}\n\n/**\n * Whether to create a span for the incoming request, based on the HttpServer integration config.\n * Called internally by `wrapRequestHandler`.\n */\nexport function shouldCreateIncomingRequestSpan(client: Client | undefined, request: Request): boolean {\n if (!client) {\n return false;\n }\n\n const integration = client.getIntegrationByName<HttpServerIntegrationInstance>(INTEGRATION_NAME);\n if (!(integration?.spans ?? hasSpansEnabled(client.getOptions()))) {\n return false;\n }\n\n const urlObject = parseStringToURLObject(request.url);\n const urlPath = urlObject ? `${urlObject.pathname}${urlObject.search}` : '/';\n if (integration?.ignoreStaticAssets && request.method === 'GET' && isStaticAssetRequest(urlPath)) {\n return false;\n }\n\n const ignoreIncomingRequests = integration?.ignoreIncomingRequests;\n return !(\n ignoreIncomingRequests &&\n safeCallback(\n DEBUG_BUILD ? 'Error in `ignoreIncomingRequests`, creating the span:' : '',\n () => ignoreIncomingRequests(urlPath, request),\n () => false,\n )\n );\n}\n\n/**\n * The `onSpanCreated` and `onSpanEnd` hooks of the HttpServer integration, guarded so that a hook\n * that throws does not fail the request. Called internally by `wrapRequestHandler`.\n */\nexport function getIncomingRequestSpanHooks(client: Client | undefined): {\n onSpanCreated: (span: Span, request: Request) => void;\n onSpanEnd: (span: Span, request: Request, response: Response) => void;\n} {\n const integration = client?.getIntegrationByName<HttpServerIntegrationInstance>(INTEGRATION_NAME);\n return {\n onSpanCreated: (span, request) =>\n safeCallback(\n DEBUG_BUILD ? 'Error in `onSpanCreated`:' : '',\n () => integration?.onSpanCreated?.(span, request),\n () => undefined,\n ),\n onSpanEnd: (span, request, response) =>\n safeCallback(\n DEBUG_BUILD ? 'Error in `onSpanEnd`:' : '',\n () => integration?.onSpanEnd?.(span, request, response),\n () => undefined,\n ),\n };\n}\n"],"names":["defineIntegration","safeCallback","DEBUG_BUILD","getIsolationScope","captureBodyFromWinterCGRequest","hasSpansEnabled","parseStringToURLObject","isStaticAssetRequest"],"mappings":";;;;;;AAaA,MAAM,gBAAA,GAAmB,YAAA;AA8FzB,MAAM,sBAAA,IAA0B,CAAC,OA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B,EAAA;AAAA,MAC5C,MAAM,WAAA,EAAa,aAAA,GAAgB,IAAA,EAAM,OAAO,CAAA;AAAA,MAChD,MAAM;AAAA,KACR;AAAA,IACF,SAAA,EAAW,CAAC,IAAA,EAAM,OAAA,EAAS,QAAA,KACzBD,iBAAA;AAAA,MACEC,yBAAc,uBAAA,GAA0B,EAAA;AAAA,MACxC,MAAM,WAAA,EAAa,SAAA,GAAY,IAAA,EAAM,SAAS,QAAQ,CAAA;AAAA,MACtD,MAAM;AAAA;AACR,GACJ;AACF;;;;;;;"}
@@ -27,12 +27,14 @@ class IsolatedPromiseBuffer {
27
27
  this._taskProducers = [];
28
28
  const drainController = new AbortController();
29
29
  this.drainSignal = drainController.signal;
30
- let tasks;
31
- try {
32
- tasks = oldTaskProducers.map((taskProducer) => taskProducer());
33
- } finally {
34
- this.drainSignal = void 0;
35
- }
30
+ const tasks = oldTaskProducers.map((taskProducer) => {
31
+ try {
32
+ return taskProducer();
33
+ } catch (error) {
34
+ return Promise.reject(error);
35
+ }
36
+ });
37
+ this.drainSignal = void 0;
36
38
  return new Promise((resolve) => {
37
39
  const timer = setTimeout(() => {
38
40
  if (timeout && timeout > 0) {
@@ -1 +1 @@
1
- {"version":3,"file":"transport.js","sources":["../../../src/transport.ts"],"sourcesContent":["import type { BaseTransportOptions, Transport, TransportMakeRequestResponse, TransportRequest } from '@sentry/core';\nimport { createTransport, SENTRY_BUFFER_FULL_ERROR, suppressTracing } from '@sentry/core';\n\nexport interface CloudflareTransportOptions extends BaseTransportOptions {\n /** Custom fetch function to use. This allows usage of things like Workers VPC */\n fetch?: typeof fetch;\n /** Fetch API init parameters. */\n fetchOptions?: RequestInit;\n}\n\n/**\n * How many payloads the buffer holds before it starts rejecting new ones.\n *\n * With `cacheClient` a single client is reused across an isolate's invocations, so one buffer now has to absorb\n * the payloads of many invocations rather than one. 256 is the size that held up under load testing that scenario.\n */\nconst DEFAULT_TRANSPORT_BUFFER_SIZE = 256;\n\n/**\n * This is a modified promise buffer that collects tasks until drain is called.\n * We need this in the edge runtime because edge function invocations may not share I/O objects, like fetch requests\n * and responses, and the normal PromiseBuffer inherently buffers stuff inbetween incoming requests.\n *\n * A limitation we need to be aware of is that DEFAULT_TRANSPORT_BUFFER_SIZE is the maximum amount of payloads the\n * SDK can send for a given edge function invocation.\n */\nexport class IsolatedPromiseBuffer {\n // We just have this field because the promise buffer interface requires it.\n // If we ever remove it from the interface we should also remove it here.\n public $: Array<PromiseLike<TransportMakeRequestResponse>>;\n\n /**\n * Abort signal of the drain that is starting its requests. It is set only while `drain()` runs the task\n * producers, so a request reads the signal of the drain that sends it.\n */\n public drainSignal: AbortSignal | undefined;\n\n private _taskProducers: (() => PromiseLike<TransportMakeRequestResponse>)[];\n\n private readonly _bufferSize: number;\n\n public constructor(_bufferSize = DEFAULT_TRANSPORT_BUFFER_SIZE) {\n this.$ = [];\n this._taskProducers = [];\n this._bufferSize = _bufferSize;\n }\n\n /**\n * @inheritdoc\n */\n public add(taskProducer: () => PromiseLike<TransportMakeRequestResponse>): PromiseLike<TransportMakeRequestResponse> {\n if (this._taskProducers.length >= this._bufferSize) {\n return Promise.reject(SENTRY_BUFFER_FULL_ERROR);\n }\n\n this._taskProducers.push(taskProducer);\n return Promise.resolve({});\n }\n\n /**\n * @inheritdoc\n */\n public drain(timeout?: number): PromiseLike<boolean> {\n const oldTaskProducers = [...this._taskProducers];\n this._taskProducers = [];\n\n const drainController = new AbortController();\n this.drainSignal = drainController.signal;\n let tasks: PromiseLike<TransportMakeRequestResponse>[];\n try {\n tasks = oldTaskProducers.map(taskProducer => taskProducer());\n } finally {\n this.drainSignal = undefined;\n }\n\n return new Promise(resolve => {\n const timer = setTimeout(() => {\n if (timeout && timeout > 0) {\n // Requests still pending when the drain times out are aborted. Otherwise Cloudflare keeps them\n // until it cancels the invocation's `waitUntil` work and logs a warning.\n drainController.abort();\n resolve(false);\n }\n }, timeout);\n\n // This cannot reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n Promise.all(\n tasks.map(task =>\n task.then(null, () => {\n // catch all failed requests\n }),\n ),\n ).then(() => {\n // resolve to true if all fetch requests settled\n clearTimeout(timer);\n resolve(true);\n });\n });\n }\n}\n\n/**\n * Creates a Transport that uses the native fetch API to send events to Sentry.\n */\nexport function makeCloudflareTransport(options: CloudflareTransportOptions): Transport {\n const buffer = new IsolatedPromiseBuffer(options.bufferSize);\n\n function makeRequest(request: TransportRequest): PromiseLike<TransportMakeRequestResponse> {\n const drainSignal = buffer.drainSignal;\n const callerSignal = options.fetchOptions?.signal ?? undefined;\n const signal =\n drainSignal && callerSignal ? AbortSignal.any([drainSignal, callerSignal]) : (drainSignal ?? callerSignal);\n\n const requestOptions: RequestInit = {\n body: request.body as BodyInit,\n method: 'POST',\n headers: options.headers,\n ...options.fetchOptions,\n ...(signal ? { signal } : {}),\n };\n\n return suppressTracing(() => {\n return (options.fetch ?? fetch)(options.url, requestOptions).then(async response => {\n // Consume the response body to satisfy Cloudflare Workers' fetch requirements.\n // The runtime requires all fetch response bodies to be read or explicitly canceled\n // to prevent connection stalls and potential deadlocks. We read the body as text\n // even though we don't use the content, as Sentry's response information is in the headers.\n // See: https://github.com/getsentry/sentry-javascript/issues/18534\n try {\n await response.text();\n } catch {\n // no-op\n }\n\n return {\n statusCode: response.status,\n headers: {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n },\n };\n });\n });\n }\n\n return createTransport(options, makeRequest, buffer);\n}\n"],"names":["SENTRY_BUFFER_FULL_ERROR","suppressTracing","createTransport"],"mappings":";;;;AAgBA,MAAM,6BAAA,GAAgC,GAAA;AAU/B,MAAM,qBAAA,CAAsB;AAAA,EAe1B,WAAA,CAAY,cAAc,6BAAA,EAA+B;AAC9D,IAAA,IAAA,CAAK,IAAI,EAAC;AACV,IAAA,IAAA,CAAK,iBAAiB,EAAC;AACvB,IAAA,IAAA,CAAK,WAAA,GAAc,WAAA;AAAA,EACrB;AA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,aAAa;AAAA;AACnD,SACF;AAAA,MACF,CAAC,CAAA;AAAA,IACH,CAAC,CAAA;AAAA,EACH;AAEA,EAAA,OAAOC,oBAAA,CAAgB,OAAA,EAAS,WAAA,EAAa,MAAM,CAAA;AACrD;;;;;"}
1
+ {"version":3,"file":"transport.js","sources":["../../../src/transport.ts"],"sourcesContent":["import type { BaseTransportOptions, Transport, TransportMakeRequestResponse, TransportRequest } from '@sentry/core';\nimport { createTransport, SENTRY_BUFFER_FULL_ERROR, suppressTracing } from '@sentry/core';\n\nexport interface CloudflareTransportOptions extends BaseTransportOptions {\n /** Custom fetch function to use. This allows usage of things like Workers VPC */\n fetch?: typeof fetch;\n /** Fetch API init parameters. */\n fetchOptions?: RequestInit;\n}\n\n/**\n * How many payloads the buffer holds before it starts rejecting new ones.\n *\n * With `cacheClient` a single client is reused across an isolate's invocations, so one buffer now has to absorb\n * the payloads of many invocations rather than one. 256 is the size that held up under load testing that scenario.\n */\nconst DEFAULT_TRANSPORT_BUFFER_SIZE = 256;\n\n/**\n * This is a modified promise buffer that collects tasks until drain is called.\n * We need this in the edge runtime because edge function invocations may not share I/O objects, like fetch requests\n * and responses, and the normal PromiseBuffer inherently buffers stuff inbetween incoming requests.\n *\n * A limitation we need to be aware of is that DEFAULT_TRANSPORT_BUFFER_SIZE is the maximum amount of payloads the\n * SDK can send for a given edge function invocation.\n */\nexport class IsolatedPromiseBuffer {\n // We just have this field because the promise buffer interface requires it.\n // If we ever remove it from the interface we should also remove it here.\n public $: Array<PromiseLike<TransportMakeRequestResponse>>;\n\n /**\n * Abort signal of the drain that is starting its requests. It is set only while `drain()` runs the task\n * producers, so a request reads the signal of the drain that sends it.\n */\n public drainSignal: AbortSignal | undefined;\n\n private _taskProducers: (() => PromiseLike<TransportMakeRequestResponse>)[];\n\n private readonly _bufferSize: number;\n\n public constructor(_bufferSize = DEFAULT_TRANSPORT_BUFFER_SIZE) {\n this.$ = [];\n this._taskProducers = [];\n this._bufferSize = _bufferSize;\n }\n\n /**\n * @inheritdoc\n */\n public add(taskProducer: () => PromiseLike<TransportMakeRequestResponse>): PromiseLike<TransportMakeRequestResponse> {\n if (this._taskProducers.length >= this._bufferSize) {\n return Promise.reject(SENTRY_BUFFER_FULL_ERROR);\n }\n\n this._taskProducers.push(taskProducer);\n return Promise.resolve({});\n }\n\n /**\n * @inheritdoc\n */\n public drain(timeout?: number): PromiseLike<boolean> {\n const oldTaskProducers = [...this._taskProducers];\n this._taskProducers = [];\n\n const drainController = new AbortController();\n this.drainSignal = drainController.signal;\n const tasks = oldTaskProducers.map(taskProducer => {\n // A request that throws synchronously, such as a custom `fetch`, must not stop the other requests\n // or throw into the caller.\n try {\n return taskProducer();\n } catch (error) {\n return Promise.reject(error);\n }\n });\n this.drainSignal = undefined;\n\n return new Promise(resolve => {\n const timer = setTimeout(() => {\n if (timeout && timeout > 0) {\n // Requests still pending when the drain times out are aborted. Otherwise Cloudflare keeps them\n // until it cancels the invocation's `waitUntil` work and logs a warning.\n drainController.abort();\n resolve(false);\n }\n }, timeout);\n\n // This cannot reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n Promise.all(\n tasks.map(task =>\n task.then(null, () => {\n // catch all failed requests\n }),\n ),\n ).then(() => {\n // resolve to true if all fetch requests settled\n clearTimeout(timer);\n resolve(true);\n });\n });\n }\n}\n\n/**\n * Creates a Transport that uses the native fetch API to send events to Sentry.\n */\nexport function makeCloudflareTransport(options: CloudflareTransportOptions): Transport {\n const buffer = new IsolatedPromiseBuffer(options.bufferSize);\n\n function makeRequest(request: TransportRequest): PromiseLike<TransportMakeRequestResponse> {\n const drainSignal = buffer.drainSignal;\n const callerSignal = options.fetchOptions?.signal ?? undefined;\n const signal =\n drainSignal && callerSignal ? AbortSignal.any([drainSignal, callerSignal]) : (drainSignal ?? callerSignal);\n\n const requestOptions: RequestInit = {\n body: request.body as BodyInit,\n method: 'POST',\n headers: options.headers,\n ...options.fetchOptions,\n ...(signal ? { signal } : {}),\n };\n\n return suppressTracing(() => {\n return (options.fetch ?? fetch)(options.url, requestOptions).then(async response => {\n // Consume the response body to satisfy Cloudflare Workers' fetch requirements.\n // The runtime requires all fetch response bodies to be read or explicitly canceled\n // to prevent connection stalls and potential deadlocks. We read the body as text\n // even though we don't use the content, as Sentry's response information is in the headers.\n // See: https://github.com/getsentry/sentry-javascript/issues/18534\n try {\n await response.text();\n } catch {\n // no-op\n }\n\n return {\n statusCode: response.status,\n headers: {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n },\n };\n });\n });\n }\n\n return createTransport(options, makeRequest, buffer);\n}\n"],"names":["SENTRY_BUFFER_FULL_ERROR","suppressTracing","createTransport"],"mappings":";;;;AAgBA,MAAM,6BAAA,GAAgC,GAAA;AAU/B,MAAM,qBAAA,CAAsB;AAAA,EAe1B,WAAA,CAAY,cAAc,6BAAA,EAA+B;AAC9D,IAAA,IAAA,CAAK,IAAI,EAAC;AACV,IAAA,IAAA,CAAK,iBAAiB,EAAC;AACvB,IAAA,IAAA,CAAK,WAAA,GAAc,WAAA;AAAA,EACrB;AAAA;AAAA;AAAA;AAAA,EAKO,IAAI,YAAA,EAA0G;AACnH,IAAA,IAAI,IAAA,CAAK,cAAA,CAAe,MAAA,IAAU,IAAA,CAAK,WAAA,EAAa;AAClD,MAAA,OAAO,OAAA,CAAQ,OAAOA,6BAAwB,CAAA;AAAA,IAChD;AAEA,IAAA,IAAA,CAAK,cAAA,CAAe,KAAK,YAAY,CAAA;AACrC,IAAA,OAAO,OAAA,CAAQ,OAAA,CAAQ,EAAE,CAAA;AAAA,EAC3B;AAAA;AAAA;AAAA;AAAA,EAKO,MAAM,OAAA,EAAwC;AACnD,IAAA,MAAM,gBAAA,GAAmB,CAAC,GAAG,IAAA,CAAK,cAAc,CAAA;AAChD,IAAA,IAAA,CAAK,iBAAiB,EAAC;AAEvB,IAAA,MAAM,eAAA,GAAkB,IAAI,eAAA,EAAgB;AAC5C,IAAA,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,CAAI,CAAC,WAAA,EAAa,YAAY,CAAC,CAAA,GAAK,WAAA,IAAe,YAAA;AAE/F,IAAA,MAAM,cAAA,GAA8B;AAAA,MAClC,MAAM,OAAA,CAAQ,IAAA;AAAA,MACd,MAAA,EAAQ,MAAA;AAAA,MACR,SAAS,OAAA,CAAQ,OAAA;AAAA,MACjB,GAAG,OAAA,CAAQ,YAAA;AAAA,MACX,GAAI,MAAA,GAAS,EAAE,MAAA,KAAW;AAAC,KAC7B;AAEA,IAAA,OAAOC,qBAAgB,MAAM;AAC3B,MAAA,OAAA,CAAQ,OAAA,CAAQ,SAAS,KAAA,EAAO,OAAA,CAAQ,KAAK,cAAc,CAAA,CAAE,IAAA,CAAK,OAAM,QAAA,KAAY;AAMlF,QAAA,IAAI;AACF,UAAA,MAAM,SAAS,IAAA,EAAK;AAAA,QACtB,CAAA,CAAA,MAAQ;AAAA,QAER;AAEA,QAAA,OAAO;AAAA,UACL,YAAY,QAAA,CAAS,MAAA;AAAA,UACrB,OAAA,EAAS;AAAA,YACP,sBAAA,EAAwB,QAAA,CAAS,OAAA,CAAQ,GAAA,CAAI,sBAAsB,CAAA;AAAA,YACnE,aAAA,EAAe,QAAA,CAAS,OAAA,CAAQ,GAAA,CAAI,aAAa;AAAA;AACnD,SACF;AAAA,MACF,CAAC,CAAA;AAAA,IACH,CAAC,CAAA;AAAA,EACH;AAEA,EAAA,OAAOC,oBAAA,CAAgB,OAAA,EAAS,WAAA,EAAa,MAAM,CAAA;AACrD;;;;;"}
@@ -25,14 +25,14 @@ function setInvocationState(scope, state) {
25
25
  );
26
26
  return;
27
27
  }
28
- scope[INVOCATION_STATE] = state;
28
+ scope.refs[INVOCATION_STATE] = state;
29
29
  }
30
30
  function getInvocationState() {
31
31
  const isolationScope = core.getIsolationScope();
32
32
  if (isolationScope === core.getDefaultIsolationScope()) {
33
33
  return void 0;
34
34
  }
35
- return isolationScope[INVOCATION_STATE];
35
+ return isolationScope.refs[INVOCATION_STATE];
36
36
  }
37
37
 
38
38
  exports.getInvocationState = getInvocationState;
@@ -1 +1 @@
1
- {"version":3,"file":"invocationContext.js","sources":["../../../../src/utils/invocationContext.ts"],"sourcesContent":["import type { ExecutionContext } from '@cloudflare/workers-types';\nimport type { Scope } from '@sentry/core';\nimport { debug, getDefaultIsolationScope, getIsolationScope } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { ExecutionContextCompat } from '../executionContext';\nimport { getOriginalWaitUntil } from '../flush';\n\n/**\n * State owned by a single invocation (request, RPC call, cron, ...).\n *\n * A cached client (`cacheClient`) is shared by all invocations running in the same\n * isolate, so anything invocation-owned must not live on the client: two overlapping\n * requests would otherwise overwrite each other's state (e.g. the execution context\n * used to register eager flushes) and the earlier invocation's envelopes would be\n * suspended when the later invocation ends.\n *\n * The state rides on the invocation's forked isolation scope, which the async\n * context strategy (AsyncLocalStorage) hands back for exactly the async context that\n * owns the invocation — including detached continuations created inside it. A symbol\n * key keeps it off `Scope.clone()` and out of serialized event data.\n */\nexport interface InvocationState {\n /**\n * The execution context of the invocation that owns this scope. Eager envelope\n * sends are registered with this context's `waitUntil`, so they are attributed to\n * the invocation that captured the data even when invocations overlap.\n */\n readonly ctx: ExecutionContextCompat | undefined;\n /**\n * Set on the client's `flush` hook, the invocation's natural flush point.\n * Captures before it are drained by that flush; captures after it (in\n * `waitUntil` work or detached continuations) have no later flush to ride and\n * are delivered eagerly.\n */\n flushPointReached?: boolean;\n /**\n * `ctx.waitUntil` resolved once for this invocation (see `getInvocationWaitUntil`).\n * `null` once resolved to \"no usable waitUntil\".\n */\n waitUntil?: ExecutionContext['waitUntil'] | null;\n}\n\nconst INVOCATION_STATE: unique symbol = Symbol('sentryInvocationState');\n\n/**\n * Returns the invocation's original (un-instrumented) `waitUntil`, bound to its context,\n * resolving it on first use and caching it on the state. Reading `ctx.waitUntil` on a\n * native `ExecutionContext`/`DurableObjectState` goes through the runtime's property\n * getter every time; one read per invocation is enough.\n */\nexport function getInvocationWaitUntil(state: InvocationState): ExecutionContext['waitUntil'] | undefined {\n if (state.waitUntil === undefined) {\n const ctx = state.ctx;\n let resolved: ExecutionContext['waitUntil'] | null = null;\n try {\n const original = ctx && getOriginalWaitUntil(ctx);\n resolved = original ? original.bind(ctx) : null;\n } catch {\n // Accessing `waitUntil` can throw on foreign or already-torn-down contexts.\n }\n state.waitUntil = resolved;\n }\n return state.waitUntil ?? undefined;\n}\n\ntype ScopeWithInvocationState = Scope & {\n [INVOCATION_STATE]?: InvocationState;\n};\n\n/**\n * Attaches invocation state to a forked isolation scope. Only meaningful on a scope\n * that outlives nothing but this invocation — never attach to the default isolation\n * scope, which is shared by every invocation in the isolate.\n */\nexport function setInvocationState(scope: Scope, state: InvocationState): void {\n if (scope === getDefaultIsolationScope()) {\n DEBUG_BUILD &&\n debug.warn(\n '[Sentry] Cannot track this invocation. Telemetry captured after the invocation ends may not be delivered.',\n );\n return;\n }\n\n (scope as ScopeWithInvocationState)[INVOCATION_STATE] = state;\n}\n\n/**\n * Returns the state of the invocation that owns the current async context, or\n * `undefined` outside any instrumented invocation (the default isolation scope is\n * shared, so state read from it could not be attributed to one invocation — and it\n * is never attached there in the first place).\n */\nexport function getInvocationState(): InvocationState | undefined {\n const isolationScope = getIsolationScope() as ScopeWithInvocationState;\n if (isolationScope === getDefaultIsolationScope()) {\n return undefined;\n }\n return isolationScope[INVOCATION_STATE];\n}\n"],"names":["getOriginalWaitUntil","getDefaultIsolationScope","DEBUG_BUILD","debug","getIsolationScope"],"mappings":";;;;;;AA0CA,MAAM,gBAAA,0BAAyC,uBAAuB,CAAA;AAQ/D,SAAS,uBAAuB,KAAA,EAAmE;AACxG,EAAA,IAAI,KAAA,CAAM,cAAc,MAAA,EAAW;AACjC,IAAA,MAAM,MAAM,KAAA,CAAM,GAAA;AAClB,IAAA,IAAI,QAAA,GAAiD,IAAA;AACrD,IAAA,IAAI;AACF,MAAA,MAAM,QAAA,GAAW,GAAA,IAAOA,0BAAA,CAAqB,GAAG,CAAA;AAChD,MAAA,QAAA,GAAW,QAAA,GAAW,QAAA,CAAS,IAAA,CAAK,GAAG,CAAA,GAAI,IAAA;AAAA,IAC7C,CAAA,CAAA,MAAQ;AAAA,IAER;AACA,IAAA,KAAA,CAAM,SAAA,GAAY,QAAA;AAAA,EACpB;AACA,EAAA,OAAO,MAAM,SAAA,IAAa,MAAA;AAC5B;AAWO,SAAS,kBAAA,CAAmB,OAAc,KAAA,EAA8B;AAC7E,EAAA,IAAI,KAAA,KAAUC,+BAAyB,EAAG;AACxC,IAAAC,sBAAA,IACEC,UAAA,CAAM,IAAA;AAAA,MACJ;AAAA,KACF;AACF,IAAA;AAAA,EACF;AAEA,EAAC,KAAA,CAAmC,gBAAgB,CAAA,GAAI,KAAA;AAC1D;AAQO,SAAS,kBAAA,GAAkD;AAChE,EAAA,MAAM,iBAAiBC,sBAAA,EAAkB;AACzC,EAAA,IAAI,cAAA,KAAmBH,+BAAyB,EAAG;AACjD,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,OAAO,eAAe,gBAAgB,CAAA;AACxC;;;;;;"}
1
+ {"version":3,"file":"invocationContext.js","sources":["../../../../src/utils/invocationContext.ts"],"sourcesContent":["import type { ExecutionContext } from '@cloudflare/workers-types';\nimport type { Scope } from '@sentry/core';\nimport { debug, getDefaultIsolationScope, getIsolationScope } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { ExecutionContextCompat } from '../executionContext';\nimport { getOriginalWaitUntil } from '../flush';\n\n/**\n * State owned by a single invocation (request, RPC call, cron, ...).\n *\n * A cached client (`cacheClient`) is shared by all invocations running in the same\n * isolate, so anything invocation-owned must not live on the client: two overlapping\n * requests would otherwise overwrite each other's state (e.g. the execution context\n * used to register eager flushes) and the earlier invocation's envelopes would be\n * suspended when the later invocation ends.\n *\n * The state rides on the invocation's forked isolation scope, which the async\n * context strategy (AsyncLocalStorage) hands back for exactly the async context that\n * owns the invocation — including detached continuations created inside it. It lives under\n * a symbol key in the scope's `refs`, so isolation scopes forked inside the invocation\n * (`withMonitor`, `withIsolationScope`) share it, and it stays out of serialized event data.\n */\nexport interface InvocationState {\n /**\n * The execution context of the invocation that owns this scope. Eager envelope\n * sends are registered with this context's `waitUntil`, so they are attributed to\n * the invocation that captured the data even when invocations overlap.\n */\n readonly ctx: ExecutionContextCompat | undefined;\n /**\n * Set on the client's `flush` hook, the invocation's natural flush point.\n * Captures before it are drained by that flush; captures after it (in\n * `waitUntil` work or detached continuations) have no later flush to ride and\n * are delivered eagerly.\n */\n flushPointReached?: boolean;\n /**\n * `ctx.waitUntil` resolved once for this invocation (see `getInvocationWaitUntil`).\n * `null` once resolved to \"no usable waitUntil\".\n */\n waitUntil?: ExecutionContext['waitUntil'] | null;\n}\n\nconst INVOCATION_STATE: unique symbol = Symbol('sentryInvocationState');\n\n/**\n * Returns the invocation's original (un-instrumented) `waitUntil`, bound to its context,\n * resolving it on first use and caching it on the state. Reading `ctx.waitUntil` on a\n * native `ExecutionContext`/`DurableObjectState` goes through the runtime's property\n * getter every time; one read per invocation is enough.\n */\nexport function getInvocationWaitUntil(state: InvocationState): ExecutionContext['waitUntil'] | undefined {\n if (state.waitUntil === undefined) {\n const ctx = state.ctx;\n let resolved: ExecutionContext['waitUntil'] | null = null;\n try {\n const original = ctx && getOriginalWaitUntil(ctx);\n resolved = original ? original.bind(ctx) : null;\n } catch {\n // Accessing `waitUntil` can throw on foreign or already-torn-down contexts.\n }\n state.waitUntil = resolved;\n }\n return state.waitUntil ?? undefined;\n}\n\ntype ScopeRefsWithInvocationState = Scope['refs'] & {\n [INVOCATION_STATE]?: InvocationState;\n};\n\n/**\n * Attaches invocation state to a forked isolation scope. Only meaningful on a scope\n * that outlives nothing but this invocation — never attach to the default isolation\n * scope, which is shared by every invocation in the isolate.\n */\nexport function setInvocationState(scope: Scope, state: InvocationState): void {\n if (scope === getDefaultIsolationScope()) {\n DEBUG_BUILD &&\n debug.warn(\n '[Sentry] Cannot track this invocation. Telemetry captured after the invocation ends may not be delivered.',\n );\n return;\n }\n\n (scope.refs as ScopeRefsWithInvocationState)[INVOCATION_STATE] = state;\n}\n\n/**\n * Returns the state of the invocation that owns the current async context, or\n * `undefined` outside any instrumented invocation (the default isolation scope is\n * shared, so state read from it could not be attributed to one invocation — and it\n * is never attached there in the first place).\n */\nexport function getInvocationState(): InvocationState | undefined {\n const isolationScope = getIsolationScope();\n if (isolationScope === getDefaultIsolationScope()) {\n return undefined;\n }\n return (isolationScope.refs as ScopeRefsWithInvocationState)[INVOCATION_STATE];\n}\n"],"names":["getOriginalWaitUntil","getDefaultIsolationScope","DEBUG_BUILD","debug","getIsolationScope"],"mappings":";;;;;;AA2CA,MAAM,gBAAA,0BAAyC,uBAAuB,CAAA;AAQ/D,SAAS,uBAAuB,KAAA,EAAmE;AACxG,EAAA,IAAI,KAAA,CAAM,cAAc,MAAA,EAAW;AACjC,IAAA,MAAM,MAAM,KAAA,CAAM,GAAA;AAClB,IAAA,IAAI,QAAA,GAAiD,IAAA;AACrD,IAAA,IAAI;AACF,MAAA,MAAM,QAAA,GAAW,GAAA,IAAOA,0BAAA,CAAqB,GAAG,CAAA;AAChD,MAAA,QAAA,GAAW,QAAA,GAAW,QAAA,CAAS,IAAA,CAAK,GAAG,CAAA,GAAI,IAAA;AAAA,IAC7C,CAAA,CAAA,MAAQ;AAAA,IAER;AACA,IAAA,KAAA,CAAM,SAAA,GAAY,QAAA;AAAA,EACpB;AACA,EAAA,OAAO,MAAM,SAAA,IAAa,MAAA;AAC5B;AAWO,SAAS,kBAAA,CAAmB,OAAc,KAAA,EAA8B;AAC7E,EAAA,IAAI,KAAA,KAAUC,+BAAyB,EAAG;AACxC,IAAAC,sBAAA,IACEC,UAAA,CAAM,IAAA;AAAA,MACJ;AAAA,KACF;AACF,IAAA;AAAA,EACF;AAEA,EAAC,KAAA,CAAM,IAAA,CAAsC,gBAAgB,CAAA,GAAI,KAAA;AACnE;AAQO,SAAS,kBAAA,GAAkD;AAChE,EAAA,MAAM,iBAAiBC,sBAAA,EAAkB;AACzC,EAAA,IAAI,cAAA,KAAmBH,+BAAyB,EAAG;AACjD,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,OAAQ,cAAA,CAAe,KAAsC,gBAAgB,CAAA;AAC/E;;;;;;"}
@@ -20,6 +20,9 @@ function isD1Database(item) {
20
20
  function isAiBinding(item) {
21
21
  return item != null && isNotJSRPC(item) && typeof item.run === "function" && typeof item.gateway === "function" && typeof item.toMarkdown === "function";
22
22
  }
23
+ function isKVNamespace(item) {
24
+ return item != null && isNotJSRPC(item) && typeof item.get === "function" && typeof item.put === "function" && typeof item.list === "function" && typeof item.getWithMetadata === "function";
25
+ }
23
26
  function isR2Bucket(item) {
24
27
  return item != null && isNotJSRPC(item) && typeof item.head === "function" && typeof item.put === "function" && typeof item.createMultipartUpload === "function";
25
28
  }
@@ -28,6 +31,7 @@ exports.isAiBinding = isAiBinding;
28
31
  exports.isD1Database = isD1Database;
29
32
  exports.isDurableObjectNamespace = isDurableObjectNamespace;
30
33
  exports.isJSRPC = isJSRPC;
34
+ exports.isKVNamespace = isKVNamespace;
31
35
  exports.isQueue = isQueue;
32
36
  exports.isR2Bucket = isR2Bucket;
33
37
  //# sourceMappingURL=isBinding.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"isBinding.js","sources":["../../../../src/utils/isBinding.ts"],"sourcesContent":["/**\n * Adapted from https://github.com/evanderkoogh/otel-cf-workers/blob/effeb549f0a4ed1c55ea0c4f0d8e8e37e5494fb3/src/instrumentation/env.ts\n *\n * BSD 3-Clause License\n *\n * Copyright (c) 2023, Erwin van der Koogh\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport type { Ai, D1Database, DurableObjectNamespace, Queue, R2Bucket } from '@cloudflare/workers-types';\n\n/**\n * Checks if a value is a JSRPC proxy (service binding).\n *\n * JSRPC proxies return a truthy value for ANY property access, including\n * properties that don't exist. This makes other duck-type checks unreliable\n * unless we exclude JSRPC first.\n *\n * Must be checked before other binding type checks.\n */\nexport function isJSRPC(item: unknown): item is Service {\n try {\n return !!(item as Record<string, unknown>)[`__some_property_that_will_never_exist__${Math.random()}`];\n } catch {\n return false;\n }\n}\n\nconst isNotJSRPC = (item: unknown): item is Record<string, unknown> => !isJSRPC(item);\n\n/**\n * Duck-type check for DurableObjectNamespace bindings.\n * DurableObjectNamespace has `idFromName`, `idFromString`, `get`, `newUniqueId`.\n */\nexport function isDurableObjectNamespace(item: unknown): item is DurableObjectNamespace {\n return item != null && isNotJSRPC(item) && typeof item.idFromName === 'function';\n}\n\n/**\n * Duck-type check for Queue producer bindings.\n * Queue has `send` and `sendBatch` async methods.\n */\nexport function isQueue(item: unknown): item is Queue {\n return item != null && isNotJSRPC(item) && typeof item.send === 'function' && typeof item.sendBatch === 'function';\n}\n\n/**\n * Duck-type check for D1Database bindings.\n * D1Database has `prepare`, `batch`, and `exec` methods.\n */\nexport function isD1Database(item: unknown): item is D1Database {\n return (\n item != null &&\n isNotJSRPC(item) &&\n typeof item.prepare === 'function' &&\n typeof item.batch === 'function' &&\n typeof item.exec === 'function'\n );\n}\n\n/**\n * Duck-type check for Workers AI bindings.\n * The Ai binding has `run`, `gateway`, and `toMarkdown` methods.\n */\nexport function isAiBinding(item: unknown): item is Ai {\n return (\n item != null &&\n isNotJSRPC(item) &&\n typeof item.run === 'function' &&\n typeof item.gateway === 'function' &&\n typeof item.toMarkdown === 'function'\n );\n}\n\n/**\n * Duck-type check for R2 Bucket bindings.\n * R2Bucket has `head`, `put`, and `createMultipartUpload` methods.\n */\nexport function isR2Bucket(item: unknown): item is R2Bucket {\n return (\n item != null &&\n isNotJSRPC(item) &&\n typeof item.head === 'function' &&\n typeof item.put === 'function' &&\n typeof item.createMultipartUpload === 'function'\n );\n}\n"],"names":[],"mappings":";;AA4CO,SAAS,QAAQ,IAAA,EAAgC;AACtD,EAAA,IAAI;AACF,IAAA,OAAO,CAAC,CAAE,IAAA,CAAiC,0CAA0C,IAAA,CAAK,MAAA,EAAQ,CAAA,CAAE,CAAA;AAAA,EACtG,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF;AAEA,MAAM,UAAA,GAAa,CAAC,IAAA,KAAmD,CAAC,QAAQ,IAAI,CAAA;AAM7E,SAAS,yBAAyB,IAAA,EAA+C;AACtF,EAAA,OAAO,QAAQ,IAAA,IAAQ,UAAA,CAAW,IAAI,CAAA,IAAK,OAAO,KAAK,UAAA,KAAe,UAAA;AACxE;AAMO,SAAS,QAAQ,IAAA,EAA8B;AACpD,EAAA,OAAO,IAAA,IAAQ,IAAA,IAAQ,UAAA,CAAW,IAAI,CAAA,IAAK,OAAO,IAAA,CAAK,IAAA,KAAS,UAAA,IAAc,OAAO,IAAA,CAAK,SAAA,KAAc,UAAA;AAC1G;AAMO,SAAS,aAAa,IAAA,EAAmC;AAC9D,EAAA,OACE,IAAA,IAAQ,IAAA,IACR,UAAA,CAAW,IAAI,KACf,OAAO,IAAA,CAAK,OAAA,KAAY,UAAA,IACxB,OAAO,IAAA,CAAK,KAAA,KAAU,UAAA,IACtB,OAAO,KAAK,IAAA,KAAS,UAAA;AAEzB;AAMO,SAAS,YAAY,IAAA,EAA2B;AACrD,EAAA,OACE,IAAA,IAAQ,IAAA,IACR,UAAA,CAAW,IAAI,KACf,OAAO,IAAA,CAAK,GAAA,KAAQ,UAAA,IACpB,OAAO,IAAA,CAAK,OAAA,KAAY,UAAA,IACxB,OAAO,KAAK,UAAA,KAAe,UAAA;AAE/B;AAMO,SAAS,WAAW,IAAA,EAAiC;AAC1D,EAAA,OACE,IAAA,IAAQ,IAAA,IACR,UAAA,CAAW,IAAI,KACf,OAAO,IAAA,CAAK,IAAA,KAAS,UAAA,IACrB,OAAO,IAAA,CAAK,GAAA,KAAQ,UAAA,IACpB,OAAO,KAAK,qBAAA,KAA0B,UAAA;AAE1C;;;;;;;;;"}
1
+ {"version":3,"file":"isBinding.js","sources":["../../../../src/utils/isBinding.ts"],"sourcesContent":["/**\n * Adapted from https://github.com/evanderkoogh/otel-cf-workers/blob/effeb549f0a4ed1c55ea0c4f0d8e8e37e5494fb3/src/instrumentation/env.ts\n *\n * BSD 3-Clause License\n *\n * Copyright (c) 2023, Erwin van der Koogh\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport type { Ai, D1Database, DurableObjectNamespace, KVNamespace, Queue, R2Bucket } from '@cloudflare/workers-types';\n\n/**\n * Checks if a value is a JSRPC proxy (service binding).\n *\n * JSRPC proxies return a truthy value for ANY property access, including\n * properties that don't exist. This makes other duck-type checks unreliable\n * unless we exclude JSRPC first.\n *\n * Must be checked before other binding type checks.\n */\nexport function isJSRPC(item: unknown): item is Service {\n try {\n return !!(item as Record<string, unknown>)[`__some_property_that_will_never_exist__${Math.random()}`];\n } catch {\n return false;\n }\n}\n\nconst isNotJSRPC = (item: unknown): item is Record<string, unknown> => !isJSRPC(item);\n\n/**\n * Duck-type check for DurableObjectNamespace bindings.\n * DurableObjectNamespace has `idFromName`, `idFromString`, `get`, `newUniqueId`.\n */\nexport function isDurableObjectNamespace(item: unknown): item is DurableObjectNamespace {\n return item != null && isNotJSRPC(item) && typeof item.idFromName === 'function';\n}\n\n/**\n * Duck-type check for Queue producer bindings.\n * Queue has `send` and `sendBatch` async methods.\n */\nexport function isQueue(item: unknown): item is Queue {\n return item != null && isNotJSRPC(item) && typeof item.send === 'function' && typeof item.sendBatch === 'function';\n}\n\n/**\n * Duck-type check for D1Database bindings.\n * D1Database has `prepare`, `batch`, and `exec` methods.\n */\nexport function isD1Database(item: unknown): item is D1Database {\n return (\n item != null &&\n isNotJSRPC(item) &&\n typeof item.prepare === 'function' &&\n typeof item.batch === 'function' &&\n typeof item.exec === 'function'\n );\n}\n\n/**\n * Duck-type check for Workers AI bindings.\n * The Ai binding has `run`, `gateway`, and `toMarkdown` methods.\n */\nexport function isAiBinding(item: unknown): item is Ai {\n return (\n item != null &&\n isNotJSRPC(item) &&\n typeof item.run === 'function' &&\n typeof item.gateway === 'function' &&\n typeof item.toMarkdown === 'function'\n );\n}\n\n/**\n * Duck-type check for Workers KV namespace bindings.\n * KVNamespace has `get`, `put`, `list`, and `getWithMetadata` methods.\n */\nexport function isKVNamespace(item: unknown): item is KVNamespace {\n return (\n item != null &&\n isNotJSRPC(item) &&\n typeof item.get === 'function' &&\n typeof item.put === 'function' &&\n typeof item.list === 'function' &&\n typeof item.getWithMetadata === 'function'\n );\n}\n\n/**\n * Duck-type check for R2 Bucket bindings.\n * R2Bucket has `head`, `put`, and `createMultipartUpload` methods.\n */\nexport function isR2Bucket(item: unknown): item is R2Bucket {\n return (\n item != null &&\n isNotJSRPC(item) &&\n typeof item.head === 'function' &&\n typeof item.put === 'function' &&\n typeof item.createMultipartUpload === 'function'\n );\n}\n"],"names":[],"mappings":";;AA4CO,SAAS,QAAQ,IAAA,EAAgC;AACtD,EAAA,IAAI;AACF,IAAA,OAAO,CAAC,CAAE,IAAA,CAAiC,0CAA0C,IAAA,CAAK,MAAA,EAAQ,CAAA,CAAE,CAAA;AAAA,EACtG,CAAA,CAAA,MAAQ;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,IAAA,KAAS,UAAA,IACrB,OAAO,IAAA,CAAK,GAAA,KAAQ,UAAA,IACpB,OAAO,KAAK,qBAAA,KAA0B,UAAA;AAE1C;;;;;;;;;;"}
@@ -136,13 +136,53 @@ function wrapDefaultExport(node, ctx, state) {
136
136
  return;
137
137
  }
138
138
  }
139
- state.ms.overwrite(node.start, decl.start, "const __SENTRY_DEFAULT_EXPORT__ = ");
139
+ const source = state.ms.original;
140
+ const keywordsEnd = exportDefaultKeywordsEnd(source, node.start);
141
+ const declaredName = decl.type === "ClassDeclaration" || decl.type === "FunctionDeclaration" ? decl.id?.name : void 0;
142
+ let wrapped = "__SENTRY_DEFAULT_EXPORT__";
143
+ if (declaredName) {
144
+ state.ms.remove(node.start, decl.start);
145
+ state.ms.appendLeft(node.end, `
146
+ var __SENTRY_DEFAULT_EXPORT__ = ${declaredName};`);
147
+ wrapped = declaredName;
148
+ } else if (isAnonymousFunctionOrClass(decl)) {
149
+ const hasSemicolon = source[node.end - 1] === ";";
150
+ state.ms.overwrite(node.start, keywordsEnd, "var __SENTRY_DEFAULT_EXPORT__ = { default:");
151
+ state.ms.appendLeft(hasSemicolon ? node.end - 1 : node.end, hasSemicolon ? " }.default" : " }.default;");
152
+ } else {
153
+ state.ms.overwrite(node.start, keywordsEnd, "var __SENTRY_DEFAULT_EXPORT__ =");
154
+ }
155
+ state.ms.appendLeft(node.end, "\nexport { __SENTRY_DEFAULT_EXPORT__ as default };");
140
156
  state.ms.append(`
141
- export default __SENTRY__.withSentry(${state.optionsFn}, __SENTRY_DEFAULT_EXPORT__);
142
- `);
157
+ __SENTRY_DEFAULT_EXPORT__ = __SENTRY__.withSentry(${state.optionsFn}, ${wrapped});`);
143
158
  state.needsImport = true;
144
159
  state.autoWrapped.add(wranglerConfig.DEFAULT_EXPORT);
145
160
  }
161
+ function exportDefaultKeywordsEnd(source, start) {
162
+ let index = start + "export".length;
163
+ while (index < source.length && !source.startsWith("default", index)) {
164
+ if (source.startsWith("//", index)) {
165
+ const lineEnd = source.indexOf("\n", index);
166
+ index = lineEnd === -1 ? source.length : lineEnd;
167
+ } else if (source.startsWith("/*", index)) {
168
+ const commentEnd = source.indexOf("*/", index + 2);
169
+ index = commentEnd === -1 ? source.length : commentEnd + 2;
170
+ } else {
171
+ index++;
172
+ }
173
+ }
174
+ return index + "default".length;
175
+ }
176
+ function isAnonymousFunctionOrClass(node) {
177
+ if (node.type === "ArrowFunctionExpression") return true;
178
+ const isFunctionOrClass = [
179
+ "FunctionExpression",
180
+ "FunctionDeclaration",
181
+ "ClassExpression",
182
+ "ClassDeclaration"
183
+ ].includes(node.type);
184
+ return isFunctionOrClass && !node.id;
185
+ }
146
186
  function handleNamedExport(node, ctx, state) {
147
187
  const decl = node.declaration;
148
188
  if (decl?.type === "VariableDeclaration") {
@@ -235,13 +275,24 @@ ${declaringStatement ? "" : "var "}__SENTRY_DEFAULT_EXPORT__ = __SENTRY__.withSe
235
275
  state.autoWrapped.add(wranglerConfig.DEFAULT_EXPORT);
236
276
  return "__SENTRY_DEFAULT_EXPORT__ as default";
237
277
  }
278
+ function wrapDefaultReexport(localName, sourceLiteral, state, prelude) {
279
+ const target = "__SENTRY_REEXPORT_default__";
280
+ prelude.push(
281
+ localName === DEFAULT_IMPORT ? `import ${target} from ${sourceLiteral};` : `import { ${localName} as ${target} } from ${sourceLiteral};`,
282
+ `var __SENTRY_DEFAULT_EXPORT__ = __SENTRY__._INTERNAL_wrapUnlessInstrumented(__SENTRY__.withSentry, ${state.optionsFn}, ${target});`
283
+ );
284
+ state.needsImport = true;
285
+ state.autoWrapped.add(wranglerConfig.DEFAULT_EXPORT);
286
+ return "__SENTRY_DEFAULT_EXPORT__ as default";
287
+ }
238
288
  function wrapSpecifier(specifier, sourceLiteral, ctx, state, prelude) {
239
289
  const exportedName = specifier.type === "ExportSpecifier" && specifier.exported?.type === "Identifier" ? specifier.exported.name : void 0;
240
290
  const localName = specifier.local?.type === "Identifier" ? specifier.local.name : void 0;
241
291
  const kind = exportedName ? resolveWrapperKind(exportedName, sourceLiteral ? void 0 : localName, state) : void 0;
242
292
  if (!exportedName || !localName) return void 0;
243
293
  if (!kind) {
244
- return exportedName === DEFAULT_IMPORT && !sourceLiteral ? wrapDefaultSpecifier(localName, state) : void 0;
294
+ if (exportedName !== DEFAULT_IMPORT) return void 0;
295
+ return sourceLiteral ? wrapDefaultReexport(localName, sourceLiteral, state, prelude) : wrapDefaultSpecifier(localName, state);
245
296
  }
246
297
  if (!sourceLiteral) {
247
298
  const localClass = state.topLevelClasses.get(localName);
@@ -1 +1 @@
1
- {"version":3,"file":"transform.js","sources":["../../../../src/vite/transform.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport MagicString from 'magic-string';\nimport { DEFAULT_EXPORT, type ExportName, type SameWorkerBinding } from './wranglerConfig';\nimport { detectWorkerEntrypointClasses } from './workerEntrypoint';\n\nconst MERGED_OPTIONS_IDENTIFIER = '__SENTRY_OPTIONS__';\n\n// ---------------------------------------------------------------------------\n// Minimal ESTree node types for the AST nodes we inspect.\n// ---------------------------------------------------------------------------\n\nexport interface BaseNode {\n type: string;\n start: number;\n end: number;\n}\n\nexport interface ProgramBody {\n body: BaseNode[];\n}\n\ninterface IdentifierNode extends BaseNode {\n name: string;\n}\n\ninterface CalleeNode {\n type: string;\n name?: string;\n property?: { type: string; name?: string };\n}\n\ninterface CallExpressionNode extends BaseNode {\n callee?: CalleeNode;\n}\n\ninterface ClassDeclarationNode extends BaseNode {\n id?: IdentifierNode | null;\n}\n\ninterface ExportDefaultNode extends BaseNode {\n declaration: BaseNode;\n}\n\ninterface ExportSpecifierNode extends BaseNode {\n local?: { type: string; name?: string };\n exported?: { type: string; name?: string };\n}\n\ninterface ExportNamedNode extends BaseNode {\n declaration?: BaseNode | null;\n source?: BaseNode | null;\n specifiers?: ExportSpecifierNode[];\n}\n\ninterface VariableDeclaratorNode {\n id?: { type: string; name?: string };\n init?: BaseNode | null;\n}\n\ninterface VariableDeclarationNode extends BaseNode {\n declarations?: VariableDeclaratorNode[];\n}\n\ninterface ImportDeclarationNode extends BaseNode {\n specifiers?: Array<{ local?: { type: string; name?: string } }>;\n}\n\nfunction isCallToMethod(node: BaseNode, methodName: string): boolean {\n if (node.type !== 'CallExpression') return false;\n const callee = (node as CallExpressionNode).callee;\n if (!callee) return false;\n if (callee.type === 'Identifier' && callee.name === methodName) return true;\n return (\n callee.type === 'MemberExpression' && callee.property?.type === 'Identifier' && callee.property.name === methodName\n );\n}\n\n/**\n * The kind of Sentry wrapper to apply to an exported class.\n *\n * `durableObject` and `workflow` are keyed by name from the wrangler config\n * (`durable_objects.bindings`, `workflows`), since those class names are\n * authoritative there. `workerEntrypoint` is different: a worker's own\n * entrypoints aren't enumerated in its config, so they're detected structurally\n * (a class extending `WorkerEntrypoint` from `cloudflare:workers`), with the\n * config providing only a fallback for self-bound entrypoints whose base class\n * lives in another module.\n */\nexport type ClassWrapperKind = 'durableObject' | 'agent' | 'workflow' | 'workerEntrypoint';\n\n/** Specifier name a `export { default as X } from '...'` re-export uses for the source's default. */\nconst DEFAULT_IMPORT = 'default';\n\n/**\n * The `@sentry/cloudflare` helper each wrapper kind emits. All share the same\n * `(optionsCallback, Class)` signature. `WorkerEntrypoint` classes use\n * `withSentry`, which runtime-detects the class type and routes accordingly.\n */\nconst WRAPPER_METHODS: Record<ClassWrapperKind, string> = {\n durableObject: 'instrumentDurableObjectWithSentry',\n agent: 'instrumentAgentWithSentry',\n workflow: 'instrumentWorkflowWithSentry',\n workerEntrypoint: 'withSentry',\n};\n\nexport interface TransformContext {\n /**\n * Exported class name → the kind of Sentry wrapper to apply. Populated from\n * the wrangler config, so the transform can wrap by name without resolving\n * each class's base type.\n */\n classWrappers: Map<string, ClassWrapperKind>;\n /**\n * Local class names detected as `agents` Agents. An Agent is configured as a Durable Object in\n * wrangler, so this upgrades those entries from `durableObject` to `agent`.\n */\n agentClasses?: ReadonlySet<string>;\n optionsFn: string;\n /** Import statement prepended when `optionsFn` references a separate module. */\n optionsImport?: string;\n /** Module the generated code imports `withSentry` and the class wrappers from. Defaults to `@sentry/cloudflare`. */\n sentryModule?: string;\n /** @see {@link import('./wranglerConfig').WranglerConfig.sameWorkerBindings} */\n sameWorkerBindings?: readonly SameWorkerBinding[];\n}\n\nexport interface TransformResult {\n code: string;\n map: ReturnType<MagicString['generateMap']>;\n /**\n * The configured class names that were actually wrapped. Lets the plugin warn\n * about configured classes it could not find, instead of silently leaving\n * them uninstrumented.\n */\n wrappedClasses: Set<string>;\n}\n\n/**\n * Rewrite the worker entry source to wrap its default export with `withSentry`\n * and any configured class export with its matching Sentry wrapper (see\n * {@link TransformContext.classWrappers}, e.g. Durable Object classes with\n * `instrumentDurableObjectWithSentry`).\n *\n * Handles `export class MyDO {}`, the specifier form (`class MyDO {}` …\n * `export { MyDO }` / `export { Foo as MyDO }`), and classes that live in\n * another module (`import { MyDO } from './do'; export { MyDO }` or\n * `export { MyDO } from './do'`). Only star re-exports (`export * from './do'`)\n * are left alone — the plugin warns about those via\n * {@link TransformResult.wrappedClasses}.\n *\n * Exported (rather than inlined into the plugin) so it can be unit-tested with a\n * plain AST and no Vite context. Returns `undefined` when nothing was wrapped and\n * there are no already-manually-wrapped classes to report.\n */\nexport function applyAutoInstrumentTransforms(\n code: string,\n ast: ProgramBody,\n ctx: TransformContext,\n): TransformResult | undefined {\n const ms = new MagicString(code);\n const topLevelClasses = collectTopLevelClasses(ast);\n const sameWorkerBindings = ctx.sameWorkerBindings ?? [];\n const state: TransformState = {\n ms,\n needsImport: false,\n wrappedClasses: new Set<string>(),\n topLevelClasses,\n wrappedLocals: new Map<string, string>(),\n classWrappers: ctx.classWrappers,\n agentClasses: ctx.agentClasses ?? new Set<string>(),\n workerEntrypointClasses: detectWorkerEntrypointClasses(ast),\n // The identifier must be chosen before wrapping, which bindings survive is only known after.\n optionsFn: sameWorkerBindings.length > 0 ? MERGED_OPTIONS_IDENTIFIER : ctx.optionsFn,\n autoWrapped: new Set<ExportName>(),\n manuallyWrappedLocals: collectManuallyWrappedLocals(ast),\n declaringStatements: collectDeclaringStatements(ast),\n };\n const { wrappedClasses } = state;\n\n // Named exports first, regardless of source order: the default-export handler\n // needs to know which local bindings a named export already wrapped, so it can\n // skip a class that is both exported by name and re-exported as default (which\n // would otherwise wrap it twice).\n for (const node of ast.body) {\n if (node.type === 'ExportNamedDeclaration') {\n handleNamedExport(node, ctx, state);\n }\n }\n for (const node of ast.body) {\n if (node.type === 'ExportDefaultDeclaration') {\n wrapDefaultExport(node as ExportDefaultNode, ctx, state);\n }\n }\n\n if (!state.needsImport) {\n // Nothing was rewritten. Still surface any classes found already wrapped\n // manually (via `wrappedClasses`) so the caller doesn't warn about them;\n // return undefined only when there was nothing to report either.\n if (wrappedClasses.size === 0) return undefined;\n return { code, map: ms.generateMap({ hires: true }), wrappedClasses };\n }\n\n // `prepend` inserts before earlier prepends, yielding: Sentry import, options import, declaration.\n if (sameWorkerBindings.length > 0) {\n ms.prepend(buildMergedOptionsDeclaration(sameWorkerBindings, ctx.optionsFn, state));\n }\n if (ctx.optionsImport) ms.prepend(ctx.optionsImport);\n ms.prepend(`import * as __SENTRY__ from '${ctx.sentryModule ?? '@sentry/cloudflare'}';\\n`);\n\n return {\n code: ms.toString(),\n map: ms.generateMap({ hires: true }),\n wrappedClasses,\n };\n}\n\ninterface TransformState {\n ms: MagicString;\n needsImport: boolean;\n wrappedClasses: Set<string>;\n /**\n * Top-level class declarations, exported or not, so specifier exports like\n * `export { MyDO }` can locate the class they refer to.\n */\n topLevelClasses: Map<string, ClassDeclarationNode>;\n /**\n * Local class name → the binding holding its wrapper, so two exports of the same class share one\n * wrapper and a default export of it can be re-pointed.\n */\n wrappedLocals: Map<string, string>;\n /** Class name → wrapper kind, keyed by the *exported* name (from config). */\n classWrappers: Map<string, ClassWrapperKind>;\n /** Local class names detected as `agents` Agents (see {@link TransformContext.agentClasses}). */\n agentClasses: ReadonlySet<string>;\n /**\n * Local class names detected as `WorkerEntrypoint` subclasses in this module,\n * so they can be wrapped without a config entry.\n */\n workerEntrypointClasses: Set<string>;\n optionsFn: string;\n /**\n * Export names wrapped by this transform, so their options can be extended with\n * `rpcTracePropagationBindings`. Hand-wrapped exports stay out, they keep the options they were\n * wrapped with. `wrappedClasses` counts both.\n */\n autoWrapped: Set<ExportName>;\n /**\n * Top-level bindings already assigned an `instrument*WithSentry(...)` result\n * (`const MyDO = instrumentDurableObjectWithSentry(...)`). Exporting one by\n * specifier must report it as wrapped rather than wrap it a second time.\n */\n manuallyWrappedLocals: Set<string>;\n /** Top-level binding name → the statement that declares it. */\n declaringStatements: Map<string, BaseNode>;\n}\n\n/**\n * Builds the callback that merges same-worker binding names into `rpcTracePropagationBindings` at\n * runtime, the options object only exists once the callback runs with `env`. Only bindings whose\n * class this transform wrapped survive, a hand-wrapped class runs on its own options.\n */\nfunction buildMergedOptionsDeclaration(\n sameWorkerBindings: readonly SameWorkerBinding[],\n optionsFn: string,\n state: TransformState,\n): string {\n const bindingNames = sameWorkerBindings\n .filter(({ className }) => state.autoWrapped.has(className))\n .map(({ bindingName }) => bindingName);\n\n if (!bindingNames.length) {\n return `const ${MERGED_OPTIONS_IDENTIFIER} = ${optionsFn};\\n`;\n }\n\n const names = bindingNames.map(name => JSON.stringify(name)).join(', ');\n return (\n `const ${MERGED_OPTIONS_IDENTIFIER} = (env) => { ` +\n `const opts = (${optionsFn})(env); ` +\n `return { ...opts, rpcTracePropagationBindings: [${names}, ...(opts?.rpcTracePropagationBindings ?? [])] }; };\\n`\n );\n}\n\n/**\n * Resolve the wrapper kind for a class export.\n *\n * Config (`classWrappers`) wins — it's authoritative for Durable Objects and\n * Workflows, and provides the self-binding fallback for WorkerEntrypoints whose\n * base class this module can't see. Otherwise a structurally-detected\n * `WorkerEntrypoint` subclass (matched by its *local* name) gets wrapped with\n * `withSentry`.\n *\n * `localName` is the binding **in this module** the export refers to, and must be\n * left undefined for `export { X } from '...'`: there the specifier's name belongs\n * to the source module, so matching it against anything detected here would wrap a\n * class that merely shares a name.\n *\n * The one case where config is refined rather than obeyed is an `agents` Agent:\n * it *is* a Durable Object, so wrangler can only ever describe it as one, and\n * only the detected base chain distinguishes the two.\n */\nfunction resolveWrapperKind(\n exportedName: string,\n localName: string | undefined,\n state: TransformState,\n): ClassWrapperKind | undefined {\n const configured = state.classWrappers.get(exportedName);\n\n if (\n configured === 'durableObject' &&\n ((localName && state.agentClasses.has(localName)) || state.agentClasses.has(exportedName))\n ) {\n return 'agent';\n }\n\n if (configured) return configured;\n if (localName && state.workerEntrypointClasses.has(localName)) return 'workerEntrypoint';\n return undefined;\n}\n\n/**\n * Top-level `const X = instrument*WithSentry(...)` bindings — a hand-wrapped class that is exported\n * separately (`export { X }`) rather than inline.\n */\nfunction collectManuallyWrappedLocals(ast: ProgramBody): Set<string> {\n const wrapperMethods = Object.values(WRAPPER_METHODS);\n const locals = new Set<string>();\n\n for (const node of ast.body) {\n const declaration = declarationOf(node);\n if (declaration?.type !== 'VariableDeclaration') continue;\n for (const declarator of (declaration as VariableDeclarationNode).declarations ?? []) {\n const name = declarator.id?.type === 'Identifier' ? declarator.id.name : undefined;\n const init = declarator.init;\n if (name && init && wrapperMethods.some(method => isCallToMethod(init, method))) {\n locals.add(name);\n }\n }\n }\n\n return locals;\n}\n\nfunction collectDeclaringStatements(ast: ProgramBody): Map<string, BaseNode> {\n const statements = new Map<string, BaseNode>();\n for (const node of ast.body) {\n const declaration = declarationOf(node);\n if (!declaration) continue;\n const ids =\n declaration.type === 'VariableDeclaration'\n ? ((declaration as VariableDeclarationNode).declarations ?? []).map(declarator => declarator.id)\n : declaration.type === 'ImportDeclaration'\n ? ((declaration as ImportDeclarationNode).specifiers ?? []).map(specifier => specifier.local)\n : [(declaration as ClassDeclarationNode).id];\n for (const id of ids) {\n if (id?.type === 'Identifier' && id.name) statements.set(id.name, node);\n }\n }\n return statements;\n}\n\nfunction collectTopLevelClasses(ast: ProgramBody): Map<string, ClassDeclarationNode> {\n const classes = new Map<string, ClassDeclarationNode>();\n for (const node of ast.body) {\n const declaration = declarationOf(node);\n if (declaration?.type !== 'ClassDeclaration') continue;\n const classNode = declaration as ClassDeclarationNode;\n if (classNode.id?.name) classes.set(classNode.id.name, classNode);\n }\n return classes;\n}\n\n/** The declaration a top-level statement makes, looking through `export` (`export const x = ...`). */\nfunction declarationOf(node: BaseNode): BaseNode | null | undefined {\n return node.type === 'ExportNamedDeclaration' ? (node as ExportNamedNode).declaration : node;\n}\n\nfunction wrapDefaultExport(node: ExportDefaultNode, ctx: TransformContext, state: TransformState): void {\n const decl = node.declaration;\n\n // Already wrapped — leave it alone\n if (isCallToMethod(decl, 'withSentry')) return;\n\n // `export default Foo` where `Foo` is a local class already wrapped by a named\n // export (e.g. a self-bound WorkerEntrypoint also used as the default handler).\n // Wrapping again would produce `withSentry(withSentry(...))`, so the default\n // export is re-pointed at the wrapper binding the named export created.\n if (decl.type === 'Identifier') {\n const wrappedName = state.wrappedLocals.get((decl as IdentifierNode).name);\n if (wrappedName) {\n state.ms.overwrite(decl.start, decl.end, wrappedName);\n state.autoWrapped.add(DEFAULT_EXPORT);\n return;\n }\n }\n\n // `export default <expr>` → `const __SENTRY_DEFAULT_EXPORT__ = <expr>`\n // MagicString positions are always relative to the original source.\n state.ms.overwrite(node.start, decl.start, 'const __SENTRY_DEFAULT_EXPORT__ = ');\n state.ms.append(`\\nexport default __SENTRY__.withSentry(${state.optionsFn}, __SENTRY_DEFAULT_EXPORT__);\\n`);\n state.needsImport = true;\n state.autoWrapped.add(DEFAULT_EXPORT);\n}\n\nfunction handleNamedExport(node: ExportNamedNode, ctx: TransformContext, state: TransformState): void {\n const decl = node.declaration;\n\n // ---- Manually wrapped class export ----\n // `export const MyDO = instrumentDurableObjectWithSentry(...)` — count it\n // as wrapped so the plugin doesn't warn about it, but leave it alone.\n if (decl?.type === 'VariableDeclaration') {\n collectManuallyWrappedClassExports(decl, ctx, state);\n return;\n }\n\n // ---- Named class export matching a configured binding ----\n if (decl?.type === 'ClassDeclaration') {\n wrapInlineClassExport(node, decl, ctx, state);\n return;\n }\n\n // ---- Specifier export (`export { Foo as MyDO }`, `export { MyDO } from './do'`) ----\n wrapSpecifierExports(node, ctx, state);\n}\n\nfunction collectManuallyWrappedClassExports(\n varDecl: VariableDeclarationNode,\n ctx: TransformContext,\n state: TransformState,\n): void {\n for (const declarator of varDecl.declarations ?? []) {\n const name = declarator.id?.type === 'Identifier' ? declarator.id.name : undefined;\n const kind = name ? ctx.classWrappers.get(name) : undefined;\n if (!name || !kind || !declarator.init) continue;\n\n // A hand-wrapped Agent is configured as a Durable Object, so accept either helper there —\n // otherwise an already-instrumented Agent would be reported as unwrapped.\n const accepted =\n kind === 'durableObject' ? [WRAPPER_METHODS.durableObject, WRAPPER_METHODS.agent] : [WRAPPER_METHODS[kind]];\n\n if (accepted.some(method => isCallToMethod(declarator.init as BaseNode, method))) {\n state.wrappedClasses.add(name);\n }\n }\n}\n\nfunction wrapInlineClassExport(\n exportNode: ExportNamedNode,\n classDecl: ClassDeclarationNode,\n ctx: TransformContext,\n state: TransformState,\n): void {\n const classId = classDecl.id;\n // Inline export: the exported name and the local class name are the same.\n const kind = classId ? resolveWrapperKind(classId.name, classId.name, state) : undefined;\n if (!classId || !kind) return;\n\n const className = classId.name;\n\n // Strip the `export ` keyword\n state.ms.overwrite(exportNode.start, classDecl.start, '');\n\n const wrappedName = wrapLocalClass(className, classDecl, kind, state);\n state.ms.appendLeft(exportNode.end, `export { ${wrappedName} as ${className} };\\n`);\n\n state.wrappedClasses.add(className);\n state.autoWrapped.add(className);\n}\n\n/**\n * Wrap a class declared in this module and return the binding that holds the wrapper.\n *\n * The declaration is left exactly as written. Only the *export* has to become the wrapper, so the\n * wrapper gets its own binding and the export is aliased to it, the same shape as the documented\n * manual `instrument*WithSentry` pattern and the cross-module re-export path below. Renaming the\n * declaration instead (`class __SENTRY_ORIGINAL_MyAgent__`) would also rename what the class reports\n * as `Function.prototype.name`, which libraries read to identify the user's class: `@cloudflare/think`\n * hands `this.constructor.name` to the AI SDK as the telemetry `functionId`, and that surfaced as a\n * `gen_ai.invoke_agent __SENTRY_ORIGINAL_MyAgent__` span.\n */\nfunction wrapLocalClass(\n localName: string,\n localClass: ClassDeclarationNode,\n kind: ClassWrapperKind,\n state: TransformState,\n): string {\n const existing = state.wrappedLocals.get(localName);\n if (existing) return existing;\n\n const wrappedName = `__SENTRY_WRAPPED_${localName}__`;\n state.wrappedLocals.set(localName, wrappedName);\n state.ms.appendLeft(\n localClass.end,\n `\\nconst ${wrappedName} = __SENTRY__.${WRAPPER_METHODS[kind]}(${state.optionsFn}, ${localName});\\n`,\n );\n state.needsImport = true;\n return wrappedName;\n}\n\n/**\n * Wrap the configured classes an `export { ... }` statement names.\n *\n * Each such specifier is re-pointed at a binding holding the wrapper, which means rebuilding the\n * statement; specifiers this plugin has no business touching are carried over verbatim. For a class\n * declared in this module the wrapper binding follows the declaration (see {@link wrapLocalClass}).\n * A class that lives in **another** module — imported and re-exported, or re-exported directly — is\n * first bound under a private name, since an import binding cannot be reassigned and the `from` form\n * has no local binding at all.\n */\nfunction wrapSpecifierExports(node: ExportNamedNode, ctx: TransformContext, state: TransformState): void {\n const specifiers = node.specifiers ?? [];\n if (specifiers.length === 0) return;\n\n const sourceLiteral = node.source ? state.ms.original.slice(node.source.start, node.source.end) : undefined;\n\n const prelude: string[] = [];\n const wrappedPairs: string[] = [];\n const kept: string[] = [];\n\n for (const specifier of specifiers) {\n const pair = wrapSpecifier(specifier, sourceLiteral, ctx, state, prelude);\n if (pair) {\n wrappedPairs.push(pair);\n } else {\n kept.push(state.ms.original.slice(specifier.start, specifier.end));\n }\n }\n\n if (wrappedPairs.length === 0) return;\n\n const statements = [...prelude, `export { ${wrappedPairs.join(', ')} };`];\n if (kept.length > 0) {\n const clause = `export { ${kept.join(', ')} }`;\n statements.push(sourceLiteral ? `${clause} from ${sourceLiteral};` : `${clause};`);\n }\n state.ms.overwrite(node.start, node.end, statements.join('\\n'));\n}\n\n/**\n * `export { handler as default }`, the form bundlers emit for a default export. The export is set\n * in two steps. Right after `handler` is declared, it is bound to `handler` as-is, so a circular\n * import that reads it during module evaluation gets the handler, as before the transform. At the\n * end of the module, it is rebound to the wrapper, so a handler assigned or given methods later is\n * wrapped as it ends up. The binding is a `var`: a read before `handler` is declared gets\n * `undefined`, as it would from the bundler's own `var`, where a `const` would throw and stop the\n * Worker from starting.\n */\nfunction wrapDefaultSpecifier(localName: string, state: TransformState): string | undefined {\n if (state.manuallyWrappedLocals.has(localName)) return undefined;\n\n // Same as `export default Foo`: re-point at the wrapper a named export already made.\n const wrappedName = state.wrappedLocals.get(localName);\n if (wrappedName) {\n state.autoWrapped.add(DEFAULT_EXPORT);\n return `${wrappedName} as default`;\n }\n\n const declaringStatement = state.declaringStatements.get(localName);\n if (declaringStatement) {\n state.ms.appendLeft(declaringStatement.end, `\\nvar __SENTRY_DEFAULT_EXPORT__ = ${localName};`);\n }\n state.ms.append(\n `\\n${declaringStatement ? '' : 'var '}__SENTRY_DEFAULT_EXPORT__ = __SENTRY__.withSentry(${state.optionsFn}, ${localName});`,\n );\n state.needsImport = true;\n state.autoWrapped.add(DEFAULT_EXPORT);\n return '__SENTRY_DEFAULT_EXPORT__ as default';\n}\n\n/**\n * Handle one export specifier, returning the `Wrapped as Exported` pair to emit for a class that\n * gets wrapped. The import/wrapper statements a cross-module pair depends on are pushed onto\n * `prelude`; a local class's wrapper binding is emitted after its declaration instead.\n *\n * Returns `undefined` when the specifier can stay exactly as written: it doesn't name a configured\n * class, or the binding is already hand-wrapped.\n */\nfunction wrapSpecifier(\n specifier: ExportSpecifierNode,\n sourceLiteral: string | undefined,\n ctx: TransformContext,\n state: TransformState,\n prelude: string[],\n): string | undefined {\n const exportedName =\n specifier.type === 'ExportSpecifier' && specifier.exported?.type === 'Identifier'\n ? specifier.exported.name\n : undefined;\n const localName = specifier.local?.type === 'Identifier' ? specifier.local.name : undefined;\n // With a `from` clause the specifier names an export of the *source* module, not a binding here.\n const kind = exportedName\n ? resolveWrapperKind(exportedName, sourceLiteral ? undefined : localName, state)\n : undefined;\n\n if (!exportedName || !localName) return undefined;\n if (!kind) {\n return exportedName === DEFAULT_IMPORT && !sourceLiteral ? wrapDefaultSpecifier(localName, state) : undefined;\n }\n\n // Without a `from` clause the specifier points at a module-local binding.\n if (!sourceLiteral) {\n const localClass = state.topLevelClasses.get(localName);\n\n if (localClass?.id) {\n const wrappedName = wrapLocalClass(localName, localClass, kind, state);\n state.wrappedClasses.add(exportedName);\n return `${wrappedName} as ${exportedName}`;\n }\n\n if (state.manuallyWrappedLocals.has(localName)) {\n state.wrappedClasses.add(exportedName);\n return undefined;\n }\n }\n\n // The class comes from another module: bind it under a private name (for the `from` form, which\n // has no local binding at all), wrap that, and export the wrapper under the configured name.\n let target = localName;\n\n if (sourceLiteral) {\n target = `__SENTRY_REEXPORT_${exportedName}__`;\n prelude.push(\n localName === DEFAULT_IMPORT\n ? `import ${target} from ${sourceLiteral};`\n : `import { ${localName} as ${target} } from ${sourceLiteral};`,\n );\n }\n\n const wrappedName = `__SENTRY_WRAPPED_${exportedName}__`;\n\n // The class may already be hand-wrapped in its own module, which this transform cannot see. The\n // emitted guard returns such a class as-is instead of nesting a second wrapper around it.\n prelude.push(\n `const ${wrappedName} = __SENTRY__._INTERNAL_wrapUnlessInstrumented(__SENTRY__.${WRAPPER_METHODS[kind]}, ${state.optionsFn}, ${target});`,\n );\n state.wrappedClasses.add(exportedName);\n state.autoWrapped.add(exportedName);\n state.needsImport = true;\n\n return `${wrappedName} as ${exportedName}`;\n}\n"],"names":["MagicString","detectWorkerEntrypointClasses","DEFAULT_EXPORT","wrappedName"],"mappings":";;;;;;AAKA,MAAM,yBAAA,GAA4B,oBAAA;AA8DlC,SAAS,cAAA,CAAe,MAAgB,UAAA,EAA6B;AACnE,EAAA,IAAI,IAAA,CAAK,IAAA,KAAS,gBAAA,EAAkB,OAAO,KAAA;AAC3C,EAAA,MAAM,SAAU,IAAA,CAA4B,MAAA;AAC5C,EAAA,IAAI,CAAC,QAAQ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,MAAA,OAAO,CAAA,EAAGA,YAAW,CAAA,IAAA,EAAO,YAAY,CAAA,CAAA;AAAA,IAC1C;AAEA,IAAA,IAAI,KAAA,CAAM,qBAAA,CAAsB,GAAA,CAAI,SAAS,CAAA,EAAG;AAC9C,MAAA,KAAA,CAAM,cAAA,CAAe,IAAI,YAAY,CAAA;AACrC,MAAA,OAAO,MAAA;AAAA,IACT;AAAA,EACF;AAIA,EAAA,IAAI,MAAA,GAAS,SAAA;AAEb,EAAA,IAAI,aAAA,EAAe;AACjB,IAAA,MAAA,GAAS,qBAAqB,YAAY,CAAA,EAAA,CAAA;AAC1C,IAAA,OAAA,CAAQ,IAAA;AAAA,MACN,SAAA,KAAc,cAAA,GACV,CAAA,OAAA,EAAU,MAAM,CAAA,MAAA,EAAS,aAAa,CAAA,CAAA,CAAA,GACtC,CAAA,SAAA,EAAY,SAAS,CAAA,IAAA,EAAO,MAAM,CAAA,QAAA,EAAW,aAAa,CAAA,CAAA;AAAA,KAChE;AAAA,EACF;AAEA,EAAA,MAAM,WAAA,GAAc,oBAAoB,YAAY,CAAA,EAAA,CAAA;AAIpD,EAAA,OAAA,CAAQ,IAAA;AAAA,IACN,CAAA,MAAA,EAAS,WAAW,CAAA,0DAAA,EAA6D,eAAA,CAAgB,IAAI,CAAC,CAAA,EAAA,EAAK,KAAA,CAAM,SAAS,CAAA,EAAA,EAAK,MAAM,CAAA,EAAA;AAAA,GACvI;AACA,EAAA,KAAA,CAAM,cAAA,CAAe,IAAI,YAAY,CAAA;AACrC,EAAA,KAAA,CAAM,WAAA,CAAY,IAAI,YAAY,CAAA;AAClC,EAAA,KAAA,CAAM,WAAA,GAAc,IAAA;AAEpB,EAAA,OAAO,CAAA,EAAG,WAAW,CAAA,IAAA,EAAO,YAAY,CAAA,CAAA;AAC1C;;;;"}
1
+ {"version":3,"file":"transform.js","sources":["../../../../src/vite/transform.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport MagicString from 'magic-string';\nimport { DEFAULT_EXPORT, type ExportName, type SameWorkerBinding } from './wranglerConfig';\nimport { detectWorkerEntrypointClasses } from './workerEntrypoint';\n\nconst MERGED_OPTIONS_IDENTIFIER = '__SENTRY_OPTIONS__';\n\n// ---------------------------------------------------------------------------\n// Minimal ESTree node types for the AST nodes we inspect.\n// ---------------------------------------------------------------------------\n\nexport interface BaseNode {\n type: string;\n start: number;\n end: number;\n}\n\nexport interface ProgramBody {\n body: BaseNode[];\n}\n\ninterface IdentifierNode extends BaseNode {\n name: string;\n}\n\ninterface CalleeNode {\n type: string;\n name?: string;\n property?: { type: string; name?: string };\n}\n\ninterface CallExpressionNode extends BaseNode {\n callee?: CalleeNode;\n}\n\ninterface ClassDeclarationNode extends BaseNode {\n id?: IdentifierNode | null;\n}\n\ninterface ExportDefaultNode extends BaseNode {\n declaration: BaseNode;\n}\n\ninterface ExportSpecifierNode extends BaseNode {\n local?: { type: string; name?: string };\n exported?: { type: string; name?: string };\n}\n\ninterface ExportNamedNode extends BaseNode {\n declaration?: BaseNode | null;\n source?: BaseNode | null;\n specifiers?: ExportSpecifierNode[];\n}\n\ninterface VariableDeclaratorNode {\n id?: { type: string; name?: string };\n init?: BaseNode | null;\n}\n\ninterface VariableDeclarationNode extends BaseNode {\n declarations?: VariableDeclaratorNode[];\n}\n\ninterface ImportDeclarationNode extends BaseNode {\n specifiers?: Array<{ local?: { type: string; name?: string } }>;\n}\n\nfunction isCallToMethod(node: BaseNode, methodName: string): boolean {\n if (node.type !== 'CallExpression') return false;\n const callee = (node as CallExpressionNode).callee;\n if (!callee) return false;\n if (callee.type === 'Identifier' && callee.name === methodName) return true;\n return (\n callee.type === 'MemberExpression' && callee.property?.type === 'Identifier' && callee.property.name === methodName\n );\n}\n\n/**\n * The kind of Sentry wrapper to apply to an exported class.\n *\n * `durableObject` and `workflow` are keyed by name from the wrangler config\n * (`durable_objects.bindings`, `workflows`), since those class names are\n * authoritative there. `workerEntrypoint` is different: a worker's own\n * entrypoints aren't enumerated in its config, so they're detected structurally\n * (a class extending `WorkerEntrypoint` from `cloudflare:workers`), with the\n * config providing only a fallback for self-bound entrypoints whose base class\n * lives in another module.\n */\nexport type ClassWrapperKind = 'durableObject' | 'agent' | 'workflow' | 'workerEntrypoint';\n\n/** Specifier name a `export { default as X } from '...'` re-export uses for the source's default. */\nconst DEFAULT_IMPORT = 'default';\n\n/**\n * The `@sentry/cloudflare` helper each wrapper kind emits. All share the same\n * `(optionsCallback, Class)` signature. `WorkerEntrypoint` classes use\n * `withSentry`, which runtime-detects the class type and routes accordingly.\n */\nconst WRAPPER_METHODS: Record<ClassWrapperKind, string> = {\n durableObject: 'instrumentDurableObjectWithSentry',\n agent: 'instrumentAgentWithSentry',\n workflow: 'instrumentWorkflowWithSentry',\n workerEntrypoint: 'withSentry',\n};\n\nexport interface TransformContext {\n /**\n * Exported class name → the kind of Sentry wrapper to apply. Populated from\n * the wrangler config, so the transform can wrap by name without resolving\n * each class's base type.\n */\n classWrappers: Map<string, ClassWrapperKind>;\n /**\n * Local class names detected as `agents` Agents. An Agent is configured as a Durable Object in\n * wrangler, so this upgrades those entries from `durableObject` to `agent`.\n */\n agentClasses?: ReadonlySet<string>;\n optionsFn: string;\n /** Import statement prepended when `optionsFn` references a separate module. */\n optionsImport?: string;\n /** Module the generated code imports `withSentry` and the class wrappers from. Defaults to `@sentry/cloudflare`. */\n sentryModule?: string;\n /** @see {@link import('./wranglerConfig').WranglerConfig.sameWorkerBindings} */\n sameWorkerBindings?: readonly SameWorkerBinding[];\n}\n\nexport interface TransformResult {\n code: string;\n map: ReturnType<MagicString['generateMap']>;\n /**\n * The configured class names that were actually wrapped. Lets the plugin warn\n * about configured classes it could not find, instead of silently leaving\n * them uninstrumented.\n */\n wrappedClasses: Set<string>;\n}\n\n/**\n * Rewrite the worker entry source to wrap its default export with `withSentry`\n * and any configured class export with its matching Sentry wrapper (see\n * {@link TransformContext.classWrappers}, e.g. Durable Object classes with\n * `instrumentDurableObjectWithSentry`).\n *\n * Handles `export class MyDO {}`, the specifier form (`class MyDO {}` …\n * `export { MyDO }` / `export { Foo as MyDO }`), and classes that live in\n * another module (`import { MyDO } from './do'; export { MyDO }` or\n * `export { MyDO } from './do'`). Only star re-exports (`export * from './do'`)\n * are left alone — the plugin warns about those via\n * {@link TransformResult.wrappedClasses}.\n *\n * Exported (rather than inlined into the plugin) so it can be unit-tested with a\n * plain AST and no Vite context. Returns `undefined` when nothing was wrapped and\n * there are no already-manually-wrapped classes to report.\n */\nexport function applyAutoInstrumentTransforms(\n code: string,\n ast: ProgramBody,\n ctx: TransformContext,\n): TransformResult | undefined {\n const ms = new MagicString(code);\n const topLevelClasses = collectTopLevelClasses(ast);\n const sameWorkerBindings = ctx.sameWorkerBindings ?? [];\n const state: TransformState = {\n ms,\n needsImport: false,\n wrappedClasses: new Set<string>(),\n topLevelClasses,\n wrappedLocals: new Map<string, string>(),\n classWrappers: ctx.classWrappers,\n agentClasses: ctx.agentClasses ?? new Set<string>(),\n workerEntrypointClasses: detectWorkerEntrypointClasses(ast),\n // The identifier must be chosen before wrapping, which bindings survive is only known after.\n optionsFn: sameWorkerBindings.length > 0 ? MERGED_OPTIONS_IDENTIFIER : ctx.optionsFn,\n autoWrapped: new Set<ExportName>(),\n manuallyWrappedLocals: collectManuallyWrappedLocals(ast),\n declaringStatements: collectDeclaringStatements(ast),\n };\n const { wrappedClasses } = state;\n\n // Named exports first, regardless of source order: the default-export handler\n // needs to know which local bindings a named export already wrapped, so it can\n // skip a class that is both exported by name and re-exported as default (which\n // would otherwise wrap it twice).\n for (const node of ast.body) {\n if (node.type === 'ExportNamedDeclaration') {\n handleNamedExport(node, ctx, state);\n }\n }\n for (const node of ast.body) {\n if (node.type === 'ExportDefaultDeclaration') {\n wrapDefaultExport(node as ExportDefaultNode, ctx, state);\n }\n }\n\n if (!state.needsImport) {\n // Nothing was rewritten. Still surface any classes found already wrapped\n // manually (via `wrappedClasses`) so the caller doesn't warn about them;\n // return undefined only when there was nothing to report either.\n if (wrappedClasses.size === 0) return undefined;\n return { code, map: ms.generateMap({ hires: true }), wrappedClasses };\n }\n\n // `prepend` inserts before earlier prepends, yielding: Sentry import, options import, declaration.\n if (sameWorkerBindings.length > 0) {\n ms.prepend(buildMergedOptionsDeclaration(sameWorkerBindings, ctx.optionsFn, state));\n }\n if (ctx.optionsImport) ms.prepend(ctx.optionsImport);\n ms.prepend(`import * as __SENTRY__ from '${ctx.sentryModule ?? '@sentry/cloudflare'}';\\n`);\n\n return {\n code: ms.toString(),\n map: ms.generateMap({ hires: true }),\n wrappedClasses,\n };\n}\n\ninterface TransformState {\n ms: MagicString;\n needsImport: boolean;\n wrappedClasses: Set<string>;\n /**\n * Top-level class declarations, exported or not, so specifier exports like\n * `export { MyDO }` can locate the class they refer to.\n */\n topLevelClasses: Map<string, ClassDeclarationNode>;\n /**\n * Local class name → the binding holding its wrapper, so two exports of the same class share one\n * wrapper and a default export of it can be re-pointed.\n */\n wrappedLocals: Map<string, string>;\n /** Class name → wrapper kind, keyed by the *exported* name (from config). */\n classWrappers: Map<string, ClassWrapperKind>;\n /** Local class names detected as `agents` Agents (see {@link TransformContext.agentClasses}). */\n agentClasses: ReadonlySet<string>;\n /**\n * Local class names detected as `WorkerEntrypoint` subclasses in this module,\n * so they can be wrapped without a config entry.\n */\n workerEntrypointClasses: Set<string>;\n optionsFn: string;\n /**\n * Export names wrapped by this transform, so their options can be extended with\n * `rpcTracePropagationBindings`. Hand-wrapped exports stay out, they keep the options they were\n * wrapped with. `wrappedClasses` counts both.\n */\n autoWrapped: Set<ExportName>;\n /**\n * Top-level bindings already assigned an `instrument*WithSentry(...)` result\n * (`const MyDO = instrumentDurableObjectWithSentry(...)`). Exporting one by\n * specifier must report it as wrapped rather than wrap it a second time.\n */\n manuallyWrappedLocals: Set<string>;\n /** Top-level binding name → the statement that declares it. */\n declaringStatements: Map<string, BaseNode>;\n}\n\n/**\n * Builds the callback that merges same-worker binding names into `rpcTracePropagationBindings` at\n * runtime, the options object only exists once the callback runs with `env`. Only bindings whose\n * class this transform wrapped survive, a hand-wrapped class runs on its own options.\n */\nfunction buildMergedOptionsDeclaration(\n sameWorkerBindings: readonly SameWorkerBinding[],\n optionsFn: string,\n state: TransformState,\n): string {\n const bindingNames = sameWorkerBindings\n .filter(({ className }) => state.autoWrapped.has(className))\n .map(({ bindingName }) => bindingName);\n\n if (!bindingNames.length) {\n return `const ${MERGED_OPTIONS_IDENTIFIER} = ${optionsFn};\\n`;\n }\n\n const names = bindingNames.map(name => JSON.stringify(name)).join(', ');\n return (\n `const ${MERGED_OPTIONS_IDENTIFIER} = (env) => { ` +\n `const opts = (${optionsFn})(env); ` +\n `return { ...opts, rpcTracePropagationBindings: [${names}, ...(opts?.rpcTracePropagationBindings ?? [])] }; };\\n`\n );\n}\n\n/**\n * Resolve the wrapper kind for a class export.\n *\n * Config (`classWrappers`) wins — it's authoritative for Durable Objects and\n * Workflows, and provides the self-binding fallback for WorkerEntrypoints whose\n * base class this module can't see. Otherwise a structurally-detected\n * `WorkerEntrypoint` subclass (matched by its *local* name) gets wrapped with\n * `withSentry`.\n *\n * `localName` is the binding **in this module** the export refers to, and must be\n * left undefined for `export { X } from '...'`: there the specifier's name belongs\n * to the source module, so matching it against anything detected here would wrap a\n * class that merely shares a name.\n *\n * The one case where config is refined rather than obeyed is an `agents` Agent:\n * it *is* a Durable Object, so wrangler can only ever describe it as one, and\n * only the detected base chain distinguishes the two.\n */\nfunction resolveWrapperKind(\n exportedName: string,\n localName: string | undefined,\n state: TransformState,\n): ClassWrapperKind | undefined {\n const configured = state.classWrappers.get(exportedName);\n\n if (\n configured === 'durableObject' &&\n ((localName && state.agentClasses.has(localName)) || state.agentClasses.has(exportedName))\n ) {\n return 'agent';\n }\n\n if (configured) return configured;\n if (localName && state.workerEntrypointClasses.has(localName)) return 'workerEntrypoint';\n return undefined;\n}\n\n/**\n * Top-level `const X = instrument*WithSentry(...)` bindings — a hand-wrapped class that is exported\n * separately (`export { X }`) rather than inline.\n */\nfunction collectManuallyWrappedLocals(ast: ProgramBody): Set<string> {\n const wrapperMethods = Object.values(WRAPPER_METHODS);\n const locals = new Set<string>();\n\n for (const node of ast.body) {\n const declaration = declarationOf(node);\n if (declaration?.type !== 'VariableDeclaration') continue;\n for (const declarator of (declaration as VariableDeclarationNode).declarations ?? []) {\n const name = declarator.id?.type === 'Identifier' ? declarator.id.name : undefined;\n const init = declarator.init;\n if (name && init && wrapperMethods.some(method => isCallToMethod(init, method))) {\n locals.add(name);\n }\n }\n }\n\n return locals;\n}\n\nfunction collectDeclaringStatements(ast: ProgramBody): Map<string, BaseNode> {\n const statements = new Map<string, BaseNode>();\n for (const node of ast.body) {\n const declaration = declarationOf(node);\n if (!declaration) continue;\n const ids =\n declaration.type === 'VariableDeclaration'\n ? ((declaration as VariableDeclarationNode).declarations ?? []).map(declarator => declarator.id)\n : declaration.type === 'ImportDeclaration'\n ? ((declaration as ImportDeclarationNode).specifiers ?? []).map(specifier => specifier.local)\n : [(declaration as ClassDeclarationNode).id];\n for (const id of ids) {\n if (id?.type === 'Identifier' && id.name) statements.set(id.name, node);\n }\n }\n return statements;\n}\n\nfunction collectTopLevelClasses(ast: ProgramBody): Map<string, ClassDeclarationNode> {\n const classes = new Map<string, ClassDeclarationNode>();\n for (const node of ast.body) {\n const declaration = declarationOf(node);\n if (declaration?.type !== 'ClassDeclaration') continue;\n const classNode = declaration as ClassDeclarationNode;\n if (classNode.id?.name) classes.set(classNode.id.name, classNode);\n }\n return classes;\n}\n\n/** The declaration a top-level statement makes, looking through `export` (`export const x = ...`). */\nfunction declarationOf(node: BaseNode): BaseNode | null | undefined {\n return node.type === 'ExportNamedDeclaration' ? (node as ExportNamedNode).declaration : node;\n}\n\nfunction wrapDefaultExport(node: ExportDefaultNode, ctx: TransformContext, state: TransformState): void {\n const decl = node.declaration;\n\n // Already wrapped — leave it alone\n if (isCallToMethod(decl, 'withSentry')) return;\n\n // `export default Foo` where `Foo` is a local class already wrapped by a named\n // export (e.g. a self-bound WorkerEntrypoint also used as the default handler).\n // Wrapping again would produce `withSentry(withSentry(...))`, so the default\n // export is re-pointed at the wrapper binding the named export created.\n if (decl.type === 'Identifier') {\n const wrappedName = state.wrappedLocals.get((decl as IdentifierNode).name);\n if (wrappedName) {\n state.ms.overwrite(decl.start, decl.end, wrappedName);\n state.autoWrapped.add(DEFAULT_EXPORT);\n return;\n }\n }\n\n // MagicString positions are always relative to the original source. Only the `export default`\n // keywords are replaced, so parentheses around the expression stay.\n const source = state.ms.original;\n const keywordsEnd = exportDefaultKeywordsEnd(source, node.start);\n const declaredName =\n decl.type === 'ClassDeclaration' || decl.type === 'FunctionDeclaration'\n ? (decl as ClassDeclarationNode).id?.name\n : undefined;\n\n // As with `export { handler as default }`, the export is set in two steps: bound as-is where the\n // original statement set it, then rebound at the end of the module to the wrapper, which sees\n // methods added in between. See `wrapDefaultSpecifier`.\n let wrapped = '__SENTRY_DEFAULT_EXPORT__';\n if (declaredName) {\n // `export default class Handler {}`: the declaration stays, so `Handler` stays bound in the module.\n state.ms.remove(node.start, decl.start);\n state.ms.appendLeft(node.end, `\\nvar __SENTRY_DEFAULT_EXPORT__ = ${declaredName};`);\n wrapped = declaredName;\n } else if (isAnonymousFunctionOrClass(decl)) {\n // As a property value, the class or function gets the name `default`, as `export default` gives it.\n const hasSemicolon = source[node.end - 1] === ';';\n state.ms.overwrite(node.start, keywordsEnd, 'var __SENTRY_DEFAULT_EXPORT__ = { default:');\n state.ms.appendLeft(hasSemicolon ? node.end - 1 : node.end, hasSemicolon ? ' }.default' : ' }.default;');\n } else {\n state.ms.overwrite(node.start, keywordsEnd, 'var __SENTRY_DEFAULT_EXPORT__ =');\n }\n state.ms.appendLeft(node.end, '\\nexport { __SENTRY_DEFAULT_EXPORT__ as default };');\n state.ms.append(`\\n__SENTRY_DEFAULT_EXPORT__ = __SENTRY__.withSentry(${state.optionsFn}, ${wrapped});`);\n state.needsImport = true;\n state.autoWrapped.add(DEFAULT_EXPORT);\n}\n\n/**\n * Offset just past the `default` keyword of the `export default` statement at `start`. Comments can\n * sit between `export`, `default` and the expression, and may themselves contain the word `default`.\n */\nfunction exportDefaultKeywordsEnd(source: string, start: number): number {\n let index = start + 'export'.length;\n while (index < source.length && !source.startsWith('default', index)) {\n if (source.startsWith('//', index)) {\n const lineEnd = source.indexOf('\\n', index);\n index = lineEnd === -1 ? source.length : lineEnd;\n } else if (source.startsWith('/*', index)) {\n const commentEnd = source.indexOf('*/', index + 2);\n index = commentEnd === -1 ? source.length : commentEnd + 2;\n } else {\n index++;\n }\n }\n return index + 'default'.length;\n}\n\nfunction isAnonymousFunctionOrClass(node: BaseNode): boolean {\n if (node.type === 'ArrowFunctionExpression') return true;\n const isFunctionOrClass = [\n 'FunctionExpression',\n 'FunctionDeclaration',\n 'ClassExpression',\n 'ClassDeclaration',\n ].includes(node.type);\n return isFunctionOrClass && !(node as ClassDeclarationNode).id;\n}\n\nfunction handleNamedExport(node: ExportNamedNode, ctx: TransformContext, state: TransformState): void {\n const decl = node.declaration;\n\n // ---- Manually wrapped class export ----\n // `export const MyDO = instrumentDurableObjectWithSentry(...)` — count it\n // as wrapped so the plugin doesn't warn about it, but leave it alone.\n if (decl?.type === 'VariableDeclaration') {\n collectManuallyWrappedClassExports(decl, ctx, state);\n return;\n }\n\n // ---- Named class export matching a configured binding ----\n if (decl?.type === 'ClassDeclaration') {\n wrapInlineClassExport(node, decl, ctx, state);\n return;\n }\n\n // ---- Specifier export (`export { Foo as MyDO }`, `export { MyDO } from './do'`) ----\n wrapSpecifierExports(node, ctx, state);\n}\n\nfunction collectManuallyWrappedClassExports(\n varDecl: VariableDeclarationNode,\n ctx: TransformContext,\n state: TransformState,\n): void {\n for (const declarator of varDecl.declarations ?? []) {\n const name = declarator.id?.type === 'Identifier' ? declarator.id.name : undefined;\n const kind = name ? ctx.classWrappers.get(name) : undefined;\n if (!name || !kind || !declarator.init) continue;\n\n // A hand-wrapped Agent is configured as a Durable Object, so accept either helper there —\n // otherwise an already-instrumented Agent would be reported as unwrapped.\n const accepted =\n kind === 'durableObject' ? [WRAPPER_METHODS.durableObject, WRAPPER_METHODS.agent] : [WRAPPER_METHODS[kind]];\n\n if (accepted.some(method => isCallToMethod(declarator.init as BaseNode, method))) {\n state.wrappedClasses.add(name);\n }\n }\n}\n\nfunction wrapInlineClassExport(\n exportNode: ExportNamedNode,\n classDecl: ClassDeclarationNode,\n ctx: TransformContext,\n state: TransformState,\n): void {\n const classId = classDecl.id;\n // Inline export: the exported name and the local class name are the same.\n const kind = classId ? resolveWrapperKind(classId.name, classId.name, state) : undefined;\n if (!classId || !kind) return;\n\n const className = classId.name;\n\n // Strip the `export ` keyword\n state.ms.overwrite(exportNode.start, classDecl.start, '');\n\n const wrappedName = wrapLocalClass(className, classDecl, kind, state);\n state.ms.appendLeft(exportNode.end, `export { ${wrappedName} as ${className} };\\n`);\n\n state.wrappedClasses.add(className);\n state.autoWrapped.add(className);\n}\n\n/**\n * Wrap a class declared in this module and return the binding that holds the wrapper.\n *\n * The declaration is left exactly as written. Only the *export* has to become the wrapper, so the\n * wrapper gets its own binding and the export is aliased to it, the same shape as the documented\n * manual `instrument*WithSentry` pattern and the cross-module re-export path below. Renaming the\n * declaration instead (`class __SENTRY_ORIGINAL_MyAgent__`) would also rename what the class reports\n * as `Function.prototype.name`, which libraries read to identify the user's class: `@cloudflare/think`\n * hands `this.constructor.name` to the AI SDK as the telemetry `functionId`, and that surfaced as a\n * `gen_ai.invoke_agent __SENTRY_ORIGINAL_MyAgent__` span.\n */\nfunction wrapLocalClass(\n localName: string,\n localClass: ClassDeclarationNode,\n kind: ClassWrapperKind,\n state: TransformState,\n): string {\n const existing = state.wrappedLocals.get(localName);\n if (existing) return existing;\n\n const wrappedName = `__SENTRY_WRAPPED_${localName}__`;\n state.wrappedLocals.set(localName, wrappedName);\n state.ms.appendLeft(\n localClass.end,\n `\\nconst ${wrappedName} = __SENTRY__.${WRAPPER_METHODS[kind]}(${state.optionsFn}, ${localName});\\n`,\n );\n state.needsImport = true;\n return wrappedName;\n}\n\n/**\n * Wrap the configured classes an `export { ... }` statement names.\n *\n * Each such specifier is re-pointed at a binding holding the wrapper, which means rebuilding the\n * statement; specifiers this plugin has no business touching are carried over verbatim. For a class\n * declared in this module the wrapper binding follows the declaration (see {@link wrapLocalClass}).\n * A class that lives in **another** module — imported and re-exported, or re-exported directly — is\n * first bound under a private name, since an import binding cannot be reassigned and the `from` form\n * has no local binding at all.\n */\nfunction wrapSpecifierExports(node: ExportNamedNode, ctx: TransformContext, state: TransformState): void {\n const specifiers = node.specifiers ?? [];\n if (specifiers.length === 0) return;\n\n const sourceLiteral = node.source ? state.ms.original.slice(node.source.start, node.source.end) : undefined;\n\n const prelude: string[] = [];\n const wrappedPairs: string[] = [];\n const kept: string[] = [];\n\n for (const specifier of specifiers) {\n const pair = wrapSpecifier(specifier, sourceLiteral, ctx, state, prelude);\n if (pair) {\n wrappedPairs.push(pair);\n } else {\n kept.push(state.ms.original.slice(specifier.start, specifier.end));\n }\n }\n\n if (wrappedPairs.length === 0) return;\n\n const statements = [...prelude, `export { ${wrappedPairs.join(', ')} };`];\n if (kept.length > 0) {\n const clause = `export { ${kept.join(', ')} }`;\n statements.push(sourceLiteral ? `${clause} from ${sourceLiteral};` : `${clause};`);\n }\n state.ms.overwrite(node.start, node.end, statements.join('\\n'));\n}\n\n/**\n * `export { handler as default }`, the form bundlers emit for a default export. The export is set\n * in two steps. Right after `handler` is declared, it is bound to `handler` as-is, so a circular\n * import that reads it during module evaluation gets the handler, as before the transform. At the\n * end of the module, it is rebound to the wrapper, so a handler assigned or given methods later is\n * wrapped as it ends up. The binding is a `var`: a read before `handler` is declared gets\n * `undefined`, as it would from the bundler's own `var`, where a `const` would throw and stop the\n * Worker from starting.\n */\nfunction wrapDefaultSpecifier(localName: string, state: TransformState): string | undefined {\n if (state.manuallyWrappedLocals.has(localName)) return undefined;\n\n // Same as `export default Foo`: re-point at the wrapper a named export already made.\n const wrappedName = state.wrappedLocals.get(localName);\n if (wrappedName) {\n state.autoWrapped.add(DEFAULT_EXPORT);\n return `${wrappedName} as default`;\n }\n\n const declaringStatement = state.declaringStatements.get(localName);\n if (declaringStatement) {\n state.ms.appendLeft(declaringStatement.end, `\\nvar __SENTRY_DEFAULT_EXPORT__ = ${localName};`);\n }\n state.ms.append(\n `\\n${declaringStatement ? '' : 'var '}__SENTRY_DEFAULT_EXPORT__ = __SENTRY__.withSentry(${state.optionsFn}, ${localName});`,\n );\n state.needsImport = true;\n state.autoWrapped.add(DEFAULT_EXPORT);\n return '__SENTRY_DEFAULT_EXPORT__ as default';\n}\n\n/**\n * `export { default } from './handler'`. The handler may already be wrapped in its own module,\n * which this transform cannot see, so the emitted guard returns such a handler as-is.\n *\n * The original re-export is a live binding to the handler module's export, but the wrapper is not\n * set until this module's body runs. A circular import that reads the default export before then\n * gets `undefined` instead of the handler. The binding is a `var` so that the read does not throw,\n * as a `const` would, and stop the Worker from starting. See `wrapDefaultSpecifier`.\n */\nfunction wrapDefaultReexport(\n localName: string,\n sourceLiteral: string,\n state: TransformState,\n prelude: string[],\n): string {\n const target = '__SENTRY_REEXPORT_default__';\n prelude.push(\n localName === DEFAULT_IMPORT\n ? `import ${target} from ${sourceLiteral};`\n : `import { ${localName} as ${target} } from ${sourceLiteral};`,\n `var __SENTRY_DEFAULT_EXPORT__ = __SENTRY__._INTERNAL_wrapUnlessInstrumented(__SENTRY__.withSentry, ${state.optionsFn}, ${target});`,\n );\n state.needsImport = true;\n state.autoWrapped.add(DEFAULT_EXPORT);\n return '__SENTRY_DEFAULT_EXPORT__ as default';\n}\n\n/**\n * Handle one export specifier, returning the `Wrapped as Exported` pair to emit for a class that\n * gets wrapped. The import/wrapper statements a cross-module pair depends on are pushed onto\n * `prelude`; a local class's wrapper binding is emitted after its declaration instead.\n *\n * Returns `undefined` when the specifier can stay exactly as written: it doesn't name a configured\n * class, or the binding is already hand-wrapped.\n */\nfunction wrapSpecifier(\n specifier: ExportSpecifierNode,\n sourceLiteral: string | undefined,\n ctx: TransformContext,\n state: TransformState,\n prelude: string[],\n): string | undefined {\n const exportedName =\n specifier.type === 'ExportSpecifier' && specifier.exported?.type === 'Identifier'\n ? specifier.exported.name\n : undefined;\n const localName = specifier.local?.type === 'Identifier' ? specifier.local.name : undefined;\n // With a `from` clause the specifier names an export of the *source* module, not a binding here.\n const kind = exportedName\n ? resolveWrapperKind(exportedName, sourceLiteral ? undefined : localName, state)\n : undefined;\n\n if (!exportedName || !localName) return undefined;\n if (!kind) {\n if (exportedName !== DEFAULT_IMPORT) return undefined;\n return sourceLiteral\n ? wrapDefaultReexport(localName, sourceLiteral, state, prelude)\n : wrapDefaultSpecifier(localName, state);\n }\n\n // Without a `from` clause the specifier points at a module-local binding.\n if (!sourceLiteral) {\n const localClass = state.topLevelClasses.get(localName);\n\n if (localClass?.id) {\n const wrappedName = wrapLocalClass(localName, localClass, kind, state);\n state.wrappedClasses.add(exportedName);\n return `${wrappedName} as ${exportedName}`;\n }\n\n if (state.manuallyWrappedLocals.has(localName)) {\n state.wrappedClasses.add(exportedName);\n return undefined;\n }\n }\n\n // The class comes from another module: bind it under a private name (for the `from` form, which\n // has no local binding at all), wrap that, and export the wrapper under the configured name.\n let target = localName;\n\n if (sourceLiteral) {\n target = `__SENTRY_REEXPORT_${exportedName}__`;\n prelude.push(\n localName === DEFAULT_IMPORT\n ? `import ${target} from ${sourceLiteral};`\n : `import { ${localName} as ${target} } from ${sourceLiteral};`,\n );\n }\n\n const wrappedName = `__SENTRY_WRAPPED_${exportedName}__`;\n\n // The class may already be hand-wrapped in its own module, which this transform cannot see. The\n // emitted guard returns such a class as-is instead of nesting a second wrapper around it.\n prelude.push(\n `const ${wrappedName} = __SENTRY__._INTERNAL_wrapUnlessInstrumented(__SENTRY__.${WRAPPER_METHODS[kind]}, ${state.optionsFn}, ${target});`,\n );\n state.wrappedClasses.add(exportedName);\n state.autoWrapped.add(exportedName);\n state.needsImport = true;\n\n return `${wrappedName} as ${exportedName}`;\n}\n"],"names":["MagicString","detectWorkerEntrypointClas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