braintrust 3.20.0 → 3.21.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 (88) hide show
  1. package/NOTICE +20 -0
  2. package/README.md +2 -0
  3. package/dev/dist/index.d.mts +309 -199
  4. package/dev/dist/index.d.ts +309 -199
  5. package/dev/dist/index.js +2826 -983
  6. package/dev/dist/index.mjs +2286 -443
  7. package/dist/apply-auto-instrumentation.js +781 -199
  8. package/dist/apply-auto-instrumentation.mjs +588 -6
  9. package/dist/auto-instrumentations/bundler/esbuild.cjs +594 -2
  10. package/dist/auto-instrumentations/bundler/esbuild.d.mts +2 -2
  11. package/dist/auto-instrumentations/bundler/esbuild.d.ts +2 -2
  12. package/dist/auto-instrumentations/bundler/esbuild.mjs +3 -3
  13. package/dist/auto-instrumentations/bundler/next.cjs +594 -2
  14. package/dist/auto-instrumentations/bundler/next.mjs +4 -4
  15. package/dist/auto-instrumentations/bundler/rollup.cjs +594 -2
  16. package/dist/auto-instrumentations/bundler/rollup.d.mts +2 -2
  17. package/dist/auto-instrumentations/bundler/rollup.d.ts +2 -2
  18. package/dist/auto-instrumentations/bundler/rollup.mjs +3 -3
  19. package/dist/auto-instrumentations/bundler/vite.cjs +594 -2
  20. package/dist/auto-instrumentations/bundler/vite.d.mts +2 -2
  21. package/dist/auto-instrumentations/bundler/vite.d.ts +2 -2
  22. package/dist/auto-instrumentations/bundler/vite.mjs +3 -3
  23. package/dist/auto-instrumentations/bundler/webpack-loader.cjs +593 -9
  24. package/dist/auto-instrumentations/bundler/webpack-loader.d.ts +68 -1
  25. package/dist/auto-instrumentations/bundler/webpack.cjs +594 -2
  26. package/dist/auto-instrumentations/bundler/webpack.d.mts +2 -2
  27. package/dist/auto-instrumentations/bundler/webpack.d.ts +2 -2
  28. package/dist/auto-instrumentations/bundler/webpack.mjs +4 -4
  29. package/dist/auto-instrumentations/{chunk-W4E36GIW.mjs → chunk-BRQX23KL.mjs} +16 -0
  30. package/dist/auto-instrumentations/chunk-M6DLIJ2Z.mjs +784 -0
  31. package/dist/auto-instrumentations/{chunk-K74TZGGM.mjs → chunk-T6J4C7LX.mjs} +1 -1
  32. package/dist/auto-instrumentations/{chunk-S4374IP6.mjs → chunk-TKRPRPGD.mjs} +4 -6
  33. package/dist/auto-instrumentations/chunk-VT6DDNKM.mjs +856 -0
  34. package/dist/auto-instrumentations/hook.mjs +749 -45
  35. package/dist/auto-instrumentations/index.cjs +16 -0
  36. package/dist/auto-instrumentations/index.d.mts +2 -3
  37. package/dist/auto-instrumentations/index.d.ts +2 -3
  38. package/dist/auto-instrumentations/index.mjs +1 -1
  39. package/dist/auto-instrumentations/loader/cjs-patch.cjs +578 -4
  40. package/dist/auto-instrumentations/loader/cjs-patch.d.mts +1 -1
  41. package/dist/auto-instrumentations/loader/cjs-patch.d.ts +1 -1
  42. package/dist/auto-instrumentations/loader/cjs-patch.mjs +3 -7
  43. package/dist/auto-instrumentations/loader/esm-hook.mjs +2 -6
  44. package/dist/auto-instrumentations/{plugin-D7nDswtC.d.mts → plugin-D0KHwSJv.d.mts} +1 -1
  45. package/dist/auto-instrumentations/{plugin-D7nDswtC.d.ts → plugin-G6fgxk1b.d.ts} +1 -1
  46. package/dist/auto-instrumentations/types-RNPaKi9o.d.mts +70 -0
  47. package/dist/auto-instrumentations/types-RNPaKi9o.d.ts +70 -0
  48. package/dist/browser.d.mts +1357 -847
  49. package/dist/browser.d.ts +1357 -847
  50. package/dist/browser.js +2726 -469
  51. package/dist/browser.mjs +2726 -469
  52. package/dist/{chunk-LPC4W2WX.js → chunk-BFGIH2ZJ.js} +4 -0
  53. package/dist/{chunk-POCCIJAL.js → chunk-FY7DAKA5.js} +3141 -1269
  54. package/dist/{chunk-Y7W7WP6H.mjs → chunk-KMGUTPB7.mjs} +4 -0
  55. package/dist/{chunk-F73OMF66.mjs → chunk-O2P765XK.mjs} +2391 -519
  56. package/dist/cli.js +2260 -408
  57. package/dist/edge-light.d.mts +1 -1
  58. package/dist/edge-light.d.ts +1 -1
  59. package/dist/edge-light.js +2726 -469
  60. package/dist/edge-light.mjs +2726 -469
  61. package/dist/index.d.mts +1837 -1327
  62. package/dist/index.d.ts +1837 -1327
  63. package/dist/index.js +752 -353
  64. package/dist/index.mjs +445 -46
  65. package/dist/instrumentation/index.d.mts +107 -19
  66. package/dist/instrumentation/index.d.ts +107 -19
  67. package/dist/instrumentation/index.js +2337 -509
  68. package/dist/instrumentation/index.mjs +2337 -509
  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 +2726 -469
  74. package/dist/workerd.mjs +2726 -469
  75. package/licenses/import-in-the-middle/LICENSE +201 -0
  76. package/licenses/import-in-the-middle/LICENSE-3rdparty.csv +4 -0
  77. package/licenses/import-in-the-middle/NOTICE +34 -0
  78. package/licenses/orchestrion-js/LICENSE +202 -0
  79. package/licenses/orchestrion-js/LICENSE-3rdparty.csv +8 -0
  80. package/licenses/orchestrion-js/NOTICE +3 -0
  81. package/licenses/require-in-the-middle/LICENSE +23 -0
  82. package/package.json +13 -4
  83. package/util/dist/index.d.mts +1 -0
  84. package/util/dist/index.d.ts +1 -0
  85. package/util/dist/index.js +4 -4
  86. package/util/dist/index.mjs +2 -2
  87. package/dist/auto-instrumentations/chunk-J57YF7WS.mjs +0 -208
  88. package/dist/auto-instrumentations/chunk-QFMACSOL.mjs +0 -280
@@ -712,6 +712,10 @@ var aiSDKChannels = defineChannels("ai", {
712
712
  channelName: "ToolLoopAgent.stream",
713
713
  kind: "async"
714
714
  }),
715
+ workflowAgentStream: channel({
716
+ channelName: "WorkflowAgent.stream",
717
+ kind: "async"
718
+ }),
715
719
  v7CreateTelemetryDispatcher: channel({
716
720
  channelName: "createTelemetryDispatcher",
717
721
  kind: "sync-stream"
@@ -910,6 +914,18 @@ var aiSDKConfigs = [
910
914
  kind: "Sync"
911
915
  }
912
916
  },
917
+ {
918
+ channelName: aiSDKChannels.v7CreateTelemetryDispatcher.channelName,
919
+ module: {
920
+ name: "ai",
921
+ versionRange: ">=7.0.0-0 <8.0.0",
922
+ filePath: "dist/internal/index.js"
923
+ },
924
+ functionQuery: {
925
+ functionName: "createTelemetryDispatcher",
926
+ kind: "Sync"
927
+ }
928
+ },
913
929
  // streamObject - async function (v3 only, before the sync refactor in v4)
914
930
  {
915
931
  channelName: aiSDKChannels.streamObject.channelName,
@@ -1,5 +1,4 @@
1
- import { InstrumentationConfig } from '@apm-js-collab/code-transformer';
2
- export { InstrumentationConfig } from '@apm-js-collab/code-transformer';
1
+ import { I as InstrumentationConfig } from './types-RNPaKi9o.mjs';
3
2
 
4
3
  /**
5
4
  * Instrumentation configurations for the OpenAI SDK.
@@ -114,4 +113,4 @@ declare const langchainConfigs: InstrumentationConfig[];
114
113
 
115
114
  declare const piCodingAgentConfigs: InstrumentationConfig[];
116
115
 
117
- export { aiSDKConfigs, anthropicConfigs, bedrockRuntimeConfigs, claudeAgentSDKConfigs, cohereConfigs, cursorSDKConfigs, genkitConfigs, gitHubCopilotConfigs, googleADKConfigs, googleGenAIConfigs, groqConfigs, huggingFaceConfigs, langchainConfigs, mistralConfigs, openAIAgentsCoreConfigs, openAICodexConfigs, openRouterAgentConfigs, openRouterConfigs, openaiConfigs, piCodingAgentConfigs };
116
+ export { InstrumentationConfig, aiSDKConfigs, anthropicConfigs, bedrockRuntimeConfigs, claudeAgentSDKConfigs, cohereConfigs, cursorSDKConfigs, genkitConfigs, gitHubCopilotConfigs, googleADKConfigs, googleGenAIConfigs, groqConfigs, huggingFaceConfigs, langchainConfigs, mistralConfigs, openAIAgentsCoreConfigs, openAICodexConfigs, openRouterAgentConfigs, openRouterConfigs, openaiConfigs, piCodingAgentConfigs };
@@ -1,5 +1,4 @@
1
- import { InstrumentationConfig } from '@apm-js-collab/code-transformer';
2
- export { InstrumentationConfig } from '@apm-js-collab/code-transformer';
1
+ import { I as InstrumentationConfig } from './types-RNPaKi9o.js';
3
2
 
4
3
  /**
5
4
  * Instrumentation configurations for the OpenAI SDK.
@@ -114,4 +113,4 @@ declare const langchainConfigs: InstrumentationConfig[];
114
113
 
115
114
  declare const piCodingAgentConfigs: InstrumentationConfig[];
116
115
 
117
- export { aiSDKConfigs, anthropicConfigs, bedrockRuntimeConfigs, claudeAgentSDKConfigs, cohereConfigs, cursorSDKConfigs, genkitConfigs, gitHubCopilotConfigs, googleADKConfigs, googleGenAIConfigs, groqConfigs, huggingFaceConfigs, langchainConfigs, mistralConfigs, openAIAgentsCoreConfigs, openAICodexConfigs, openRouterAgentConfigs, openRouterConfigs, openaiConfigs, piCodingAgentConfigs };
116
+ export { InstrumentationConfig, aiSDKConfigs, anthropicConfigs, bedrockRuntimeConfigs, claudeAgentSDKConfigs, cohereConfigs, cursorSDKConfigs, genkitConfigs, gitHubCopilotConfigs, googleADKConfigs, googleGenAIConfigs, groqConfigs, huggingFaceConfigs, langchainConfigs, mistralConfigs, openAIAgentsCoreConfigs, openAICodexConfigs, openRouterAgentConfigs, openRouterConfigs, openaiConfigs, piCodingAgentConfigs };
@@ -19,7 +19,7 @@ import {
19
19
  openRouterConfigs,
20
20
  openaiConfigs,
21
21
  piCodingAgentConfigs
22
- } from "./chunk-W4E36GIW.mjs";
22
+ } from "./chunk-BRQX23KL.mjs";
23
23
  export {
24
24
  aiSDKConfigs,
25
25
  anthropicConfigs,
@@ -33,7 +33,583 @@ __export(cjs_patch_exports, {
33
33
  ModulePatch: () => ModulePatch
34
34
  });
35
35
  module.exports = __toCommonJS(cjs_patch_exports);
36
- var import_code_transformer = require("@apm-js-collab/code-transformer");
36
+
37
+ // src/auto-instrumentations/orchestrion-js/matcher.ts
38
+ var import_semifies = __toESM(require("semifies"));
39
+
40
+ // src/auto-instrumentations/orchestrion-js/transformer.ts
41
+ var import_esquery2 = __toESM(require("esquery"));
42
+ var import_astring = require("astring");
43
+ var import_meriyah2 = require("meriyah");
44
+ var import_source_map = require("source-map");
45
+
46
+ // src/auto-instrumentations/orchestrion-js/transforms.ts
47
+ var import_esquery = __toESM(require("esquery"));
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, "_")}`;
53
+ }
54
+ var transforms = {
55
+ tracingChannelImport({ dcModule, moduleType }, node) {
56
+ if (node.body.some(tracingChannelPredicate)) {
57
+ return;
58
+ }
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]
76
+ );
77
+ },
78
+ tracingChannelDeclaration(state, node) {
79
+ const {
80
+ channelName,
81
+ module: { name }
82
+ } = state;
83
+ const channelVariable = formatChannelVariable(channelName);
84
+ if (node.body.some(
85
+ (child) => child.declarations?.[0]?.id?.name === channelVariable
86
+ )) {
87
+ return;
88
+ }
89
+ transforms.tracingChannelImport(state, node, null, []);
90
+ const index = node.body.findIndex(tracingChannelPredicate);
91
+ const code = `
92
+ const ${channelVariable} = tr_ch_apm_tracingChannel("orchestrion:${name}:${channelName}")
93
+ `;
94
+ node.body.splice(index + 1, 0, (0, import_meriyah.parse)(code).body[0]);
95
+ },
96
+ traceCallback: traceAny,
97
+ tracePromise: traceAny,
98
+ traceSync: traceAny
99
+ };
100
+ function traceAny(state, node, _parent, ancestry) {
101
+ const program = ancestry[ancestry.length - 1];
102
+ if (node.type === "ClassDeclaration" || node.type === "ClassExpression") {
103
+ traceInstanceMethod(state, node, program);
104
+ } else {
105
+ traceFunction(state, node, program);
106
+ }
107
+ }
108
+ function traceFunction(state, node, program) {
109
+ transforms.tracingChannelDeclaration(state, program, null, []);
110
+ const { functionQuery } = state;
111
+ const methodName = "methodName" in functionQuery ? functionQuery.methodName : void 0;
112
+ const privateMethodName = "privateMethodName" in functionQuery ? functionQuery.privateMethodName : void 0;
113
+ const functionName = "functionName" in functionQuery ? functionQuery.functionName : void 0;
114
+ const isConstructor = methodName === "constructor" || !methodName && !privateMethodName && !functionName;
115
+ 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
+ );
128
+ node.generator = false;
129
+ node.async = false;
130
+ wrapSuper(node);
131
+ }
132
+ function traceInstanceMethod(state, node, program) {
133
+ const { functionQuery, operator } = state;
134
+ const { methodName } = functionQuery;
135
+ if (!methodName) {
136
+ return;
137
+ }
138
+ const classBody = node.body;
139
+ if (classBody.body.some(({ key }) => key.name === methodName)) {
140
+ return;
141
+ }
142
+ let ctor = classBody.body.find(({ kind }) => kind === "constructor");
143
+ transforms.tracingChannelDeclaration(state, program, null, []);
144
+ if (!ctor) {
145
+ ctor = (0, import_meriyah.parse)(
146
+ node.superClass ? "class A extends Object { constructor (...args) { super(...args) } }" : "class A { constructor () {} }"
147
+ ).body[0].body.body[0];
148
+ classBody.body.unshift(ctor);
149
+ }
150
+ const ctorBody = (0, import_meriyah.parse)(`
151
+ const __apm$${methodName} = this["${methodName}"]
152
+ this["${methodName}"] = function () {}
153
+ `).body;
154
+ const fn = ctorBody[1].expression.right;
155
+ fn.async = operator === "tracePromise";
156
+ fn.body = wrap(
157
+ state,
158
+ { type: "Identifier", name: `__apm$${methodName}` },
159
+ program
160
+ );
161
+ wrapSuper(fn);
162
+ ctor.value.body.body.push(...ctorBody);
163
+ }
164
+ function wrap(state, node, program) {
165
+ const { operator, moduleVersion } = state;
166
+ const wrapper = operator === "traceCallback" ? wrapCallback(state) : operator === "tracePromise" ? wrapPromise(state) : wrapSync(state);
167
+ const block = wrapper.body[0].body;
168
+ const common = (0, import_meriyah.parse)(
169
+ node.type === "ArrowFunctionExpression" ? `
170
+ const __apm$ctx = {
171
+ arguments,
172
+ moduleVersion: ${JSON.stringify(moduleVersion)}
173
+ };
174
+ const __apm$traced = () => {
175
+ const __apm$wrapped = () => {};
176
+ return __apm$wrapped(...arguments);
177
+ };
178
+ ` : `
179
+ const __apm$ctx = {
180
+ arguments,
181
+ self: this,
182
+ moduleVersion: ${JSON.stringify(moduleVersion)}
183
+ };
184
+ const __apm$traced = () => {
185
+ const __apm$wrapped = () => {};
186
+ return __apm$wrapped.apply(this, arguments);
187
+ };
188
+ `
189
+ ).body;
190
+ block.body.unshift(...common);
191
+ import_esquery.default.query(block, "[id.name=__apm$wrapped]")[0].init = node;
192
+ return block;
193
+ }
194
+ function wrapSuper(node) {
195
+ const members = /* @__PURE__ */ new Set();
196
+ import_esquery.default.traverse(
197
+ node.body,
198
+ import_esquery.default.parse("[object.type=Super]"),
199
+ (node2, parent) => {
200
+ const { name } = node2.property;
201
+ let child;
202
+ if (parent.callee) {
203
+ const { expression } = (0, import_meriyah.parse)(`__apm$super['${name}'].call(this)`).body[0];
204
+ parent.callee = child = expression.callee;
205
+ parent.arguments.unshift(...expression.arguments);
206
+ } else {
207
+ parent.expression = child = (0, import_meriyah.parse)(`__apm$super['${name}']`).body[0];
208
+ }
209
+ child.computed = parent.callee.computed;
210
+ child.optional = parent.callee.optional;
211
+ members.add(name);
212
+ }
213
+ );
214
+ for (const name of members) {
215
+ const member = (0, import_meriyah.parse)(`
216
+ class Wrapper {
217
+ wrapper () {
218
+ __apm$super['${name}'] = super['${name}']
219
+ }
220
+ }
221
+ `).body[0].body.body[0].value.body.body[0];
222
+ node.body.body.unshift(member);
223
+ }
224
+ if (members.size > 0) {
225
+ node.body.body.unshift((0, import_meriyah.parse)("const __apm$super = {}").body[0]);
226
+ }
227
+ }
228
+ function wrapCallback(state) {
229
+ const {
230
+ channelName,
231
+ functionQuery: { callbackIndex = -1 }
232
+ } = state;
233
+ const channelVariable = formatChannelVariable(channelName);
234
+ return (0, import_meriyah.parse)(`
235
+ 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
+ });
276
+ }
277
+ `);
278
+ }
279
+ function wrapPromise(state) {
280
+ const { channelName } = state;
281
+ const channelVariable = formatChannelVariable(channelName);
282
+ return (0, import_meriyah.parse)(`
283
+ 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
+ });
339
+ }
340
+ `);
341
+ }
342
+ function wrapSync(state) {
343
+ const { channelName } = state;
344
+ const channelVariable = formatChannelVariable(channelName);
345
+ return (0, import_meriyah.parse)(`
346
+ 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
+ });
363
+ }
364
+ `);
365
+ }
366
+
367
+ // src/auto-instrumentations/orchestrion-js/transformer.ts
368
+ var Transformer = class {
369
+ moduleName;
370
+ version;
371
+ filePath;
372
+ configs = [];
373
+ dcModule;
374
+ constructor(moduleName, version, filePath, configs, dcModule) {
375
+ this.moduleName = moduleName;
376
+ this.version = version;
377
+ this.filePath = filePath;
378
+ this.configs = configs;
379
+ this.dcModule = dcModule;
380
+ }
381
+ /**
382
+ * Instruments `code` by injecting diagnostics_channel tracing around the
383
+ * target functions defined by this transformer's configs.
384
+ */
385
+ transform(code, moduleType) {
386
+ if (Buffer.isBuffer(code)) {
387
+ code = code.toString();
388
+ }
389
+ if (!code) {
390
+ return { code };
391
+ }
392
+ let ast;
393
+ let aliases = {};
394
+ let injectionCount = 0;
395
+ for (const config of this.configs) {
396
+ const { astQuery, functionQuery } = config;
397
+ if (!ast) {
398
+ const options = {
399
+ loc: true,
400
+ ranges: true,
401
+ raw: true,
402
+ module: moduleType === "esm"
403
+ };
404
+ try {
405
+ ast = (0, import_meriyah2.parse)(code, options);
406
+ } catch {
407
+ ast = (0, import_meriyah2.parse)(code, { ...options, module: !options.module });
408
+ }
409
+ if (moduleType === "esm") {
410
+ aliases = this.collectExportAliases(ast);
411
+ }
412
+ }
413
+ const resolvedFunctionQuery = this.resolveExportAlias(
414
+ functionQuery,
415
+ aliases
416
+ );
417
+ const query = astQuery || this.fromFunctionQuery(resolvedFunctionQuery);
418
+ const state = {
419
+ ...config,
420
+ dcModule: this.dcModule,
421
+ moduleType,
422
+ moduleVersion: this.version,
423
+ functionQuery: resolvedFunctionQuery,
424
+ operator: this.getOperator(resolvedFunctionQuery.kind)
425
+ };
426
+ import_esquery2.default.traverse(ast, import_esquery2.default.parse(query), (...args) => {
427
+ injectionCount++;
428
+ this.visit(state, ...args);
429
+ });
430
+ }
431
+ if (injectionCount === 0 && this.configs.length > 0) {
432
+ const names = this.configs.map(({ astQuery, functionQuery }) => {
433
+ const resolvedQuery = this.resolveExportAlias(functionQuery, aliases);
434
+ const queryName = (q) => q.methodName || q.privateMethodName || q.functionName || q.propertyName || astQuery || "unknown";
435
+ const originalName = queryName(functionQuery);
436
+ const originalAlias = functionQuery.className || functionQuery.functionName;
437
+ const resolvedAlias = resolvedQuery.className || resolvedQuery.functionName;
438
+ if (originalAlias && originalAlias !== resolvedAlias) {
439
+ return `${originalAlias} (local name: ${resolvedAlias})`;
440
+ }
441
+ return originalName;
442
+ });
443
+ throw new Error(
444
+ `Failed to find injection points for: ${JSON.stringify(names)}`
445
+ );
446
+ }
447
+ if (ast) {
448
+ const file = `${this.moduleName}/${this.filePath}`;
449
+ const sourceMap = new import_source_map.SourceMapGenerator({ file });
450
+ const transformedCode = (0, import_astring.generate)(ast, { sourceMap });
451
+ const map = sourceMap.toString();
452
+ return { code: transformedCode, map };
453
+ }
454
+ return { code };
455
+ }
456
+ free() {
457
+ }
458
+ visit(state, ...args) {
459
+ const transform = transforms[state.operator];
460
+ const { index = 0 } = state.functionQuery;
461
+ const [node] = args;
462
+ const type = node.init?.type || node.type;
463
+ if (type !== "ClassDeclaration" && type !== "ClassExpression") {
464
+ if (node.type === "VariableDeclarator") {
465
+ return;
466
+ }
467
+ state.functionIndex = state.functionIndex === void 0 ? 0 : state.functionIndex + 1;
468
+ if (index !== null && index !== state.functionIndex) {
469
+ return;
470
+ }
471
+ }
472
+ transform(state, ...args);
473
+ }
474
+ getOperator(kind) {
475
+ switch (kind) {
476
+ case "Async":
477
+ return "tracePromise";
478
+ case "Callback":
479
+ return "traceCallback";
480
+ case "Sync":
481
+ return "traceSync";
482
+ }
483
+ }
484
+ collectExportAliases(ast) {
485
+ const aliases = {};
486
+ for (const node of ast.body) {
487
+ if (node.type === "ExportNamedDeclaration" && !node.source) {
488
+ for (const spec of node.specifiers) {
489
+ if (spec.exported && spec.local) {
490
+ const exportedName = spec.exported.name ?? spec.exported.value;
491
+ const localName = spec.local.name ?? spec.local.value;
492
+ if (exportedName && localName) {
493
+ aliases[exportedName] = localName;
494
+ }
495
+ }
496
+ }
497
+ }
498
+ }
499
+ return aliases;
500
+ }
501
+ resolveExportAlias(functionQuery, aliases) {
502
+ if (!("isExportAlias" in functionQuery) || !functionQuery.isExportAlias) {
503
+ return functionQuery;
504
+ }
505
+ if ("className" in functionQuery && aliases[functionQuery.className]) {
506
+ return {
507
+ ...functionQuery,
508
+ className: aliases[functionQuery.className]
509
+ };
510
+ }
511
+ if ("functionName" in functionQuery && aliases[functionQuery.functionName]) {
512
+ return {
513
+ ...functionQuery,
514
+ functionName: aliases[functionQuery.functionName]
515
+ };
516
+ }
517
+ return functionQuery;
518
+ }
519
+ functionQueryLabel(functionQuery) {
520
+ if ("methodName" in functionQuery) {
521
+ return functionQuery.methodName;
522
+ }
523
+ if ("privateMethodName" in functionQuery) {
524
+ return functionQuery.privateMethodName;
525
+ }
526
+ if ("functionName" in functionQuery) {
527
+ return functionQuery.functionName;
528
+ }
529
+ if ("propertyName" in functionQuery) {
530
+ return functionQuery.propertyName;
531
+ }
532
+ return "unknown";
533
+ }
534
+ fromFunctionQuery(functionQuery) {
535
+ const queries = [];
536
+ if ("className" in functionQuery) {
537
+ const { className } = functionQuery;
538
+ const methodName = this.functionQueryLabel(functionQuery);
539
+ const keyType = "privateMethodName" in functionQuery ? "PrivateIdentifier" : "Identifier";
540
+ queries.push(
541
+ `[id.name="${className}"]`,
542
+ `[id.name="${className}"] > ClassExpression`,
543
+ `[id.name="${className}"] > ClassBody > [key.name="${methodName}"][key.type=${keyType}] > [async]`,
544
+ `[id.name="${className}"] > ClassExpression > ClassBody > [key.name="${methodName}"][key.type=${keyType}] > [async]`
545
+ );
546
+ } else if ("methodName" in functionQuery) {
547
+ const { methodName } = functionQuery;
548
+ queries.push(
549
+ `ClassBody > [key.name="${methodName}"][key.type=Identifier] > [async]`,
550
+ `Property[key.name="${methodName}"][key.type=Identifier] > [async]`
551
+ );
552
+ }
553
+ if ("functionName" in functionQuery) {
554
+ const { functionName } = functionQuery;
555
+ queries.push(`FunctionDeclaration[id.name="${functionName}"][async]`);
556
+ }
557
+ if ("objectName" in functionQuery) {
558
+ const { objectName, propertyName } = functionQuery;
559
+ const objectSelector = objectName === "this" ? "left.object.type=ThisExpression" : `left.object.name="${objectName}"`;
560
+ queries.push(
561
+ `AssignmentExpression[${objectSelector}][left.property.name="${propertyName}"] > [async]`
562
+ );
563
+ }
564
+ return queries.join(", ");
565
+ }
566
+ };
567
+
568
+ // src/auto-instrumentations/orchestrion-js/matcher.ts
569
+ var InstrumentationMatcher = class {
570
+ configs = [];
571
+ dcModule;
572
+ transformers = {};
573
+ constructor(configs, dcModule) {
574
+ this.configs = configs;
575
+ this.dcModule = dcModule || "diagnostics_channel";
576
+ }
577
+ /**
578
+ * Returns a Transformer for the given module/file/version, or undefined if no
579
+ * registered config matches.
580
+ */
581
+ getTransformer(moduleName, version, filePath) {
582
+ filePath = filePath.replace(/\\/g, "/");
583
+ const id = `${moduleName}/${filePath}@${version}`;
584
+ if (this.transformers[id]) {
585
+ return this.transformers[id];
586
+ }
587
+ const configs = this.configs.filter(
588
+ ({ module: mod }) => mod.name === moduleName && mod.filePath === filePath && (0, import_semifies.default)(version, mod.versionRange)
589
+ );
590
+ if (configs.length === 0) {
591
+ return void 0;
592
+ }
593
+ this.transformers[id] = new Transformer(
594
+ moduleName,
595
+ version,
596
+ filePath,
597
+ configs,
598
+ this.dcModule
599
+ );
600
+ return this.transformers[id];
601
+ }
602
+ free() {
603
+ this.transformers = {};
604
+ }
605
+ };
606
+
607
+ // src/auto-instrumentations/orchestrion-js/index.ts
608
+ function create(configs, dcModule) {
609
+ return new InstrumentationMatcher(configs, dcModule);
610
+ }
611
+
612
+ // src/auto-instrumentations/loader/cjs-patch.ts
37
613
  var NodeModule = __toESM(require("module"));
38
614
  var import_node_path2 = require("path");
39
615
  var import_module_details_from_path = __toESM(require("module-details-from-path"));
@@ -309,7 +885,7 @@ var ModulePatch = class {
309
885
  } = {}) {
310
886
  const modulePrototype = resolveModulePrototype();
311
887
  this.packages = new Set(instrumentations.map((i) => i.module.name));
312
- this.instrumentator = (0, import_code_transformer.create)(instrumentations);
888
+ this.instrumentator = create(instrumentations);
313
889
  this.modulePrototype = modulePrototype;
314
890
  this.originalCompile = modulePrototype._compile;
315
891
  }
@@ -352,8 +928,6 @@ var ModulePatch = class {
352
928
  args[0] = transformedCode?.code;
353
929
  } catch (error) {
354
930
  console.warn(`Error transforming module ${filename}:`, error);
355
- } finally {
356
- transformer.free();
357
931
  }
358
932
  }
359
933
  }
@@ -1,4 +1,4 @@
1
- import { InstrumentationConfig } from '@apm-js-collab/code-transformer';
1
+ import { I as InstrumentationConfig } from '../types-RNPaKi9o.mjs';
2
2
 
3
3
  /**
4
4
  * CJS module patcher for auto-instrumentation.
@@ -1,4 +1,4 @@
1
- import { InstrumentationConfig } from '@apm-js-collab/code-transformer';
1
+ import { I as InstrumentationConfig } from '../types-RNPaKi9o.js';
2
2
 
3
3
  /**
4
4
  * CJS module patcher for auto-instrumentation.