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
@@ -46,52 +46,453 @@ var import_source_map = require("source-map");
46
46
  // src/auto-instrumentations/orchestrion-js/transforms.ts
47
47
  var import_esquery = __toESM(require("esquery"));
48
48
  var import_meriyah = require("meriyah");
49
- var tracingChannelPredicate = (node) => node.declarations?.[0]?.id?.properties?.[0]?.value?.name === "tr_ch_apm_tracingChannel";
50
- var CHANNEL_REGEX = /[^\w]/g;
51
- function formatChannelVariable(channelName) {
52
- return `tr_ch_apm$${channelName.replace(CHANNEL_REGEX, "_")}`;
49
+
50
+ // src/global-instrumentation-hooks.ts
51
+ var GLOBAL_INSTRUMENTATION_HOOKS_KEY = "__braintrust_instrumentation_hooks";
52
+ var GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION = 1;
53
+ var GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND = "braintrust.global-instrumentation-hooks.registry";
54
+ var GLOBAL_INSTRUMENTATION_HOOK_BRAND = "braintrust.global-instrumentation-hooks.hook";
55
+ var registryBrand = Symbol.for(GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND);
56
+ var hookBrand = Symbol.for(GLOBAL_INSTRUMENTATION_HOOK_BRAND);
57
+ var errorReporter;
58
+ function reportError(error) {
59
+ try {
60
+ errorReporter?.(error);
61
+ } catch {
62
+ }
53
63
  }
54
- var transforms = {
55
- tracingChannelImport({ dcModule, moduleType }, node) {
56
- if (node.body.some(tracingChannelPredicate)) {
57
- return;
64
+ function setContextValue(context, key, value) {
65
+ try {
66
+ context[key] = value;
67
+ } catch (error) {
68
+ reportError(error);
69
+ }
70
+ }
71
+ function wrapStoreRun(store, message, next, transform) {
72
+ return () => {
73
+ let context;
74
+ try {
75
+ context = transform ? transform(message) : message;
76
+ } catch (error) {
77
+ reportError(error);
78
+ return next();
58
79
  }
59
- const options = { module: moduleType === "esm" };
60
- const index = node.body.findIndex(
61
- (child) => child.directive === "use strict"
62
- );
63
- const dc = moduleType === "esm" ? `import tr_ch_apm_dc from "${dcModule}"` : `const tr_ch_apm_dc = ${"require"}("${dcModule}")`;
64
- const tracingChannel = "const { tracingChannel: tr_ch_apm_tracingChannel } = tr_ch_apm_dc";
65
- const hasSubscribers = `const tr_ch_apm_hasSubscribers = ch => ch.start.hasSubscribers
66
- || ch.end.hasSubscribers
67
- || ch.asyncStart.hasSubscribers
68
- || ch.asyncEnd.hasSubscribers
69
- || ch.error.hasSubscribers`;
70
- node.body.splice(
71
- index + 1,
72
- 0,
73
- (0, import_meriyah.parse)(dc, options).body[0],
74
- (0, import_meriyah.parse)(tracingChannel, options).body[0],
75
- (0, import_meriyah.parse)(hasSubscribers, options).body[0]
80
+ let called = false;
81
+ let result;
82
+ let providerError;
83
+ let providerThrew = false;
84
+ const runNext = () => {
85
+ if (called) {
86
+ reportError(
87
+ new Error(
88
+ "Instrumentation store invoked its callback more than once"
89
+ )
90
+ );
91
+ if (providerThrew) {
92
+ throw providerError;
93
+ }
94
+ return result;
95
+ }
96
+ called = true;
97
+ try {
98
+ result = next();
99
+ return result;
100
+ } catch (error) {
101
+ providerThrew = true;
102
+ providerError = error;
103
+ throw error;
104
+ }
105
+ };
106
+ try {
107
+ store.run(context, runNext);
108
+ } catch (error) {
109
+ if (!providerThrew || error !== providerError) {
110
+ reportError(error);
111
+ }
112
+ }
113
+ if (!called) {
114
+ reportError(
115
+ new Error("Instrumentation store did not invoke its callback")
116
+ );
117
+ return runNext();
118
+ }
119
+ if (providerThrew) {
120
+ throw providerError;
121
+ }
122
+ return result;
123
+ };
124
+ }
125
+ var HookChannel = class {
126
+ constructor(name) {
127
+ this.name = name;
128
+ }
129
+ name;
130
+ subscribers = [];
131
+ stores = /* @__PURE__ */ new Map();
132
+ get hasSubscribers() {
133
+ return this.subscribers.length > 0 || this.stores.size > 0;
134
+ }
135
+ subscribe(subscription) {
136
+ if (typeof subscription !== "function") {
137
+ throw new TypeError("subscription must be a function");
138
+ }
139
+ this.subscribers = [...this.subscribers, subscription];
140
+ }
141
+ unsubscribe(subscription) {
142
+ const index = this.subscribers.indexOf(subscription);
143
+ if (index === -1) {
144
+ return false;
145
+ }
146
+ this.subscribers = [
147
+ ...this.subscribers.slice(0, index),
148
+ ...this.subscribers.slice(index + 1)
149
+ ];
150
+ return true;
151
+ }
152
+ bindStore(store, transform) {
153
+ if (!store || typeof store.run !== "function") {
154
+ throw new TypeError("store must have a run method");
155
+ }
156
+ this.stores.set(
157
+ store,
158
+ transform
76
159
  );
160
+ }
161
+ unbindStore(store) {
162
+ return this.stores.delete(store);
163
+ }
164
+ publish(message) {
165
+ const subscribers = this.subscribers;
166
+ for (const subscriber of subscribers) {
167
+ try {
168
+ subscriber(message, this.name);
169
+ } catch (error) {
170
+ reportError(error);
171
+ }
172
+ }
173
+ }
174
+ runStores(message, fn, thisArg, ...args) {
175
+ let run = () => {
176
+ this.publish(message);
177
+ return Reflect.apply(fn, thisArg, args);
178
+ };
179
+ for (const [store, transform] of this.stores.entries()) {
180
+ run = wrapStoreRun(store, message, run, transform);
181
+ }
182
+ return run();
183
+ }
184
+ };
185
+ var traceEvents = [
186
+ "start",
187
+ "end",
188
+ "asyncStart",
189
+ "asyncEnd",
190
+ "error"
191
+ ];
192
+ var TracingHook = class {
193
+ start;
194
+ end;
195
+ asyncStart;
196
+ asyncEnd;
197
+ error;
198
+ constructor(nameOrChannels) {
199
+ Object.defineProperty(this, hookBrand, {
200
+ configurable: false,
201
+ enumerable: false,
202
+ value: GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
203
+ writable: false
204
+ });
205
+ if (typeof nameOrChannels === "string") {
206
+ this.start = new HookChannel(`tracing:${nameOrChannels}:start`);
207
+ this.end = new HookChannel(`tracing:${nameOrChannels}:end`);
208
+ this.asyncStart = new HookChannel(`tracing:${nameOrChannels}:asyncStart`);
209
+ this.asyncEnd = new HookChannel(`tracing:${nameOrChannels}:asyncEnd`);
210
+ this.error = new HookChannel(`tracing:${nameOrChannels}:error`);
211
+ return;
212
+ }
213
+ this.start = nameOrChannels.start ?? new HookChannel("tracing:start");
214
+ this.end = nameOrChannels.end ?? new HookChannel("tracing:end");
215
+ this.asyncStart = nameOrChannels.asyncStart ?? new HookChannel("tracing:asyncStart");
216
+ this.asyncEnd = nameOrChannels.asyncEnd ?? new HookChannel("tracing:asyncEnd");
217
+ this.error = nameOrChannels.error ?? new HookChannel("tracing:error");
218
+ }
219
+ get hasSubscribers() {
220
+ return this.start.hasSubscribers || this.end.hasSubscribers || this.asyncStart.hasSubscribers || this.asyncEnd.hasSubscribers || this.error.hasSubscribers;
221
+ }
222
+ subscribe(handlers) {
223
+ for (const eventName of traceEvents) {
224
+ const handler = handlers[eventName];
225
+ if (handler) {
226
+ this[eventName].subscribe(handler);
227
+ }
228
+ }
229
+ }
230
+ unsubscribe(handlers) {
231
+ let done = true;
232
+ for (const eventName of traceEvents) {
233
+ const handler = handlers[eventName];
234
+ if (handler && !this[eventName].unsubscribe(handler)) {
235
+ done = false;
236
+ }
237
+ }
238
+ return done;
239
+ }
240
+ traceSync(fn, message = {}, thisArg, ...args) {
241
+ if (!this.hasSubscribers) {
242
+ return Reflect.apply(fn, thisArg, args);
243
+ }
244
+ const context = message;
245
+ return this.start.runStores(message, () => {
246
+ try {
247
+ const result = Reflect.apply(fn, thisArg, args);
248
+ setContextValue(context, "result", result);
249
+ return result;
250
+ } catch (error) {
251
+ setContextValue(context, "error", error);
252
+ this.error.publish(message);
253
+ throw error;
254
+ } finally {
255
+ this.end.publish(message);
256
+ }
257
+ });
258
+ }
259
+ tracePromise(fn, message = {}, thisArg, ...args) {
260
+ if (!this.hasSubscribers) {
261
+ return Reflect.apply(fn, thisArg, args);
262
+ }
263
+ const context = message;
264
+ return this.start.runStores(message, () => {
265
+ let result;
266
+ try {
267
+ result = Reflect.apply(fn, thisArg, args);
268
+ } catch (error) {
269
+ setContextValue(context, "error", error);
270
+ this.error.publish(message);
271
+ this.end.publish(message);
272
+ throw error;
273
+ }
274
+ this.end.publish(message);
275
+ if (!result || typeof result !== "object" && typeof result !== "function") {
276
+ setContextValue(context, "result", result);
277
+ this.asyncStart.publish(message);
278
+ this.asyncEnd.publish(message);
279
+ return result;
280
+ }
281
+ let terminalPublished = false;
282
+ const finishUnobservedResult = (error) => {
283
+ reportError(error);
284
+ if (!terminalPublished) {
285
+ terminalPublished = true;
286
+ setContextValue(context, "result", result);
287
+ this.asyncStart.publish(message);
288
+ this.asyncEnd.publish(message);
289
+ }
290
+ return result;
291
+ };
292
+ let then;
293
+ try {
294
+ then = result.then;
295
+ } catch (error) {
296
+ return finishUnobservedResult(error);
297
+ }
298
+ if (typeof then !== "function") {
299
+ setContextValue(context, "result", result);
300
+ this.asyncStart.publish(message);
301
+ this.asyncEnd.publish(message);
302
+ return result;
303
+ }
304
+ const resolve = (resolved) => {
305
+ if (!terminalPublished) {
306
+ terminalPublished = true;
307
+ setContextValue(context, "result", resolved);
308
+ this.asyncStart.publish(message);
309
+ this.asyncEnd.publish(message);
310
+ }
311
+ return resolved;
312
+ };
313
+ let rejectionThrown = false;
314
+ let rejectionError;
315
+ const reject = (error) => {
316
+ if (!terminalPublished) {
317
+ terminalPublished = true;
318
+ setContextValue(context, "error", error);
319
+ this.error.publish(message);
320
+ this.asyncStart.publish(message);
321
+ this.asyncEnd.publish(message);
322
+ }
323
+ rejectionThrown = true;
324
+ rejectionError = error;
325
+ throw error;
326
+ };
327
+ let isPlainPromise;
328
+ try {
329
+ isPlainPromise = result instanceof Promise && result.constructor === Promise;
330
+ } catch (error) {
331
+ return finishUnobservedResult(error);
332
+ }
333
+ try {
334
+ if (isPlainPromise) {
335
+ return Reflect.apply(then, result, [resolve, reject]);
336
+ }
337
+ Reflect.apply(then, result, [
338
+ resolve,
339
+ (error) => {
340
+ try {
341
+ reject(error);
342
+ } catch {
343
+ }
344
+ }
345
+ ]);
346
+ } catch (error) {
347
+ if (rejectionThrown && error === rejectionError) {
348
+ return result;
349
+ }
350
+ return finishUnobservedResult(error);
351
+ }
352
+ return result;
353
+ });
354
+ }
355
+ traceCallback(fn, position = -1, message = {}, thisArg, ...args) {
356
+ if (!this.hasSubscribers) {
357
+ return Reflect.apply(fn, thisArg, args);
358
+ }
359
+ const context = message;
360
+ const callArgs = args.length > 0 ? args : context.arguments ?? args;
361
+ const callback = Array.prototype.at.call(callArgs, position);
362
+ if (typeof callback !== "function") {
363
+ return Reflect.apply(fn, thisArg, args);
364
+ }
365
+ const { asyncStart, asyncEnd, error: errorChannel } = this;
366
+ function wrappedCallback(error, result) {
367
+ if (error) {
368
+ setContextValue(context, "error", error);
369
+ errorChannel.publish(message);
370
+ } else {
371
+ setContextValue(context, "result", result);
372
+ }
373
+ return asyncStart.runStores(message, () => {
374
+ try {
375
+ return Reflect.apply(callback, this, arguments);
376
+ } finally {
377
+ asyncEnd.publish(message);
378
+ }
379
+ });
380
+ }
381
+ Array.prototype.splice.call(callArgs, position, 1, wrappedCallback);
382
+ return this.start.runStores(message, () => {
383
+ try {
384
+ return Reflect.apply(fn, thisArg, args);
385
+ } catch (error) {
386
+ setContextValue(context, "error", error);
387
+ this.error.publish(message);
388
+ throw error;
389
+ } finally {
390
+ this.end.publish(message);
391
+ }
392
+ });
393
+ }
394
+ };
395
+ var inertChannel = Object.freeze({
396
+ name: "braintrust:inert",
397
+ hasSubscribers: false,
398
+ subscribe() {
399
+ },
400
+ unsubscribe() {
401
+ return false;
402
+ },
403
+ bindStore() {
404
+ },
405
+ unbindStore() {
406
+ return false;
407
+ },
408
+ publish() {
77
409
  },
78
- tracingChannelDeclaration(state, node) {
410
+ runStores(_message, fn, thisArg, ...args) {
411
+ return Reflect.apply(fn, thisArg, args);
412
+ }
413
+ });
414
+ var inertTracingHook = new TracingHook({
415
+ start: inertChannel,
416
+ end: inertChannel,
417
+ asyncStart: inertChannel,
418
+ asyncEnd: inertChannel,
419
+ error: inertChannel
420
+ });
421
+
422
+ // src/auto-instrumentations/orchestrion-js/transforms.ts
423
+ var CHANNEL_REGEX = /[^\w]/g;
424
+ var SHARED_HOOK_LOOKUP = "tr_ch_bt$get_hook";
425
+ function formatChannelVariable(channelName) {
426
+ return `tr_ch_bt$${channelName.replace(CHANNEL_REGEX, "_")}`;
427
+ }
428
+ function formatChannelGetter(channelName) {
429
+ return `tr_ch_bt$get_${channelName.replace(CHANNEL_REGEX, "_")}`;
430
+ }
431
+ var transforms = {
432
+ tracingHookDeclaration(state, node) {
79
433
  const {
80
434
  channelName,
81
- module: { name }
435
+ module: { name },
436
+ operator
82
437
  } = state;
83
438
  const channelVariable = formatChannelVariable(channelName);
439
+ const channelGetter = formatChannelGetter(channelName);
440
+ const hasSharedHookLookup = node.body.some(
441
+ (child) => child.declarations?.[0]?.id?.name === SHARED_HOOK_LOOKUP
442
+ );
84
443
  if (node.body.some(
85
- (child) => child.declarations?.[0]?.id?.name === channelVariable
444
+ (child) => child.declarations?.[0]?.id?.name === channelGetter
86
445
  )) {
87
446
  return;
88
447
  }
89
- transforms.tracingChannelImport(state, node, null, []);
90
- const index = node.body.findIndex(tracingChannelPredicate);
448
+ const sharedHookLookup = hasSharedHookLookup ? "" : `
449
+ const ${SHARED_HOOK_LOOKUP} = (__bt$hookName, __bt$operator) => {
450
+ try {
451
+ const __bt$hooks = globalThis[${JSON.stringify(
452
+ GLOBAL_INSTRUMENTATION_HOOKS_KEY
453
+ )}];
454
+ if (
455
+ !(__bt$hooks instanceof Map) ||
456
+ __bt$hooks[Symbol.for(${JSON.stringify(
457
+ GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND
458
+ )})] !== ${GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION}
459
+ ) return undefined;
460
+ const __bt$hook = Map.prototype.get.call(
461
+ __bt$hooks,
462
+ __bt$hookName
463
+ );
464
+ if (
465
+ (__bt$hook === null ||
466
+ (typeof __bt$hook !== "object" &&
467
+ typeof __bt$hook !== "function")) ||
468
+ __bt$hook[Symbol.for(${JSON.stringify(
469
+ GLOBAL_INSTRUMENTATION_HOOK_BRAND
470
+ )})] !== ${GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION} ||
471
+ typeof __bt$hook.hasSubscribers !== "boolean" ||
472
+ typeof __bt$hook[__bt$operator] !== "function"
473
+ ) return undefined;
474
+ return __bt$hook;
475
+ } catch {
476
+ return undefined;
477
+ }
478
+ };
479
+ `;
91
480
  const code = `
92
- const ${channelVariable} = tr_ch_apm_tracingChannel("orchestrion:${name}:${channelName}")
481
+ ${sharedHookLookup}
482
+ let ${channelVariable};
483
+ const ${channelGetter} = () =>
484
+ ${channelVariable} ??= ${SHARED_HOOK_LOOKUP}(
485
+ ${JSON.stringify(`orchestrion:${name}:${channelName}`)},
486
+ ${JSON.stringify(operator)}
487
+ );
93
488
  `;
94
- node.body.splice(index + 1, 0, (0, import_meriyah.parse)(code).body[0]);
489
+ const sharedHookLookupIndex = node.body.findIndex(
490
+ (child) => child.declarations?.[0]?.id?.name === SHARED_HOOK_LOOKUP
491
+ );
492
+ const index = sharedHookLookupIndex === -1 ? node.body.findIndex(
493
+ (child) => child.directive === "use strict"
494
+ ) : sharedHookLookupIndex;
495
+ node.body.splice(index + 1, 0, ...(0, import_meriyah.parse)(code).body);
95
496
  },
96
497
  traceCallback: traceAny,
97
498
  tracePromise: traceAny,
@@ -106,25 +507,21 @@ function traceAny(state, node, _parent, ancestry) {
106
507
  }
107
508
  }
108
509
  function traceFunction(state, node, program) {
109
- transforms.tracingChannelDeclaration(state, program, null, []);
510
+ transforms.tracingHookDeclaration(state, program, null, []);
110
511
  const { functionQuery } = state;
111
512
  const methodName = "methodName" in functionQuery ? functionQuery.methodName : void 0;
112
513
  const privateMethodName = "privateMethodName" in functionQuery ? functionQuery.privateMethodName : void 0;
113
514
  const functionName = "functionName" in functionQuery ? functionQuery.functionName : void 0;
114
515
  const isConstructor = methodName === "constructor" || !methodName && !privateMethodName && !functionName;
115
516
  const type = isConstructor ? "ArrowFunctionExpression" : "FunctionExpression";
116
- node.body = wrap(
117
- state,
118
- {
119
- type,
120
- params: node.params,
121
- body: node.body,
122
- async: node.async,
123
- expression: false,
124
- generator: node.generator
125
- },
126
- program
127
- );
517
+ node.body = wrap(state, {
518
+ type,
519
+ params: node.params,
520
+ body: node.body,
521
+ async: node.async,
522
+ expression: false,
523
+ generator: node.generator
524
+ });
128
525
  node.generator = false;
129
526
  node.async = false;
130
527
  wrapSuper(node);
@@ -136,11 +533,11 @@ function traceInstanceMethod(state, node, program) {
136
533
  return;
137
534
  }
138
535
  const classBody = node.body;
139
- if (classBody.body.some(({ key }) => key.name === methodName)) {
536
+ if (classBody.body.some(({ key }) => key?.name === methodName)) {
140
537
  return;
141
538
  }
142
539
  let ctor = classBody.body.find(({ kind }) => kind === "constructor");
143
- transforms.tracingChannelDeclaration(state, program, null, []);
540
+ transforms.tracingHookDeclaration(state, program, null, []);
144
541
  if (!ctor) {
145
542
  ctor = (0, import_meriyah.parse)(
146
543
  node.superClass ? "class A extends Object { constructor (...args) { super(...args) } }" : "class A { constructor () {} }"
@@ -148,47 +545,46 @@ function traceInstanceMethod(state, node, program) {
148
545
  classBody.body.unshift(ctor);
149
546
  }
150
547
  const ctorBody = (0, import_meriyah.parse)(`
151
- const __apm$${methodName} = this["${methodName}"]
548
+ const __bt$${methodName} = this["${methodName}"]
152
549
  this["${methodName}"] = function () {}
153
550
  `).body;
154
551
  const fn = ctorBody[1].expression.right;
155
552
  fn.async = operator === "tracePromise";
156
- fn.body = wrap(
157
- state,
158
- { type: "Identifier", name: `__apm$${methodName}` },
159
- program
160
- );
553
+ fn.body = wrap(state, {
554
+ type: "Identifier",
555
+ name: `__bt$${methodName}`
556
+ });
161
557
  wrapSuper(fn);
162
558
  ctor.value.body.body.push(...ctorBody);
163
559
  }
164
- function wrap(state, node, program) {
560
+ function wrap(state, node) {
165
561
  const { operator, moduleVersion } = state;
166
562
  const wrapper = operator === "traceCallback" ? wrapCallback(state) : operator === "tracePromise" ? wrapPromise(state) : wrapSync(state);
167
563
  const block = wrapper.body[0].body;
168
564
  const common = (0, import_meriyah.parse)(
169
565
  node.type === "ArrowFunctionExpression" ? `
170
- const __apm$ctx = {
566
+ const __bt$ctx = {
171
567
  arguments,
172
568
  moduleVersion: ${JSON.stringify(moduleVersion)}
173
569
  };
174
- const __apm$traced = () => {
175
- const __apm$wrapped = () => {};
176
- return __apm$wrapped(...arguments);
570
+ const __bt$traced = () => {
571
+ const __bt$wrapped = () => {};
572
+ return __bt$wrapped(...arguments);
177
573
  };
178
574
  ` : `
179
- const __apm$ctx = {
575
+ const __bt$ctx = {
180
576
  arguments,
181
577
  self: this,
182
578
  moduleVersion: ${JSON.stringify(moduleVersion)}
183
579
  };
184
- const __apm$traced = () => {
185
- const __apm$wrapped = () => {};
186
- return __apm$wrapped.apply(this, arguments);
580
+ const __bt$traced = () => {
581
+ const __bt$wrapped = () => {};
582
+ return __bt$wrapped.apply(this, arguments);
187
583
  };
188
584
  `
189
585
  ).body;
190
586
  block.body.unshift(...common);
191
- import_esquery.default.query(block, "[id.name=__apm$wrapped]")[0].init = node;
587
+ import_esquery.default.query(block, "[id.name=__bt$wrapped]")[0].init = node;
192
588
  return block;
193
589
  }
194
590
  function wrapSuper(node) {
@@ -200,11 +596,11 @@ function wrapSuper(node) {
200
596
  const { name } = node2.property;
201
597
  let child;
202
598
  if (parent.callee) {
203
- const { expression } = (0, import_meriyah.parse)(`__apm$super['${name}'].call(this)`).body[0];
599
+ const { expression } = (0, import_meriyah.parse)(`__bt$super['${name}'].call(this)`).body[0];
204
600
  parent.callee = child = expression.callee;
205
601
  parent.arguments.unshift(...expression.arguments);
206
602
  } else {
207
- parent.expression = child = (0, import_meriyah.parse)(`__apm$super['${name}']`).body[0];
603
+ parent.expression = child = (0, import_meriyah.parse)(`__bt$super['${name}']`).body[0];
208
604
  }
209
605
  child.computed = parent.callee.computed;
210
606
  child.optional = parent.callee.optional;
@@ -215,14 +611,14 @@ function wrapSuper(node) {
215
611
  const member = (0, import_meriyah.parse)(`
216
612
  class Wrapper {
217
613
  wrapper () {
218
- __apm$super['${name}'] = super['${name}']
614
+ __bt$super['${name}'] = super['${name}']
219
615
  }
220
616
  }
221
617
  `).body[0].body.body[0].value.body.body[0];
222
618
  node.body.body.unshift(member);
223
619
  }
224
620
  if (members.size > 0) {
225
- node.body.body.unshift((0, import_meriyah.parse)("const __apm$super = {}").body[0]);
621
+ node.body.body.unshift((0, import_meriyah.parse)("const __bt$super = {}").body[0]);
226
622
  }
227
623
  }
228
624
  function wrapCallback(state) {
@@ -230,136 +626,41 @@ function wrapCallback(state) {
230
626
  channelName,
231
627
  functionQuery: { callbackIndex = -1 }
232
628
  } = state;
233
- const channelVariable = formatChannelVariable(channelName);
629
+ const channelGetter = formatChannelGetter(channelName);
234
630
  return (0, import_meriyah.parse)(`
235
631
  function wrapper () {
236
- const __apm$cb = Array.prototype.at.call(arguments, ${callbackIndex});
237
-
238
- if (!${channelVariable}.start.hasSubscribers) return __apm$traced();
239
-
240
- function __apm$wrappedCb(err, res) {
241
- if (err) {
242
- __apm$ctx.error = err;
243
- ${channelVariable}.error.publish(__apm$ctx);
244
- } else {
245
- __apm$ctx.result = res;
246
- }
247
-
248
- ${channelVariable}.asyncStart.runStores(__apm$ctx, () => {
249
- try {
250
- if (__apm$cb) {
251
- return __apm$cb.apply(this, arguments);
252
- }
253
- } finally {
254
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
255
- }
256
- });
257
- }
258
-
259
- if (typeof __apm$cb !== 'function') {
260
- return __apm$traced();
261
- }
262
- Array.prototype.splice.call(arguments, ${callbackIndex}, 1, __apm$wrappedCb);
263
-
264
- return ${channelVariable}.start.runStores(__apm$ctx, () => {
265
- try {
266
- return __apm$traced();
267
- } catch (err) {
268
- __apm$ctx.error = err;
269
- ${channelVariable}.error.publish(__apm$ctx);
270
- throw err;
271
- } finally {
272
- __apm$ctx.self ??= this;
273
- ${channelVariable}.end.publish(__apm$ctx);
274
- }
275
- });
632
+ const __bt$hook = ${channelGetter}();
633
+ if (!__bt$hook?.hasSubscribers) return __bt$traced();
634
+ __bt$ctx.self ??= this;
635
+ return __bt$hook.traceCallback(
636
+ __bt$traced,
637
+ ${callbackIndex},
638
+ __bt$ctx
639
+ );
276
640
  }
277
641
  `);
278
642
  }
279
643
  function wrapPromise(state) {
280
644
  const { channelName } = state;
281
- const channelVariable = formatChannelVariable(channelName);
645
+ const channelGetter = formatChannelGetter(channelName);
282
646
  return (0, import_meriyah.parse)(`
283
647
  function wrapper () {
284
- if (!tr_ch_apm_hasSubscribers(${channelVariable})) return __apm$traced();
285
-
286
- return ${channelVariable}.start.runStores(__apm$ctx, () => {
287
- try {
288
- let promise = __apm$traced();
289
- if (typeof promise?.then !== 'function') {
290
- __apm$ctx.result = promise;
291
- return promise;
292
- }
293
- // Mirror Node.js core diagnostics_channel behaviour: for native Promise
294
- // instances, chain normally (safe since there is no subclass API to
295
- // preserve). For Promise subclasses and other thenables, side-chain the
296
- // callbacks for event publishing and return the original so that any
297
- // subclass-specific methods (e.g. APIPromise.withResponse()) remain
298
- // accessible to the caller.
299
- if (promise instanceof Promise && promise.constructor === Promise) {
300
- return promise.then(
301
- result => {
302
- __apm$ctx.result = result;
303
- ${channelVariable}.asyncStart.publish(__apm$ctx);
304
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
305
- return result;
306
- },
307
- err => {
308
- __apm$ctx.error = err;
309
- ${channelVariable}.error.publish(__apm$ctx);
310
- ${channelVariable}.asyncStart.publish(__apm$ctx);
311
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
312
- throw err;
313
- }
314
- );
315
- }
316
- promise.then(
317
- result => {
318
- __apm$ctx.result = result;
319
- ${channelVariable}.asyncStart.publish(__apm$ctx);
320
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
321
- },
322
- err => {
323
- __apm$ctx.error = err;
324
- ${channelVariable}.error.publish(__apm$ctx);
325
- ${channelVariable}.asyncStart.publish(__apm$ctx);
326
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
327
- }
328
- );
329
- return promise;
330
- } catch (err) {
331
- __apm$ctx.error = err;
332
- ${channelVariable}.error.publish(__apm$ctx);
333
- throw err;
334
- } finally {
335
- __apm$ctx.self ??= this;
336
- ${channelVariable}.end.publish(__apm$ctx);
337
- }
338
- });
648
+ const __bt$hook = ${channelGetter}();
649
+ if (!__bt$hook?.hasSubscribers) return __bt$traced();
650
+ __bt$ctx.self ??= this;
651
+ return __bt$hook.tracePromise(__bt$traced, __bt$ctx);
339
652
  }
340
653
  `);
341
654
  }
342
655
  function wrapSync(state) {
343
656
  const { channelName } = state;
344
- const channelVariable = formatChannelVariable(channelName);
657
+ const channelGetter = formatChannelGetter(channelName);
345
658
  return (0, import_meriyah.parse)(`
346
659
  function wrapper () {
347
- if (!tr_ch_apm_hasSubscribers(${channelVariable})) return __apm$traced();
348
-
349
- return ${channelVariable}.start.runStores(__apm$ctx, () => {
350
- try {
351
- const result = __apm$traced();
352
- __apm$ctx.result = result;
353
- return result;
354
- } catch (err) {
355
- __apm$ctx.error = err;
356
- ${channelVariable}.error.publish(__apm$ctx);
357
- throw err;
358
- } finally {
359
- __apm$ctx.self ??= this;
360
- ${channelVariable}.end.publish(__apm$ctx);
361
- }
362
- });
660
+ const __bt$hook = ${channelGetter}();
661
+ if (!__bt$hook?.hasSubscribers) return __bt$traced();
662
+ __bt$ctx.self ??= this;
663
+ return __bt$hook.traceSync(__bt$traced, __bt$ctx);
363
664
  }
364
665
  `);
365
666
  }
@@ -370,16 +671,14 @@ var Transformer = class {
370
671
  version;
371
672
  filePath;
372
673
  configs = [];
373
- dcModule;
374
- constructor(moduleName, version, filePath, configs, dcModule) {
674
+ constructor(moduleName, version, filePath, configs) {
375
675
  this.moduleName = moduleName;
376
676
  this.version = version;
377
677
  this.filePath = filePath;
378
678
  this.configs = configs;
379
- this.dcModule = dcModule;
380
679
  }
381
680
  /**
382
- * Instruments `code` by injecting diagnostics_channel tracing around the
681
+ * Instruments `code` by injecting global tracing hooks around the
383
682
  * target functions defined by this transformer's configs.
384
683
  */
385
684
  transform(code, moduleType) {
@@ -417,8 +716,6 @@ var Transformer = class {
417
716
  const query = astQuery || this.fromFunctionQuery(resolvedFunctionQuery);
418
717
  const state = {
419
718
  ...config,
420
- dcModule: this.dcModule,
421
- moduleType,
422
719
  moduleVersion: this.version,
423
720
  functionQuery: resolvedFunctionQuery,
424
721
  operator: this.getOperator(resolvedFunctionQuery.kind)
@@ -568,11 +865,9 @@ var Transformer = class {
568
865
  // src/auto-instrumentations/orchestrion-js/matcher.ts
569
866
  var InstrumentationMatcher = class {
570
867
  configs = [];
571
- dcModule;
572
868
  transformers = {};
573
- constructor(configs, dcModule) {
869
+ constructor(configs) {
574
870
  this.configs = configs;
575
- this.dcModule = dcModule || "diagnostics_channel";
576
871
  }
577
872
  /**
578
873
  * Returns a Transformer for the given module/file/version, or undefined if no
@@ -594,8 +889,7 @@ var InstrumentationMatcher = class {
594
889
  moduleName,
595
890
  version,
596
891
  filePath,
597
- configs,
598
- this.dcModule
892
+ configs
599
893
  );
600
894
  return this.transformers[id];
601
895
  }
@@ -605,8 +899,8 @@ var InstrumentationMatcher = class {
605
899
  };
606
900
 
607
901
  // src/auto-instrumentations/orchestrion-js/index.ts
608
- function create(configs, dcModule) {
609
- return new InstrumentationMatcher(configs, dcModule);
902
+ function create(configs) {
903
+ return new InstrumentationMatcher(configs);
610
904
  }
611
905
 
612
906
  // src/auto-instrumentations/loader/cjs-patch.ts
@@ -864,6 +1158,9 @@ function applySpecialCasePatch(input) {
864
1158
  if (input.packageName === "openai" && input.modulePath.includes("api-promise")) {
865
1159
  return input.source + OPENAI_API_PROMISE_PATCH;
866
1160
  }
1161
+ if (input.browser) {
1162
+ return null;
1163
+ }
867
1164
  const mastraTarget = classifyMastraTarget(
868
1165
  input.packageName,
869
1166
  input.modulePath
@@ -892,7 +1189,7 @@ var ModulePatch = class {
892
1189
  /**
893
1190
  * Patches the Node.js module class method that is responsible for compiling code.
894
1191
  * If a module is found that has an instrumentator, it will transform the code before compiling it
895
- * with tracing channel methods.
1192
+ * with global hook calls.
896
1193
  */
897
1194
  patch() {
898
1195
  const self = this;