@sentry/cloudflare 11.10.0 → 11.11.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 (145) hide show
  1. package/build/cjs/dev/baseSdk.js +4 -8
  2. package/build/cjs/dev/baseSdk.js.map +1 -1
  3. package/build/cjs/dev/index.js +2 -1
  4. package/build/cjs/dev/index.js.map +1 -1
  5. package/build/cjs/dev/instrumentations/instrumentDurableObjectStorage.js +2 -2
  6. package/build/cjs/dev/instrumentations/instrumentDurableObjectStorage.js.map +1 -1
  7. package/build/cjs/dev/instrumentations/instrumentDurableObjectSyncKvStorage.js +2 -2
  8. package/build/cjs/dev/instrumentations/instrumentDurableObjectSyncKvStorage.js.map +1 -1
  9. package/build/cjs/dev/instrumentations/instrumentSqlStorage.js +5 -5
  10. package/build/cjs/dev/instrumentations/instrumentSqlStorage.js.map +1 -1
  11. package/build/cjs/dev/instrumentations/worker/instrumentD1.js +12 -12
  12. package/build/cjs/dev/instrumentations/worker/instrumentD1.js.map +1 -1
  13. package/build/cjs/dev/instrumentations/worker/instrumentQueue.js +7 -7
  14. package/build/cjs/dev/instrumentations/worker/instrumentQueue.js.map +1 -1
  15. package/build/cjs/dev/instrumentations/worker/instrumentQueueProducer.js +6 -6
  16. package/build/cjs/dev/instrumentations/worker/instrumentQueueProducer.js.map +1 -1
  17. package/build/cjs/dev/instrumentations/worker/instrumentR2.js +1 -1
  18. package/build/cjs/dev/instrumentations/worker/instrumentR2.js.map +1 -1
  19. package/build/cjs/dev/integrations/httpServer.js +15 -72
  20. package/build/cjs/dev/integrations/httpServer.js.map +1 -1
  21. package/build/cjs/dev/request.js.map +1 -1
  22. package/build/cjs/dev/scope-utils.js +2 -6
  23. package/build/cjs/dev/scope-utils.js.map +1 -1
  24. package/build/cjs/dev/sdk.js +2 -5
  25. package/build/cjs/dev/sdk.js.map +1 -1
  26. package/build/cjs/dev/vite/index.js +2 -1
  27. package/build/cjs/dev/vite/index.js.map +1 -1
  28. package/build/cjs/dev/workflows.js +5 -5
  29. package/build/cjs/dev/workflows.js.map +1 -1
  30. package/build/cjs/dev/wrapRequestHandlerWithInit.js +29 -111
  31. package/build/cjs/dev/wrapRequestHandlerWithInit.js.map +1 -1
  32. package/build/cjs/prod/baseSdk.js +4 -8
  33. package/build/cjs/prod/baseSdk.js.map +1 -1
  34. package/build/cjs/prod/index.js +2 -1
  35. package/build/cjs/prod/index.js.map +1 -1
  36. package/build/cjs/prod/instrumentations/instrumentDurableObjectStorage.js +2 -2
  37. package/build/cjs/prod/instrumentations/instrumentDurableObjectStorage.js.map +1 -1
  38. package/build/cjs/prod/instrumentations/instrumentDurableObjectSyncKvStorage.js +2 -2
  39. package/build/cjs/prod/instrumentations/instrumentDurableObjectSyncKvStorage.js.map +1 -1
  40. package/build/cjs/prod/instrumentations/instrumentSqlStorage.js +5 -5
  41. package/build/cjs/prod/instrumentations/instrumentSqlStorage.js.map +1 -1
  42. package/build/cjs/prod/instrumentations/worker/instrumentD1.js +12 -12
  43. package/build/cjs/prod/instrumentations/worker/instrumentD1.js.map +1 -1
  44. package/build/cjs/prod/instrumentations/worker/instrumentQueue.js +7 -7
  45. package/build/cjs/prod/instrumentations/worker/instrumentQueue.js.map +1 -1
  46. package/build/cjs/prod/instrumentations/worker/instrumentQueueProducer.js +6 -6
  47. package/build/cjs/prod/instrumentations/worker/instrumentQueueProducer.js.map +1 -1
  48. package/build/cjs/prod/instrumentations/worker/instrumentR2.js +1 -1
  49. package/build/cjs/prod/instrumentations/worker/instrumentR2.js.map +1 -1
  50. package/build/cjs/prod/integrations/httpServer.js +15 -72
  51. package/build/cjs/prod/integrations/httpServer.js.map +1 -1
  52. package/build/cjs/prod/request.js.map +1 -1
  53. package/build/cjs/prod/scope-utils.js +2 -6
  54. package/build/cjs/prod/scope-utils.js.map +1 -1
  55. package/build/cjs/prod/sdk.js +2 -5
  56. package/build/cjs/prod/sdk.js.map +1 -1
  57. package/build/cjs/prod/vite/index.js +2 -1
  58. package/build/cjs/prod/vite/index.js.map +1 -1
  59. package/build/cjs/prod/workflows.js +5 -5
  60. package/build/cjs/prod/workflows.js.map +1 -1
  61. package/build/cjs/prod/wrapRequestHandlerWithInit.js +29 -111
  62. package/build/cjs/prod/wrapRequestHandlerWithInit.js.map +1 -1
  63. package/build/esm/dev/baseSdk.js +4 -7
  64. package/build/esm/dev/baseSdk.js.map +1 -1
  65. package/build/esm/dev/index.js +2 -1
  66. package/build/esm/dev/index.js.map +1 -1
  67. package/build/esm/dev/instrumentations/instrumentDurableObjectStorage.js +3 -3
  68. package/build/esm/dev/instrumentations/instrumentDurableObjectStorage.js.map +1 -1
  69. package/build/esm/dev/instrumentations/instrumentDurableObjectSyncKvStorage.js +3 -3
  70. package/build/esm/dev/instrumentations/instrumentDurableObjectSyncKvStorage.js.map +1 -1
  71. package/build/esm/dev/instrumentations/instrumentSqlStorage.js +6 -6
  72. package/build/esm/dev/instrumentations/instrumentSqlStorage.js.map +1 -1
  73. package/build/esm/dev/instrumentations/worker/instrumentD1.js +13 -13
  74. package/build/esm/dev/instrumentations/worker/instrumentD1.js.map +1 -1
  75. package/build/esm/dev/instrumentations/worker/instrumentQueue.js +8 -8
  76. package/build/esm/dev/instrumentations/worker/instrumentQueue.js.map +1 -1
  77. package/build/esm/dev/instrumentations/worker/instrumentQueueProducer.js +7 -7
  78. package/build/esm/dev/instrumentations/worker/instrumentQueueProducer.js.map +1 -1
  79. package/build/esm/dev/instrumentations/worker/instrumentR2.js +1 -1
  80. package/build/esm/dev/instrumentations/worker/instrumentR2.js.map +1 -1
  81. package/build/esm/dev/integrations/httpServer.js +16 -71
  82. package/build/esm/dev/integrations/httpServer.js.map +1 -1
  83. package/build/esm/dev/package.json +1 -1
  84. package/build/esm/dev/request.js.map +1 -1
  85. package/build/esm/dev/scope-utils.js +3 -6
  86. package/build/esm/dev/scope-utils.js.map +1 -1
  87. package/build/esm/dev/sdk.js +4 -6
  88. package/build/esm/dev/sdk.js.map +1 -1
  89. package/build/esm/dev/vite/index.js +2 -1
  90. package/build/esm/dev/vite/index.js.map +1 -1
  91. package/build/esm/dev/workflows.js +6 -6
  92. package/build/esm/dev/workflows.js.map +1 -1
  93. package/build/esm/dev/wrapRequestHandlerWithInit.js +33 -115
  94. package/build/esm/dev/wrapRequestHandlerWithInit.js.map +1 -1
  95. package/build/esm/prod/baseSdk.js +4 -7
  96. package/build/esm/prod/baseSdk.js.map +1 -1
  97. package/build/esm/prod/index.js +2 -1
  98. package/build/esm/prod/index.js.map +1 -1
  99. package/build/esm/prod/instrumentations/instrumentDurableObjectStorage.js +3 -3
  100. package/build/esm/prod/instrumentations/instrumentDurableObjectStorage.js.map +1 -1
  101. package/build/esm/prod/instrumentations/instrumentDurableObjectSyncKvStorage.js +3 -3
  102. package/build/esm/prod/instrumentations/instrumentDurableObjectSyncKvStorage.js.map +1 -1
  103. package/build/esm/prod/instrumentations/instrumentSqlStorage.js +6 -6
  104. package/build/esm/prod/instrumentations/instrumentSqlStorage.js.map +1 -1
  105. package/build/esm/prod/instrumentations/worker/instrumentD1.js +13 -13
  106. package/build/esm/prod/instrumentations/worker/instrumentD1.js.map +1 -1
  107. package/build/esm/prod/instrumentations/worker/instrumentQueue.js +8 -8
  108. package/build/esm/prod/instrumentations/worker/instrumentQueue.js.map +1 -1
  109. package/build/esm/prod/instrumentations/worker/instrumentQueueProducer.js +7 -7
  110. package/build/esm/prod/instrumentations/worker/instrumentQueueProducer.js.map +1 -1
  111. package/build/esm/prod/instrumentations/worker/instrumentR2.js +1 -1
  112. package/build/esm/prod/instrumentations/worker/instrumentR2.js.map +1 -1
  113. package/build/esm/prod/integrations/httpServer.js +16 -71
  114. package/build/esm/prod/integrations/httpServer.js.map +1 -1
  115. package/build/esm/prod/package.json +1 -1
  116. package/build/esm/prod/request.js.map +1 -1
  117. package/build/esm/prod/scope-utils.js +3 -6
  118. package/build/esm/prod/scope-utils.js.map +1 -1
  119. package/build/esm/prod/sdk.js +4 -6
  120. package/build/esm/prod/sdk.js.map +1 -1
  121. package/build/esm/prod/vite/index.js +2 -1
  122. package/build/esm/prod/vite/index.js.map +1 -1
  123. package/build/esm/prod/workflows.js +6 -6
  124. package/build/esm/prod/workflows.js.map +1 -1
  125. package/build/esm/prod/wrapRequestHandlerWithInit.js +33 -115
  126. package/build/esm/prod/wrapRequestHandlerWithInit.js.map +1 -1
  127. package/build/types/baseSdk.d.ts +6 -18
  128. package/build/types/baseSdk.d.ts.map +1 -1
  129. package/build/types/instrumentations/instrumentSqlStorage.d.ts.map +1 -1
  130. package/build/types/instrumentations/worker/instrumentD1.d.ts.map +1 -1
  131. package/build/types/instrumentations/worker/instrumentQueue.d.ts.map +1 -1
  132. package/build/types/instrumentations/worker/instrumentQueueProducer.d.ts.map +1 -1
  133. package/build/types/integrations/httpServer.d.ts +9 -20
  134. package/build/types/integrations/httpServer.d.ts.map +1 -1
  135. package/build/types/request.d.ts +3 -4
  136. package/build/types/request.d.ts.map +1 -1
  137. package/build/types/scope-utils.d.ts +0 -4
  138. package/build/types/scope-utils.d.ts.map +1 -1
  139. package/build/types/sdk.d.ts +3 -8
  140. package/build/types/sdk.d.ts.map +1 -1
  141. package/build/types/vite/index.d.ts.map +1 -1
  142. package/build/types/workflows.d.ts.map +1 -1
  143. package/build/types/wrapRequestHandlerWithInit.d.ts +1 -1
  144. package/build/types/wrapRequestHandlerWithInit.d.ts.map +1 -1
  145. package/package.json +8 -8
@@ -1,86 +1,29 @@
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');
6
4
 
7
5
  const INTEGRATION_NAME = "HttpServer";
6
+ function getHttpServerRequestOptions(client) {
7
+ return client.getIntegrationByName(INTEGRATION_NAME)?.requestOptions ?? {
8
+ maxRequestBodySize: "none"
9
+ };
10
+ }
8
11
  const _httpServerIntegration = ((options = {}) => {
9
12
  return {
10
13
  name: INTEGRATION_NAME,
11
- maxRequestBodySize: options.maxRequestBodySize,
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
14
+ requestOptions: {
15
+ maxRequestBodySize: options.maxRequestBodySize,
16
+ ignoreRequestBody: options.ignoreRequestBody,
17
+ ignoreIncomingRequests: options.ignoreIncomingRequests,
18
+ ignoreStaticAssets: options.ignoreStaticAssets ?? true,
19
+ spans: options.spans,
20
+ onSpanCreated: options.onSpanCreated,
21
+ onSpanEnd: options.onSpanEnd
22
+ }
18
23
  };
19
24
  });
20
25
  const httpServerIntegration = core.defineIntegration(_httpServerIntegration);
21
- async function captureIncomingRequestBody(client, request) {
22
- const integration = client.getIntegrationByName(INTEGRATION_NAME);
23
- if (!integration) {
24
- return;
25
- }
26
- const configuredBodySize = integration.maxRequestBodySize;
27
- const effectiveBodySize = configuredBodySize ?? (client.getDataCollectionOptions().httpBodies.includes("incomingRequest") ? "medium" : "none");
28
- if (effectiveBodySize === "none") {
29
- return;
30
- }
31
- if (request.method === "GET" || request.method === "HEAD" || request.method === "OPTIONS") {
32
- return;
33
- }
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
- )) {
41
- return;
42
- }
43
- const isolationScope = core.getIsolationScope();
44
- await core.captureBodyFromWinterCGRequest(request, isolationScope, effectiveBodySize);
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
- }
81
26
 
82
- exports.captureIncomingRequestBody = captureIncomingRequestBody;
83
- exports.getIncomingRequestSpanHooks = getIncomingRequestSpanHooks;
27
+ exports.getHttpServerRequestOptions = getHttpServerRequestOptions;
84
28
  exports.httpServerIntegration = httpServerIntegration;
85
- exports.shouldCreateIncomingRequestSpan = shouldCreateIncomingRequestSpan;
86
29
  //# sourceMappingURL=httpServer.js.map
@@ -1 +1 @@
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,OAAA,GAAwC,EAAC,KAAqC;AAC7G,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,oBAAoB,OAAA,CAAQ,kBAAA;AAAA,IAC5B,mBAAmB,OAAA,CAAQ,iBAAA;AAAA,IAC3B,wBAAwB,OAAA,CAAQ,sBAAA;AAAA,IAChC,kBAAA,EAAoB,QAAQ,kBAAA,IAAsB,IAAA;AAAA,IAClD,OAAO,OAAA,CAAQ,KAAA;AAAA,IACf,eAAe,OAAA,CAAQ,aAAA;AAAA,IACvB,WAAW,OAAA,CAAQ;AAAA,GACrB;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,iBA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AG;AAChG,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,MAAM,yBAAyB,WAAA,EAAa,sBAAA;AAC5C,EAAA,OAAO,EACL,sBAAA,IACAN,iBAAA;AAAA,IACEC,yBAAc,uDAAA,GAA0D,EAAA;AAAA,IACxE,MAAM,sBAAA,CAAuB,OAAA,EAAS,OAAO,CAAA;AAAA,IAC7C,MAAM;AAAA,GACR,CAAA;AAEJ;AAMO,SAAS,4BAA4B,MAAA,EAG1C;AACA,EAAA,MAAM,WAAA,GAAc,MAAA,EAAQ,oBAAA,CAAoD,gBAAgB,CAAA;AAChG,EAAA,OAAO;AAAA,IACL,aAAA,EAAe,CAAC,IAAA,EAAM,OAAA,KACpBD,iBAAA;AAAA,MACEC,yBAAc,2BAAA,GAA8B,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;;;;;;;"}
1
+ {"version":3,"file":"httpServer.js","sources":["../../../../src/integrations/httpServer.ts"],"sourcesContent":["import type { Client, Integration, IntegrationFn, MaxRequestBodySize, Span } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport type { AssertTrue, CheckServerRequestOptions, ServerRequestOptions } from '@sentry/core/server';\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\ntype SupportedServerRequestOptions = Omit<\n ServerRequestOptions<Request, Response>,\n 'sessions' | 'sessionFlushingDelayMS'\n>;\n\n// Every supported shared option is a required key, so a new one fails to compile below until the\n// integration passes it on.\ntype HttpServerRequestOptions = {\n [K in keyof Required<SupportedServerRequestOptions>]: SupportedServerRequestOptions[K];\n};\n\ninterface HttpServerIntegration extends Integration {\n requestOptions: HttpServerRequestOptions;\n}\n\n/**\n * The incoming request options of the client's `httpServerIntegration`. If the integration does not\n * set `maxRequestBodySize`, `dataCollection.httpBodies` decides. Without the integration, the SDK\n * attaches no request body.\n */\nexport function getHttpServerRequestOptions(client: Client): ServerRequestOptions<Request, Response> {\n return (\n client.getIntegrationByName<HttpServerIntegration>(INTEGRATION_NAME)?.requestOptions ?? {\n maxRequestBodySize: 'none',\n }\n );\n}\n\nconst _httpServerIntegration = ((options: HttpServerIntegrationOptions = {}): HttpServerIntegration => {\n return {\n name: INTEGRATION_NAME,\n requestOptions: {\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 };\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"],"names":["defineIntegration"],"mappings":";;;;AAIA,MAAM,gBAAA,GAAmB,YAAA;AA6GlB,SAAS,4BAA4B,MAAA,EAAyD;AACnG,EAAA,OACE,MAAA,CAAO,oBAAA,CAA4C,gBAAgB,CAAA,EAAG,cAAA,IAAkB;AAAA,IACtF,kBAAA,EAAoB;AAAA,GACtB;AAEJ;AAEA,MAAM,sBAAA,IAA0B,CAAC,OAAA,GAAwC,EAAC,KAA6B;AACrG,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,cAAA,EAAgB;AAAA,MACd,oBAAoB,OAAA,CAAQ,kBAAA;AAAA,MAC5B,mBAAmB,OAAA,CAAQ,iBAAA;AAAA,MAC3B,wBAAwB,OAAA,CAAQ,sBAAA;AAAA,MAChC,kBAAA,EAAoB,QAAQ,kBAAA,IAAsB,IAAA;AAAA,MAClD,OAAO,OAAA,CAAQ,KAAA;AAAA,MACf,eAAe,OAAA,CAAQ,aAAA;AAAA,MACvB,WAAW,OAAA,CAAQ;AAAA;AACrB,GACF;AACF,CAAA,CAAA;AAoBO,MAAM,qBAAA,GAAwBA,uBAAkB,sBAAsB;;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"request.js","sources":["../../../src/request.ts"],"sourcesContent":["import { initBaseSdk } from './baseSdk';\nimport type { CloudflareOptions } from './client';\nimport { type RequestHandlerWrapperOptions, wrapRequestHandlerWithInit } from './wrapRequestHandlerWithInit';\n\n/**\n * Wraps a cloudflare request handler in Sentry instrumentation.\n *\n * The client is set up with the default integrations that work without the `nodejs_compat`\n * compatibility flag, so that this also works on runtimes that cannot enable it (e.g. Shopify\n * Oxygen). On a runtime that has `nodejs_compat`, pass `defaultIntegrations:\n * getDefaultIntegrations(options)` in `options` to get the full set instead.\n */\nexport function wrapRequestHandler(\n wrapperOptions: Omit<RequestHandlerWrapperOptions, 'options'> & {\n // `enableOpenTelemetrySetup` is only honored by `init` from `sdk.ts`; this entry point\n // initializes the SDK via `initBaseSdk`, where setting it would have no effect.\n options: Omit<CloudflareOptions, 'enableOpenTelemetrySetup'>;\n },\n handler: (...args: unknown[]) => Response | Promise<Response>,\n): Promise<Response> {\n return wrapRequestHandlerWithInit(wrapperOptions, handler, initBaseSdk);\n}\n\nexport { httpServerIntegration } from './integrations/httpServer';\n"],"names":["wrapRequestHandlerWithInit","initBaseSdk"],"mappings":";;;;;;AAYO,SAAS,kBAAA,CACd,gBAKA,OAAA,EACmB;AACnB,EAAA,OAAOA,qDAAA,CAA2B,cAAA,EAAgB,OAAA,EAASC,mBAAW,CAAA;AACxE;;;;;"}
1
+ {"version":3,"file":"request.js","sources":["../../../src/request.ts"],"sourcesContent":["import { initBaseSdk } from './baseSdk';\nimport type { CloudflareOptions } from './client';\nimport { type RequestHandlerWrapperOptions, wrapRequestHandlerWithInit } from './wrapRequestHandlerWithInit';\n\n/**\n * Wraps a cloudflare request handler in Sentry instrumentation.\n *\n * The client uses the same default integrations as `init`, without setting up an OpenTelemetry\n * tracer provider. This entry point also works on runtimes that cannot enable the `nodejs_compat`\n * compatibility flag, such as Shopify Oxygen.\n */\nexport function wrapRequestHandler(\n wrapperOptions: Omit<RequestHandlerWrapperOptions, 'options'> & {\n // `enableOpenTelemetrySetup` is only honored by `init` from `sdk.ts`; this entry point\n // initializes the SDK via `initBaseSdk`, where setting it would have no effect.\n options: Omit<CloudflareOptions, 'enableOpenTelemetrySetup'>;\n },\n handler: (...args: unknown[]) => Response | Promise<Response>,\n): Promise<Response> {\n return wrapRequestHandlerWithInit(wrapperOptions, handler, initBaseSdk);\n}\n\nexport { httpServerIntegration } from './integrations/httpServer';\n"],"names":["wrapRequestHandlerWithInit","initBaseSdk"],"mappings":";;;;;;AAWO,SAAS,kBAAA,CACd,gBAKA,OAAA,EACmB;AACnB,EAAA,OAAOA,qDAAA,CAA2B,cAAA,EAAgB,OAAA,EAASC,mBAAW,CAAA;AACxE;;;;;"}
@@ -1,10 +1,10 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
 
3
- const core = require('@sentry/core');
3
+ const attributes = require('@sentry/conventions/attributes');
4
4
 
5
5
  function addCloudResourceContext(scope) {
6
6
  scope.setContext("cloud_resource", {
7
- "cloud.provider": "cloudflare"
7
+ [attributes.CLOUD_PROVIDER]: "cloudflare"
8
8
  });
9
9
  }
10
10
  function addCultureContext(scope, cf) {
@@ -12,11 +12,7 @@ function addCultureContext(scope, cf) {
12
12
  timezone: cf.timezone
13
13
  });
14
14
  }
15
- function addRequest(scope, request) {
16
- scope.setSDKProcessingMetadata({ normalizedRequest: core.winterCGRequestToRequestData(request) });
17
- }
18
15
 
19
16
  exports.addCloudResourceContext = addCloudResourceContext;
20
17
  exports.addCultureContext = addCultureContext;
21
- exports.addRequest = addRequest;
22
18
  //# sourceMappingURL=scope-utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"scope-utils.js","sources":["../../../src/scope-utils.ts"],"sourcesContent":["import type { CfProperties, IncomingRequestCfProperties } from '@cloudflare/workers-types';\nimport type { Scope } from '@sentry/core';\nimport { winterCGRequestToRequestData } from '@sentry/core';\n\n/**\n * Set cloud resource context on scope.\n */\nexport function addCloudResourceContext(scope: Scope): void {\n scope.setContext('cloud_resource', {\n 'cloud.provider': 'cloudflare',\n });\n}\n\n/**\n * Set culture context on scope\n */\nexport function addCultureContext(scope: Scope, cf: IncomingRequestCfProperties | CfProperties): void {\n scope.setContext('culture', {\n timezone: cf.timezone,\n });\n}\n\n/**\n * Set request data on scope\n */\nexport function addRequest(scope: Scope, request: Request): void {\n scope.setSDKProcessingMetadata({ normalizedRequest: winterCGRequestToRequestData(request) });\n}\n"],"names":["winterCGRequestToRequestData"],"mappings":";;;;AAOO,SAAS,wBAAwB,KAAA,EAAoB;AAC1D,EAAA,KAAA,CAAM,WAAW,gBAAA,EAAkB;AAAA,IACjC,gBAAA,EAAkB;AAAA,GACnB,CAAA;AACH;AAKO,SAAS,iBAAA,CAAkB,OAAc,EAAA,EAAsD;AACpG,EAAA,KAAA,CAAM,WAAW,SAAA,EAAW;AAAA,IAC1B,UAAU,EAAA,CAAG;AAAA,GACd,CAAA;AACH;AAKO,SAAS,UAAA,CAAW,OAAc,OAAA,EAAwB;AAC/D,EAAA,KAAA,CAAM,yBAAyB,EAAE,iBAAA,EAAmBA,iCAAA,CAA6B,OAAO,GAAG,CAAA;AAC7F;;;;;;"}
1
+ {"version":3,"file":"scope-utils.js","sources":["../../../src/scope-utils.ts"],"sourcesContent":["import { CLOUD_PROVIDER } from '@sentry/conventions/attributes';\nimport type { CfProperties, IncomingRequestCfProperties } from '@cloudflare/workers-types';\nimport type { Scope } from '@sentry/core';\n\n/**\n * Set cloud resource context on scope.\n */\nexport function addCloudResourceContext(scope: Scope): void {\n scope.setContext('cloud_resource', {\n [CLOUD_PROVIDER]: 'cloudflare',\n });\n}\n\n/**\n * Set culture context on scope\n */\nexport function addCultureContext(scope: Scope, cf: IncomingRequestCfProperties | CfProperties): void {\n scope.setContext('culture', {\n timezone: cf.timezone,\n });\n}\n"],"names":["CLOUD_PROVIDER"],"mappings":";;;;AAOO,SAAS,wBAAwB,KAAA,EAAoB;AAC1D,EAAA,KAAA,CAAM,WAAW,gBAAA,EAAkB;AAAA,IACjC,CAACA,yBAAc,GAAG;AAAA,GACnB,CAAA;AACH;AAKO,SAAS,iBAAA,CAAkB,OAAc,EAAA,EAAsD;AACpG,EAAA,KAAA,CAAM,WAAW,SAAA,EAAW;AAAA,IAC1B,UAAU,EAAA,CAAG;AAAA,GACd,CAAA;AACH;;;;;"}
@@ -4,21 +4,18 @@ const baseSdk = require('./baseSdk.js');
4
4
  const tracer = require('./opentelemetry/tracer.js');
5
5
  const wrapRequestHandlerWithInit = require('./wrapRequestHandlerWithInit.js');
6
6
 
7
- function getDefaultIntegrations(options) {
8
- return baseSdk.getBaseDefaultIntegrations(options);
9
- }
10
7
  function init(options) {
11
8
  options.enableOpenTelemetrySetup ?? (options.enableOpenTelemetrySetup = false);
12
9
  if (options.enableOpenTelemetrySetup) {
13
10
  tracer.setupOpenTelemetryTracer();
14
11
  }
15
- return baseSdk.initWithDefaultIntegrations(options, getDefaultIntegrations);
12
+ return baseSdk.initBaseSdk(options);
16
13
  }
17
14
  function _INTERNAL_wrapRequestHandler(wrapperOptions, handler) {
18
15
  return wrapRequestHandlerWithInit.wrapRequestHandlerWithInit(wrapperOptions, handler, init);
19
16
  }
20
17
 
18
+ exports.getDefaultIntegrations = baseSdk.getDefaultIntegrations;
21
19
  exports._INTERNAL_wrapRequestHandler = _INTERNAL_wrapRequestHandler;
22
- exports.getDefaultIntegrations = getDefaultIntegrations;
23
20
  exports.init = init;
24
21
  //# sourceMappingURL=sdk.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.js","sources":["../../../src/sdk.ts"],"sourcesContent":["import type { Integration } from '@sentry/core';\nimport { getBaseDefaultIntegrations, initWithDefaultIntegrations } from './baseSdk';\nimport type { CloudflareClient, CloudflareOptions } from './client';\nimport { setupOpenTelemetryTracer } from './opentelemetry/tracer';\nimport { type RequestHandlerWrapperOptions, wrapRequestHandlerWithInit } from './wrapRequestHandlerWithInit';\n\n// Test-only helper, re-exported here so tests can reset the global client cache.\nexport { _clearGlobalClientCache } from './clientCache';\n\n/**\n * Get the default integrations for the Cloudflare SDK.\n */\nexport function getDefaultIntegrations(options: CloudflareOptions): Integration[] {\n return getBaseDefaultIntegrations(options);\n}\n\n/**\n * Initializes the cloudflare SDK.\n */\nexport function init(options: CloudflareOptions): CloudflareClient | undefined {\n // Like most Node-based SDKs, Cloudflare defaults to running without a Sentry OpenTelemetry tracer\n // provider. Scope isolation is handled by the entrypoint wrappers' AsyncLocalStorage strategy.\n options.enableOpenTelemetrySetup ??= false;\n\n // Opt-in only: when `enableOpenTelemetrySetup` is `true`, set up a custom trace provider so spans\n // emitted via `@opentelemetry/api` are captured by Sentry. See the option's docs for the caveats.\n if (options.enableOpenTelemetrySetup) {\n setupOpenTelemetryTracer();\n }\n\n return initWithDefaultIntegrations(options, getDefaultIntegrations);\n}\n\n/**\n * `wrapRequestHandler` backed by `init`, so the request gets the full default integrations and\n * honors `enableOpenTelemetrySetup`. The `@sentry/cloudflare/request` variant deliberately skips\n * both to stay usable without `nodejs_compat`.\n *\n * For framework SDKs building on the main entry point, e.g. SvelteKit, whose OpenTelemetry spans\n * need the tracer provider.\n *\n * @internal\n */\nexport function _INTERNAL_wrapRequestHandler(\n wrapperOptions: RequestHandlerWrapperOptions,\n handler: (...args: unknown[]) => Response | Promise<Response>,\n): Promise<Response> {\n return wrapRequestHandlerWithInit(wrapperOptions, handler, init);\n}\n"],"names":["getBaseDefaultIntegrations","setupOpenTelemetryTracer","initWithDefaultIntegrations","wrapRequestHandlerWithInit"],"mappings":";;;;;;AAYO,SAAS,uBAAuB,OAAA,EAA2C;AAChF,EAAA,OAAOA,mCAA2B,OAAO,CAAA;AAC3C;AAKO,SAAS,KAAK,OAAA,EAA0D;AAG7E,EAAA,OAAA,CAAQ,wBAAA,KAAR,QAAQ,wBAAA,GAA6B,KAAA,CAAA;AAIrC,EAAA,IAAI,QAAQ,wBAAA,EAA0B;AACpC,IAAAC,+BAAA,EAAyB;AAAA,EAC3B;AAEA,EAAA,OAAOC,mCAAA,CAA4B,SAAS,sBAAsB,CAAA;AACpE;AAYO,SAAS,4BAAA,CACd,gBACA,OAAA,EACmB;AACnB,EAAA,OAAOC,qDAAA,CAA2B,cAAA,EAAgB,OAAA,EAAS,IAAI,CAAA;AACjE;;;;;;"}
1
+ {"version":3,"file":"sdk.js","sources":["../../../src/sdk.ts"],"sourcesContent":["import { initBaseSdk } from './baseSdk';\nimport type { CloudflareClient, CloudflareOptions } from './client';\nimport { setupOpenTelemetryTracer } from './opentelemetry/tracer';\nimport { type RequestHandlerWrapperOptions, wrapRequestHandlerWithInit } from './wrapRequestHandlerWithInit';\n\n// Test-only helper, re-exported here so tests can reset the global client cache.\nexport { _clearGlobalClientCache } from './clientCache';\n\nexport { getDefaultIntegrations } from './baseSdk';\n\n/**\n * Initializes the cloudflare SDK.\n */\nexport function init(options: CloudflareOptions): CloudflareClient | undefined {\n // Like most Node-based SDKs, Cloudflare defaults to running without a Sentry OpenTelemetry tracer\n // provider. Scope isolation is handled by the entrypoint wrappers' AsyncLocalStorage strategy.\n options.enableOpenTelemetrySetup ??= false;\n\n // Opt-in only: when `enableOpenTelemetrySetup` is `true`, set up a custom trace provider so spans\n // emitted via `@opentelemetry/api` are captured by Sentry. See the option's docs for the caveats.\n if (options.enableOpenTelemetrySetup) {\n setupOpenTelemetryTracer();\n }\n\n return initBaseSdk(options);\n}\n\n/**\n * `wrapRequestHandler` backed by `init`, so the request honors `enableOpenTelemetrySetup`. The\n * `@sentry/cloudflare/request` variant deliberately skips it to stay usable without `nodejs_compat`.\n *\n * For framework SDKs building on the main entry point, e.g. SvelteKit, whose OpenTelemetry spans\n * need the tracer provider.\n *\n * @internal\n */\nexport function _INTERNAL_wrapRequestHandler(\n wrapperOptions: RequestHandlerWrapperOptions,\n handler: (...args: unknown[]) => Response | Promise<Response>,\n): Promise<Response> {\n return wrapRequestHandlerWithInit(wrapperOptions, handler, init);\n}\n"],"names":["setupOpenTelemetryTracer","initBaseSdk","wrapRequestHandlerWithInit"],"mappings":";;;;;;AAaO,SAAS,KAAK,OAAA,EAA0D;AAG7E,EAAA,OAAA,CAAQ,wBAAA,KAAR,QAAQ,wBAAA,GAA6B,KAAA,CAAA;AAIrC,EAAA,IAAI,QAAQ,wBAAA,EAA0B;AACpC,IAAAA,+BAAA,EAAyB;AAAA,EAC3B;AAEA,EAAA,OAAOC,oBAAY,OAAO,CAAA;AAC5B;AAWO,SAAS,4BAAA,CACd,gBACA,OAAA,EACmB;AACnB,EAAA,OAAOC,qDAAA,CAA2B,cAAA,EAAgB,OAAA,EAAS,IAAI,CAAA;AACjE;;;;;;"}
@@ -11,7 +11,8 @@ function sentryCloudflareVitePlugin(options = {}) {
11
11
  buildTimeInstrumentation: options.buildTimeInstrumentation,
12
12
  // Route the injected `tracingChannel` imports through the workerd-safe façade so a
13
13
  // dependency wrapped at module scope (`const app = new Hono()`) doesn't throw on workerd.
14
- dcModule: "@sentry/cloudflare/orchestrion-diagnostics-channel"
14
+ dcModule: "@sentry/cloudflare/orchestrion-diagnostics-channel",
15
+ transformOptimizedDeps: true
15
16
  }),
16
17
  mastraObservability.sentryMastraObservabilityProviderPlugin(),
17
18
  flueRuntime.sentryFlueRuntimeProviderPlugin(),
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../../src/vite/index.ts"],"sourcesContent":["// Published ESM-only via the `@sentry/cloudflare/vite` subpath export:\n// `@sentry/server-utils/orchestrion/vite` exposes no `require` condition, so a\n// CJS entry here would fail at resolution time (ERR_PACKAGE_PATH_NOT_EXPORTED).\n// The CJS rollup variant still emits this file, but `package.json` doesn't\n// expose it — same setup as `@sentry/server-utils/orchestrion/vite` itself.\nimport { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';\nimport { sentryCloudflareAutoInstrumentPlugin } from './autoInstrument';\nimport { sentryFlueRuntimeProviderPlugin } from './flueRuntime';\nimport { sentryMastraObservabilityProviderPlugin } from './mastraObservability';\n\n/**\n * Options for {@link sentryCloudflareVitePlugin}.\n */\nexport interface SentryCloudflareVitePluginOptions {\n /**\n * Path to the wrangler config, relative to the Vite root (or absolute).\n * Set this when your config doesn't use a default name — e.g. when you\n * pass `configPath: './wrangler.agent.jsonc'` to `@cloudflare/vite-plugin`,\n * which the Sentry plugin cannot see. When set, only this file is read\n * (no default-name probing), and a warning is emitted if it is missing or\n * unparseable.\n *\n * @default undefined (probes `wrangler.json`, `wrangler.jsonc`, `wrangler.toml` at the Vite root)\n */\n wranglerConfigPath?: string;\n /**\n * Build-time automatic instrumentation of supported dependencies (e.g.\n * database clients like `mysql`) so the Sentry Cloudflare SDK can trace them\n * without monkey-patching, which wouldn't work in workerd anyway.\n *\n * When enabled, the plugin injects `diagnostics_channel.tracingChannel` calls\n * into the bundled packages and, next to each, a snippet that registers the\n * matching Sentry channel-subscriber factory on the global marker, which the\n * SDK picks up in `Sentry.withSentry()`. Both `vite build` and `vite dev` are\n * instrumented. Set to `false` to opt out.\n *\n * @default true\n */\n buildTimeInstrumentation?: boolean;\n /**\n * Automatically wraps your Worker at build time so you don't have to edit\n * your entry: the plugin reads your wrangler config, wraps the default\n * export with `Sentry.withSentry()` (sourcing options from a co-located\n * `instrument.*` file, falling back to env), and wraps any configured\n * Durable Object class with `instrumentDurableObjectWithSentry`. Both\n * `vite build` and `vite dev` are instrumented. Already-wrapped entries are\n * left alone, so this is safe alongside manual instrumentation. Set to\n * `false` to opt out.\n *\n * The plugin also adds the bindings that resolve to the wrapped classes (this worker's own\n * Durable Objects and self service bindings) to `rpcTracePropagationBindings`. Bindings to\n * other workers stay opt-in, their receivers may not run Sentry.\n *\n * @default true\n */\n autoInstrumentation?: boolean;\n}\n\n/**\n * Sentry Vite plugin for Cloudflare Workers.\n *\n * Add this plugin to your Vite configuration to enable additional Sentry\n * instrumentation for Cloudflare Workers built with Vite.\n *\n * By default, the plugin\n * - build-time instruments supported dependencies (such as database clients) so\n * they are traced without changing your application code — opt out with\n * `buildTimeInstrumentation: false`, and\n * - wraps your Worker entry (and any Durable Object, Workflow or\n * WorkerEntrypoint class in your wrangler config) with the matching Sentry\n * helper — opt out with `autoInstrumentation: false` and call\n * `Sentry.withSentry()` yourself.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { cloudflare } from '@cloudflare/vite-plugin';\n * import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite';\n * import { defineConfig } from 'vite';\n *\n * export default defineConfig({\n * plugins: [cloudflare(), sentryCloudflareVitePlugin()],\n * });\n * ```\n */\nexport function sentryCloudflareVitePlugin(options: SentryCloudflareVitePluginOptions = {}): Array<{ name: string }> {\n return [\n sentryOrchestrionPlugin({\n buildTimeInstrumentation: options.buildTimeInstrumentation,\n // Route the injected `tracingChannel` imports through the workerd-safe façade so a\n // dependency wrapped at module scope (`const app = new Hono()`) doesn't throw on workerd.\n dcModule: '@sentry/cloudflare/orchestrion-diagnostics-channel',\n }),\n sentryMastraObservabilityProviderPlugin(),\n sentryFlueRuntimeProviderPlugin(),\n ...(options.autoInstrumentation !== false\n ? [sentryCloudflareAutoInstrumentPlugin({ wranglerConfigPath: options.wranglerConfigPath })]\n : []),\n ];\n}\n"],"names":["sentryOrchestrionPlugin","sentryMastraObservabilityProviderPlugin","sentryFlueRuntimeProviderPlugin","sentryCloudflareAutoInstrumentPlugin"],"mappings":";;;;;;;AAqFO,SAAS,0BAAA,CAA2B,OAAA,GAA6C,EAAC,EAA4B;AACnH,EAAA,OAAO;AAAA,IACLA,4BAAA,CAAwB;AAAA,MACtB,0BAA0B,OAAA,CAAQ,wBAAA;AAAA;AAAA;AAAA,MAGlC,QAAA,EAAU;AAAA,KACX,CAAA;AAAA,IACDC,2DAAA,EAAwC;AAAA,IACxCC,2CAAA,EAAgC;AAAA,IAChC,GAAI,OAAA,CAAQ,mBAAA,KAAwB,KAAA,GAChC,CAACC,mDAAA,CAAqC,EAAE,kBAAA,EAAoB,OAAA,CAAQ,kBAAA,EAAoB,CAAC,IACzF;AAAC,GACP;AACF;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../../../../src/vite/index.ts"],"sourcesContent":["// Published ESM-only via the `@sentry/cloudflare/vite` subpath export:\n// `@sentry/server-utils/orchestrion/vite` exposes no `require` condition, so a\n// CJS entry here would fail at resolution time (ERR_PACKAGE_PATH_NOT_EXPORTED).\n// The CJS rollup variant still emits this file, but `package.json` doesn't\n// expose it — same setup as `@sentry/server-utils/orchestrion/vite` itself.\nimport { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';\nimport { sentryCloudflareAutoInstrumentPlugin } from './autoInstrument';\nimport { sentryFlueRuntimeProviderPlugin } from './flueRuntime';\nimport { sentryMastraObservabilityProviderPlugin } from './mastraObservability';\n\n/**\n * Options for {@link sentryCloudflareVitePlugin}.\n */\nexport interface SentryCloudflareVitePluginOptions {\n /**\n * Path to the wrangler config, relative to the Vite root (or absolute).\n * Set this when your config doesn't use a default name — e.g. when you\n * pass `configPath: './wrangler.agent.jsonc'` to `@cloudflare/vite-plugin`,\n * which the Sentry plugin cannot see. When set, only this file is read\n * (no default-name probing), and a warning is emitted if it is missing or\n * unparseable.\n *\n * @default undefined (probes `wrangler.json`, `wrangler.jsonc`, `wrangler.toml` at the Vite root)\n */\n wranglerConfigPath?: string;\n /**\n * Build-time automatic instrumentation of supported dependencies (e.g.\n * database clients like `mysql`) so the Sentry Cloudflare SDK can trace them\n * without monkey-patching, which wouldn't work in workerd anyway.\n *\n * When enabled, the plugin injects `diagnostics_channel.tracingChannel` calls\n * into the bundled packages and, next to each, a snippet that registers the\n * matching Sentry channel-subscriber factory on the global marker, which the\n * SDK picks up in `Sentry.withSentry()`. Both `vite build` and `vite dev` are\n * instrumented. Set to `false` to opt out.\n *\n * @default true\n */\n buildTimeInstrumentation?: boolean;\n /**\n * Automatically wraps your Worker at build time so you don't have to edit\n * your entry: the plugin reads your wrangler config, wraps the default\n * export with `Sentry.withSentry()` (sourcing options from a co-located\n * `instrument.*` file, falling back to env), and wraps any configured\n * Durable Object class with `instrumentDurableObjectWithSentry`. Both\n * `vite build` and `vite dev` are instrumented. Already-wrapped entries are\n * left alone, so this is safe alongside manual instrumentation. Set to\n * `false` to opt out.\n *\n * The plugin also adds the bindings that resolve to the wrapped classes (this worker's own\n * Durable Objects and self service bindings) to `rpcTracePropagationBindings`. Bindings to\n * other workers stay opt-in, their receivers may not run Sentry.\n *\n * @default true\n */\n autoInstrumentation?: boolean;\n}\n\n/**\n * Sentry Vite plugin for Cloudflare Workers.\n *\n * Add this plugin to your Vite configuration to enable additional Sentry\n * instrumentation for Cloudflare Workers built with Vite.\n *\n * By default, the plugin\n * - build-time instruments supported dependencies (such as database clients) so\n * they are traced without changing your application code — opt out with\n * `buildTimeInstrumentation: false`, and\n * - wraps your Worker entry (and any Durable Object, Workflow or\n * WorkerEntrypoint class in your wrangler config) with the matching Sentry\n * helper — opt out with `autoInstrumentation: false` and call\n * `Sentry.withSentry()` yourself.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { cloudflare } from '@cloudflare/vite-plugin';\n * import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite';\n * import { defineConfig } from 'vite';\n *\n * export default defineConfig({\n * plugins: [cloudflare(), sentryCloudflareVitePlugin()],\n * });\n * ```\n */\nexport function sentryCloudflareVitePlugin(options: SentryCloudflareVitePluginOptions = {}): Array<{ name: string }> {\n return [\n sentryOrchestrionPlugin({\n buildTimeInstrumentation: options.buildTimeInstrumentation,\n // Route the injected `tracingChannel` imports through the workerd-safe façade so a\n // dependency wrapped at module scope (`const app = new Hono()`) doesn't throw on workerd.\n dcModule: '@sentry/cloudflare/orchestrion-diagnostics-channel',\n transformOptimizedDeps: true,\n }),\n sentryMastraObservabilityProviderPlugin(),\n sentryFlueRuntimeProviderPlugin(),\n ...(options.autoInstrumentation !== false\n ? [sentryCloudflareAutoInstrumentPlugin({ wranglerConfigPath: options.wranglerConfigPath })]\n : []),\n ];\n}\n"],"names":["sentryOrchestrionPlugin","sentryMastraObservabilityProviderPlugin","sentryFlueRuntimeProviderPlugin","sentryCloudflareAutoInstrumentPlugin"],"mappings":";;;;;;;AAqFO,SAAS,0BAAA,CAA2B,OAAA,GAA6C,EAAC,EAA4B;AACnH,EAAA,OAAO;AAAA,IACLA,4BAAA,CAAwB;AAAA,MACtB,0BAA0B,OAAA,CAAQ,wBAAA;AAAA;AAAA;AAAA,MAGlC,QAAA,EAAU,oDAAA;AAAA,MACV,sBAAA,EAAwB;AAAA,KACzB,CAAA;AAAA,IACDC,2DAAA,EAAwC;AAAA,IACxCC,2CAAA,EAAgC;AAAA,IAChC,GAAI,OAAA,CAAQ,mBAAA,KAAwB,KAAA,GAChC,CAACC,mDAAA,CAAqC,EAAE,kBAAA,EAAoB,OAAA,CAAQ,kBAAA,EAAoB,CAAC,IACzF;AAAC,GACP;AACF;;;;"}
@@ -59,12 +59,12 @@ class WrappedWorkflowStep {
59
59
  [attributes.SENTRY_OP]: op.FUNCTION,
60
60
  [attributes.CODE_FUNCTION_NAME]: name,
61
61
  "workflow.step.name": name,
62
- "cloudflare.workflow.timeout": config?.timeout,
63
- "cloudflare.workflow.retries.backoff": config?.retries?.backoff,
62
+ [attributes.CLOUDFLARE_WORKFLOW_TIMEOUT]: config?.timeout,
63
+ [attributes.CLOUDFLARE_WORKFLOW_RETRIES_BACKOFF]: config?.retries?.backoff,
64
64
  // In workers-types v5, `delay` may be a `WorkflowDelayFunction`, which isn't a valid span attribute value.
65
- "cloudflare.workflow.retries.delay": typeof config?.retries?.delay === "function" ? void 0 : config?.retries?.delay,
66
- "cloudflare.workflow.retries.limit": config?.retries?.limit,
67
- "cloudflare.workflow.attempt": attempt,
65
+ [attributes.CLOUDFLARE_WORKFLOW_RETRIES_DELAY]: typeof config?.retries?.delay === "function" ? void 0 : config?.retries?.delay,
66
+ [attributes.CLOUDFLARE_WORKFLOW_RETRIES_LIMIT]: config?.retries?.limit,
67
+ [attributes.CLOUDFLARE_WORKFLOW_ATTEMPT]: attempt,
68
68
  [attributes.SENTRY_ORIGIN]: "auto.faas.cloudflare.workflow",
69
69
  [attributes.SENTRY_SEGMENT_NAME_SOURCE]: "task"
70
70
  }
@@ -1 +1 @@
1
- {"version":3,"file":"workflows.js","sources":["../../../src/workflows.ts"],"sourcesContent":["import {\n SENTRY_SEGMENT_NAME_SOURCE,\n CODE_FUNCTION_NAME,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { FUNCTION } from '@sentry/conventions/op';\nimport type { PropagationContext, Scope } from '@sentry/core';\nimport { captureException, flush, getCurrentScope, startSpan, withIsolationScope, withScope } from '@sentry/core';\nimport type {\n WorkflowDelayDuration,\n WorkflowEntrypoint,\n WorkflowEvent,\n WorkflowSleepDuration,\n WorkflowStep,\n WorkflowStepConfig,\n WorkflowStepContext,\n WorkflowStepEvent,\n WorkflowStepRollbackOptions,\n WorkflowTimeoutDuration,\n} from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategyForWorker } from './utils/asyncContextStrategy';\nimport type { CloudflareOptions } from './client';\nimport { flushAndDispose, getOriginalWaitUntil } from './flush';\nimport { markAsInstrumented } from './instrument';\nimport { instrumentEnv } from './instrumentations/worker/instrumentEnv';\nimport { addCloudResourceContext } from './scope-utils';\nimport { init } from './sdk';\nimport { instrumentContext } from './utils/instrumentContext';\nimport type { DefaultEnv, ResolveEnv, StrictCloudflareOptions } from './types';\nimport { getInvocationState } from './utils/invocationContext';\nimport { withInvocationIsolationScope } from './utils/invocationScope';\n\nconst UUID_REGEX = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i;\n\n/**\n * Hashes a string to a UUID using SHA-1.\n */\nexport async function deterministicTraceIdFromInstanceId(instanceId: string): Promise<string> {\n const buf = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(instanceId));\n return (\n Array.from(new Uint8Array(buf))\n // We only need the first 16 bytes for the 32 characters\n .slice(0, 16)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('')\n );\n}\n\nasync function propagationContextFromInstanceId(instanceId: string): Promise<PropagationContext> {\n const traceId = UUID_REGEX.test(instanceId)\n ? instanceId.replace(/-/g, '')\n : await deterministicTraceIdFromInstanceId(instanceId);\n\n // Derive sampleRand from last 4 characters of the random UUID\n //\n // We cannot store any state between workflow steps, so we derive the\n // sampleRand from the traceId itself. This ensures that the sampling is\n // consistent across all steps in the same workflow instance.\n const sampleRand = parseInt(traceId.slice(-4), 16) / 0xffff;\n\n return {\n traceId,\n sampleRand,\n };\n}\n\nclass WrappedWorkflowStep implements WorkflowStep {\n public constructor(\n private _instanceId: string,\n private _options: CloudflareOptions,\n private _step: WorkflowStep,\n private _waitUntil: ExecutionContext['waitUntil'],\n private _isolationScope: Scope,\n ) {}\n\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n callback: (ctx: WorkflowStepContext) => Promise<T>,\n rollbackOptions?: WorkflowStepRollbackOptions<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>, const C extends WorkflowStepConfig>(\n name: string,\n config: C,\n callback: (\n ctx: WorkflowStepContext<C['retries'] extends { delay: infer D } ? D : WorkflowDelayDuration | number>,\n ) => Promise<T>,\n rollbackOptions?: WorkflowStepRollbackOptions<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n configOrCallback: WorkflowStepConfig | ((ctx: WorkflowStepContext) => Promise<T>),\n callbackOrRollback?: ((ctx: WorkflowStepContext) => Promise<T>) | WorkflowStepRollbackOptions<T>,\n maybeRollback?: WorkflowStepRollbackOptions<T>,\n ): Promise<T> {\n // Capture the current scope, so parent span (e.g., a startSpan surrounding step.do) is preserved\n const scopeForStep = getCurrentScope();\n\n const hasConfig = typeof configOrCallback !== 'function';\n const config = hasConfig ? configOrCallback : undefined;\n const userCallback = (hasConfig ? callbackOrRollback : configOrCallback) as (\n ctx: WorkflowStepContext,\n ) => Promise<T>;\n const rollbackOptions = (hasConfig ? maybeRollback : callbackOrRollback) as\n | WorkflowStepRollbackOptions<T>\n | undefined;\n\n const instrumentedCallback = async (...args: unknown[]): Promise<T> => {\n // Feature detection: Cloudflare Workflows (April 2026+) pass a step context\n // with `attempt` and `config.retries.limit`. When available, we only capture\n // errors on the final attempt to avoid duplicates during retries.\n const stepContext = args[0] as { attempt?: number; config?: { retries?: { limit?: number } } } | undefined;\n const attempt = stepContext?.attempt;\n const retryLimit = stepContext?.config?.retries?.limit;\n const hasStepContext = typeof attempt === 'number' && typeof retryLimit === 'number';\n\n // Only capture error on final attempt (attempt > retryLimit means no more retries left)\n // or when step context is unavailable (legacy behavior - capture all errors)\n const isFinalAttempt = !hasStepContext || attempt > retryLimit;\n\n // The engine invokes step callbacks outside the async context of `run`, so the\n // run's isolation scope (and with it the invocation state that ties eager sends\n // to this invocation's `waitUntil`) has to be restored explicitly.\n return withIsolationScope(this._isolationScope, () => {\n const invocationState = getInvocationState();\n\n if (invocationState) {\n invocationState.flushPointReached = false;\n }\n\n const stepResult = startSpan(\n {\n name,\n scope: scopeForStep,\n attributes: {\n [SENTRY_OP]: FUNCTION,\n [CODE_FUNCTION_NAME]: name,\n 'workflow.step.name': name,\n 'cloudflare.workflow.timeout': config?.timeout,\n 'cloudflare.workflow.retries.backoff': config?.retries?.backoff,\n // In workers-types v5, `delay` may be a `WorkflowDelayFunction`, which isn't a valid span attribute value.\n 'cloudflare.workflow.retries.delay':\n typeof config?.retries?.delay === 'function' ? undefined : config?.retries?.delay,\n 'cloudflare.workflow.retries.limit': config?.retries?.limit,\n 'cloudflare.workflow.attempt': attempt,\n [SENTRY_ORIGIN]: 'auto.faas.cloudflare.workflow',\n [SENTRY_SEGMENT_NAME_SOURCE]: 'task',\n },\n },\n async span => {\n try {\n const result = await (userCallback as (...args: unknown[]) => Promise<T>)(...args);\n span.setStatus({ code: 1 });\n return result;\n } catch (error) {\n if (isFinalAttempt) {\n captureException(error, { mechanism: { handled: true, type: 'auto.faas.cloudflare.workflow' } });\n }\n throw error;\n }\n },\n );\n // Deliver after the step span has ended, so the span rides this flush instead of\n // starting an eager drain (same ordering as `wrapMethodWithSentry`'s teardown). The flush runs on the\n // step's scope: the engine calls the step callback outside of `run()`, so the current scope here has\n // neither the client nor the run's trace, and envelopes without a DSC are dropped by Relay.\n return stepResult.then(\n result => {\n this._waitUntil(withScope(scopeForStep, () => flush(2000)));\n return result;\n },\n error => {\n this._waitUntil(withScope(scopeForStep, () => flush(2000)));\n throw error;\n },\n );\n });\n };\n\n if (config) {\n return rollbackOptions\n ? this._step.do(name, config, instrumentedCallback, rollbackOptions)\n : this._step.do(name, config, instrumentedCallback);\n }\n\n return rollbackOptions\n ? this._step.do(name, instrumentedCallback, rollbackOptions)\n : this._step.do(name, instrumentedCallback);\n }\n\n public async sleep(name: string, duration: WorkflowSleepDuration): Promise<void> {\n return this._step.sleep(name, duration);\n }\n\n public async sleepUntil(name: string, timestamp: Date | number): Promise<void> {\n return this._step.sleepUntil(name, timestamp);\n }\n\n public async waitForEvent<T extends Rpc.Serializable<T>>(\n name: string,\n options: { type: string; timeout?: WorkflowTimeoutDuration | number },\n ): Promise<WorkflowStepEvent<T>> {\n return this._step.waitForEvent<T>(name, options);\n }\n}\n\n/**\n * Instruments a Cloudflare Workflow class with Sentry.\n *\n * @example\n * ```typescript\n * const InstrumentedWorkflow = instrumentWorkflowWithSentry(\n * (env) => ({ dsn: env.SENTRY_DSN }),\n * MyWorkflowClass\n * );\n *\n * export default InstrumentedWorkflow;\n * ```\n *\n * @param optionsCallback - Function that returns Sentry options to initialize Sentry\n * @param WorkflowClass - The workflow class to instrument\n * @returns Instrumented workflow class with the same interface\n */\nexport function instrumentWorkflowWithSentry<\n E = DefaultEnv, // Environment type\n P = unknown, // Payload type\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends WorkflowEntrypoint<any, any> = WorkflowEntrypoint<E, P>, // WorkflowEntrypoint type\n // The constraint must not route through `T`: workers-types defaults `WorkflowEntrypoint`'s\n // `Env` to `unknown` (unlike `WorkerEntrypoint`/`DurableObject`, which default to\n // `Cloudflare.Env`), so a bare subclass would be rejected in a `wrangler types` project.\n // The callback env is resolved from the inferred constructor via `ResolveEnv` instead.\n // oxlint-disable-next-line typescript/no-explicit-any\n C extends new (ctx: ExecutionContext, env: any) => WorkflowEntrypoint<any, any> = new (\n ctx: ExecutionContext,\n // oxlint-disable-next-line typescript/no-explicit-any\n env: any,\n ) => T, // Constructor type of the WorkflowEntrypoint class\n O = unknown,\n>(optionsCallback: (env: ResolveEnv<C, E>) => StrictCloudflareOptions<O>, WorkFlowClass: C): C {\n const InstrumentedClass = new Proxy(WorkFlowClass, {\n // oxlint-disable-next-line typescript/no-explicit-any\n construct(target: C, args: [ctx: ExecutionContext, env: any], newTarget) {\n const [ctx, env] = args;\n const context = instrumentContext(ctx);\n const options = optionsCallback(env);\n args[0] = context;\n args[1] = instrumentEnv(env as Record<string, unknown>, options) as E;\n const instance = Reflect.construct(target, args, newTarget) as T;\n return new Proxy(instance, {\n get(obj, prop, receiver) {\n if (prop === 'run') {\n return async function (event: WorkflowEvent<P>, step: WorkflowStep): Promise<unknown> {\n setAsyncLocalStorageAsyncContextStrategyForWorker();\n\n return withInvocationIsolationScope(async isolationScope => {\n const waitUntil = getOriginalWaitUntil(context).bind(context);\n const client = init({ ...options, ctx: context, enableDedupe: false });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return withScope(async scope => {\n const propagationContext = await propagationContextFromInstanceId(event.instanceId);\n scope.setPropagationContext(propagationContext);\n\n try {\n return await obj.run.call(\n obj,\n event,\n new WrappedWorkflowStep(event.instanceId, options, step, waitUntil, isolationScope),\n );\n } finally {\n waitUntil(flushAndDispose(client));\n }\n });\n }, context);\n };\n }\n return Reflect.get(obj, prop, receiver);\n },\n });\n },\n });\n // Recognizable for `_INTERNAL_wrapUnlessInstrumented`, so auto-instrumentation never nests wrappers.\n markAsInstrumented(InstrumentedClass);\n return InstrumentedClass;\n}\n"],"names":["getCurrentScope","withIsolationScope","getInvocationState","startSpan","SENTRY_OP","FUNCTION","CODE_FUNCTION_NAME","SENTRY_ORIGIN","SENTRY_SEGMENT_NAME_SOURCE","captureException","withScope","flush","instrumentContext","instrumentEnv","setAsyncLocalStorageAsyncContextStrategyForWorker","withInvocationIsolationScope","getOriginalWaitUntil","init","addCloudResourceContext","flushAndDispose","markAsInstrumented"],"mappings":";;;;;;;;;;;;;;;AAiCA,MAAM,UAAA,GAAa,qEAAA;AAKnB,eAAsB,mCAAmC,UAAA,EAAqC;AAC5F,EAAA,MAAM,GAAA,GAAM,MAAM,MAAA,CAAO,MAAA,CAAO,MAAA,CAAO,OAAA,EAAS,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,UAAU,CAAC,CAAA;AACpF,EAAA,OACE,KAAA,CAAM,KAAK,IAAI,UAAA,CAAW,GAAG,CAAC,CAAA,CAE3B,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA,CACX,IAAI,CAAA,CAAA,KAAK,CAAA,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CAAE,KAAK,OAAO,CAAA;AAC5D,gBAAA,MAAM,MAAA,GAASC,SAAK,EAAE,GAAG,SAAS,GAAA,EAAK,OAAA,EAAS,YAAA,EAAc,KAAA,EAAO,CAAA;AACrE,gBAAA,cAAA,CAAe,UAAU,MAAM,CAAA;AAE/B,gBAAAC,kCAAA,CAAwB,cAAc,CAAA;AAEtC,gBAAA,OAAOR,cAAA,CAAU,OAAM,KAAA,KAAS;AAC9B,kBAAA,MAAM,kBAAA,GAAqB,MAAM,gCAAA,CAAiC,KAAA,CAAM,UAAU,CAAA;AAClF,kBAAA,KAAA,CAAM,sBAAsB,kBAAkB,CAAA;AAE9C,kBAAA,IAAI;AACF,oBAAA,OAAO,MAAM,IAAI,GAAA,CAAI,IAAA;AAAA,sBACnB,GAAA;AAAA,sBACA,KAAA;AAAA,sBACA,IAAI,mBAAA,CAAoB,KAAA,CAAM,YAAY,OAAA,EAAS,IAAA,EAAM,WAAW,cAAc;AAAA,qBACpF;AAAA,kBACF,CAAA,SAAE;AACA,oBAAA,SAAA,CAAUS,qBAAA,CAAgB,MAAM,CAAC,CAAA;AAAA,kBACnC;AAAA,gBACF,CAAC,CAAA;AAAA,cACH,GAAG,OAAO,CAAA;AAAA,YACZ,CAAA;AAAA,UACF;AACA,UAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,GAAA,EAAK,IAAA,EAAM,QAAQ,CAAA;AAAA,QACxC;AAAA,OACD,CAAA;AAAA,IACH;AAAA,GACD,CAAA;AAED,EAAAC,6BAAA,CAAmB,iBAAiB,CAAA;AACpC,EAAA,OAAO,iBAAA;AACT;;;;;"}
1
+ {"version":3,"file":"workflows.js","sources":["../../../src/workflows.ts"],"sourcesContent":["import {\n SENTRY_SEGMENT_NAME_SOURCE,\n CODE_FUNCTION_NAME,\n SENTRY_OP,\n SENTRY_ORIGIN,\n CLOUDFLARE_WORKFLOW_ATTEMPT,\n CLOUDFLARE_WORKFLOW_RETRIES_BACKOFF,\n CLOUDFLARE_WORKFLOW_RETRIES_DELAY,\n CLOUDFLARE_WORKFLOW_RETRIES_LIMIT,\n CLOUDFLARE_WORKFLOW_TIMEOUT,\n} from '@sentry/conventions/attributes';\nimport { FUNCTION } from '@sentry/conventions/op';\nimport type { PropagationContext, Scope } from '@sentry/core';\nimport { captureException, flush, getCurrentScope, startSpan, withIsolationScope, withScope } from '@sentry/core';\nimport type {\n WorkflowDelayDuration,\n WorkflowEntrypoint,\n WorkflowEvent,\n WorkflowSleepDuration,\n WorkflowStep,\n WorkflowStepConfig,\n WorkflowStepContext,\n WorkflowStepEvent,\n WorkflowStepRollbackOptions,\n WorkflowTimeoutDuration,\n} from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategyForWorker } from './utils/asyncContextStrategy';\nimport type { CloudflareOptions } from './client';\nimport { flushAndDispose, getOriginalWaitUntil } from './flush';\nimport { markAsInstrumented } from './instrument';\nimport { instrumentEnv } from './instrumentations/worker/instrumentEnv';\nimport { addCloudResourceContext } from './scope-utils';\nimport { init } from './sdk';\nimport { instrumentContext } from './utils/instrumentContext';\nimport type { DefaultEnv, ResolveEnv, StrictCloudflareOptions } from './types';\nimport { getInvocationState } from './utils/invocationContext';\nimport { withInvocationIsolationScope } from './utils/invocationScope';\n\nconst UUID_REGEX = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i;\n\n/**\n * Hashes a string to a UUID using SHA-1.\n */\nexport async function deterministicTraceIdFromInstanceId(instanceId: string): Promise<string> {\n const buf = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(instanceId));\n return (\n Array.from(new Uint8Array(buf))\n // We only need the first 16 bytes for the 32 characters\n .slice(0, 16)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('')\n );\n}\n\nasync function propagationContextFromInstanceId(instanceId: string): Promise<PropagationContext> {\n const traceId = UUID_REGEX.test(instanceId)\n ? instanceId.replace(/-/g, '')\n : await deterministicTraceIdFromInstanceId(instanceId);\n\n // Derive sampleRand from last 4 characters of the random UUID\n //\n // We cannot store any state between workflow steps, so we derive the\n // sampleRand from the traceId itself. This ensures that the sampling is\n // consistent across all steps in the same workflow instance.\n const sampleRand = parseInt(traceId.slice(-4), 16) / 0xffff;\n\n return {\n traceId,\n sampleRand,\n };\n}\n\nclass WrappedWorkflowStep implements WorkflowStep {\n public constructor(\n private _instanceId: string,\n private _options: CloudflareOptions,\n private _step: WorkflowStep,\n private _waitUntil: ExecutionContext['waitUntil'],\n private _isolationScope: Scope,\n ) {}\n\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n callback: (ctx: WorkflowStepContext) => Promise<T>,\n rollbackOptions?: WorkflowStepRollbackOptions<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>, const C extends WorkflowStepConfig>(\n name: string,\n config: C,\n callback: (\n ctx: WorkflowStepContext<C['retries'] extends { delay: infer D } ? D : WorkflowDelayDuration | number>,\n ) => Promise<T>,\n rollbackOptions?: WorkflowStepRollbackOptions<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n configOrCallback: WorkflowStepConfig | ((ctx: WorkflowStepContext) => Promise<T>),\n callbackOrRollback?: ((ctx: WorkflowStepContext) => Promise<T>) | WorkflowStepRollbackOptions<T>,\n maybeRollback?: WorkflowStepRollbackOptions<T>,\n ): Promise<T> {\n // Capture the current scope, so parent span (e.g., a startSpan surrounding step.do) is preserved\n const scopeForStep = getCurrentScope();\n\n const hasConfig = typeof configOrCallback !== 'function';\n const config = hasConfig ? configOrCallback : undefined;\n const userCallback = (hasConfig ? callbackOrRollback : configOrCallback) as (\n ctx: WorkflowStepContext,\n ) => Promise<T>;\n const rollbackOptions = (hasConfig ? maybeRollback : callbackOrRollback) as\n | WorkflowStepRollbackOptions<T>\n | undefined;\n\n const instrumentedCallback = async (...args: unknown[]): Promise<T> => {\n // Feature detection: Cloudflare Workflows (April 2026+) pass a step context\n // with `attempt` and `config.retries.limit`. When available, we only capture\n // errors on the final attempt to avoid duplicates during retries.\n const stepContext = args[0] as { attempt?: number; config?: { retries?: { limit?: number } } } | undefined;\n const attempt = stepContext?.attempt;\n const retryLimit = stepContext?.config?.retries?.limit;\n const hasStepContext = typeof attempt === 'number' && typeof retryLimit === 'number';\n\n // Only capture error on final attempt (attempt > retryLimit means no more retries left)\n // or when step context is unavailable (legacy behavior - capture all errors)\n const isFinalAttempt = !hasStepContext || attempt > retryLimit;\n\n // The engine invokes step callbacks outside the async context of `run`, so the\n // run's isolation scope (and with it the invocation state that ties eager sends\n // to this invocation's `waitUntil`) has to be restored explicitly.\n return withIsolationScope(this._isolationScope, () => {\n const invocationState = getInvocationState();\n\n if (invocationState) {\n invocationState.flushPointReached = false;\n }\n\n const stepResult = startSpan(\n {\n name,\n scope: scopeForStep,\n attributes: {\n [SENTRY_OP]: FUNCTION,\n [CODE_FUNCTION_NAME]: name,\n 'workflow.step.name': name,\n [CLOUDFLARE_WORKFLOW_TIMEOUT]: config?.timeout,\n [CLOUDFLARE_WORKFLOW_RETRIES_BACKOFF]: config?.retries?.backoff,\n // In workers-types v5, `delay` may be a `WorkflowDelayFunction`, which isn't a valid span attribute value.\n [CLOUDFLARE_WORKFLOW_RETRIES_DELAY]:\n typeof config?.retries?.delay === 'function' ? undefined : config?.retries?.delay,\n [CLOUDFLARE_WORKFLOW_RETRIES_LIMIT]: config?.retries?.limit,\n [CLOUDFLARE_WORKFLOW_ATTEMPT]: attempt,\n [SENTRY_ORIGIN]: 'auto.faas.cloudflare.workflow',\n [SENTRY_SEGMENT_NAME_SOURCE]: 'task',\n },\n },\n async span => {\n try {\n const result = await (userCallback as (...args: unknown[]) => Promise<T>)(...args);\n span.setStatus({ code: 1 });\n return result;\n } catch (error) {\n if (isFinalAttempt) {\n captureException(error, { mechanism: { handled: true, type: 'auto.faas.cloudflare.workflow' } });\n }\n throw error;\n }\n },\n );\n // Deliver after the step span has ended, so the span rides this flush instead of\n // starting an eager drain (same ordering as `wrapMethodWithSentry`'s teardown). The flush runs on the\n // step's scope: the engine calls the step callback outside of `run()`, so the current scope here has\n // neither the client nor the run's trace, and envelopes without a DSC are dropped by Relay.\n return stepResult.then(\n result => {\n this._waitUntil(withScope(scopeForStep, () => flush(2000)));\n return result;\n },\n error => {\n this._waitUntil(withScope(scopeForStep, () => flush(2000)));\n throw error;\n },\n );\n });\n };\n\n if (config) {\n return rollbackOptions\n ? this._step.do(name, config, instrumentedCallback, rollbackOptions)\n : this._step.do(name, config, instrumentedCallback);\n }\n\n return rollbackOptions\n ? this._step.do(name, instrumentedCallback, rollbackOptions)\n : this._step.do(name, instrumentedCallback);\n }\n\n public async sleep(name: string, duration: WorkflowSleepDuration): Promise<void> {\n return this._step.sleep(name, duration);\n }\n\n public async sleepUntil(name: string, timestamp: Date | number): Promise<void> {\n return this._step.sleepUntil(name, timestamp);\n }\n\n public async waitForEvent<T extends Rpc.Serializable<T>>(\n name: string,\n options: { type: string; timeout?: WorkflowTimeoutDuration | number },\n ): Promise<WorkflowStepEvent<T>> {\n return this._step.waitForEvent<T>(name, options);\n }\n}\n\n/**\n * Instruments a Cloudflare Workflow class with Sentry.\n *\n * @example\n * ```typescript\n * const InstrumentedWorkflow = instrumentWorkflowWithSentry(\n * (env) => ({ dsn: env.SENTRY_DSN }),\n * MyWorkflowClass\n * );\n *\n * export default InstrumentedWorkflow;\n * ```\n *\n * @param optionsCallback - Function that returns Sentry options to initialize Sentry\n * @param WorkflowClass - The workflow class to instrument\n * @returns Instrumented workflow class with the same interface\n */\nexport function instrumentWorkflowWithSentry<\n E = DefaultEnv, // Environment type\n P = unknown, // Payload type\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends WorkflowEntrypoint<any, any> = WorkflowEntrypoint<E, P>, // WorkflowEntrypoint type\n // The constraint must not route through `T`: workers-types defaults `WorkflowEntrypoint`'s\n // `Env` to `unknown` (unlike `WorkerEntrypoint`/`DurableObject`, which default to\n // `Cloudflare.Env`), so a bare subclass would be rejected in a `wrangler types` project.\n // The callback env is resolved from the inferred constructor via `ResolveEnv` instead.\n // oxlint-disable-next-line typescript/no-explicit-any\n C extends new (ctx: ExecutionContext, env: any) => WorkflowEntrypoint<any, any> = new (\n ctx: ExecutionContext,\n // oxlint-disable-next-line typescript/no-explicit-any\n env: any,\n ) => T, // Constructor type of the WorkflowEntrypoint class\n O = unknown,\n>(optionsCallback: (env: ResolveEnv<C, E>) => StrictCloudflareOptions<O>, WorkFlowClass: C): C {\n const InstrumentedClass = new Proxy(WorkFlowClass, {\n // oxlint-disable-next-line typescript/no-explicit-any\n construct(target: C, args: [ctx: ExecutionContext, env: any], newTarget) {\n const [ctx, env] = args;\n const context = instrumentContext(ctx);\n const options = optionsCallback(env);\n args[0] = context;\n args[1] = instrumentEnv(env as Record<string, unknown>, options) as E;\n const instance = Reflect.construct(target, args, newTarget) as T;\n return new Proxy(instance, {\n get(obj, prop, receiver) {\n if (prop === 'run') {\n return async function (event: WorkflowEvent<P>, step: WorkflowStep): Promise<unknown> {\n setAsyncLocalStorageAsyncContextStrategyForWorker();\n\n return withInvocationIsolationScope(async isolationScope => {\n const waitUntil = getOriginalWaitUntil(context).bind(context);\n const client = init({ ...options, ctx: context, enableDedupe: false });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return withScope(async scope => {\n const propagationContext = await propagationContextFromInstanceId(event.instanceId);\n scope.setPropagationContext(propagationContext);\n\n try {\n return await obj.run.call(\n obj,\n event,\n new WrappedWorkflowStep(event.instanceId, options, step, waitUntil, isolationScope),\n );\n } finally {\n waitUntil(flushAndDispose(client));\n }\n });\n }, context);\n };\n }\n return Reflect.get(obj, prop, receiver);\n },\n });\n },\n });\n // Recognizable for `_INTERNAL_wrapUnlessInstrumented`, so auto-instrumentation never nests wrappers.\n markAsInstrumented(InstrumentedClass);\n return InstrumentedClass;\n}\n"],"names":["getCurrentScope","withIsolationScope","getInvocationState","startSpan","SENTRY_OP","FUNCTION","CODE_FUNCTION_NAME","CLOUDFLARE_WORKFLOW_TIMEOUT","CLOUDFLARE_WORKFLOW_RETRIES_BACKOFF","CLOUDFLARE_WORKFLOW_RETRIES_DELAY","CLOUDFLARE_WORKFLOW_RETRIES_LIMIT","CLOUDFLARE_WORKFLOW_ATTEMPT","SENTRY_ORIGIN","SENTRY_SEGMENT_NAME_SOURCE","captureException","withScope","flush","instrumentContext","instrumentEnv","setAsyncLocalStorageAsyncContextStrategyForWorker","withInvocationIsolationScope","getOriginalWaitUntil","init","addCloudResourceContext","flushAndDispose","markAsInstrumented"],"mappings":";;;;;;;;;;;;;;;AAsCA,MAAM,UAAA,GAAa,qEAAA;AAKnB,eAAsB,mCAAmC,UAAA,EAAqC;AAC5F,EAAA,MAAM,GAAA,GAAM,MAAM,MAAA,CAAO,MAAA,CAAO,MAAA,CAAO,OAAA,EAAS,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,UAAU,CAAC,CAAA;AACpF,EAAA,OACE,KAAA,CAAM,KAAK,IAAI,UAAA,CAAW,GAAG,CAAC,CAAA,CAE3B,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA,CACX,IAAI,CAAA,CAAA,KAAK,CAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,QAAA,CAAS,GAAG,GAAG,CAAC,CAAA,CACxC,IAAA,CAAK,EAAE,CAAA;AAEd;AAEA,eAAe,iCAAiC,UAAA,EAAiD;AAC/F,EAAA,MAAM,OAAA,GAAU,UAAA,CAAW,IAAA,CAAK,UAAU,CAAA,GACtC,UAAA,CAAW,OAAA,CAAQ,IAAA,EAAM,EAAE,CAAA,GAC3B,MAAM,kCAAA,CAAmC,UAAU,CAAA;AAOvD,EAAA,MAAM,aAAa,QAAA,CAAS,OAAA,CAAQ,MAAM,EAAE,CAAA,EAAG,EAAE,CAAA,GAAI,KAAA;AAErD,EAAA,OAAO;AAAA,IACL,OAAA;AAAA,IACA;AAAA,GACF;AACF;AAEA,MAAM,mBAAA,CAA4C;AAAA,EACzC,WAAA,CACG,WAAA,EACA,QAAA,E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BACnB,GAAA;AAAA,sBACA,KAAA;AAAA,sBACA,IAAI,mBAAA,CAAoB,KAAA,CAAM,YAAY,OAAA,EAAS,IAAA,EAAM,WAAW,cAAc;AAAA,qBACpF;AAAA,kBACF,CAAA,SAAE;AACA,oBAAA,SAAA,CAAUS,qBAAA,CAAgB,MAAM,CAAC,CAAA;AAAA,kBACnC;AAAA,gBACF,CAAC,CAAA;AAAA,cACH,GAAG,OAAO,CAAA;AAAA,YACZ,CAAA;AAAA,UACF;AACA,UAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,GAAA,EAAK,IAAA,EAAM,QAAQ,CAAA;AAAA,QACxC;AAAA,OACD,CAAA;AAAA,IACH;AAAA,GACD,CAAA;AAED,EAAAC,6BAAA,CAAmB,iBAAiB,CAAA;AACpC,EAAA,OAAO,iBAAA;AACT;;;;;"}
@@ -1,9 +1,8 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
 
3
3
  const attributes = require('@sentry/conventions/attributes');
4
- const op = require('@sentry/conventions/op');
5
4
  const core = require('@sentry/core');
6
- const server = require('@sentry/core/server');
5
+ const requestHandler = require('@sentry/server-utils/request-handler');
7
6
  const debugBuild = require('./debug-build.js');
8
7
  const httpServer = require('./integrations/httpServer.js');
9
8
  const orchestrionDeferredChannels = require('./orchestrion-deferred-channels.js');
@@ -21,37 +20,11 @@ function wrapRequestHandlerWithInit(wrapperOptions, handler, initSdk) {
21
20
  const context = wrapperOptions.context;
22
21
  const invocationState = invocationContext.getInvocationState();
23
22
  const waitUntil = invocationState ? invocationContext.getInvocationWaitUntil(invocationState) : context ? flush.getOriginalWaitUntil(context).bind(context) : void 0;
24
- const errorMechanismType = getRequestErrorMechanismType(context);
25
23
  const client = initSdk({ ...options, ctx: context });
26
24
  isolationScope.setClient(client);
27
25
  orchestrionDeferredChannels.flushDeferredChannelEvents();
28
- const urlObject = core.parseStringToURLObject(request.url);
29
- const [rawName, attributes$1] = core.getHttpSpanDetailsFromUrlObject(
30
- urlObject,
31
- "server",
32
- "auto.http.cloudflare",
33
- request,
34
- void 0,
35
- client
36
- );
37
- const name = attributes$1[attributes.SENTRY_SEGMENT_NAME_SOURCE] === "route" || !client || !core.hasSpanStreamingEnabled(client) ? rawName : request.method?.toUpperCase() || core.HTTP_SPAN_NAME_FALLBACK;
38
- const contentLength = request.headers.get("content-length");
39
- if (contentLength) {
40
- attributes$1["http.request.body.size"] = parseInt(contentLength, 10);
41
- }
42
- const userAgentHeader = request.headers.get("user-agent");
43
- if (userAgentHeader) {
44
- attributes$1["user_agent.original"] = userAgentHeader;
45
- }
46
- if (client) {
47
- Object.assign(
48
- attributes$1,
49
- core.httpHeadersToSpanAttributes(core.winterCGHeadersToDict(request.headers), client.getDataCollectionOptions())
50
- );
51
- }
52
- attributes$1[attributes.SENTRY_OP] = op.HTTP_SERVER;
53
26
  scopeUtils.addCloudResourceContext(isolationScope);
54
- scopeUtils.addRequest(isolationScope, request);
27
+ const attributes$1 = {};
55
28
  if (request.cf) {
56
29
  scopeUtils.addCultureContext(isolationScope, request.cf);
57
30
  if (typeof request.cf.httpProtocol === "string") {
@@ -60,97 +33,42 @@ function wrapRequestHandlerWithInit(wrapperOptions, handler, initSdk) {
60
33
  attributes$1[attributes.NETWORK_PROTOCOL_VERSION] = protocolVersion;
61
34
  }
62
35
  }
63
- if (request.method === "OPTIONS" || request.method === "HEAD") {
36
+ if (!client) {
64
37
  try {
65
38
  return await handler();
66
- } catch (e) {
67
- if (captureErrors) {
68
- core.captureException(e, { mechanism: { handled: false, type: errorMechanismType } });
69
- }
70
- throw e;
71
39
  } finally {
72
40
  waitUntil?.(flush.flushAndDispose(client));
73
41
  }
74
42
  }
75
- if (client) {
76
- await httpServer.captureIncomingRequestBody(client, request);
77
- }
78
- const { onSpanCreated, onSpanEnd } = httpServer.getIncomingRequestSpanHooks(client);
79
- const respond = async (span) => {
80
- let res;
81
- try {
82
- res = await handler();
83
- if (span) {
84
- core.setHttpStatus(span, res.status);
85
- }
86
- } catch (e) {
87
- span?.end();
88
- if (captureErrors) {
89
- core.captureException(e, { mechanism: { handled: false, type: errorMechanismType } });
90
- }
91
- waitUntil?.(flush.flushAndDispose(client));
92
- throw e;
93
- }
94
- let ended = false;
95
- const endSpan = () => {
96
- if (ended) return;
97
- ended = true;
98
- if (span) {
99
- onSpanEnd(span, request, res);
100
- span.end();
101
- }
102
- };
103
- const userClassification = core.safeCallback(
104
- debugBuild.DEBUG_BUILD ? "Error in `isStreamingResponse`, using the default classification:" : "",
105
- () => options.isStreamingResponse?.(res, request),
106
- () => void 0
107
- );
108
- const isStreaming = typeof userClassification === "boolean" ? userClassification : server.classifyResponseStreaming(res).isStreaming;
109
- if (isStreaming && res.body) {
110
- try {
111
- let transformerUsed = false;
112
- const endSpanOnce = () => {
113
- if (ended) return;
114
- endSpan();
43
+ return requestHandler.wrapServerRequestHandler(
44
+ {
45
+ request,
46
+ client,
47
+ // Without `AsyncLocalStorage`, `withInvocationIsolationScope` does not fork, and the scope it
48
+ // passes in is not the current one. The request data has to go on the current scope, where
49
+ // events captured in the handler read it.
50
+ isolationScope: core.getIsolationScope(),
51
+ options: httpServer.getHttpServerRequestOptions(client),
52
+ origin: "auto.http.cloudflare",
53
+ mechanism: captureErrors ? { handled: false, type: getRequestErrorMechanismType(context) } : void 0,
54
+ attributes: attributes$1,
55
+ isStreamingResponse: (response) => {
56
+ const classification = core.safeCallback(
57
+ debugBuild.DEBUG_BUILD ? "Error in `isStreamingResponse`, using the default classification:" : "",
58
+ () => options.isStreamingResponse?.(response, request),
59
+ () => void 0
60
+ );
61
+ return typeof classification === "boolean" ? classification : void 0;
62
+ },
63
+ onDone: (response) => {
64
+ if (response?.status === 101) {
65
+ waitUntil?.(client.flush(2e3));
66
+ } else {
115
67
  waitUntil?.(flush.flushAndDispose(client));
116
- };
117
- const transform = new TransformStream({
118
- start() {
119
- transformerUsed = true;
120
- },
121
- flush() {
122
- endSpanOnce();
123
- },
124
- cancel() {
125
- endSpanOnce();
126
- }
127
- });
128
- if (transformerUsed) {
129
- return new Response(res.body.pipeThrough(transform), res);
130
68
  }
131
- } catch {
132
- }
133
- }
134
- endSpan();
135
- if (res.status === 101) {
136
- waitUntil?.(client?.flush(2e3));
137
- } else {
138
- waitUntil?.(flush.flushAndDispose(client));
139
- }
140
- return res;
141
- };
142
- const createSpan = httpServer.shouldCreateIncomingRequestSpan(client, request);
143
- return core.continueTrace(
144
- { sentryTrace: request.headers.get("sentry-trace") || "", baggage: request.headers.get("baggage") },
145
- () => {
146
- if (!createSpan) {
147
- return respond(void 0);
148
69
  }
149
- return core.startSpanManual({ name, attributes: attributes$1 }, (span) => {
150
- onSpanCreated(span, request);
151
- return respond(span);
152
- });
153
- }
70
+ },
71
+ () => handler()
154
72
  );
155
73
  }, wrapperOptions.context);
156
74
  }