@sentry/server-utils 10.63.0 → 10.64.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 (206) hide show
  1. package/build/cjs/index.js +6 -2
  2. package/build/cjs/index.js.map +1 -1
  3. package/build/cjs/integrations/tracing-channel/anthropic.js +101 -0
  4. package/build/cjs/integrations/tracing-channel/anthropic.js.map +1 -0
  5. package/build/cjs/integrations/tracing-channel/hapi-types.js +30 -0
  6. package/build/cjs/integrations/tracing-channel/hapi-types.js.map +1 -0
  7. package/build/cjs/integrations/tracing-channel/hapi-utils.js +177 -0
  8. package/build/cjs/integrations/tracing-channel/hapi-utils.js.map +1 -0
  9. package/build/cjs/integrations/tracing-channel/hapi.js +52 -0
  10. package/build/cjs/integrations/tracing-channel/hapi.js.map +1 -0
  11. package/build/cjs/integrations/tracing-channel/ioredis.js +96 -0
  12. package/build/cjs/integrations/tracing-channel/ioredis.js.map +1 -0
  13. package/build/cjs/integrations/tracing-channel/mysql.js +1 -0
  14. package/build/cjs/integrations/tracing-channel/mysql.js.map +1 -1
  15. package/build/cjs/integrations/tracing-channel/openai.js +83 -0
  16. package/build/cjs/integrations/tracing-channel/openai.js.map +1 -0
  17. package/build/cjs/integrations/tracing-channel/postgres.js +170 -0
  18. package/build/cjs/integrations/tracing-channel/postgres.js.map +1 -0
  19. package/build/cjs/integrations/tracing-channel/vercel-ai.js +25 -0
  20. package/build/cjs/integrations/tracing-channel/vercel-ai.js.map +1 -0
  21. package/build/cjs/mongoose/index.js +23 -0
  22. package/build/cjs/mongoose/index.js.map +1 -0
  23. package/build/cjs/mongoose/mongoose-dc-subscriber.js +97 -0
  24. package/build/cjs/mongoose/mongoose-dc-subscriber.js.map +1 -0
  25. package/build/cjs/orchestrion/bundler/vite.js +3 -3
  26. package/build/cjs/orchestrion/bundler/vite.js.map +1 -1
  27. package/build/cjs/orchestrion/channels.js +17 -2
  28. package/build/cjs/orchestrion/channels.js.map +1 -1
  29. package/build/cjs/orchestrion/config/anthropic-ai.js +43 -0
  30. package/build/cjs/orchestrion/config/anthropic-ai.js.map +1 -0
  31. package/build/cjs/orchestrion/config/hapi.js +26 -0
  32. package/build/cjs/orchestrion/config/hapi.js.map +1 -0
  33. package/build/cjs/orchestrion/config/index.js +35 -0
  34. package/build/cjs/orchestrion/config/index.js.map +1 -0
  35. package/build/cjs/orchestrion/config/ioredis.js +35 -0
  36. package/build/cjs/orchestrion/config/ioredis.js.map +1 -0
  37. package/build/cjs/orchestrion/config/lru-memoizer.js +17 -0
  38. package/build/cjs/orchestrion/config/lru-memoizer.js.map +1 -0
  39. package/build/cjs/orchestrion/config/mysql.js +16 -0
  40. package/build/cjs/orchestrion/config/mysql.js.map +1 -0
  41. package/build/cjs/orchestrion/config/openai.js +40 -0
  42. package/build/cjs/orchestrion/config/openai.js.map +1 -0
  43. package/build/cjs/orchestrion/config/pg.js +51 -0
  44. package/build/cjs/orchestrion/config/pg.js.map +1 -0
  45. package/build/cjs/orchestrion/config/vercel-ai.js +44 -0
  46. package/build/cjs/orchestrion/config/vercel-ai.js.map +1 -0
  47. package/build/cjs/orchestrion/detect.js +6 -1
  48. package/build/cjs/orchestrion/detect.js.map +1 -1
  49. package/build/cjs/orchestrion/index.js +27 -5
  50. package/build/cjs/orchestrion/index.js.map +1 -1
  51. package/build/cjs/orchestrion/runtime/register.js +10 -7
  52. package/build/cjs/orchestrion/runtime/register.js.map +1 -1
  53. package/build/cjs/redis/redis-statement-serializer.js +34 -0
  54. package/build/cjs/redis/redis-statement-serializer.js.map +1 -0
  55. package/build/cjs/tracing-channel.js +1 -1
  56. package/build/cjs/tracing-channel.js.map +1 -1
  57. package/build/cjs/vercel-ai/vercel-ai-dc-subscriber.js +11 -4
  58. package/build/cjs/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
  59. package/build/cjs/vercel-ai/vercel-ai-orchestrion-v6-subscriber.js +256 -0
  60. package/build/cjs/vercel-ai/vercel-ai-orchestrion-v6-subscriber.js.map +1 -0
  61. package/build/esm/index.js +2 -0
  62. package/build/esm/index.js.map +1 -1
  63. package/build/esm/integrations/tracing-channel/anthropic.js +99 -0
  64. package/build/esm/integrations/tracing-channel/anthropic.js.map +1 -0
  65. package/build/esm/integrations/tracing-channel/hapi-types.js +25 -0
  66. package/build/esm/integrations/tracing-channel/hapi-types.js.map +1 -0
  67. package/build/esm/integrations/tracing-channel/hapi-utils.js +172 -0
  68. package/build/esm/integrations/tracing-channel/hapi-utils.js.map +1 -0
  69. package/build/esm/integrations/tracing-channel/hapi.js +50 -0
  70. package/build/esm/integrations/tracing-channel/hapi.js.map +1 -0
  71. package/build/esm/integrations/tracing-channel/ioredis.js +94 -0
  72. package/build/esm/integrations/tracing-channel/ioredis.js.map +1 -0
  73. package/build/esm/integrations/tracing-channel/mysql.js +2 -1
  74. package/build/esm/integrations/tracing-channel/mysql.js.map +1 -1
  75. package/build/esm/integrations/tracing-channel/openai.js +81 -0
  76. package/build/esm/integrations/tracing-channel/openai.js.map +1 -0
  77. package/build/esm/integrations/tracing-channel/postgres.js +168 -0
  78. package/build/esm/integrations/tracing-channel/postgres.js.map +1 -0
  79. package/build/esm/integrations/tracing-channel/vercel-ai.js +23 -0
  80. package/build/esm/integrations/tracing-channel/vercel-ai.js.map +1 -0
  81. package/build/esm/mongoose/index.js +21 -0
  82. package/build/esm/mongoose/index.js.map +1 -0
  83. package/build/esm/mongoose/mongoose-dc-subscriber.js +89 -0
  84. package/build/esm/mongoose/mongoose-dc-subscriber.js.map +1 -0
  85. package/build/esm/orchestrion/bundler/vite.js +1 -1
  86. package/build/esm/orchestrion/channels.js +17 -2
  87. package/build/esm/orchestrion/channels.js.map +1 -1
  88. package/build/esm/orchestrion/config/anthropic-ai.js +40 -0
  89. package/build/esm/orchestrion/config/anthropic-ai.js.map +1 -0
  90. package/build/esm/orchestrion/config/hapi.js +23 -0
  91. package/build/esm/orchestrion/config/hapi.js.map +1 -0
  92. package/build/esm/orchestrion/config/index.js +31 -0
  93. package/build/esm/orchestrion/config/index.js.map +1 -0
  94. package/build/esm/orchestrion/config/ioredis.js +32 -0
  95. package/build/esm/orchestrion/config/ioredis.js.map +1 -0
  96. package/build/esm/orchestrion/config/lru-memoizer.js +14 -0
  97. package/build/esm/orchestrion/config/lru-memoizer.js.map +1 -0
  98. package/build/esm/orchestrion/config/mysql.js +13 -0
  99. package/build/esm/orchestrion/config/mysql.js.map +1 -0
  100. package/build/esm/orchestrion/config/openai.js +37 -0
  101. package/build/esm/orchestrion/config/openai.js.map +1 -0
  102. package/build/esm/orchestrion/config/pg.js +48 -0
  103. package/build/esm/orchestrion/config/pg.js.map +1 -0
  104. package/build/esm/orchestrion/config/vercel-ai.js +41 -0
  105. package/build/esm/orchestrion/config/vercel-ai.js.map +1 -0
  106. package/build/esm/orchestrion/detect.js +6 -2
  107. package/build/esm/orchestrion/detect.js.map +1 -1
  108. package/build/esm/orchestrion/index.js +21 -3
  109. package/build/esm/orchestrion/index.js.map +1 -1
  110. package/build/esm/orchestrion/runtime/register.js +8 -4
  111. package/build/esm/orchestrion/runtime/register.js.map +1 -1
  112. package/build/esm/package.json +1 -1
  113. package/build/esm/redis/redis-statement-serializer.js +32 -0
  114. package/build/esm/redis/redis-statement-serializer.js.map +1 -0
  115. package/build/esm/tracing-channel.js +2 -2
  116. package/build/esm/tracing-channel.js.map +1 -1
  117. package/build/esm/vercel-ai/vercel-ai-dc-subscriber.js +14 -8
  118. package/build/esm/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
  119. package/build/esm/vercel-ai/vercel-ai-orchestrion-v6-subscriber.js +254 -0
  120. package/build/esm/vercel-ai/vercel-ai-orchestrion-v6-subscriber.js.map +1 -0
  121. package/build/types/index.d.ts +2 -0
  122. package/build/types/index.d.ts.map +1 -1
  123. package/build/types/integrations/tracing-channel/anthropic.d.ts +10 -0
  124. package/build/types/integrations/tracing-channel/anthropic.d.ts.map +1 -0
  125. package/build/types/integrations/tracing-channel/hapi-types.d.ts +53 -0
  126. package/build/types/integrations/tracing-channel/hapi-types.d.ts.map +1 -0
  127. package/build/types/integrations/tracing-channel/hapi-utils.d.ts +25 -0
  128. package/build/types/integrations/tracing-channel/hapi-utils.d.ts.map +1 -0
  129. package/build/types/integrations/tracing-channel/hapi.d.ts +9 -0
  130. package/build/types/integrations/tracing-channel/hapi.d.ts.map +1 -0
  131. package/build/types/integrations/tracing-channel/ioredis.d.ts +17 -0
  132. package/build/types/integrations/tracing-channel/ioredis.d.ts.map +1 -0
  133. package/build/types/integrations/tracing-channel/mysql.d.ts.map +1 -1
  134. package/build/types/integrations/tracing-channel/openai.d.ts +10 -0
  135. package/build/types/integrations/tracing-channel/openai.d.ts.map +1 -0
  136. package/build/types/integrations/tracing-channel/postgres.d.ts +15 -0
  137. package/build/types/integrations/tracing-channel/postgres.d.ts.map +1 -0
  138. package/build/types/integrations/tracing-channel/vercel-ai.d.ts +13 -0
  139. package/build/types/integrations/tracing-channel/vercel-ai.d.ts.map +1 -0
  140. package/build/types/mongoose/index.d.ts +11 -0
  141. package/build/types/mongoose/index.d.ts.map +1 -0
  142. package/build/types/mongoose/mongoose-dc-subscriber.d.ts +63 -0
  143. package/build/types/mongoose/mongoose-dc-subscriber.d.ts.map +1 -0
  144. package/build/types/orchestrion/channels.d.ts +21 -1
  145. package/build/types/orchestrion/channels.d.ts.map +1 -1
  146. package/build/types/orchestrion/config/anthropic-ai.d.ts +31 -0
  147. package/build/types/orchestrion/config/anthropic-ai.d.ts.map +1 -0
  148. package/build/types/orchestrion/config/hapi.d.ts +17 -0
  149. package/build/types/orchestrion/config/hapi.d.ts.map +1 -0
  150. package/build/types/orchestrion/{config.d.ts → config/index.d.ts} +1 -12
  151. package/build/types/orchestrion/config/index.d.ts.map +1 -0
  152. package/build/types/orchestrion/config/ioredis.d.ts +7 -0
  153. package/build/types/orchestrion/config/ioredis.d.ts.map +1 -0
  154. package/build/types/orchestrion/config/lru-memoizer.d.ts +16 -0
  155. package/build/types/orchestrion/config/lru-memoizer.d.ts.map +1 -0
  156. package/build/types/orchestrion/config/mysql.d.ts +16 -0
  157. package/build/types/orchestrion/config/mysql.d.ts.map +1 -0
  158. package/build/types/orchestrion/config/openai.d.ts +20 -0
  159. package/build/types/orchestrion/config/openai.d.ts.map +1 -0
  160. package/build/types/orchestrion/config/pg.d.ts +33 -0
  161. package/build/types/orchestrion/config/pg.d.ts.map +1 -0
  162. package/build/types/orchestrion/config/vercel-ai.d.ts +11 -0
  163. package/build/types/orchestrion/config/vercel-ai.d.ts.map +1 -0
  164. package/build/types/orchestrion/detect.d.ts +10 -0
  165. package/build/types/orchestrion/detect.d.ts.map +1 -1
  166. package/build/types/orchestrion/index.d.ts +53 -3
  167. package/build/types/orchestrion/index.d.ts.map +1 -1
  168. package/build/types/orchestrion/runtime/register.d.ts.map +1 -1
  169. package/build/types/redis/redis-statement-serializer.d.ts +6 -0
  170. package/build/types/redis/redis-statement-serializer.d.ts.map +1 -0
  171. package/build/types/vercel-ai/vercel-ai-dc-subscriber.d.ts +10 -4
  172. package/build/types/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
  173. package/build/types/vercel-ai/vercel-ai-orchestrion-v6-subscriber.d.ts +12 -0
  174. package/build/types/vercel-ai/vercel-ai-orchestrion-v6-subscriber.d.ts.map +1 -0
  175. package/build/types-ts3.8/index.d.ts +2 -0
  176. package/build/types-ts3.8/integrations/tracing-channel/anthropic.d.ts +10 -0
  177. package/build/types-ts3.8/integrations/tracing-channel/hapi-types.d.ts +65 -0
  178. package/build/types-ts3.8/integrations/tracing-channel/hapi-utils.d.ts +25 -0
  179. package/build/types-ts3.8/integrations/tracing-channel/hapi.d.ts +9 -0
  180. package/build/types-ts3.8/integrations/tracing-channel/ioredis.d.ts +17 -0
  181. package/build/types-ts3.8/integrations/tracing-channel/openai.d.ts +10 -0
  182. package/build/types-ts3.8/integrations/tracing-channel/postgres.d.ts +15 -0
  183. package/build/types-ts3.8/integrations/tracing-channel/vercel-ai.d.ts +13 -0
  184. package/build/types-ts3.8/mongoose/index.d.ts +11 -0
  185. package/build/types-ts3.8/mongoose/mongoose-dc-subscriber.d.ts +63 -0
  186. package/build/types-ts3.8/orchestrion/channels.d.ts +21 -1
  187. package/build/types-ts3.8/orchestrion/config/anthropic-ai.d.ts +31 -0
  188. package/build/types-ts3.8/orchestrion/config/hapi.d.ts +17 -0
  189. package/build/types-ts3.8/orchestrion/{config.d.ts → config/index.d.ts} +1 -12
  190. package/build/types-ts3.8/orchestrion/config/ioredis.d.ts +7 -0
  191. package/build/types-ts3.8/orchestrion/config/lru-memoizer.d.ts +16 -0
  192. package/build/types-ts3.8/orchestrion/config/mysql.d.ts +16 -0
  193. package/build/types-ts3.8/orchestrion/config/openai.d.ts +20 -0
  194. package/build/types-ts3.8/orchestrion/config/pg.d.ts +33 -0
  195. package/build/types-ts3.8/orchestrion/config/vercel-ai.d.ts +11 -0
  196. package/build/types-ts3.8/orchestrion/detect.d.ts +10 -0
  197. package/build/types-ts3.8/orchestrion/index.d.ts +53 -3
  198. package/build/types-ts3.8/redis/redis-statement-serializer.d.ts +6 -0
  199. package/build/types-ts3.8/vercel-ai/vercel-ai-dc-subscriber.d.ts +10 -4
  200. package/build/types-ts3.8/vercel-ai/vercel-ai-orchestrion-v6-subscriber.d.ts +12 -0
  201. package/package.json +9 -9
  202. package/build/cjs/orchestrion/config.js +0 -44
  203. package/build/cjs/orchestrion/config.js.map +0 -1
  204. package/build/esm/orchestrion/config.js +0 -40
  205. package/build/esm/orchestrion/config.js.map +0 -1
  206. package/build/types/orchestrion/config.d.ts.map +0 -1
@@ -0,0 +1,256 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+
3
+ const core = require('@sentry/core');
4
+ const debugBuild = require('../debug-build.js');
5
+ const channels = require('../orchestrion/channels.js');
6
+ const tracingChannel = require('../tracing-channel.js');
7
+ const vercelAiDcSubscriber = require('./vercel-ai-dc-subscriber.js');
8
+
9
+ const PATCHED = /* @__PURE__ */ Symbol("SentryVercelAiModelPatched");
10
+ let callIdCounter = 0;
11
+ function nextCallId() {
12
+ return `v6-${++callIdCounter}`;
13
+ }
14
+ const messages = /* @__PURE__ */ new WeakMap();
15
+ const operationSpans = /* @__PURE__ */ new WeakSet();
16
+ const callIdBySpan = /* @__PURE__ */ new WeakMap();
17
+ const recordingBySpan = /* @__PURE__ */ new WeakMap();
18
+ const suppressedTelemetry = /* @__PURE__ */ new WeakSet();
19
+ let subscribed = false;
20
+ function subscribeVercelAiOrchestrionChannels(tracingChannel, options = {}) {
21
+ if (subscribed) {
22
+ return;
23
+ }
24
+ subscribed = true;
25
+ try {
26
+ bindOperation(tracingChannel, channels.CHANNELS.VERCEL_AI_GENERATE_TEXT, buildTextMessage("generateText"), options);
27
+ bindOperation(tracingChannel, channels.CHANNELS.VERCEL_AI_STREAM_TEXT, buildTextMessage("streamText"), options);
28
+ bindOperation(
29
+ tracingChannel,
30
+ channels.CHANNELS.VERCEL_AI_EMBED,
31
+ (callOptions, telemetry) => ({
32
+ type: "embed",
33
+ event: {
34
+ callId: nextCallId(),
35
+ ...modelFields(callOptions.model),
36
+ maxRetries: callOptions.maxRetries,
37
+ value: callOptions.value,
38
+ ...recording(telemetry)
39
+ }
40
+ }),
41
+ options
42
+ );
43
+ bindOperation(
44
+ tracingChannel,
45
+ channels.CHANNELS.VERCEL_AI_EMBED_MANY,
46
+ // `embedMany` takes a `values` array (vs `embed`'s single `value`); the shared core reads it as the
47
+ // embeddings input, matching the OTel path's batch `ai.embedMany` span.
48
+ (callOptions, telemetry) => ({
49
+ type: "embedMany",
50
+ event: {
51
+ callId: nextCallId(),
52
+ ...modelFields(callOptions.model),
53
+ maxRetries: callOptions.maxRetries,
54
+ values: callOptions.values,
55
+ ...recording(telemetry)
56
+ }
57
+ }),
58
+ options
59
+ );
60
+ bindOperation(
61
+ tracingChannel,
62
+ channels.CHANNELS.VERCEL_AI_EXECUTE_TOOL_CALL,
63
+ (callOptions, telemetry) => ({
64
+ type: "executeTool",
65
+ // v6 carries the tool definitions on the executeToolCall args (a record keyed by name);
66
+ // the shared core reads the matching tool's `description` for the span.
67
+ event: {
68
+ callId: nextCallId(),
69
+ toolCall: callOptions.toolCall,
70
+ tools: callOptions.tools,
71
+ ...recording(telemetry)
72
+ }
73
+ }),
74
+ options
75
+ );
76
+ subscribeResolveLanguageModel(tracingChannel, channels.CHANNELS.VERCEL_AI_RESOLVE_LANGUAGE_MODEL, options);
77
+ } catch {
78
+ debugBuild.DEBUG_BUILD && core.debug.log("Vercel AI orchestrion channel subscription failed.");
79
+ }
80
+ }
81
+ function bindOperation(tracingChannel$1, channelName, build, options) {
82
+ const channel = tracingChannel$1(channelName);
83
+ const buildOperationSpan = (data) => {
84
+ const callOptions = isRecord(data.arguments[0]) ? data.arguments[0] : {};
85
+ const telemetry = isRecord(callOptions.experimental_telemetry) ? callOptions.experimental_telemetry : {};
86
+ if (telemetry.isEnabled === false && !suppressedTelemetry.has(telemetry)) {
87
+ return void 0;
88
+ }
89
+ const message = build(callOptions, telemetry);
90
+ suppressNativeTelemetry(callOptions, telemetry);
91
+ const span = vercelAiDcSubscriber.createSpanFromMessage(message, options);
92
+ if (span) {
93
+ messages.set(data, message);
94
+ operationSpans.add(span);
95
+ const callId = asString(message.event.callId);
96
+ if (callId) {
97
+ callIdBySpan.set(span, callId);
98
+ }
99
+ recordingBySpan.set(span, recording(telemetry));
100
+ }
101
+ return span;
102
+ };
103
+ tracingChannel.bindTracingChannelToSpan(
104
+ channel,
105
+ (data) => buildOperationSpan(data),
106
+ {
107
+ beforeSpanEnd: (span, data) => {
108
+ const message = messages.get(data);
109
+ if (!message) {
110
+ return;
111
+ }
112
+ if (!("error" in data)) {
113
+ message.result = message.type === "executeTool" ? { output: data.result } : data.result;
114
+ vercelAiDcSubscriber.enrichSpanOnEnd(span, message, options);
115
+ }
116
+ if (message.type !== "streamText") {
117
+ vercelAiDcSubscriber.clearOperationId(message);
118
+ }
119
+ messages.delete(data);
120
+ }
121
+ }
122
+ );
123
+ }
124
+ function suppressNativeTelemetry(callOptions, telemetry) {
125
+ if (telemetry.isEnabled !== true) {
126
+ return;
127
+ }
128
+ const suppressed = { ...telemetry, isEnabled: false };
129
+ suppressedTelemetry.add(suppressed);
130
+ callOptions.experimental_telemetry = suppressed;
131
+ }
132
+ function subscribeResolveLanguageModel(tracingChannel, channelName, options) {
133
+ tracingChannel(channelName).subscribe({
134
+ end(rawCtx) {
135
+ const ctx = rawCtx;
136
+ if (!isRecord(ctx.result)) {
137
+ return;
138
+ }
139
+ const model = ctx.result;
140
+ if (!model[PATCHED]) {
141
+ model[PATCHED] = true;
142
+ patchModelMethod(model, "doGenerate", options);
143
+ patchModelMethod(model, "doStream", options);
144
+ }
145
+ },
146
+ start() {
147
+ },
148
+ asyncStart() {
149
+ },
150
+ asyncEnd() {
151
+ },
152
+ error() {
153
+ }
154
+ });
155
+ }
156
+ function resolveModelCallParent() {
157
+ const active = core.getActiveSpan();
158
+ return active && operationSpans.has(active) ? active : void 0;
159
+ }
160
+ function patchModelMethod(model, method, options) {
161
+ const original = model[method];
162
+ if (typeof original !== "function") {
163
+ return;
164
+ }
165
+ model[method] = function(...args) {
166
+ const parent = resolveModelCallParent();
167
+ if (!parent) {
168
+ return Promise.resolve(original.apply(this, args));
169
+ }
170
+ const callArgs = isRecord(args[0]) ? args[0] : {};
171
+ const callId = callIdBySpan.get(parent);
172
+ const message = {
173
+ type: "languageModelCall",
174
+ event: {
175
+ callId,
176
+ provider: model.provider,
177
+ modelId: model.modelId,
178
+ tools: callArgs.tools,
179
+ messages: callArgs.prompt,
180
+ // Inherit the enclosing operation's per-call recording flags so inputs/tools/outputs are recorded on
181
+ // the model-call span whenever they are on the parent `invoke_agent` span.
182
+ ...recordingBySpan.get(parent)
183
+ }
184
+ };
185
+ const span = core.withActiveSpan(parent, () => vercelAiDcSubscriber.createSpanFromMessage(message, options));
186
+ if (!span) {
187
+ return Promise.resolve(original.apply(this, args));
188
+ }
189
+ const clearStreamCallId = () => {
190
+ if (method === "doStream" && callId) {
191
+ vercelAiDcSubscriber.clearOperationCallId(callId);
192
+ }
193
+ };
194
+ const failSpan = (error) => {
195
+ span.setStatus({ code: core.SPAN_STATUS_ERROR, message: error instanceof Error ? error.message : "unknown_error" });
196
+ span.end();
197
+ clearStreamCallId();
198
+ throw error;
199
+ };
200
+ try {
201
+ const result = Promise.resolve(original.apply(this, args));
202
+ return result.then((value) => {
203
+ message.result = value;
204
+ vercelAiDcSubscriber.enrichSpanOnEnd(span, message, options);
205
+ span.end();
206
+ clearStreamCallId();
207
+ return value;
208
+ }, failSpan);
209
+ } catch (error) {
210
+ return failSpan(error);
211
+ }
212
+ };
213
+ }
214
+ function buildTextMessage(type) {
215
+ return (options, telemetry) => ({
216
+ type,
217
+ event: {
218
+ callId: nextCallId(),
219
+ operationId: `ai.${type}`,
220
+ functionId: asString(telemetry.functionId),
221
+ ...modelFields(options.model),
222
+ maxRetries: options.maxRetries,
223
+ // Normalize to the message-array shape the shared core (and v7's channel) expects: a bare string
224
+ // `prompt` becomes a single user message, matching the SDK's own normalization.
225
+ messages: normalizePromptMessages(options),
226
+ ...recording(telemetry)
227
+ }
228
+ });
229
+ }
230
+ function normalizePromptMessages(options) {
231
+ if (Array.isArray(options.messages)) {
232
+ return options.messages;
233
+ }
234
+ if (typeof options.prompt === "string") {
235
+ return [{ role: "user", content: options.prompt }];
236
+ }
237
+ return options.messages ?? options.prompt;
238
+ }
239
+ function recording(telemetry) {
240
+ return { recordInputs: telemetry.recordInputs, recordOutputs: telemetry.recordOutputs };
241
+ }
242
+ function modelFields(model) {
243
+ return { provider: modelField(model, "provider"), modelId: modelField(model, "modelId") };
244
+ }
245
+ function modelField(model, field) {
246
+ return isRecord(model) ? asString(model[field]) : void 0;
247
+ }
248
+ function asString(value) {
249
+ return typeof value === "string" ? value : void 0;
250
+ }
251
+ function isRecord(value) {
252
+ return typeof value === "object" && value !== null;
253
+ }
254
+
255
+ exports.subscribeVercelAiOrchestrionChannels = subscribeVercelAiOrchestrionChannels;
256
+ //# sourceMappingURL=vercel-ai-orchestrion-v6-subscriber.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vercel-ai-orchestrion-v6-subscriber.js","sources":["../../../src/vercel-ai/vercel-ai-orchestrion-v6-subscriber.ts"],"sourcesContent":["import type { Span } from '@sentry/core';\nimport { debug, getActiveSpan, SPAN_STATUS_ERROR, withActiveSpan } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { bindTracingChannelToSpan, type TracingChannelPayloadWithSpan } from '../tracing-channel';\nimport {\n clearOperationCallId,\n clearOperationId,\n createSpanFromMessage,\n enrichSpanOnEnd,\n type VercelAiChannelMessage,\n type VercelAiChannelOptions,\n type VercelAiTracingChannelFactory,\n} from './vercel-ai-dc-subscriber';\n\n/**\n * v6 channel adapter for the Vercel AI (`ai`) SDK.\n *\n * `ai` >= 7 publishes a normalized `ai:telemetry` tracing channel natively\n * (consumed by `subscribeVercelAiTracingChannel`). v6 has no such channel, so\n * orchestrion injects `orchestrion:ai:*` channels around the top-level\n * functions (see `orchestrion/config/index.ts`). The injected channels carry only the\n * wrapped call's `{ arguments, result, error }` — NOT v7's normalized `event`\n * object — so this adapter reconstructs an equivalent {@link VercelAiChannelMessage}\n * from v6's argument/result shapes and delegates to the SAME span-building core\n * (`createSpanFromMessage` / `enrichSpanOnEnd`) the v7 subscriber uses, so the\n * emitted spans are identical between v6 and v7.\n *\n * The model call (`languageModelCall` / `generate_content` span) has no\n * injectable definition in `ai`, so we instead wrap `resolveLanguageModel` (the\n * single chokepoint every model call flows through) and monkey-patch\n * `doGenerate`/`doStream` on the returned model.\n */\n\n/** Shape orchestrion's transform attaches to the tracing-channel context. */\ninterface OrchestrionContext {\n arguments: unknown[];\n result?: unknown;\n error?: unknown;\n}\n\n/** Builds the normalized message for a channel from the wrapped call's first-arg options. */\ntype MessageBuilder = (options: Record<string, unknown>, telemetry: Record<string, unknown>) => VercelAiChannelMessage;\n\n/** A resolved `ai` language model — has `doGenerate`/`doStream` and identity fields. */\ninterface ResolvedModel {\n modelId?: string;\n provider?: string;\n doGenerate?: (...args: unknown[]) => Promise<unknown>;\n doStream?: (...args: unknown[]) => Promise<unknown>;\n}\n\nconst PATCHED = Symbol('SentryVercelAiModelPatched');\n\n/** A resolved model with our patch bookkeeping (idempotency flag). */\ntype PatchableModel = ResolvedModel & { [PATCHED]?: boolean };\n\n// Per-operation correlation id. No Date/random (unavailable / non-deterministic) — a counter is enough.\nlet callIdCounter = 0;\nfunction nextCallId(): string {\n return `v6-${++callIdCounter}`;\n}\n\n// The message built on `start` for each operation, keyed by the (stable-identity) channel context, so\n// the `beforeSpanEnd` handler can enrich the span from the settled result and clear the `callId` maps.\nconst messages = new WeakMap<object, VercelAiChannelMessage>();\n// The spans we opened for top-level operations, and each one's `callId`. A model call resolves its\n// parent against this set (so it never mis-attributes to the enclosing `main`/user span) and reads the\n// parent's `callId` so its span can be named after the operation (e.g. `ai.streamText.doStream`).\nconst operationSpans = new WeakSet<Span>();\nconst callIdBySpan = new WeakMap<Span, string>();\n// The operation's per-call recording flags (`experimental_telemetry.recordInputs/recordOutputs`), keyed by\n// its span. A model call carries no telemetry of its own, so it inherits the enclosing operation's flags —\n// otherwise a per-call `recordInputs: true` would record inputs on the `invoke_agent` span but not on the\n// child `generate_content` span (whose event would fall back to the global default). v7's channel forwards\n// these flags on every event, so this keeps v6 identical.\nconst recordingBySpan = new WeakMap<Span, ReturnType<typeof recording>>();\n\n// The `experimental_telemetry` objects we swapped in to suppress `ai`'s native OTel spans (see\n// `suppressNativeTelemetry`). Our skip logic treats `isEnabled === false` as \"user disabled telemetry,\n// emit no span\"; without this set, a call whose options object we already neutralized — or a user-shared\n// telemetry object we replaced on a prior call — would be misread as user-disabled and lose its span.\nconst suppressedTelemetry = new WeakSet<object>();\n\nlet subscribed = false;\n\n/**\n * Subscribe the v6 orchestrion channel adapter. Safe to always call: inert on\n * `ai` >= 7 (those channels are never published) and when orchestrion injection\n * isn't active. Idempotent.\n *\n * `tracingChannel` is the platform-provided factory (the same one passed to\n * `subscribeVercelAiTracingChannel`); `options` pins the recording settings at\n * subscribe time so we never look the integration up per event.\n */\nexport function subscribeVercelAiOrchestrionChannels(\n tracingChannel: VercelAiTracingChannelFactory,\n options: VercelAiChannelOptions = {},\n): void {\n if (subscribed) {\n return;\n }\n subscribed = true;\n\n try {\n bindOperation(tracingChannel, CHANNELS.VERCEL_AI_GENERATE_TEXT, buildTextMessage('generateText'), options);\n bindOperation(tracingChannel, CHANNELS.VERCEL_AI_STREAM_TEXT, buildTextMessage('streamText'), options);\n bindOperation(\n tracingChannel,\n CHANNELS.VERCEL_AI_EMBED,\n (callOptions, telemetry) => ({\n type: 'embed',\n event: {\n callId: nextCallId(),\n ...modelFields(callOptions.model),\n maxRetries: callOptions.maxRetries,\n value: callOptions.value,\n ...recording(telemetry),\n },\n }),\n options,\n );\n bindOperation(\n tracingChannel,\n CHANNELS.VERCEL_AI_EMBED_MANY,\n // `embedMany` takes a `values` array (vs `embed`'s single `value`); the shared core reads it as the\n // embeddings input, matching the OTel path's batch `ai.embedMany` span.\n (callOptions, telemetry) => ({\n type: 'embedMany',\n event: {\n callId: nextCallId(),\n ...modelFields(callOptions.model),\n maxRetries: callOptions.maxRetries,\n values: callOptions.values,\n ...recording(telemetry),\n },\n }),\n options,\n );\n bindOperation(\n tracingChannel,\n CHANNELS.VERCEL_AI_EXECUTE_TOOL_CALL,\n (callOptions, telemetry) => ({\n type: 'executeTool',\n // v6 carries the tool definitions on the executeToolCall args (a record keyed by name);\n // the shared core reads the matching tool's `description` for the span.\n event: {\n callId: nextCallId(),\n toolCall: callOptions.toolCall,\n tools: callOptions.tools,\n ...recording(telemetry),\n },\n }),\n options,\n );\n subscribeResolveLanguageModel(tracingChannel, CHANNELS.VERCEL_AI_RESOLVE_LANGUAGE_MODEL, options);\n } catch {\n DEBUG_BUILD && debug.log('Vercel AI orchestrion channel subscription failed.');\n }\n}\n\n/**\n * Bind one operation channel: `getSpan` opens a span from the message reconstructed out of the wrapped\n * call's first argument; `beforeSpanEnd` enriches it from the settled result (tokens, output messages,\n * finish reasons, …) before the helper ends the span.\n *\n * An operation whose `experimental_telemetry.isEnabled` is explicitly `false` is skipped entirely (no\n * span): the orchestrion channel fires regardless of that flag, whereas v7's native `ai:telemetry`\n * channel is simply not published in that case — so we reproduce v7's \"no telemetry → no span\".\n */\nfunction bindOperation(\n tracingChannel: VercelAiTracingChannelFactory,\n channelName: string,\n build: MessageBuilder,\n options: VercelAiChannelOptions,\n): void {\n const channel = tracingChannel<OrchestrionContext>(channelName);\n\n // Build the operation span from the wrapped call's first argument and track it (so a model call can\n // resolve it as its parent). `bindTracingChannelToSpan` calls this once at channel `start` and makes\n // the returned span the active async context for the operation's duration — that active span is what\n // `resolveModelCallParent` reads. It also sets `data._sentrySpan`, so we don't here.\n const buildOperationSpan = (data: TracingChannelPayloadWithSpan<OrchestrionContext>): Span | undefined => {\n const callOptions = isRecord(data.arguments[0]) ? data.arguments[0] : {};\n const telemetry = isRecord(callOptions.experimental_telemetry) ? callOptions.experimental_telemetry : {};\n // `isEnabled === false` means the user opted out — emit no span. But `isEnabled` is also `false` on\n // the telemetry object we swap in to suppress native spans, so don't mistake our own object for a\n // user opt-out (which would drop the span on a call whose options we already neutralized).\n if (telemetry.isEnabled === false && !suppressedTelemetry.has(telemetry)) {\n return undefined;\n }\n const message = build(callOptions, telemetry);\n // Stop `ai` from emitting its own native OTel spans for this call — we build the equivalent spans\n // from the channels, so the SDK's would be duplicates. Reads above have already captured everything\n // we need off `telemetry`.\n suppressNativeTelemetry(callOptions, telemetry);\n const span = createSpanFromMessage(message, options);\n if (span) {\n messages.set(data, message);\n operationSpans.add(span);\n const callId = asString(message.event.callId);\n if (callId) {\n callIdBySpan.set(span, callId);\n }\n recordingBySpan.set(span, recording(telemetry));\n }\n return span;\n };\n\n bindTracingChannelToSpan(\n channel,\n (data: TracingChannelPayloadWithSpan<OrchestrionContext>) => buildOperationSpan(data),\n {\n beforeSpanEnd: (span, data) => {\n const message = messages.get(data);\n if (!message) {\n return;\n }\n // The helper's `error` handler already set the span status; only enrich from a successful result.\n if (!('error' in data)) {\n // v6's `executeToolCall` returns the tool result/error object directly, whereas the shared core\n // (matching v7) expects it nested under `output`; wrap it so tool-error detection works.\n message.result = message.type === 'executeTool' ? { output: data.result } : data.result;\n enrichSpanOnEnd(span, message, options);\n }\n // A `streamText` model call runs after this (synchronously-returning) operation's span has\n // already ended, so its `callId` entry must outlive the operation — it's cleared once the model\n // call settles (see `patchModelMethod`). Every other operation can clear here.\n if (message.type !== 'streamText') {\n clearOperationId(message);\n }\n messages.delete(data);\n },\n },\n );\n}\n\n/**\n * Neutralize `ai`'s native OpenTelemetry instrumentation for this call by pointing\n * `experimental_telemetry` at a copy with `isEnabled: false`. `ai`'s `getTracer` then returns its\n * internal no-op tracer, so it never creates (nor sets active) the duplicate `ai.*` spans we'd\n * otherwise have to drop.\n *\n * Only a call that explicitly enabled telemetry emits native spans — otherwise `ai` already uses its\n * no-op tracer, so there's nothing to suppress and we leave the user's options untouched. When\n * `isEnabled === true`, `telemetry` is `callOptions.experimental_telemetry` and `callOptions` is the\n * real first argument the SDK will read, so the reassignment takes effect for the wrapped call. We\n * replace rather than mutate in place, so a telemetry object the user shares across calls keeps its own\n * `isEnabled: true`; the replacement is tracked in `suppressedTelemetry` so our skip logic doesn't\n * later read it back as a user opt-out.\n */\nfunction suppressNativeTelemetry(callOptions: Record<string, unknown>, telemetry: Record<string, unknown>): void {\n if (telemetry.isEnabled !== true) {\n return;\n }\n const suppressed = { ...telemetry, isEnabled: false };\n suppressedTelemetry.add(suppressed);\n callOptions.experimental_telemetry = suppressed;\n}\n\n/**\n * `resolveLanguageModel` returns the model every call flows through. We don't span it — on `end` we\n * monkey-patch `doGenerate`/`doStream` on the returned model so each invocation produces a\n * `languageModelCall` span parented to the enclosing invoke_agent span.\n */\nfunction subscribeResolveLanguageModel(\n tracingChannel: VercelAiTracingChannelFactory,\n channelName: string,\n options: VercelAiChannelOptions,\n): void {\n tracingChannel<OrchestrionContext>(channelName).subscribe({\n end(rawCtx) {\n const ctx = rawCtx as OrchestrionContext;\n if (!isRecord(ctx.result)) {\n return;\n }\n const model = ctx.result as PatchableModel;\n // Patch the model's `doGenerate`/`doStream` once. The model call recovers its parent from the\n // active async context at call time (the operation span `bindTracingChannelToSpan` bound), which\n // propagates into the model call for `streamText` too, so there is nothing to capture on the model here.\n if (!model[PATCHED]) {\n model[PATCHED] = true;\n patchModelMethod(model, 'doGenerate', options);\n patchModelMethod(model, 'doStream', options);\n }\n },\n start() {\n /* no-op */\n },\n asyncStart() {\n /* no-op */\n },\n asyncEnd() {\n /* no-op */\n },\n error() {\n /* no-op */\n },\n });\n}\n\n/**\n * Pick the invoke_agent span a model call should hang under: the operation span that\n * `bindTracingChannelToSpan` planted as the active async context for the enclosing operation.\n *\n * Because we suppress `ai`'s native telemetry (so it never installs its own span as active), the active\n * span inside `doGenerate`/`doStream` is our operation span. The `operationSpans` gate makes this return\n * `undefined` when the active span isn't one of ours — e.g. telemetry was disabled for the call so we\n * opened no operation span and the active span is the user's enclosing span — so the model call is\n * skipped rather than mis-parented.\n *\n * This covers `generateText`/`embed` (whose model call is awaited inside the operation body) and\n * `streamText` alike — `ai` initiates the stream synchronously within the operation's bound context, so\n * the later `doStream` continuation restores the same active span even though the operation's span has\n * already ended. The per-operation binding also disambiguates concurrent calls that share one model\n * instance (a single mutable slot on the shared model could not — it would hold whichever operation\n * resolved the model last).\n */\nfunction resolveModelCallParent(): Span | undefined {\n const active = getActiveSpan();\n return active && operationSpans.has(active) ? active : undefined;\n}\n\nfunction patchModelMethod(\n model: PatchableModel,\n method: 'doGenerate' | 'doStream',\n options: VercelAiChannelOptions,\n): void {\n const original = model[method];\n if (typeof original !== 'function') {\n return;\n }\n model[method] = function (this: unknown, ...args: unknown[]): Promise<unknown> {\n const parent = resolveModelCallParent();\n // No enclosing operation span (e.g. telemetry disabled for the call) → don't open a model-call span.\n if (!parent) {\n return Promise.resolve(original.apply(this, args));\n }\n\n const callArgs = isRecord(args[0]) ? args[0] : {};\n // Carry the operation's `callId` so the shared core can name the span after it\n // (`ai.generateText.doGenerate` / `ai.streamText.doStream`).\n const callId = callIdBySpan.get(parent);\n const message: VercelAiChannelMessage = {\n type: 'languageModelCall',\n event: {\n callId,\n provider: model.provider,\n modelId: model.modelId,\n tools: callArgs.tools,\n messages: callArgs.prompt,\n // Inherit the enclosing operation's per-call recording flags so inputs/tools/outputs are recorded on\n // the model-call span whenever they are on the parent `invoke_agent` span.\n ...recordingBySpan.get(parent),\n },\n };\n const span = withActiveSpan(parent, () => createSpanFromMessage(message, options));\n // `languageModelCall` always opens a span; the guard just keeps the wrapper safe if that changes.\n if (!span) {\n return Promise.resolve(original.apply(this, args));\n }\n\n // `streamText` ends its operation span synchronously, so its `callId` entry was deliberately left in\n // place for this later model call; drop it now that we've used it.\n const clearStreamCallId = (): void => {\n if (method === 'doStream' && callId) {\n clearOperationCallId(callId);\n }\n };\n\n // Both the synchronous throw and the async rejection of the model call must end the span with an\n // error status (an `async` `doGenerate`/`doStream` that throws rejects rather than throwing here).\n const failSpan = (error: unknown): never => {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: error instanceof Error ? error.message : 'unknown_error' });\n span.end();\n clearStreamCallId();\n throw error;\n };\n\n try {\n const result = Promise.resolve(original.apply(this, args));\n // `doStream` resolves to `{ stream, ... }` before the stream is consumed; we end here (start/end\n // bracket the call) to match the channel timing.\n return result.then(value => {\n message.result = value;\n enrichSpanOnEnd(span, message, options);\n span.end();\n clearStreamCallId();\n return value;\n }, failSpan);\n } catch (error) {\n return failSpan(error);\n }\n };\n}\n\nfunction buildTextMessage(type: 'generateText' | 'streamText'): MessageBuilder {\n return (options, telemetry) => ({\n type,\n event: {\n callId: nextCallId(),\n operationId: `ai.${type}`,\n functionId: asString(telemetry.functionId),\n ...modelFields(options.model),\n maxRetries: options.maxRetries,\n // Normalize to the message-array shape the shared core (and v7's channel) expects: a bare string\n // `prompt` becomes a single user message, matching the SDK's own normalization.\n messages: normalizePromptMessages(options),\n ...recording(telemetry),\n },\n });\n}\n\nfunction normalizePromptMessages(options: Record<string, unknown>): unknown {\n if (Array.isArray(options.messages)) {\n return options.messages;\n }\n if (typeof options.prompt === 'string') {\n return [{ role: 'user', content: options.prompt }];\n }\n return options.messages ?? options.prompt;\n}\n\nfunction recording(telemetry: Record<string, unknown>): { recordInputs: unknown; recordOutputs: unknown } {\n return { recordInputs: telemetry.recordInputs, recordOutputs: telemetry.recordOutputs };\n}\n\nfunction modelFields(model: unknown): { provider?: string; modelId?: string } {\n return { provider: modelField(model, 'provider'), modelId: modelField(model, 'modelId') };\n}\n\nfunction modelField(model: unknown, field: 'modelId' | 'provider'): string | undefined {\n return isRecord(model) ? asString(model[field]) : undefined;\n}\n\nfunction asString(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n"],"names":["CHANNELS","DEBUG_BUILD","debug","tracingChannel","createSpanFromMessage","bindTracingChannelToSpan","enrichSpanOnEnd","clearOperationId","getActiveSpan","withActiveSpan","clearOperationCallId","SPAN_STATUS_ERROR"],"mappings":";;;;;;;;AAoDA,MAAM,OAAA,0BAAiB,4BAA4B,CAAA;AAMnD,IAAI,aAAA,GAAgB,CAAA;AACpB,SAAS,UAAA,GAAqB;AAC5B,EAAA,OAAO,CAAA,GAAA,EAAM,EAAE,aAAa,CAAA,CAAA;AAC9B;AAIA,MAAM,QAAA,uBAAe,OAAA,EAAwC;AAI7D,MAAM,cAAA,uBAAqB,OAAA,EAAc;AACzC,MAAM,YAAA,uBAAmB,OAAA,EAAsB;AAM/C,MAAM,eAAA,uBAAsB,OAAA,EAA4C;AAMxE,MAAM,mBAAA,uBAA0B,OAAA,EAAgB;AAEhD,IAAI,UAAA,GAAa,KAAA;AAWV,SAAS,oCAAA,CAC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AO,OAAA,CAAQ,QAAA;AAAA,EACjB;AACA,EAAA,IAAI,OAAO,OAAA,CAAQ,MAAA,KAAW,QAAA,EAAU;AACtC,IAAA,OAAO,CAAC,EAAE,IAAA,EAAM,QAAQ,OAAA,EAAS,OAAA,CAAQ,QAAQ,CAAA;AAAA,EACnD;AACA,EAAA,OAAO,OAAA,CAAQ,YAAY,OAAA,CAAQ,MAAA;AACrC;AAEA,SAAS,UAAU,SAAA,EAAuF;AACxG,EAAA,OAAO,EAAE,YAAA,EAAc,SAAA,CAAU,YAAA,EAAc,aAAA,EAAe,UAAU,aAAA,EAAc;AACxF;AAEA,SAAS,YAAY,KAAA,EAAyD;AAC5E,EAAA,OAAO,EAAE,QAAA,EAAU,UAAA,CAAW,KAAA,EAAO,UAAU,GAAG,OAAA,EAAS,UAAA,CAAW,KAAA,EAAO,SAAS,CAAA,EAAE;AAC1F;AAEA,SAAS,UAAA,CAAW,OAAgB,KAAA,EAAmD;AACrF,EAAA,OAAO,SAAS,KAAK,CAAA,GAAI,SAAS,KAAA,CAAM,KAAK,CAAC,CAAA,GAAI,MAAA;AACpD;AAEA,SAAS,SAAS,KAAA,EAAoC;AACpD,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,GAAW,KAAA,GAAQ,MAAA;AAC7C;AAEA,SAAS,SAAS,KAAA,EAAkD;AAClE,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,IAAA;AAChD;;;;"}
@@ -1,4 +1,6 @@
1
+ export { mongooseIntegration } from './mongoose/index.js';
1
2
  export { IOREDIS_DC_CHANNEL_COMMAND, IOREDIS_DC_CHANNEL_CONNECT, REDIS_DC_CHANNEL_BATCH, REDIS_DC_CHANNEL_COMMAND, REDIS_DC_CHANNEL_CONNECT, subscribeRedisDiagnosticChannels } from './redis/redis-dc-subscriber.js';
3
+ export { defaultDbStatementSerializer } from './redis/redis-statement-serializer.js';
2
4
  export { bindTracingChannelToSpan } from './tracing-channel.js';
3
5
  export { vercelAiIntegration } from './vercel-ai/index.js';
4
6
  export { fastifyIntegration, handleFastifyError, instrumentFastify } from './integrations/tracing-channel/fastify/index.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;"}
@@ -0,0 +1,99 @@
1
+ import * as diagnosticsChannel from 'node:diagnostics_channel';
2
+ import { defineIntegration, waitForTracingChannelBinding, debug, _INTERNAL_shouldSkipAiProviderWrapping, resolveAIRecordingOptions, shouldEnableTruncation, extractAnthropicRequestAttributes, GEN_AI_REQUEST_MODEL_ATTRIBUTE, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, startInactiveSpan, addAnthropicRequestAttributes, addAnthropicResponseAttributes, instrumentAsyncIterableStream, instrumentMessageStream } from '@sentry/core';
3
+ import { DEBUG_BUILD } from '../../debug-build.js';
4
+ import { CHANNELS } from '../../orchestrion/channels.js';
5
+ import { bindTracingChannelToSpan } from '../../tracing-channel.js';
6
+
7
+ const INTEGRATION_NAME = "Anthropic_AI";
8
+ const ORIGIN = "auto.ai.orchestrion.anthropic";
9
+ const INSTRUMENTED_CHANNELS = [
10
+ { channel: CHANNELS.ANTHROPIC_CHAT, operation: "chat", methodPath: "messages.create", stream: "async-iterable" },
11
+ { channel: CHANNELS.ANTHROPIC_MODELS, operation: "models", methodPath: "models.retrieve", stream: "none" },
12
+ {
13
+ channel: CHANNELS.ANTHROPIC_MESSAGES_STREAM,
14
+ operation: "chat",
15
+ methodPath: "messages.stream",
16
+ stream: "message-stream"
17
+ }
18
+ ];
19
+ let subscribed = false;
20
+ const _anthropicChannelIntegration = ((options = {}) => {
21
+ return {
22
+ name: INTEGRATION_NAME,
23
+ setupOnce() {
24
+ if (!diagnosticsChannel.tracingChannel || subscribed) {
25
+ return;
26
+ }
27
+ subscribed = true;
28
+ waitForTracingChannelBinding(() => {
29
+ for (const { channel, operation, methodPath, stream } of INSTRUMENTED_CHANNELS) {
30
+ DEBUG_BUILD && debug.log(`[orchestrion:anthropic] subscribing to channel "${channel}"`);
31
+ bindTracingChannelToSpan(
32
+ diagnosticsChannel.tracingChannel(channel),
33
+ (data) => createGenAiSpan(data, operation, methodPath, options),
34
+ {
35
+ beforeSpanEnd: (span, data) => {
36
+ addAnthropicResponseAttributes(
37
+ span,
38
+ data.result,
39
+ resolveAIRecordingOptions(options).recordOutputs
40
+ );
41
+ },
42
+ deferSpanEnd: ({ span, data }) => wrapStreamResult(span, data, stream, options)
43
+ }
44
+ );
45
+ }
46
+ });
47
+ }
48
+ };
49
+ });
50
+ function createGenAiSpan(data, operation, methodPath, options) {
51
+ const args = data.arguments ?? [];
52
+ if (_INTERNAL_shouldSkipAiProviderWrapping(INTEGRATION_NAME)) {
53
+ return void 0;
54
+ }
55
+ const requestOptions = args[1];
56
+ if (requestOptions?.headers?.["X-Stainless-Helper-Method"] === "stream") {
57
+ return void 0;
58
+ }
59
+ const params = typeof args[0] === "object" && args[0] !== null ? args[0] : void 0;
60
+ const { recordInputs } = resolveAIRecordingOptions(options);
61
+ const enableTruncation = shouldEnableTruncation(options.enableTruncation);
62
+ const attributes = extractAnthropicRequestAttributes(args, methodPath, operation);
63
+ const model = attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] || "unknown";
64
+ attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] = ORIGIN;
65
+ const span = startInactiveSpan({
66
+ name: `${operation} ${model}`,
67
+ op: `gen_ai.${operation}`,
68
+ attributes
69
+ });
70
+ if (recordInputs && params) {
71
+ addAnthropicRequestAttributes(span, params, enableTruncation);
72
+ }
73
+ return span;
74
+ }
75
+ function isAsyncIterable(value) {
76
+ return !!value && typeof value[Symbol.asyncIterator] === "function";
77
+ }
78
+ function isMessageStream(value) {
79
+ return !!value && typeof value.on === "function";
80
+ }
81
+ function wrapStreamResult(span, data, stream, options) {
82
+ const { recordOutputs } = resolveAIRecordingOptions(options);
83
+ const result = data.result;
84
+ if (stream === "async-iterable" && isAsyncIterable(result)) {
85
+ const iterate = result[Symbol.asyncIterator].bind(result);
86
+ const instrumented = instrumentAsyncIterableStream({ [Symbol.asyncIterator]: iterate }, span, recordOutputs);
87
+ result[Symbol.asyncIterator] = () => instrumented;
88
+ return true;
89
+ }
90
+ if (stream === "message-stream" && isMessageStream(result)) {
91
+ instrumentMessageStream(result, span, recordOutputs);
92
+ return true;
93
+ }
94
+ return false;
95
+ }
96
+ const anthropicChannelIntegration = defineIntegration(_anthropicChannelIntegration);
97
+
98
+ export { anthropicChannelIntegration };
99
+ //# sourceMappingURL=anthropic.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"anthropic.js","sources":["../../../../src/integrations/tracing-channel/anthropic.ts"],"sourcesContent":["import * as diagnosticsChannel from 'node:diagnostics_channel';\nimport type { AnthropicAiOptions, AnthropicAiResponse, IntegrationFn, Span, SpanAttributeValue } from '@sentry/core';\nimport {\n _INTERNAL_shouldSkipAiProviderWrapping,\n addAnthropicRequestAttributes,\n addAnthropicResponseAttributes,\n debug,\n defineIntegration,\n extractAnthropicRequestAttributes,\n GEN_AI_REQUEST_MODEL_ATTRIBUTE,\n instrumentAsyncIterableStream,\n instrumentMessageStream,\n resolveAIRecordingOptions,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n shouldEnableTruncation,\n startInactiveSpan,\n waitForTracingChannelBinding,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\n\n// Same name as the OTel integration by design: when enabled, the OTel 'Anthropic_AI'\n// integration is dropped from the default set (see the Node opt-in loader).\nconst INTEGRATION_NAME = 'Anthropic_AI' as const;\n\n// Distinct from the proxy's `auto.ai.anthropic` so spans from the orchestrion path\n// are attributable separately from the OTel/proxy one.\nconst ORIGIN = 'auto.ai.orchestrion.anthropic';\n\n// `stream` determines how the span is ended\nconst INSTRUMENTED_CHANNELS = [\n { channel: CHANNELS.ANTHROPIC_CHAT, operation: 'chat', methodPath: 'messages.create', stream: 'async-iterable' },\n { channel: CHANNELS.ANTHROPIC_MODELS, operation: 'models', methodPath: 'models.retrieve', stream: 'none' },\n {\n channel: CHANNELS.ANTHROPIC_MESSAGES_STREAM,\n operation: 'chat',\n methodPath: 'messages.stream',\n stream: 'message-stream',\n },\n] as const;\n\ntype StreamMode = (typeof INSTRUMENTED_CHANNELS)[number]['stream'];\n\ninterface AnthropicChannelContext {\n arguments: unknown[];\n result?: unknown;\n}\n\nlet subscribed = false;\n\nconst _anthropicChannelIntegration = ((options: AnthropicAiOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n // tracingChannel is unavailable before Node 18.19 and prevent double-subscribe\n if (!diagnosticsChannel.tracingChannel || subscribed) {\n return;\n }\n subscribed = true;\n\n // `bindTracingChannelToSpan` needs the async-context binding that `initOpenTelemetry()` registers\n // after `setupOnce` runs, so wait for it before subscribing.\n waitForTracingChannelBinding(() => {\n for (const { channel, operation, methodPath, stream } of INSTRUMENTED_CHANNELS) {\n DEBUG_BUILD && debug.log(`[orchestrion:anthropic] subscribing to channel \"${channel}\"`);\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<AnthropicChannelContext>(channel),\n data => createGenAiSpan(data, operation, methodPath, options),\n {\n beforeSpanEnd: (span, data) => {\n addAnthropicResponseAttributes(\n span,\n data.result as AnthropicAiResponse,\n resolveAIRecordingOptions(options).recordOutputs,\n );\n },\n deferSpanEnd: ({ span, data }) => wrapStreamResult(span, data, stream, options),\n },\n );\n }\n });\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Build the span for an instrumented call.\n * Returning `undefined` opts the payload out so no span is opened.\n */\nfunction createGenAiSpan(\n data: AnthropicChannelContext,\n operation: string,\n methodPath: string,\n options: AnthropicAiOptions,\n): Span | undefined {\n const args = data.arguments ?? [];\n\n // When LangChain (or another provider) is driving the SDK, it records the spans itself and marks this\n // provider as skipped — mirror the OTel integration and don't double-instrument.\n if (_INTERNAL_shouldSkipAiProviderWrapping(INTEGRATION_NAME)) {\n return undefined;\n }\n\n // `messages.stream()` internally calls the instrumented `messages.create({ stream: true })` tagged with\n // an `X-Stainless-Helper-Method: 'stream'` header. The messages-stream channel already covers it, so skip\n // the nested create to avoid a duplicate span.\n const requestOptions = args[1] as { headers?: Record<string, unknown> } | undefined;\n if (requestOptions?.headers?.['X-Stainless-Helper-Method'] === 'stream') {\n return undefined;\n }\n\n const params = typeof args[0] === 'object' && args[0] !== null ? (args[0] as Record<string, unknown>) : undefined;\n\n const { recordInputs } = resolveAIRecordingOptions(options);\n const enableTruncation = shouldEnableTruncation(options.enableTruncation);\n\n const attributes = extractAnthropicRequestAttributes(args, methodPath, operation);\n const model = (attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] as string) || 'unknown';\n attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] = ORIGIN;\n\n const span = startInactiveSpan({\n name: `${operation} ${model}`,\n op: `gen_ai.${operation}`,\n attributes: attributes as Record<string, SpanAttributeValue>,\n });\n\n if (recordInputs && params) {\n addAnthropicRequestAttributes(span, params, enableTruncation);\n }\n\n return span;\n}\n\ntype AsyncIterableStream = { [Symbol.asyncIterator]: () => AsyncIterator<unknown> };\ntype MessageStreamEmitter = { on: (...args: unknown[]) => void };\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterableStream {\n return !!value && typeof (value as AsyncIterableStream)[Symbol.asyncIterator] === 'function';\n}\n\nfunction isMessageStream(value: unknown): value is MessageStreamEmitter {\n return !!value && typeof (value as MessageStreamEmitter).on === 'function';\n}\n\n/**\n * Hand span-ending ownership to a streamed result: returns `true` to skip the normal `beforeSpanEnd`,\n * `false` for non-streaming results (which end via `beforeSpanEnd`).\n *\n * - `async-iterable`: patch the `Stream`'s async iterator in place so `instrumentAsyncIterableStream` ends\n * the span when iteration finishes.\n * - `message-stream`: `instrumentMessageStream` attaches `'message'`/`'error'` listeners that end the span.\n */\nfunction wrapStreamResult(\n span: Span,\n data: AnthropicChannelContext,\n stream: StreamMode,\n options: AnthropicAiOptions,\n): boolean {\n const { recordOutputs } = resolveAIRecordingOptions(options);\n const result = data.result;\n\n if (stream === 'async-iterable' && isAsyncIterable(result)) {\n const iterate = result[Symbol.asyncIterator].bind(result);\n const instrumented = instrumentAsyncIterableStream({ [Symbol.asyncIterator]: iterate }, span, recordOutputs);\n result[Symbol.asyncIterator] = () => instrumented;\n return true;\n }\n\n if (stream === 'message-stream' && isMessageStream(result)) {\n instrumentMessageStream(result, span, recordOutputs);\n return true;\n }\n\n return false;\n}\n\n/**\n * EXPERIMENTAL — orchestrion-driven Anthropic integration. Subscribes to the `orchestrion:@anthropic-ai/sdk:*`\n * diagnostics_channels injected into the SDK's chat (`messages`/`completions`/beta `messages`), `models`, and\n * `messages.stream()` methods, so it requires the orchestrion runtime hook or bundler plugin.\n */\nexport const anthropicChannelIntegration = defineIntegration(_anthropicChannelIntegration);\n"],"names":[],"mappings":";;;;;;AAwBA,MAAM,gBAAA,GAAmB,cAAA;AAIzB,MAAM,MAAA,GAAS,+BAAA;AAGf,MAAM,qBAAA,GAAwB;AAAA,EAC5B,EAAE,SAAS,QAAA,CAAS,cAAA,EAAgB,WAAW,MAAA,EAAQ,UAAA,EAAY,iBAAA,EAAmB,MAAA,EAAQ,gBAAA,EAAiB;AAAA,EAC/G,EAAE,SAAS,QAAA,CAAS,gBAAA,EAAkB,WAAW,QAAA,EAAU,UAAA,EAAY,iBAAA,EAAmB,MAAA,EAAQ,MAAA,EAAO;AAAA,EACzG;AAAA,IACE,SAAS,QAAA,CAAS,yBAAA;AAAA,IAClB,SAAA,EAAW,MAAA;AAAA,IACX,UAAA,EAAY,iBAAA;AAAA,IACZ,MAAA,EAAQ;AAAA;AAEZ,CAAA;AASA,IAAI,UAAA,GAAa,KAAA;AAEjB,MAAM,4BAAA,IAAgC,CAAC,OAAA,GAA8B,EAAC,KAAM;AAC1E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AA,CACP,IAAA,EACA,IAAA,EACA,MAAA,EACA,OAAA,EACS;AACT,EAAA,MAAM,EAAE,aAAA,EAAc,GAAI,yBAAA,CAA0B,OAAO,CAAA;AAC3D,EAAA,MAAM,SAAS,IAAA,CAAK,MAAA;AAEpB,EAAA,IAAI,MAAA,KAAW,gBAAA,IAAoB,eAAA,CAAgB,MAAM,CAAA,EAAG;AAC1D,IAAA,MAAM,UAAU,MAAA,CAAO,MAAA,CAAO,aAAa,CAAA,CAAE,KAAK,MAAM,CAAA;AACxD,IAAA,MAAM,YAAA,GAAe,6BAAA,CAA8B,EAAE,CAAC,MAAA,CAAO,aAAa,GAAG,OAAA,EAAQ,EAAG,IAAA,EAAM,aAAa,CAAA;AAC3G,IAAA,MAAA,CAAO,MAAA,CAAO,aAAa,CAAA,GAAI,MAAM,YAAA;AACrC,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,IAAI,MAAA,KAAW,gBAAA,IAAoB,eAAA,CAAgB,MAAM,CAAA,EAAG;AAC1D,IAAA,uBAAA,CAAwB,MAAA,EAAQ,MAAM,aAAa,CAAA;AACnD,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,OAAO,KAAA;AACT;AAOO,MAAM,2BAAA,GAA8B,kBAAkB,4BAA4B;;;;"}
@@ -0,0 +1,25 @@
1
+ const LIFECYCLE_EXT_POINTS = [
2
+ "onPreAuth",
3
+ "onCredentials",
4
+ "onPostAuth",
5
+ "onPreHandler",
6
+ "onPostHandler",
7
+ "onPreResponse",
8
+ "onRequest"
9
+ ];
10
+ const handlerPatched = /* @__PURE__ */ Symbol("hapi-handler-patched");
11
+ const HapiLayerType = {
12
+ ROUTER: "router",
13
+ PLUGIN: "plugin",
14
+ EXT: "server.ext"
15
+ };
16
+ const HapiLifecycleMethodNames = new Set(LIFECYCLE_EXT_POINTS);
17
+ var AttributeNames = /* @__PURE__ */ ((AttributeNames2) => {
18
+ AttributeNames2["HAPI_TYPE"] = "hapi.type";
19
+ AttributeNames2["PLUGIN_NAME"] = "hapi.plugin.name";
20
+ AttributeNames2["EXT_TYPE"] = "server.ext.type";
21
+ return AttributeNames2;
22
+ })(AttributeNames || {});
23
+
24
+ export { AttributeNames, HapiLayerType, HapiLifecycleMethodNames, handlerPatched };
25
+ //# sourceMappingURL=hapi-types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hapi-types.js","sources":["../../../../src/integrations/tracing-channel/hapi-types.ts"],"sourcesContent":["/*\n * Structural type definitions and constants ported from the vendored\n * `@opentelemetry/instrumentation-hapi` types, with all `@hapi/*` and\n * `@opentelemetry/*` dependencies removed. Only the shapes actually accessed by\n * the orchestrion hapi subscriber are kept.\n */\n\n// Single source of truth for the request lifecycle extension points, so the\n// `ServerRequestExtType` union and the runtime `HapiLifecycleMethodNames` set\n// below can't drift apart.\nconst LIFECYCLE_EXT_POINTS = [\n 'onPreAuth',\n 'onCredentials',\n 'onPostAuth',\n 'onPreHandler',\n 'onPostHandler',\n 'onPreResponse',\n 'onRequest',\n] as const;\n\nexport type ServerRequestExtType = (typeof LIFECYCLE_EXT_POINTS)[number];\n\nexport type LifecycleMethod = (request: unknown, h: unknown, err?: Error) => unknown;\n\nexport interface ServerRouteOptions {\n handler?: LifecycleMethod | unknown;\n [key: string]: unknown;\n}\n\nexport interface ServerRoute {\n path: string;\n method: string;\n handler?: LifecycleMethod | unknown;\n options?: ((server: unknown) => ServerRouteOptions) | ServerRouteOptions;\n [key: string]: unknown;\n}\n\nexport interface ServerExtEventsObject {\n type: string;\n [key: string]: unknown;\n}\n\nexport interface ServerExtEventsRequestObject {\n type: ServerRequestExtType;\n method: LifecycleMethod;\n [key: string]: unknown;\n}\n\nexport interface ServerExtOptions {\n [key: string]: unknown;\n}\n\n/**\n * This symbol is used to mark a Hapi route handler or server extension handler as\n * already patched, since it's possible to use these handlers multiple times\n * i.e. when allowing multiple versions of one plugin, or when registering a plugin\n * multiple times on different servers.\n */\nexport const handlerPatched: unique symbol = Symbol('hapi-handler-patched');\n\nexport type PatchableServerRoute = ServerRoute & {\n [handlerPatched]?: boolean;\n};\n\nexport type PatchableExtMethod = LifecycleMethod & {\n [handlerPatched]?: boolean;\n};\n\nexport type ServerExtDirectInput = [ServerRequestExtType, LifecycleMethod, (ServerExtOptions | undefined)?];\n\nexport const HapiLayerType = {\n ROUTER: 'router',\n PLUGIN: 'plugin',\n EXT: 'server.ext',\n} as const;\n\nexport const HapiLifecycleMethodNames = new Set<string>(LIFECYCLE_EXT_POINTS);\n\nexport enum AttributeNames {\n HAPI_TYPE = 'hapi.type',\n PLUGIN_NAME = 'hapi.plugin.name',\n EXT_TYPE = 'server.ext.type',\n}\n"],"names":["AttributeNames"],"mappings":"AAUA,MAAM,oBAAA,GAAuB;AAAA,EAC3B,WAAA;AAAA,EACA,eAAA;AAAA,EACA,YAAA;AAAA,EACA,cAAA;AAAA,EACA,eAAA;AAAA,EACA,eAAA;AAAA,EACA;AACF,CAAA;AAwCO,MAAM,cAAA,0BAAuC,sBAAsB;AAYnE,MAAM,aAAA,GAAgB;AAAA,EAC3B,MAAA,EAAQ,QAAA;AAAA,EACR,MAAA,EAAQ,QAAA;AAAA,EACR,GAAA,EAAK;AACP;AAEO,MAAM,wBAAA,GAA2B,IAAI,GAAA,CAAY,oBAAoB;AAErE,IAAK,cAAA,qBAAAA,eAAAA,KAAL;AACL,EAAAA,gBAAA,WAAA,CAAA,GAAY,WAAA;AACZ,EAAAA,gBAAA,aAAA,CAAA,GAAc,kBAAA;AACd,EAAAA,gBAAA,UAAA,CAAA,GAAW,iBAAA;AAHD,EAAA,OAAAA,eAAAA;AAAA,CAAA,EAAA,cAAA,IAAA,EAAA;;;;"}
@@ -0,0 +1,172 @@
1
+ import { getActiveSpan, getRootSpan, spanToJSON, SEMANTIC_ATTRIBUTE_SENTRY_OP, startSpan, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '@sentry/core';
2
+ import { HTTP_ROUTE, HTTP_METHOD } from '@sentry/conventions/attributes';
3
+ import { handlerPatched, HapiLifecycleMethodNames, HapiLayerType, AttributeNames } from './hapi-types.js';
4
+
5
+ function setHttpServerSpanRouteAttribute(route) {
6
+ const activeSpan = getActiveSpan();
7
+ if (!activeSpan) {
8
+ return;
9
+ }
10
+ const rootSpan = getRootSpan(activeSpan);
11
+ if (!rootSpan) {
12
+ return;
13
+ }
14
+ if (spanToJSON(rootSpan).data[SEMANTIC_ATTRIBUTE_SENTRY_OP] !== "http.server") {
15
+ return;
16
+ }
17
+ rootSpan.setAttribute(HTTP_ROUTE, route);
18
+ }
19
+ const isLifecycleExtType = (variableToCheck) => {
20
+ return typeof variableToCheck === "string" && HapiLifecycleMethodNames.has(variableToCheck);
21
+ };
22
+ const isLifecycleExtEventObj = (variableToCheck) => {
23
+ const event = variableToCheck?.type;
24
+ return event !== void 0 && isLifecycleExtType(event);
25
+ };
26
+ const isDirectExtInput = (variableToCheck) => {
27
+ return Array.isArray(variableToCheck) && variableToCheck.length <= 3 && isLifecycleExtType(variableToCheck[0]) && typeof variableToCheck[1] === "function";
28
+ };
29
+ const isPatchableExtMethod = (variableToCheck) => {
30
+ return !Array.isArray(variableToCheck);
31
+ };
32
+ const getRouteMetadata = (route, pluginName) => {
33
+ const attributes = {
34
+ [HTTP_ROUTE]: route.path,
35
+ // eslint-disable-next-line typescript/no-deprecated -- TODO(v11): Replace deprecated attributes
36
+ [HTTP_METHOD]: route.method
37
+ };
38
+ let name;
39
+ if (pluginName) {
40
+ attributes[AttributeNames.HAPI_TYPE] = HapiLayerType.PLUGIN;
41
+ attributes[AttributeNames.PLUGIN_NAME] = pluginName;
42
+ name = `${pluginName}: route - ${route.path}`;
43
+ } else {
44
+ attributes[AttributeNames.HAPI_TYPE] = HapiLayerType.ROUTER;
45
+ name = `route - ${route.path}`;
46
+ }
47
+ return { attributes, name };
48
+ };
49
+ const getExtMetadata = (extPoint, pluginName, methodName) => {
50
+ let baseName = `ext - ${extPoint}`;
51
+ if (methodName && methodName !== "method") {
52
+ baseName = `ext - ${extPoint} - ${methodName}`;
53
+ }
54
+ if (pluginName) {
55
+ return {
56
+ attributes: {
57
+ [AttributeNames.EXT_TYPE]: extPoint,
58
+ [AttributeNames.HAPI_TYPE]: HapiLayerType.EXT,
59
+ [AttributeNames.PLUGIN_NAME]: pluginName
60
+ },
61
+ name: `${pluginName}: ${baseName}`
62
+ };
63
+ }
64
+ return {
65
+ attributes: {
66
+ [AttributeNames.EXT_TYPE]: extPoint,
67
+ [AttributeNames.HAPI_TYPE]: HapiLayerType.EXT
68
+ },
69
+ name: baseName
70
+ };
71
+ };
72
+ function startMetadataSpan(metadata, original) {
73
+ return startSpan(
74
+ {
75
+ name: metadata.name,
76
+ op: `${metadata.attributes[AttributeNames.HAPI_TYPE]}.hapi`,
77
+ attributes: {
78
+ ...metadata.attributes,
79
+ [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.http.orchestrion.hapi"
80
+ }
81
+ },
82
+ original
83
+ );
84
+ }
85
+ function wrapRouteHandler(route, pluginName) {
86
+ if (route[handlerPatched] === true) return route;
87
+ route[handlerPatched] = true;
88
+ const wrapHandler = (oldHandler) => {
89
+ return function(...params) {
90
+ if (!getActiveSpan()) {
91
+ return oldHandler.call(this, ...params);
92
+ }
93
+ setHttpServerSpanRouteAttribute(route.path);
94
+ const metadata = getRouteMetadata(route, pluginName);
95
+ return startMetadataSpan(metadata, () => oldHandler.call(this, ...params));
96
+ };
97
+ };
98
+ if (typeof route.handler === "function") {
99
+ route.handler = wrapHandler(route.handler);
100
+ } else if (typeof route.options === "function") {
101
+ const oldOptions = route.options;
102
+ route.options = function(server) {
103
+ const options = oldOptions(server);
104
+ if (typeof options.handler === "function") {
105
+ options.handler = wrapHandler(options.handler);
106
+ }
107
+ return options;
108
+ };
109
+ } else if (typeof route.options?.handler === "function") {
110
+ route.options.handler = wrapHandler(route.options.handler);
111
+ }
112
+ return route;
113
+ }
114
+ function wrapExtMethods(method, extPoint, pluginName) {
115
+ if (Array.isArray(method)) {
116
+ for (let i = 0; i < method.length; i++) {
117
+ method[i] = wrapExtMethods(method[i], extPoint);
118
+ }
119
+ return method;
120
+ } else if (isPatchableExtMethod(method)) {
121
+ if (method[handlerPatched] === true) return method;
122
+ method[handlerPatched] = true;
123
+ const newHandler = function(...params) {
124
+ if (!getActiveSpan()) {
125
+ return method.apply(this, params);
126
+ }
127
+ const metadata = getExtMetadata(extPoint, pluginName, method.name);
128
+ return startMetadataSpan(metadata, () => method.apply(void 0, params));
129
+ };
130
+ newHandler[handlerPatched] = true;
131
+ return newHandler;
132
+ }
133
+ return method;
134
+ }
135
+ function wrapRouteArguments(args, pluginName) {
136
+ const route = args[0];
137
+ if (Array.isArray(route)) {
138
+ for (let i = 0; i < route.length; i++) {
139
+ route[i] = wrapRouteHandler(route[i], pluginName);
140
+ }
141
+ } else {
142
+ args[0] = wrapRouteHandler(route, pluginName);
143
+ }
144
+ }
145
+ function wrapExtArguments(args, pluginName) {
146
+ if (Array.isArray(args[0])) {
147
+ const eventsList = args[0];
148
+ for (let i = 0; i < eventsList.length; i++) {
149
+ const eventObj = eventsList[i];
150
+ if (isLifecycleExtType(eventObj.type)) {
151
+ const lifecycleEventObj = eventObj;
152
+ const handler = wrapExtMethods(lifecycleEventObj.method, eventObj.type, pluginName);
153
+ lifecycleEventObj.method = handler;
154
+ eventsList[i] = lifecycleEventObj;
155
+ }
156
+ }
157
+ return;
158
+ } else if (isDirectExtInput(args)) {
159
+ const extInput = args;
160
+ const method = extInput[1];
161
+ const handler = wrapExtMethods(method, extInput[0], pluginName);
162
+ args[1] = handler;
163
+ return;
164
+ } else if (isLifecycleExtEventObj(args[0])) {
165
+ const lifecycleEventObj = args[0];
166
+ const handler = wrapExtMethods(lifecycleEventObj.method, lifecycleEventObj.type, pluginName);
167
+ lifecycleEventObj.method = handler;
168
+ }
169
+ }
170
+
171
+ export { getExtMetadata, getRouteMetadata, wrapExtArguments, wrapRouteArguments };
172
+ //# sourceMappingURL=hapi-utils.js.map