braintrust 3.25.0 → 3.26.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 (78) hide show
  1. package/NOTICE +6 -0
  2. package/dev/dist/index.d.mts +130 -2
  3. package/dev/dist/index.d.ts +130 -2
  4. package/dev/dist/index.js +2455 -1116
  5. package/dev/dist/index.mjs +1599 -260
  6. package/dist/apply-auto-instrumentation.js +439 -398
  7. package/dist/apply-auto-instrumentation.mjs +242 -201
  8. package/dist/auto-instrumentations/bundler/esbuild.cjs +853 -337
  9. package/dist/auto-instrumentations/bundler/esbuild.d.mts +4 -4
  10. package/dist/auto-instrumentations/bundler/esbuild.d.ts +4 -4
  11. package/dist/auto-instrumentations/bundler/esbuild.mjs +5 -8
  12. package/dist/auto-instrumentations/bundler/next.cjs +852 -356
  13. package/dist/auto-instrumentations/bundler/next.mjs +6 -29
  14. package/dist/auto-instrumentations/bundler/rollup.cjs +853 -337
  15. package/dist/auto-instrumentations/bundler/rollup.d.mts +4 -4
  16. package/dist/auto-instrumentations/bundler/rollup.d.ts +4 -4
  17. package/dist/auto-instrumentations/bundler/rollup.mjs +5 -8
  18. package/dist/auto-instrumentations/bundler/vite.cjs +853 -337
  19. package/dist/auto-instrumentations/bundler/vite.d.mts +4 -4
  20. package/dist/auto-instrumentations/bundler/vite.d.ts +4 -4
  21. package/dist/auto-instrumentations/bundler/vite.mjs +5 -8
  22. package/dist/auto-instrumentations/bundler/webpack-loader.cjs +1006 -266
  23. package/dist/auto-instrumentations/bundler/webpack-loader.d.ts +20 -12
  24. package/dist/auto-instrumentations/bundler/webpack.cjs +853 -337
  25. package/dist/auto-instrumentations/bundler/webpack.d.mts +4 -4
  26. package/dist/auto-instrumentations/bundler/webpack.d.ts +4 -4
  27. package/dist/auto-instrumentations/bundler/webpack.mjs +5 -4
  28. package/dist/auto-instrumentations/{chunk-JPVCUKTY.mjs → chunk-6E22MYSW.mjs} +165 -73
  29. package/dist/auto-instrumentations/{chunk-VT6DDNKM.mjs → chunk-AKKPLXTP.mjs} +631 -194
  30. package/dist/auto-instrumentations/chunk-NRE4QUQR.mjs +509 -0
  31. package/dist/auto-instrumentations/{chunk-7P6563SW.mjs → chunk-V5LEODRX.mjs} +2 -6
  32. package/dist/auto-instrumentations/{chunk-M6DLIJ2Z.mjs → chunk-XYN63IG5.mjs} +124 -194
  33. package/dist/auto-instrumentations/{chunk-CZ24KNHT.mjs → chunk-XZHHE4Y3.mjs} +77 -68
  34. package/dist/auto-instrumentations/hook.mjs +247 -182
  35. package/dist/auto-instrumentations/index.cjs +557 -48
  36. package/dist/auto-instrumentations/index.d.mts +6 -2
  37. package/dist/auto-instrumentations/index.d.ts +6 -2
  38. package/dist/auto-instrumentations/index.mjs +6 -1
  39. package/dist/auto-instrumentations/loader/cjs-patch.cjs +492 -195
  40. package/dist/auto-instrumentations/loader/cjs-patch.d.mts +2 -2
  41. package/dist/auto-instrumentations/loader/cjs-patch.d.ts +2 -2
  42. package/dist/auto-instrumentations/loader/cjs-patch.mjs +3 -2
  43. package/dist/auto-instrumentations/loader/esm-hook.mjs +1 -1
  44. package/dist/auto-instrumentations/plugin-B-aZh7EP.d.ts +30 -0
  45. package/dist/auto-instrumentations/plugin-Bnj4E_6B.d.mts +30 -0
  46. package/dist/auto-instrumentations/{types-RNPaKi9o.d.mts → types-C1fVeiCp.d.mts} +1 -1
  47. package/dist/auto-instrumentations/{types-RNPaKi9o.d.ts → types-C1fVeiCp.d.ts} +1 -1
  48. package/dist/browser.d.mts +817 -197
  49. package/dist/browser.d.ts +817 -197
  50. package/dist/browser.js +1883 -265
  51. package/dist/browser.mjs +1883 -265
  52. package/dist/{chunk-ABR2QWDP.mjs → chunk-PN7EWK66.mjs} +581 -133
  53. package/dist/{chunk-GSIDVFE6.js → chunk-VRZZQPAA.js} +1670 -736
  54. package/dist/{chunk-P25IOOU4.js → chunk-VYNNEKSA.js} +586 -138
  55. package/dist/{chunk-2SANLSWX.mjs → chunk-XIZOM2HO.mjs} +1052 -118
  56. package/dist/cli.js +1601 -263
  57. package/dist/edge-light.d.mts +1 -1
  58. package/dist/edge-light.d.ts +1 -1
  59. package/dist/edge-light.js +1883 -268
  60. package/dist/edge-light.mjs +1883 -268
  61. package/dist/index.d.mts +817 -197
  62. package/dist/index.d.ts +817 -197
  63. package/dist/index.js +695 -435
  64. package/dist/index.mjs +264 -4
  65. package/dist/instrumentation/index.d.mts +130 -6
  66. package/dist/instrumentation/index.d.ts +130 -6
  67. package/dist/instrumentation/index.js +1510 -80
  68. package/dist/instrumentation/index.mjs +1510 -80
  69. package/dist/vitest-evals-reporter.js +16 -16
  70. package/dist/vitest-evals-reporter.mjs +2 -2
  71. package/dist/workerd.d.mts +1 -1
  72. package/dist/workerd.d.ts +1 -1
  73. package/dist/workerd.js +1883 -268
  74. package/dist/workerd.mjs +1883 -268
  75. package/licenses/node-diagnostics-channel/LICENSE +19 -0
  76. package/package.json +34 -35
  77. package/dist/auto-instrumentations/plugin-D0KHwSJv.d.mts +0 -44
  78. package/dist/auto-instrumentations/plugin-G6fgxk1b.d.ts +0 -44
@@ -1,3 +1,514 @@
1
+ // src/global-instrumentation-hooks.ts
2
+ var GLOBAL_INSTRUMENTATION_HOOKS_KEY = "__braintrust_instrumentation_hooks";
3
+ var GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION = 1;
4
+ var GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND = "braintrust.global-instrumentation-hooks.registry";
5
+ var GLOBAL_INSTRUMENTATION_HOOK_BRAND = "braintrust.global-instrumentation-hooks.hook";
6
+ var registryBrand = Symbol.for(GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND);
7
+ var hookBrand = Symbol.for(GLOBAL_INSTRUMENTATION_HOOK_BRAND);
8
+ var errorReporter;
9
+ function setGlobalHookErrorReporter(reporter) {
10
+ const previousReporter = errorReporter;
11
+ errorReporter = reporter;
12
+ return () => {
13
+ if (errorReporter === reporter) {
14
+ errorReporter = previousReporter;
15
+ }
16
+ };
17
+ }
18
+ function reportError(error) {
19
+ try {
20
+ errorReporter?.(error);
21
+ } catch {
22
+ }
23
+ }
24
+ function setContextValue(context, key, value) {
25
+ try {
26
+ context[key] = value;
27
+ } catch (error) {
28
+ reportError(error);
29
+ }
30
+ }
31
+ function wrapStoreRun(store, message, next, transform) {
32
+ return () => {
33
+ let context;
34
+ try {
35
+ context = transform ? transform(message) : message;
36
+ } catch (error) {
37
+ reportError(error);
38
+ return next();
39
+ }
40
+ let called = false;
41
+ let result;
42
+ let providerError;
43
+ let providerThrew = false;
44
+ const runNext = () => {
45
+ if (called) {
46
+ reportError(
47
+ new Error(
48
+ "Instrumentation store invoked its callback more than once"
49
+ )
50
+ );
51
+ if (providerThrew) {
52
+ throw providerError;
53
+ }
54
+ return result;
55
+ }
56
+ called = true;
57
+ try {
58
+ result = next();
59
+ return result;
60
+ } catch (error) {
61
+ providerThrew = true;
62
+ providerError = error;
63
+ throw error;
64
+ }
65
+ };
66
+ try {
67
+ store.run(context, runNext);
68
+ } catch (error) {
69
+ if (!providerThrew || error !== providerError) {
70
+ reportError(error);
71
+ }
72
+ }
73
+ if (!called) {
74
+ reportError(
75
+ new Error("Instrumentation store did not invoke its callback")
76
+ );
77
+ return runNext();
78
+ }
79
+ if (providerThrew) {
80
+ throw providerError;
81
+ }
82
+ return result;
83
+ };
84
+ }
85
+ var HookChannel = class {
86
+ constructor(name) {
87
+ this.name = name;
88
+ }
89
+ name;
90
+ subscribers = [];
91
+ stores = /* @__PURE__ */ new Map();
92
+ get hasSubscribers() {
93
+ return this.subscribers.length > 0 || this.stores.size > 0;
94
+ }
95
+ subscribe(subscription) {
96
+ if (typeof subscription !== "function") {
97
+ throw new TypeError("subscription must be a function");
98
+ }
99
+ this.subscribers = [...this.subscribers, subscription];
100
+ }
101
+ unsubscribe(subscription) {
102
+ const index = this.subscribers.indexOf(subscription);
103
+ if (index === -1) {
104
+ return false;
105
+ }
106
+ this.subscribers = [
107
+ ...this.subscribers.slice(0, index),
108
+ ...this.subscribers.slice(index + 1)
109
+ ];
110
+ return true;
111
+ }
112
+ bindStore(store, transform) {
113
+ if (!store || typeof store.run !== "function") {
114
+ throw new TypeError("store must have a run method");
115
+ }
116
+ this.stores.set(
117
+ store,
118
+ transform
119
+ );
120
+ }
121
+ unbindStore(store) {
122
+ return this.stores.delete(store);
123
+ }
124
+ publish(message) {
125
+ const subscribers = this.subscribers;
126
+ for (const subscriber of subscribers) {
127
+ try {
128
+ subscriber(message, this.name);
129
+ } catch (error) {
130
+ reportError(error);
131
+ }
132
+ }
133
+ }
134
+ runStores(message, fn, thisArg, ...args) {
135
+ let run = () => {
136
+ this.publish(message);
137
+ return Reflect.apply(fn, thisArg, args);
138
+ };
139
+ for (const [store, transform] of this.stores.entries()) {
140
+ run = wrapStoreRun(store, message, run, transform);
141
+ }
142
+ return run();
143
+ }
144
+ };
145
+ var traceEvents = [
146
+ "start",
147
+ "end",
148
+ "asyncStart",
149
+ "asyncEnd",
150
+ "error"
151
+ ];
152
+ var TracingHook = class {
153
+ start;
154
+ end;
155
+ asyncStart;
156
+ asyncEnd;
157
+ error;
158
+ constructor(nameOrChannels) {
159
+ Object.defineProperty(this, hookBrand, {
160
+ configurable: false,
161
+ enumerable: false,
162
+ value: GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
163
+ writable: false
164
+ });
165
+ if (typeof nameOrChannels === "string") {
166
+ this.start = new HookChannel(`tracing:${nameOrChannels}:start`);
167
+ this.end = new HookChannel(`tracing:${nameOrChannels}:end`);
168
+ this.asyncStart = new HookChannel(`tracing:${nameOrChannels}:asyncStart`);
169
+ this.asyncEnd = new HookChannel(`tracing:${nameOrChannels}:asyncEnd`);
170
+ this.error = new HookChannel(`tracing:${nameOrChannels}:error`);
171
+ return;
172
+ }
173
+ this.start = nameOrChannels.start ?? new HookChannel("tracing:start");
174
+ this.end = nameOrChannels.end ?? new HookChannel("tracing:end");
175
+ this.asyncStart = nameOrChannels.asyncStart ?? new HookChannel("tracing:asyncStart");
176
+ this.asyncEnd = nameOrChannels.asyncEnd ?? new HookChannel("tracing:asyncEnd");
177
+ this.error = nameOrChannels.error ?? new HookChannel("tracing:error");
178
+ }
179
+ get hasSubscribers() {
180
+ return this.start.hasSubscribers || this.end.hasSubscribers || this.asyncStart.hasSubscribers || this.asyncEnd.hasSubscribers || this.error.hasSubscribers;
181
+ }
182
+ subscribe(handlers) {
183
+ for (const eventName of traceEvents) {
184
+ const handler = handlers[eventName];
185
+ if (handler) {
186
+ this[eventName].subscribe(handler);
187
+ }
188
+ }
189
+ }
190
+ unsubscribe(handlers) {
191
+ let done = true;
192
+ for (const eventName of traceEvents) {
193
+ const handler = handlers[eventName];
194
+ if (handler && !this[eventName].unsubscribe(handler)) {
195
+ done = false;
196
+ }
197
+ }
198
+ return done;
199
+ }
200
+ traceSync(fn, message = {}, thisArg, ...args) {
201
+ if (!this.hasSubscribers) {
202
+ return Reflect.apply(fn, thisArg, args);
203
+ }
204
+ const context = message;
205
+ return this.start.runStores(message, () => {
206
+ try {
207
+ const result = Reflect.apply(fn, thisArg, args);
208
+ setContextValue(context, "result", result);
209
+ return result;
210
+ } catch (error) {
211
+ setContextValue(context, "error", error);
212
+ this.error.publish(message);
213
+ throw error;
214
+ } finally {
215
+ this.end.publish(message);
216
+ }
217
+ });
218
+ }
219
+ tracePromise(fn, message = {}, thisArg, ...args) {
220
+ if (!this.hasSubscribers) {
221
+ return Reflect.apply(fn, thisArg, args);
222
+ }
223
+ const context = message;
224
+ return this.start.runStores(message, () => {
225
+ let result;
226
+ try {
227
+ result = Reflect.apply(fn, thisArg, args);
228
+ } catch (error) {
229
+ setContextValue(context, "error", error);
230
+ this.error.publish(message);
231
+ this.end.publish(message);
232
+ throw error;
233
+ }
234
+ this.end.publish(message);
235
+ if (!result || typeof result !== "object" && typeof result !== "function") {
236
+ setContextValue(context, "result", result);
237
+ this.asyncStart.publish(message);
238
+ this.asyncEnd.publish(message);
239
+ return result;
240
+ }
241
+ let terminalPublished = false;
242
+ const finishUnobservedResult = (error) => {
243
+ reportError(error);
244
+ if (!terminalPublished) {
245
+ terminalPublished = true;
246
+ setContextValue(context, "result", result);
247
+ this.asyncStart.publish(message);
248
+ this.asyncEnd.publish(message);
249
+ }
250
+ return result;
251
+ };
252
+ let then;
253
+ try {
254
+ then = result.then;
255
+ } catch (error) {
256
+ return finishUnobservedResult(error);
257
+ }
258
+ if (typeof then !== "function") {
259
+ setContextValue(context, "result", result);
260
+ this.asyncStart.publish(message);
261
+ this.asyncEnd.publish(message);
262
+ return result;
263
+ }
264
+ const resolve = (resolved) => {
265
+ if (!terminalPublished) {
266
+ terminalPublished = true;
267
+ setContextValue(context, "result", resolved);
268
+ this.asyncStart.publish(message);
269
+ this.asyncEnd.publish(message);
270
+ }
271
+ return resolved;
272
+ };
273
+ let rejectionThrown = false;
274
+ let rejectionError;
275
+ const reject = (error) => {
276
+ if (!terminalPublished) {
277
+ terminalPublished = true;
278
+ setContextValue(context, "error", error);
279
+ this.error.publish(message);
280
+ this.asyncStart.publish(message);
281
+ this.asyncEnd.publish(message);
282
+ }
283
+ rejectionThrown = true;
284
+ rejectionError = error;
285
+ throw error;
286
+ };
287
+ let isPlainPromise;
288
+ try {
289
+ isPlainPromise = result instanceof Promise && result.constructor === Promise;
290
+ } catch (error) {
291
+ return finishUnobservedResult(error);
292
+ }
293
+ try {
294
+ if (isPlainPromise) {
295
+ return Reflect.apply(then, result, [resolve, reject]);
296
+ }
297
+ Reflect.apply(then, result, [
298
+ resolve,
299
+ (error) => {
300
+ try {
301
+ reject(error);
302
+ } catch {
303
+ }
304
+ }
305
+ ]);
306
+ } catch (error) {
307
+ if (rejectionThrown && error === rejectionError) {
308
+ return result;
309
+ }
310
+ return finishUnobservedResult(error);
311
+ }
312
+ return result;
313
+ });
314
+ }
315
+ traceCallback(fn, position = -1, message = {}, thisArg, ...args) {
316
+ if (!this.hasSubscribers) {
317
+ return Reflect.apply(fn, thisArg, args);
318
+ }
319
+ const context = message;
320
+ const callArgs = args.length > 0 ? args : context.arguments ?? args;
321
+ const callback = Array.prototype.at.call(callArgs, position);
322
+ if (typeof callback !== "function") {
323
+ return Reflect.apply(fn, thisArg, args);
324
+ }
325
+ const { asyncStart, asyncEnd, error: errorChannel } = this;
326
+ function wrappedCallback(error, result) {
327
+ if (error) {
328
+ setContextValue(context, "error", error);
329
+ errorChannel.publish(message);
330
+ } else {
331
+ setContextValue(context, "result", result);
332
+ }
333
+ return asyncStart.runStores(message, () => {
334
+ try {
335
+ return Reflect.apply(callback, this, arguments);
336
+ } finally {
337
+ asyncEnd.publish(message);
338
+ }
339
+ });
340
+ }
341
+ Array.prototype.splice.call(callArgs, position, 1, wrappedCallback);
342
+ return this.start.runStores(message, () => {
343
+ try {
344
+ return Reflect.apply(fn, thisArg, args);
345
+ } catch (error) {
346
+ setContextValue(context, "error", error);
347
+ this.error.publish(message);
348
+ throw error;
349
+ } finally {
350
+ this.end.publish(message);
351
+ }
352
+ });
353
+ }
354
+ };
355
+ var inertChannel = Object.freeze({
356
+ name: "braintrust:inert",
357
+ hasSubscribers: false,
358
+ subscribe() {
359
+ },
360
+ unsubscribe() {
361
+ return false;
362
+ },
363
+ bindStore() {
364
+ },
365
+ unbindStore() {
366
+ return false;
367
+ },
368
+ publish() {
369
+ },
370
+ runStores(_message, fn, thisArg, ...args) {
371
+ return Reflect.apply(fn, thisArg, args);
372
+ }
373
+ });
374
+ var inertTracingHook = new TracingHook({
375
+ start: inertChannel,
376
+ end: inertChannel,
377
+ asyncStart: inertChannel,
378
+ asyncEnd: inertChannel,
379
+ error: inertChannel
380
+ });
381
+ function isHookChannel(value) {
382
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
383
+ return false;
384
+ }
385
+ try {
386
+ const channel = value;
387
+ return typeof channel.hasSubscribers === "boolean" && typeof channel.subscribe === "function" && typeof channel.unsubscribe === "function" && typeof channel.bindStore === "function" && typeof channel.unbindStore === "function" && typeof channel.publish === "function" && typeof channel.runStores === "function";
388
+ } catch {
389
+ return false;
390
+ }
391
+ }
392
+ function hasTracingHookShape(value) {
393
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
394
+ return false;
395
+ }
396
+ try {
397
+ const hook = value;
398
+ return typeof hook.hasSubscribers === "boolean" && typeof hook.subscribe === "function" && typeof hook.unsubscribe === "function" && typeof hook.traceSync === "function" && typeof hook.tracePromise === "function" && typeof hook.traceCallback === "function" && isHookChannel(hook.start) && isHookChannel(hook.end) && isHookChannel(hook.asyncStart) && isHookChannel(hook.asyncEnd) && isHookChannel(hook.error);
399
+ } catch {
400
+ return false;
401
+ }
402
+ }
403
+ function isCompatibleTracingHook(value) {
404
+ try {
405
+ return value[hookBrand] === GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION && hasTracingHookShape(value);
406
+ } catch {
407
+ return false;
408
+ }
409
+ }
410
+ function isCompatibleHookRegistry(value) {
411
+ try {
412
+ return value instanceof Map && value[registryBrand] === GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION;
413
+ } catch {
414
+ return false;
415
+ }
416
+ }
417
+ function getHookRegistry() {
418
+ let descriptor;
419
+ try {
420
+ descriptor = Object.getOwnPropertyDescriptor(
421
+ globalThis,
422
+ GLOBAL_INSTRUMENTATION_HOOKS_KEY
423
+ );
424
+ } catch (error) {
425
+ reportError(error);
426
+ return void 0;
427
+ }
428
+ if (descriptor && "value" in descriptor && isCompatibleHookRegistry(descriptor.value) && (descriptor.configurable || descriptor.enumerable === false)) {
429
+ if (descriptor.configurable || descriptor.writable) {
430
+ try {
431
+ Object.defineProperty(globalThis, GLOBAL_INSTRUMENTATION_HOOKS_KEY, {
432
+ configurable: false,
433
+ enumerable: false,
434
+ value: descriptor.value,
435
+ writable: false
436
+ });
437
+ } catch (error) {
438
+ reportError(error);
439
+ return void 0;
440
+ }
441
+ }
442
+ return descriptor.value;
443
+ }
444
+ if (descriptor && !descriptor.configurable) {
445
+ reportError(new Error("Incompatible global instrumentation hook registry"));
446
+ return void 0;
447
+ }
448
+ const registry = /* @__PURE__ */ new Map();
449
+ try {
450
+ Object.defineProperty(registry, registryBrand, {
451
+ configurable: false,
452
+ enumerable: false,
453
+ value: GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
454
+ writable: false
455
+ });
456
+ } catch (error) {
457
+ reportError(error);
458
+ return void 0;
459
+ }
460
+ try {
461
+ Object.defineProperty(globalThis, GLOBAL_INSTRUMENTATION_HOOKS_KEY, {
462
+ configurable: false,
463
+ enumerable: false,
464
+ value: registry,
465
+ writable: false
466
+ });
467
+ return registry;
468
+ } catch (error) {
469
+ reportError(error);
470
+ return void 0;
471
+ }
472
+ }
473
+ function newGlobalTracingChannel(nameOrChannels) {
474
+ if (typeof nameOrChannels !== "string") {
475
+ return new TracingHook(nameOrChannels);
476
+ }
477
+ const registry = getHookRegistry();
478
+ if (!registry) {
479
+ return inertTracingHook;
480
+ }
481
+ let existing;
482
+ try {
483
+ existing = Map.prototype.get.call(registry, nameOrChannels);
484
+ } catch (error) {
485
+ reportError(error);
486
+ return inertTracingHook;
487
+ }
488
+ if (isCompatibleTracingHook(existing)) {
489
+ return existing;
490
+ }
491
+ if (existing !== void 0) {
492
+ reportError(
493
+ new Error(`Invalid global instrumentation hook: ${nameOrChannels}`)
494
+ );
495
+ try {
496
+ Map.prototype.delete.call(registry, nameOrChannels);
497
+ } catch (error) {
498
+ reportError(error);
499
+ return inertTracingHook;
500
+ }
501
+ }
502
+ const hook = new TracingHook(nameOrChannels);
503
+ try {
504
+ Map.prototype.set.call(registry, nameOrChannels, hook);
505
+ } catch (error) {
506
+ reportError(error);
507
+ return inertTracingHook;
508
+ }
509
+ return hook;
510
+ }
511
+
1
512
  // src/auto-instrumentations/loader/mastra-observability-patch.ts
2
513
  var MASTRA_EXPORTER_FACTORY_GLOBAL = "__braintrustMastraExporterFactory";
3
514
  function installMastraExporterFactory(factory) {
@@ -183,52 +694,79 @@ import { SourceMapGenerator } from "source-map";
183
694
  // src/auto-instrumentations/orchestrion-js/transforms.ts
184
695
  import esquery from "esquery";
185
696
  import { parse } from "meriyah";
186
- var tracingChannelPredicate = (node) => node.declarations?.[0]?.id?.properties?.[0]?.value?.name === "tr_ch_apm_tracingChannel";
187
697
  var CHANNEL_REGEX = /[^\w]/g;
698
+ var SHARED_HOOK_LOOKUP = "tr_ch_bt$get_hook";
188
699
  function formatChannelVariable(channelName) {
189
- return `tr_ch_apm$${channelName.replace(CHANNEL_REGEX, "_")}`;
700
+ return `tr_ch_bt$${channelName.replace(CHANNEL_REGEX, "_")}`;
701
+ }
702
+ function formatChannelGetter(channelName) {
703
+ return `tr_ch_bt$get_${channelName.replace(CHANNEL_REGEX, "_")}`;
190
704
  }
191
705
  var transforms = {
192
- tracingChannelImport({ dcModule, moduleType }, node) {
193
- if (node.body.some(tracingChannelPredicate)) {
194
- return;
195
- }
196
- const options = { module: moduleType === "esm" };
197
- const index = node.body.findIndex(
198
- (child) => child.directive === "use strict"
199
- );
200
- const dc = moduleType === "esm" ? `import tr_ch_apm_dc from "${dcModule}"` : `const tr_ch_apm_dc = ${"require"}("${dcModule}")`;
201
- const tracingChannel = "const { tracingChannel: tr_ch_apm_tracingChannel } = tr_ch_apm_dc";
202
- const hasSubscribers = `const tr_ch_apm_hasSubscribers = ch => ch.start.hasSubscribers
203
- || ch.end.hasSubscribers
204
- || ch.asyncStart.hasSubscribers
205
- || ch.asyncEnd.hasSubscribers
206
- || ch.error.hasSubscribers`;
207
- node.body.splice(
208
- index + 1,
209
- 0,
210
- parse(dc, options).body[0],
211
- parse(tracingChannel, options).body[0],
212
- parse(hasSubscribers, options).body[0]
213
- );
214
- },
215
- tracingChannelDeclaration(state, node) {
706
+ tracingHookDeclaration(state, node) {
216
707
  const {
217
708
  channelName,
218
- module: { name }
709
+ module: { name },
710
+ operator
219
711
  } = state;
220
712
  const channelVariable = formatChannelVariable(channelName);
713
+ const channelGetter = formatChannelGetter(channelName);
714
+ const hasSharedHookLookup = node.body.some(
715
+ (child) => child.declarations?.[0]?.id?.name === SHARED_HOOK_LOOKUP
716
+ );
221
717
  if (node.body.some(
222
- (child) => child.declarations?.[0]?.id?.name === channelVariable
718
+ (child) => child.declarations?.[0]?.id?.name === channelGetter
223
719
  )) {
224
720
  return;
225
721
  }
226
- transforms.tracingChannelImport(state, node, null, []);
227
- const index = node.body.findIndex(tracingChannelPredicate);
722
+ const sharedHookLookup = hasSharedHookLookup ? "" : `
723
+ const ${SHARED_HOOK_LOOKUP} = (__bt$hookName, __bt$operator) => {
724
+ try {
725
+ const __bt$hooks = globalThis[${JSON.stringify(
726
+ GLOBAL_INSTRUMENTATION_HOOKS_KEY
727
+ )}];
728
+ if (
729
+ !(__bt$hooks instanceof Map) ||
730
+ __bt$hooks[Symbol.for(${JSON.stringify(
731
+ GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND
732
+ )})] !== ${GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION}
733
+ ) return undefined;
734
+ const __bt$hook = Map.prototype.get.call(
735
+ __bt$hooks,
736
+ __bt$hookName
737
+ );
738
+ if (
739
+ (__bt$hook === null ||
740
+ (typeof __bt$hook !== "object" &&
741
+ typeof __bt$hook !== "function")) ||
742
+ __bt$hook[Symbol.for(${JSON.stringify(
743
+ GLOBAL_INSTRUMENTATION_HOOK_BRAND
744
+ )})] !== ${GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION} ||
745
+ typeof __bt$hook.hasSubscribers !== "boolean" ||
746
+ typeof __bt$hook[__bt$operator] !== "function"
747
+ ) return undefined;
748
+ return __bt$hook;
749
+ } catch {
750
+ return undefined;
751
+ }
752
+ };
753
+ `;
228
754
  const code = `
229
- const ${channelVariable} = tr_ch_apm_tracingChannel("orchestrion:${name}:${channelName}")
755
+ ${sharedHookLookup}
756
+ let ${channelVariable};
757
+ const ${channelGetter} = () =>
758
+ ${channelVariable} ??= ${SHARED_HOOK_LOOKUP}(
759
+ ${JSON.stringify(`orchestrion:${name}:${channelName}`)},
760
+ ${JSON.stringify(operator)}
761
+ );
230
762
  `;
231
- node.body.splice(index + 1, 0, parse(code).body[0]);
763
+ const sharedHookLookupIndex = node.body.findIndex(
764
+ (child) => child.declarations?.[0]?.id?.name === SHARED_HOOK_LOOKUP
765
+ );
766
+ const index = sharedHookLookupIndex === -1 ? node.body.findIndex(
767
+ (child) => child.directive === "use strict"
768
+ ) : sharedHookLookupIndex;
769
+ node.body.splice(index + 1, 0, ...parse(code).body);
232
770
  },
233
771
  traceCallback: traceAny,
234
772
  tracePromise: traceAny,
@@ -243,25 +781,21 @@ function traceAny(state, node, _parent, ancestry) {
243
781
  }
244
782
  }
245
783
  function traceFunction(state, node, program) {
246
- transforms.tracingChannelDeclaration(state, program, null, []);
784
+ transforms.tracingHookDeclaration(state, program, null, []);
247
785
  const { functionQuery } = state;
248
786
  const methodName = "methodName" in functionQuery ? functionQuery.methodName : void 0;
249
787
  const privateMethodName = "privateMethodName" in functionQuery ? functionQuery.privateMethodName : void 0;
250
788
  const functionName = "functionName" in functionQuery ? functionQuery.functionName : void 0;
251
789
  const isConstructor = methodName === "constructor" || !methodName && !privateMethodName && !functionName;
252
790
  const type = isConstructor ? "ArrowFunctionExpression" : "FunctionExpression";
253
- node.body = wrap(
254
- state,
255
- {
256
- type,
257
- params: node.params,
258
- body: node.body,
259
- async: node.async,
260
- expression: false,
261
- generator: node.generator
262
- },
263
- program
264
- );
791
+ node.body = wrap(state, {
792
+ type,
793
+ params: node.params,
794
+ body: node.body,
795
+ async: node.async,
796
+ expression: false,
797
+ generator: node.generator
798
+ });
265
799
  node.generator = false;
266
800
  node.async = false;
267
801
  wrapSuper(node);
@@ -273,11 +807,11 @@ function traceInstanceMethod(state, node, program) {
273
807
  return;
274
808
  }
275
809
  const classBody = node.body;
276
- if (classBody.body.some(({ key }) => key.name === methodName)) {
810
+ if (classBody.body.some(({ key }) => key?.name === methodName)) {
277
811
  return;
278
812
  }
279
813
  let ctor = classBody.body.find(({ kind }) => kind === "constructor");
280
- transforms.tracingChannelDeclaration(state, program, null, []);
814
+ transforms.tracingHookDeclaration(state, program, null, []);
281
815
  if (!ctor) {
282
816
  ctor = parse(
283
817
  node.superClass ? "class A extends Object { constructor (...args) { super(...args) } }" : "class A { constructor () {} }"
@@ -285,47 +819,46 @@ function traceInstanceMethod(state, node, program) {
285
819
  classBody.body.unshift(ctor);
286
820
  }
287
821
  const ctorBody = parse(`
288
- const __apm$${methodName} = this["${methodName}"]
822
+ const __bt$${methodName} = this["${methodName}"]
289
823
  this["${methodName}"] = function () {}
290
824
  `).body;
291
825
  const fn = ctorBody[1].expression.right;
292
826
  fn.async = operator === "tracePromise";
293
- fn.body = wrap(
294
- state,
295
- { type: "Identifier", name: `__apm$${methodName}` },
296
- program
297
- );
827
+ fn.body = wrap(state, {
828
+ type: "Identifier",
829
+ name: `__bt$${methodName}`
830
+ });
298
831
  wrapSuper(fn);
299
832
  ctor.value.body.body.push(...ctorBody);
300
833
  }
301
- function wrap(state, node, program) {
834
+ function wrap(state, node) {
302
835
  const { operator, moduleVersion } = state;
303
836
  const wrapper = operator === "traceCallback" ? wrapCallback(state) : operator === "tracePromise" ? wrapPromise(state) : wrapSync(state);
304
837
  const block = wrapper.body[0].body;
305
838
  const common = parse(
306
839
  node.type === "ArrowFunctionExpression" ? `
307
- const __apm$ctx = {
840
+ const __bt$ctx = {
308
841
  arguments,
309
842
  moduleVersion: ${JSON.stringify(moduleVersion)}
310
843
  };
311
- const __apm$traced = () => {
312
- const __apm$wrapped = () => {};
313
- return __apm$wrapped(...arguments);
844
+ const __bt$traced = () => {
845
+ const __bt$wrapped = () => {};
846
+ return __bt$wrapped(...arguments);
314
847
  };
315
848
  ` : `
316
- const __apm$ctx = {
849
+ const __bt$ctx = {
317
850
  arguments,
318
851
  self: this,
319
852
  moduleVersion: ${JSON.stringify(moduleVersion)}
320
853
  };
321
- const __apm$traced = () => {
322
- const __apm$wrapped = () => {};
323
- return __apm$wrapped.apply(this, arguments);
854
+ const __bt$traced = () => {
855
+ const __bt$wrapped = () => {};
856
+ return __bt$wrapped.apply(this, arguments);
324
857
  };
325
858
  `
326
859
  ).body;
327
860
  block.body.unshift(...common);
328
- esquery.query(block, "[id.name=__apm$wrapped]")[0].init = node;
861
+ esquery.query(block, "[id.name=__bt$wrapped]")[0].init = node;
329
862
  return block;
330
863
  }
331
864
  function wrapSuper(node) {
@@ -337,11 +870,11 @@ function wrapSuper(node) {
337
870
  const { name } = node2.property;
338
871
  let child;
339
872
  if (parent.callee) {
340
- const { expression } = parse(`__apm$super['${name}'].call(this)`).body[0];
873
+ const { expression } = parse(`__bt$super['${name}'].call(this)`).body[0];
341
874
  parent.callee = child = expression.callee;
342
875
  parent.arguments.unshift(...expression.arguments);
343
876
  } else {
344
- parent.expression = child = parse(`__apm$super['${name}']`).body[0];
877
+ parent.expression = child = parse(`__bt$super['${name}']`).body[0];
345
878
  }
346
879
  child.computed = parent.callee.computed;
347
880
  child.optional = parent.callee.optional;
@@ -352,14 +885,14 @@ function wrapSuper(node) {
352
885
  const member = parse(`
353
886
  class Wrapper {
354
887
  wrapper () {
355
- __apm$super['${name}'] = super['${name}']
888
+ __bt$super['${name}'] = super['${name}']
356
889
  }
357
890
  }
358
891
  `).body[0].body.body[0].value.body.body[0];
359
892
  node.body.body.unshift(member);
360
893
  }
361
894
  if (members.size > 0) {
362
- node.body.body.unshift(parse("const __apm$super = {}").body[0]);
895
+ node.body.body.unshift(parse("const __bt$super = {}").body[0]);
363
896
  }
364
897
  }
365
898
  function wrapCallback(state) {
@@ -367,136 +900,41 @@ function wrapCallback(state) {
367
900
  channelName,
368
901
  functionQuery: { callbackIndex = -1 }
369
902
  } = state;
370
- const channelVariable = formatChannelVariable(channelName);
903
+ const channelGetter = formatChannelGetter(channelName);
371
904
  return parse(`
372
905
  function wrapper () {
373
- const __apm$cb = Array.prototype.at.call(arguments, ${callbackIndex});
374
-
375
- if (!${channelVariable}.start.hasSubscribers) return __apm$traced();
376
-
377
- function __apm$wrappedCb(err, res) {
378
- if (err) {
379
- __apm$ctx.error = err;
380
- ${channelVariable}.error.publish(__apm$ctx);
381
- } else {
382
- __apm$ctx.result = res;
383
- }
384
-
385
- ${channelVariable}.asyncStart.runStores(__apm$ctx, () => {
386
- try {
387
- if (__apm$cb) {
388
- return __apm$cb.apply(this, arguments);
389
- }
390
- } finally {
391
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
392
- }
393
- });
394
- }
395
-
396
- if (typeof __apm$cb !== 'function') {
397
- return __apm$traced();
398
- }
399
- Array.prototype.splice.call(arguments, ${callbackIndex}, 1, __apm$wrappedCb);
400
-
401
- return ${channelVariable}.start.runStores(__apm$ctx, () => {
402
- try {
403
- return __apm$traced();
404
- } catch (err) {
405
- __apm$ctx.error = err;
406
- ${channelVariable}.error.publish(__apm$ctx);
407
- throw err;
408
- } finally {
409
- __apm$ctx.self ??= this;
410
- ${channelVariable}.end.publish(__apm$ctx);
411
- }
412
- });
906
+ const __bt$hook = ${channelGetter}();
907
+ if (!__bt$hook?.hasSubscribers) return __bt$traced();
908
+ __bt$ctx.self ??= this;
909
+ return __bt$hook.traceCallback(
910
+ __bt$traced,
911
+ ${callbackIndex},
912
+ __bt$ctx
913
+ );
413
914
  }
414
915
  `);
415
916
  }
416
917
  function wrapPromise(state) {
417
918
  const { channelName } = state;
418
- const channelVariable = formatChannelVariable(channelName);
919
+ const channelGetter = formatChannelGetter(channelName);
419
920
  return parse(`
420
921
  function wrapper () {
421
- if (!tr_ch_apm_hasSubscribers(${channelVariable})) return __apm$traced();
422
-
423
- return ${channelVariable}.start.runStores(__apm$ctx, () => {
424
- try {
425
- let promise = __apm$traced();
426
- if (typeof promise?.then !== 'function') {
427
- __apm$ctx.result = promise;
428
- return promise;
429
- }
430
- // Mirror Node.js core diagnostics_channel behaviour: for native Promise
431
- // instances, chain normally (safe since there is no subclass API to
432
- // preserve). For Promise subclasses and other thenables, side-chain the
433
- // callbacks for event publishing and return the original so that any
434
- // subclass-specific methods (e.g. APIPromise.withResponse()) remain
435
- // accessible to the caller.
436
- if (promise instanceof Promise && promise.constructor === Promise) {
437
- return promise.then(
438
- result => {
439
- __apm$ctx.result = result;
440
- ${channelVariable}.asyncStart.publish(__apm$ctx);
441
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
442
- return result;
443
- },
444
- err => {
445
- __apm$ctx.error = err;
446
- ${channelVariable}.error.publish(__apm$ctx);
447
- ${channelVariable}.asyncStart.publish(__apm$ctx);
448
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
449
- throw err;
450
- }
451
- );
452
- }
453
- promise.then(
454
- result => {
455
- __apm$ctx.result = result;
456
- ${channelVariable}.asyncStart.publish(__apm$ctx);
457
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
458
- },
459
- err => {
460
- __apm$ctx.error = err;
461
- ${channelVariable}.error.publish(__apm$ctx);
462
- ${channelVariable}.asyncStart.publish(__apm$ctx);
463
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
464
- }
465
- );
466
- return promise;
467
- } catch (err) {
468
- __apm$ctx.error = err;
469
- ${channelVariable}.error.publish(__apm$ctx);
470
- throw err;
471
- } finally {
472
- __apm$ctx.self ??= this;
473
- ${channelVariable}.end.publish(__apm$ctx);
474
- }
475
- });
922
+ const __bt$hook = ${channelGetter}();
923
+ if (!__bt$hook?.hasSubscribers) return __bt$traced();
924
+ __bt$ctx.self ??= this;
925
+ return __bt$hook.tracePromise(__bt$traced, __bt$ctx);
476
926
  }
477
927
  `);
478
928
  }
479
929
  function wrapSync(state) {
480
930
  const { channelName } = state;
481
- const channelVariable = formatChannelVariable(channelName);
931
+ const channelGetter = formatChannelGetter(channelName);
482
932
  return parse(`
483
933
  function wrapper () {
484
- if (!tr_ch_apm_hasSubscribers(${channelVariable})) return __apm$traced();
485
-
486
- return ${channelVariable}.start.runStores(__apm$ctx, () => {
487
- try {
488
- const result = __apm$traced();
489
- __apm$ctx.result = result;
490
- return result;
491
- } catch (err) {
492
- __apm$ctx.error = err;
493
- ${channelVariable}.error.publish(__apm$ctx);
494
- throw err;
495
- } finally {
496
- __apm$ctx.self ??= this;
497
- ${channelVariable}.end.publish(__apm$ctx);
498
- }
499
- });
934
+ const __bt$hook = ${channelGetter}();
935
+ if (!__bt$hook?.hasSubscribers) return __bt$traced();
936
+ __bt$ctx.self ??= this;
937
+ return __bt$hook.traceSync(__bt$traced, __bt$ctx);
500
938
  }
501
939
  `);
502
940
  }
@@ -507,16 +945,14 @@ var Transformer = class {
507
945
  version;
508
946
  filePath;
509
947
  configs = [];
510
- dcModule;
511
- constructor(moduleName, version, filePath, configs, dcModule) {
948
+ constructor(moduleName, version, filePath, configs) {
512
949
  this.moduleName = moduleName;
513
950
  this.version = version;
514
951
  this.filePath = filePath;
515
952
  this.configs = configs;
516
- this.dcModule = dcModule;
517
953
  }
518
954
  /**
519
- * Instruments `code` by injecting diagnostics_channel tracing around the
955
+ * Instruments `code` by injecting global tracing hooks around the
520
956
  * target functions defined by this transformer's configs.
521
957
  */
522
958
  transform(code, moduleType) {
@@ -554,8 +990,6 @@ var Transformer = class {
554
990
  const query = astQuery || this.fromFunctionQuery(resolvedFunctionQuery);
555
991
  const state = {
556
992
  ...config,
557
- dcModule: this.dcModule,
558
- moduleType,
559
993
  moduleVersion: this.version,
560
994
  functionQuery: resolvedFunctionQuery,
561
995
  operator: this.getOperator(resolvedFunctionQuery.kind)
@@ -705,11 +1139,9 @@ var Transformer = class {
705
1139
  // src/auto-instrumentations/orchestrion-js/matcher.ts
706
1140
  var InstrumentationMatcher = class {
707
1141
  configs = [];
708
- dcModule;
709
1142
  transformers = {};
710
- constructor(configs, dcModule) {
1143
+ constructor(configs) {
711
1144
  this.configs = configs;
712
- this.dcModule = dcModule || "diagnostics_channel";
713
1145
  }
714
1146
  /**
715
1147
  * Returns a Transformer for the given module/file/version, or undefined if no
@@ -731,8 +1163,7 @@ var InstrumentationMatcher = class {
731
1163
  moduleName,
732
1164
  version,
733
1165
  filePath,
734
- configs,
735
- this.dcModule
1166
+ configs
736
1167
  );
737
1168
  return this.transformers[id];
738
1169
  }
@@ -742,8 +1173,8 @@ var InstrumentationMatcher = class {
742
1173
  };
743
1174
 
744
1175
  // src/auto-instrumentations/orchestrion-js/index.ts
745
- function create(configs, dcModule) {
746
- return new InstrumentationMatcher(configs, dcModule);
1176
+ function create(configs) {
1177
+ return new InstrumentationMatcher(configs);
747
1178
  }
748
1179
 
749
1180
  // src/auto-instrumentations/loader/get-package-version.ts
@@ -827,6 +1258,9 @@ function applySpecialCasePatch(input) {
827
1258
  if (input.packageName === "openai" && input.modulePath.includes("api-promise")) {
828
1259
  return input.source + OPENAI_API_PROMISE_PATCH;
829
1260
  }
1261
+ if (input.browser) {
1262
+ return null;
1263
+ }
830
1264
  const mastraTarget = classifyMastraTarget(
831
1265
  input.packageName,
832
1266
  input.modulePath
@@ -847,6 +1281,9 @@ function isSpecialCaseTarget(packageName, modulePath) {
847
1281
  }
848
1282
 
849
1283
  export {
1284
+ GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
1285
+ setGlobalHookErrorReporter,
1286
+ newGlobalTracingChannel,
850
1287
  installMastraExporterFactory,
851
1288
  create,
852
1289
  getPackageVersion,