@sailfish-ai/sf-veritas 0.2.5 → 0.2.7

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.
@@ -0,0 +1,718 @@
1
+ var te = Object.defineProperty;
2
+ var re = (r, e, n) => e in r ? te(r, e, { enumerable: !0, configurable: !0, writable: !0, value: n }) : r[e] = n;
3
+ var c = (r, e, n) => re(r, typeof e != "symbol" ? e + "" : e, n);
4
+ import { AsyncLocalStorage as V, AsyncResource as ne } from "async_hooks";
5
+ import { appendFileSync as oe } from "fs";
6
+ import { threadId as w } from "worker_threads";
7
+ const l = [];
8
+ for (let r = 0; r < 256; ++r) l.push((r + 256).toString(16).slice(1));
9
+ let U;
10
+ const se = new Uint8Array(16), z = { randomUUID: typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto) };
11
+ function C(r, e, n) {
12
+ if (z.randomUUID && !r) return z.randomUUID();
13
+ const a = (r = r || {}).random ?? r.rng?.() ?? (function() {
14
+ if (!U) {
15
+ if (typeof crypto > "u" || !crypto.getRandomValues) throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
16
+ U = crypto.getRandomValues.bind(crypto);
17
+ }
18
+ return U(se);
19
+ })();
20
+ if (a.length < 16) throw new Error("Random bytes length must be >= 16");
21
+ return a[6] = 15 & a[6] | 64, a[8] = 63 & a[8] | 128, (function(s, i = 0) {
22
+ return (l[s[i + 0]] + l[s[i + 1]] + l[s[i + 2]] + l[s[i + 3]] + "-" + l[s[i + 4]] + l[s[i + 5]] + "-" + l[s[i + 6]] + l[s[i + 7]] + "-" + l[s[i + 8]] + l[s[i + 9]] + "-" + l[s[i + 10]] + l[s[i + 11]] + l[s[i + 12]] + l[s[i + 13]] + l[s[i + 14]] + l[s[i + 15]]).toLowerCase();
23
+ })(a);
24
+ }
25
+ class ae {
26
+ constructor(e) {
27
+ c(this, "apiKey");
28
+ c(this, "apiGraphqlEndpoint");
29
+ c(this, "sfDebug");
30
+ c(this, "serviceIdentifier");
31
+ c(this, "serviceVersion");
32
+ c(this, "serviceUUID");
33
+ c(this, "serviceAdditionalMetadata");
34
+ c(this, "profilingModeEnabled");
35
+ c(this, "profilingMaxDepth");
36
+ c(this, "profilingMaxVariableSizeKb");
37
+ c(this, "domainsToNotPropagateHeadersTo");
38
+ c(this, "nodeModulesToCollectLocalVariablesOn");
39
+ c(this, "printConfigurationStatuses");
40
+ c(this, "logLevel");
41
+ c(this, "stackDepthLocals");
42
+ c(this, "stackDepthCodeTraceDepth");
43
+ c(this, "packageLibraryType");
44
+ c(this, "version");
45
+ c(this, "gitSha");
46
+ c(this, "_serviceIdentificationReceived", !1);
47
+ this.apiKey = e.apiKey, this.apiGraphqlEndpoint = e?.apiGraphqlEndpoint || process.env.SAILFISH_GRAPHQL_ENDPOINT || "https://api-service.sailfishqa.com/graphql/", this.sfDebug = e?.debug === !0 || process.env.SF_DEBUG === "true", this.serviceIdentifier = e?.serviceIdentifier || process.env.SERVICE_IDENTIFIER, this.serviceUUID = C(), this.serviceVersion = e?.serviceVersion || process.env.SERVICE_VERSION, this.gitSha = e?.gitSha || process.env.GIT_SHA || process.env.VERCEL_GIT_COMMIT_SHA, this.serviceAdditionalMetadata = e?.serviceAdditionalMetadata || {}, this.profilingModeEnabled = e?.profilingModeEnabled ?? !1, this.profilingMaxDepth = e?.profilingMaxDepth ?? 5, this.profilingMaxVariableSizeKb = e?.profilingMaxVariableSizeKb ?? 25, this.domainsToNotPropagateHeadersTo = e?.domainsToNotPropagateHeadersTo || [], this.nodeModulesToCollectLocalVariablesOn = e?.nodeModulesToCollectLocalVariablesOn || ["_all_"], this.printConfigurationStatuses = process.env.PRINT_CONFIGURATION_STATUSES || "true", this.logLevel = process.env.LOG_LEVEL || "INFO", this.stackDepthLocals = process.env.SAILFISH_EXCEPTION_STACK_DEPTH_LOCALS !== void 0 ? parseInt(process.env.SAILFISH_EXCEPTION_STACK_DEPTH_LOCALS, 10) : 5, isNaN(this.stackDepthLocals) && (this.stackDepthLocals = -1), this.stackDepthCodeTraceDepth = process.env.SAILFISH_EXCEPTION_STACK_DEPTH_CODE_TRACE_DEPTH !== void 0 ? parseInt(process.env.SAILFISH_EXCEPTION_STACK_DEPTH_CODE_TRACE_DEPTH, 10) : -1, isNaN(this.stackDepthCodeTraceDepth) && (this.stackDepthCodeTraceDepth = -1), this.packageLibraryType = "JS/TS BACKEND", this.version = this.getPackageVersion();
48
+ }
49
+ getPackageVersion() {
50
+ return "0.1.15";
51
+ }
52
+ get serviceIdentificationReceived() {
53
+ return this._serviceIdentificationReceived;
54
+ }
55
+ setServiceIdentificationReceived(e) {
56
+ this._serviceIdentificationReceived = e;
57
+ }
58
+ }
59
+ const Y = Symbol.for("sailfish.sf_config");
60
+ function A() {
61
+ return globalThis[Y];
62
+ }
63
+ function Se(r) {
64
+ const e = A();
65
+ if (e) return { config: e };
66
+ const n = new ae(r);
67
+ return (function(a) {
68
+ globalThis[Y] = a;
69
+ })(n), n.sfDebug && console.log("[[getOrCreateConfig]] Created global config:", n), { config: n };
70
+ }
71
+ function f() {
72
+ const r = A();
73
+ if (!r) throw new Error("Configuration has not been initialized. Call getOrCreateConfig(options) first.");
74
+ return r;
75
+ }
76
+ const H = Symbol.for("sf.ctx.storeAls"), h = globalThis, k = h[H] ?? (h[H] = new V()), ie = ["identitytoolkit.googleapis.com", "t.co", "*.twitter.com", "*.gravatar.com", "*.googleapis.com", "*.amazonaws.com", "*.smooch.io", "*.zendesk.com"], J = Symbol.for("sf.ctx.als"), E = h[J] ?? (h[J] = new V()), j = Symbol.for("sf.ctx.sessionRegistry"), $ = h[j] ?? (h[j] = /* @__PURE__ */ new Map()), F = { handledExceptions: /* @__PURE__ */ new Set(), reentrancyGuardLoggingActive: !1, reentrancyGuardLoggingPreActive: !1, reentrancyGuardPrintActive: !1, reentrancyGuardPrintPreActive: !1, reentrancyGuardExceptionActive: !1, reentrancyGuardExceptionPreActive: !1, excludedDomains: new Set(ie), supportedDomains: /* @__PURE__ */ new Set() }, _ = class _ {
77
+ constructor() {
78
+ }
79
+ current() {
80
+ return k.getStore();
81
+ }
82
+ ensureStore() {
83
+ const e = this.current();
84
+ if (e) return e;
85
+ const n = /* @__PURE__ */ new Map();
86
+ return k.enterWith(n), n;
87
+ }
88
+ runWith(e, n) {
89
+ const a = this.current() ?? /* @__PURE__ */ new Map(), s = new Map(a);
90
+ for (const [i, t] of Object.entries(e)) s.set(i, t);
91
+ return k.run(s, n);
92
+ }
93
+ static getInstance() {
94
+ return h[_.GLOBAL_MANAGER_SYMBOL] || (h[_.GLOBAL_MANAGER_SYMBOL] = new _()), h[_.GLOBAL_MANAGER_SYMBOL];
95
+ }
96
+ getCurrentContext() {
97
+ return E.getStore() || F;
98
+ }
99
+ setCurrentContext(e) {
100
+ const n = E.getStore() || F;
101
+ E.enterWith({ ...n, ...e });
102
+ }
103
+ ensureSession(e) {
104
+ let n = $.get(e);
105
+ return n || (n = { ...F }, $.set(e, n)), n;
106
+ }
107
+ getContextFor(e) {
108
+ return $.get(e) ?? F;
109
+ }
110
+ updateContextFor(e, n) {
111
+ const a = this.ensureSession(e);
112
+ $.set(e, { ...a, ...n });
113
+ }
114
+ runWithSession(e, n) {
115
+ const a = { ...this.ensureSession(e) };
116
+ return E.run(a, n);
117
+ }
118
+ deleteSession(e) {
119
+ $.delete(e);
120
+ }
121
+ getTraceId() {
122
+ return this.getCurrentContext().traceId;
123
+ }
124
+ getPageVisitUUID() {
125
+ return this.getCurrentContext().pageVisitUUID;
126
+ }
127
+ setTraceId(e) {
128
+ this.setCurrentContext({ traceId: e });
129
+ }
130
+ setPageVisitUUID(e) {
131
+ this.setCurrentContext({ pageVisitUUID: e });
132
+ }
133
+ getCurrentFunctionSpanId() {
134
+ return this.getCurrentContext().currentFunctionSpanId;
135
+ }
136
+ setCurrentFunctionSpanId(e) {
137
+ this.setCurrentContext({ currentFunctionSpanId: e });
138
+ }
139
+ clearCurrentFunctionSpanId() {
140
+ this.setCurrentContext({ currentFunctionSpanId: void 0 });
141
+ }
142
+ getOrSetSfTraceId(e, n = !1) {
143
+ let a = this.getTraceId();
144
+ return a || (a = e || (n ? C() : `nonsession-applogs-v3/${f().apiKey}/${C()}`), this.setTraceId(a), f().sfDebug && console.log(" Created new trace ID:", a), a);
145
+ }
146
+ getOrSetPageVisitUUID() {
147
+ let e = this.getPageVisitUUID();
148
+ return e || (e = C(), this.setPageVisitUUID(e), f().sfDebug && console.log(" Created new page visit UUID:", e), e);
149
+ }
150
+ getHandledExceptions() {
151
+ return this.getCurrentContext().handledExceptions;
152
+ }
153
+ markExceptionHandled(e) {
154
+ const n = this.getHandledExceptions();
155
+ n.add(e), this.setCurrentContext({ handledExceptions: n });
156
+ }
157
+ hasHandledException(e) {
158
+ return this.getHandledExceptions().has(e);
159
+ }
160
+ resetHandledExceptions() {
161
+ this.setCurrentContext({ handledExceptions: /* @__PURE__ */ new Set() });
162
+ }
163
+ getExcludedDomains() {
164
+ return this.getCurrentContext().excludedDomains;
165
+ }
166
+ getSupportedDomains() {
167
+ return this.getCurrentContext().supportedDomains;
168
+ }
169
+ addSupportedDomains(e) {
170
+ this.getCurrentContext().supportedDomains.add(e.toLowerCase().trim());
171
+ }
172
+ setTraceIdFor(e, n) {
173
+ this.updateContextFor(e, { traceId: n });
174
+ }
175
+ setPageVisitUUIDFor(e, n) {
176
+ this.updateContextFor(e, { pageVisitUUID: n });
177
+ }
178
+ };
179
+ c(_, "GLOBAL_MANAGER_SYMBOL", Symbol.for("sf.ctx.manager"));
180
+ let I = _;
181
+ function he(r) {
182
+ const e = { ...I.getInstance().getCurrentContext() };
183
+ E.run(e, () => {
184
+ r();
185
+ });
186
+ }
187
+ function ye() {
188
+ return I.getInstance().getCurrentFunctionSpanId();
189
+ }
190
+ class ce {
191
+ constructor() {
192
+ c(this, "apiKey");
193
+ c(this, "endpoint");
194
+ c(this, "queryType", "mutation");
195
+ c(this, "operationName", "");
196
+ c(this, "serviceUUID", f().serviceUUID);
197
+ c(this, "contextManager");
198
+ this.apiKey = f().apiKey, this.endpoint = f().apiGraphqlEndpoint, this.contextManager = I.getInstance();
199
+ }
200
+ get queryName() {
201
+ return this.operationName ? this.operationName.charAt(0).toLowerCase() + this.operationName.slice(1) : "";
202
+ }
203
+ getDefaultVariables() {
204
+ const e = Date.now().toString(), n = this.contextManager.getOrSetSfTraceId(), a = this.contextManager.getCurrentFunctionSpanId();
205
+ return { apiKey: this.apiKey, serviceUuid: this.serviceUUID, sessionId: n, timestampMs: e, parentSpanId: a };
206
+ }
207
+ getVariables(e = {}) {
208
+ return { ...this.getDefaultVariables(), ...e };
209
+ }
210
+ setOperationName(e) {
211
+ this.operationName = e;
212
+ }
213
+ setEndpoint(e) {
214
+ this.endpoint = e;
215
+ }
216
+ setServiceUUID(e) {
217
+ this.serviceUUID = e;
218
+ }
219
+ }
220
+ const ue = fetch;
221
+ let D = !1;
222
+ async function q(r, e, n, a) {
223
+ try {
224
+ const s = f();
225
+ let i;
226
+ try {
227
+ i = JSON.stringify({ query: n, variables: a, operationName: e });
228
+ } catch {
229
+ i = JSON.stringify({ query: n, operationName: e });
230
+ }
231
+ D = !0, ue(r, { method: "POST", headers: { "Content-Type": "application/json" }, body: i }).then(async (t) => {
232
+ if (D = !1, !t.ok) return void (s.sfDebug && console.error(`GraphQL request failed with status ${t.status} for ${e}`));
233
+ const o = await t.json();
234
+ o.errors?.length ? (function(u, m, p) {
235
+ const g = u && typeof u == "object" && !Array.isArray(u) ? Object.keys(u)[0] : void 0;
236
+ console.error(g === "identifyServiceDetails" ? `IdentifyServiceDetails NOT sent successfully for service: UUID=${p.serviceUUID}` : `GraphQL request failed with errors: ${JSON.stringify(m)} for operation key ${g}`);
237
+ })(o.data, o.errors, s) : s.sfDebug && (function(u, m, p) {
238
+ const g = u && typeof u == "object" && !Array.isArray(u) ? Object.keys(u)[0] : void 0, d = u[g] || !1;
239
+ g === "identifyServiceDetails" && (p.setServiceIdentificationReceived(d), f().sfDebug && console.log(`IdentifyServiceDetails sent successfully for service: UUID=${p.serviceUUID}; serviceIdentificationReceived=${g === "identifyServiceDetails" ? d : "N/A"}`));
240
+ })(o.data, 0, s);
241
+ }).catch((t) => {
242
+ D = !1, s.sfDebug && (console.error(`[RequestUtils] Fetch error for ${e} to ${r}:`, t), t.cause && console.error("[RequestUtils] Error cause:", t.cause));
243
+ });
244
+ } catch (s) {
245
+ D = !1, f().sfDebug && console.error("Error sending data to GraphQL server:", s);
246
+ }
247
+ }
248
+ function Ne() {
249
+ return { capture_arguments: b(process.env.SF_FUNCSPAN_CAPTURE_ARGUMENTS, !0), capture_return_value: b(process.env.SF_FUNCSPAN_CAPTURE_RETURN_VALUE, !0), arg_limit_mb: parseInt(process.env.SF_FUNCSPAN_ARG_LIMIT_MB || "1", 10), return_limit_mb: parseInt(process.env.SF_FUNCSPAN_RETURN_LIMIT_MB || "1", 10), autocapture_all_child_functions: b(process.env.SF_FUNCSPAN_AUTOCAPTURE_ALL_CHILD_FUNCTIONS, !1), sample_rate: parseFloat(process.env.SF_FUNCSPAN_SAMPLE_RATE || "1.0"), enable_sampling: b(process.env.SF_FUNCSPAN_ENABLE_SAMPLING, !1), capture_sf_veritas: b(process.env.SF_FUNCSPAN_CAPTURE_SF_VERITAS, !1), parse_json_strings: b(process.env.SF_FUNCSPAN_PARSE_JSON_STRINGS, !1) };
250
+ }
251
+ function _e() {
252
+ return { capture_arguments: !1, capture_return_value: !1, arg_limit_mb: 1, return_limit_mb: 1, autocapture_all_child_functions: !1, sample_rate: 0, enable_sampling: !1, capture_sf_veritas: !1, parse_json_strings: !1 };
253
+ }
254
+ function Ie(r) {
255
+ try {
256
+ const e = r.split("-");
257
+ return e.length !== 9 ? (console.error(`[FuncSpan] Invalid header format: expected 9 parts, got ${e.length}`), null) : { capture_arguments: e[0] === "1", capture_return_value: e[1] === "1", arg_limit_mb: parseInt(e[2], 10), return_limit_mb: parseInt(e[3], 10), autocapture_all_child_functions: e[4] === "1", sample_rate: parseFloat(e[5]), enable_sampling: e[6] === "1", capture_sf_veritas: e[7] === "1", parse_json_strings: e[8] === "1" };
258
+ } catch (e) {
259
+ return console.error(`[FuncSpan] Failed to parse header override "${r}":`, e), null;
260
+ }
261
+ }
262
+ function b(r, e) {
263
+ if (!r) return e;
264
+ const n = r.toLowerCase();
265
+ return n === "true" || n === "1" || n === "yes";
266
+ }
267
+ const x = new V();
268
+ let L = !1;
269
+ function ve(r) {
270
+ x.enterWith(r);
271
+ }
272
+ function be() {
273
+ if (L) return x.getStore();
274
+ try {
275
+ L = !0;
276
+ const r = x.getStore(), e = new Error().stack?.split(`
277
+ `).slice(1, 4).join(`
278
+ `);
279
+ return console.log(`[getFuncspanOverride] Called from:
280
+ ${e}`), console.log("[getFuncspanOverride] Returned value:", r), r;
281
+ } catch (r) {
282
+ return void console.error("[getFuncspanOverride] ❌ Error:", r);
283
+ } finally {
284
+ L = !1;
285
+ }
286
+ }
287
+ function Ce() {
288
+ }
289
+ function Te(...r) {
290
+ const e = {};
291
+ for (const n of r) for (const a in n) n[a] !== void 0 && (e[a] = n[a]);
292
+ return e;
293
+ }
294
+ function X(r, e) {
295
+ try {
296
+ const n = JSON.stringify(r).length / 1048576;
297
+ return n <= e ? r : { _truncated: !0, _originalSizeMB: n.toFixed(2), _limitMB: e, _preview: JSON.stringify(r).substring(0, 500) + "..." };
298
+ } catch {
299
+ return { _error: "Failed to serialize data", _type: typeof r };
300
+ }
301
+ }
302
+ function N(r, e) {
303
+ const n = process.env[r];
304
+ return n === void 0 ? e : n === "true" || n === "1";
305
+ }
306
+ function Q(r, e) {
307
+ const n = process.env[r];
308
+ if (n === void 0) return e;
309
+ const a = parseFloat(n);
310
+ return isNaN(a) ? e : a;
311
+ }
312
+ function K() {
313
+ return { enabled: N("SF_WORKER_POOL_ENABLED", !0), trackFs: N("SF_WORKER_POOL_TRACK_FS", !1), trackDns: N("SF_WORKER_POOL_TRACK_DNS", !0), trackCrypto: N("SF_WORKER_POOL_TRACK_CRYPTO", !1), trackZlib: N("SF_WORKER_POOL_TRACK_ZLIB", !1), captureArguments: N("SF_WORKER_POOL_CAPTURE_ARGUMENTS", !0), captureReturnValue: N("SF_WORKER_POOL_CAPTURE_RETURN_VALUE", !0), argLimitMb: Q("SF_WORKER_POOL_ARG_LIMIT_MB", 1), returnLimitMb: Q("SF_WORKER_POOL_RETURN_LIMIT_MB", 1) };
314
+ }
315
+ function $e(r) {
316
+ const e = K();
317
+ if (!e.enabled) return !1;
318
+ switch (r) {
319
+ case "fs":
320
+ return e.trackFs;
321
+ case "dns":
322
+ return e.trackDns;
323
+ case "crypto":
324
+ return e.trackCrypto;
325
+ case "zlib":
326
+ return e.trackZlib;
327
+ default:
328
+ return !1;
329
+ }
330
+ }
331
+ function Z(r, e, n, a) {
332
+ let s;
333
+ try {
334
+ switch (r) {
335
+ case "fs":
336
+ s = (function(i, t) {
337
+ const o = {};
338
+ switch (i) {
339
+ case "readFile":
340
+ case "writeFile":
341
+ case "appendFile":
342
+ o.path = String(t[0] || ""), t[1] && typeof t[1] == "object" ? (o.encoding = t[1].encoding || null, o.flag = t[1].flag || null) : typeof t[1] == "string" && (o.encoding = t[1]), i !== "writeFile" && i !== "appendFile" || (Buffer.isBuffer(t[1]) ? (o.dataType = "Buffer", o.dataSize = t[1].length) : typeof t[1] == "string" && (o.dataType = "string", o.dataSize = t[1].length));
343
+ break;
344
+ case "readdir":
345
+ case "stat":
346
+ case "lstat":
347
+ case "access":
348
+ case "chmod":
349
+ case "mkdir":
350
+ case "rmdir":
351
+ case "unlink":
352
+ o.path = String(t[0] || ""), t[1] && typeof t[1] == "object" && (o.options = { ...t[1] }, delete o.options.callback);
353
+ break;
354
+ case "rename":
355
+ o.oldPath = String(t[0] || ""), o.newPath = String(t[1] || "");
356
+ break;
357
+ case "open":
358
+ o.path = String(t[0] || ""), o.flags = t[1], o.mode = t[2];
359
+ break;
360
+ case "close":
361
+ case "fstat":
362
+ o.fd = t[0];
363
+ break;
364
+ case "read":
365
+ case "write":
366
+ o.fd = t[0], Buffer.isBuffer(t[1]) && (o.bufferSize = t[1].length), o.offset = t[2], o.length = t[3], o.position = t[4];
367
+ break;
368
+ default:
369
+ o.argsCount = t.length - 1;
370
+ }
371
+ return o;
372
+ })(e, n);
373
+ break;
374
+ case "dns":
375
+ s = (function(i, t) {
376
+ const o = {};
377
+ switch (i) {
378
+ case "lookup":
379
+ o.hostname = String(t[0] || ""), typeof t[1] == "object" ? (o.family = t[1].family, o.all = t[1].all) : typeof t[1] == "number" && (o.family = t[1]);
380
+ break;
381
+ case "resolve":
382
+ case "resolve4":
383
+ case "resolve6":
384
+ case "resolveAny":
385
+ case "resolveMx":
386
+ case "resolveNs":
387
+ case "resolveTxt":
388
+ o.hostname = String(t[0] || "");
389
+ break;
390
+ case "reverse":
391
+ o.ip = String(t[0] || "");
392
+ break;
393
+ default:
394
+ o.argsCount = t.length - 1;
395
+ }
396
+ return o;
397
+ })(e, n);
398
+ break;
399
+ case "crypto":
400
+ s = (function(i, t) {
401
+ const o = {};
402
+ switch (i) {
403
+ case "pbkdf2":
404
+ o.passwordType = typeof t[0], o.saltType = typeof t[1], o.iterations = t[2], o.keylen = t[3], o.digest = t[4];
405
+ break;
406
+ case "scrypt":
407
+ o.passwordType = typeof t[0], o.saltType = typeof t[1], o.keylen = t[2], typeof t[3] == "object" && (o.N = t[3].N, o.r = t[3].r, o.p = t[3].p);
408
+ break;
409
+ case "randomBytes":
410
+ o.size = t[0];
411
+ break;
412
+ case "generateKeyPair":
413
+ o.type = t[0], typeof t[1] == "object" && (o.modulusLength = t[1].modulusLength, o.namedCurve = t[1].namedCurve);
414
+ break;
415
+ default:
416
+ o.argsCount = t.length - 1;
417
+ }
418
+ return o;
419
+ })(e, n);
420
+ break;
421
+ case "zlib":
422
+ s = (function(i, t) {
423
+ const o = {};
424
+ return Buffer.isBuffer(t[0]) ? (o.inputType = "Buffer", o.inputSize = t[0].length) : typeof t[0] == "string" ? (o.inputType = "string", o.inputSize = t[0].length) : o.inputType = typeof t[0], t[1] && typeof t[1] == "object" && typeof t[1] != "function" && (o.options = { ...t[1] }), o;
425
+ })(0, n);
426
+ break;
427
+ default:
428
+ return null;
429
+ }
430
+ return a > 0 ? X(s, a) : s;
431
+ } catch {
432
+ return { error: "Failed to capture arguments", argsCount: n.length - 1 };
433
+ }
434
+ }
435
+ function ee(r, e, n, a) {
436
+ let s;
437
+ try {
438
+ switch (r) {
439
+ case "fs":
440
+ s = (function(i, t) {
441
+ if (!t) return null;
442
+ switch (i) {
443
+ case "readFile":
444
+ return Buffer.isBuffer(t) ? { type: "Buffer", size: t.length } : typeof t == "string" ? { type: "string", size: t.length } : { type: typeof t };
445
+ case "readdir":
446
+ return { count: Array.isArray(t) ? t.length : 0, items: t };
447
+ case "stat":
448
+ case "lstat":
449
+ case "fstat":
450
+ return { size: t.size, mode: t.mode, isFile: t.isFile(), isDirectory: t.isDirectory() };
451
+ case "open":
452
+ return { fd: t };
453
+ case "read":
454
+ return { bytesRead: t };
455
+ case "write":
456
+ return { bytesWritten: t };
457
+ default:
458
+ return t;
459
+ }
460
+ })(e, n);
461
+ break;
462
+ case "dns":
463
+ s = (function(i, t) {
464
+ if (!t) return null;
465
+ switch (i) {
466
+ case "lookup":
467
+ return Array.isArray(t) ? { count: t.length, addresses: t } : t;
468
+ case "resolve":
469
+ case "resolve4":
470
+ case "resolve6":
471
+ case "resolveAny":
472
+ case "resolveMx":
473
+ case "resolveNs":
474
+ case "resolveTxt":
475
+ return { count: Array.isArray(t) ? t.length : 0, records: t };
476
+ case "reverse":
477
+ return { hostnames: t };
478
+ default:
479
+ return t;
480
+ }
481
+ })(e, n);
482
+ break;
483
+ case "crypto":
484
+ s = (function(i, t) {
485
+ if (!t) return null;
486
+ switch (i) {
487
+ case "pbkdf2":
488
+ case "scrypt":
489
+ case "randomBytes":
490
+ return Buffer.isBuffer(t) ? { type: "Buffer", size: t.length } : { type: typeof t };
491
+ case "generateKeyPair":
492
+ return { hasPublicKey: !!t?.publicKey, hasPrivateKey: !!t?.privateKey };
493
+ default:
494
+ return t;
495
+ }
496
+ })(e, n);
497
+ break;
498
+ case "zlib":
499
+ s = (function(i, t) {
500
+ return t ? Buffer.isBuffer(t) ? { type: "Buffer", size: t.length } : typeof t == "string" ? { type: "string", size: t.length } : { type: typeof t } : null;
501
+ })(0, n);
502
+ break;
503
+ default:
504
+ return null;
505
+ }
506
+ return a > 0 ? X(s, a) : s;
507
+ } catch {
508
+ return { error: "Failed to capture result", type: typeof n };
509
+ }
510
+ }
511
+ function le(r) {
512
+ return r.operationType === "worker_pool";
513
+ }
514
+ class pe extends ce {
515
+ constructor() {
516
+ super(), this.operationName = "CollectFunctionSpans";
517
+ }
518
+ send(e) {
519
+ const n = f().sfDebug;
520
+ n && console.log(`[FunctionSpanTransmitter] Preparing to send ${e.length} function span(s)`);
521
+ for (const a of e) try {
522
+ if (le(a)) {
523
+ this.sendWorkerPoolSpan(a, n);
524
+ continue;
525
+ }
526
+ const s = a;
527
+ let i;
528
+ if (s.result !== void 0 && s.result !== null) {
529
+ const o = typeof s.result;
530
+ i = JSON.stringify({ type: o, has_value: !0, value: s.result });
531
+ } else i = s.result === null ? JSON.stringify({ type: "null", has_value: !0, value: null }) : JSON.stringify({ type: "undefined", has_value: !1, value: null });
532
+ const t = this.getVariables({ library: "JS/TS BACKEND", version: f().version, spanId: s.spanId, parentSpanId: s.parentSpanId, filePath: s.filePath, lineNumber: s.metadata.line, columnNumber: s.metadata.column, functionName: s.functionName, arguments: JSON.stringify(s.args || {}), returnValue: i, startTimeNs: (1e6 * Date.now() - 1e6 * s.duration).toString(), durationNs: (1e6 * s.duration).toString() });
533
+ n && (console.log(`[FunctionSpanTransmitter] Sending GraphQL mutation to ${this.endpoint}`), console.log("[FunctionSpanTransmitter] Variables:", JSON.stringify(t, null, 2))), q(this.endpoint, this.operationName, this.getQuery(), t), n && console.log(`[FunctionSpanTransmitter] Queued function span for ${s.functionName}`);
534
+ } catch (s) {
535
+ console.error(`[FunctionSpanTransmitter] Error preparing function span for ${a.functionName}:`, s);
536
+ }
537
+ }
538
+ sendWorkerPoolSpan(e, n) {
539
+ try {
540
+ let a;
541
+ if (e.result !== void 0 && e.result !== null) {
542
+ const i = typeof e.result;
543
+ a = JSON.stringify({ type: i, has_value: !0, value: e.result });
544
+ } else a = e.result === null ? JSON.stringify({ type: "null", has_value: !0, value: null }) : JSON.stringify({ type: "undefined", has_value: !1, value: null });
545
+ const s = this.getVariables({ library: "JS/TS BACKEND", version: f().version, spanId: e.spanId, operationName: e.operationName, moduleName: e.moduleName, methodName: e.methodName, startTimeNs: e.startTimeNs, durationNs: e.durationNs, arguments: JSON.stringify(e.args || {}), returnValue: a, error: e.error, pid: e.pid, threadId: e.threadId });
546
+ n && (console.log(`[FunctionSpanTransmitter] Sending worker pool span: ${e.operationName}`), console.log("[FunctionSpanTransmitter] Variables:", JSON.stringify(s, null, 2))), q(this.endpoint, "CollectWorkerPoolSpans", this.getWorkerPoolQuery(), s), n && console.log(`[FunctionSpanTransmitter] Queued worker pool span for ${e.operationName}`);
547
+ } catch (a) {
548
+ console.error(`[FunctionSpanTransmitter] Error preparing worker pool span for ${e.operationName}:`, a);
549
+ }
550
+ }
551
+ getWorkerPoolQuery() {
552
+ return `
553
+ mutation CollectWorkerPoolSpans(
554
+ $apiKey: String!,
555
+ $serviceUuid: String!,
556
+ $sessionId: String!,
557
+ $timestampMs: String!,
558
+ $library: String!,
559
+ $version: String!,
560
+ $spanId: String!,
561
+ $operationName: String!,
562
+ $moduleName: String!,
563
+ $methodName: String!,
564
+ $startTimeNs: String!,
565
+ $durationNs: String!,
566
+ $parentSpanId: String,
567
+ $arguments: String,
568
+ $returnValue: String,
569
+ $error: String,
570
+ $pid: Int,
571
+ $threadId: Int
572
+ ) {
573
+ collectWorkerPoolSpans(
574
+ apiKey: $apiKey,
575
+ serviceUuid: $serviceUuid,
576
+ sessionId: $sessionId,
577
+ timestampMs: $timestampMs,
578
+ library: $library,
579
+ version: $version,
580
+ spanId: $spanId,
581
+ operationName: $operationName,
582
+ moduleName: $moduleName,
583
+ methodName: $methodName,
584
+ startTimeNs: $startTimeNs,
585
+ durationNs: $durationNs,
586
+ parentSpanId: $parentSpanId,
587
+ arguments: $arguments,
588
+ returnValue: $returnValue,
589
+ error: $error,
590
+ pid: $pid,
591
+ threadId: $threadId
592
+ )
593
+ }
594
+ `;
595
+ }
596
+ getQuery() {
597
+ return `
598
+ ${this.queryType} ${this.operationName}(
599
+ $apiKey: String!,
600
+ $serviceUuid: String!,
601
+ $sessionId: String!,
602
+ $timestampMs: String!,
603
+ $parentSpanId: String,
604
+ $library: String!,
605
+ $version: String!,
606
+ $spanId: String!,
607
+ $filePath: String!,
608
+ $lineNumber: Int!,
609
+ $columnNumber: Int!,
610
+ $functionName: String!,
611
+ $arguments: String!,
612
+ $returnValue: String,
613
+ $startTimeNs: String!,
614
+ $durationNs: String!
615
+ ) {
616
+ ${this.queryName}(
617
+ apiKey: $apiKey,
618
+ serviceUuid: $serviceUuid,
619
+ sessionId: $sessionId,
620
+ timestampMs: $timestampMs,
621
+ parentSpanId: $parentSpanId,
622
+ library: $library,
623
+ version: $version,
624
+ spanId: $spanId,
625
+ filePath: $filePath,
626
+ lineNumber: $lineNumber,
627
+ columnNumber: $columnNumber,
628
+ functionName: $functionName,
629
+ arguments: $arguments,
630
+ returnValue: $returnValue,
631
+ startTimeNs: $startTimeNs,
632
+ durationNs: $durationNs
633
+ )
634
+ }
635
+ `;
636
+ }
637
+ }
638
+ let R = null;
639
+ function Ee(r, e, n, a, s) {
640
+ const i = A(), t = i?.sfDebug || !1;
641
+ t && console.log(`[WorkerPool] Capturing ${r}.${e}`);
642
+ const o = K(), u = I.getInstance().getCurrentFunctionSpanId(), m = C();
643
+ t && console.log(`[WorkerPool] Span ID: ${m}, Parent: ${u || "none"}`);
644
+ const p = new ne("WorkerPoolOperation"), g = process.hrtime.bigint();
645
+ let d = null;
646
+ o.captureArguments && (d = Z(r, e, a, o.argLimitMb));
647
+ const S = a.findIndex((v) => typeof v == "function");
648
+ if (S === -1) return t && console.log(`[WorkerPool] No callback found for ${r}.${e}`), n.apply(s, a);
649
+ const y = a[S], T = [...a];
650
+ return T[S] = function(v, ...P) {
651
+ const O = process.hrtime.bigint() - g, B = Number(O) / 1e6;
652
+ y(v, ...P), p.runInAsyncScope(() => {
653
+ t && console.log(`[WorkerPool] ${r}.${e} completed in ${B.toFixed(3)}ms (${O}ns)`);
654
+ let W = null, G = null;
655
+ v ? G = v?.message || String(v) : o.captureReturnValue && P.length > 0 && (W = ee(r, e, P[0], o.returnLimitMb)), M({ operationType: "worker_pool", operationName: `${r}.${e}`, moduleName: r, methodName: e, duration: B, durationNs: O.toString(), startTimeNs: g.toString(), args: d, result: W, error: G, spanId: m, parentSpanId: u, pid: process.pid, threadId: w });
656
+ }), p.emitDestroy();
657
+ }, n.apply(s, T);
658
+ }
659
+ function Ae(r, e, n, a, s) {
660
+ const i = A(), t = i?.sfDebug || !1;
661
+ t && console.log(`[WorkerPool] Capturing ${r}.${e} (Promise)`);
662
+ const o = K(), u = I.getInstance().getCurrentFunctionSpanId(), m = C();
663
+ t && console.log(`[WorkerPool] Span ID: ${m}, Parent: ${u || "none"}`);
664
+ const p = process.hrtime.bigint();
665
+ let g = null;
666
+ return o.captureArguments && (g = Z(r, e, a, o.argLimitMb)), n.apply(s, a).then((d) => {
667
+ const S = process.hrtime.bigint() - p, y = Number(S) / 1e6;
668
+ t && console.log(`[WorkerPool] ${r}.${e} completed in ${y.toFixed(3)}ms (${S}ns)`);
669
+ let T = null;
670
+ return o.captureReturnValue && (T = ee(r, e, d, o.returnLimitMb)), M({ operationType: "worker_pool", operationName: `${r}.${e}`, moduleName: r, methodName: e, duration: y, durationNs: S.toString(), startTimeNs: p.toString(), args: g, result: T, error: null, spanId: m, parentSpanId: u, pid: process.pid, threadId: w }), d;
671
+ }, (d) => {
672
+ const S = process.hrtime.bigint() - p, y = Number(S) / 1e6;
673
+ throw t && console.log(`[WorkerPool] ${r}.${e} failed in ${y.toFixed(3)}ms: ${d?.message || d}`), M({ operationType: "worker_pool", operationName: `${r}.${e}`, moduleName: r, methodName: e, duration: y, durationNs: S.toString(), startTimeNs: p.toString(), args: g, result: null, error: d?.message || String(d), spanId: m, parentSpanId: u, pid: process.pid, threadId: w }), d;
674
+ });
675
+ }
676
+ function M(r) {
677
+ const e = A(), n = e?.sfDebug || !1;
678
+ n && console.log("[WorkerPool] Capturing span:", { operation: r.operationName, duration: `${r.duration}ms`, error: r.error, spanId: r.spanId, parentSpanId: r.parentSpanId }), process.env.SF_FUNCSPAN_CONSOLE_OUTPUT === "true" && console.log(`
679
+ ⚙️ Worker Pool Operation:`, { operation: r.operationName, duration: `${r.duration.toFixed(2)}ms`, arguments: r.args, result: r.error ? `Error: ${r.error}` : r.result, spanId: r.spanId, parentSpanId: r.parentSpanId || "none" });
680
+ const a = process.env.SF_FUNCSPAN_JSONL_FILE;
681
+ if (a) try {
682
+ const s = a === "true" || a === "1" ? "funcspans.jsonl" : a, i = Date.now(), t = process.hrtime.bigint(), o = BigInt(r.startTimeNs), u = Number(t - o) / 1e6, m = new Date(i - u).toISOString(), p = JSON.stringify({ timestamp: m, operationType: r.operationType, operationName: r.operationName, moduleName: r.moduleName, methodName: r.methodName, duration: r.duration, durationNs: r.durationNs, startTimeNs: r.startTimeNs, arguments: r.args, returnValue: r.error ? { error: String(r.error) } : r.result, spanId: r.spanId, parentSpanId: r.parentSpanId, pid: r.pid, threadId: r.threadId }) + `
683
+ `;
684
+ oe(s, p, "utf-8");
685
+ } catch (s) {
686
+ console.error("[WorkerPool] Error writing to JSONL file:", s);
687
+ }
688
+ if (n && console.log("[WorkerPool] Sending span to transmitter"), process.env.SF_FUNCSPAN_SKIP_BACKEND !== "true") try {
689
+ (R || (R = new pe()), R).send([r]), n && console.log("[WorkerPool] Span sent successfully");
690
+ } catch (s) {
691
+ n && console.error("[WorkerPool] Error sending span:", s);
692
+ }
693
+ }
694
+ export {
695
+ ce as B,
696
+ I as C,
697
+ ie as D,
698
+ pe as F,
699
+ be as a,
700
+ ye as b,
701
+ Ee as c,
702
+ Ne as d,
703
+ _e as e,
704
+ x as f,
705
+ f as g,
706
+ Ae as h,
707
+ $e as i,
708
+ Se as j,
709
+ A as k,
710
+ Ce as l,
711
+ Te as m,
712
+ q as n,
713
+ Ie as p,
714
+ he as r,
715
+ ve as s,
716
+ X as t,
717
+ C as v
718
+ };