braintrust 3.25.0 → 3.27.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 (79) 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 +4133 -1421
  5. package/dev/dist/index.mjs +3242 -530
  6. package/dist/apply-auto-instrumentation.js +526 -426
  7. package/dist/apply-auto-instrumentation.mjs +329 -229
  8. package/dist/auto-instrumentations/bundler/esbuild.cjs +1198 -364
  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 +6 -8
  12. package/dist/auto-instrumentations/bundler/next.cjs +1227 -413
  13. package/dist/auto-instrumentations/bundler/next.mjs +7 -29
  14. package/dist/auto-instrumentations/bundler/rollup.cjs +1198 -364
  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 +6 -8
  18. package/dist/auto-instrumentations/bundler/vite.cjs +1249 -387
  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 +34 -8
  22. package/dist/auto-instrumentations/bundler/webpack-loader.cjs +1368 -324
  23. package/dist/auto-instrumentations/bundler/webpack-loader.d.ts +20 -12
  24. package/dist/auto-instrumentations/bundler/webpack.cjs +1198 -364
  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 +6 -4
  28. package/dist/auto-instrumentations/chunk-2AMDGD65.mjs +1396 -0
  29. package/dist/auto-instrumentations/{chunk-7P6563SW.mjs → chunk-BW33ULMW.mjs} +2 -6
  30. package/dist/auto-instrumentations/{chunk-M6DLIJ2Z.mjs → chunk-I55G56ZL.mjs} +114 -221
  31. package/dist/auto-instrumentations/chunk-JPUFNW7X.mjs +649 -0
  32. package/dist/auto-instrumentations/{chunk-JPVCUKTY.mjs → chunk-XEYKUBLY.mjs} +191 -73
  33. package/dist/auto-instrumentations/{chunk-CZ24KNHT.mjs → chunk-ZNHTSSGI.mjs} +231 -69
  34. package/dist/auto-instrumentations/hook.mjs +406 -183
  35. package/dist/auto-instrumentations/index.cjs +853 -49
  36. package/dist/auto-instrumentations/index.d.mts +10 -2
  37. package/dist/auto-instrumentations/index.d.ts +10 -2
  38. package/dist/auto-instrumentations/index.mjs +10 -1
  39. package/dist/auto-instrumentations/loader/cjs-patch.cjs +566 -221
  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 +871 -199
  49. package/dist/browser.d.ts +871 -199
  50. package/dist/browser.js +3737 -549
  51. package/dist/browser.mjs +3737 -549
  52. package/dist/{chunk-ABR2QWDP.mjs → chunk-CZM5JIQL.mjs} +788 -132
  53. package/dist/{chunk-P25IOOU4.js → chunk-MF7NU6BT.js} +795 -139
  54. package/dist/{chunk-GSIDVFE6.js → chunk-QRHGVBKU.js} +3580 -1463
  55. package/dist/{chunk-2SANLSWX.mjs → chunk-YKD22IMR.mjs} +2505 -388
  56. package/dist/cli.js +3244 -533
  57. package/dist/edge-light.d.mts +1 -1
  58. package/dist/edge-light.d.ts +1 -1
  59. package/dist/edge-light.js +3737 -552
  60. package/dist/edge-light.mjs +3737 -552
  61. package/dist/index.d.mts +871 -199
  62. package/dist/index.d.ts +871 -199
  63. package/dist/index.js +893 -446
  64. package/dist/index.mjs +463 -16
  65. package/dist/instrumentation/index.d.mts +138 -6
  66. package/dist/instrumentation/index.d.ts +138 -6
  67. package/dist/instrumentation/index.js +3362 -559
  68. package/dist/instrumentation/index.mjs +3362 -559
  69. package/dist/vitest-evals-reporter.js +45 -43
  70. package/dist/vitest-evals-reporter.mjs +5 -3
  71. package/dist/workerd.d.mts +1 -1
  72. package/dist/workerd.d.ts +1 -1
  73. package/dist/workerd.js +3737 -552
  74. package/dist/workerd.mjs +3737 -552
  75. package/licenses/node-diagnostics-channel/LICENSE +19 -0
  76. package/package.json +34 -35
  77. package/dist/auto-instrumentations/chunk-VT6DDNKM.mjs +0 -856
  78. package/dist/auto-instrumentations/plugin-D0KHwSJv.d.mts +0 -44
  79. package/dist/auto-instrumentations/plugin-G6fgxk1b.d.ts +0 -44
@@ -50,52 +50,720 @@ var import_source_map = require("source-map");
50
50
  // src/auto-instrumentations/orchestrion-js/transforms.ts
51
51
  var import_esquery = __toESM(require("esquery"));
52
52
  var import_meriyah = require("meriyah");
53
- var tracingChannelPredicate = (node) => node.declarations?.[0]?.id?.properties?.[0]?.value?.name === "tr_ch_apm_tracingChannel";
54
- var CHANNEL_REGEX = /[^\w]/g;
55
- function formatChannelVariable(channelName) {
56
- return `tr_ch_apm$${channelName.replace(CHANNEL_REGEX, "_")}`;
53
+
54
+ // src/global-instrumentation-hooks.ts
55
+ var GLOBAL_INSTRUMENTATION_HOOKS_KEY = "__braintrust_instrumentation_hooks";
56
+ var GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION = 1;
57
+ var GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND = "braintrust.global-instrumentation-hooks.registry";
58
+ var GLOBAL_INSTRUMENTATION_HOOK_BRAND = "braintrust.global-instrumentation-hooks.hook";
59
+ var GLOBAL_INVOCATION_HOOK_BRAND = "braintrust.global-instrumentation-hooks.invocation-hook";
60
+ var registryBrand = Symbol.for(GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND);
61
+ var hookBrand = Symbol.for(GLOBAL_INSTRUMENTATION_HOOK_BRAND);
62
+ var invocationHookBrand = Symbol.for(GLOBAL_INVOCATION_HOOK_BRAND);
63
+ var errorReporter;
64
+ function reportError(error) {
65
+ try {
66
+ errorReporter?.(error);
67
+ } catch {
68
+ }
57
69
  }
58
- var transforms = {
59
- tracingChannelImport({ dcModule, moduleType }, node) {
60
- if (node.body.some(tracingChannelPredicate)) {
61
- return;
70
+ function setContextValue(context, key, value) {
71
+ try {
72
+ context[key] = value;
73
+ } catch (error) {
74
+ reportError(error);
75
+ }
76
+ }
77
+ function wrapStoreRun(store, message, next, transform) {
78
+ return () => {
79
+ let context;
80
+ try {
81
+ context = transform ? transform(message) : message;
82
+ } catch (error) {
83
+ reportError(error);
84
+ return next();
85
+ }
86
+ let called = false;
87
+ let result;
88
+ let providerError;
89
+ let providerThrew = false;
90
+ const runNext = () => {
91
+ if (called) {
92
+ reportError(
93
+ new Error(
94
+ "Instrumentation store invoked its callback more than once"
95
+ )
96
+ );
97
+ if (providerThrew) {
98
+ throw providerError;
99
+ }
100
+ return result;
101
+ }
102
+ called = true;
103
+ try {
104
+ result = next();
105
+ return result;
106
+ } catch (error) {
107
+ providerThrew = true;
108
+ providerError = error;
109
+ throw error;
110
+ }
111
+ };
112
+ try {
113
+ store.run(context, runNext);
114
+ } catch (error) {
115
+ if (!providerThrew || error !== providerError) {
116
+ reportError(error);
117
+ }
62
118
  }
63
- const options = { module: moduleType === "esm" };
64
- const index = node.body.findIndex(
65
- (child) => child.directive === "use strict"
119
+ if (!called) {
120
+ reportError(
121
+ new Error("Instrumentation store did not invoke its callback")
122
+ );
123
+ return runNext();
124
+ }
125
+ if (providerThrew) {
126
+ throw providerError;
127
+ }
128
+ return result;
129
+ };
130
+ }
131
+ var HookChannel = class {
132
+ constructor(name) {
133
+ this.name = name;
134
+ }
135
+ name;
136
+ subscribers = [];
137
+ stores = /* @__PURE__ */ new Map();
138
+ get hasSubscribers() {
139
+ return this.subscribers.length > 0 || this.stores.size > 0;
140
+ }
141
+ subscribe(subscription) {
142
+ if (typeof subscription !== "function") {
143
+ throw new TypeError("subscription must be a function");
144
+ }
145
+ this.subscribers = [...this.subscribers, subscription];
146
+ }
147
+ unsubscribe(subscription) {
148
+ const index = this.subscribers.indexOf(subscription);
149
+ if (index === -1) {
150
+ return false;
151
+ }
152
+ this.subscribers = [
153
+ ...this.subscribers.slice(0, index),
154
+ ...this.subscribers.slice(index + 1)
155
+ ];
156
+ return true;
157
+ }
158
+ bindStore(store, transform) {
159
+ if (!store || typeof store.run !== "function") {
160
+ throw new TypeError("store must have a run method");
161
+ }
162
+ this.stores.set(
163
+ store,
164
+ transform
66
165
  );
67
- const dc = moduleType === "esm" ? `import tr_ch_apm_dc from "${dcModule}"` : `const tr_ch_apm_dc = ${"require"}("${dcModule}")`;
68
- const tracingChannel = "const { tracingChannel: tr_ch_apm_tracingChannel } = tr_ch_apm_dc";
69
- const hasSubscribers = `const tr_ch_apm_hasSubscribers = ch => ch.start.hasSubscribers
70
- || ch.end.hasSubscribers
71
- || ch.asyncStart.hasSubscribers
72
- || ch.asyncEnd.hasSubscribers
73
- || ch.error.hasSubscribers`;
74
- node.body.splice(
75
- index + 1,
76
- 0,
77
- (0, import_meriyah.parse)(dc, options).body[0],
78
- (0, import_meriyah.parse)(tracingChannel, options).body[0],
79
- (0, import_meriyah.parse)(hasSubscribers, options).body[0]
166
+ }
167
+ unbindStore(store) {
168
+ return this.stores.delete(store);
169
+ }
170
+ publish(message) {
171
+ const subscribers = this.subscribers;
172
+ for (const subscriber of subscribers) {
173
+ try {
174
+ subscriber(message, this.name);
175
+ } catch (error) {
176
+ reportError(error);
177
+ }
178
+ }
179
+ }
180
+ runStores(message, fn, thisArg, ...args) {
181
+ let run = () => {
182
+ this.publish(message);
183
+ return Reflect.apply(fn, thisArg, args);
184
+ };
185
+ for (const [store, transform] of this.stores.entries()) {
186
+ run = wrapStoreRun(store, message, run, transform);
187
+ }
188
+ return run();
189
+ }
190
+ };
191
+ var traceEvents = [
192
+ "start",
193
+ "end",
194
+ "asyncStart",
195
+ "asyncEnd",
196
+ "error"
197
+ ];
198
+ function traceInvocation(hook, operator, target, thisArg, args, additional, callbackIndex = -1) {
199
+ const context = {
200
+ ...additional,
201
+ arguments: args,
202
+ self: thisArg
203
+ };
204
+ const invoke = () => hook.invoke(target, thisArg, args, additional);
205
+ if (operator === "traceCallback") {
206
+ return hook.traceCallback(invoke, callbackIndex, context);
207
+ }
208
+ if (operator === "tracePromise") {
209
+ return hook.tracePromise(invoke, context);
210
+ }
211
+ return hook.traceSync(invoke, context);
212
+ }
213
+ var InvocationHook = class {
214
+ interceptors = [];
215
+ get hasInterceptors() {
216
+ return this.interceptors.length > 0;
217
+ }
218
+ intercept(interceptor) {
219
+ if (typeof interceptor !== "function") {
220
+ throw new TypeError("interceptor must be a function");
221
+ }
222
+ this.interceptors = [...this.interceptors, interceptor];
223
+ let active = true;
224
+ return () => {
225
+ if (!active) {
226
+ return;
227
+ }
228
+ active = false;
229
+ const index = this.interceptors.indexOf(interceptor);
230
+ if (index !== -1) {
231
+ this.interceptors = [
232
+ ...this.interceptors.slice(0, index),
233
+ ...this.interceptors.slice(index + 1)
234
+ ];
235
+ }
236
+ };
237
+ }
238
+ invoke(target, thisArg, args, additional) {
239
+ const interceptors = this.interceptors;
240
+ if (interceptors.length === 0) {
241
+ return Reflect.apply(target, thisArg, args);
242
+ }
243
+ let next = target;
244
+ for (let index = interceptors.length - 1; index >= 0; index -= 1) {
245
+ const interceptor = interceptors[index];
246
+ const downstream = next;
247
+ next = function(...nextArgs) {
248
+ return interceptor(downstream, this, nextArgs, additional);
249
+ };
250
+ }
251
+ return Reflect.apply(next, thisArg, args);
252
+ }
253
+ };
254
+ var TracingHook = class {
255
+ start;
256
+ end;
257
+ asyncStart;
258
+ asyncEnd;
259
+ error;
260
+ invocationHook = new InvocationHook();
261
+ constructor(nameOrChannels) {
262
+ Object.defineProperty(this, hookBrand, {
263
+ configurable: false,
264
+ enumerable: false,
265
+ value: GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
266
+ writable: false
267
+ });
268
+ Object.defineProperty(this, invocationHookBrand, {
269
+ configurable: false,
270
+ enumerable: false,
271
+ value: GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
272
+ writable: false
273
+ });
274
+ if (typeof nameOrChannels === "string") {
275
+ this.start = new HookChannel(`tracing:${nameOrChannels}:start`);
276
+ this.end = new HookChannel(`tracing:${nameOrChannels}:end`);
277
+ this.asyncStart = new HookChannel(`tracing:${nameOrChannels}:asyncStart`);
278
+ this.asyncEnd = new HookChannel(`tracing:${nameOrChannels}:asyncEnd`);
279
+ this.error = new HookChannel(`tracing:${nameOrChannels}:error`);
280
+ return;
281
+ }
282
+ this.start = nameOrChannels.start ?? new HookChannel("tracing:start");
283
+ this.end = nameOrChannels.end ?? new HookChannel("tracing:end");
284
+ this.asyncStart = nameOrChannels.asyncStart ?? new HookChannel("tracing:asyncStart");
285
+ this.asyncEnd = nameOrChannels.asyncEnd ?? new HookChannel("tracing:asyncEnd");
286
+ this.error = nameOrChannels.error ?? new HookChannel("tracing:error");
287
+ }
288
+ get hasSubscribers() {
289
+ return this.start.hasSubscribers || this.end.hasSubscribers || this.asyncStart.hasSubscribers || this.asyncEnd.hasSubscribers || this.error.hasSubscribers;
290
+ }
291
+ get hasInterceptors() {
292
+ return this.invocationHook.hasInterceptors;
293
+ }
294
+ intercept(interceptor) {
295
+ return this.invocationHook.intercept(interceptor);
296
+ }
297
+ invoke(target, thisArg, args, additional) {
298
+ return this.invocationHook.invoke(target, thisArg, args, additional);
299
+ }
300
+ traceInvocation(operator, target, thisArg, args, additional, callbackIndex = -1) {
301
+ return traceInvocation(
302
+ this,
303
+ operator,
304
+ target,
305
+ thisArg,
306
+ args,
307
+ additional,
308
+ callbackIndex
80
309
  );
310
+ }
311
+ subscribe(handlers) {
312
+ for (const eventName of traceEvents) {
313
+ const handler = handlers[eventName];
314
+ if (handler) {
315
+ this[eventName].subscribe(handler);
316
+ }
317
+ }
318
+ }
319
+ unsubscribe(handlers) {
320
+ let done = true;
321
+ for (const eventName of traceEvents) {
322
+ const handler = handlers[eventName];
323
+ if (handler && !this[eventName].unsubscribe(handler)) {
324
+ done = false;
325
+ }
326
+ }
327
+ return done;
328
+ }
329
+ traceSync(fn, message = {}, thisArg, ...args) {
330
+ if (!this.hasSubscribers) {
331
+ return Reflect.apply(fn, thisArg, args);
332
+ }
333
+ const context = message;
334
+ return this.start.runStores(message, () => {
335
+ try {
336
+ const result = Reflect.apply(fn, thisArg, args);
337
+ setContextValue(context, "result", result);
338
+ return result;
339
+ } catch (error) {
340
+ setContextValue(context, "error", error);
341
+ this.error.publish(message);
342
+ throw error;
343
+ } finally {
344
+ this.end.publish(message);
345
+ }
346
+ });
347
+ }
348
+ tracePromise(fn, message = {}, thisArg, ...args) {
349
+ if (!this.hasSubscribers) {
350
+ return Reflect.apply(fn, thisArg, args);
351
+ }
352
+ const context = message;
353
+ return this.start.runStores(message, () => {
354
+ let result;
355
+ try {
356
+ result = Reflect.apply(fn, thisArg, args);
357
+ } catch (error) {
358
+ setContextValue(context, "error", error);
359
+ this.error.publish(message);
360
+ this.end.publish(message);
361
+ throw error;
362
+ }
363
+ this.end.publish(message);
364
+ if (!result || typeof result !== "object" && typeof result !== "function") {
365
+ setContextValue(context, "result", result);
366
+ this.asyncStart.publish(message);
367
+ this.asyncEnd.publish(message);
368
+ return result;
369
+ }
370
+ let terminalPublished = false;
371
+ const finishUnobservedResult = (error) => {
372
+ reportError(error);
373
+ if (!terminalPublished) {
374
+ terminalPublished = true;
375
+ setContextValue(context, "result", result);
376
+ this.asyncStart.publish(message);
377
+ this.asyncEnd.publish(message);
378
+ }
379
+ return result;
380
+ };
381
+ let then;
382
+ try {
383
+ then = result.then;
384
+ } catch (error) {
385
+ return finishUnobservedResult(error);
386
+ }
387
+ if (typeof then !== "function") {
388
+ setContextValue(context, "result", result);
389
+ this.asyncStart.publish(message);
390
+ this.asyncEnd.publish(message);
391
+ return result;
392
+ }
393
+ const resolve = (resolved) => {
394
+ if (!terminalPublished) {
395
+ terminalPublished = true;
396
+ setContextValue(context, "result", resolved);
397
+ this.asyncStart.publish(message);
398
+ this.asyncEnd.publish(message);
399
+ }
400
+ return resolved;
401
+ };
402
+ let rejectionThrown = false;
403
+ let rejectionError;
404
+ const reject = (error) => {
405
+ if (!terminalPublished) {
406
+ terminalPublished = true;
407
+ setContextValue(context, "error", error);
408
+ this.error.publish(message);
409
+ this.asyncStart.publish(message);
410
+ this.asyncEnd.publish(message);
411
+ }
412
+ rejectionThrown = true;
413
+ rejectionError = error;
414
+ throw error;
415
+ };
416
+ let isPlainPromise;
417
+ try {
418
+ isPlainPromise = result instanceof Promise && result.constructor === Promise;
419
+ } catch (error) {
420
+ return finishUnobservedResult(error);
421
+ }
422
+ try {
423
+ if (isPlainPromise) {
424
+ return Reflect.apply(then, result, [resolve, reject]);
425
+ }
426
+ Reflect.apply(then, result, [
427
+ resolve,
428
+ (error) => {
429
+ try {
430
+ reject(error);
431
+ } catch {
432
+ }
433
+ }
434
+ ]);
435
+ } catch (error) {
436
+ if (rejectionThrown && error === rejectionError) {
437
+ return result;
438
+ }
439
+ return finishUnobservedResult(error);
440
+ }
441
+ return result;
442
+ });
443
+ }
444
+ traceCallback(fn, position = -1, message = {}, thisArg, ...args) {
445
+ if (!this.hasSubscribers) {
446
+ return Reflect.apply(fn, thisArg, args);
447
+ }
448
+ const context = message;
449
+ const callArgs = args.length > 0 ? args : context.arguments ?? args;
450
+ const callback = Array.prototype.at.call(callArgs, position);
451
+ if (typeof callback !== "function") {
452
+ return Reflect.apply(fn, thisArg, args);
453
+ }
454
+ const { asyncStart, asyncEnd, error: errorChannel } = this;
455
+ function wrappedCallback(error, result) {
456
+ if (error) {
457
+ setContextValue(context, "error", error);
458
+ errorChannel.publish(message);
459
+ } else {
460
+ setContextValue(context, "result", result);
461
+ }
462
+ return asyncStart.runStores(message, () => {
463
+ try {
464
+ return Reflect.apply(callback, this, arguments);
465
+ } finally {
466
+ asyncEnd.publish(message);
467
+ }
468
+ });
469
+ }
470
+ Array.prototype.splice.call(callArgs, position, 1, wrappedCallback);
471
+ return this.start.runStores(message, () => {
472
+ try {
473
+ return Reflect.apply(fn, thisArg, args);
474
+ } catch (error) {
475
+ setContextValue(context, "error", error);
476
+ this.error.publish(message);
477
+ throw error;
478
+ } finally {
479
+ this.end.publish(message);
480
+ }
481
+ });
482
+ }
483
+ };
484
+ var inertChannel = Object.freeze({
485
+ name: "braintrust:inert",
486
+ hasSubscribers: false,
487
+ subscribe() {
488
+ },
489
+ unsubscribe() {
490
+ return false;
491
+ },
492
+ bindStore() {
81
493
  },
82
- tracingChannelDeclaration(state, node) {
494
+ unbindStore() {
495
+ return false;
496
+ },
497
+ publish() {
498
+ },
499
+ runStores(_message, fn, thisArg, ...args) {
500
+ return Reflect.apply(fn, thisArg, args);
501
+ }
502
+ });
503
+ var inertTracingHook = new TracingHook({
504
+ start: inertChannel,
505
+ end: inertChannel,
506
+ asyncStart: inertChannel,
507
+ asyncEnd: inertChannel,
508
+ error: inertChannel
509
+ });
510
+ function isHookChannel(value) {
511
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
512
+ return false;
513
+ }
514
+ try {
515
+ const channel2 = value;
516
+ return typeof channel2.hasSubscribers === "boolean" && typeof channel2.subscribe === "function" && typeof channel2.unsubscribe === "function" && typeof channel2.bindStore === "function" && typeof channel2.unbindStore === "function" && typeof channel2.publish === "function" && typeof channel2.runStores === "function";
517
+ } catch {
518
+ return false;
519
+ }
520
+ }
521
+ function hasTracingHookShape(value) {
522
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
523
+ return false;
524
+ }
525
+ try {
526
+ const hook = value;
527
+ 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);
528
+ } catch {
529
+ return false;
530
+ }
531
+ }
532
+ function hasInvocationHookShape(value) {
533
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
534
+ return false;
535
+ }
536
+ try {
537
+ const hook = value;
538
+ return value[invocationHookBrand] === GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION && typeof hook.hasInterceptors === "boolean" && typeof hook.intercept === "function" && typeof hook.invoke === "function";
539
+ } catch {
540
+ return false;
541
+ }
542
+ }
543
+ function installInvocationHook(value) {
544
+ const hasInvocationHook = hasInvocationHookShape(value);
545
+ const invocationHook = new InvocationHook();
546
+ try {
547
+ if (!hasInvocationHook) {
548
+ Object.defineProperties(value, {
549
+ [invocationHookBrand]: {
550
+ configurable: false,
551
+ enumerable: false,
552
+ value: GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
553
+ writable: false
554
+ },
555
+ hasInterceptors: {
556
+ configurable: false,
557
+ enumerable: false,
558
+ get: () => invocationHook.hasInterceptors
559
+ },
560
+ intercept: {
561
+ configurable: false,
562
+ enumerable: false,
563
+ value: invocationHook.intercept.bind(invocationHook),
564
+ writable: false
565
+ },
566
+ invoke: {
567
+ configurable: false,
568
+ enumerable: false,
569
+ value: invocationHook.invoke.bind(invocationHook),
570
+ writable: false
571
+ }
572
+ });
573
+ }
574
+ if (typeof value.traceInvocation !== "function") {
575
+ Object.defineProperty(value, "traceInvocation", {
576
+ configurable: false,
577
+ enumerable: false,
578
+ value: traceInvocation.bind(void 0, value),
579
+ writable: false
580
+ });
581
+ }
582
+ } catch (error) {
583
+ reportError(error);
584
+ }
585
+ }
586
+ function isCompatibleTracingHook(value) {
587
+ try {
588
+ return value[hookBrand] === GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION && hasTracingHookShape(value);
589
+ } catch {
590
+ return false;
591
+ }
592
+ }
593
+ function isCompatibleHookRegistry(value) {
594
+ try {
595
+ return value instanceof Map && value[registryBrand] === GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION;
596
+ } catch {
597
+ return false;
598
+ }
599
+ }
600
+ function getHookRegistry() {
601
+ let descriptor;
602
+ try {
603
+ descriptor = Object.getOwnPropertyDescriptor(
604
+ globalThis,
605
+ GLOBAL_INSTRUMENTATION_HOOKS_KEY
606
+ );
607
+ } catch (error) {
608
+ reportError(error);
609
+ return void 0;
610
+ }
611
+ if (descriptor && "value" in descriptor && isCompatibleHookRegistry(descriptor.value) && (descriptor.configurable || descriptor.enumerable === false)) {
612
+ if (descriptor.configurable || descriptor.writable) {
613
+ try {
614
+ Object.defineProperty(globalThis, GLOBAL_INSTRUMENTATION_HOOKS_KEY, {
615
+ configurable: false,
616
+ enumerable: false,
617
+ value: descriptor.value,
618
+ writable: false
619
+ });
620
+ } catch (error) {
621
+ reportError(error);
622
+ return void 0;
623
+ }
624
+ }
625
+ return descriptor.value;
626
+ }
627
+ if (descriptor && !descriptor.configurable) {
628
+ reportError(new Error("Incompatible global instrumentation hook registry"));
629
+ return void 0;
630
+ }
631
+ const registry = /* @__PURE__ */ new Map();
632
+ try {
633
+ Object.defineProperty(registry, registryBrand, {
634
+ configurable: false,
635
+ enumerable: false,
636
+ value: GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
637
+ writable: false
638
+ });
639
+ } catch (error) {
640
+ reportError(error);
641
+ return void 0;
642
+ }
643
+ try {
644
+ Object.defineProperty(globalThis, GLOBAL_INSTRUMENTATION_HOOKS_KEY, {
645
+ configurable: false,
646
+ enumerable: false,
647
+ value: registry,
648
+ writable: false
649
+ });
650
+ return registry;
651
+ } catch (error) {
652
+ reportError(error);
653
+ return void 0;
654
+ }
655
+ }
656
+ function newGlobalTracingChannel(nameOrChannels) {
657
+ if (typeof nameOrChannels !== "string") {
658
+ return new TracingHook(nameOrChannels);
659
+ }
660
+ const registry = getHookRegistry();
661
+ if (!registry) {
662
+ return inertTracingHook;
663
+ }
664
+ let existing;
665
+ try {
666
+ existing = Map.prototype.get.call(registry, nameOrChannels);
667
+ } catch (error) {
668
+ reportError(error);
669
+ return inertTracingHook;
670
+ }
671
+ if (isCompatibleTracingHook(existing)) {
672
+ installInvocationHook(existing);
673
+ return existing;
674
+ }
675
+ if (existing !== void 0) {
676
+ reportError(
677
+ new Error(`Invalid global instrumentation hook: ${nameOrChannels}`)
678
+ );
679
+ try {
680
+ Map.prototype.delete.call(registry, nameOrChannels);
681
+ } catch (error) {
682
+ reportError(error);
683
+ return inertTracingHook;
684
+ }
685
+ }
686
+ const hook = new TracingHook(nameOrChannels);
687
+ try {
688
+ Map.prototype.set.call(registry, nameOrChannels, hook);
689
+ } catch (error) {
690
+ reportError(error);
691
+ return inertTracingHook;
692
+ }
693
+ return hook;
694
+ }
695
+
696
+ // src/auto-instrumentations/orchestrion-js/transforms.ts
697
+ var CHANNEL_REGEX = /[^\w]/g;
698
+ var SHARED_HOOK_LOOKUP = "tr_ch_bt$get_hook";
699
+ function formatChannelVariable(channelName) {
700
+ return `tr_ch_bt$${channelName.replace(CHANNEL_REGEX, "_")}`;
701
+ }
702
+ function formatChannelGetter(channelName) {
703
+ return `tr_ch_bt$get_${channelName.replace(CHANNEL_REGEX, "_")}`;
704
+ }
705
+ var transforms = {
706
+ tracingHookDeclaration(state, node) {
83
707
  const {
84
708
  channelName,
85
709
  module: { name }
86
710
  } = state;
87
711
  const channelVariable = formatChannelVariable(channelName);
712
+ const channelGetter = formatChannelGetter(channelName);
713
+ const hasSharedHookLookup = node.body.some(
714
+ (child) => child.declarations?.[0]?.id?.name === SHARED_HOOK_LOOKUP
715
+ );
88
716
  if (node.body.some(
89
- (child) => child.declarations?.[0]?.id?.name === channelVariable
717
+ (child) => child.declarations?.[0]?.id?.name === channelGetter
90
718
  )) {
91
719
  return;
92
720
  }
93
- transforms.tracingChannelImport(state, node, null, []);
94
- const index = node.body.findIndex(tracingChannelPredicate);
721
+ const sharedHookLookup = hasSharedHookLookup ? "" : `
722
+ const ${SHARED_HOOK_LOOKUP} = (__bt$hookName) => {
723
+ try {
724
+ const __bt$hooks = globalThis[${JSON.stringify(
725
+ GLOBAL_INSTRUMENTATION_HOOKS_KEY
726
+ )}];
727
+ if (
728
+ !(__bt$hooks instanceof Map) ||
729
+ __bt$hooks[Symbol.for(${JSON.stringify(
730
+ GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND
731
+ )})] !== ${GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION}
732
+ ) return undefined;
733
+ const __bt$hook = Map.prototype.get.call(
734
+ __bt$hooks,
735
+ __bt$hookName
736
+ );
737
+ if (
738
+ (__bt$hook === null ||
739
+ (typeof __bt$hook !== "object" &&
740
+ typeof __bt$hook !== "function")) ||
741
+ __bt$hook[Symbol.for(${JSON.stringify(
742
+ GLOBAL_INSTRUMENTATION_HOOK_BRAND
743
+ )})] !== ${GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION} ||
744
+ typeof __bt$hook.traceInvocation !== "function"
745
+ ) return undefined;
746
+ return __bt$hook;
747
+ } catch {
748
+ return undefined;
749
+ }
750
+ };
751
+ `;
95
752
  const code = `
96
- const ${channelVariable} = tr_ch_apm_tracingChannel("orchestrion:${name}:${channelName}")
753
+ ${sharedHookLookup}
754
+ let ${channelVariable};
755
+ const ${channelGetter} = () =>
756
+ ${channelVariable} ??= ${SHARED_HOOK_LOOKUP}(
757
+ ${JSON.stringify(`orchestrion:${name}:${channelName}`)}
758
+ );
97
759
  `;
98
- node.body.splice(index + 1, 0, (0, import_meriyah.parse)(code).body[0]);
760
+ const sharedHookLookupIndex = node.body.findIndex(
761
+ (child) => child.declarations?.[0]?.id?.name === SHARED_HOOK_LOOKUP
762
+ );
763
+ const index = sharedHookLookupIndex === -1 ? node.body.findIndex(
764
+ (child) => child.directive === "use strict"
765
+ ) : sharedHookLookupIndex;
766
+ node.body.splice(index + 1, 0, ...(0, import_meriyah.parse)(code).body);
99
767
  },
100
768
  traceCallback: traceAny,
101
769
  tracePromise: traceAny,
@@ -110,25 +778,21 @@ function traceAny(state, node, _parent, ancestry) {
110
778
  }
111
779
  }
112
780
  function traceFunction(state, node, program) {
113
- transforms.tracingChannelDeclaration(state, program, null, []);
781
+ transforms.tracingHookDeclaration(state, program, null, []);
114
782
  const { functionQuery } = state;
115
783
  const methodName = "methodName" in functionQuery ? functionQuery.methodName : void 0;
116
784
  const privateMethodName = "privateMethodName" in functionQuery ? functionQuery.privateMethodName : void 0;
117
785
  const functionName = "functionName" in functionQuery ? functionQuery.functionName : void 0;
118
786
  const isConstructor = methodName === "constructor" || !methodName && !privateMethodName && !functionName;
119
787
  const type = isConstructor ? "ArrowFunctionExpression" : "FunctionExpression";
120
- node.body = wrap(
121
- state,
122
- {
123
- type,
124
- params: node.params,
125
- body: node.body,
126
- async: node.async,
127
- expression: false,
128
- generator: node.generator
129
- },
130
- program
131
- );
788
+ node.body = wrap(state, {
789
+ type,
790
+ params: node.params,
791
+ body: node.body,
792
+ async: node.async,
793
+ expression: false,
794
+ generator: node.generator
795
+ });
132
796
  node.generator = false;
133
797
  node.async = false;
134
798
  wrapSuper(node);
@@ -140,11 +804,11 @@ function traceInstanceMethod(state, node, program) {
140
804
  return;
141
805
  }
142
806
  const classBody = node.body;
143
- if (classBody.body.some(({ key }) => key.name === methodName)) {
807
+ if (classBody.body.some(({ key }) => key?.name === methodName)) {
144
808
  return;
145
809
  }
146
810
  let ctor = classBody.body.find(({ kind }) => kind === "constructor");
147
- transforms.tracingChannelDeclaration(state, program, null, []);
811
+ transforms.tracingHookDeclaration(state, program, null, []);
148
812
  if (!ctor) {
149
813
  ctor = (0, import_meriyah.parse)(
150
814
  node.superClass ? "class A extends Object { constructor (...args) { super(...args) } }" : "class A { constructor () {} }"
@@ -152,47 +816,36 @@ function traceInstanceMethod(state, node, program) {
152
816
  classBody.body.unshift(ctor);
153
817
  }
154
818
  const ctorBody = (0, import_meriyah.parse)(`
155
- const __apm$${methodName} = this["${methodName}"]
819
+ const __bt$${methodName} = this["${methodName}"]
156
820
  this["${methodName}"] = function () {}
157
821
  `).body;
158
822
  const fn = ctorBody[1].expression.right;
159
823
  fn.async = operator === "tracePromise";
160
- fn.body = wrap(
161
- state,
162
- { type: "Identifier", name: `__apm$${methodName}` },
163
- program
164
- );
824
+ fn.body = wrap(state, {
825
+ type: "Identifier",
826
+ name: `__bt$${methodName}`
827
+ });
165
828
  wrapSuper(fn);
166
829
  ctor.value.body.body.push(...ctorBody);
167
830
  }
168
- function wrap(state, node, program) {
169
- const { operator, moduleVersion } = state;
170
- const wrapper = operator === "traceCallback" ? wrapCallback(state) : operator === "tracePromise" ? wrapPromise(state) : wrapSync(state);
831
+ function wrap(state, node) {
832
+ const wrapper = wrapInvocation(state);
171
833
  const block = wrapper.body[0].body;
172
834
  const common = (0, import_meriyah.parse)(
173
835
  node.type === "ArrowFunctionExpression" ? `
174
- const __apm$ctx = {
175
- arguments,
176
- moduleVersion: ${JSON.stringify(moduleVersion)}
177
- };
178
- const __apm$traced = () => {
179
- const __apm$wrapped = () => {};
180
- return __apm$wrapped(...arguments);
836
+ const __bt$target = (...__bt$args) => {
837
+ const __bt$wrapped = () => {};
838
+ return __bt$wrapped(...__bt$args);
181
839
  };
182
840
  ` : `
183
- const __apm$ctx = {
184
- arguments,
185
- self: this,
186
- moduleVersion: ${JSON.stringify(moduleVersion)}
187
- };
188
- const __apm$traced = () => {
189
- const __apm$wrapped = () => {};
190
- return __apm$wrapped.apply(this, arguments);
841
+ const __bt$target = function (...__bt$args) {
842
+ const __bt$wrapped = () => {};
843
+ return __bt$wrapped.apply(this, __bt$args);
191
844
  };
192
845
  `
193
846
  ).body;
194
847
  block.body.unshift(...common);
195
- import_esquery.default.query(block, "[id.name=__apm$wrapped]")[0].init = node;
848
+ import_esquery.default.query(block, "[id.name=__bt$wrapped]")[0].init = node;
196
849
  return block;
197
850
  }
198
851
  function wrapSuper(node) {
@@ -204,11 +857,11 @@ function wrapSuper(node) {
204
857
  const { name } = node2.property;
205
858
  let child;
206
859
  if (parent.callee) {
207
- const { expression } = (0, import_meriyah.parse)(`__apm$super['${name}'].call(this)`).body[0];
860
+ const { expression } = (0, import_meriyah.parse)(`__bt$super['${name}'].call(this)`).body[0];
208
861
  parent.callee = child = expression.callee;
209
862
  parent.arguments.unshift(...expression.arguments);
210
863
  } else {
211
- parent.expression = child = (0, import_meriyah.parse)(`__apm$super['${name}']`).body[0];
864
+ parent.expression = child = (0, import_meriyah.parse)(`__bt$super['${name}']`).body[0];
212
865
  }
213
866
  child.computed = parent.callee.computed;
214
867
  child.optional = parent.callee.optional;
@@ -219,151 +872,32 @@ function wrapSuper(node) {
219
872
  const member = (0, import_meriyah.parse)(`
220
873
  class Wrapper {
221
874
  wrapper () {
222
- __apm$super['${name}'] = super['${name}']
875
+ __bt$super['${name}'] = super['${name}']
223
876
  }
224
877
  }
225
878
  `).body[0].body.body[0].value.body.body[0];
226
879
  node.body.body.unshift(member);
227
880
  }
228
881
  if (members.size > 0) {
229
- node.body.body.unshift((0, import_meriyah.parse)("const __apm$super = {}").body[0]);
882
+ node.body.body.unshift((0, import_meriyah.parse)("const __bt$super = {}").body[0]);
230
883
  }
231
884
  }
232
- function wrapCallback(state) {
233
- const {
234
- channelName,
235
- functionQuery: { callbackIndex = -1 }
236
- } = state;
237
- const channelVariable = formatChannelVariable(channelName);
238
- return (0, import_meriyah.parse)(`
239
- function wrapper () {
240
- const __apm$cb = Array.prototype.at.call(arguments, ${callbackIndex});
241
-
242
- if (!${channelVariable}.start.hasSubscribers) return __apm$traced();
243
-
244
- function __apm$wrappedCb(err, res) {
245
- if (err) {
246
- __apm$ctx.error = err;
247
- ${channelVariable}.error.publish(__apm$ctx);
248
- } else {
249
- __apm$ctx.result = res;
250
- }
251
-
252
- ${channelVariable}.asyncStart.runStores(__apm$ctx, () => {
253
- try {
254
- if (__apm$cb) {
255
- return __apm$cb.apply(this, arguments);
256
- }
257
- } finally {
258
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
259
- }
260
- });
261
- }
262
-
263
- if (typeof __apm$cb !== 'function') {
264
- return __apm$traced();
265
- }
266
- Array.prototype.splice.call(arguments, ${callbackIndex}, 1, __apm$wrappedCb);
267
-
268
- return ${channelVariable}.start.runStores(__apm$ctx, () => {
269
- try {
270
- return __apm$traced();
271
- } catch (err) {
272
- __apm$ctx.error = err;
273
- ${channelVariable}.error.publish(__apm$ctx);
274
- throw err;
275
- } finally {
276
- __apm$ctx.self ??= this;
277
- ${channelVariable}.end.publish(__apm$ctx);
278
- }
279
- });
280
- }
281
- `);
282
- }
283
- function wrapPromise(state) {
284
- const { channelName } = state;
285
- const channelVariable = formatChannelVariable(channelName);
286
- return (0, import_meriyah.parse)(`
287
- function wrapper () {
288
- if (!tr_ch_apm_hasSubscribers(${channelVariable})) return __apm$traced();
289
-
290
- return ${channelVariable}.start.runStores(__apm$ctx, () => {
291
- try {
292
- let promise = __apm$traced();
293
- if (typeof promise?.then !== 'function') {
294
- __apm$ctx.result = promise;
295
- return promise;
296
- }
297
- // Mirror Node.js core diagnostics_channel behaviour: for native Promise
298
- // instances, chain normally (safe since there is no subclass API to
299
- // preserve). For Promise subclasses and other thenables, side-chain the
300
- // callbacks for event publishing and return the original so that any
301
- // subclass-specific methods (e.g. APIPromise.withResponse()) remain
302
- // accessible to the caller.
303
- if (promise instanceof Promise && promise.constructor === Promise) {
304
- return promise.then(
305
- result => {
306
- __apm$ctx.result = result;
307
- ${channelVariable}.asyncStart.publish(__apm$ctx);
308
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
309
- return result;
310
- },
311
- err => {
312
- __apm$ctx.error = err;
313
- ${channelVariable}.error.publish(__apm$ctx);
314
- ${channelVariable}.asyncStart.publish(__apm$ctx);
315
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
316
- throw err;
317
- }
318
- );
319
- }
320
- promise.then(
321
- result => {
322
- __apm$ctx.result = result;
323
- ${channelVariable}.asyncStart.publish(__apm$ctx);
324
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
325
- },
326
- err => {
327
- __apm$ctx.error = err;
328
- ${channelVariable}.error.publish(__apm$ctx);
329
- ${channelVariable}.asyncStart.publish(__apm$ctx);
330
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
331
- }
332
- );
333
- return promise;
334
- } catch (err) {
335
- __apm$ctx.error = err;
336
- ${channelVariable}.error.publish(__apm$ctx);
337
- throw err;
338
- } finally {
339
- __apm$ctx.self ??= this;
340
- ${channelVariable}.end.publish(__apm$ctx);
341
- }
342
- });
343
- }
344
- `);
345
- }
346
- function wrapSync(state) {
347
- const { channelName } = state;
348
- const channelVariable = formatChannelVariable(channelName);
885
+ function wrapInvocation(state) {
886
+ const { channelName, moduleVersion, operator, functionQuery } = state;
887
+ const channelGetter = formatChannelGetter(channelName);
888
+ const callbackIndex = functionQuery.callbackIndex ?? -1;
349
889
  return (0, import_meriyah.parse)(`
350
890
  function wrapper () {
351
- if (!tr_ch_apm_hasSubscribers(${channelVariable})) return __apm$traced();
352
-
353
- return ${channelVariable}.start.runStores(__apm$ctx, () => {
354
- try {
355
- const result = __apm$traced();
356
- __apm$ctx.result = result;
357
- return result;
358
- } catch (err) {
359
- __apm$ctx.error = err;
360
- ${channelVariable}.error.publish(__apm$ctx);
361
- throw err;
362
- } finally {
363
- __apm$ctx.self ??= this;
364
- ${channelVariable}.end.publish(__apm$ctx);
365
- }
366
- });
891
+ const __bt$hook = ${channelGetter}();
892
+ if (!__bt$hook) return __bt$target.apply(this, arguments);
893
+ return __bt$hook.traceInvocation(
894
+ ${JSON.stringify(operator)},
895
+ __bt$target,
896
+ this,
897
+ arguments,
898
+ { moduleVersion: ${JSON.stringify(moduleVersion)} },
899
+ ${callbackIndex}
900
+ );
367
901
  }
368
902
  `);
369
903
  }
@@ -374,16 +908,14 @@ var Transformer = class {
374
908
  version;
375
909
  filePath;
376
910
  configs = [];
377
- dcModule;
378
- constructor(moduleName, version, filePath, configs, dcModule) {
911
+ constructor(moduleName, version, filePath, configs) {
379
912
  this.moduleName = moduleName;
380
913
  this.version = version;
381
914
  this.filePath = filePath;
382
915
  this.configs = configs;
383
- this.dcModule = dcModule;
384
916
  }
385
917
  /**
386
- * Instruments `code` by injecting diagnostics_channel tracing around the
918
+ * Instruments `code` by injecting global tracing hooks around the
387
919
  * target functions defined by this transformer's configs.
388
920
  */
389
921
  transform(code, moduleType) {
@@ -421,8 +953,6 @@ var Transformer = class {
421
953
  const query = astQuery || this.fromFunctionQuery(resolvedFunctionQuery);
422
954
  const state = {
423
955
  ...config,
424
- dcModule: this.dcModule,
425
- moduleType,
426
956
  moduleVersion: this.version,
427
957
  functionQuery: resolvedFunctionQuery,
428
958
  operator: this.getOperator(resolvedFunctionQuery.kind)
@@ -572,11 +1102,9 @@ var Transformer = class {
572
1102
  // src/auto-instrumentations/orchestrion-js/matcher.ts
573
1103
  var InstrumentationMatcher = class {
574
1104
  configs = [];
575
- dcModule;
576
1105
  transformers = {};
577
- constructor(configs, dcModule) {
1106
+ constructor(configs) {
578
1107
  this.configs = configs;
579
- this.dcModule = dcModule || "diagnostics_channel";
580
1108
  }
581
1109
  /**
582
1110
  * Returns a Transformer for the given module/file/version, or undefined if no
@@ -598,8 +1126,7 @@ var InstrumentationMatcher = class {
598
1126
  moduleName,
599
1127
  version,
600
1128
  filePath,
601
- configs,
602
- this.dcModule
1129
+ configs
603
1130
  );
604
1131
  return this.transformers[id];
605
1132
  }
@@ -609,8 +1136,8 @@ var InstrumentationMatcher = class {
609
1136
  };
610
1137
 
611
1138
  // src/auto-instrumentations/orchestrion-js/index.ts
612
- function create(configs, dcModule) {
613
- return new InstrumentationMatcher(configs, dcModule);
1139
+ function create(configs) {
1140
+ return new InstrumentationMatcher(configs);
614
1141
  }
615
1142
 
616
1143
  // src/auto-instrumentations/bundler/plugin.ts
@@ -636,6 +1163,9 @@ var envIntegrationAliases = {
636
1163
  strandsagentsdk: "strandsAgentSDK",
637
1164
  "strands-agent-sdk": "strandsAgentSDK",
638
1165
  "@strands-agents/sdk": "strandsAgentSDK",
1166
+ agents: "cloudflareAgents",
1167
+ "cloudflare-agents": "cloudflareAgents",
1168
+ cloudflareagents: "cloudflareAgents",
639
1169
  anthropic: "anthropic",
640
1170
  aisdk: "aisdk",
641
1171
  "ai-sdk": "aisdk",
@@ -643,6 +1173,10 @@ var envIntegrationAliases = {
643
1173
  vercel: "vercel",
644
1174
  claudeagentsdk: "claudeAgentSDK",
645
1175
  "claude-agent-sdk": "claudeAgentSDK",
1176
+ cloudflareaichat: "cloudflareAIChat",
1177
+ "cloudflare-ai-chat": "cloudflareAIChat",
1178
+ "@cloudflare/ai-chat": "cloudflareAIChat",
1179
+ cloudflarethink: "cloudflareThink",
646
1180
  cursor: "cursor",
647
1181
  "cursor-sdk": "cursorSDK",
648
1182
  cursorsdk: "cursorSDK",
@@ -657,10 +1191,13 @@ var envIntegrationAliases = {
657
1191
  "google-genai": "googleGenAI",
658
1192
  googlegenai: "googleGenAI",
659
1193
  huggingface: "huggingface",
1194
+ "@huggingface/transformers": "huggingface",
1195
+ transformers: "huggingface",
660
1196
  openrouter: "openrouter",
661
1197
  openrouteragent: "openrouterAgent",
662
1198
  "openrouter-agent": "openrouterAgent",
663
1199
  mistral: "mistral",
1200
+ ollama: "ollama",
664
1201
  googleadk: "googleADK",
665
1202
  "google-adk": "googleADK",
666
1203
  cohere: "cohere",
@@ -713,73 +1250,6 @@ var DefaultAsyncLocalStorage = class {
713
1250
  return void 0;
714
1251
  }
715
1252
  };
716
- var DefaultChannel = class {
717
- constructor(name) {
718
- this.name = name;
719
- }
720
- name;
721
- hasSubscribers = false;
722
- subscribe(_subscription) {
723
- }
724
- unsubscribe(_subscription) {
725
- return false;
726
- }
727
- bindStore(_store, _transform) {
728
- }
729
- unbindStore(_store) {
730
- return false;
731
- }
732
- publish(_message) {
733
- }
734
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
735
- runStores(_message, fn, thisArg, ...args) {
736
- return fn.apply(thisArg, args);
737
- }
738
- };
739
- var DefaultTracingChannel = class {
740
- start;
741
- end;
742
- asyncStart;
743
- asyncEnd;
744
- error;
745
- constructor(nameOrChannels) {
746
- if (typeof nameOrChannels === "string") {
747
- this.start = new DefaultChannel(`tracing:${nameOrChannels}:start`);
748
- this.end = new DefaultChannel(`tracing:${nameOrChannels}:end`);
749
- this.asyncStart = new DefaultChannel(
750
- `tracing:${nameOrChannels}:asyncStart`
751
- );
752
- this.asyncEnd = new DefaultChannel(`tracing:${nameOrChannels}:asyncEnd`);
753
- this.error = new DefaultChannel(`tracing:${nameOrChannels}:error`);
754
- return;
755
- }
756
- this.start = nameOrChannels.start ?? new DefaultChannel("tracing:start");
757
- this.end = nameOrChannels.end ?? new DefaultChannel("tracing:end");
758
- this.asyncStart = nameOrChannels.asyncStart ?? new DefaultChannel("tracing:asyncStart");
759
- this.asyncEnd = nameOrChannels.asyncEnd ?? new DefaultChannel("tracing:asyncEnd");
760
- this.error = nameOrChannels.error ?? new DefaultChannel("tracing:error");
761
- }
762
- get hasSubscribers() {
763
- return this.start.hasSubscribers || this.end.hasSubscribers || this.asyncStart.hasSubscribers || this.asyncEnd.hasSubscribers || this.error.hasSubscribers;
764
- }
765
- subscribe(_handlers) {
766
- }
767
- unsubscribe(_handlers) {
768
- return false;
769
- }
770
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
771
- traceSync(fn, _message, thisArg, ...args) {
772
- return fn.apply(thisArg, args);
773
- }
774
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
775
- tracePromise(fn, _message, thisArg, ...args) {
776
- return fn.apply(thisArg, args);
777
- }
778
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
779
- traceCallback(fn, _position, _message, thisArg, ...args) {
780
- return fn.apply(thisArg, args);
781
- }
782
- };
783
1253
  var iso = {
784
1254
  buildType: "unknown",
785
1255
  // Will be set by configureBrowser() or configureNode()
@@ -790,7 +1260,7 @@ var iso = {
790
1260
  getCallerLocation: () => void 0,
791
1261
  newAsyncLocalStorage: () => new DefaultAsyncLocalStorage(),
792
1262
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
793
- newTracingChannel: (nameOrChannels) => new DefaultTracingChannel(nameOrChannels),
1263
+ newTracingChannel: (nameOrChannels) => newGlobalTracingChannel(nameOrChannels),
794
1264
  processOn: (_0, _1) => {
795
1265
  },
796
1266
  basename: (filepath) => filepath.split(/[\\/]/).pop() || filepath,
@@ -813,11 +1283,21 @@ function defineChannels(pkg, channels, options) {
813
1283
  const tracingChannel2 = () => isomorph_default.newTracingChannel(
814
1284
  fullChannelName
815
1285
  );
1286
+ const intercept2 = (interceptor) => {
1287
+ const hook = tracingChannel2();
1288
+ return typeof hook.intercept === "function" ? hook.intercept(interceptor) : () => {
1289
+ };
1290
+ };
816
1291
  return [
817
1292
  key,
818
1293
  {
819
1294
  ...asyncSpec,
820
1295
  instrumentationName,
1296
+ intercept: intercept2,
1297
+ invoke: (target, thisArg, args, additional) => {
1298
+ const hook = tracingChannel2();
1299
+ return typeof hook.invoke === "function" ? hook.invoke(target, thisArg, args, additional) : Reflect.apply(target, thisArg, args);
1300
+ },
821
1301
  tracingChannel: tracingChannel2,
822
1302
  tracePromise: (fn, context) => tracingChannel2().tracePromise(
823
1303
  fn,
@@ -831,11 +1311,21 @@ function defineChannels(pkg, channels, options) {
831
1311
  const tracingChannel = () => isomorph_default.newTracingChannel(
832
1312
  fullChannelName
833
1313
  );
1314
+ const intercept = (interceptor) => {
1315
+ const hook = tracingChannel();
1316
+ return typeof hook.intercept === "function" ? hook.intercept(interceptor) : () => {
1317
+ };
1318
+ };
834
1319
  return [
835
1320
  key,
836
1321
  {
837
1322
  ...syncSpec,
838
1323
  instrumentationName,
1324
+ intercept,
1325
+ invoke: (target, thisArg, args, additional) => {
1326
+ const hook = tracingChannel();
1327
+ return typeof hook.invoke === "function" ? hook.invoke(target, thisArg, args, additional) : Reflect.apply(target, thisArg, args);
1328
+ },
839
1329
  tracingChannel,
840
1330
  traceSync: (fn, context) => tracingChannel().traceSync(
841
1331
  fn,
@@ -855,6 +1345,9 @@ var INSTRUMENTATION_NAMES = {
855
1345
  BEDROCK_RUNTIME: "bedrock-runtime",
856
1346
  BRAINTRUST_JS_LOGGER: "braintrust-js-logger",
857
1347
  CLAUDE_AGENT_SDK: "claude-agent-sdk",
1348
+ CLOUDFLARE_AI_CHAT: "cloudflare-ai-chat",
1349
+ CLOUDFLARE_AGENTS: "cloudflare-agents",
1350
+ CLOUDFLARE_THINK: "cloudflare-think",
858
1351
  COHERE: "cohere",
859
1352
  CURSOR_SDK: "cursor-sdk",
860
1353
  EVE: "eve",
@@ -869,6 +1362,7 @@ var INSTRUMENTATION_NAMES = {
869
1362
  LANGSMITH: "langsmith",
870
1363
  MASTRA: "mastra",
871
1364
  MISTRAL: "mistral",
1365
+ OLLAMA: "ollama",
872
1366
  OPENAI: "openai",
873
1367
  OPENAI_AGENTS: "openai-agents",
874
1368
  OPENAI_CODEX: "openai-codex",
@@ -1385,6 +1879,14 @@ var anthropicChannels = defineChannels(
1385
1879
  betaMessagesToolRunner: channel({
1386
1880
  channelName: "beta.messages.toolRunner",
1387
1881
  kind: "sync-stream"
1882
+ }),
1883
+ betaSessionsEventsStream: channel({
1884
+ channelName: "beta.sessions.events.stream",
1885
+ kind: "async"
1886
+ }),
1887
+ betaSessionsThreadsEventsStream: channel({
1888
+ channelName: "beta.sessions.threads.events.stream",
1889
+ kind: "async"
1388
1890
  })
1389
1891
  },
1390
1892
  { instrumentationName: INSTRUMENTATION_NAMES.ANTHROPIC }
@@ -1503,7 +2005,40 @@ var anthropicConfigs = [
1503
2005
  methodName: "toolRunner",
1504
2006
  kind: "Sync"
1505
2007
  }
1506
- }
2008
+ },
2009
+ // Managed Agents Sessions event streams are discovered automatically, but
2010
+ // remain passive until the user calls collectAnthropicSession() on the
2011
+ // returned stream.
2012
+ ...["mjs", "js"].map(
2013
+ (extension) => ({
2014
+ channelName: anthropicChannels.betaSessionsEventsStream.channelName,
2015
+ module: {
2016
+ name: "@anthropic-ai/sdk",
2017
+ versionRange: ">=0.86.0",
2018
+ filePath: `resources/beta/sessions/events.${extension}`
2019
+ },
2020
+ functionQuery: {
2021
+ className: "Events",
2022
+ methodName: "stream",
2023
+ kind: "Async"
2024
+ }
2025
+ })
2026
+ ),
2027
+ ...["mjs", "js"].map(
2028
+ (extension) => ({
2029
+ channelName: anthropicChannels.betaSessionsThreadsEventsStream.channelName,
2030
+ module: {
2031
+ name: "@anthropic-ai/sdk",
2032
+ versionRange: ">=0.86.0",
2033
+ filePath: `resources/beta/sessions/threads/events.${extension}`
2034
+ },
2035
+ functionQuery: {
2036
+ className: "Events",
2037
+ methodName: "stream",
2038
+ kind: "Async"
2039
+ }
2040
+ })
2041
+ )
1507
2042
  ];
1508
2043
 
1509
2044
  // src/instrumentation/plugins/bedrock-runtime-channels.ts
@@ -1632,6 +2167,104 @@ var claudeAgentSDKConfigs = [
1632
2167
  }
1633
2168
  ];
1634
2169
 
2170
+ // src/instrumentation/plugins/cloudflare-ai-chat-channels.ts
2171
+ var cloudflareAIChatChannels = defineChannels(
2172
+ "@cloudflare/ai-chat",
2173
+ {
2174
+ runExclusiveChatTurn: channel({
2175
+ channelName: "AIChatAgent._runExclusiveChatTurn",
2176
+ kind: "async"
2177
+ }),
2178
+ onChatResponse: channel({
2179
+ channelName: "AIChatAgent.onChatResponse",
2180
+ kind: "sync-stream"
2181
+ })
2182
+ },
2183
+ { instrumentationName: INSTRUMENTATION_NAMES.CLOUDFLARE_AI_CHAT }
2184
+ );
2185
+
2186
+ // src/auto-instrumentations/configs/cloudflare-ai-chat.ts
2187
+ var cloudflareAIChatVersionRange = ">=0.9.0 <0.10.0";
2188
+ var cloudflareAIChatConfigs = [
2189
+ {
2190
+ // AIChatAgent subclasses replace onChatMessage, so there is no stable
2191
+ // public implementation for the transformer to target. This runner is
2192
+ // the narrowest shared boundary around every chat turn; keep the version
2193
+ // range tight because it is an internal method.
2194
+ channelName: cloudflareAIChatChannels.runExclusiveChatTurn.channelName,
2195
+ module: {
2196
+ name: "@cloudflare/ai-chat",
2197
+ versionRange: cloudflareAIChatVersionRange,
2198
+ filePath: "dist/index.js"
2199
+ },
2200
+ functionQuery: {
2201
+ className: "AIChatAgent",
2202
+ methodName: "_runExclusiveChatTurn",
2203
+ kind: "Async"
2204
+ }
2205
+ }
2206
+ ];
2207
+
2208
+ // src/instrumentation/plugins/cloudflare-agents-channels.ts
2209
+ var cloudflareAgentsChannels = defineChannels(
2210
+ "agents",
2211
+ {
2212
+ runAgentTool: channel({
2213
+ channelName: "Agent.runAgentTool",
2214
+ kind: "async"
2215
+ })
2216
+ },
2217
+ { instrumentationName: INSTRUMENTATION_NAMES.CLOUDFLARE_AGENTS }
2218
+ );
2219
+
2220
+ // src/auto-instrumentations/configs/cloudflare-agents.ts
2221
+ var cloudflareAgentsVersionRange = ">=0.17.0 <0.18.0";
2222
+ var cloudflareAgentsConfigs = [
2223
+ {
2224
+ channelName: cloudflareAgentsChannels.runAgentTool.channelName,
2225
+ module: {
2226
+ name: "agents",
2227
+ versionRange: cloudflareAgentsVersionRange,
2228
+ filePath: "dist/index.js"
2229
+ },
2230
+ functionQuery: {
2231
+ className: "Agent",
2232
+ methodName: "runAgentTool",
2233
+ kind: "Async"
2234
+ }
2235
+ }
2236
+ ];
2237
+
2238
+ // src/instrumentation/plugins/cloudflare-think-channels.ts
2239
+ var cloudflareThinkChannels = defineChannels(
2240
+ "@cloudflare/think",
2241
+ {
2242
+ runInferenceLoop: channel({
2243
+ channelName: "Think.runInferenceLoop",
2244
+ kind: "async"
2245
+ })
2246
+ },
2247
+ { instrumentationName: INSTRUMENTATION_NAMES.CLOUDFLARE_THINK }
2248
+ );
2249
+
2250
+ // src/auto-instrumentations/configs/cloudflare-think.ts
2251
+ var cloudflareThinkVersionRange = ">=0.13.0 <0.14.0";
2252
+ var cloudflareThinkConfigs = [
2253
+ {
2254
+ channelName: cloudflareThinkChannels.runInferenceLoop.channelName,
2255
+ module: {
2256
+ name: "@cloudflare/think",
2257
+ versionRange: cloudflareThinkVersionRange,
2258
+ filePath: "dist/think.js"
2259
+ },
2260
+ functionQuery: {
2261
+ className: "Think",
2262
+ methodName: "_runInferenceLoop",
2263
+ kind: "Async"
2264
+ }
2265
+ }
2266
+ ];
2267
+
1635
2268
  // src/instrumentation/plugins/cohere-channels.ts
1636
2269
  var cohereChannels = defineChannels(
1637
2270
  "cohere-ai",
@@ -2994,6 +3627,83 @@ var huggingFaceConfigs = [
2994
3627
  }
2995
3628
  ];
2996
3629
 
3630
+ // src/instrumentation/plugins/huggingface-transformers-channels.ts
3631
+ var huggingFaceTransformersChannels = defineChannels(
3632
+ "@huggingface/transformers",
3633
+ {
3634
+ pipeline: channel({
3635
+ channelName: "pipeline",
3636
+ kind: "async"
3637
+ }),
3638
+ pipelineCall: channel({
3639
+ channelName: "pipeline.call",
3640
+ kind: "async"
3641
+ })
3642
+ },
3643
+ { instrumentationName: INSTRUMENTATION_NAMES.HUGGINGFACE }
3644
+ );
3645
+
3646
+ // src/auto-instrumentations/configs/huggingface-transformers.ts
3647
+ var moduleFiles = [
3648
+ {
3649
+ filePath: "dist/transformers.mjs",
3650
+ versionRange: ">=3.0.0 <3.4.0"
3651
+ },
3652
+ {
3653
+ filePath: "dist/transformers.cjs",
3654
+ versionRange: ">=3.0.0 <3.4.0"
3655
+ },
3656
+ {
3657
+ filePath: "dist/transformers.js",
3658
+ versionRange: ">=3.0.0 <3.4.0"
3659
+ },
3660
+ {
3661
+ filePath: "dist/transformers.node.mjs",
3662
+ versionRange: ">=3.4.0 <5.0.0"
3663
+ },
3664
+ {
3665
+ filePath: "dist/transformers.node.cjs",
3666
+ versionRange: ">=3.4.0 <5.0.0"
3667
+ },
3668
+ {
3669
+ filePath: "dist/transformers.web.js",
3670
+ versionRange: ">=3.4.0 <5.0.0"
3671
+ }
3672
+ ];
3673
+ var pipelineClasses = [
3674
+ "TextGenerationPipeline",
3675
+ "Text2TextGenerationPipeline",
3676
+ "FeatureExtractionPipeline",
3677
+ "QuestionAnsweringPipeline"
3678
+ ];
3679
+ var huggingFaceTransformersConfigs = moduleFiles.flatMap(({ filePath, versionRange: versionRange2 }) => [
3680
+ {
3681
+ channelName: huggingFaceTransformersChannels.pipeline.channelName,
3682
+ module: {
3683
+ name: "@huggingface/transformers",
3684
+ versionRange: versionRange2,
3685
+ filePath
3686
+ },
3687
+ functionQuery: {
3688
+ functionName: "pipeline",
3689
+ kind: "Async"
3690
+ }
3691
+ },
3692
+ ...pipelineClasses.map((className) => ({
3693
+ channelName: huggingFaceTransformersChannels.pipelineCall.channelName,
3694
+ module: {
3695
+ name: "@huggingface/transformers",
3696
+ versionRange: versionRange2,
3697
+ filePath
3698
+ },
3699
+ functionQuery: {
3700
+ className,
3701
+ methodName: "_call",
3702
+ kind: "Async"
3703
+ }
3704
+ }))
3705
+ ]);
3706
+
2997
3707
  // src/instrumentation/plugins/langchain-channels.ts
2998
3708
  var langChainChannels = defineChannels(
2999
3709
  "@langchain/core",
@@ -3438,6 +4148,51 @@ var mistralConfigs = [
3438
4148
  }
3439
4149
  ];
3440
4150
 
4151
+ // src/instrumentation/plugins/ollama-channels.ts
4152
+ var ollamaChannels = defineChannels(
4153
+ "ollama",
4154
+ {
4155
+ chat: channel({
4156
+ channelName: "chat",
4157
+ kind: "async"
4158
+ }),
4159
+ generate: channel({
4160
+ channelName: "generate",
4161
+ kind: "async"
4162
+ }),
4163
+ embed: channel({
4164
+ channelName: "embed",
4165
+ kind: "async"
4166
+ })
4167
+ },
4168
+ { instrumentationName: INSTRUMENTATION_NAMES.OLLAMA }
4169
+ );
4170
+
4171
+ // src/auto-instrumentations/configs/ollama.ts
4172
+ var methods = [
4173
+ ["chat", ollamaChannels.chat.channelName],
4174
+ ["generate", ollamaChannels.generate.channelName],
4175
+ ["embed", ollamaChannels.embed.channelName]
4176
+ ];
4177
+ var implementationFiles = ["dist/browser.mjs", "dist/browser.cjs"];
4178
+ var ollamaConfigs = [
4179
+ ...implementationFiles.flatMap(
4180
+ (filePath) => methods.map(([methodName, channelName]) => ({
4181
+ channelName,
4182
+ module: {
4183
+ name: "ollama",
4184
+ versionRange: ">=0.6.0 <0.7.0",
4185
+ filePath
4186
+ },
4187
+ functionQuery: {
4188
+ className: "Ollama",
4189
+ methodName,
4190
+ kind: "Async"
4191
+ }
4192
+ }))
4193
+ )
4194
+ ];
4195
+
3441
4196
  // src/instrumentation/plugins/openai-agents-channels.ts
3442
4197
  var openAIAgentsCoreChannels = defineChannels(
3443
4198
  "@openai/agents-core",
@@ -3847,6 +4602,19 @@ var openRouterConfigs = [
3847
4602
  kind: "Async"
3848
4603
  }
3849
4604
  },
4605
+ {
4606
+ channelName: openRouterChannels.betaResponsesSend.channelName,
4607
+ module: {
4608
+ name: "@openrouter/sdk",
4609
+ versionRange: ">=1.1.2 <2.0.0",
4610
+ filePath: "esm/sdk/betaresponses.js"
4611
+ },
4612
+ functionQuery: {
4613
+ className: "BetaResponses",
4614
+ methodName: "send",
4615
+ kind: "Async"
4616
+ }
4617
+ },
3850
4618
  {
3851
4619
  channelName: openRouterChannels.callModel.channelName,
3852
4620
  module: {
@@ -4012,6 +4780,18 @@ var defaultInstrumentationConfigGroups = [
4012
4780
  integrations: ["claudeAgentSDK"],
4013
4781
  configs: claudeAgentSDKConfigs
4014
4782
  },
4783
+ {
4784
+ integrations: ["cloudflareAIChat"],
4785
+ configs: cloudflareAIChatConfigs
4786
+ },
4787
+ {
4788
+ integrations: ["cloudflareAgents"],
4789
+ configs: cloudflareAgentsConfigs
4790
+ },
4791
+ {
4792
+ integrations: ["cloudflareThink"],
4793
+ configs: cloudflareThinkConfigs
4794
+ },
4015
4795
  { integrations: ["cursor", "cursorSDK"], configs: cursorSDKConfigs },
4016
4796
  {
4017
4797
  integrations: ["openAIAgents"],
@@ -4021,7 +4801,10 @@ var defaultInstrumentationConfigGroups = [
4021
4801
  integrations: ["google", "googleGenAI"],
4022
4802
  configs: googleGenAIConfigs
4023
4803
  },
4024
- { integrations: ["huggingface"], configs: huggingFaceConfigs },
4804
+ {
4805
+ integrations: ["huggingface"],
4806
+ configs: [...huggingFaceConfigs, ...huggingFaceTransformersConfigs]
4807
+ },
4025
4808
  {
4026
4809
  integrations: ["langchain", "langgraph"],
4027
4810
  configs: langchainConfigs
@@ -4033,6 +4816,7 @@ var defaultInstrumentationConfigGroups = [
4033
4816
  configs: openRouterAgentConfigs
4034
4817
  },
4035
4818
  { integrations: ["mistral"], configs: mistralConfigs },
4819
+ { integrations: ["ollama"], configs: ollamaConfigs },
4036
4820
  { integrations: ["googleADK"], configs: googleADKConfigs },
4037
4821
  { integrations: ["cohere"], configs: cohereConfigs },
4038
4822
  { integrations: ["groq"], configs: groqConfigs },
@@ -4275,6 +5059,9 @@ function applySpecialCasePatch(input) {
4275
5059
  if (input.packageName === "openai" && input.modulePath.includes("api-promise")) {
4276
5060
  return input.source + OPENAI_API_PROMISE_PATCH;
4277
5061
  }
5062
+ if (input.browser) {
5063
+ return null;
5064
+ }
4278
5065
  const mastraTarget = classifyMastraTarget(
4279
5066
  input.packageName,
4280
5067
  input.modulePath
@@ -4285,6 +5072,49 @@ function applySpecialCasePatch(input) {
4285
5072
  return null;
4286
5073
  }
4287
5074
 
5075
+ // src/auto-instrumentations/loader/get-package-version.ts
5076
+ var import_node_fs = require("fs");
5077
+ var import_node_path = require("path");
5078
+ var packageNames = /* @__PURE__ */ new Map();
5079
+ function readPackageJson(baseDir) {
5080
+ try {
5081
+ const packageJsonPath = (0, import_node_path.join)(baseDir, "package.json");
5082
+ const jsonFile = (0, import_node_fs.readFileSync)(packageJsonPath, "utf8");
5083
+ return JSON.parse(jsonFile);
5084
+ } catch {
5085
+ return void 0;
5086
+ }
5087
+ }
5088
+ function resolvePackageBaseDir(baseDir) {
5089
+ try {
5090
+ return (0, import_node_fs.realpathSync)(baseDir);
5091
+ } catch {
5092
+ return baseDir;
5093
+ }
5094
+ }
5095
+ function readPackageJsonWithFallback(baseDir) {
5096
+ const packageJson = readPackageJson(baseDir);
5097
+ if (packageJson) {
5098
+ return packageJson;
5099
+ }
5100
+ const resolvedBaseDir = resolvePackageBaseDir(baseDir);
5101
+ if (resolvedBaseDir === baseDir) {
5102
+ return void 0;
5103
+ }
5104
+ return readPackageJson(resolvedBaseDir);
5105
+ }
5106
+ function getPackageName(baseDir) {
5107
+ if (packageNames.has(baseDir)) {
5108
+ return packageNames.get(baseDir);
5109
+ }
5110
+ const packageJson = readPackageJsonWithFallback(baseDir);
5111
+ if (typeof packageJson?.name === "string") {
5112
+ packageNames.set(baseDir, packageJson.name);
5113
+ return packageJson.name;
5114
+ }
5115
+ return void 0;
5116
+ }
5117
+
4288
5118
  // src/auto-instrumentations/bundler/plugin.ts
4289
5119
  function getModuleVersion(basedir) {
4290
5120
  try {
@@ -4297,86 +5127,90 @@ function getModuleVersion(basedir) {
4297
5127
  }
4298
5128
  return void 0;
4299
5129
  }
4300
- var unplugin = (0, import_unplugin.createUnplugin)(
4301
- (options = {}) => {
4302
- const allInstrumentations = getDefaultInstrumentationConfigs({
4303
- additionalInstrumentations: options.instrumentations
4304
- });
4305
- const dcModule = options.browser === false ? void 0 : "dc-browser";
4306
- const instrumentationMatcher = create(allInstrumentations, dcModule);
4307
- return {
4308
- name: "code-transformer",
4309
- enforce: "pre",
4310
- transform(code, id) {
4311
- if (!id) {
4312
- return null;
4313
- }
4314
- const filePath = id.startsWith("file:") ? (0, import_url.fileURLToPath)(id) : id;
4315
- const ext = (0, import_path.extname)(filePath);
4316
- let isModule = ext === ".mjs" || ext === ".ts" || ext === ".tsx";
4317
- if (ext === ".js") {
4318
- isModule = code.includes("export ") || code.includes("import ");
4319
- }
4320
- const normalizedForPlatform = filePath.split("/").join(import_path.sep);
4321
- const moduleDetails = (0, import_module_details_from_path.default)(normalizedForPlatform);
4322
- if (!moduleDetails) {
4323
- return null;
4324
- }
4325
- const moduleName = moduleDetails.name;
4326
- const normalizedModulePath = moduleDetails.path.replace(/\\/g, "/");
4327
- const moduleVersion = getModuleVersion(moduleDetails.basedir);
4328
- if (options.browser !== true) {
4329
- const patched = applySpecialCasePatch({
4330
- packageName: moduleName,
4331
- modulePath: normalizedModulePath,
4332
- source: code,
4333
- format: isModule ? "esm" : "cjs"
4334
- });
4335
- if (patched !== null) {
4336
- return { code: patched, map: null };
4337
- }
4338
- }
4339
- if (!moduleVersion) {
4340
- console.warn(
4341
- `No 'package.json' version found for module ${moduleName} at ${moduleDetails.basedir}. Skipping transformation.`
4342
- );
4343
- return null;
4344
- }
4345
- const transformer = instrumentationMatcher.getTransformer(
4346
- moduleName,
4347
- moduleVersion,
4348
- normalizedModulePath
4349
- );
4350
- if (!transformer) {
4351
- return null;
4352
- }
5130
+ var unplugin = (0, import_unplugin.createUnplugin)((options = {}) => {
5131
+ const browser = options.browser ?? options.useDiagnosticChannelCompatShim ?? false;
5132
+ const allInstrumentations = getDefaultInstrumentationConfigs({
5133
+ additionalInstrumentations: options.instrumentations
5134
+ });
5135
+ const instrumentationMatcher = create(allInstrumentations);
5136
+ return {
5137
+ name: "code-transformer",
5138
+ enforce: "pre",
5139
+ transformInclude(id) {
5140
+ const pathWithoutQuery = id.split("?", 1)[0];
5141
+ if (!pathWithoutQuery) {
5142
+ return false;
5143
+ }
5144
+ if (pathWithoutQuery.startsWith("file:")) {
4353
5145
  try {
4354
- const moduleType = isModule ? "esm" : "cjs";
4355
- const result = transformer.transform(code, moduleType);
4356
- const transformedCode = result.code.replace(
4357
- /const \{tracingChannel: ([A-Za-z_$][\w$]*)\} = ([A-Za-z_$][\w$]*);/g,
4358
- "const $1 = $2.tracingChannel;"
4359
- );
4360
- return {
4361
- code: transformedCode,
4362
- map: result.map
4363
- };
4364
- } catch (error) {
4365
- console.warn(`Code transformation failed for ${id}: ${error}`);
4366
- return null;
5146
+ return (0, import_path.isAbsolute)((0, import_url.fileURLToPath)(pathWithoutQuery));
5147
+ } catch {
5148
+ return false;
4367
5149
  }
4368
5150
  }
4369
- };
4370
- }
4371
- );
5151
+ return (0, import_path.isAbsolute)(pathWithoutQuery);
5152
+ },
5153
+ transform(code, id) {
5154
+ if (!id) {
5155
+ return null;
5156
+ }
5157
+ const cleanId = id.replace(/[?#].*$/, "");
5158
+ const filePath = cleanId.startsWith("file:") ? (0, import_url.fileURLToPath)(cleanId) : cleanId;
5159
+ const ext = (0, import_path.extname)(filePath);
5160
+ let isModule = ext === ".mjs" || ext === ".ts" || ext === ".tsx";
5161
+ if (ext === ".js") {
5162
+ isModule = code.includes("export ") || code.includes("import ");
5163
+ }
5164
+ const normalizedForPlatform = filePath.split("/").join(import_path.sep);
5165
+ const moduleDetails = (0, import_module_details_from_path.default)(normalizedForPlatform);
5166
+ if (!moduleDetails) {
5167
+ return null;
5168
+ }
5169
+ const moduleName = getPackageName(moduleDetails.basedir) ?? moduleDetails.name;
5170
+ const normalizedModulePath = moduleDetails.path.replace(/\\/g, "/");
5171
+ const moduleVersion = getModuleVersion(moduleDetails.basedir);
5172
+ const patched = applySpecialCasePatch({
5173
+ packageName: moduleName,
5174
+ modulePath: normalizedModulePath,
5175
+ source: code,
5176
+ format: isModule ? "esm" : "cjs",
5177
+ browser
5178
+ });
5179
+ if (patched !== null) {
5180
+ return { code: patched, map: null };
5181
+ }
5182
+ if (!moduleVersion) {
5183
+ console.warn(
5184
+ `No 'package.json' version found for module ${moduleName} at ${moduleDetails.basedir}. Skipping transformation.`
5185
+ );
5186
+ return null;
5187
+ }
5188
+ const transformer = instrumentationMatcher.getTransformer(
5189
+ moduleName,
5190
+ moduleVersion,
5191
+ normalizedModulePath
5192
+ );
5193
+ if (!transformer) {
5194
+ return null;
5195
+ }
5196
+ try {
5197
+ const moduleType = isModule ? "esm" : "cjs";
5198
+ const result = transformer.transform(code, moduleType);
5199
+ return {
5200
+ code: result.code,
5201
+ map: result.map
5202
+ };
5203
+ } catch (error) {
5204
+ console.warn(`Code transformation failed for ${id}: ${error}`);
5205
+ return null;
5206
+ }
5207
+ }
5208
+ };
5209
+ });
4372
5210
 
4373
5211
  // src/auto-instrumentations/bundler/esbuild.ts
4374
5212
  function braintrustEsbuildPlugin(options = {}) {
4375
- const { useDiagnosticChannelCompatShim = false, ...pluginOptions } = options;
4376
- return unplugin.esbuild({
4377
- ...pluginOptions,
4378
- browser: useDiagnosticChannelCompatShim
4379
- });
5213
+ return unplugin.esbuild(options);
4380
5214
  }
4381
5215
  var esbuildPlugin = unplugin.esbuild;
4382
5216
  // Annotate the CommonJS export names for ESM import in node: