@sentry/cloudflare 11.0.0-rc.0 → 11.0.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 (116) hide show
  1. package/build/cjs/dev/client.js +11 -4
  2. package/build/cjs/dev/client.js.map +1 -1
  3. package/build/cjs/dev/durableobject.js +26 -18
  4. package/build/cjs/dev/durableobject.js.map +1 -1
  5. package/build/cjs/dev/index.js +1 -1
  6. package/build/cjs/dev/instrumentations/instrumentDurableObjectNamespace.js +6 -0
  7. package/build/cjs/dev/instrumentations/instrumentDurableObjectNamespace.js.map +1 -1
  8. package/build/cjs/dev/instrumentations/worker/instrumentQueueProducer.js +2 -1
  9. package/build/cjs/dev/instrumentations/worker/instrumentQueueProducer.js.map +1 -1
  10. package/build/cjs/dev/integrations/fetch.js +3 -101
  11. package/build/cjs/dev/integrations/fetch.js.map +1 -1
  12. package/build/cjs/dev/transport.js +18 -4
  13. package/build/cjs/dev/transport.js.map +1 -1
  14. package/build/cjs/dev/vite/flueRuntime.js +15 -0
  15. package/build/cjs/dev/vite/flueRuntime.js.map +1 -0
  16. package/build/cjs/dev/vite/index.js +2 -0
  17. package/build/cjs/dev/vite/index.js.map +1 -1
  18. package/build/cjs/dev/vite/mastraObservability.js +6 -30
  19. package/build/cjs/dev/vite/mastraObservability.js.map +1 -1
  20. package/build/cjs/dev/vite/providedModulePlugin.js +53 -0
  21. package/build/cjs/dev/vite/providedModulePlugin.js.map +1 -0
  22. package/build/cjs/dev/workflows.js +7 -2
  23. package/build/cjs/dev/workflows.js.map +1 -1
  24. package/build/cjs/prod/client.js +11 -4
  25. package/build/cjs/prod/client.js.map +1 -1
  26. package/build/cjs/prod/durableobject.js +26 -18
  27. package/build/cjs/prod/durableobject.js.map +1 -1
  28. package/build/cjs/prod/index.js +1 -1
  29. package/build/cjs/prod/instrumentations/instrumentDurableObjectNamespace.js +6 -0
  30. package/build/cjs/prod/instrumentations/instrumentDurableObjectNamespace.js.map +1 -1
  31. package/build/cjs/prod/instrumentations/worker/instrumentQueueProducer.js +2 -1
  32. package/build/cjs/prod/instrumentations/worker/instrumentQueueProducer.js.map +1 -1
  33. package/build/cjs/prod/integrations/fetch.js +3 -101
  34. package/build/cjs/prod/integrations/fetch.js.map +1 -1
  35. package/build/cjs/prod/transport.js +18 -4
  36. package/build/cjs/prod/transport.js.map +1 -1
  37. package/build/cjs/prod/vite/flueRuntime.js +15 -0
  38. package/build/cjs/prod/vite/flueRuntime.js.map +1 -0
  39. package/build/cjs/prod/vite/index.js +2 -0
  40. package/build/cjs/prod/vite/index.js.map +1 -1
  41. package/build/cjs/prod/vite/mastraObservability.js +6 -30
  42. package/build/cjs/prod/vite/mastraObservability.js.map +1 -1
  43. package/build/cjs/prod/vite/providedModulePlugin.js +53 -0
  44. package/build/cjs/prod/vite/providedModulePlugin.js.map +1 -0
  45. package/build/cjs/prod/workflows.js +7 -2
  46. package/build/cjs/prod/workflows.js.map +1 -1
  47. package/build/esm/dev/client.js +11 -4
  48. package/build/esm/dev/client.js.map +1 -1
  49. package/build/esm/dev/durableobject.js +27 -19
  50. package/build/esm/dev/durableobject.js.map +1 -1
  51. package/build/esm/dev/index.js +2 -2
  52. package/build/esm/dev/instrumentations/instrumentDurableObjectNamespace.js +6 -0
  53. package/build/esm/dev/instrumentations/instrumentDurableObjectNamespace.js.map +1 -1
  54. package/build/esm/dev/instrumentations/worker/instrumentQueueProducer.js +2 -1
  55. package/build/esm/dev/instrumentations/worker/instrumentQueueProducer.js.map +1 -1
  56. package/build/esm/dev/integrations/fetch.js +4 -102
  57. package/build/esm/dev/integrations/fetch.js.map +1 -1
  58. package/build/esm/dev/package.json +1 -1
  59. package/build/esm/dev/transport.js +19 -5
  60. package/build/esm/dev/transport.js.map +1 -1
  61. package/build/esm/dev/vite/flueRuntime.js +13 -0
  62. package/build/esm/dev/vite/flueRuntime.js.map +1 -0
  63. package/build/esm/dev/vite/index.js +2 -0
  64. package/build/esm/dev/vite/index.js.map +1 -1
  65. package/build/esm/dev/vite/mastraObservability.js +7 -30
  66. package/build/esm/dev/vite/mastraObservability.js.map +1 -1
  67. package/build/esm/dev/vite/providedModulePlugin.js +50 -0
  68. package/build/esm/dev/vite/providedModulePlugin.js.map +1 -0
  69. package/build/esm/dev/workflows.js +7 -2
  70. package/build/esm/dev/workflows.js.map +1 -1
  71. package/build/esm/prod/client.js +11 -4
  72. package/build/esm/prod/client.js.map +1 -1
  73. package/build/esm/prod/durableobject.js +27 -19
  74. package/build/esm/prod/durableobject.js.map +1 -1
  75. package/build/esm/prod/index.js +2 -2
  76. package/build/esm/prod/instrumentations/instrumentDurableObjectNamespace.js +6 -0
  77. package/build/esm/prod/instrumentations/instrumentDurableObjectNamespace.js.map +1 -1
  78. package/build/esm/prod/instrumentations/worker/instrumentQueueProducer.js +2 -1
  79. package/build/esm/prod/instrumentations/worker/instrumentQueueProducer.js.map +1 -1
  80. package/build/esm/prod/integrations/fetch.js +4 -102
  81. package/build/esm/prod/integrations/fetch.js.map +1 -1
  82. package/build/esm/prod/package.json +1 -1
  83. package/build/esm/prod/transport.js +19 -5
  84. package/build/esm/prod/transport.js.map +1 -1
  85. package/build/esm/prod/vite/flueRuntime.js +13 -0
  86. package/build/esm/prod/vite/flueRuntime.js.map +1 -0
  87. package/build/esm/prod/vite/index.js +2 -0
  88. package/build/esm/prod/vite/index.js.map +1 -1
  89. package/build/esm/prod/vite/mastraObservability.js +7 -30
  90. package/build/esm/prod/vite/mastraObservability.js.map +1 -1
  91. package/build/esm/prod/vite/providedModulePlugin.js +50 -0
  92. package/build/esm/prod/vite/providedModulePlugin.js.map +1 -0
  93. package/build/esm/prod/workflows.js +7 -2
  94. package/build/esm/prod/workflows.js.map +1 -1
  95. package/build/types/client.d.ts +5 -3
  96. package/build/types/client.d.ts.map +1 -1
  97. package/build/types/durableobject.d.ts +3 -2
  98. package/build/types/durableobject.d.ts.map +1 -1
  99. package/build/types/index.d.ts +4 -2
  100. package/build/types/index.d.ts.map +1 -1
  101. package/build/types/instrumentations/instrumentDurableObjectNamespace.d.ts +1 -0
  102. package/build/types/instrumentations/instrumentDurableObjectNamespace.d.ts.map +1 -1
  103. package/build/types/instrumentations/worker/instrumentQueueProducer.d.ts.map +1 -1
  104. package/build/types/integrations/fetch.d.ts +1 -15
  105. package/build/types/integrations/fetch.d.ts.map +1 -1
  106. package/build/types/transport.d.ts +5 -0
  107. package/build/types/transport.d.ts.map +1 -1
  108. package/build/types/vite/flueRuntime.d.ts +12 -0
  109. package/build/types/vite/flueRuntime.d.ts.map +1 -0
  110. package/build/types/vite/index.d.ts.map +1 -1
  111. package/build/types/vite/mastraObservability.d.ts +8 -23
  112. package/build/types/vite/mastraObservability.d.ts.map +1 -1
  113. package/build/types/vite/providedModulePlugin.d.ts +62 -0
  114. package/build/types/vite/providedModulePlugin.d.ts.map +1 -0
  115. package/build/types/workflows.d.ts.map +1 -1
  116. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentQueueProducer.js","sources":["../../../../../src/instrumentations/worker/instrumentQueueProducer.ts"],"sourcesContent":["import type { MessageSendRequest, Queue, QueueSendBatchOptions, QueueSendOptions } from '@cloudflare/workers-types';\nimport { SENTRY_OP } from '@sentry/conventions/attributes';\nimport { QUEUE_PUBLISH } from '@sentry/conventions/op';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, startSpan } from '@sentry/core';\n\nconst ORIGIN = 'auto.faas.cloudflare.queue';\n\nfunction startPublishSpan<T>(\n options: {\n bindingName: string;\n bodySize: number | undefined;\n messageCount?: number;\n },\n callback: () => T,\n): T {\n const { bindingName, bodySize, messageCount } = options;\n\n return startSpan(\n {\n name: `send ${bindingName}`,\n attributes: {\n 'messaging.system': 'cloudflare',\n 'messaging.destination.name': bindingName,\n 'messaging.operation.type': 'send',\n 'messaging.operation.name': 'send',\n ...(messageCount !== undefined && { 'messaging.batch.message_count': messageCount }),\n 'messaging.message.body.size': bodySize,\n [SENTRY_OP]: QUEUE_PUBLISH,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: ORIGIN,\n },\n },\n callback,\n );\n}\n\nfunction getBodySize(body: unknown): number | undefined {\n if (body == null) {\n return undefined;\n }\n\n if (typeof body === 'string') {\n return new TextEncoder().encode(body).byteLength;\n }\n\n if (body instanceof ArrayBuffer) {\n return body.byteLength;\n }\n\n if (ArrayBuffer.isView(body)) {\n return body.byteLength;\n }\n\n try {\n return new TextEncoder().encode(JSON.stringify(body)).byteLength;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Wraps a Queue producer binding to create `queue.publish` spans on\n * `send` and `sendBatch` calls.\n *\n * The queue's own name is not available on the binding object, so we use\n * the env binding key (e.g. `MY_QUEUE`) as `messaging.destination.name`.\n */\nexport function instrumentQueueProducer<T extends Queue>(queue: T, bindingName: string): T {\n return new Proxy(queue, {\n get(target, prop, receiver) {\n if (prop === 'send') {\n const original = Reflect.get(target, prop, receiver) as Queue['send'];\n\n return function (this: unknown, message: unknown, options?: QueueSendOptions): ReturnType<Queue['send']> {\n return startPublishSpan({ bindingName, bodySize: getBodySize(message) }, () =>\n Reflect.apply(original, target, [message, options]),\n );\n };\n }\n\n if (prop === 'sendBatch') {\n const original = Reflect.get(target, prop, receiver) as Queue['sendBatch'];\n return function (\n this: unknown,\n messages: Iterable<MessageSendRequest>,\n options?: QueueSendBatchOptions,\n ): ReturnType<Queue['sendBatch']> {\n const messageArray = Array.from(messages);\n const totalBodySize = messageArray.reduce<number | undefined>((acc, m) => {\n const size = getBodySize(m.body);\n if (size === undefined) {\n return acc;\n }\n return (acc ?? 0) + size;\n }, undefined);\n\n return startPublishSpan({ bindingName, bodySize: totalBodySize, messageCount: messageArray.length }, () =>\n Reflect.apply(original, target, [messageArray, options]),\n );\n };\n }\n\n return Reflect.get(target, prop, receiver);\n },\n });\n}\n"],"names":[],"mappings":";;;;AAKA,MAAM,MAAA,GAAS,4BAAA;AAEf,SAAS,gBAAA,CACP,SAKA,QAAA,EACG;AACH,EAAA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AAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,IAAA,EAAM,QAAQ,CAAA;AAAA,IAC3C;AAAA,GACD,CAAA;AACH;;;;"}
1
+ {"version":3,"file":"instrumentQueueProducer.js","sources":["../../../../../src/instrumentations/worker/instrumentQueueProducer.ts"],"sourcesContent":["import type { MessageSendRequest, Queue, QueueSendBatchOptions, QueueSendOptions } from '@cloudflare/workers-types';\nimport { SENTRY_OP } from '@sentry/conventions/attributes';\nimport { QUEUE_PUBLISH } from '@sentry/conventions/op';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, startSpan } from '@sentry/core';\n\nconst ORIGIN = 'auto.faas.cloudflare.queue';\n\nfunction startPublishSpan<T>(\n options: {\n bindingName: string;\n bodySize: number | undefined;\n messageCount?: number;\n },\n callback: () => T,\n): T {\n const { bindingName, bodySize, messageCount } = options;\n\n return startSpan(\n {\n name: `send ${bindingName}`,\n attributes: {\n 'messaging.system': 'cloudflare',\n 'messaging.destination.name': bindingName,\n 'messaging.operation.type': 'send',\n 'messaging.operation.name': 'send',\n ...(messageCount !== undefined && { 'messaging.batch.message_count': messageCount }),\n 'messaging.message.body.size': bodySize,\n [SENTRY_OP]: QUEUE_PUBLISH,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: ORIGIN,\n },\n },\n callback,\n );\n}\n\nfunction getBodySize(body: unknown): number | undefined {\n if (body == null) {\n return undefined;\n }\n\n if (typeof body === 'string') {\n return new TextEncoder().encode(body).byteLength;\n }\n\n if (body instanceof ArrayBuffer) {\n return body.byteLength;\n }\n\n if (ArrayBuffer.isView(body)) {\n return body.byteLength;\n }\n\n try {\n return new TextEncoder().encode(JSON.stringify(body)).byteLength;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Wraps a Queue producer binding to create `queue.publish` spans on\n * `send` and `sendBatch` calls.\n *\n * The queue's own name is not available on the binding object, so we use\n * the env binding key (e.g. `MY_QUEUE`) as `messaging.destination.name`.\n */\nexport function instrumentQueueProducer<T extends Queue>(queue: T, bindingName: string): T {\n return new Proxy(queue, {\n get(target, prop, receiver) {\n if (prop === 'send') {\n const original = Reflect.get(target, prop, receiver) as Queue['send'];\n\n return function (this: unknown, message: unknown, options?: QueueSendOptions): ReturnType<Queue['send']> {\n return startPublishSpan({ bindingName, bodySize: getBodySize(message) }, () =>\n Reflect.apply(original, target, [message, options]),\n );\n };\n }\n\n if (prop === 'sendBatch') {\n const original = Reflect.get(target, prop, receiver) as Queue['sendBatch'];\n return function (\n this: unknown,\n messages: Iterable<MessageSendRequest>,\n options?: QueueSendBatchOptions,\n ): ReturnType<Queue['sendBatch']> {\n const messageArray = Array.from(messages);\n const totalBodySize = messageArray.reduce<number | undefined>((acc, m) => {\n const size = getBodySize(m.body);\n if (size === undefined) {\n return acc;\n }\n return (acc ?? 0) + size;\n }, undefined);\n\n return startPublishSpan({ bindingName, bodySize: totalBodySize, messageCount: messageArray.length }, () =>\n Reflect.apply(original, target, [messageArray, options]),\n );\n };\n }\n\n const value = Reflect.get(target, prop) as unknown;\n\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n}\n"],"names":[],"mappings":";;;;AAKA,MAAM,MAAA,GAAS,4BAAA;AAEf,SAAS,gBAAA,CACP,SAKA,QAAA,EACG;AACH,EAAA,MAAM,EAAE,WAAA,EAAa,QAAA,EAAU,YAAA,EAAa,GAAI,OAAA;AAEhD,EAAA,OAAO,SAAA;AAAA,IACL;AAAA,MACE,IAAA,EAAM,QAAQ,WAAW,CAAA,CAAA;AAAA,MACzB,UAAA,EAAY;AAAA,QACV,kBAAA,EAAoB,YAAA;AAAA,QACpB,4BAAA,EAA8B,WAAA;AAAA,QAC9B,0BAAA,EAA4B,MAAA;AAAA,QAC5B,0BAAA,EAA4B,MAAA;AAAA,QAC5B,GAAI,YAAA,KAAiB,MAAA,IAAa,EAAE,iCAAiC,YAAA,EAAa;AAAA,QAClF,6BAAA,EAA+B,QAAA;AAAA,QAC/B,CAAC,SAAS,GAAG,aAAA;AAAA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AEA,MAAA,IAAI,SAAS,WAAA,EAAa;AACxB,QAAA,MAAM,QAAA,GAAW,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,MAAM,QAAQ,CAAA;AACnD,QAAA,OAAO,SAEL,UACA,OAAA,EACgC;AAChC,UAAA,MAAM,YAAA,GAAe,KAAA,CAAM,IAAA,CAAK,QAAQ,CAAA;AACxC,UAAA,MAAM,aAAA,GAAgB,YAAA,CAAa,MAAA,CAA2B,CAAC,KAAK,CAAA,KAAM;AACxE,YAAA,MAAM,IAAA,GAAO,WAAA,CAAY,CAAA,CAAE,IAAI,CAAA;AAC/B,YAAA,IAAI,SAAS,MAAA,EAAW;AACtB,cAAA,OAAO,GAAA;AAAA,YACT;AACA,YAAA,OAAA,CAAQ,OAAO,CAAA,IAAK,IAAA;AAAA,UACtB,GAAG,MAAS,CAAA;AAEZ,UAAA,OAAO,gBAAA;AAAA,YAAiB,EAAE,WAAA,EAAa,QAAA,EAAU,aAAA,EAAe,YAAA,EAAc,aAAa,MAAA,EAAO;AAAA,YAAG,MACnG,QAAQ,KAAA,CAAM,QAAA,EAAU,QAAQ,CAAC,YAAA,EAAc,OAAO,CAAC;AAAA,WACzD;AAAA,QACF,CAAA;AAAA,MACF;AAEA,MAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,IAAI,CAAA;AAEtC,MAAA,OAAO,OAAO,KAAA,KAAU,UAAA,GAAa,KAAA,CAAM,IAAA,CAAK,MAAM,CAAA,GAAI,KAAA;AAAA,IAC5D;AAAA,GACD,CAAA;AACH;;;;"}
@@ -1,107 +1,9 @@
1
- import { defineIntegration, LRUMap, addFetchInstrumentationHandler, getClient, isSentryRequestUrl, instrumentFetchRequest, shouldPropagateTraceForUrl, addBreadcrumb, getBreadcrumbLogLevelFromHttpStatusCode } from '@sentry/core';
1
+ import { createFetchIntegration } from '@sentry/core';
2
2
 
3
- const INTEGRATION_NAME = "Fetch";
4
- const HAS_CLIENT_MAP = /* @__PURE__ */ new WeakMap();
5
- const _fetchIntegration = ((options = {}) => {
6
- const breadcrumbs = options.breadcrumbs === void 0 ? true : options.breadcrumbs;
7
- const shouldCreateSpanForRequest = options.shouldCreateSpanForRequest;
8
- const _createSpanUrlMap = new LRUMap(100);
9
- const _headersUrlMap = new LRUMap(100);
10
- const spans = {};
11
- function _shouldAttachTraceData(url) {
12
- const client = getClient();
13
- if (!client) {
14
- return false;
15
- }
16
- return shouldPropagateTraceForUrl(url, client.getOptions().tracePropagationTargets, _headersUrlMap);
17
- }
18
- function _shouldCreateSpan(url) {
19
- if (shouldCreateSpanForRequest === void 0) {
20
- return true;
21
- }
22
- const cachedDecision = _createSpanUrlMap.get(url);
23
- if (cachedDecision !== void 0) {
24
- return cachedDecision;
25
- }
26
- const decision = shouldCreateSpanForRequest(url);
27
- _createSpanUrlMap.set(url, decision);
28
- return decision;
29
- }
30
- return {
31
- name: INTEGRATION_NAME,
32
- setupOnce() {
33
- addFetchInstrumentationHandler((handlerData) => {
34
- const client = getClient();
35
- const { propagateTraceparent } = client?.getOptions() || {};
36
- if (!client || !HAS_CLIENT_MAP.get(client)) {
37
- return;
38
- }
39
- if (isSentryRequestUrl(handlerData.fetchData.url, client)) {
40
- return;
41
- }
42
- instrumentFetchRequest(handlerData, _shouldCreateSpan, _shouldAttachTraceData, spans, {
43
- spanOrigin: "auto.http.fetch",
44
- propagateTraceparent
45
- });
46
- if (breadcrumbs) {
47
- createBreadcrumb(handlerData);
48
- }
49
- });
50
- },
51
- setup(client) {
52
- HAS_CLIENT_MAP.set(client, true);
53
- }
54
- };
3
+ const fetchIntegration = createFetchIntegration({
4
+ name: "Fetch",
5
+ spanOrigin: "auto.http.fetch"
55
6
  });
56
- const fetchIntegration = defineIntegration(_fetchIntegration);
57
- function createBreadcrumb(handlerData) {
58
- const { startTimestamp, endTimestamp } = handlerData;
59
- if (!endTimestamp) {
60
- return;
61
- }
62
- const breadcrumbData = {
63
- method: handlerData.fetchData.method,
64
- url: handlerData.fetchData.url
65
- };
66
- if (handlerData.error) {
67
- const hint = {
68
- data: handlerData.error,
69
- input: handlerData.args,
70
- startTimestamp,
71
- endTimestamp
72
- };
73
- addBreadcrumb(
74
- {
75
- category: "fetch",
76
- data: breadcrumbData,
77
- level: "error",
78
- type: "http"
79
- },
80
- hint
81
- );
82
- } else {
83
- const response = handlerData.response;
84
- breadcrumbData.request_body_size = handlerData.fetchData.request_body_size;
85
- breadcrumbData.response_body_size = handlerData.fetchData.response_body_size;
86
- breadcrumbData.status_code = response?.status;
87
- const hint = {
88
- input: handlerData.args,
89
- response,
90
- startTimestamp,
91
- endTimestamp
92
- };
93
- const level = getBreadcrumbLogLevelFromHttpStatusCode(breadcrumbData.status_code);
94
- addBreadcrumb(
95
- {
96
- category: "fetch",
97
- data: breadcrumbData,
98
- type: "http",
99
- level
100
- },
101
- hint
102
- );
103
- }
104
- }
105
7
 
106
8
  export { fetchIntegration };
107
9
  //# sourceMappingURL=fetch.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.js","sources":["../../../../src/integrations/fetch.ts"],"sourcesContent":["import type {\n Client,\n FetchBreadcrumbData,\n FetchBreadcrumbHint,\n HandlerDataFetch,\n IntegrationFn,\n Span,\n} from '@sentry/core';\nimport {\n addBreadcrumb,\n addFetchInstrumentationHandler,\n defineIntegration,\n getBreadcrumbLogLevelFromHttpStatusCode,\n getClient,\n instrumentFetchRequest,\n isSentryRequestUrl,\n LRUMap,\n shouldPropagateTraceForUrl,\n} from '@sentry/core';\n\nconst INTEGRATION_NAME = 'Fetch' as const;\n\nconst HAS_CLIENT_MAP = new WeakMap<Client, boolean>();\n\nexport interface Options {\n /**\n * Whether breadcrumbs should be recorded for requests\n * Defaults to true\n */\n breadcrumbs: boolean;\n\n /**\n * Function determining whether or not to create spans to track outgoing requests to the given URL.\n * By default, spans will be created for all outgoing requests.\n */\n shouldCreateSpanForRequest?: (url: string) => boolean;\n}\n\nconst _fetchIntegration = ((options: Partial<Options> = {}) => {\n const breadcrumbs = options.breadcrumbs === undefined ? true : options.breadcrumbs;\n const shouldCreateSpanForRequest = options.shouldCreateSpanForRequest;\n\n const _createSpanUrlMap = new LRUMap<string, boolean>(100);\n const _headersUrlMap = new LRUMap<string, boolean>(100);\n\n const spans: Record<string, Span> = {};\n\n /** Decides whether to attach trace data to the outgoing fetch request */\n function _shouldAttachTraceData(url: string): boolean {\n const client = getClient();\n\n if (!client) {\n return false;\n }\n\n return shouldPropagateTraceForUrl(url, client.getOptions().tracePropagationTargets, _headersUrlMap);\n }\n\n /** Helper that wraps shouldCreateSpanForRequest option */\n function _shouldCreateSpan(url: string): boolean {\n if (shouldCreateSpanForRequest === undefined) {\n return true;\n }\n\n const cachedDecision = _createSpanUrlMap.get(url);\n if (cachedDecision !== undefined) {\n return cachedDecision;\n }\n\n const decision = shouldCreateSpanForRequest(url);\n _createSpanUrlMap.set(url, decision);\n return decision;\n }\n\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n addFetchInstrumentationHandler(handlerData => {\n const client = getClient();\n const { propagateTraceparent } = client?.getOptions() || {};\n if (!client || !HAS_CLIENT_MAP.get(client)) {\n return;\n }\n\n if (isSentryRequestUrl(handlerData.fetchData.url, client)) {\n return;\n }\n\n instrumentFetchRequest(handlerData, _shouldCreateSpan, _shouldAttachTraceData, spans, {\n spanOrigin: 'auto.http.fetch',\n propagateTraceparent,\n });\n\n if (breadcrumbs) {\n createBreadcrumb(handlerData);\n }\n });\n },\n setup(client) {\n HAS_CLIENT_MAP.set(client, true);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Creates spans and attaches tracing headers to fetch requests.\n */\nexport const fetchIntegration = defineIntegration(_fetchIntegration);\n\nfunction createBreadcrumb(handlerData: HandlerDataFetch): void {\n const { startTimestamp, endTimestamp } = handlerData;\n\n // We only capture complete fetch requests\n if (!endTimestamp) {\n return;\n }\n\n const breadcrumbData: FetchBreadcrumbData = {\n method: handlerData.fetchData.method,\n url: handlerData.fetchData.url,\n };\n\n if (handlerData.error) {\n const hint: FetchBreadcrumbHint = {\n data: handlerData.error,\n input: handlerData.args,\n startTimestamp,\n endTimestamp,\n };\n\n addBreadcrumb(\n {\n category: 'fetch',\n data: breadcrumbData,\n level: 'error',\n type: 'http',\n },\n hint,\n );\n } else {\n const response = handlerData.response as Response | undefined;\n\n breadcrumbData.request_body_size = handlerData.fetchData.request_body_size;\n breadcrumbData.response_body_size = handlerData.fetchData.response_body_size;\n breadcrumbData.status_code = response?.status;\n\n const hint: FetchBreadcrumbHint = {\n input: handlerData.args,\n response,\n startTimestamp,\n endTimestamp,\n };\n const level = getBreadcrumbLogLevelFromHttpStatusCode(breadcrumbData.status_code);\n\n addBreadcrumb(\n {\n category: 'fetch',\n data: breadcrumbData,\n type: 'http',\n level,\n },\n hint,\n );\n }\n}\n"],"names":[],"mappings":";;AAoBA,MAAM,gBAAA,GAAmB,OAAA;AAEzB,MAAM,cAAA,uBAAqB,OAAA,EAAyB;AAgBpD,MAAM,iBAAA,IAAqB,CAAC,OAAA,GAA4B,EAAC,KAAM;AAC7D,EAAA,MAAM,WAAA,GAAc,OAAA,CAAQ,WAAA,KAAgB,MAAA,GAAY,OAAO,OAAA,CAAQ,WAAA;AACvE,EAAA,MAAM,6BAA6B,OAAA,CAAQ,0BAAA;AAE3C,EAAA,MAAM,iBAAA,GAAoB,IAAI,MAAA,CAAwB,GAAG,CAAA;AACzD,EAAA,MAAM,cAAA,GAAiB,IAAI,MAAA,CAAwB,GAAG,CAAA;AAEtD,EAAA,MAAM,QAA8B,EAAC;AAGrC,EAAA,SAAS,uBAAuB,GAAA,EAAsB;AACpD,IAAA,MAAM,SAAS,SAAA,EAAU;AAEzB,IAAA,IAAI,CAAC,MAAA,EAAQ;AACX,MAAA,OAAO,KAAA;AAAA,IACT;AAEA,IAAA,OAAO,2BAA2B,GAAA,EAAK,MAAA,CAAO,UAAA,EAAW,CAAE,yBAAyB,cAAc,CAAA;AAAA,EACpG;AAGA,EAAA,SAAS,kBAAkB,G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,OACF;AAAA,MACA;AAAA,KACF;AAAA,EACF;AACF;;;;"}
1
+ {"version":3,"file":"fetch.js","sources":["../../../../src/integrations/fetch.ts"],"sourcesContent":["import { createFetchIntegration } from '@sentry/core';\n\n/**\n * Creates spans and attaches tracing headers to fetch requests.\n */\nexport const fetchIntegration = createFetchIntegration({\n name: 'Fetch',\n spanOrigin: 'auto.http.fetch',\n});\n"],"names":[],"mappings":";;AAKO,MAAM,mBAAmB,sBAAA,CAAuB;AAAA,EACrD,IAAA,EAAM,OAAA;AAAA,EACN,UAAA,EAAY;AACd,CAAC;;;;"}
@@ -1 +1 @@
1
- {"type":"module","version":"11.0.0-rc.0","sideEffects":false}
1
+ {"type":"module","version":"11.0.0","sideEffects":false}
@@ -1,4 +1,4 @@
1
- import { createTransport, suppressTracing, SENTRY_BUFFER_FULL_ERROR } from '@sentry/core';
1
+ import { createTransport, SENTRY_BUFFER_FULL_ERROR, suppressTracing } from '@sentry/core';
2
2
 
3
3
  const DEFAULT_TRANSPORT_BUFFER_SIZE = 256;
4
4
  class IsolatedPromiseBuffer {
@@ -23,15 +23,24 @@ class IsolatedPromiseBuffer {
23
23
  drain(timeout) {
24
24
  const oldTaskProducers = [...this._taskProducers];
25
25
  this._taskProducers = [];
26
+ const drainController = new AbortController();
27
+ this.drainSignal = drainController.signal;
28
+ let tasks;
29
+ try {
30
+ tasks = oldTaskProducers.map((taskProducer) => taskProducer());
31
+ } finally {
32
+ this.drainSignal = void 0;
33
+ }
26
34
  return new Promise((resolve) => {
27
35
  const timer = setTimeout(() => {
28
36
  if (timeout && timeout > 0) {
37
+ drainController.abort();
29
38
  resolve(false);
30
39
  }
31
40
  }, timeout);
32
41
  Promise.all(
33
- oldTaskProducers.map(
34
- (taskProducer) => taskProducer().then(null, () => {
42
+ tasks.map(
43
+ (task) => task.then(null, () => {
35
44
  })
36
45
  )
37
46
  ).then(() => {
@@ -42,12 +51,17 @@ class IsolatedPromiseBuffer {
42
51
  }
43
52
  }
44
53
  function makeCloudflareTransport(options) {
54
+ const buffer = new IsolatedPromiseBuffer(options.bufferSize);
45
55
  function makeRequest(request) {
56
+ const drainSignal = buffer.drainSignal;
57
+ const callerSignal = options.fetchOptions?.signal ?? void 0;
58
+ const signal = drainSignal && callerSignal ? AbortSignal.any([drainSignal, callerSignal]) : drainSignal ?? callerSignal;
46
59
  const requestOptions = {
47
60
  body: request.body,
48
61
  method: "POST",
49
62
  headers: options.headers,
50
- ...options.fetchOptions
63
+ ...options.fetchOptions,
64
+ ...signal ? { signal } : {}
51
65
  };
52
66
  return suppressTracing(() => {
53
67
  return (options.fetch ?? fetch)(options.url, requestOptions).then(async (response) => {
@@ -65,7 +79,7 @@ function makeCloudflareTransport(options) {
65
79
  });
66
80
  });
67
81
  }
68
- return createTransport(options, makeRequest, new IsolatedPromiseBuffer(options.bufferSize));
82
+ return createTransport(options, makeRequest, buffer);
69
83
  }
70
84
 
71
85
  export { IsolatedPromiseBuffer, makeCloudflareTransport };
@@ -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 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 return new Promise(resolve => {\n const timer = setTimeout(() => {\n if (timeout && timeout > 0) {\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 oldTaskProducers.map(taskProducer =>\n taskProducer().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 function makeRequest(request: TransportRequest): PromiseLike<TransportMakeRequestResponse> {\n const requestOptions: RequestInit = {\n body: request.body as BodyInit,\n method: 'POST',\n headers: options.headers,\n ...options.fetchOptions,\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, new IsolatedPromiseBuffer(options.bufferSize));\n}\n"],"names":[],"mappings":";;AAgBA,MAAM,6BAAA,GAAgC,GAAA;AAU/B,MAAM,qBAAA,CAAsB;AAAA,EAS1B,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,OAAO,wBAAwB,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,OAAO,IAAI,QAAQ,CAAA,OAAA,KAAW;AAC5B,MAAA,MAAM,KAAA,GAAQ,WAAW,MAAM;AAC7B,QAAA,IAAI,OAAA,IAAW,UAAU,CAAA,EAAG;AAC1B,UAAA,OAAA,CAAQ,KAAK,CAAA;A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A,CAAQ,UAAU,CAAC,CAAA;AAC5F;;;;"}
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":[],"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,OAAO,wBAAwB,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,IAAA,CAAK,cAAc,eAAA,CAAgB,MAAA;AACnC,IAAA,IAAI,KAAA;AACJ,IAAA,IAAI;AACF,MAAA,KAAA,GAAQ,gBAAA,CAAiB,GAAA,CAAI,CAAA,YAAA,KAAgB,YAAA,EAAc,CAAA;AAAA,IAC7D,CAAA,SAAE;AACA,MAAA,IAAA,C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AW;AAAC,KAC7B;AAEA,IAAA,OAAO,gBAAgB,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,OAAO,eAAA,CAAgB,OAAA,EAAS,WAAA,EAAa,MAAM,CAAA;AACrD;;;;"}
@@ -0,0 +1,13 @@
1
+ import { createProvidedModulePlugin } from './providedModulePlugin.js';
2
+
3
+ function sentryFlueRuntimeProviderPlugin() {
4
+ return createProvidedModulePlugin({
5
+ name: "sentry-cloudflare-flue-runtime-provider",
6
+ moduleName: "@flue/runtime",
7
+ identifier: "__SENTRY_FLUE_RUNTIME__",
8
+ integrationModule: "flue"
9
+ });
10
+ }
11
+
12
+ export { sentryFlueRuntimeProviderPlugin };
13
+ //# sourceMappingURL=flueRuntime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"flueRuntime.js","sources":["../../../../src/vite/flueRuntime.ts"],"sourcesContent":["import type { ProvidedModulePlugin } from './providedModulePlugin';\nimport { createProvidedModulePlugin } from './providedModulePlugin';\n\n/**\n * Splices a static `import * as … from '@flue/runtime'` into Sentry's own Flue integration module\n * and exposes the namespace on the global orchestrion marker.\n *\n * Flue is registered rather than patched — `instrument()` writes into module-scope state — so\n * instrumenting it needs that module's own binding, and no channel payload carries one. On Node the\n * user passes it by calling `instrument()` themselves; a bundled worker has no `node_modules` to\n * resolve from, so it is supplied at build time instead.\n */\nexport function sentryFlueRuntimeProviderPlugin(): ProvidedModulePlugin {\n return createProvidedModulePlugin({\n name: 'sentry-cloudflare-flue-runtime-provider',\n moduleName: '@flue/runtime',\n identifier: '__SENTRY_FLUE_RUNTIME__',\n integrationModule: 'flue',\n });\n}\n"],"names":[],"mappings":";;AAYO,SAAS,+BAAA,GAAwD;AACtE,EAAA,OAAO,0BAAA,CAA2B;AAAA,IAChC,IAAA,EAAM,yCAAA;AAAA,IACN,UAAA,EAAY,eAAA;AAAA,IACZ,UAAA,EAAY,yBAAA;AAAA,IACZ,iBAAA,EAAmB;AAAA,GACpB,CAAA;AACH;;;;"}
@@ -1,5 +1,6 @@
1
1
  import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';
2
2
  import { sentryCloudflareAutoInstrumentPlugin } from './autoInstrument.js';
3
+ import { sentryFlueRuntimeProviderPlugin } from './flueRuntime.js';
3
4
  import { sentryMastraObservabilityProviderPlugin } from './mastraObservability.js';
4
5
 
5
6
  function sentryCloudflareVitePlugin(options = {}) {
@@ -11,6 +12,7 @@ function sentryCloudflareVitePlugin(options = {}) {
11
12
  dcModule: "@sentry/cloudflare/orchestrion-diagnostics-channel"
12
13
  }),
13
14
  sentryMastraObservabilityProviderPlugin(),
15
+ sentryFlueRuntimeProviderPlugin(),
14
16
  ...options.autoInstrumentation !== false ? [sentryCloudflareAutoInstrumentPlugin({ wranglerConfigPath: options.wranglerConfigPath })] : []
15
17
  ];
16
18
  }
@@ -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 { 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 ...(options.autoInstrumentation !== false\n ? [sentryCloudflareAutoInstrumentPlugin({ wranglerConfigPath: options.wranglerConfigPath })]\n : []),\n ];\n}\n"],"names":[],"mappings":";;;;AAoFO,SAAS,0BAAA,CAA2B,OAAA,GAA6C,EAAC,EAA4B;AACnH,EAAA,OAAO;AAAA,IACL,uBAAA,CAAwB;AAAA,MACtB,0BAA0B,OAAA,CAAQ,wBAAA;AAAA;AAAA;AAAA,MAGlC,QAAA,EAAU;AAAA,KACX,CAAA;AAAA,IACD,uCAAA,EAAwC;AAAA,IACxC,GAAI,OAAA,CAAQ,mBAAA,KAAwB,KAAA,GAChC,CAAC,oCAAA,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 }),\n sentryMastraObservabilityProviderPlugin(),\n sentryFlueRuntimeProviderPlugin(),\n ...(options.autoInstrumentation !== false\n ? [sentryCloudflareAutoInstrumentPlugin({ wranglerConfigPath: options.wranglerConfigPath })]\n : []),\n ];\n}\n"],"names":[],"mappings":";;;;;AAqFO,SAAS,0BAAA,CAA2B,OAAA,GAA6C,EAAC,EAA4B;AACnH,EAAA,OAAO;AAAA,IACL,uBAAA,CAAwB;AAAA,MACtB,0BAA0B,OAAA,CAAQ,wBAAA;AAAA;AAAA;AAAA,MAGlC,QAAA,EAAU;AAAA,KACX,CAAA;AAAA,IACD,uCAAA,EAAwC;AAAA,IACxC,+BAAA,EAAgC;AAAA,IAChC,GAAI,OAAA,CAAQ,mBAAA,KAAwB,KAAA,GAChC,CAAC,oCAAA,CAAqC,EAAE,kBAAA,EAAoB,OAAA,CAAQ,kBAAA,EAAoB,CAAC,IACzF;AAAC,GACP;AACF;;;;"}
@@ -1,36 +1,13 @@
1
- import { createRequire } from 'node:module';
2
- import { resolve } from 'node:path';
3
- import MagicString from 'magic-string';
1
+ import { createProvidedModulePlugin } from './providedModulePlugin.js';
4
2
 
5
- const PROVIDER_IDENTIFIER = "__SENTRY_MASTRA_OBSERVABILITY__";
6
- const MASTRA_INTEGRATION_ID = /@sentry\/server-utils\/build\/esm\/integrations\/mastra\.js$/;
7
- function isMastraIntegrationModuleId(id) {
8
- const normalizedId = id.replace(/\\/g, "/").replace(/[?#].*$/, "");
9
- return MASTRA_INTEGRATION_ID.test(normalizedId);
10
- }
11
3
  function sentryMastraObservabilityProviderPlugin() {
12
- let providerSnippet;
13
- return {
4
+ return createProvidedModulePlugin({
14
5
  name: "sentry-cloudflare-mastra-observability-provider",
15
- configResolved(config) {
16
- try {
17
- createRequire(resolve(config.root, "noop.js")).resolve("@mastra/observability");
18
- } catch {
19
- return;
20
- }
21
- providerSnippet = `import * as ${PROVIDER_IDENTIFIER} from '@mastra/observability';
22
- (globalThis.__SENTRY_ORCHESTRION__ = globalThis.__SENTRY_ORCHESTRION__ || {});
23
- (globalThis.__SENTRY_ORCHESTRION__.providedModules = globalThis.__SENTRY_ORCHESTRION__.providedModules || {})['@mastra/observability'] = ${PROVIDER_IDENTIFIER};
24
- `;
25
- },
26
- transform(code, id) {
27
- if (!providerSnippet || !isMastraIntegrationModuleId(id)) return void 0;
28
- const ms = new MagicString(code);
29
- ms.prepend(providerSnippet);
30
- return { code: ms.toString(), map: ms.generateMap({ hires: true }) };
31
- }
32
- };
6
+ moduleName: "@mastra/observability",
7
+ identifier: "__SENTRY_MASTRA_OBSERVABILITY__",
8
+ integrationModule: "mastra"
9
+ });
33
10
  }
34
11
 
35
- export { isMastraIntegrationModuleId, sentryMastraObservabilityProviderPlugin };
12
+ export { sentryMastraObservabilityProviderPlugin };
36
13
  //# sourceMappingURL=mastraObservability.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"mastraObservability.js","sources":["../../../../src/vite/mastraObservability.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { resolve } from 'node:path';\nimport MagicString from 'magic-string';\n\n// Namespace binding the injected provider import uses; read back by the integration\n// off the global marker.\nconst PROVIDER_IDENTIFIER = '__SENTRY_MASTRA_OBSERVABILITY__';\n\n// The bundled `@sentry/server-utils` Mastra integration module (ESM build — the only\n// one a worker loads). Its `loadMastraObservability` reads `@mastra/observability` off\n// the global marker this provider populates, instead of `createRequire`, which cannot\n// resolve a package inside a bundled worker.\nconst MASTRA_INTEGRATION_ID = /@sentry\\/server-utils\\/build\\/esm\\/integrations\\/mastra\\.js$/;\n\n/** Whether `id` is the Sentry Mastra integration module the provider injects into. */\nexport function isMastraIntegrationModuleId(id: string): boolean {\n const normalizedId = id.replace(/\\\\/g, '/').replace(/[?#].*$/, '');\n return MASTRA_INTEGRATION_ID.test(normalizedId);\n}\n\n/**\n * Splices a static `import * as … from '@mastra/observability'` into Sentry's own\n * Mastra integration module and stashes the namespace on the global orchestrion\n * marker.\n *\n * On Cloudflare the integration cannot `createRequire('@mastra/observability')` to\n * bootstrap Mastra's observability pipeline — there is no on-disk `node_modules` in\n * workerd — so without this the user has to construct and wire up an `Observability`\n * themselves. The import is static (statically analyzable, no lazy `import()`), lands\n * in Sentry's module rather than the user's code, and is only emitted when the package\n * actually resolves; if it is absent, the integration keeps its Node `createRequire`\n * fallback and the marker stays empty.\n */\nexport function sentryMastraObservabilityProviderPlugin(): {\n name: string;\n configResolved(config: { root: string }): void;\n transform(code: string, id: string): { code: string; map: ReturnType<MagicString['generateMap']> } | undefined;\n} {\n let providerSnippet: string | undefined;\n\n return {\n name: 'sentry-cloudflare-mastra-observability-provider',\n\n configResolved(config: { root: string }): void {\n // Resolved at build time (Node), so this `createRequire` never ships to the worker.\n try {\n createRequire(resolve(config.root, 'noop.js')).resolve('@mastra/observability');\n } catch {\n return;\n }\n providerSnippet =\n `import * as ${PROVIDER_IDENTIFIER} from '@mastra/observability';\\n` +\n '(globalThis.__SENTRY_ORCHESTRION__ = globalThis.__SENTRY_ORCHESTRION__ || {});\\n' +\n '(globalThis.__SENTRY_ORCHESTRION__.providedModules = globalThis.__SENTRY_ORCHESTRION__.providedModules || {})' +\n `['@mastra/observability'] = ${PROVIDER_IDENTIFIER};\\n`;\n },\n\n transform(code: string, id: string): { code: string; map: ReturnType<MagicString['generateMap']> } | undefined {\n if (!providerSnippet || !isMastraIntegrationModuleId(id)) return undefined;\n\n const ms = new MagicString(code);\n ms.prepend(providerSnippet);\n return { code: ms.toString(), map: ms.generateMap({ hires: true }) };\n },\n };\n}\n"],"names":[],"mappings":";;;;AAMA,MAAM,mBAAA,GAAsB,iCAAA;AAM5B,MAAM,qBAAA,GAAwB,8DAAA;AAGvB,SAAS,4BAA4B,EAAA,EAAqB;AAC/D,EAAA,MAAM,YAAA,GAAe,GAAG,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA,CAAE,OAAA,CAAQ,WAAW,EAAE,CAAA;AACjE,EAAA,OAAO,qBAAA,CAAsB,KAAK,YAAY,CAAA;AAChD;AAeO,SAAS,uCAAA,GAId;AACA,EAAA,IAAI,eAAA;AAEJ,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,iDAAA;AAAA,IAEN,eAAe,MAAA,EAAgC;AAE7C,MAAA,IAAI;AACF,QAAA,aAAA,CAAc,QAAQ,MAAA,CAAO,IAAA,EAAM,SAAS,CAAC,CAAA,CAAE,QAAQ,uBAAuB,CAAA;AAAA,MAChF,CAAA,CAAA,MAAQ;AACN,QAAA;AAAA,MACF;AACA,MAAA,eAAA,GACE,eAAe,mBAAmB,CAAA;AAAA;AAAA,yIAAA,EAGH,mBAAmB,CAAA;AAAA,CAAA;AAAA,IACtD,CAAA;AAAA,IAEA,SAAA,CAAU,MAAc,EAAA,EAAuF;AAC7G,MAAA,IAAI,CAAC,eAAA,IAAmB,CAAC,2BAAA,CAA4B,EAAE,GAAG,OAAO,MAAA;AAEjE,MAAA,MAAM,EAAA,GAAK,IAAI,WAAA,CAAY,IAAI,CAAA;AAC/B,MAAA,EAAA,CAAG,QAAQ,eAAe,CAAA;AAC1B,MAAA,OAAO,EAAE,IAAA,EAAM,EAAA,CAAG,QAAA,EAAS,EAAG,GAAA,EAAK,EAAA,CAAG,WAAA,CAAY,EAAE,KAAA,EAAO,IAAA,EAAM,CAAA,EAAE;AAAA,IACrE;AAAA,GACF;AACF;;;;"}
1
+ {"version":3,"file":"mastraObservability.js","sources":["../../../../src/vite/mastraObservability.ts"],"sourcesContent":["import type { ProvidedModulePlugin } from './providedModulePlugin';\nimport { createProvidedModulePlugin } from './providedModulePlugin';\n\n/**\n * Splices a static `import * as … from '@mastra/observability'` into Sentry's own Mastra\n * integration module and stashes the namespace on the global orchestrion marker.\n *\n * On Cloudflare the integration cannot `createRequire('@mastra/observability')` to bootstrap\n * Mastra's observability pipeline — there is no on-disk `node_modules` in workerd — so without\n * this the user has to construct and wire up an `Observability` themselves. If the package is\n * absent, the integration keeps its Node `createRequire` fallback and the marker stays empty.\n */\nexport function sentryMastraObservabilityProviderPlugin(): ProvidedModulePlugin {\n return createProvidedModulePlugin({\n name: 'sentry-cloudflare-mastra-observability-provider',\n moduleName: '@mastra/observability',\n identifier: '__SENTRY_MASTRA_OBSERVABILITY__',\n integrationModule: 'mastra',\n });\n}\n"],"names":[],"mappings":";;AAYO,SAAS,uCAAA,GAAgE;AAC9E,EAAA,OAAO,0BAAA,CAA2B;AAAA,IAChC,IAAA,EAAM,iDAAA;AAAA,IACN,UAAA,EAAY,uBAAA;AAAA,IACZ,UAAA,EAAY,iCAAA;AAAA,IACZ,iBAAA,EAAmB;AAAA,GACpB,CAAA;AACH;;;;"}
@@ -0,0 +1,50 @@
1
+ import { resolve } from 'node:path';
2
+ import MagicString from 'magic-string';
3
+
4
+ function createIntegrationModuleMatcher(integrationModule) {
5
+ const suffix = `@sentry/server-utils/build/esm/integrations/${integrationModule}.js`;
6
+ return (id) => id.replace(/\\/g, "/").replace(/[?#].*$/, "").endsWith(suffix);
7
+ }
8
+ function buildProviderSnippet({ moduleName, identifier }) {
9
+ const marker = "globalThis.__SENTRY_ORCHESTRION__";
10
+ return `import * as ${identifier} from '${moduleName}';
11
+ (${marker} = ${marker} || {});
12
+ (${marker}.providedModules = ${marker}.providedModules || {});
13
+ Object.defineProperty(${marker}.providedModules, '${moduleName}', { configurable: true, enumerable: true, get() { return ${identifier}; } });
14
+ `;
15
+ }
16
+ function createProvidedModulePlugin(options) {
17
+ const isIntegrationModuleId = createIntegrationModuleMatcher(options.integrationModule);
18
+ let root = process.cwd();
19
+ let providerSnippet;
20
+ return {
21
+ name: options.name,
22
+ applyToEnvironment(environment) {
23
+ return environment.config.consumer === "server";
24
+ },
25
+ configResolved(config) {
26
+ root = config.root;
27
+ },
28
+ async buildStart() {
29
+ if (providerSnippet) return;
30
+ try {
31
+ const resolved = await this.resolve(options.moduleName, resolve(root, "noop.js"));
32
+ if (!resolved) return;
33
+ } catch (error) {
34
+ this.warn(
35
+ `[Sentry] could not resolve ${options.moduleName} while probing for it; injecting the provider anyway. ${error?.message ?? error}`
36
+ );
37
+ }
38
+ providerSnippet = buildProviderSnippet(options);
39
+ },
40
+ transform(code, id) {
41
+ if (!providerSnippet || !isIntegrationModuleId(id) || code.includes(options.identifier)) return void 0;
42
+ const ms = new MagicString(code);
43
+ ms.prepend(providerSnippet);
44
+ return { code: ms.toString(), map: ms.generateMap({ hires: true }) };
45
+ }
46
+ };
47
+ }
48
+
49
+ export { createIntegrationModuleMatcher, createProvidedModulePlugin };
50
+ //# sourceMappingURL=providedModulePlugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"providedModulePlugin.js","sources":["../../../../src/vite/providedModulePlugin.ts"],"sourcesContent":["import { resolve } from 'node:path';\nimport MagicString from 'magic-string';\n\n/**\n * The slice of the Rollup plugin context the probe needs. Declared here rather than imported so\n * this file carries no Rollup or Vite type dependency.\n */\ninterface ResolveContext {\n resolve(\n source: string,\n importer?: string,\n options?: { skipSelf?: boolean },\n ): Promise<{ id: string; external?: boolean | string } | null>;\n warn(message: string): void;\n}\n\n/** The plugin shape `sentryCloudflareVitePlugin` composes. */\nexport interface ProvidedModulePlugin {\n name: string;\n applyToEnvironment(environment: { config: { consumer: string } }): boolean;\n configResolved(config: { root: string }): void;\n buildStart(this: ResolveContext): Promise<void>;\n transform(code: string, id: string): { code: string; map: ReturnType<MagicString['generateMap']> } | undefined;\n}\n\nexport interface ProvidedModulePluginOptions {\n /** Vite plugin name, e.g. `sentry-cloudflare-flue-runtime-provider`. */\n name: string;\n /** Bare specifier of the package to provide, e.g. `@flue/runtime`. */\n moduleName: string;\n /** Namespace binding the injected import uses, e.g. `__SENTRY_FLUE_RUNTIME__`. */\n identifier: string;\n /** Basename of the `@sentry/server-utils` integration module to inject into, e.g. `flue`. */\n integrationModule: string;\n}\n\n/**\n * Build the matcher for one `@sentry/server-utils` integration module.\n *\n * Plain `endsWith`, not a `RegExp`: nothing here needs pattern matching, and building one from\n * a caller-supplied string would need escaping, which is the only reason this file would have to\n * import from `@sentry/core`. A build-time plugin should not drag the SDK into the build.\n */\nexport function createIntegrationModuleMatcher(integrationModule: string): (id: string) => boolean {\n // The ESM build only: a worker never loads the CJS one.\n const suffix = `@sentry/server-utils/build/esm/integrations/${integrationModule}.js`;\n\n return (id: string): boolean =>\n id\n .replace(/\\\\/g, '/')\n .replace(/[?#].*$/, '')\n .endsWith(suffix);\n}\n\nfunction buildProviderSnippet({ moduleName, identifier }: ProvidedModulePluginOptions): string {\n const marker = 'globalThis.__SENTRY_ORCHESTRION__';\n\n // A getter, not an assignment: assigning reads the binding at injection time, so it stores\n // `undefined` whenever the bundler evaluates Sentry's module before the provided package\n // finished initializing. Enumerable so the entry shows up in `Object.keys` and a spread.\n return (\n `import * as ${identifier} from '${moduleName}';\\n` +\n `(${marker} = ${marker} || {});\\n` +\n `(${marker}.providedModules = ${marker}.providedModules || {});\\n` +\n `Object.defineProperty(${marker}.providedModules, '${moduleName}', ` +\n `{ configurable: true, enumerable: true, get() { return ${identifier}; } });\\n`\n );\n}\n\n/**\n * Build a Vite plugin that splices a static `import * as … from '<moduleName>'` into one of\n * Sentry's own integration modules and exposes the namespace on the global orchestrion marker.\n *\n * Some packages are instrumented by registration rather than by patching, so instrumenting them\n * needs a reference to that module's own binding and no channel payload carries one. On Node the\n * integration resolves it itself; a bundled worker has no `node_modules` to resolve from, so the\n * binding is supplied at build time instead. The import is static, lands in Sentry's module rather\n * than the user's code, and is only emitted when the package actually resolves.\n */\nexport function createProvidedModulePlugin(options: ProvidedModulePluginOptions): ProvidedModulePlugin {\n const isIntegrationModuleId = createIntegrationModuleMatcher(options.integrationModule);\n\n let root = process.cwd();\n let providerSnippet: string | undefined;\n\n return {\n name: options.name,\n\n applyToEnvironment(environment: { config: { consumer: string } }): boolean {\n // Server environments only. `buildStart` runs per environment against one shared plugin\n // instance, so without this a `client` build resolves first, under browser conditions, and\n // answers on the worker's behalf. That defeats the point of probing with `this.resolve`.\n // Same gate the orchestrion plugin uses.\n return environment.config.consumer === 'server';\n },\n\n configResolved(config: { root: string }): void {\n root = config.root;\n },\n\n async buildStart(this: ResolveContext): Promise<void> {\n // Already answered by an earlier server environment. A build with several worker\n // environments shares the answer: they resolve under the same conditions.\n if (providerSnippet) return;\n\n try {\n // The environment's own resolver, so the probe uses the conditions the injected import\n // will. That is what a `require.resolve` probe cannot do: an ESM-only package has no\n // `require` condition and reads as missing. Resolved from the app root, not from Sentry's\n // own install.\n const resolved = await this.resolve(options.moduleName, resolve(root, 'noop.js'));\n if (!resolved) return;\n } catch (error) {\n // Present but unresolvable for some other reason. Inject anyway so the build fails loudly\n // rather than silently shipping a worker with no instrumentation, and surface the original\n // cause: the import error Vite raises next says nothing about why resolution broke.\n this.warn(\n `[Sentry] could not resolve ${options.moduleName} while probing for it; injecting the provider anyway. ${\n (error as Error | undefined)?.message ?? error\n }`,\n );\n }\n\n providerSnippet = buildProviderSnippet(options);\n },\n\n transform(code: string, id: string): { code: string; map: ReturnType<MagicString['generateMap']> } | undefined {\n // `code.includes` keeps this idempotent: a second pass over already-injected output would\n // otherwise emit a duplicate `import * as` binding, which is a syntax error.\n if (!providerSnippet || !isIntegrationModuleId(id) || code.includes(options.identifier)) return undefined;\n\n const ms = new MagicString(code);\n ms.prepend(providerSnippet);\n return { code: ms.toString(), map: ms.generateMap({ hires: true }) };\n },\n };\n}\n"],"names":[],"mappings":";;;AA2CO,SAAS,+BAA+B,iBAAA,EAAoD;AAEjG,EAAA,MAAM,MAAA,GAAS,+CAA+C,iBAAiB,CAAA,GAAA,CAAA;AAE/E,EAAA,OAAO,CAAC,EAAA,KACN,EAAA,CACG,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA,CAClB,OAAA,CAAQ,SAAA,EAAW,EAAE,CAAA,CACrB,QAAA,CAAS,MAAM,CAAA;AACtB;AAEA,SAAS,oBAAA,CAAqB,EAAE,UAAA,EAAY,UAAA,EAAW,EAAwC;AAC7F,EAAA,MAAM,MAAA,GAAS,mCAAA;AAKf,EAAA,OACE,CAAA,YAAA,EAAe,UAAU,CAAA,OAAA,EAAU,UAAU,CAAA;AAAA,CAAA,EACzC,MAAM,MAAM,MAAM,CAAA;AAAA,CAAA,EAClB,MAAM,sBAAsB,MAAM,CAAA;AAAA,sBAAA,EACb,MAAM,CAAA,mBAAA,EAAsB,UAAU,CAAA,0DAAA,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eAAe,CAAA;AAC1B,MAAA,OAAO,EAAE,IAAA,EAAM,EAAA,CAAG,QAAA,EAAS,EAAG,GAAA,EAAK,EAAA,CAAG,WAAA,CAAY,EAAE,KAAA,EAAO,IAAA,EAAM,CAAA,EAAE;AAAA,IACrE;AAAA,GACF;AACF;;;;"}
@@ -8,6 +8,7 @@ import { instrumentEnv } from './instrumentations/worker/instrumentEnv.js';
8
8
  import { addCloudResourceContext } from './scope-utils.js';
9
9
  import { init } from './sdk.js';
10
10
  import { instrumentContext } from './utils/instrumentContext.js';
11
+ import { getInvocationState } from './utils/invocationContext.js';
11
12
  import { withInvocationIsolationScope } from './utils/invocationScope.js';
12
13
 
13
14
  const UUID_REGEX = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i;
@@ -44,6 +45,10 @@ class WrappedWorkflowStep {
44
45
  const hasStepContext = typeof attempt === "number" && typeof retryLimit === "number";
45
46
  const isFinalAttempt = !hasStepContext || attempt > retryLimit;
46
47
  return withIsolationScope(this._isolationScope, () => {
48
+ const invocationState = getInvocationState();
49
+ if (invocationState) {
50
+ invocationState.flushPointReached = false;
51
+ }
47
52
  const stepResult = startSpan(
48
53
  {
49
54
  name,
@@ -77,11 +82,11 @@ class WrappedWorkflowStep {
77
82
  );
78
83
  return stepResult.then(
79
84
  (result) => {
80
- this._waitUntil(flush(2e3));
85
+ this._waitUntil(withScope(scopeForStep, () => flush(2e3)));
81
86
  return result;
82
87
  },
83
88
  (error) => {
84
- this._waitUntil(flush(2e3));
89
+ this._waitUntil(withScope(scopeForStep, () => flush(2e3)));
85
90
  throw error;
86
91
  }
87
92
  );
@@ -1 +1 @@
1
- {"version":3,"file":"workflows.js","sources":["../../../src/workflows.ts"],"sourcesContent":["import { SENTRY_SEGMENT_NAME_SOURCE, CODE_FUNCTION_NAME, SENTRY_OP } from '@sentry/conventions/attributes';\nimport { FUNCTION } from '@sentry/conventions/op';\nimport type { PropagationContext, Scope } from '@sentry/core';\nimport {\n captureException,\n flush,\n getCurrentScope,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n startSpan,\n withIsolationScope,\n withScope,\n} 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 { setAsyncLocalStorageAsyncContextStrategy } from '@sentry/server-utils/no-diagnostic-channels';\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 { 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 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 [SEMANTIC_ATTRIBUTE_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).\n return stepResult.then(\n result => {\n this._waitUntil(flush(2000));\n return result;\n },\n error => {\n this._waitUntil(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 setAsyncLocalStorageAsyncContextStrategy();\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":[],"mappings":";;;;;;;;;;;;AAmCA,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,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,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,CAAU,eAAA,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,EAAA,kBAAA,CAAmB,iBAAiB,CAAA;AACpC,EAAA,OAAO,iBAAA;AACT;;;;"}
1
+ {"version":3,"file":"workflows.js","sources":["../../../src/workflows.ts"],"sourcesContent":["import { SENTRY_SEGMENT_NAME_SOURCE, CODE_FUNCTION_NAME, SENTRY_OP } from '@sentry/conventions/attributes';\nimport { FUNCTION } from '@sentry/conventions/op';\nimport type { PropagationContext, Scope } from '@sentry/core';\nimport {\n captureException,\n flush,\n getCurrentScope,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n startSpan,\n withIsolationScope,\n withScope,\n} 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 { setAsyncLocalStorageAsyncContextStrategy } from '@sentry/server-utils/no-diagnostic-channels';\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 [SEMANTIC_ATTRIBUTE_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 setAsyncLocalStorageAsyncContextStrategy();\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":[],"mappings":";;;;;;;;;;;;;AAoCA,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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OAAO,SAAA,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,CAAU,eAAA,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,EAAA,kBAAA,CAAmB,iBAAiB,CAAA;AACpC,EAAA,OAAO,iBAAA;AACT;;;;"}
@@ -59,16 +59,23 @@ class CloudflareClient extends ServerRuntimeClient {
59
59
  }
60
60
  /**
61
61
  * Flushes pending operations and ensures all data is processed.
62
- * If a timeout is provided, the operation will be completed within the specified time limit.
63
62
  *
64
- * It will wait for all pending spans to complete before flushing.
63
+ * Each phase waits at most `timeout`: the flush lock of a per-invocation client, pending spans, event
64
+ * processing and the transport drain. So a flush can take a small multiple of `timeout`, which stays well
65
+ * below Cloudflare's 30 second `waitUntil` limit for the timeouts the SDK uses. Sends still pending when
66
+ * the drain times out are aborted.
65
67
  *
66
- * @param {number} [timeout] - Optional timeout in milliseconds to force the completion of the flush operation.
68
+ * @param {number} [timeout] - Maximum time in milliseconds for each phase of the flush.
67
69
  * @return {Promise<boolean>} A promise that resolves to a boolean indicating whether the flush operation was successful.
68
70
  */
69
71
  async flush(timeout) {
70
72
  if (this._flushLock) {
71
- await this._flushLock.finalize();
73
+ let timer;
74
+ await Promise.race([
75
+ this._flushLock.finalize(),
76
+ ...timeout ? [new Promise((resolve) => timer = setTimeout(resolve, timeout))] : []
77
+ ]);
78
+ clearTimeout(timer);
72
79
  }
73
80
  if (this._pendingSpans.size > 0 && this._spanCompletionPromise) {
74
81
  DEBUG_BUILD && debug.log("[CloudflareClient] Waiting for", this._pendingSpans.size, "pending spans to complete...");