@jennifersoft/jennifer5-instrumentation 5.6.5-1

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.
package/dist/index.js ADDED
@@ -0,0 +1,3547 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ TransactionContextManager: () => TransactionContextManager,
24
+ contextManager: () => contextManager,
25
+ registerIitmHooks: () => registerIitmHooks,
26
+ registerRitmHooks: () => registerRitmHooks,
27
+ startGcMetricsCollection: () => startGcMetricsCollection,
28
+ startHeapMetricsCollection: () => startHeapMetricsCollection,
29
+ withJenniferNextRouteTx: () => withJenniferNextRouteTx
30
+ });
31
+ module.exports = __toCommonJS(index_exports);
32
+
33
+ // src/instrumentations/register-ritm.ts
34
+ var import_require_in_the_middle = require("require-in-the-middle");
35
+
36
+ // src/instrumentations/http-server.ts
37
+ var import_jennifer5_agent4 = require("@jennifersoft/jennifer5-agent");
38
+
39
+ // src/core/shimmer.ts
40
+ var skipMethods = /* @__PURE__ */ new Set(["caller", "arguments", "name", "length"]);
41
+ var skipMethodSize = skipMethods.size;
42
+ var nonConfigurableModuleExports = /* @__PURE__ */ new WeakMap();
43
+ function copyProperties(original, wrapped) {
44
+ if (original.constructor !== wrapped.constructor) {
45
+ const proto = Object.getPrototypeOf(original);
46
+ Object.setPrototypeOf(wrapped, proto);
47
+ }
48
+ const ownKeys = Reflect.ownKeys(original);
49
+ if (original.length !== wrapped.length) {
50
+ Object.defineProperty(wrapped, "length", { value: original.length, configurable: true });
51
+ }
52
+ if (original.name !== wrapped.name) {
53
+ Object.defineProperty(wrapped, "name", { value: original.name, configurable: true });
54
+ }
55
+ if (ownKeys.length !== 2) {
56
+ for (const key of ownKeys) {
57
+ if (skipMethods.has(key)) continue;
58
+ const descriptor = Object.getOwnPropertyDescriptor(original, key);
59
+ if (descriptor.writable && descriptor.enumerable && descriptor.configurable) {
60
+ wrapped[key] = original[key];
61
+ } else if (descriptor.writable || descriptor.configurable || !Object.hasOwn(wrapped, key)) {
62
+ Object.defineProperty(wrapped, key, descriptor);
63
+ }
64
+ }
65
+ }
66
+ }
67
+ function copyObjectProperties(original, wrapped, skipKey) {
68
+ const ownKeys = Reflect.ownKeys(original);
69
+ for (const key of ownKeys) {
70
+ if (key === skipKey) continue;
71
+ const descriptor = Object.getOwnPropertyDescriptor(original, key);
72
+ if (descriptor.writable && descriptor.enumerable && descriptor.configurable) {
73
+ wrapped[key] = original[key];
74
+ } else if (descriptor.writable || descriptor.configurable || !Object.hasOwn(wrapped, key)) {
75
+ Object.defineProperty(wrapped, key, descriptor);
76
+ }
77
+ }
78
+ }
79
+ function wrap(target, name, wrapper, options) {
80
+ if (typeof wrapper !== "function") {
81
+ throw new TypeError(wrapper ? "Target is not a function" : "No function provided");
82
+ }
83
+ if (target == null) {
84
+ return;
85
+ }
86
+ const descriptor = Object.getOwnPropertyDescriptor(target, name) ?? {
87
+ value: target[name],
88
+ writable: true,
89
+ configurable: true,
90
+ enumerable: false
91
+ };
92
+ if (descriptor.set && (!descriptor.get || options?.replaceGetter)) {
93
+ throw new Error(
94
+ options?.replaceGetter ? "Replacing a getter/setter pair is not supported. Implement if required." : "Replacing setters is not supported. Implement if required."
95
+ );
96
+ }
97
+ const original = descriptor.value ?? (options?.replaceGetter ? target[name] : descriptor.get);
98
+ assertMethod(target, name, original);
99
+ const wrapped = wrapper(original);
100
+ copyProperties(original, wrapped);
101
+ if (descriptor.writable) {
102
+ if (descriptor.configurable && descriptor.enumerable) {
103
+ target[name] = wrapped;
104
+ return target;
105
+ }
106
+ descriptor.value = wrapped;
107
+ } else {
108
+ if (descriptor.get) {
109
+ descriptor.get = options?.replaceGetter ? () => wrapped : wrapped;
110
+ } else {
111
+ descriptor.value = wrapped;
112
+ }
113
+ if (descriptor.configurable === false) {
114
+ let moduleExports = nonConfigurableModuleExports.get(target);
115
+ if (!moduleExports) {
116
+ if (typeof target === "function") {
117
+ const original2 = target;
118
+ moduleExports = function(...args) {
119
+ return original2.apply(original2, args);
120
+ };
121
+ skipMethods.add(name);
122
+ copyProperties(target, moduleExports);
123
+ if (skipMethods.size === skipMethodSize + 1) {
124
+ skipMethods.delete(name);
125
+ }
126
+ } else {
127
+ moduleExports = Object.create(target);
128
+ copyObjectProperties(target, moduleExports, name);
129
+ }
130
+ nonConfigurableModuleExports.set(target, moduleExports);
131
+ }
132
+ target = moduleExports;
133
+ }
134
+ }
135
+ Object.defineProperty(target, name, descriptor);
136
+ return target;
137
+ }
138
+ function assertMethod(target, name, method) {
139
+ if (typeof method !== "function") {
140
+ let message = "No target object provided";
141
+ if (target) {
142
+ if (typeof target !== "object" && typeof target !== "function") {
143
+ message = "Invalid target";
144
+ } else {
145
+ const nameStr = String(name);
146
+ message = method ? `Original method ${nameStr} is not a function` : `No original method ${nameStr}`;
147
+ }
148
+ }
149
+ throw new TypeError(message);
150
+ }
151
+ }
152
+
153
+ // src/core/context-manager.ts
154
+ var import_node_async_hooks = require("async_hooks");
155
+ var import_jennifer5_agent = require("@jennifersoft/jennifer5-agent");
156
+ var TransactionContextManager = class {
157
+ constructor() {
158
+ this._asyncLocalStorage = new import_node_async_hooks.AsyncLocalStorage();
159
+ }
160
+ /**
161
+ * Create a new transaction context
162
+ */
163
+ start() {
164
+ const ctx = {
165
+ id: (0, import_jennifer5_agent.generateTxid)(),
166
+ enable: (0, import_jennifer5_agent.configEnable)()
167
+ };
168
+ return ctx;
169
+ }
170
+ /**
171
+ * Run a callback within a transaction context scope
172
+ * All async operations within this scope will automatically have access to the context
173
+ */
174
+ run(ctx, callback) {
175
+ return this._asyncLocalStorage.run(ctx, callback);
176
+ }
177
+ /**
178
+ * Get the current transaction context (if any)
179
+ * This works automatically across async boundaries thanks to AsyncLocalStorage
180
+ */
181
+ getCurrentContext() {
182
+ return this._asyncLocalStorage.getStore();
183
+ }
184
+ };
185
+ var contextManager = new TransactionContextManager();
186
+
187
+ // src/feat/wmonid.ts
188
+ var import_jennifer5_agent2 = require("@jennifersoft/jennifer5-agent");
189
+
190
+ // src/dep/cookie.ts
191
+ var cookieNameRegExp = /^[\u0021-\u003A\u003C\u003E-\u007E]+$/;
192
+ var cookieValueRegExp = /^[\u0021-\u003A\u003C-\u007E]*$/;
193
+ var domainValueRegExp = /^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i;
194
+ var pathValueRegExp = /^[\u0020-\u003A\u003D-\u007E]*$/;
195
+ var __toString = Object.prototype.toString;
196
+ var NullObject = /* @__PURE__ */ (() => {
197
+ const C = function() {
198
+ };
199
+ C.prototype = /* @__PURE__ */ Object.create(null);
200
+ return C;
201
+ })();
202
+ function parseCookie(str, options) {
203
+ const obj = new NullObject();
204
+ const len = str.length;
205
+ if (len < 2) return obj;
206
+ const dec = options?.decode || decode;
207
+ let index = 0;
208
+ do {
209
+ const eqIdx = eqIndex(str, index, len);
210
+ if (eqIdx === -1) break;
211
+ const endIdx = endIndex(str, index, len);
212
+ if (eqIdx > endIdx) {
213
+ index = str.lastIndexOf(";", eqIdx - 1) + 1;
214
+ continue;
215
+ }
216
+ const key = valueSlice(str, index, eqIdx);
217
+ if (obj[key] === void 0) {
218
+ obj[key] = dec(valueSlice(str, eqIdx + 1, endIdx));
219
+ }
220
+ index = endIdx + 1;
221
+ } while (index < len);
222
+ return obj;
223
+ }
224
+ function stringifySetCookie(_name, _val, _opts) {
225
+ const cookie = typeof _name === "object" ? _name : { ..._opts, name: _name, value: String(_val) };
226
+ const options = typeof _val === "object" ? _val : _opts;
227
+ const enc = options?.encode || encodeURIComponent;
228
+ if (!cookieNameRegExp.test(cookie.name)) {
229
+ throw new TypeError(`argument name is invalid: ${cookie.name}`);
230
+ }
231
+ const value = cookie.value ? enc(cookie.value) : "";
232
+ if (!cookieValueRegExp.test(value)) {
233
+ throw new TypeError(`argument val is invalid: ${cookie.value}`);
234
+ }
235
+ let str = cookie.name + "=" + value;
236
+ if (cookie.maxAge !== void 0) {
237
+ if (!Number.isInteger(cookie.maxAge)) {
238
+ throw new TypeError(`option maxAge is invalid: ${cookie.maxAge}`);
239
+ }
240
+ str += "; Max-Age=" + cookie.maxAge;
241
+ }
242
+ if (cookie.domain) {
243
+ if (!domainValueRegExp.test(cookie.domain)) {
244
+ throw new TypeError(`option domain is invalid: ${cookie.domain}`);
245
+ }
246
+ str += "; Domain=" + cookie.domain;
247
+ }
248
+ if (cookie.path) {
249
+ if (!pathValueRegExp.test(cookie.path)) {
250
+ throw new TypeError(`option path is invalid: ${cookie.path}`);
251
+ }
252
+ str += "; Path=" + cookie.path;
253
+ }
254
+ if (cookie.expires) {
255
+ if (!isDate(cookie.expires) || !Number.isFinite(cookie.expires.valueOf())) {
256
+ throw new TypeError(`option expires is invalid: ${cookie.expires}`);
257
+ }
258
+ str += "; Expires=" + cookie.expires.toUTCString();
259
+ }
260
+ if (cookie.httpOnly) {
261
+ str += "; HttpOnly";
262
+ }
263
+ if (cookie.secure) {
264
+ str += "; Secure";
265
+ }
266
+ if (cookie.partitioned) {
267
+ str += "; Partitioned";
268
+ }
269
+ if (cookie.priority) {
270
+ const priority = typeof cookie.priority === "string" ? cookie.priority.toLowerCase() : void 0;
271
+ switch (priority) {
272
+ case "low":
273
+ str += "; Priority=Low";
274
+ break;
275
+ case "medium":
276
+ str += "; Priority=Medium";
277
+ break;
278
+ case "high":
279
+ str += "; Priority=High";
280
+ break;
281
+ default:
282
+ throw new TypeError(`option priority is invalid: ${cookie.priority}`);
283
+ }
284
+ }
285
+ if (cookie.sameSite) {
286
+ const sameSite = typeof cookie.sameSite === "string" ? cookie.sameSite.toLowerCase() : cookie.sameSite;
287
+ switch (sameSite) {
288
+ case true:
289
+ case "strict":
290
+ str += "; SameSite=Strict";
291
+ break;
292
+ case "lax":
293
+ str += "; SameSite=Lax";
294
+ break;
295
+ case "none":
296
+ str += "; SameSite=None";
297
+ break;
298
+ default:
299
+ throw new TypeError(`option sameSite is invalid: ${cookie.sameSite}`);
300
+ }
301
+ }
302
+ return str;
303
+ }
304
+ function endIndex(str, min, len) {
305
+ const index = str.indexOf(";", min);
306
+ return index === -1 ? len : index;
307
+ }
308
+ function eqIndex(str, min, max) {
309
+ const index = str.indexOf("=", min);
310
+ return index < max ? index : -1;
311
+ }
312
+ function valueSlice(str, min, max) {
313
+ let start = min;
314
+ let end = max;
315
+ do {
316
+ const code = str.charCodeAt(start);
317
+ if (code !== 32 && code !== 9) break;
318
+ } while (++start < end);
319
+ while (end > start) {
320
+ const code = str.charCodeAt(end - 1);
321
+ if (code !== 32 && code !== 9) break;
322
+ end--;
323
+ }
324
+ return str.slice(start, end);
325
+ }
326
+ function decode(str) {
327
+ if (str.indexOf("%") === -1) return str;
328
+ try {
329
+ return decodeURIComponent(str);
330
+ } catch (e) {
331
+ return str;
332
+ }
333
+ }
334
+ function isDate(val) {
335
+ return __toString.call(val) === "[object Date]";
336
+ }
337
+
338
+ // src/feat/wmonid.ts
339
+ var WMONID_COOKIE_NAME = "WMONID";
340
+ var SECONDS_PER_YEAR = 365 * 24 * 60 * 60;
341
+ function getCookie(req, name) {
342
+ const cookieHeader = req.headers?.cookie;
343
+ if (!cookieHeader) {
344
+ return void 0;
345
+ }
346
+ const cookieString = Array.isArray(cookieHeader) ? cookieHeader.join("; ") : cookieHeader;
347
+ const cookies = parseCookie(cookieString);
348
+ return cookies[name];
349
+ }
350
+ function setCookie(res, cookie) {
351
+ const cookieString = stringifySetCookie(cookie);
352
+ const existingSetCookie = res.getHeader("Set-Cookie");
353
+ if (existingSetCookie === void 0) {
354
+ res.setHeader("Set-Cookie", cookieString);
355
+ } else if (Array.isArray(existingSetCookie)) {
356
+ res.setHeader("Set-Cookie", [...existingSetCookie, cookieString]);
357
+ } else {
358
+ res.setHeader("Set-Cookie", [String(existingSetCookie), cookieString]);
359
+ }
360
+ }
361
+ function setNewWmonidCookie(res, txid) {
362
+ const cookieValue = (0, import_jennifer5_agent2.i64ToBase64)(txid);
363
+ setCookie(res, {
364
+ name: WMONID_COOKIE_NAME,
365
+ value: cookieValue,
366
+ maxAge: SECONDS_PER_YEAR,
367
+ path: "/",
368
+ secure: (0, import_jennifer5_agent2.configEnableSecureForWmonidCookie)(),
369
+ httpOnly: (0, import_jennifer5_agent2.configEnableHttpOnlyForWmonidCookie)()
370
+ });
371
+ }
372
+ function getWmonidInCookie(req, res, txid) {
373
+ try {
374
+ const wmonidCookie = getCookie(req, WMONID_COOKIE_NAME);
375
+ if (wmonidCookie) {
376
+ return (0, import_jennifer5_agent2.base64ToI64)(wmonidCookie);
377
+ }
378
+ } catch (e) {
379
+ (0, import_jennifer5_agent2.warn)(`Failed to get WMONID cookie: ${e}`);
380
+ }
381
+ try {
382
+ setNewWmonidCookie(res, txid);
383
+ } catch (e) {
384
+ (0, import_jennifer5_agent2.warn)(`Failed to set WMONID cookie: ${e}`);
385
+ }
386
+ return 0;
387
+ }
388
+
389
+ // src/feat/topology.ts
390
+ var import_jennifer5_agent3 = require("@jennifersoft/jennifer5-agent");
391
+ var X_DOMAIN_ID = "x-domainid";
392
+ var X_AGENT_ID = "x-agentid";
393
+ function getTopologyInfo(msg) {
394
+ if (!(0, import_jennifer5_agent3.configEnableHttpTopologyMode)()) {
395
+ return void 0;
396
+ }
397
+ try {
398
+ const topologyHeaderKey = (0, import_jennifer5_agent3.configTopologyHttpHeaderKey)();
399
+ const remoteCallKey = parseNumber(getHeader(msg, topologyHeaderKey));
400
+ const sid = parseNumber(getHeader(msg, X_DOMAIN_ID));
401
+ const oid = parseNumber(getHeader(msg, X_AGENT_ID));
402
+ if ([remoteCallKey, sid, oid].some((v) => v === void 0)) {
403
+ return void 0;
404
+ }
405
+ if (!(0, import_jennifer5_agent3.isAgentId)(oid)) {
406
+ return void 0;
407
+ }
408
+ return { remoteCallKey, domainId: sid, oid };
409
+ } catch {
410
+ return void 0;
411
+ }
412
+ }
413
+ function setTopologyResponseHeaders(incoming, res) {
414
+ if (!(0, import_jennifer5_agent3.configEnableHttpTopologyMode)()) {
415
+ return;
416
+ }
417
+ try {
418
+ if (!incoming) return;
419
+ if (res.headersSent || res.writableEnded) {
420
+ return;
421
+ }
422
+ const currentDomainId = (0, import_jennifer5_agent3.domainId)();
423
+ const currentAgentId = (0, import_jennifer5_agent3.agentId)();
424
+ if (!currentDomainId || !currentAgentId) {
425
+ return;
426
+ }
427
+ const topologyHeaderKey = (0, import_jennifer5_agent3.configTopologyHttpHeaderKey)();
428
+ res.setHeader(topologyHeaderKey, incoming.remoteCallKey);
429
+ res.setHeader(X_DOMAIN_ID, String(currentDomainId));
430
+ res.setHeader(X_AGENT_ID, String(currentAgentId));
431
+ } catch (error) {
432
+ (0, import_jennifer5_agent3.warn)(`Failed to set topology response headers: ${error}`);
433
+ }
434
+ }
435
+ function setTopologyRequestHeaders(req) {
436
+ if (!(0, import_jennifer5_agent3.configEnableHttpTopologyMode)()) {
437
+ return void 0;
438
+ }
439
+ try {
440
+ const remoteCallKey = (0, import_jennifer5_agent3.generateTxid)();
441
+ const currentDomainId = (0, import_jennifer5_agent3.domainId)();
442
+ const currentAgentId = (0, import_jennifer5_agent3.agentId)();
443
+ if (!currentDomainId || !currentAgentId) {
444
+ return void 0;
445
+ }
446
+ const topologyHeaderKey = (0, import_jennifer5_agent3.configTopologyHttpHeaderKey)();
447
+ if (!req.getHeader(topologyHeaderKey)) {
448
+ req.setHeader(topologyHeaderKey, String(remoteCallKey));
449
+ req.setHeader(X_DOMAIN_ID, String(currentDomainId));
450
+ req.setHeader(X_AGENT_ID, String(currentAgentId));
451
+ }
452
+ return {
453
+ remoteCallKey,
454
+ domainId: currentDomainId,
455
+ oid: currentAgentId
456
+ };
457
+ } catch (error) {
458
+ (0, import_jennifer5_agent3.warn)(`Failed to set topology request headers: ${error}`);
459
+ return void 0;
460
+ }
461
+ }
462
+ function setTopologyFetchHeaders(headers) {
463
+ if (!(0, import_jennifer5_agent3.configEnableHttpTopologyMode)()) {
464
+ return void 0;
465
+ }
466
+ try {
467
+ const remoteCallKey = (0, import_jennifer5_agent3.generateTxid)();
468
+ const currentDomainId = (0, import_jennifer5_agent3.domainId)();
469
+ const currentAgentId = (0, import_jennifer5_agent3.agentId)();
470
+ if (!currentDomainId || !currentAgentId) {
471
+ return void 0;
472
+ }
473
+ const topologyHeaderKey = (0, import_jennifer5_agent3.configTopologyHttpHeaderKey)();
474
+ if (!headers.get(topologyHeaderKey)) {
475
+ headers.set(topologyHeaderKey, String(remoteCallKey));
476
+ headers.set(X_DOMAIN_ID, String(currentDomainId));
477
+ headers.set(X_AGENT_ID, String(currentAgentId));
478
+ }
479
+ return {
480
+ remoteCallKey,
481
+ domainId: currentDomainId,
482
+ oid: currentAgentId
483
+ };
484
+ } catch (error) {
485
+ (0, import_jennifer5_agent3.warn)(`Failed to set topology fetch headers: ${error}`);
486
+ return void 0;
487
+ }
488
+ }
489
+ function getTopologyInfoFromFetch(response) {
490
+ if (!(0, import_jennifer5_agent3.configEnableHttpTopologyMode)()) {
491
+ return void 0;
492
+ }
493
+ try {
494
+ const topologyHeaderKey = (0, import_jennifer5_agent3.configTopologyHttpHeaderKey)();
495
+ const remoteCallKey = parseNumber(response.headers.get(topologyHeaderKey) || void 0);
496
+ const targetDomainId = parseNumber(response.headers.get(X_DOMAIN_ID) || void 0);
497
+ const targetAgentId = parseNumber(response.headers.get(X_AGENT_ID) || void 0);
498
+ if ([remoteCallKey, targetDomainId, targetAgentId].some((v) => v === void 0)) {
499
+ return void 0;
500
+ }
501
+ if (!(0, import_jennifer5_agent3.isAgentId)(targetAgentId)) {
502
+ return void 0;
503
+ }
504
+ return {
505
+ remoteCallKey,
506
+ domainId: targetDomainId,
507
+ oid: targetAgentId
508
+ };
509
+ } catch {
510
+ return void 0;
511
+ }
512
+ }
513
+ function getHeader(req, name) {
514
+ const value = req.headers?.[name.toLowerCase()];
515
+ if (!value) {
516
+ return void 0;
517
+ }
518
+ return Array.isArray(value) ? value[0] : value;
519
+ }
520
+ function parseNumber(value) {
521
+ if (!value) {
522
+ return void 0;
523
+ }
524
+ const parsed = Number(value);
525
+ return Number.isNaN(parsed) ? void 0 : parsed;
526
+ }
527
+
528
+ // src/instrumentations/http-server.ts
529
+ var JENNIFER_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.http.wrapped");
530
+ function collectResponseHeaders(res) {
531
+ if (!res?.getHeaders) return void 0;
532
+ return Object.entries(res.getHeaders()).map(([key, value]) => {
533
+ const valueStr = Array.isArray(value) ? value.join(", ") : String(value);
534
+ return `${key}:${valueStr}`;
535
+ });
536
+ }
537
+ function patchHttpServer(httpModule, moduleName) {
538
+ try {
539
+ if (instrumentServerEmit(httpModule)) {
540
+ (0, import_jennifer5_agent4.info)(`${moduleName} server instrumentation registered`);
541
+ }
542
+ } catch (error) {
543
+ (0, import_jennifer5_agent4.warn)(`Failed to register ${moduleName} server instrumentation: ${error}`);
544
+ }
545
+ }
546
+ function instrumentServerEmit(httpModule) {
547
+ const ServerPrototype = httpModule.Server.prototype;
548
+ if (ServerPrototype.emit?.[JENNIFER_WRAPPED]) {
549
+ return false;
550
+ }
551
+ wrap(ServerPrototype, "emit", (originalEmit) => {
552
+ const wrapper = function(eventName, ...args) {
553
+ if (eventName === "request") {
554
+ return handleRequestEvent(this, originalEmit, eventName, args);
555
+ }
556
+ if (eventName === "upgrade") {
557
+ return handleUpgradeEvent(this, originalEmit, eventName, args);
558
+ }
559
+ return originalEmit.apply(this, [eventName, ...args]);
560
+ };
561
+ wrapper[JENNIFER_WRAPPED] = true;
562
+ return wrapper;
563
+ });
564
+ return true;
565
+ }
566
+ function createHttpHeaders(req) {
567
+ return req?.headers ? Object.entries(req.headers).map(([key, value]) => `${key}:${value}`) : void 0;
568
+ }
569
+ function handleRequestEvent(server, originalEmit, eventName, args) {
570
+ const [req, res] = args;
571
+ const ctx = contextManager.start();
572
+ if (ctx.enable) {
573
+ const wmonidInCookie = !(0, import_jennifer5_agent4.configUsingRemoteAddressForWmonid)() ? getWmonidInCookie(req, res, ctx.id) : void 0;
574
+ const incomingRemotecallInfo = getTopologyInfo(req);
575
+ setTopologyResponseHeaders(incomingRemotecallInfo, res);
576
+ (0, import_jennifer5_agent4.createTransactionCtx)({
577
+ txId: ctx.id,
578
+ httpMethod: req?.method,
579
+ httpHeaders: createHttpHeaders(req),
580
+ httpUrl: req?.url,
581
+ clientIp: req?.socket?.remoteAddress,
582
+ wmonidInCookie,
583
+ incomingRemotecallInfo
584
+ });
585
+ return contextManager.run(ctx, () => {
586
+ let transactionEnded = false;
587
+ res.once("close", () => {
588
+ if (!transactionEnded) {
589
+ transactionEnded = true;
590
+ (0, import_jennifer5_agent4.releaseTransactionCtx)(ctx.id, {
591
+ httpStatusCode: res?.statusCode,
592
+ httpHeaders: collectResponseHeaders(res),
593
+ connectionAborted: true
594
+ });
595
+ }
596
+ });
597
+ wrap(res, "end", (originalEnd) => {
598
+ return function(...endArgs) {
599
+ if (!transactionEnded) {
600
+ transactionEnded = true;
601
+ (0, import_jennifer5_agent4.releaseTransactionCtx)(ctx.id, {
602
+ httpStatusCode: res?.statusCode,
603
+ httpHeaders: collectResponseHeaders(res)
604
+ });
605
+ }
606
+ return originalEnd.apply(this, endArgs);
607
+ };
608
+ });
609
+ return originalEmit.call(server, eventName, req, res);
610
+ });
611
+ } else {
612
+ return originalEmit.call(server, eventName, req, res);
613
+ }
614
+ }
615
+ function handleUpgradeEvent(server, originalEmit, eventName, args) {
616
+ const [req] = args;
617
+ const ctx = contextManager.start();
618
+ if (ctx.enable) {
619
+ (0, import_jennifer5_agent4.createTransactionCtx)({
620
+ txId: ctx.id,
621
+ method: "http.upgrade",
622
+ httpMethod: req?.method,
623
+ httpHeaders: createHttpHeaders(req),
624
+ httpUrl: req?.url,
625
+ clientIp: req?.socket?.remoteAddress
626
+ });
627
+ } else {
628
+ return originalEmit.apply(server, [eventName, ...args]);
629
+ }
630
+ return contextManager.run(ctx, () => {
631
+ try {
632
+ return originalEmit.apply(server, [eventName, ...args]);
633
+ } finally {
634
+ (0, import_jennifer5_agent4.releaseTransactionCtx)(ctx.id, {});
635
+ }
636
+ });
637
+ }
638
+
639
+ // src/instrumentations/apollo.ts
640
+ var import_jennifer5_agent5 = require("@jennifersoft/jennifer5-agent");
641
+ var JENNIFER_APOLLO_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.apollo.execute_http_graphql_request.wrapped");
642
+ function extractGraphQLErrorsMessage(response) {
643
+ const body = response?.body;
644
+ if (!body || typeof body !== "object") {
645
+ return null;
646
+ }
647
+ let errors = [];
648
+ if (Array.isArray(body.errors)) {
649
+ errors = body.errors;
650
+ } else if (body.singleResult && Array.isArray(body.singleResult.errors)) {
651
+ errors = body.singleResult.errors;
652
+ } else if (typeof body.string === "string") {
653
+ try {
654
+ const parsed = JSON.parse(body.string);
655
+ if (Array.isArray(parsed?.errors)) {
656
+ errors = parsed.errors;
657
+ }
658
+ } catch {
659
+ }
660
+ }
661
+ if (!errors.length) {
662
+ return null;
663
+ }
664
+ const messages = errors.map((error) => typeof error?.message === "string" ? error.message : "Unknown GraphQL error").filter((message) => message.length > 0);
665
+ if (!messages.length) {
666
+ return "GraphQL: Unknown GraphQL error";
667
+ }
668
+ return messages.map((message) => `GraphQL: ${message}`).join(" | ");
669
+ }
670
+ function detectOperationType(query) {
671
+ const normalized = query?.trim().toLowerCase();
672
+ if (!normalized) {
673
+ return "unknown";
674
+ }
675
+ if (normalized.startsWith("mutation")) {
676
+ return "mutation";
677
+ }
678
+ if (normalized.startsWith("query") || normalized.startsWith("{")) {
679
+ return "query";
680
+ }
681
+ return "unknown";
682
+ }
683
+ function buildServiceName(requestContext) {
684
+ const body = requestContext?.httpGraphQLRequest?.body;
685
+ if (!body || typeof body !== "object") {
686
+ return null;
687
+ }
688
+ if (body.kind && body.kind !== "single") {
689
+ return "GraphQL - unknown anonymous";
690
+ }
691
+ const operationType = detectOperationType(body.query);
692
+ const operationName = body.operationName?.trim() || "anonymous";
693
+ return `GraphQL - ${operationType} ${operationName}`;
694
+ }
695
+ function patchApolloServerModule(apolloModule, moduleName) {
696
+ try {
697
+ const ApolloServer = apolloModule?.ApolloServer;
698
+ const proto = ApolloServer?.prototype;
699
+ if (!proto || typeof proto.executeHTTPGraphQLRequest !== "function") {
700
+ return;
701
+ }
702
+ if (proto.executeHTTPGraphQLRequest[JENNIFER_APOLLO_WRAPPED]) {
703
+ return;
704
+ }
705
+ wrap(proto, "executeHTTPGraphQLRequest", (original) => {
706
+ const wrapper = async function(...args) {
707
+ const ctx = contextManager.getCurrentContext();
708
+ if (ctx?.enable && (0, import_jennifer5_agent5.configServiceNamingByGraphqlOperation)()) {
709
+ const serviceName = buildServiceName(args[0]);
710
+ if (serviceName) {
711
+ (0, import_jennifer5_agent5.changeTransactionServiceName)(ctx.id, serviceName);
712
+ }
713
+ }
714
+ const response = await original.apply(this, args);
715
+ if (ctx?.enable) {
716
+ const errorsMessage = extractGraphQLErrorsMessage(response);
717
+ if (errorsMessage) {
718
+ (0, import_jennifer5_agent5.sendError)(ctx.id, errorsMessage);
719
+ }
720
+ }
721
+ return response;
722
+ };
723
+ wrapper[JENNIFER_APOLLO_WRAPPED] = true;
724
+ return wrapper;
725
+ });
726
+ (0, import_jennifer5_agent5.info)(`${moduleName}.ApolloServer instrumentation registered`);
727
+ } catch (error) {
728
+ (0, import_jennifer5_agent5.warn)(`Failed to register ${moduleName} Apollo instrumentation: ${error}`);
729
+ }
730
+ }
731
+
732
+ // src/instrumentations/http-client.ts
733
+ var import_node_url = require("url");
734
+ var import_jennifer5_agent6 = require("@jennifersoft/jennifer5-agent");
735
+ var JENNIFER_WRAPPED2 = /* @__PURE__ */ Symbol.for("jennifer.http.wrapped");
736
+ function patchHttpClient(httpModule, moduleName) {
737
+ try {
738
+ if (instrumentClientRequest(httpModule)) {
739
+ (0, import_jennifer5_agent6.info)(`${moduleName} client instrumentation registered`);
740
+ }
741
+ } catch (error) {
742
+ (0, import_jennifer5_agent6.warn)(`Failed to register ${moduleName} client instrumentation: ${error}`);
743
+ }
744
+ }
745
+ function instrumentClientRequest(httpModule) {
746
+ if (httpModule.request?.[JENNIFER_WRAPPED2]) {
747
+ return false;
748
+ }
749
+ wrap(httpModule, "request", (originalRequest) => {
750
+ const wrapper = function(...args) {
751
+ const req = originalRequest.apply(this, args);
752
+ const ctx = contextManager.getCurrentContext();
753
+ if (!ctx || !ctx.enable || !(0, import_jennifer5_agent6.configEnableHttpClientProfile)()) {
754
+ return req;
755
+ }
756
+ const { uri, options } = normalizeArgs(httpModule, args[0], args[1]);
757
+ const method = options.method || req.method || "GET";
758
+ setTopologyRequestHeaders(req);
759
+ const headers = {};
760
+ const rawHeaders = req.getHeaders();
761
+ for (const [key, value] of Object.entries(rawHeaders)) {
762
+ if (typeof value === "string") {
763
+ headers[key] = value;
764
+ } else if (Array.isArray(value)) {
765
+ headers[key] = value.join(", ");
766
+ } else if (value !== void 0) {
767
+ headers[key] = String(value);
768
+ }
769
+ }
770
+ const startCtx = (0, import_jennifer5_agent6.createHttpProfileCtx)(method, uri, headers, ctx.id);
771
+ let released = false;
772
+ const release = (endCtx) => {
773
+ if (!released) {
774
+ released = true;
775
+ (0, import_jennifer5_agent6.releaseHttpProfileCtx)(startCtx, endCtx);
776
+ }
777
+ };
778
+ const originalEmit = req.emit;
779
+ req.emit = function(eventName, ...emitArgs) {
780
+ switch (eventName) {
781
+ case "response": {
782
+ const res = emitArgs[0];
783
+ res.once("end", () => {
784
+ release({
785
+ statusCode: res.statusCode,
786
+ remoteCallInfo: getTopologyInfo(res)
787
+ });
788
+ });
789
+ break;
790
+ }
791
+ case "error":
792
+ case "timeout": {
793
+ const error = emitArgs[0];
794
+ release({
795
+ error: {
796
+ message: error?.message,
797
+ stack: error?.stack
798
+ }
799
+ });
800
+ break;
801
+ }
802
+ case "abort":
803
+ case "close":
804
+ break;
805
+ }
806
+ return originalEmit.apply(this, [eventName, ...emitArgs]);
807
+ };
808
+ return req;
809
+ };
810
+ wrapper[JENNIFER_WRAPPED2] = true;
811
+ return wrapper;
812
+ });
813
+ wrap(httpModule, "get", (originalGet) => {
814
+ return function(...args) {
815
+ const req = httpModule.request.apply(this, args);
816
+ req.end();
817
+ return req;
818
+ };
819
+ });
820
+ return true;
821
+ }
822
+ function normalizeOptions(httpModule, inputURL) {
823
+ if (typeof inputURL === "string") {
824
+ try {
825
+ return urlToOptions(httpModule, new URL(inputURL));
826
+ } catch {
827
+ return { path: inputURL };
828
+ }
829
+ }
830
+ if (inputURL instanceof URL) {
831
+ return urlToOptions(httpModule, inputURL);
832
+ }
833
+ if (inputURL) {
834
+ const result = { ...inputURL };
835
+ if (!result.protocol) {
836
+ result.protocol = httpModule.globalAgent?.protocol || "http:";
837
+ }
838
+ if (!result.pathname && result.path) {
839
+ const pathParts = result.path.split("?");
840
+ result.pathname = pathParts[0];
841
+ if (pathParts[1] && !result.search) {
842
+ result.search = `?${pathParts[1]}`;
843
+ }
844
+ }
845
+ return result;
846
+ }
847
+ return inputURL;
848
+ }
849
+ function urlToOptions(httpModule, urlObj) {
850
+ const agent = httpModule.globalAgent;
851
+ const options = {
852
+ protocol: urlObj.protocol || agent?.protocol,
853
+ hostname: urlObj.hostname.startsWith("[") ? urlObj.hostname.slice(1, -1) : urlObj.hostname || "localhost",
854
+ hash: urlObj.hash,
855
+ search: urlObj.search,
856
+ pathname: urlObj.pathname,
857
+ path: `${urlObj.pathname || ""}${urlObj.search || ""}`,
858
+ href: urlObj.href
859
+ };
860
+ if (urlObj.port !== "") {
861
+ options.port = Number(urlObj.port);
862
+ }
863
+ if (urlObj.username || urlObj.password) {
864
+ options.auth = `${urlObj.username}:${urlObj.password}`;
865
+ }
866
+ return options;
867
+ }
868
+ function combineOptions(inputURL, inputOptions) {
869
+ return inputOptions !== null && typeof inputOptions === "object" ? Object.assign(inputURL || {}, inputOptions) : inputURL;
870
+ }
871
+ function normalizeArgs(httpModule, inputURL, inputOptions) {
872
+ const normalizedURL = normalizeOptions(httpModule, inputURL);
873
+ const options = combineOptions(normalizedURL, inputOptions);
874
+ const uri = (0, import_node_url.format)(options);
875
+ return { uri, options };
876
+ }
877
+
878
+ // src/instrumentations/fs.ts
879
+ var import_jennifer5_agent7 = require("@jennifersoft/jennifer5-agent");
880
+ var JENNIFER_WRAPPED3 = /* @__PURE__ */ Symbol.for("jennifer.fs.wrapped");
881
+ function patchFsSync(fs, _moduleName) {
882
+ const methods = [
883
+ ["readFileSync", import_jennifer5_agent7.FsActionType.SyncRead],
884
+ ["writeFileSync", import_jennifer5_agent7.FsActionType.SyncWrite]
885
+ ];
886
+ let patchedCount = 0;
887
+ for (const [method, event] of methods) {
888
+ if (fs[method]?.[JENNIFER_WRAPPED3]) {
889
+ continue;
890
+ }
891
+ wrap(fs, method, (original) => {
892
+ const wrapper = function(...args) {
893
+ const ctx = contextManager.getCurrentContext();
894
+ if (!ctx || !ctx.enable || !(0, import_jennifer5_agent7.configEnableFileProfile)()) {
895
+ return original.apply(this, args);
896
+ }
897
+ const filePathArg = args[0];
898
+ const filePath = filePathArg ? String(filePathArg) : "undefined";
899
+ const profileCtx = (0, import_jennifer5_agent7.createFsProfileCtx)(event, filePath, ctx.id);
900
+ try {
901
+ const result = original.apply(this, args);
902
+ (0, import_jennifer5_agent7.releaseFsProfileCtx)(profileCtx, {
903
+ fileSize: result?.length
904
+ });
905
+ return result;
906
+ } catch (error) {
907
+ (0, import_jennifer5_agent7.releaseFsProfileCtx)(profileCtx, {
908
+ error: {
909
+ message: error.toString()
910
+ }
911
+ });
912
+ throw error;
913
+ }
914
+ };
915
+ wrapper[JENNIFER_WRAPPED3] = true;
916
+ return wrapper;
917
+ });
918
+ patchedCount++;
919
+ }
920
+ if (patchedCount > 0) {
921
+ (0, import_jennifer5_agent7.info)(`fs sync: ${patchedCount} methods instrumented`);
922
+ }
923
+ return patchedCount > 0;
924
+ }
925
+ function patchFsAsync(fs, _moduleName) {
926
+ const asyncMethods = [
927
+ ["readFile", import_jennifer5_agent7.FsActionType.AsyncRead],
928
+ ["writeFile", import_jennifer5_agent7.FsActionType.AsyncWrite]
929
+ ];
930
+ let patchedCount = 0;
931
+ for (const [method, event] of asyncMethods) {
932
+ if (fs[method]?.[JENNIFER_WRAPPED3]) {
933
+ continue;
934
+ }
935
+ wrap(fs, method, (original) => {
936
+ const wrapper = function(...args) {
937
+ const callbackIndex = args.findIndex((arg) => typeof arg === "function");
938
+ if (callbackIndex === -1) {
939
+ return original.apply(this, args);
940
+ }
941
+ const ctx = contextManager.getCurrentContext();
942
+ if (!ctx || !ctx.enable || !(0, import_jennifer5_agent7.configEnableFileProfile)()) {
943
+ return original.apply(this, args);
944
+ }
945
+ const filePathArg = args[0];
946
+ const filePath = filePathArg ? String(filePathArg) : "undefined";
947
+ const perfCtx = (0, import_jennifer5_agent7.createFsProfileCtx)(event, filePath, ctx.id);
948
+ const originalCallback = args[callbackIndex];
949
+ args[callbackIndex] = function(err, data) {
950
+ (0, import_jennifer5_agent7.releaseFsProfileCtx)(perfCtx, {
951
+ error: err ? { message: err.message, stack: err.stack } : void 0,
952
+ fileSize: data?.length
953
+ });
954
+ return contextManager.run(ctx, () => originalCallback.call(this, err, data));
955
+ };
956
+ return original.apply(this, args);
957
+ };
958
+ wrapper[JENNIFER_WRAPPED3] = true;
959
+ return wrapper;
960
+ });
961
+ patchedCount++;
962
+ }
963
+ if (patchedCount > 0) {
964
+ (0, import_jennifer5_agent7.info)(`fs async: ${patchedCount} methods instrumented`);
965
+ }
966
+ return patchedCount > 0;
967
+ }
968
+ function patchFsPromise(fs, _moduleName) {
969
+ const fsPromises = fs.promises;
970
+ if (!fsPromises) {
971
+ return false;
972
+ }
973
+ const promiseMethods = [
974
+ ["readFile", import_jennifer5_agent7.FsActionType.PromiseRead],
975
+ ["writeFile", import_jennifer5_agent7.FsActionType.PromiseWrite]
976
+ ];
977
+ let patchedCount = 0;
978
+ for (const [method, event] of promiseMethods) {
979
+ if (fsPromises[method]?.[JENNIFER_WRAPPED3]) {
980
+ continue;
981
+ }
982
+ wrap(fsPromises, method, (original) => {
983
+ const wrapper = function(...args) {
984
+ const ctx = contextManager.getCurrentContext();
985
+ if (!ctx || !ctx.enable || !(0, import_jennifer5_agent7.configEnableFileProfile)()) {
986
+ return original.apply(this, args);
987
+ }
988
+ const filePathArg = args[0];
989
+ const filePath = filePathArg ? String(filePathArg) : "undefined";
990
+ const perfCtx = (0, import_jennifer5_agent7.createFsProfileCtx)(event, filePath, ctx.id);
991
+ try {
992
+ const result = original.apply(this, args);
993
+ if (result && typeof result.then === "function") {
994
+ return result.then(
995
+ (res) => {
996
+ (0, import_jennifer5_agent7.releaseFsProfileCtx)(perfCtx, {
997
+ fileSize: res?.length
998
+ });
999
+ return res;
1000
+ },
1001
+ (err) => {
1002
+ (0, import_jennifer5_agent7.releaseFsProfileCtx)(perfCtx, {
1003
+ error: {
1004
+ message: err.message,
1005
+ stack: err.stack
1006
+ }
1007
+ });
1008
+ throw err;
1009
+ }
1010
+ );
1011
+ } else {
1012
+ (0, import_jennifer5_agent7.releaseFsProfileCtx)(perfCtx, {});
1013
+ return result;
1014
+ }
1015
+ } catch (error) {
1016
+ (0, import_jennifer5_agent7.releaseFsProfileCtx)(perfCtx, {
1017
+ error: { message: error.message, stack: error.stack }
1018
+ });
1019
+ throw error;
1020
+ }
1021
+ };
1022
+ wrapper[JENNIFER_WRAPPED3] = true;
1023
+ return wrapper;
1024
+ });
1025
+ patchedCount++;
1026
+ }
1027
+ if (patchedCount > 0) {
1028
+ (0, import_jennifer5_agent7.info)(`fs.promises: ${patchedCount} methods instrumented`);
1029
+ }
1030
+ return patchedCount > 0;
1031
+ }
1032
+
1033
+ // src/instrumentations/fetch.ts
1034
+ var import_jennifer5_agent8 = require("@jennifersoft/jennifer5-agent");
1035
+ var JENNIFER_WRAPPED4 = /* @__PURE__ */ Symbol.for("jennifer.fetch.wrapped");
1036
+ function handleRequestObject(originalFetch, request, init, txId) {
1037
+ const normalizedRequest = init ? new Request(request, init) : request;
1038
+ const url = normalizedRequest.url;
1039
+ const method = normalizedRequest.method;
1040
+ const fetchHeaders = new Headers(normalizedRequest.headers);
1041
+ setTopologyFetchHeaders(fetchHeaders);
1042
+ const headers = {};
1043
+ fetchHeaders.forEach((value, key) => {
1044
+ headers[key] = value;
1045
+ });
1046
+ const wrappedRequest = new Request(normalizedRequest, { headers: fetchHeaders });
1047
+ const startCtx = (0, import_jennifer5_agent8.createHttpProfileCtx)(method, url, headers, txId);
1048
+ const result = originalFetch(wrappedRequest);
1049
+ return { result, startCtx };
1050
+ }
1051
+ function handleUrlString(originalFetch, input, init, txId) {
1052
+ const url = typeof input === "string" ? input : input.href;
1053
+ const method = init?.method || "GET";
1054
+ const fetchHeaders = new Headers(init?.headers);
1055
+ setTopologyFetchHeaders(fetchHeaders);
1056
+ const headers = {};
1057
+ fetchHeaders.forEach((value, key) => {
1058
+ headers[key] = value;
1059
+ });
1060
+ const modifiedInit = {
1061
+ ...init,
1062
+ headers: fetchHeaders
1063
+ };
1064
+ const startCtx = (0, import_jennifer5_agent8.createHttpProfileCtx)(method, url, headers, txId);
1065
+ const result = originalFetch(input, modifiedInit);
1066
+ return { result, startCtx };
1067
+ }
1068
+ function createFetchWrapper(originalFetch) {
1069
+ return function(...args) {
1070
+ const ctx = contextManager.getCurrentContext();
1071
+ if (!ctx || !ctx.enable || !(0, import_jennifer5_agent8.configEnableHttpClientProfile)()) {
1072
+ return originalFetch(...args);
1073
+ }
1074
+ const [input, init] = args;
1075
+ const { result, startCtx } = input instanceof Request ? handleRequestObject(originalFetch, input, init, ctx.id) : handleUrlString(originalFetch, input, init, ctx.id);
1076
+ return result.then(
1077
+ (response) => {
1078
+ const contentLength = response.headers.get("content-length");
1079
+ const responseSize = contentLength ? parseInt(contentLength, 10) : void 0;
1080
+ const remoteCallInfo = getTopologyInfoFromFetch(response);
1081
+ (0, import_jennifer5_agent8.releaseHttpProfileCtx)(startCtx, {
1082
+ statusCode: response.status,
1083
+ responseSize,
1084
+ remoteCallInfo
1085
+ });
1086
+ return response;
1087
+ },
1088
+ (error) => {
1089
+ (0, import_jennifer5_agent8.releaseHttpProfileCtx)(startCtx, {
1090
+ error: {
1091
+ message: error.message,
1092
+ stack: error.stack
1093
+ }
1094
+ });
1095
+ throw error;
1096
+ }
1097
+ );
1098
+ };
1099
+ }
1100
+ function patchGlobalFetch() {
1101
+ try {
1102
+ if (typeof global.fetch !== "function") {
1103
+ return;
1104
+ }
1105
+ if (global.fetch[JENNIFER_WRAPPED4]) {
1106
+ return;
1107
+ }
1108
+ wrap(global, "fetch", (originalFetch) => {
1109
+ const wrapper = createFetchWrapper(originalFetch);
1110
+ wrapper[JENNIFER_WRAPPED4] = true;
1111
+ return wrapper;
1112
+ });
1113
+ (0, import_jennifer5_agent8.info)("global.fetch instrumentation registered");
1114
+ } catch (error) {
1115
+ (0, import_jennifer5_agent8.warn)("Failed to register global.fetch instrumentation:" + error);
1116
+ }
1117
+ }
1118
+
1119
+ // src/instrumentations/n8n-workflow.ts
1120
+ var import_jennifer5_agent9 = require("@jennifersoft/jennifer5-agent");
1121
+ var JENNIFER_WRAPPED5 = /* @__PURE__ */ Symbol.for("jennifer.n8n.workflow.wrapped");
1122
+ var executionTxMap = /* @__PURE__ */ new Map();
1123
+ function registerWorkflowExecutionTx(executionId, txId) {
1124
+ executionTxMap.set(executionId, txId);
1125
+ }
1126
+ function takeWorkflowExecutionTx(executionId) {
1127
+ const txId = executionTxMap.get(executionId);
1128
+ if (txId !== void 0) {
1129
+ executionTxMap.delete(executionId);
1130
+ }
1131
+ return txId;
1132
+ }
1133
+ function patchN8nWorkflowRunner(workflowRunnerModule, moduleName) {
1134
+ try {
1135
+ if (!workflowRunnerModule?.WorkflowRunner) {
1136
+ return;
1137
+ }
1138
+ instrumentWorkflowRunner(workflowRunnerModule.WorkflowRunner);
1139
+ (0, import_jennifer5_agent9.info)(`${moduleName} WorkflowRunner instrumentation registered`);
1140
+ } catch (error) {
1141
+ (0, import_jennifer5_agent9.warn)(`Failed to register ${moduleName} WorkflowRunner instrumentation: ${error}`);
1142
+ }
1143
+ }
1144
+ function instrumentWorkflowRunner(WorkflowRunnerClass) {
1145
+ const prototype = WorkflowRunnerClass.prototype;
1146
+ if (prototype?.run?.[JENNIFER_WRAPPED5]) {
1147
+ return;
1148
+ }
1149
+ wrap(prototype, "run", (originalRun) => {
1150
+ const wrapper = function(...args) {
1151
+ const [data] = args;
1152
+ const workflowData = data?.workflowData;
1153
+ const workflowId = workflowData?.id;
1154
+ const workflowName = workflowData?.name;
1155
+ const executionMode = data?.executionMode;
1156
+ const userId = data?.userId;
1157
+ const ctx = contextManager.start();
1158
+ if (ctx.enable) {
1159
+ const serviceName = workflowName || workflowId || "unknown-workflow";
1160
+ (0, import_jennifer5_agent9.createTransactionCtx)({
1161
+ txId: ctx.id,
1162
+ method: "n8n.workflow.run",
1163
+ httpMethod: "EXECUTE",
1164
+ httpUrl: `${serviceName}`,
1165
+ httpHeaders: [
1166
+ `execution-mode:${executionMode || "unknown"}`,
1167
+ `workflow-id:${workflowId || "unknown"}`,
1168
+ ...userId ? [`user-id:${userId}`] : []
1169
+ ]
1170
+ });
1171
+ }
1172
+ const result = contextManager.run(ctx, () => {
1173
+ return originalRun.apply(this, args);
1174
+ });
1175
+ if (result && typeof result.then === "function") {
1176
+ return result.then(
1177
+ (executionId) => {
1178
+ if (ctx.enable && typeof executionId === "string") {
1179
+ registerWorkflowExecutionTx(executionId, ctx.id);
1180
+ }
1181
+ return executionId;
1182
+ },
1183
+ (error) => {
1184
+ if (ctx.enable) {
1185
+ (0, import_jennifer5_agent9.releaseTransactionCtx)(ctx.id, {
1186
+ httpStatusCode: 500
1187
+ // Error
1188
+ });
1189
+ }
1190
+ throw error;
1191
+ }
1192
+ );
1193
+ }
1194
+ if (ctx.enable) {
1195
+ (0, import_jennifer5_agent9.releaseTransactionCtx)(ctx.id, {
1196
+ httpStatusCode: 200
1197
+ // Success
1198
+ });
1199
+ }
1200
+ return result;
1201
+ };
1202
+ wrapper[JENNIFER_WRAPPED5] = true;
1203
+ return wrapper;
1204
+ });
1205
+ }
1206
+
1207
+ // src/instrumentations/n8n-active-executions.ts
1208
+ var import_jennifer5_agent10 = require("@jennifersoft/jennifer5-agent");
1209
+ var JENNIFER_WRAPPED6 = /* @__PURE__ */ Symbol.for("jennifer.n8n.active-executions.wrapped");
1210
+ function patchN8nActiveExecutions(activeExecutionsModule, moduleName) {
1211
+ try {
1212
+ if (!activeExecutionsModule?.ActiveExecutions) {
1213
+ return;
1214
+ }
1215
+ instrumentActiveExecutions(activeExecutionsModule.ActiveExecutions);
1216
+ } catch (error) {
1217
+ (0, import_jennifer5_agent10.warn)(`Failed to register ${moduleName} ActiveExecutions instrumentation: ${error}`);
1218
+ }
1219
+ }
1220
+ function instrumentActiveExecutions(ActiveExecutionsClass) {
1221
+ const prototype = ActiveExecutionsClass.prototype;
1222
+ if (prototype?.finalizeExecution?.[JENNIFER_WRAPPED6]) {
1223
+ return;
1224
+ }
1225
+ wrap(prototype, "finalizeExecution", (originalFinalize) => {
1226
+ const wrapper = function(executionId, fullRunData) {
1227
+ const txId = typeof executionId === "string" ? takeWorkflowExecutionTx(executionId) : void 0;
1228
+ try {
1229
+ return originalFinalize.apply(this, arguments);
1230
+ } finally {
1231
+ if (txId !== void 0) {
1232
+ const isError = fullRunData?.status === "error";
1233
+ (0, import_jennifer5_agent10.releaseTransactionCtx)(txId, { httpStatusCode: isError ? 500 : 200 });
1234
+ }
1235
+ }
1236
+ };
1237
+ wrapper[JENNIFER_WRAPPED6] = true;
1238
+ return wrapper;
1239
+ });
1240
+ }
1241
+
1242
+ // src/instrumentations/mariadb.ts
1243
+ var import_jennifer5_agent12 = require("@jennifersoft/jennifer5-agent");
1244
+
1245
+ // src/instrumentations/db-utils.ts
1246
+ var import_jennifer5_agent11 = require("@jennifersoft/jennifer5-agent");
1247
+ function normalizeOptionalParams(value) {
1248
+ if (value === void 0 || typeof value === "function") {
1249
+ return void 0;
1250
+ }
1251
+ return value;
1252
+ }
1253
+ function buildSqlEndCtx(startCtx, error) {
1254
+ return {
1255
+ error: error ? {
1256
+ message: error?.message,
1257
+ stack: error?.stack
1258
+ } : void 0,
1259
+ id: startCtx?.id ?? 0,
1260
+ txId: startCtx?.txId ?? 0
1261
+ };
1262
+ }
1263
+ function releaseSqlProfile(startCtx, error) {
1264
+ (0, import_jennifer5_agent11.releaseSqlProfileCtx)(startCtx, buildSqlEndCtx(startCtx, error));
1265
+ }
1266
+ function buildDbConnectionEndCtx(startCtx, error) {
1267
+ return {
1268
+ error: error ? {
1269
+ message: error?.message,
1270
+ stack: error?.stack
1271
+ } : void 0,
1272
+ id: startCtx?.id ?? 0,
1273
+ txId: startCtx?.txId ?? 0
1274
+ };
1275
+ }
1276
+ function releaseDbConnectionProfile(startCtx, error) {
1277
+ (0, import_jennifer5_agent11.releaseDbConnectionProfileCtx)(startCtx, buildDbConnectionEndCtx(startCtx, error));
1278
+ }
1279
+ function toSqlParams(params, options) {
1280
+ if (params === void 0 || params === null) {
1281
+ return void 0;
1282
+ }
1283
+ if (Array.isArray(params)) {
1284
+ return params.map((value) => buildSqlParam(value, options));
1285
+ }
1286
+ if (typeof params === "object") {
1287
+ return Object.keys(params).map((key) => buildSqlParam(params[key], options));
1288
+ }
1289
+ return [buildSqlParam(params, options)];
1290
+ }
1291
+ function buildSqlParam(value, options) {
1292
+ const normalized = normalizeSqlParamValue(value, options);
1293
+ return {
1294
+ value: normalized.value,
1295
+ paramType: normalized.paramType
1296
+ };
1297
+ }
1298
+ function normalizeSqlParamValue(input, options) {
1299
+ const value = options?.unwrapValue ? options.unwrapValue(input) : input;
1300
+ const bigintAsNumeric = options?.bigintAsNumeric ?? true;
1301
+ if (value === null || value === void 0) {
1302
+ return { value: "null", paramType: import_jennifer5_agent11.SqlParamType.String };
1303
+ }
1304
+ if (typeof value === "number" && Number.isFinite(value)) {
1305
+ return { value: String(value), paramType: import_jennifer5_agent11.SqlParamType.Numeric };
1306
+ }
1307
+ if (typeof value === "bigint") {
1308
+ return {
1309
+ value: value.toString(),
1310
+ paramType: bigintAsNumeric ? import_jennifer5_agent11.SqlParamType.Numeric : import_jennifer5_agent11.SqlParamType.String
1311
+ };
1312
+ }
1313
+ if (typeof value === "boolean") {
1314
+ return { value: String(value), paramType: import_jennifer5_agent11.SqlParamType.String };
1315
+ }
1316
+ if (typeof value === "string") {
1317
+ return { value, paramType: import_jennifer5_agent11.SqlParamType.String };
1318
+ }
1319
+ if (value instanceof Date) {
1320
+ return { value: value.toISOString(), paramType: import_jennifer5_agent11.SqlParamType.String };
1321
+ }
1322
+ if (Buffer.isBuffer(value)) {
1323
+ return { value: `[Buffer len=${value.length}]`, paramType: import_jennifer5_agent11.SqlParamType.String };
1324
+ }
1325
+ if (typeof value === "function") {
1326
+ return { value: "[Function]", paramType: import_jennifer5_agent11.SqlParamType.String };
1327
+ }
1328
+ if (isStreamLike(value)) {
1329
+ return { value: "[Stream]", paramType: import_jennifer5_agent11.SqlParamType.String };
1330
+ }
1331
+ if (typeof value === "object") {
1332
+ try {
1333
+ return {
1334
+ value: JSON.stringify(value, jsonReplacer),
1335
+ paramType: import_jennifer5_agent11.SqlParamType.String
1336
+ };
1337
+ } catch {
1338
+ return {
1339
+ value: Object.prototype.toString.call(value),
1340
+ paramType: import_jennifer5_agent11.SqlParamType.String
1341
+ };
1342
+ }
1343
+ }
1344
+ return { value: String(value), paramType: import_jennifer5_agent11.SqlParamType.String };
1345
+ }
1346
+ function jsonReplacer(_key, input) {
1347
+ if (typeof input === "bigint") {
1348
+ return input.toString();
1349
+ }
1350
+ if (Buffer.isBuffer(input)) {
1351
+ return `[Buffer len=${input.length}]`;
1352
+ }
1353
+ if (typeof input === "function") {
1354
+ return "[Function]";
1355
+ }
1356
+ if (isStreamLike(input)) {
1357
+ return "[Stream]";
1358
+ }
1359
+ if (typeof input === "symbol") {
1360
+ return input.toString();
1361
+ }
1362
+ return input;
1363
+ }
1364
+ function isStreamLike(value) {
1365
+ return Boolean(
1366
+ value && typeof value === "object" && typeof value.pipe === "function" && typeof value.read === "function"
1367
+ );
1368
+ }
1369
+
1370
+ // src/instrumentations/mariadb.ts
1371
+ var JENNIFER_MARIADB_CREATE_CONNECTION_WRAPPED = /* @__PURE__ */ Symbol.for(
1372
+ "jennifer.mariadb.create.connection.wrapped"
1373
+ );
1374
+ var JENNIFER_MARIADB_QUERY_START_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.mariadb.query.start.wrapped");
1375
+ var JENNIFER_MARIADB_EXECUTE_START_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.mariadb.execute.start.wrapped");
1376
+ function patchMariadbModule(mariadbModule, moduleName) {
1377
+ try {
1378
+ if (instrumentCreateConnection(mariadbModule)) {
1379
+ (0, import_jennifer5_agent12.info)(`${moduleName}.createConnection instrumented`);
1380
+ }
1381
+ } catch (error) {
1382
+ (0, import_jennifer5_agent12.warn)(`Failed to register ${moduleName} instrumentation: ${error}`);
1383
+ }
1384
+ }
1385
+ function patchMariadbQueryCommandModule(queryCommandModule, moduleName) {
1386
+ try {
1387
+ if (instrumentCommandStart(
1388
+ queryCommandModule?.prototype,
1389
+ "start",
1390
+ import_jennifer5_agent12.SqlExecuteMethod.ExecuteQuery,
1391
+ JENNIFER_MARIADB_QUERY_START_WRAPPED
1392
+ )) {
1393
+ (0, import_jennifer5_agent12.info)(`${moduleName}.prototype.start instrumented`);
1394
+ }
1395
+ } catch (error) {
1396
+ (0, import_jennifer5_agent12.warn)(`Failed to register ${moduleName} instrumentation: ${error}`);
1397
+ }
1398
+ }
1399
+ function patchMariadbExecuteCommandModule(executeCommandModule, moduleName) {
1400
+ try {
1401
+ if (instrumentCommandStart(
1402
+ executeCommandModule?.prototype,
1403
+ "start",
1404
+ import_jennifer5_agent12.SqlExecuteMethod.Execute,
1405
+ JENNIFER_MARIADB_EXECUTE_START_WRAPPED
1406
+ )) {
1407
+ (0, import_jennifer5_agent12.info)(`${moduleName}.prototype.start instrumented`);
1408
+ }
1409
+ } catch (error) {
1410
+ (0, import_jennifer5_agent12.warn)(`Failed to register ${moduleName} instrumentation: ${error}`);
1411
+ }
1412
+ }
1413
+ function instrumentCommandStart(prototype, methodName, executeMethod, wrapMarker) {
1414
+ if (!prototype || typeof prototype[methodName] !== "function" || prototype[methodName]?.[wrapMarker]) {
1415
+ return false;
1416
+ }
1417
+ wrap(prototype, methodName, (originalMethod) => {
1418
+ const wrapper = function(...args) {
1419
+ const ctx = contextManager.getCurrentContext();
1420
+ if (!ctx || !ctx.enable || !(0, import_jennifer5_agent12.configEnableMariadbProfile)()) {
1421
+ return originalMethod.apply(this, args);
1422
+ }
1423
+ const sqlData = extractSqlAndParams(this);
1424
+ if (!sqlData?.sql) {
1425
+ return originalMethod.apply(this, args);
1426
+ }
1427
+ const startCtx = (0, import_jennifer5_agent12.createSqlProfileCtx)(
1428
+ sqlData.sql,
1429
+ executeMethod,
1430
+ extractBoundParameters(sqlData.params),
1431
+ ctx?.id
1432
+ );
1433
+ if (!startCtx) {
1434
+ return originalMethod.apply(this, args);
1435
+ }
1436
+ let isReleased = false;
1437
+ const releaseSuccess2 = () => {
1438
+ if (isReleased) {
1439
+ return;
1440
+ }
1441
+ isReleased = true;
1442
+ releaseSqlProfile(startCtx);
1443
+ };
1444
+ const releaseError = (error) => {
1445
+ if (isReleased) {
1446
+ return;
1447
+ }
1448
+ isReleased = true;
1449
+ releaseSqlProfile(startCtx, error);
1450
+ };
1451
+ const originalResolve = this?.resolve;
1452
+ if (typeof originalResolve === "function") {
1453
+ this.resolve = function(...resolveArgs) {
1454
+ releaseSuccess2();
1455
+ return originalResolve.apply(this, resolveArgs);
1456
+ };
1457
+ }
1458
+ const originalReject = this?.reject;
1459
+ if (typeof originalReject === "function") {
1460
+ this.reject = function(error, ...rejectArgs) {
1461
+ releaseError(error);
1462
+ return originalReject.call(this, error, ...rejectArgs);
1463
+ };
1464
+ }
1465
+ try {
1466
+ return originalMethod.apply(this, args);
1467
+ } catch (error) {
1468
+ releaseError(error);
1469
+ throw error;
1470
+ }
1471
+ };
1472
+ wrapper[wrapMarker] = true;
1473
+ return wrapper;
1474
+ });
1475
+ return true;
1476
+ }
1477
+ function instrumentCreateConnection(mariadbModule) {
1478
+ if (!mariadbModule || typeof mariadbModule.createConnection !== "function" || mariadbModule.createConnection?.[JENNIFER_MARIADB_CREATE_CONNECTION_WRAPPED]) {
1479
+ return false;
1480
+ }
1481
+ wrap(mariadbModule, "createConnection", (originalCreateConnection) => {
1482
+ const wrapper = function(...args) {
1483
+ const ctx = contextManager.getCurrentContext();
1484
+ if (!ctx || !ctx.enable || !(0, import_jennifer5_agent12.configEnableMariadbProfile)()) {
1485
+ return originalCreateConnection.apply(this, args);
1486
+ }
1487
+ const connectionInfo = extractConnectionInfo(args[0]);
1488
+ const startCtx = (0, import_jennifer5_agent12.createDbConnectionProfileCtx)(connectionInfo, void 0, ctx.id);
1489
+ try {
1490
+ const result = originalCreateConnection.apply(this, args);
1491
+ if (result && typeof result.then === "function") {
1492
+ return result.then(
1493
+ (connection) => {
1494
+ releaseDbConnectionProfile(startCtx);
1495
+ return connection;
1496
+ },
1497
+ (error) => {
1498
+ releaseDbConnectionProfile(startCtx, error);
1499
+ throw error;
1500
+ }
1501
+ );
1502
+ }
1503
+ releaseDbConnectionProfile(startCtx);
1504
+ return result;
1505
+ } catch (error) {
1506
+ releaseDbConnectionProfile(startCtx, error);
1507
+ throw error;
1508
+ }
1509
+ };
1510
+ wrapper[JENNIFER_MARIADB_CREATE_CONNECTION_WRAPPED] = true;
1511
+ return wrapper;
1512
+ });
1513
+ return true;
1514
+ }
1515
+ function extractSqlAndParams(command) {
1516
+ const sql = command?.sql;
1517
+ if (typeof sql !== "string") {
1518
+ return void 0;
1519
+ }
1520
+ return {
1521
+ sql,
1522
+ params: command?.initialValues
1523
+ };
1524
+ }
1525
+ function extractBoundParameters(params) {
1526
+ return toSqlParams(params);
1527
+ }
1528
+ function extractConnectionInfo(config) {
1529
+ if (!config) {
1530
+ return void 0;
1531
+ }
1532
+ if (typeof config === "string") {
1533
+ return parseMariadbConnectionString(config);
1534
+ }
1535
+ if (typeof config !== "object") {
1536
+ return void 0;
1537
+ }
1538
+ return {
1539
+ host: config.host || "localhost",
1540
+ port: config.port || 3306,
1541
+ user: config.user || "",
1542
+ database: config.database || ""
1543
+ };
1544
+ }
1545
+ function parseMariadbConnectionString(connectionString) {
1546
+ try {
1547
+ const parsed = new URL(connectionString);
1548
+ return {
1549
+ host: parsed.hostname || "localhost",
1550
+ port: parsed.port ? Number(parsed.port) : 3306,
1551
+ user: parsed.username || "",
1552
+ database: parsed.pathname ? parsed.pathname.replace(/^\/+/, "") : ""
1553
+ };
1554
+ } catch {
1555
+ return {
1556
+ host: "localhost",
1557
+ port: 3306,
1558
+ user: "",
1559
+ database: ""
1560
+ };
1561
+ }
1562
+ }
1563
+
1564
+ // src/instrumentations/mysql2.ts
1565
+ var import_jennifer5_agent13 = require("@jennifersoft/jennifer5-agent");
1566
+ var JENNIFER_WRAPPED7 = /* @__PURE__ */ Symbol.for("jennifer.mysql2.wrapped");
1567
+ var JENNIFER_QUERY_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.mysql2.query.wrapped");
1568
+ var JENNIFER_EXECUTE_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.mysql2.execute.wrapped");
1569
+ function patchMysql2PromiseModule(mysql2Module, moduleName) {
1570
+ patchMysql2CreateConnection(mysql2Module, moduleName, "promise");
1571
+ patchMysql2ConnectionPrototype(mysql2Module, moduleName);
1572
+ }
1573
+ function patchMysql2Module(mysql2Module, moduleName) {
1574
+ patchMysql2CreateConnection(mysql2Module, moduleName, "callback");
1575
+ patchMysql2ConnectionPrototype(mysql2Module, moduleName);
1576
+ }
1577
+ function patchMysql2CreateConnection(mysql2Module, moduleName, mode) {
1578
+ try {
1579
+ if (instrumentCreateConnection2(mysql2Module, mode)) {
1580
+ (0, import_jennifer5_agent13.info)(`${moduleName} instrumentation registered`);
1581
+ }
1582
+ } catch (error) {
1583
+ (0, import_jennifer5_agent13.warn)(`Failed to register ${moduleName} instrumentation: ${error}`);
1584
+ }
1585
+ }
1586
+ function patchMysql2ConnectionPrototype(mysql2Module, moduleName) {
1587
+ try {
1588
+ const instrumentedTargets = [];
1589
+ if (instrumentConnectionPrototype(mysql2Module?.Connection)) {
1590
+ instrumentedTargets.push("Connection.prototype");
1591
+ }
1592
+ if (instrumentConnectionPrototype(mysql2Module?.PoolConnection)) {
1593
+ instrumentedTargets.push("PoolConnection.prototype");
1594
+ }
1595
+ if (instrumentConnectionPrototype(mysql2Module?.Pool)) {
1596
+ instrumentedTargets.push("Pool.prototype");
1597
+ }
1598
+ if (instrumentedTargets.length > 0) {
1599
+ (0, import_jennifer5_agent13.info)(`${moduleName}.${instrumentedTargets.join(", ")} instrumented`);
1600
+ }
1601
+ } catch (error) {
1602
+ (0, import_jennifer5_agent13.warn)(`Failed to instrument ${moduleName} prototypes: ${error}`);
1603
+ }
1604
+ }
1605
+ function instrumentCreateConnection2(mysql2Module, mode) {
1606
+ if (typeof mysql2Module?.createConnection !== "function") {
1607
+ return false;
1608
+ }
1609
+ if (mysql2Module.createConnection?.[JENNIFER_WRAPPED7]) {
1610
+ return false;
1611
+ }
1612
+ wrap(mysql2Module, "createConnection", (originalCreateConnection) => {
1613
+ const wrapper = function(...args) {
1614
+ const ctx = contextManager.getCurrentContext();
1615
+ if (!ctx || !ctx.enable || !(0, import_jennifer5_agent13.configEnableMysql2Profile)()) {
1616
+ return originalCreateConnection.apply(this, args);
1617
+ }
1618
+ const connectionInfo = extractConnectionInfo2(args[0]);
1619
+ const startCtx = (0, import_jennifer5_agent13.createDbConnectionProfileCtx)(connectionInfo, void 0, ctx?.id);
1620
+ try {
1621
+ const result = originalCreateConnection.apply(this, args);
1622
+ if (mode === "callback") {
1623
+ instrumentConnectionPrototype(result);
1624
+ releaseDbConnectionProfile(startCtx);
1625
+ return result;
1626
+ }
1627
+ if (result && typeof result.then === "function") {
1628
+ return result.then(
1629
+ (connection) => {
1630
+ instrumentConnectionPrototype(connection?.connection ?? connection);
1631
+ releaseDbConnectionProfile(startCtx);
1632
+ return connection;
1633
+ },
1634
+ (error) => {
1635
+ releaseDbConnectionProfile(startCtx, error);
1636
+ throw error;
1637
+ }
1638
+ );
1639
+ }
1640
+ releaseDbConnectionProfile(startCtx);
1641
+ return result;
1642
+ } catch (error) {
1643
+ releaseDbConnectionProfile(startCtx, error);
1644
+ throw error;
1645
+ }
1646
+ };
1647
+ wrapper[JENNIFER_WRAPPED7] = true;
1648
+ return wrapper;
1649
+ });
1650
+ return true;
1651
+ }
1652
+ function instrumentConnectionPrototype(target) {
1653
+ const prototype = resolveConnectionPrototype(target);
1654
+ if (!prototype) {
1655
+ return false;
1656
+ }
1657
+ const queryInstrumented = instrumentSqlMethod(
1658
+ prototype,
1659
+ "query",
1660
+ import_jennifer5_agent13.SqlExecuteMethod.ExecuteQuery,
1661
+ JENNIFER_QUERY_WRAPPED
1662
+ );
1663
+ const executeInstrumented = instrumentSqlMethod(
1664
+ prototype,
1665
+ "execute",
1666
+ import_jennifer5_agent13.SqlExecuteMethod.Execute,
1667
+ JENNIFER_EXECUTE_WRAPPED
1668
+ );
1669
+ return queryInstrumented || executeInstrumented;
1670
+ }
1671
+ function resolveConnectionPrototype(target) {
1672
+ if (!target) {
1673
+ return void 0;
1674
+ }
1675
+ if (target.prototype) {
1676
+ return target.prototype;
1677
+ }
1678
+ return target.constructor?.prototype;
1679
+ }
1680
+ function instrumentSqlMethod(prototype, methodName, executeMethod, wrapMarker) {
1681
+ if (typeof prototype?.[methodName] !== "function" || prototype[methodName]?.[wrapMarker]) {
1682
+ return false;
1683
+ }
1684
+ wrap(prototype, methodName, (originalMethod) => {
1685
+ const wrapper = function(...args) {
1686
+ const ctx = contextManager.getCurrentContext();
1687
+ if (!ctx || !ctx.enable || !(0, import_jennifer5_agent13.configEnableMysql2Profile)()) {
1688
+ return originalMethod.apply(this, args);
1689
+ }
1690
+ const sqlData = extractSqlAndParams2(args);
1691
+ if (!sqlData?.sql) {
1692
+ return originalMethod.apply(this, args);
1693
+ }
1694
+ const startCtx = (0, import_jennifer5_agent13.createSqlProfileCtx)(
1695
+ sqlData.sql,
1696
+ executeMethod,
1697
+ extractBoundParameters2(sqlData.params),
1698
+ ctx?.id
1699
+ );
1700
+ if (!startCtx) {
1701
+ return originalMethod.apply(this, args);
1702
+ }
1703
+ let isReleased = false;
1704
+ const releaseSuccess2 = () => {
1705
+ if (isReleased) return;
1706
+ isReleased = true;
1707
+ releaseSqlProfile(startCtx);
1708
+ };
1709
+ const releaseError = (error) => {
1710
+ if (isReleased) return;
1711
+ isReleased = true;
1712
+ releaseSqlProfile(startCtx, error);
1713
+ };
1714
+ const lastArgIndex = args.length - 1;
1715
+ const hasCallback = lastArgIndex >= 0 && typeof args[lastArgIndex] === "function";
1716
+ if (hasCallback) {
1717
+ const originalCallback = args[lastArgIndex];
1718
+ args[lastArgIndex] = function(...callbackArgs) {
1719
+ releaseError(callbackArgs[0]);
1720
+ return contextManager.run(ctx, () => originalCallback.apply(this, callbackArgs));
1721
+ };
1722
+ }
1723
+ try {
1724
+ const result = originalMethod.apply(this, args);
1725
+ if (hasCallback) {
1726
+ return result;
1727
+ }
1728
+ if (result && typeof result.once === "function") {
1729
+ result.once("error", (error) => releaseError(error));
1730
+ result.once("end", () => releaseSuccess2());
1731
+ return result;
1732
+ }
1733
+ if (result && typeof result.then === "function") {
1734
+ return result.then(
1735
+ (value) => {
1736
+ releaseSuccess2();
1737
+ return value;
1738
+ },
1739
+ (error) => {
1740
+ releaseError(error);
1741
+ throw error;
1742
+ }
1743
+ );
1744
+ }
1745
+ releaseSuccess2();
1746
+ return result;
1747
+ } catch (error) {
1748
+ releaseError(error);
1749
+ throw error;
1750
+ }
1751
+ };
1752
+ wrapper[wrapMarker] = true;
1753
+ return wrapper;
1754
+ });
1755
+ return true;
1756
+ }
1757
+ function extractConnectionInfo2(config) {
1758
+ if (!config) {
1759
+ return void 0;
1760
+ }
1761
+ const normalizedConfig = typeof config === "object" ? config : {};
1762
+ return {
1763
+ host: normalizedConfig.host || "localhost",
1764
+ port: normalizedConfig.port || 3306,
1765
+ user: normalizedConfig.user || "",
1766
+ database: normalizedConfig.database || ""
1767
+ };
1768
+ }
1769
+ function extractSqlAndParams2(args) {
1770
+ if (!args.length) {
1771
+ return void 0;
1772
+ }
1773
+ const firstArg = args[0];
1774
+ const secondArg = args[1];
1775
+ if (typeof firstArg === "string") {
1776
+ return {
1777
+ sql: firstArg,
1778
+ params: normalizeOptionalParams(secondArg)
1779
+ };
1780
+ }
1781
+ if (firstArg && typeof firstArg === "object" && typeof firstArg.sql === "string") {
1782
+ const params = firstArg.values !== void 0 ? firstArg.values : normalizeOptionalParams(secondArg);
1783
+ return {
1784
+ sql: firstArg.sql,
1785
+ params
1786
+ };
1787
+ }
1788
+ return void 0;
1789
+ }
1790
+ function extractBoundParameters2(params) {
1791
+ return toSqlParams(params);
1792
+ }
1793
+
1794
+ // src/instrumentations/ioredis.ts
1795
+ var import_jennifer5_agent15 = require("@jennifersoft/jennifer5-agent");
1796
+
1797
+ // src/instrumentations/redis-utils.ts
1798
+ var import_jennifer5_agent14 = require("@jennifersoft/jennifer5-agent");
1799
+ function normalizeRedisCommandName(name) {
1800
+ if (typeof name === "string" && name) {
1801
+ return name.toUpperCase();
1802
+ }
1803
+ if (Buffer.isBuffer(name) && name.length > 0) {
1804
+ return name.toString("utf8").toUpperCase();
1805
+ }
1806
+ return void 0;
1807
+ }
1808
+ function isRedisCommandBlocked(commandName) {
1809
+ const blockedCommands = (0, import_jennifer5_agent14.configRedisCommandBlocklist)();
1810
+ if (!Array.isArray(blockedCommands) || blockedCommands.length === 0) {
1811
+ return false;
1812
+ }
1813
+ return blockedCommands.some((blockedCommand) => {
1814
+ if (typeof blockedCommand !== "string" || !blockedCommand) {
1815
+ return false;
1816
+ }
1817
+ return blockedCommand.toUpperCase() === commandName;
1818
+ });
1819
+ }
1820
+ function extractRedisMethodArguments(commandArgs, keyIndex) {
1821
+ if (!Array.isArray(commandArgs) || commandArgs.length <= keyIndex) {
1822
+ return [];
1823
+ }
1824
+ const key = stringifyRedisArgument(commandArgs[keyIndex]);
1825
+ return key ? [key] : [];
1826
+ }
1827
+ function stringifyRedisArgument(value) {
1828
+ if (value === void 0 || value === null) {
1829
+ return void 0;
1830
+ }
1831
+ if (Buffer.isBuffer(value)) {
1832
+ return `[Buffer len=${value.length}]`;
1833
+ }
1834
+ const normalized = String(value);
1835
+ const maxArgLen = 256;
1836
+ return normalized.length > maxArgLen ? `${normalized.slice(0, maxArgLen)}...` : normalized;
1837
+ }
1838
+
1839
+ // src/instrumentations/ioredis.ts
1840
+ var JENNIFER_IOREDIS_CONNECT_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.ioredis.connect.wrapped");
1841
+ var JENNIFER_IOREDIS_SEND_COMMAND_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.ioredis.sendCommand.wrapped");
1842
+ function patchIoredisModule(ioredisModule, moduleName) {
1843
+ try {
1844
+ const connectInstrumented = instrumentRedisConnect(ioredisModule);
1845
+ const commandInstrumented = instrumentRedisSendCommand(ioredisModule);
1846
+ if (connectInstrumented) {
1847
+ (0, import_jennifer5_agent15.info)(`${moduleName}.prototype.connect instrumented`);
1848
+ }
1849
+ if (commandInstrumented) {
1850
+ (0, import_jennifer5_agent15.info)(`${moduleName}.prototype.sendCommand instrumented`);
1851
+ }
1852
+ } catch (error) {
1853
+ (0, import_jennifer5_agent15.warn)(`Failed to register ${moduleName} instrumentation: ${error}`);
1854
+ }
1855
+ }
1856
+ function instrumentRedisConnect(ioredisModule) {
1857
+ const Redis = resolveRedisConstructor(ioredisModule);
1858
+ const prototype = Redis?.prototype;
1859
+ if (!prototype || typeof prototype.connect !== "function" || prototype.connect?.[JENNIFER_IOREDIS_CONNECT_WRAPPED]) {
1860
+ return false;
1861
+ }
1862
+ wrap(prototype, "connect", (originalConnect) => {
1863
+ const wrapper = function(...args) {
1864
+ const ctx = contextManager.getCurrentContext();
1865
+ if (!ctx || !ctx.enable || !(0, import_jennifer5_agent15.configEnableRedisProfile)()) {
1866
+ return originalConnect.apply(this, args);
1867
+ }
1868
+ const connectionString = buildRedisConnectionString(this?.options);
1869
+ const startCtx = (0, import_jennifer5_agent15.createDbConnectionProfileCtx)(void 0, connectionString, ctx.id);
1870
+ try {
1871
+ const result = originalConnect.apply(this, args);
1872
+ if (result && typeof result.then === "function") {
1873
+ return result.then(
1874
+ (value) => {
1875
+ releaseDbConnectionProfile(startCtx);
1876
+ return value;
1877
+ },
1878
+ (error) => {
1879
+ releaseDbConnectionProfile(startCtx, error);
1880
+ throw error;
1881
+ }
1882
+ );
1883
+ }
1884
+ releaseDbConnectionProfile(startCtx);
1885
+ return result;
1886
+ } catch (error) {
1887
+ releaseDbConnectionProfile(startCtx, error);
1888
+ throw error;
1889
+ }
1890
+ };
1891
+ wrapper[JENNIFER_IOREDIS_CONNECT_WRAPPED] = true;
1892
+ return wrapper;
1893
+ });
1894
+ return true;
1895
+ }
1896
+ function instrumentRedisSendCommand(ioredisModule) {
1897
+ const Redis = resolveRedisConstructor(ioredisModule);
1898
+ const prototype = Redis?.prototype;
1899
+ if (!prototype || typeof prototype.sendCommand !== "function" || prototype.sendCommand?.[JENNIFER_IOREDIS_SEND_COMMAND_WRAPPED]) {
1900
+ return false;
1901
+ }
1902
+ wrap(prototype, "sendCommand", (originalSendCommand) => {
1903
+ const wrapper = function(...args) {
1904
+ const ctx = contextManager.getCurrentContext();
1905
+ const command = args[0];
1906
+ const commandName = normalizeRedisCommandName(command?.name);
1907
+ if (!ctx || !ctx.enable || !(0, import_jennifer5_agent15.configEnableRedisProfile)() || !commandName || isRedisCommandBlocked(commandName)) {
1908
+ return originalSendCommand.apply(this, args);
1909
+ }
1910
+ const methodArgs = extractRedisMethodArguments(command?.args, 0);
1911
+ const startCtx = (0, import_jennifer5_agent15.createMethodProfileCtx)(`Redis.${commandName}`, methodArgs, ctx.id);
1912
+ if (!startCtx) {
1913
+ return originalSendCommand.apply(this, args);
1914
+ }
1915
+ let isReleased = false;
1916
+ const releaseSuccess2 = () => {
1917
+ if (isReleased) {
1918
+ return;
1919
+ }
1920
+ isReleased = true;
1921
+ (0, import_jennifer5_agent15.releaseMethodProfileCtx)(startCtx, {
1922
+ id: startCtx?.id ?? 0,
1923
+ txId: startCtx?.txId ?? 0
1924
+ });
1925
+ };
1926
+ const releaseError = (error) => {
1927
+ if (isReleased) {
1928
+ return;
1929
+ }
1930
+ isReleased = true;
1931
+ (0, import_jennifer5_agent15.releaseMethodProfileCtx)(startCtx, {
1932
+ id: startCtx?.id ?? 0,
1933
+ txId: startCtx?.txId ?? 0,
1934
+ error: error ? {
1935
+ message: error?.message,
1936
+ stack: error?.stack
1937
+ } : void 0
1938
+ });
1939
+ };
1940
+ try {
1941
+ const result = originalSendCommand.apply(this, args);
1942
+ if (result && typeof result.then === "function") {
1943
+ return result.then(
1944
+ (value) => {
1945
+ releaseSuccess2();
1946
+ return value;
1947
+ },
1948
+ (error) => {
1949
+ releaseError(error);
1950
+ throw error;
1951
+ }
1952
+ );
1953
+ }
1954
+ releaseSuccess2();
1955
+ return result;
1956
+ } catch (error) {
1957
+ releaseError(error);
1958
+ throw error;
1959
+ }
1960
+ };
1961
+ wrapper[JENNIFER_IOREDIS_SEND_COMMAND_WRAPPED] = true;
1962
+ return wrapper;
1963
+ });
1964
+ return true;
1965
+ }
1966
+ function resolveRedisConstructor(ioredisModule) {
1967
+ if (typeof ioredisModule === "function") {
1968
+ return ioredisModule;
1969
+ }
1970
+ if (typeof ioredisModule?.default === "function") {
1971
+ return ioredisModule.default;
1972
+ }
1973
+ if (typeof ioredisModule?.Redis === "function") {
1974
+ return ioredisModule.Redis;
1975
+ }
1976
+ return void 0;
1977
+ }
1978
+ function buildRedisConnectionString(options) {
1979
+ const { host, port, db } = extractConnectionOptions(options);
1980
+ return `datasource : redis://${host}:${port}/${db}`;
1981
+ }
1982
+ function extractConnectionOptions(options) {
1983
+ if (!options || typeof options !== "object") {
1984
+ return { host: "localhost", port: 6379, db: "0" };
1985
+ }
1986
+ const rawDb = options.db;
1987
+ const db = rawDb === void 0 || rawDb === null || rawDb === "" ? "0" : String(rawDb);
1988
+ return {
1989
+ host: options.host || options.sentinels?.[0]?.host || "localhost",
1990
+ port: Number(options.port || options.sentinels?.[0]?.port || 6379),
1991
+ db
1992
+ };
1993
+ }
1994
+
1995
+ // src/instrumentations/oracledb.ts
1996
+ var import_jennifer5_agent16 = require("@jennifersoft/jennifer5-agent");
1997
+ var JENNIFER_WRAPPED8 = /* @__PURE__ */ Symbol.for("jennifer.oracledb.wrapped");
1998
+ var JENNIFER_PROTO_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.oracledb.connection.prototype.wrapped");
1999
+ function patchOracleDbModule(oracledbModule, moduleName) {
2000
+ try {
2001
+ if (instrumentGetConnection(oracledbModule)) {
2002
+ (0, import_jennifer5_agent16.info)(`${moduleName}.getConnection instrumented`);
2003
+ }
2004
+ if (instrumentConnectionPrototype2(oracledbModule)) {
2005
+ (0, import_jennifer5_agent16.info)(`${moduleName}.Connection.prototype instrumented`);
2006
+ }
2007
+ } catch (error) {
2008
+ (0, import_jennifer5_agent16.warn)(`Failed to register ${moduleName} instrumentation: ${error}`);
2009
+ }
2010
+ }
2011
+ function instrumentGetConnection(oracledbModule) {
2012
+ if (oracledbModule.getConnection?.[JENNIFER_WRAPPED8]) {
2013
+ return false;
2014
+ }
2015
+ wrap(oracledbModule, "getConnection", (originalGetConnection) => {
2016
+ const wrapper = function(...args) {
2017
+ const config = args[0];
2018
+ const ctx = contextManager.getCurrentContext();
2019
+ if (!ctx || !ctx.enable || !(0, import_jennifer5_agent16.configEnableOracledbProfile)()) {
2020
+ return originalGetConnection.apply(this, args);
2021
+ }
2022
+ const connectionInfo = extractConnectionInfo3(config);
2023
+ const startCtx = (0, import_jennifer5_agent16.createDbConnectionProfileCtx)(connectionInfo, void 0, ctx?.id);
2024
+ const lastArgIndex = args.length - 1;
2025
+ const hasCallback = lastArgIndex >= 0 && typeof args[lastArgIndex] === "function";
2026
+ if (hasCallback) {
2027
+ const originalCallback = args[lastArgIndex];
2028
+ args[lastArgIndex] = function(error, connection) {
2029
+ releaseWithError(startCtx, error);
2030
+ return contextManager.run(ctx, () => originalCallback.call(this, error, connection));
2031
+ };
2032
+ }
2033
+ try {
2034
+ const connectionResult = originalGetConnection.apply(this, args);
2035
+ if (hasCallback) {
2036
+ return connectionResult;
2037
+ }
2038
+ if (connectionResult && typeof connectionResult.then === "function") {
2039
+ return handlePromise(connectionResult, startCtx);
2040
+ }
2041
+ releaseSuccess(startCtx);
2042
+ return connectionResult;
2043
+ } catch (error) {
2044
+ releaseWithError(startCtx, error);
2045
+ throw error;
2046
+ }
2047
+ };
2048
+ wrapper[JENNIFER_WRAPPED8] = true;
2049
+ return wrapper;
2050
+ });
2051
+ return true;
2052
+ }
2053
+ function handlePromise(connectionPromise, startCtx) {
2054
+ return connectionPromise.then(
2055
+ (connection) => {
2056
+ releaseSuccess(startCtx);
2057
+ return connection;
2058
+ },
2059
+ (error) => {
2060
+ releaseWithError(startCtx, error);
2061
+ throw error;
2062
+ }
2063
+ );
2064
+ }
2065
+ function releaseSuccess(startCtx) {
2066
+ releaseDbConnectionProfile(startCtx);
2067
+ }
2068
+ function releaseWithError(startCtx, error) {
2069
+ releaseDbConnectionProfile(startCtx, error);
2070
+ }
2071
+ function instrumentConnectionPrototype2(oracledbModule) {
2072
+ const connectionProto = oracledbModule?.Connection?.prototype;
2073
+ if (!connectionProto || connectionProto.execute?.[JENNIFER_PROTO_WRAPPED]) {
2074
+ return false;
2075
+ }
2076
+ wrap(connectionProto, "execute", (originalExecute) => {
2077
+ const wrapper = function(...args) {
2078
+ const ctx = contextManager.getCurrentContext();
2079
+ if (!ctx || !ctx.enable || !(0, import_jennifer5_agent16.configEnableOracledbProfile)()) {
2080
+ return originalExecute.apply(this, args);
2081
+ }
2082
+ const sql = typeof args[0] === "string" ? args[0] : void 0;
2083
+ if (!sql) {
2084
+ return originalExecute.apply(this, args);
2085
+ }
2086
+ const boundParameters = extractBoundParameters3(args[1]);
2087
+ const startCtx = (0, import_jennifer5_agent16.createSqlProfileCtx)(sql, import_jennifer5_agent16.SqlExecuteMethod.Execute, boundParameters, ctx?.id);
2088
+ if (!startCtx) {
2089
+ return originalExecute.apply(this, args);
2090
+ }
2091
+ const lastArgIndex = args.length - 1;
2092
+ const hasCallback = lastArgIndex >= 0 && typeof args[lastArgIndex] === "function";
2093
+ if (hasCallback) {
2094
+ const originalCallback = args[lastArgIndex];
2095
+ args[lastArgIndex] = function(error, result) {
2096
+ releaseSqlWithError(startCtx, error);
2097
+ return contextManager.run(ctx, () => originalCallback.call(this, error, result));
2098
+ };
2099
+ }
2100
+ try {
2101
+ const resultPromise = originalExecute.apply(this, args);
2102
+ if (hasCallback) {
2103
+ return resultPromise;
2104
+ }
2105
+ if (resultPromise && typeof resultPromise.then === "function") {
2106
+ return handleSqlPromise(resultPromise, startCtx);
2107
+ }
2108
+ releaseSqlSuccess(startCtx);
2109
+ return resultPromise;
2110
+ } catch (error) {
2111
+ releaseSqlWithError(startCtx, error);
2112
+ throw error;
2113
+ }
2114
+ };
2115
+ wrapper[JENNIFER_PROTO_WRAPPED] = true;
2116
+ return wrapper;
2117
+ });
2118
+ return true;
2119
+ }
2120
+ function handleSqlPromise(resultPromise, startCtx) {
2121
+ return resultPromise.then(
2122
+ (result) => {
2123
+ releaseSqlSuccess(startCtx);
2124
+ return result;
2125
+ },
2126
+ (error) => {
2127
+ releaseSqlWithError(startCtx, error);
2128
+ throw error;
2129
+ }
2130
+ );
2131
+ }
2132
+ function releaseSqlSuccess(startCtx) {
2133
+ releaseSqlProfile(startCtx);
2134
+ }
2135
+ function releaseSqlWithError(startCtx, error) {
2136
+ releaseSqlProfile(startCtx, error);
2137
+ }
2138
+ function extractBoundParameters3(binds) {
2139
+ if (!binds) {
2140
+ return void 0;
2141
+ }
2142
+ if (!Array.isArray(binds) && typeof binds !== "object") {
2143
+ return void 0;
2144
+ }
2145
+ return toSqlParams(binds, {
2146
+ unwrapValue: (value) => value && typeof value === "object" && "val" in value ? value.val : value
2147
+ });
2148
+ }
2149
+ function extractConnectionInfo3(config) {
2150
+ if (!config || typeof config === "function") {
2151
+ return getDefaultPoolInfo();
2152
+ }
2153
+ if (typeof config === "string") {
2154
+ if (isLikelyPoolAlias(config)) {
2155
+ return getPoolAliasInfo(config);
2156
+ }
2157
+ const parsed2 = parseOracleConnectString(config);
2158
+ return {
2159
+ host: parsed2.host,
2160
+ port: parsed2.port,
2161
+ user: "",
2162
+ database: parsed2.serviceName
2163
+ };
2164
+ }
2165
+ const connectString = typeof config.connectString === "string" ? config.connectString : "";
2166
+ const parsed = connectString ? parseOracleConnectString(connectString) : void 0;
2167
+ const poolAlias = typeof config.poolAlias === "string" ? config.poolAlias : "";
2168
+ if (!parsed && poolAlias) {
2169
+ return {
2170
+ ...getPoolAliasInfo(poolAlias),
2171
+ user: config.user || ""
2172
+ };
2173
+ }
2174
+ return {
2175
+ host: parsed?.host || "localhost",
2176
+ port: parsed?.port || 1521,
2177
+ user: config.user || "",
2178
+ database: parsed?.serviceName || ""
2179
+ };
2180
+ }
2181
+ function parseOracleConnectString(connectString) {
2182
+ if (!connectString) {
2183
+ return {
2184
+ host: "localhost",
2185
+ port: 1521,
2186
+ serviceName: ""
2187
+ };
2188
+ }
2189
+ const match = connectString.match(/^([^:/]+)(?::(\d+))?(?:\/([^\?]+))?/);
2190
+ if (match) {
2191
+ return {
2192
+ host: match[1] || "localhost",
2193
+ port: Number(match[2] || "1521"),
2194
+ serviceName: match[3] || ""
2195
+ };
2196
+ }
2197
+ return {
2198
+ host: connectString,
2199
+ port: 1521,
2200
+ serviceName: ""
2201
+ };
2202
+ }
2203
+ function isLikelyPoolAlias(value) {
2204
+ return !/[/:]/.test(value);
2205
+ }
2206
+ function getDefaultPoolInfo() {
2207
+ return getPoolAliasInfo("default");
2208
+ }
2209
+ function getPoolAliasInfo(alias) {
2210
+ return {
2211
+ host: `alias:${alias}`,
2212
+ port: 1521,
2213
+ user: "",
2214
+ database: ""
2215
+ };
2216
+ }
2217
+
2218
+ // src/instrumentations/pg.ts
2219
+ var import_jennifer5_agent17 = require("@jennifersoft/jennifer5-agent");
2220
+ var JENNIFER_PG_CLIENT_QUERY_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.pg.client.query.wrapped");
2221
+ function patchPgClientModule(clientModule, moduleName) {
2222
+ try {
2223
+ const clientPrototype = resolveClientPrototype(clientModule);
2224
+ if (!instrumentQueryMethod(clientPrototype, "query", JENNIFER_PG_CLIENT_QUERY_WRAPPED)) {
2225
+ return;
2226
+ }
2227
+ (0, import_jennifer5_agent17.info)(`${moduleName}.Client.prototype.query instrumented`);
2228
+ } catch (error) {
2229
+ (0, import_jennifer5_agent17.warn)(`Failed to register ${moduleName} instrumentation: ${error}`);
2230
+ }
2231
+ }
2232
+ function resolveClientPrototype(clientModule) {
2233
+ if (!clientModule) {
2234
+ return void 0;
2235
+ }
2236
+ if (clientModule?.Client?.prototype) {
2237
+ return clientModule.Client.prototype;
2238
+ }
2239
+ if (clientModule?.prototype) {
2240
+ return clientModule.prototype;
2241
+ }
2242
+ if (clientModule?.default?.prototype) {
2243
+ return clientModule.default.prototype;
2244
+ }
2245
+ if (clientModule?.default?.Client?.prototype) {
2246
+ return clientModule.default.Client.prototype;
2247
+ }
2248
+ return void 0;
2249
+ }
2250
+ function instrumentQueryMethod(prototype, methodName, wrapMarker) {
2251
+ if (!prototype || typeof prototype[methodName] !== "function" || prototype[methodName]?.[wrapMarker]) {
2252
+ return false;
2253
+ }
2254
+ wrap(prototype, methodName, (originalMethod) => {
2255
+ const wrapper = function(...args) {
2256
+ const ctx = contextManager.getCurrentContext();
2257
+ if (!ctx || !ctx.enable || !(0, import_jennifer5_agent17.configEnablePgProfile)()) {
2258
+ return originalMethod.apply(this, args);
2259
+ }
2260
+ const sqlData = extractSqlAndParams3(args);
2261
+ if (!sqlData?.sql) {
2262
+ return originalMethod.apply(this, args);
2263
+ }
2264
+ const startCtx = (0, import_jennifer5_agent17.createSqlProfileCtx)(
2265
+ sqlData.sql,
2266
+ import_jennifer5_agent17.SqlExecuteMethod.ExecuteQuery,
2267
+ extractBoundParameters4(sqlData.params),
2268
+ ctx?.id
2269
+ );
2270
+ if (!startCtx) {
2271
+ return originalMethod.apply(this, args);
2272
+ }
2273
+ let isReleased = false;
2274
+ const releaseSuccess2 = () => {
2275
+ if (isReleased) {
2276
+ return;
2277
+ }
2278
+ isReleased = true;
2279
+ releaseSqlProfile(startCtx);
2280
+ };
2281
+ const releaseError = (error) => {
2282
+ if (isReleased) {
2283
+ return;
2284
+ }
2285
+ isReleased = true;
2286
+ releaseSqlProfile(startCtx, error);
2287
+ };
2288
+ const lastArgIndex = args.length - 1;
2289
+ const hasCallback = lastArgIndex >= 0 && typeof args[lastArgIndex] === "function";
2290
+ if (hasCallback) {
2291
+ const originalCallback = args[lastArgIndex];
2292
+ args[lastArgIndex] = function(...callbackArgs) {
2293
+ const callbackError = callbackArgs[0];
2294
+ if (callbackError) {
2295
+ releaseError(callbackError);
2296
+ } else {
2297
+ releaseSuccess2();
2298
+ }
2299
+ return contextManager.run(ctx, () => originalCallback.apply(this, callbackArgs));
2300
+ };
2301
+ }
2302
+ try {
2303
+ const result = originalMethod.apply(this, args);
2304
+ if (hasCallback) {
2305
+ return result;
2306
+ }
2307
+ if (result && typeof result.then === "function") {
2308
+ return result.then(
2309
+ (value) => {
2310
+ releaseSuccess2();
2311
+ return value;
2312
+ },
2313
+ (error) => {
2314
+ releaseError(error);
2315
+ throw error;
2316
+ }
2317
+ );
2318
+ }
2319
+ if (result && typeof result.once === "function") {
2320
+ result.once("end", releaseSuccess2);
2321
+ result.once("error", releaseError);
2322
+ return result;
2323
+ }
2324
+ releaseSuccess2();
2325
+ return result;
2326
+ } catch (error) {
2327
+ releaseError(error);
2328
+ throw error;
2329
+ }
2330
+ };
2331
+ wrapper[wrapMarker] = true;
2332
+ return wrapper;
2333
+ });
2334
+ return true;
2335
+ }
2336
+ function extractSqlAndParams3(args) {
2337
+ if (!args.length) {
2338
+ return void 0;
2339
+ }
2340
+ const firstArg = args[0];
2341
+ const secondArg = args[1];
2342
+ if (firstArg && typeof firstArg === "object" && typeof firstArg.submit === "function") {
2343
+ return void 0;
2344
+ }
2345
+ if (typeof firstArg === "string") {
2346
+ return {
2347
+ sql: firstArg,
2348
+ params: normalizeOptionalParams(secondArg)
2349
+ };
2350
+ }
2351
+ if (firstArg && typeof firstArg === "object" && typeof firstArg.text === "string") {
2352
+ return {
2353
+ sql: firstArg.text,
2354
+ params: normalizeOptionalParams(firstArg.values)
2355
+ };
2356
+ }
2357
+ return void 0;
2358
+ }
2359
+ function extractBoundParameters4(params) {
2360
+ return toSqlParams(params);
2361
+ }
2362
+
2363
+ // src/instrumentations/prisma.ts
2364
+ var import_jennifer5_agent18 = require("@jennifersoft/jennifer5-agent");
2365
+ var JENNIFER_WRAPPED9 = /* @__PURE__ */ Symbol.for("jennifer.prisma.wrapped");
2366
+ var JENNIFER_INSTANCE_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.prisma.instance.wrapped");
2367
+ function patchPrismaModule(prismaModule, moduleName) {
2368
+ try {
2369
+ if (instrumentPrismaClient(prismaModule)) {
2370
+ (0, import_jennifer5_agent18.info)(`${moduleName}.PrismaClient instrumented`);
2371
+ }
2372
+ } catch (error) {
2373
+ (0, import_jennifer5_agent18.warn)(`Failed to register ${moduleName} instrumentation: ${error}`);
2374
+ }
2375
+ }
2376
+ function instrumentPrismaClient(prismaModule) {
2377
+ if (!prismaModule?.PrismaClient || prismaModule.PrismaClient[JENNIFER_WRAPPED9]) {
2378
+ return false;
2379
+ }
2380
+ wrap(prismaModule, "PrismaClient", (originalConstructor) => {
2381
+ const wrapper = function(...args) {
2382
+ const instance = Reflect.construct(originalConstructor, args);
2383
+ const patchedInstance = patchPrismaInstance(instance);
2384
+ return patchedInstance ?? instance;
2385
+ };
2386
+ wrapper[JENNIFER_WRAPPED9] = true;
2387
+ return wrapper;
2388
+ });
2389
+ return true;
2390
+ }
2391
+ function patchPrismaInstance(prismaInstance) {
2392
+ if (!prismaInstance || prismaInstance[JENNIFER_INSTANCE_WRAPPED]) {
2393
+ return prismaInstance;
2394
+ }
2395
+ prismaInstance[JENNIFER_INSTANCE_WRAPPED] = true;
2396
+ hookUseMiddleware(prismaInstance);
2397
+ return hookQueryExtension(prismaInstance) ?? prismaInstance;
2398
+ }
2399
+ function safeStringify(args) {
2400
+ if (!args) return "";
2401
+ try {
2402
+ const stringified = JSON.stringify(args);
2403
+ return stringified.length > 1e3 ? `${stringified.substring(0, 1e3)}...` : stringified;
2404
+ } catch {
2405
+ return "[Unserializable Args]";
2406
+ }
2407
+ }
2408
+ function hookUseMiddleware(prismaInstance) {
2409
+ if (typeof prismaInstance.$use !== "function") {
2410
+ return;
2411
+ }
2412
+ prismaInstance.$use(async (params, next) => {
2413
+ const ctx = contextManager.getCurrentContext();
2414
+ if (!ctx || !ctx.enable || !(0, import_jennifer5_agent18.configEnablePrismaProfile)()) {
2415
+ return next(params);
2416
+ }
2417
+ const modelName = params?.model;
2418
+ const action = params?.operation || params?.action || "unknown";
2419
+ const argsStr = safeStringify(params?.args);
2420
+ const queryInfo = modelName ? `Prisma ${modelName}.${action}`.trim() : `Prisma.${action}`.trim();
2421
+ const startCtx = (0, import_jennifer5_agent18.createSqlProfileCtx)(
2422
+ queryInfo,
2423
+ import_jennifer5_agent18.SqlExecuteMethod.Execute,
2424
+ [
2425
+ {
2426
+ value: argsStr,
2427
+ paramType: import_jennifer5_agent18.SqlParamType.String
2428
+ }
2429
+ ],
2430
+ ctx.id
2431
+ );
2432
+ if (!startCtx) {
2433
+ return next(params);
2434
+ }
2435
+ try {
2436
+ const result = await next(params);
2437
+ releaseSqlProfile(startCtx);
2438
+ return result;
2439
+ } catch (error) {
2440
+ releaseSqlProfile(startCtx, error);
2441
+ throw error;
2442
+ }
2443
+ });
2444
+ }
2445
+ function hookQueryExtension(prismaInstance) {
2446
+ if (typeof prismaInstance.$extends !== "function") {
2447
+ return prismaInstance;
2448
+ }
2449
+ const traceOperation = async (params) => {
2450
+ const ctx = contextManager.getCurrentContext();
2451
+ if (!ctx || !ctx.enable || !(0, import_jennifer5_agent18.configEnablePrismaProfile)()) {
2452
+ return params.query(params.args);
2453
+ }
2454
+ const modelName = params?.model;
2455
+ const action = params?.operation || params?.action || "unknown";
2456
+ const argsStr = safeStringify(params?.args);
2457
+ const queryInfo = modelName ? `Prisma ${modelName}.${action} ?`.trim() : `Prisma.${action} ?`.trim();
2458
+ const startCtx = (0, import_jennifer5_agent18.createSqlProfileCtx)(
2459
+ queryInfo,
2460
+ import_jennifer5_agent18.SqlExecuteMethod.Execute,
2461
+ [
2462
+ {
2463
+ value: argsStr,
2464
+ paramType: import_jennifer5_agent18.SqlParamType.String
2465
+ }
2466
+ ],
2467
+ ctx.id
2468
+ );
2469
+ if (!startCtx) {
2470
+ return params.query(params.args);
2471
+ }
2472
+ try {
2473
+ const result = await params.query(params.args);
2474
+ releaseSqlProfile(startCtx);
2475
+ return result;
2476
+ } catch (error) {
2477
+ releaseSqlProfile(startCtx, error);
2478
+ throw error;
2479
+ }
2480
+ };
2481
+ const extended = prismaInstance.$extends({
2482
+ query: {
2483
+ $allModels: {
2484
+ $allOperations: async (params) => traceOperation(params)
2485
+ },
2486
+ // Raw queries
2487
+ $queryRaw: async (params) => traceOperation(params),
2488
+ $executeRaw: async (params) => traceOperation(params),
2489
+ $queryRawUnsafe: async (params) => traceOperation(params),
2490
+ $executeRawUnsafe: async (params) => traceOperation(params)
2491
+ }
2492
+ });
2493
+ extended[JENNIFER_INSTANCE_WRAPPED] = true;
2494
+ return extended;
2495
+ }
2496
+
2497
+ // src/instrumentations/redis.ts
2498
+ var import_jennifer5_agent19 = require("@jennifersoft/jennifer5-agent");
2499
+ var JENNIFER_REDIS_CONNECT_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.redis.connect.wrapped");
2500
+ var JENNIFER_REDIS_ADD_COMMAND_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.redis.addCommand.wrapped");
2501
+ var JENNIFER_REDIS_CREATE_CLIENT_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.redis.createClient.wrapped");
2502
+ function patchRedisModule(redisModule, moduleName) {
2503
+ try {
2504
+ const instrumented = instrumentRedisCreateClient(redisModule);
2505
+ if (instrumented) {
2506
+ (0, import_jennifer5_agent19.info)(`${moduleName}.createClient instrumented`);
2507
+ }
2508
+ } catch (error) {
2509
+ (0, import_jennifer5_agent19.warn)(`Failed to register ${moduleName} instrumentation: ${error}`);
2510
+ }
2511
+ }
2512
+ function patchRedisCommandsQueueModule(redisCommandsQueueModule, moduleName) {
2513
+ try {
2514
+ const instrumented = instrumentRedisAddCommand(redisCommandsQueueModule);
2515
+ if (instrumented) {
2516
+ (0, import_jennifer5_agent19.info)(`${moduleName}.prototype.addCommand instrumented`);
2517
+ }
2518
+ } catch (error) {
2519
+ (0, import_jennifer5_agent19.warn)(`Failed to register ${moduleName} instrumentation: ${error}`);
2520
+ }
2521
+ }
2522
+ function instrumentRedisCreateClient(redisModule) {
2523
+ if (!redisModule || typeof redisModule.createClient !== "function" || redisModule.createClient[JENNIFER_REDIS_CREATE_CLIENT_WRAPPED]) {
2524
+ return false;
2525
+ }
2526
+ wrap(redisModule, "createClient", (originalCreateClient) => {
2527
+ const wrapper = function(...args) {
2528
+ const client = originalCreateClient.apply(this, args);
2529
+ instrumentRedisConnect2(client);
2530
+ return client;
2531
+ };
2532
+ wrapper[JENNIFER_REDIS_CREATE_CLIENT_WRAPPED] = true;
2533
+ return wrapper;
2534
+ });
2535
+ return true;
2536
+ }
2537
+ function instrumentRedisConnect2(client) {
2538
+ const prototype = resolveRedisConnectPrototype(client);
2539
+ if (!prototype || prototype.connect[JENNIFER_REDIS_CONNECT_WRAPPED]) {
2540
+ return false;
2541
+ }
2542
+ wrap(prototype, "connect", (originalConnect) => {
2543
+ const wrapper = function(...args) {
2544
+ const ctx = contextManager.getCurrentContext();
2545
+ if (!ctx || !ctx.enable || !(0, import_jennifer5_agent19.configEnableRedisProfile)()) {
2546
+ return originalConnect.apply(this, args);
2547
+ }
2548
+ const connectionString = buildRedisConnectionString2(this?.options);
2549
+ const startCtx = (0, import_jennifer5_agent19.createDbConnectionProfileCtx)(void 0, connectionString, ctx.id);
2550
+ try {
2551
+ const result = originalConnect.apply(this, args);
2552
+ if (result && typeof result.then === "function") {
2553
+ return result.then(
2554
+ (value) => {
2555
+ releaseDbConnectionProfile(startCtx);
2556
+ return value;
2557
+ },
2558
+ (error) => {
2559
+ releaseDbConnectionProfile(startCtx, error);
2560
+ throw error;
2561
+ }
2562
+ );
2563
+ }
2564
+ releaseDbConnectionProfile(startCtx);
2565
+ return result;
2566
+ } catch (error) {
2567
+ releaseDbConnectionProfile(startCtx, error);
2568
+ throw error;
2569
+ }
2570
+ };
2571
+ wrapper[JENNIFER_REDIS_CONNECT_WRAPPED] = true;
2572
+ return wrapper;
2573
+ });
2574
+ return true;
2575
+ }
2576
+ function instrumentRedisAddCommand(redisCommandsQueueModule) {
2577
+ const RedisCommandsQueue = resolveRedisCommandsQueueConstructor(redisCommandsQueueModule);
2578
+ const prototype = RedisCommandsQueue?.prototype;
2579
+ if (!prototype || typeof prototype.addCommand !== "function" || prototype.addCommand[JENNIFER_REDIS_ADD_COMMAND_WRAPPED]) {
2580
+ return false;
2581
+ }
2582
+ wrap(prototype, "addCommand", (originalAddCommand) => {
2583
+ const wrapper = function(...args) {
2584
+ const ctx = contextManager.getCurrentContext();
2585
+ const commandArgs = args[0];
2586
+ const commandName = normalizeRedisCommandName(commandArgs?.[0]);
2587
+ if (!ctx || !ctx.enable || !(0, import_jennifer5_agent19.configEnableRedisProfile)() || !commandName || isRedisCommandBlocked(commandName)) {
2588
+ return originalAddCommand.apply(this, args);
2589
+ }
2590
+ const methodArgs = extractRedisMethodArguments(commandArgs, 1);
2591
+ const startCtx = (0, import_jennifer5_agent19.createMethodProfileCtx)(`Redis.${commandName}`, methodArgs, ctx.id);
2592
+ if (!startCtx) {
2593
+ return originalAddCommand.apply(this, args);
2594
+ }
2595
+ let isReleased = false;
2596
+ const releaseSuccess2 = () => {
2597
+ if (isReleased) {
2598
+ return;
2599
+ }
2600
+ isReleased = true;
2601
+ (0, import_jennifer5_agent19.releaseMethodProfileCtx)(startCtx, {
2602
+ id: startCtx?.id ?? 0,
2603
+ txId: startCtx?.txId ?? 0
2604
+ });
2605
+ };
2606
+ const releaseError = (error) => {
2607
+ if (isReleased) {
2608
+ return;
2609
+ }
2610
+ isReleased = true;
2611
+ (0, import_jennifer5_agent19.releaseMethodProfileCtx)(startCtx, {
2612
+ id: startCtx?.id ?? 0,
2613
+ txId: startCtx?.txId ?? 0,
2614
+ error: error ? {
2615
+ message: error?.message,
2616
+ stack: error?.stack
2617
+ } : void 0
2618
+ });
2619
+ };
2620
+ try {
2621
+ const result = originalAddCommand.apply(this, args);
2622
+ if (result && typeof result.then === "function") {
2623
+ return result.then(
2624
+ (value) => {
2625
+ releaseSuccess2();
2626
+ return value;
2627
+ },
2628
+ (error) => {
2629
+ releaseError(error);
2630
+ throw error;
2631
+ }
2632
+ );
2633
+ }
2634
+ releaseSuccess2();
2635
+ return result;
2636
+ } catch (error) {
2637
+ releaseError(error);
2638
+ throw error;
2639
+ }
2640
+ };
2641
+ wrapper[JENNIFER_REDIS_ADD_COMMAND_WRAPPED] = true;
2642
+ return wrapper;
2643
+ });
2644
+ return true;
2645
+ }
2646
+ function resolveRedisConnectPrototype(client) {
2647
+ let current = client;
2648
+ while (current) {
2649
+ const descriptor = Object.getOwnPropertyDescriptor(current, "connect");
2650
+ if (descriptor && typeof descriptor.value === "function") {
2651
+ return current;
2652
+ }
2653
+ current = Object.getPrototypeOf(current);
2654
+ }
2655
+ return void 0;
2656
+ }
2657
+ function resolveRedisCommandsQueueConstructor(redisCommandsQueueModule) {
2658
+ if (typeof redisCommandsQueueModule === "function") {
2659
+ return redisCommandsQueueModule;
2660
+ }
2661
+ if (typeof redisCommandsQueueModule?.default === "function") {
2662
+ return redisCommandsQueueModule.default;
2663
+ }
2664
+ return void 0;
2665
+ }
2666
+ function buildRedisConnectionString2(options) {
2667
+ const socket = options?.socket;
2668
+ const host = socket?.host || options?.host || "localhost";
2669
+ const port = Number(socket?.port || options?.port || 6379);
2670
+ const rawDb = options?.database ?? options?.db ?? 0;
2671
+ const db = rawDb === void 0 || rawDb === null || rawDb === "" ? "0" : String(rawDb);
2672
+ return `datasource : redis://${host}:${port}/${db}`;
2673
+ }
2674
+
2675
+ // src/instrumentations/tedious.ts
2676
+ var import_jennifer5_agent20 = require("@jennifersoft/jennifer5-agent");
2677
+ var JENNIFER_TEDIOUS_MAKE_REQUEST_WRAPPED = /* @__PURE__ */ Symbol.for(
2678
+ "jennifer.tedious.connection.makeRequest.wrapped"
2679
+ );
2680
+ function patchTediousModule(tediousModule, moduleName) {
2681
+ try {
2682
+ if (instrumentConnectionPrototype3(tediousModule?.Connection?.prototype)) {
2683
+ (0, import_jennifer5_agent20.info)(`${moduleName}.Connection.prototype.makeRequest instrumented`);
2684
+ }
2685
+ } catch (error) {
2686
+ (0, import_jennifer5_agent20.warn)(`Failed to register ${moduleName} instrumentation: ${error}`);
2687
+ }
2688
+ }
2689
+ function instrumentConnectionPrototype3(connectionPrototype) {
2690
+ if (!connectionPrototype || typeof connectionPrototype.makeRequest !== "function" || connectionPrototype.makeRequest?.[JENNIFER_TEDIOUS_MAKE_REQUEST_WRAPPED]) {
2691
+ return false;
2692
+ }
2693
+ wrap(connectionPrototype, "makeRequest", (originalMakeRequest) => {
2694
+ const wrapper = function(request, ...args) {
2695
+ const ctx = contextManager.getCurrentContext();
2696
+ if (!ctx || !ctx.enable || !(0, import_jennifer5_agent20.configEnableTediousProfile)()) {
2697
+ return originalMakeRequest.call(this, request, ...args);
2698
+ }
2699
+ const sqlInfo = extractSqlInfo(request);
2700
+ if (!sqlInfo?.sql) {
2701
+ return originalMakeRequest.call(this, request, ...args);
2702
+ }
2703
+ const startCtx = (0, import_jennifer5_agent20.createSqlProfileCtx)(
2704
+ sqlInfo.sql,
2705
+ import_jennifer5_agent20.SqlExecuteMethod.Execute,
2706
+ extractBoundParameters5(request),
2707
+ ctx?.id
2708
+ );
2709
+ if (!startCtx) {
2710
+ return originalMakeRequest.call(this, request, ...args);
2711
+ }
2712
+ let isReleased = false;
2713
+ const releaseSuccess2 = () => {
2714
+ if (isReleased) {
2715
+ return;
2716
+ }
2717
+ isReleased = true;
2718
+ releaseSqlProfile(startCtx);
2719
+ };
2720
+ const releaseError = (error) => {
2721
+ if (isReleased) {
2722
+ return;
2723
+ }
2724
+ isReleased = true;
2725
+ releaseSqlProfile(startCtx, error);
2726
+ };
2727
+ const originalCallback = request?.callback;
2728
+ if (typeof originalCallback === "function") {
2729
+ request.callback = function(error, ...callbackArgs) {
2730
+ if (error) {
2731
+ releaseError(error);
2732
+ } else {
2733
+ releaseSuccess2();
2734
+ }
2735
+ return contextManager.run(ctx, () => originalCallback.call(this, error, ...callbackArgs));
2736
+ };
2737
+ }
2738
+ try {
2739
+ const result = originalMakeRequest.call(this, request, ...args);
2740
+ if (typeof originalCallback !== "function") {
2741
+ releaseSuccess2();
2742
+ }
2743
+ return result;
2744
+ } catch (error) {
2745
+ releaseError(error);
2746
+ throw error;
2747
+ }
2748
+ };
2749
+ wrapper[JENNIFER_TEDIOUS_MAKE_REQUEST_WRAPPED] = true;
2750
+ return wrapper;
2751
+ });
2752
+ return true;
2753
+ }
2754
+ function extractSqlInfo(request) {
2755
+ if (!request || typeof request !== "object") {
2756
+ return void 0;
2757
+ }
2758
+ const statement = request?.parametersByName?.statement;
2759
+ if (statement && typeof statement.value === "string") {
2760
+ return { sql: statement.value, sqlContainer: statement, sqlField: "value" };
2761
+ }
2762
+ const stmt = request?.parametersByName?.stmt;
2763
+ if (stmt && typeof stmt.value === "string") {
2764
+ return { sql: stmt.value, sqlContainer: stmt, sqlField: "value" };
2765
+ }
2766
+ if (typeof request.sqlTextOrProcedure === "string") {
2767
+ return {
2768
+ sql: request.sqlTextOrProcedure,
2769
+ sqlContainer: request,
2770
+ sqlField: "sqlTextOrProcedure"
2771
+ };
2772
+ }
2773
+ return void 0;
2774
+ }
2775
+ function extractBoundParameters5(request) {
2776
+ const parameters = request?.parameters;
2777
+ if (!Array.isArray(parameters) || parameters.length === 0) {
2778
+ return void 0;
2779
+ }
2780
+ const values = parameters.filter((parameter) => parameter && typeof parameter === "object").map((parameter) => parameter.value);
2781
+ return toSqlParams(values);
2782
+ }
2783
+
2784
+ // src/instrumentations/typeorm.ts
2785
+ var import_jennifer5_agent21 = require("@jennifersoft/jennifer5-agent");
2786
+ var JENNIFER_DATASOURCE_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.typeorm.datasource.wrapped");
2787
+ var JENNIFER_QUERYRUNNER_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.typeorm.queryrunner.wrapped");
2788
+ function patchTypeormModule(typeormModule, moduleName) {
2789
+ try {
2790
+ if (instrumentDataSource(typeormModule?.DataSource)) {
2791
+ (0, import_jennifer5_agent21.info)(`${moduleName}.DataSource instrumented`);
2792
+ }
2793
+ } catch (error) {
2794
+ (0, import_jennifer5_agent21.warn)(`Failed to register ${moduleName} instrumentation: ${error}`);
2795
+ }
2796
+ }
2797
+ function instrumentDataSource(dataSourceClass) {
2798
+ const prototype = dataSourceClass?.prototype;
2799
+ if (!prototype || prototype.createQueryRunner?.[JENNIFER_DATASOURCE_WRAPPED]) {
2800
+ return false;
2801
+ }
2802
+ wrap(prototype, "createQueryRunner", (originalCreateQueryRunner) => {
2803
+ const wrapper = function(...args) {
2804
+ const queryRunner = originalCreateQueryRunner.apply(this, args);
2805
+ instrumentQueryRunner(queryRunner);
2806
+ return queryRunner;
2807
+ };
2808
+ wrapper[JENNIFER_DATASOURCE_WRAPPED] = true;
2809
+ return wrapper;
2810
+ });
2811
+ return true;
2812
+ }
2813
+ function instrumentQueryRunner(queryRunner) {
2814
+ if (!queryRunner || typeof queryRunner.query !== "function" || queryRunner.query?.[JENNIFER_QUERYRUNNER_WRAPPED]) {
2815
+ return;
2816
+ }
2817
+ wrap(queryRunner, "query", (originalQuery) => {
2818
+ const wrapper = function(...args) {
2819
+ const ctx = contextManager.getCurrentContext();
2820
+ if (!ctx || !ctx.enable || !(0, import_jennifer5_agent21.configEnableTypeormProfile)()) {
2821
+ return originalQuery.apply(this, args);
2822
+ }
2823
+ const sql = args[0];
2824
+ if (typeof sql !== "string") {
2825
+ return originalQuery.apply(this, args);
2826
+ }
2827
+ const params = extractBoundParameters6(args[1]);
2828
+ const startCtx = (0, import_jennifer5_agent21.createSqlProfileCtx)(sql, import_jennifer5_agent21.SqlExecuteMethod.Execute, params, ctx?.id);
2829
+ if (!startCtx) {
2830
+ return originalQuery.apply(this, args);
2831
+ }
2832
+ try {
2833
+ const result = originalQuery.apply(this, args);
2834
+ if (result && typeof result.then === "function") {
2835
+ return result.then(
2836
+ (value) => {
2837
+ releaseSqlProfile(startCtx);
2838
+ return value;
2839
+ },
2840
+ (error) => {
2841
+ releaseSqlProfile(startCtx, error);
2842
+ throw error;
2843
+ }
2844
+ );
2845
+ }
2846
+ releaseSqlProfile(startCtx);
2847
+ return result;
2848
+ } catch (error) {
2849
+ releaseSqlProfile(startCtx, error);
2850
+ throw error;
2851
+ }
2852
+ };
2853
+ wrapper[JENNIFER_QUERYRUNNER_WRAPPED] = true;
2854
+ return wrapper;
2855
+ });
2856
+ }
2857
+ function extractBoundParameters6(params) {
2858
+ return toSqlParams(params);
2859
+ }
2860
+
2861
+ // src/instrumentations/undici.ts
2862
+ var import_jennifer5_agent22 = require("@jennifersoft/jennifer5-agent");
2863
+ var JENNIFER_UNDICI_FETCH_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.undici.fetch.wrapped");
2864
+ var JENNIFER_UNDICI_REQUEST_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.undici.request.wrapped");
2865
+ var X_DOMAIN_ID2 = "x-domainid";
2866
+ var X_AGENT_ID2 = "x-agentid";
2867
+ function resolveHeadersCtor(undiciModule) {
2868
+ return undiciModule.Headers ?? globalThis.Headers;
2869
+ }
2870
+ function resolveRequestCtor(undiciModule) {
2871
+ return undiciModule.Request ?? globalThis.Request;
2872
+ }
2873
+ function patchUndiciModule(undiciModule, moduleName) {
2874
+ try {
2875
+ let patched = false;
2876
+ if (typeof undiciModule?.fetch === "function" && !undiciModule.fetch[JENNIFER_UNDICI_FETCH_WRAPPED]) {
2877
+ wrap(undiciModule, "fetch", (originalFetch) => {
2878
+ const wrapper = createUndiciFetchWrapper(originalFetch, undiciModule);
2879
+ wrapper[JENNIFER_UNDICI_FETCH_WRAPPED] = true;
2880
+ return wrapper;
2881
+ });
2882
+ patched = true;
2883
+ }
2884
+ if (typeof undiciModule?.request === "function" && !undiciModule.request[JENNIFER_UNDICI_REQUEST_WRAPPED]) {
2885
+ wrap(undiciModule, "request", (originalRequest) => {
2886
+ const wrapper = createUndiciRequestWrapper(
2887
+ originalRequest,
2888
+ resolveHeadersCtor(undiciModule)
2889
+ );
2890
+ wrapper[JENNIFER_UNDICI_REQUEST_WRAPPED] = true;
2891
+ return wrapper;
2892
+ });
2893
+ patched = true;
2894
+ }
2895
+ if (patched) {
2896
+ (0, import_jennifer5_agent22.info)(`${moduleName} instrumentation registered`);
2897
+ }
2898
+ } catch (error) {
2899
+ (0, import_jennifer5_agent22.warn)(`Failed to register ${moduleName} instrumentation: ${error}`);
2900
+ }
2901
+ }
2902
+ function createUndiciFetchWrapper(originalFetch, undiciModule) {
2903
+ return function(...args) {
2904
+ const ctx = contextManager.getCurrentContext();
2905
+ if (!ctx || !ctx.enable || !(0, import_jennifer5_agent22.configEnableHttpClientProfile)()) {
2906
+ return originalFetch(...args);
2907
+ }
2908
+ const [input, init] = args;
2909
+ const HeadersCtor = resolveHeadersCtor(undiciModule);
2910
+ const RequestCtor = resolveRequestCtor(undiciModule);
2911
+ let startCtx = null;
2912
+ try {
2913
+ if (RequestCtor && input instanceof RequestCtor) {
2914
+ const normalizedRequest = init ? new RequestCtor(input, init) : input;
2915
+ const fetchHeaders2 = toHeaders(normalizedRequest.headers, HeadersCtor);
2916
+ setTopologyFetchHeaders(fetchHeaders2);
2917
+ const headers2 = headersToRecord(fetchHeaders2);
2918
+ const wrappedRequest = new RequestCtor(normalizedRequest, { headers: fetchHeaders2 });
2919
+ startCtx = (0, import_jennifer5_agent22.createHttpProfileCtx)(
2920
+ normalizedRequest.method || "GET",
2921
+ normalizedRequest.url,
2922
+ headers2,
2923
+ ctx.id
2924
+ );
2925
+ return handleFetchResult(originalFetch(wrappedRequest), startCtx);
2926
+ }
2927
+ const url = typeof input === "string" ? input : input?.href || String(input);
2928
+ const method = init?.method || "GET";
2929
+ const fetchHeaders = toHeaders(init?.headers, HeadersCtor);
2930
+ setTopologyFetchHeaders(fetchHeaders);
2931
+ const headers = headersToRecord(fetchHeaders);
2932
+ const modifiedInit = {
2933
+ ...init,
2934
+ headers: fetchHeaders
2935
+ };
2936
+ startCtx = (0, import_jennifer5_agent22.createHttpProfileCtx)(method, url, headers, ctx.id);
2937
+ return handleFetchResult(originalFetch(input, modifiedInit), startCtx);
2938
+ } catch (error) {
2939
+ (0, import_jennifer5_agent22.releaseHttpProfileCtx)(startCtx, {
2940
+ error: {
2941
+ message: error?.message,
2942
+ stack: error?.stack
2943
+ }
2944
+ });
2945
+ throw error;
2946
+ }
2947
+ };
2948
+ }
2949
+ function handleFetchResult(result, startCtx) {
2950
+ return result.then(
2951
+ (response) => {
2952
+ const contentLength = response.headers.get("content-length");
2953
+ const responseSize = contentLength ? parseInt(contentLength, 10) : void 0;
2954
+ const remoteCallInfo = getTopologyInfoFromFetch(response);
2955
+ (0, import_jennifer5_agent22.releaseHttpProfileCtx)(startCtx, {
2956
+ statusCode: response.status,
2957
+ responseSize,
2958
+ remoteCallInfo
2959
+ });
2960
+ return response;
2961
+ },
2962
+ (error) => {
2963
+ (0, import_jennifer5_agent22.releaseHttpProfileCtx)(startCtx, {
2964
+ error: {
2965
+ message: error?.message,
2966
+ stack: error?.stack
2967
+ }
2968
+ });
2969
+ throw error;
2970
+ }
2971
+ );
2972
+ }
2973
+ function createUndiciRequestWrapper(originalRequest, HeadersCtor) {
2974
+ return function(...args) {
2975
+ const ctx = contextManager.getCurrentContext();
2976
+ if (!ctx || !ctx.enable || !(0, import_jennifer5_agent22.configEnableHttpClientProfile)()) {
2977
+ return originalRequest(...args);
2978
+ }
2979
+ const { callArgs, method, url, headers } = normalizeUndiciRequestCall(args, HeadersCtor);
2980
+ const startCtx = (0, import_jennifer5_agent22.createHttpProfileCtx)(method, url, headers, ctx.id);
2981
+ try {
2982
+ return originalRequest(...callArgs).then(
2983
+ (response) => {
2984
+ const responseSize = getResponseSizeFromUndiciHeaders(response?.headers);
2985
+ const remoteCallInfo = getTopologyInfoFromUndiciHeaders(response?.headers);
2986
+ (0, import_jennifer5_agent22.releaseHttpProfileCtx)(startCtx, {
2987
+ statusCode: response?.statusCode,
2988
+ responseSize,
2989
+ remoteCallInfo
2990
+ });
2991
+ return response;
2992
+ },
2993
+ (error) => {
2994
+ (0, import_jennifer5_agent22.releaseHttpProfileCtx)(startCtx, {
2995
+ error: {
2996
+ message: error?.message,
2997
+ stack: error?.stack
2998
+ }
2999
+ });
3000
+ throw error;
3001
+ }
3002
+ );
3003
+ } catch (error) {
3004
+ (0, import_jennifer5_agent22.releaseHttpProfileCtx)(startCtx, {
3005
+ error: {
3006
+ message: error?.message,
3007
+ stack: error?.stack
3008
+ }
3009
+ });
3010
+ throw error;
3011
+ }
3012
+ };
3013
+ }
3014
+ function normalizeUndiciRequestCall(args, HeadersCtor) {
3015
+ const [firstArg, secondArg] = args;
3016
+ if (typeof firstArg === "string" || firstArg instanceof URL) {
3017
+ const options = secondArg && typeof secondArg === "object" ? secondArg : {};
3018
+ const requestHeaders = toHeaders(options.headers, HeadersCtor);
3019
+ setTopologyFetchHeaders(requestHeaders);
3020
+ const headersRecord = headersToRecord(requestHeaders);
3021
+ const callArgs = [
3022
+ firstArg,
3023
+ {
3024
+ ...options,
3025
+ headers: headersRecord
3026
+ }
3027
+ ];
3028
+ return {
3029
+ callArgs,
3030
+ method: options.method || "GET",
3031
+ url: typeof firstArg === "string" ? firstArg : firstArg.href,
3032
+ headers: headersRecord
3033
+ };
3034
+ }
3035
+ if (firstArg && typeof firstArg === "object") {
3036
+ const requestHeaders = toHeaders(firstArg.headers, HeadersCtor);
3037
+ setTopologyFetchHeaders(requestHeaders);
3038
+ const headersRecord = headersToRecord(requestHeaders);
3039
+ const callArg = {
3040
+ ...firstArg,
3041
+ headers: headersRecord
3042
+ };
3043
+ return {
3044
+ callArgs: [callArg],
3045
+ method: firstArg.method || "GET",
3046
+ url: getRequestUrlFromOptions(firstArg),
3047
+ headers: headersRecord
3048
+ };
3049
+ }
3050
+ return {
3051
+ callArgs: args,
3052
+ method: "GET",
3053
+ url: String(firstArg),
3054
+ headers: {}
3055
+ };
3056
+ }
3057
+ function getRequestUrlFromOptions(options) {
3058
+ if (!options || typeof options !== "object") {
3059
+ return String(options);
3060
+ }
3061
+ if (typeof options.href === "string") {
3062
+ return options.href;
3063
+ }
3064
+ if (typeof options.origin === "string" && typeof options.path === "string") {
3065
+ return `${options.origin}${options.path}`;
3066
+ }
3067
+ if (options.origin instanceof URL && typeof options.path === "string") {
3068
+ return `${options.origin.href.replace(/\/$/, "")}${options.path}`;
3069
+ }
3070
+ if (typeof options.path === "string") {
3071
+ return options.path;
3072
+ }
3073
+ return "[undici.request]";
3074
+ }
3075
+ function toHeaders(input, HeadersCtor) {
3076
+ const headers = new HeadersCtor();
3077
+ if (!input) {
3078
+ return headers;
3079
+ }
3080
+ try {
3081
+ if (input instanceof HeadersCtor) {
3082
+ input.forEach((value, key) => {
3083
+ headers.append(key, value);
3084
+ });
3085
+ return headers;
3086
+ }
3087
+ } catch {
3088
+ }
3089
+ if (Array.isArray(input)) {
3090
+ for (const entry of input) {
3091
+ if (!Array.isArray(entry) || entry.length < 2) {
3092
+ continue;
3093
+ }
3094
+ headers.append(String(entry[0]), String(entry[1]));
3095
+ }
3096
+ return headers;
3097
+ }
3098
+ if (typeof input === "object") {
3099
+ for (const [key, value] of Object.entries(input)) {
3100
+ if (value === void 0 || value === null) {
3101
+ continue;
3102
+ }
3103
+ if (Array.isArray(value)) {
3104
+ headers.set(key, value.map(String).join(", "));
3105
+ } else {
3106
+ headers.set(key, String(value));
3107
+ }
3108
+ }
3109
+ return headers;
3110
+ }
3111
+ return headers;
3112
+ }
3113
+ function headersToRecord(headers) {
3114
+ const record = {};
3115
+ headers.forEach((value, key) => {
3116
+ record[key] = value;
3117
+ });
3118
+ return record;
3119
+ }
3120
+ function getResponseSizeFromUndiciHeaders(headers) {
3121
+ const contentLength = getHeaderValue(headers, "content-length");
3122
+ if (!contentLength) {
3123
+ return void 0;
3124
+ }
3125
+ const parsed = Number(contentLength);
3126
+ return Number.isNaN(parsed) ? void 0 : parsed;
3127
+ }
3128
+ function getTopologyInfoFromUndiciHeaders(headers) {
3129
+ if (!(0, import_jennifer5_agent22.configEnableHttpTopologyMode)()) {
3130
+ return void 0;
3131
+ }
3132
+ const topologyHeaderKey = (0, import_jennifer5_agent22.configTopologyHttpHeaderKey)();
3133
+ const remoteCallKey = parseNumber2(getHeaderValue(headers, topologyHeaderKey));
3134
+ const sid = parseNumber2(getHeaderValue(headers, X_DOMAIN_ID2));
3135
+ const oid = parseNumber2(getHeaderValue(headers, X_AGENT_ID2));
3136
+ if ([remoteCallKey, sid, oid].some((v) => v === void 0)) {
3137
+ return void 0;
3138
+ }
3139
+ if (!(0, import_jennifer5_agent22.isAgentId)(oid)) {
3140
+ return void 0;
3141
+ }
3142
+ return {
3143
+ remoteCallKey,
3144
+ domainId: sid,
3145
+ oid
3146
+ };
3147
+ }
3148
+ function getHeaderValue(headers, key) {
3149
+ if (!headers) {
3150
+ return void 0;
3151
+ }
3152
+ const value = headers[key.toLowerCase()] ?? headers[key];
3153
+ if (Array.isArray(value)) {
3154
+ return value[0];
3155
+ }
3156
+ return typeof value === "string" ? value : void 0;
3157
+ }
3158
+ function parseNumber2(value) {
3159
+ if (!value) {
3160
+ return void 0;
3161
+ }
3162
+ const parsed = Number(value);
3163
+ return Number.isNaN(parsed) ? void 0 : parsed;
3164
+ }
3165
+
3166
+ // src/instrumentations/register-ritm.ts
3167
+ function registerHook(definition) {
3168
+ new import_require_in_the_middle.Hook(definition.modules, (module2, moduleName) => {
3169
+ for (const patch of definition.patches) {
3170
+ patch(module2, moduleName);
3171
+ }
3172
+ return module2;
3173
+ });
3174
+ }
3175
+ function registerRitmHooks() {
3176
+ const hookDefinitions = [
3177
+ {
3178
+ modules: ["http", "https", "node:http", "node:https"],
3179
+ patches: [patchHttpServer, patchHttpClient]
3180
+ },
3181
+ {
3182
+ modules: ["@apollo/server"],
3183
+ patches: [patchApolloServerModule]
3184
+ },
3185
+ {
3186
+ modules: ["fs", "node:fs"],
3187
+ patches: [patchFsSync, patchFsAsync, patchFsPromise]
3188
+ },
3189
+ {
3190
+ modules: ["mariadb", "mariadb/callback.js"],
3191
+ patches: [patchMariadbModule]
3192
+ },
3193
+ {
3194
+ modules: ["mariadb/lib/cmd/query.js", "mariadb/lib/cmd/query"],
3195
+ patches: [patchMariadbQueryCommandModule]
3196
+ },
3197
+ {
3198
+ modules: ["mariadb/lib/cmd/execute.js", "mariadb/lib/cmd/execute"],
3199
+ patches: [patchMariadbExecuteCommandModule]
3200
+ },
3201
+ {
3202
+ modules: ["mysql2/promise"],
3203
+ patches: [patchMysql2PromiseModule]
3204
+ },
3205
+ {
3206
+ modules: ["mysql2"],
3207
+ patches: [patchMysql2Module]
3208
+ },
3209
+ {
3210
+ modules: ["ioredis"],
3211
+ patches: [patchIoredisModule]
3212
+ },
3213
+ {
3214
+ modules: ["redis"],
3215
+ patches: [patchRedisModule]
3216
+ },
3217
+ {
3218
+ modules: [
3219
+ "@redis/client/dist/lib/client/commands-queue.js",
3220
+ "@redis/client/dist/lib/client/commands-queue"
3221
+ ],
3222
+ patches: [patchRedisCommandsQueueModule]
3223
+ },
3224
+ {
3225
+ modules: ["oracledb"],
3226
+ patches: [patchOracleDbModule]
3227
+ },
3228
+ {
3229
+ modules: ["pg/lib/client.js", "pg/lib/client"],
3230
+ patches: [patchPgClientModule]
3231
+ },
3232
+ {
3233
+ modules: ["pg/lib/native/client.js", "pg/lib/native/client"],
3234
+ patches: [patchPgClientModule]
3235
+ },
3236
+ {
3237
+ modules: ["tedious"],
3238
+ patches: [patchTediousModule]
3239
+ },
3240
+ {
3241
+ modules: ["@prisma/client"],
3242
+ patches: [patchPrismaModule]
3243
+ },
3244
+ {
3245
+ modules: ["typeorm", "@n8n/typeorm"],
3246
+ patches: [patchTypeormModule]
3247
+ },
3248
+ {
3249
+ modules: ["undici"],
3250
+ patches: [patchUndiciModule]
3251
+ }
3252
+ ];
3253
+ for (const definition of hookDefinitions) {
3254
+ registerHook(definition);
3255
+ }
3256
+ patchGlobalFetch();
3257
+ new import_require_in_the_middle.Hook(
3258
+ null,
3259
+ // null = intercept all modules
3260
+ { internals: true },
3261
+ // include internal/relative requires
3262
+ (exports2, moduleName) => {
3263
+ if (moduleName.includes("workflow-runner")) {
3264
+ patchN8nWorkflowRunner(exports2, moduleName);
3265
+ }
3266
+ if (moduleName.includes("active-executions")) {
3267
+ patchN8nActiveExecutions(exports2, moduleName);
3268
+ }
3269
+ return exports2;
3270
+ }
3271
+ );
3272
+ }
3273
+
3274
+ // src/instrumentations/register-iitm.ts
3275
+ var import_import_in_the_middle = require("import-in-the-middle");
3276
+ var import_jennifer5_agent23 = require("@jennifersoft/jennifer5-agent");
3277
+ function patchWithDefaultExport(module2, patcher) {
3278
+ const defaultExport = module2?.default;
3279
+ if (defaultExport && defaultExport !== module2) {
3280
+ patcher(defaultExport);
3281
+ }
3282
+ patcher(module2);
3283
+ }
3284
+ function registerDefaultExportHook(definition) {
3285
+ new import_import_in_the_middle.Hook(definition.modules, (module2, moduleName) => {
3286
+ patchWithDefaultExport(module2, (target) => {
3287
+ for (const patch of definition.patches) {
3288
+ patch(target, moduleName);
3289
+ }
3290
+ });
3291
+ return module2;
3292
+ });
3293
+ }
3294
+ function registerIitmHooks() {
3295
+ const hookDefinitions = [
3296
+ {
3297
+ modules: ["http", "https", "node:http", "node:https"],
3298
+ patches: [patchHttpServer, patchHttpClient]
3299
+ },
3300
+ {
3301
+ modules: ["@apollo/server"],
3302
+ patches: [patchApolloServerModule]
3303
+ },
3304
+ {
3305
+ modules: ["fs", "node:fs"],
3306
+ patches: [patchFsSync, patchFsAsync, patchFsPromise]
3307
+ },
3308
+ {
3309
+ modules: ["mariadb", "mariadb/callback.js"],
3310
+ patches: [patchMariadbModule]
3311
+ },
3312
+ {
3313
+ modules: ["mariadb/lib/cmd/query.js", "mariadb/lib/cmd/query"],
3314
+ patches: [patchMariadbQueryCommandModule]
3315
+ },
3316
+ {
3317
+ modules: ["mariadb/lib/cmd/execute.js", "mariadb/lib/cmd/execute"],
3318
+ patches: [patchMariadbExecuteCommandModule]
3319
+ },
3320
+ {
3321
+ modules: ["mysql2/promise"],
3322
+ patches: [patchMysql2PromiseModule]
3323
+ },
3324
+ {
3325
+ modules: ["mysql2"],
3326
+ patches: [patchMysql2Module]
3327
+ },
3328
+ {
3329
+ modules: ["ioredis"],
3330
+ patches: [patchIoredisModule]
3331
+ },
3332
+ {
3333
+ modules: ["redis"],
3334
+ patches: [patchRedisModule]
3335
+ },
3336
+ {
3337
+ modules: [
3338
+ "@redis/client/dist/lib/client/commands-queue.js",
3339
+ "@redis/client/dist/lib/client/commands-queue"
3340
+ ],
3341
+ patches: [patchRedisCommandsQueueModule]
3342
+ },
3343
+ {
3344
+ modules: ["oracledb"],
3345
+ patches: [patchOracleDbModule]
3346
+ },
3347
+ {
3348
+ modules: ["pg/lib/client.js", "pg/lib/client"],
3349
+ patches: [patchPgClientModule]
3350
+ },
3351
+ {
3352
+ modules: ["pg/lib/native/client.js", "pg/lib/native/client"],
3353
+ patches: [patchPgClientModule]
3354
+ },
3355
+ {
3356
+ modules: ["tedious"],
3357
+ patches: [patchTediousModule]
3358
+ },
3359
+ {
3360
+ modules: ["@prisma/client"],
3361
+ patches: [patchPrismaModule]
3362
+ },
3363
+ {
3364
+ modules: ["typeorm", "@n8n/typeorm"],
3365
+ patches: [patchTypeormModule]
3366
+ },
3367
+ {
3368
+ modules: ["undici"],
3369
+ patches: [patchUndiciModule]
3370
+ }
3371
+ ];
3372
+ for (const definition of hookDefinitions) {
3373
+ registerDefaultExportHook(definition);
3374
+ }
3375
+ patchGlobalFetch();
3376
+ (0, import_jennifer5_agent23.info)("IITM hooks registered");
3377
+ }
3378
+
3379
+ // src/feat/heap-collector.ts
3380
+ var import_jennifer5_agent24 = require("@jennifersoft/jennifer5-agent");
3381
+ var HEAP_COLLECTOR_STARTED = /* @__PURE__ */ Symbol.for("jennifer.heap-collector.started");
3382
+ function startHeapMetricsCollection(intervalMs = 1e3, callback) {
3383
+ if (global[HEAP_COLLECTOR_STARTED]) {
3384
+ return () => {
3385
+ };
3386
+ }
3387
+ global[HEAP_COLLECTOR_STARTED] = true;
3388
+ const sendMetrics = callback || import_jennifer5_agent24.sendHeapMetrics;
3389
+ let hasErrored = false;
3390
+ const cleanup = () => {
3391
+ global[HEAP_COLLECTOR_STARTED] = false;
3392
+ clearInterval(timer);
3393
+ };
3394
+ const timer = setInterval(() => {
3395
+ if (hasErrored) {
3396
+ return;
3397
+ }
3398
+ try {
3399
+ const mem = process.memoryUsage();
3400
+ sendMetrics(mem.heapUsed, mem.heapTotal, mem.external, mem.arrayBuffers);
3401
+ } catch (error) {
3402
+ hasErrored = true;
3403
+ (0, import_jennifer5_agent24.trace)(`Failed to collect heap metrics, stopping collection: ${error}`);
3404
+ cleanup();
3405
+ }
3406
+ }, intervalMs);
3407
+ timer.unref();
3408
+ return cleanup;
3409
+ }
3410
+
3411
+ // src/feat/gc-collector.ts
3412
+ var import_jennifer5_agent25 = require("@jennifersoft/jennifer5-agent");
3413
+ var import_node_perf_hooks = require("perf_hooks");
3414
+ var GC_COLLECTOR_STARTED = /* @__PURE__ */ Symbol.for("jennifer.gc-collector.started");
3415
+ function startGcMetricsCollection(intervalMs = 1e3, callback) {
3416
+ if (global[GC_COLLECTOR_STARTED]) {
3417
+ return null;
3418
+ }
3419
+ global[GC_COLLECTOR_STARTED] = true;
3420
+ const sendMetrics = callback || ((gcCount, gcTime, gcCountDelta) => (0, import_jennifer5_agent25.sendGcMetrics)(gcCount, gcTime, gcCountDelta));
3421
+ if (typeof import_node_perf_hooks.PerformanceObserver === "undefined") {
3422
+ (0, import_jennifer5_agent25.trace)(
3423
+ "PerformanceObserver not available, GC metrics collection disabled (requires Node 16.7+)"
3424
+ );
3425
+ return null;
3426
+ }
3427
+ let accumulatedGcCount = 0;
3428
+ let accumulatedGcTimeMs = 0;
3429
+ let lastSentGcCount = 0;
3430
+ let hasErrored = false;
3431
+ let observer = null;
3432
+ let timer = null;
3433
+ const disableCollection = (message, error, log = true) => {
3434
+ if (!hasErrored) {
3435
+ hasErrored = true;
3436
+ if (log) {
3437
+ (0, import_jennifer5_agent25.trace)(error ? `${message}: ${error}` : message);
3438
+ }
3439
+ }
3440
+ if (observer) {
3441
+ observer.disconnect();
3442
+ observer = null;
3443
+ }
3444
+ if (timer) {
3445
+ clearInterval(timer);
3446
+ timer = null;
3447
+ }
3448
+ };
3449
+ try {
3450
+ observer = new import_node_perf_hooks.PerformanceObserver((list) => {
3451
+ try {
3452
+ const entries = list.getEntries();
3453
+ for (const entry of entries) {
3454
+ if (entry.entryType === "gc") {
3455
+ accumulatedGcCount++;
3456
+ accumulatedGcTimeMs += entry.duration;
3457
+ }
3458
+ }
3459
+ } catch (error) {
3460
+ disableCollection("Error processing GC entries", error);
3461
+ }
3462
+ });
3463
+ observer.observe({ entryTypes: ["gc"] });
3464
+ } catch (error) {
3465
+ disableCollection(
3466
+ "Failed to create PerformanceObserver for GC events (requires Node 16.7+)",
3467
+ error
3468
+ );
3469
+ return null;
3470
+ }
3471
+ timer = setInterval(() => {
3472
+ if (hasErrored) {
3473
+ return;
3474
+ }
3475
+ try {
3476
+ const gcCountDelta = Math.max(0, accumulatedGcCount - lastSentGcCount);
3477
+ lastSentGcCount = accumulatedGcCount;
3478
+ sendMetrics(accumulatedGcCount, Math.round(accumulatedGcTimeMs), gcCountDelta);
3479
+ } catch (error) {
3480
+ disableCollection("Failed to send GC metrics", error);
3481
+ }
3482
+ }, intervalMs);
3483
+ timer.unref();
3484
+ const cleanup = () => {
3485
+ global[GC_COLLECTOR_STARTED] = false;
3486
+ disableCollection("GC metrics collection stopped", void 0, false);
3487
+ };
3488
+ return cleanup;
3489
+ }
3490
+
3491
+ // src/helpers/nextjs/with-jennifer-route-tx.ts
3492
+ var import_jennifer5_agent26 = require("@jennifersoft/jennifer5-agent");
3493
+ function toHeaderLines(headers) {
3494
+ const entries = [];
3495
+ headers.forEach((value, key) => {
3496
+ entries.push(`${key}:${value}`);
3497
+ });
3498
+ return entries;
3499
+ }
3500
+ function resolveHttpUrl(request) {
3501
+ if (request.nextUrl) {
3502
+ return `${request.nextUrl.pathname}${request.nextUrl.search}`;
3503
+ }
3504
+ const parsed = new URL(request.url);
3505
+ return `${parsed.pathname}${parsed.search}`;
3506
+ }
3507
+ function withJenniferNextRouteTx(handler) {
3508
+ return async function wrappedHandler(request) {
3509
+ const ctx = contextManager.start();
3510
+ const txId = ctx.id;
3511
+ const httpUrl = resolveHttpUrl(request);
3512
+ if (!ctx.enable) {
3513
+ return handler(request);
3514
+ }
3515
+ (0, import_jennifer5_agent26.createTransactionCtx)({
3516
+ txId,
3517
+ method: "next.route",
3518
+ httpMethod: request.method,
3519
+ httpUrl,
3520
+ httpHeaders: toHeaderLines(request.headers)
3521
+ });
3522
+ return contextManager.run(ctx, async () => {
3523
+ try {
3524
+ const response = await handler(request);
3525
+ (0, import_jennifer5_agent26.releaseTransactionCtx)(txId, {
3526
+ httpStatusCode: response.status
3527
+ });
3528
+ return response;
3529
+ } catch (error) {
3530
+ (0, import_jennifer5_agent26.releaseTransactionCtx)(txId, {
3531
+ httpStatusCode: 500
3532
+ });
3533
+ throw error;
3534
+ }
3535
+ });
3536
+ };
3537
+ }
3538
+ // Annotate the CommonJS export names for ESM import in node:
3539
+ 0 && (module.exports = {
3540
+ TransactionContextManager,
3541
+ contextManager,
3542
+ registerIitmHooks,
3543
+ registerRitmHooks,
3544
+ startGcMetricsCollection,
3545
+ startHeapMetricsCollection,
3546
+ withJenniferNextRouteTx
3547
+ });