@sailfish-ai/sf-veritas 0.2.11 → 0.2.13

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.
@@ -1,26 +1,26 @@
1
- var W = Object.defineProperty;
2
- var V = (n, t, s) => t in n ? W(n, t, { enumerable: !0, configurable: !0, writable: !0, value: s }) : n[t] = s;
3
- var S = (n, t, s) => V(n, typeof t != "symbol" ? t + "" : t, s);
4
- import { AsyncLocalStorage as J, AsyncResource as z } from "async_hooks";
5
- import { appendFileSync as j } from "fs";
6
- import { threadId as T } from "worker_threads";
7
- import { g as f, C as O, a as A, v as w } from "./contextManager-CEPhVu9T.js";
1
+ var M = Object.defineProperty;
2
+ var W = (n, t, a) => t in n ? M(n, t, { enumerable: !0, configurable: !0, writable: !0, value: a }) : n[t] = a;
3
+ var S = (n, t, a) => W(n, typeof t != "symbol" ? t + "" : t, a);
4
+ import { AsyncLocalStorage as V, AsyncResource as J } from "async_hooks";
5
+ import { appendFileSync as z } from "fs";
6
+ import { threadId as F } from "worker_threads";
7
+ import { g as m, C as k, v as D, a as P } from "./contextManager-CEPhVu9T.js";
8
8
  class x {
9
9
  constructor() {
10
10
  S(this, "apiKey");
11
11
  S(this, "endpoint");
12
12
  S(this, "queryType", "mutation");
13
13
  S(this, "operationName", "");
14
- S(this, "serviceUUID", f().serviceUUID);
14
+ S(this, "serviceUUID", m().serviceUUID);
15
15
  S(this, "contextManager");
16
- this.apiKey = f().apiKey, this.endpoint = f().apiGraphqlEndpoint, this.contextManager = O.getInstance();
16
+ this.apiKey = m().apiKey, this.endpoint = m().apiGraphqlEndpoint, this.contextManager = k.getInstance();
17
17
  }
18
18
  get queryName() {
19
19
  return this.operationName ? this.operationName.charAt(0).toLowerCase() + this.operationName.slice(1) : "";
20
20
  }
21
21
  getDefaultVariables() {
22
- const t = Date.now().toString(), s = this.contextManager.getOrSetSfTraceId(), o = this.contextManager.getCurrentFunctionSpanId();
23
- return { apiKey: this.apiKey, serviceUuid: this.serviceUUID, sessionId: s, timestampMs: t, parentSpanId: o };
22
+ const t = Date.now().toString(), a = this.contextManager.getOrSetSfTraceId(), o = this.contextManager.getCurrentFunctionSpanId();
23
+ return { apiKey: this.apiKey, serviceUuid: this.serviceUUID, sessionId: a, timestampMs: t, parentSpanId: o };
24
24
  }
25
25
  getVariables(t = {}) {
26
26
  return { ...this.getDefaultVariables(), ...t };
@@ -35,41 +35,41 @@ class x {
35
35
  this.serviceUUID = t;
36
36
  }
37
37
  }
38
- const q = fetch;
38
+ const j = fetch;
39
39
  let $ = !1;
40
- async function D(n, t, s, o) {
40
+ async function C(n, t, a, o) {
41
41
  try {
42
- const a = f();
42
+ const s = m();
43
43
  let i;
44
44
  try {
45
- i = JSON.stringify({ query: s, variables: o, operationName: t });
45
+ i = JSON.stringify({ query: a, variables: o, operationName: t });
46
46
  } catch {
47
- i = JSON.stringify({ query: s, operationName: t });
47
+ i = JSON.stringify({ query: a, operationName: t });
48
48
  }
49
- $ = !0, q(n, { method: "POST", headers: { "Content-Type": "application/json" }, body: i }).then(async (e) => {
50
- if ($ = !1, !e.ok) return void (a.sfDebug && console.error(`GraphQL request failed with status ${e.status} for ${t}`));
49
+ $ = !0, j(n, { method: "POST", headers: { "Content-Type": "application/json" }, body: i }).then(async (e) => {
50
+ if ($ = !1, !e.ok) return void (s.sfDebug && console.error(`GraphQL request failed with status ${e.status} for ${t}`));
51
51
  const r = await e.json();
52
52
  r.errors?.length ? (function(u, d, l) {
53
53
  const p = u && typeof u == "object" && !Array.isArray(u) ? Object.keys(u)[0] : void 0;
54
54
  console.error(p === "identifyServiceDetails" ? `IdentifyServiceDetails NOT sent successfully for service: UUID=${l.serviceUUID}` : `GraphQL request failed with errors: ${JSON.stringify(d)} for operation key ${p}`);
55
- })(r.data, r.errors, a) : a.sfDebug && (function(u, d, l) {
55
+ })(r.data, r.errors, s) : s.sfDebug && (function(u, d, l) {
56
56
  const p = u && typeof u == "object" && !Array.isArray(u) ? Object.keys(u)[0] : void 0, c = u[p] || !1;
57
- p === "identifyServiceDetails" && (l.setServiceIdentificationReceived(c), f().sfDebug && console.log(`IdentifyServiceDetails sent successfully for service: UUID=${l.serviceUUID}; serviceIdentificationReceived=${p === "identifyServiceDetails" ? c : "N/A"}`));
58
- })(r.data, 0, a);
57
+ p === "identifyServiceDetails" && (l.setServiceIdentificationReceived(c), m().sfDebug && console.log(`IdentifyServiceDetails sent successfully for service: UUID=${l.serviceUUID}; serviceIdentificationReceived=${p === "identifyServiceDetails" ? c : "N/A"}`));
58
+ })(r.data, 0, s);
59
59
  }).catch((e) => {
60
- $ = !1, a.sfDebug && (console.error(`[RequestUtils] Fetch error for ${t} to ${n}:`, e), e.cause && console.error("[RequestUtils] Error cause:", e.cause));
60
+ $ = !1, s.sfDebug && (console.error(`[RequestUtils] Fetch error for ${t} to ${n}:`, e), e.cause && console.error("[RequestUtils] Error cause:", e.cause));
61
61
  });
62
- } catch (a) {
63
- $ = !1, f().sfDebug && console.error("Error sending data to GraphQL server:", a);
62
+ } catch (s) {
63
+ $ = !1, m().sfDebug && console.error("Error sending data to GraphQL server:", s);
64
64
  }
65
65
  }
66
- function te() {
66
+ function ee() {
67
67
  return { capture_arguments: _(process.env.SF_FUNCSPAN_CAPTURE_ARGUMENTS, !0), capture_return_value: _(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: _(process.env.SF_FUNCSPAN_AUTOCAPTURE_ALL_CHILD_FUNCTIONS, !1), sample_rate: parseFloat(process.env.SF_FUNCSPAN_SAMPLE_RATE || "1.0"), enable_sampling: _(process.env.SF_FUNCSPAN_ENABLE_SAMPLING, !1), capture_sf_veritas: _(process.env.SF_FUNCSPAN_CAPTURE_SF_VERITAS, !1), parse_json_strings: _(process.env.SF_FUNCSPAN_PARSE_JSON_STRINGS, !1) };
68
68
  }
69
- function ne() {
69
+ function te() {
70
70
  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 };
71
71
  }
72
- function re(n) {
72
+ function ne(n) {
73
73
  try {
74
74
  const t = n.split("-");
75
75
  return t.length !== 9 ? (console.error(`[FuncSpan] Invalid header format: expected 9 parts, got ${t.length}`), null) : { capture_arguments: t[0] === "1", capture_return_value: t[1] === "1", arg_limit_mb: parseInt(t[2], 10), return_limit_mb: parseInt(t[3], 10), autocapture_all_child_functions: t[4] === "1", sample_rate: parseFloat(t[5]), enable_sampling: t[6] === "1", capture_sf_veritas: t[7] === "1", parse_json_strings: t[8] === "1" };
@@ -79,59 +79,46 @@ function re(n) {
79
79
  }
80
80
  function _(n, t) {
81
81
  if (!n) return t;
82
- const s = n.toLowerCase();
83
- return s === "true" || s === "1" || s === "yes";
82
+ const a = n.toLowerCase();
83
+ return a === "true" || a === "1" || a === "yes";
84
84
  }
85
- const k = new J();
86
- let I = !1;
87
- function se(n) {
88
- k.enterWith(n);
85
+ const L = new V();
86
+ function re(n) {
87
+ L.enterWith(n);
89
88
  }
90
89
  function ae() {
91
- if (I) return k.getStore();
92
- try {
93
- I = !0;
94
- const n = k.getStore(), t = new Error().stack?.split(`
95
- `).slice(1, 4).join(`
96
- `);
97
- return console.log(`[getFuncspanOverride] Called from:
98
- ${t}`), console.log("[getFuncspanOverride] Returned value:", n), n;
99
- } catch (n) {
100
- return void console.error("[getFuncspanOverride] ❌ Error:", n);
101
- } finally {
102
- I = !1;
103
- }
90
+ return L.getStore();
104
91
  }
105
- function oe() {
92
+ function se() {
106
93
  }
107
- function ie(...n) {
94
+ function oe(...n) {
108
95
  const t = {};
109
- for (const s of n) for (const o in s) s[o] !== void 0 && (t[o] = s[o]);
96
+ for (const a of n) for (const o in a) a[o] !== void 0 && (t[o] = a[o]);
110
97
  return t;
111
98
  }
112
- function K(n, t) {
99
+ function w(n, t) {
113
100
  try {
114
- const s = JSON.stringify(n).length / 1048576;
115
- return s <= t ? n : { _truncated: !0, _originalSizeMB: s.toFixed(2), _limitMB: t, _preview: JSON.stringify(n).substring(0, 500) + "..." };
101
+ const a = JSON.stringify(n).length / 1048576;
102
+ return a <= t ? n : { _truncated: !0, _originalSizeMB: a.toFixed(2), _limitMB: t, _preview: JSON.stringify(n).substring(0, 500) + "..." };
116
103
  } catch {
117
104
  return { _error: "Failed to serialize data", _type: typeof n };
118
105
  }
119
106
  }
120
107
  function y(n, t) {
121
- const s = process.env[n];
122
- return s === void 0 ? t : s === "true" || s === "1";
108
+ const a = process.env[n];
109
+ return a === void 0 ? t : a === "true" || a === "1";
123
110
  }
124
- function L(n, t) {
125
- const s = process.env[n];
126
- if (s === void 0) return t;
127
- const o = parseFloat(s);
111
+ function E(n, t) {
112
+ const a = process.env[n];
113
+ if (a === void 0) return t;
114
+ const o = parseFloat(a);
128
115
  return isNaN(o) ? t : o;
129
116
  }
130
- function U() {
131
- return { enabled: y("SF_WORKER_POOL_ENABLED", !0), trackFs: y("SF_WORKER_POOL_TRACK_FS", !1), trackDns: y("SF_WORKER_POOL_TRACK_DNS", !0), trackCrypto: y("SF_WORKER_POOL_TRACK_CRYPTO", !1), trackZlib: y("SF_WORKER_POOL_TRACK_ZLIB", !1), captureArguments: y("SF_WORKER_POOL_CAPTURE_ARGUMENTS", !0), captureReturnValue: y("SF_WORKER_POOL_CAPTURE_RETURN_VALUE", !0), argLimitMb: L("SF_WORKER_POOL_ARG_LIMIT_MB", 1), returnLimitMb: L("SF_WORKER_POOL_RETURN_LIMIT_MB", 1) };
117
+ function O() {
118
+ return { enabled: y("SF_WORKER_POOL_ENABLED", !0), trackFs: y("SF_WORKER_POOL_TRACK_FS", !1), trackDns: y("SF_WORKER_POOL_TRACK_DNS", !0), trackCrypto: y("SF_WORKER_POOL_TRACK_CRYPTO", !1), trackZlib: y("SF_WORKER_POOL_TRACK_ZLIB", !1), captureArguments: y("SF_WORKER_POOL_CAPTURE_ARGUMENTS", !0), captureReturnValue: y("SF_WORKER_POOL_CAPTURE_RETURN_VALUE", !0), argLimitMb: E("SF_WORKER_POOL_ARG_LIMIT_MB", 1), returnLimitMb: E("SF_WORKER_POOL_RETURN_LIMIT_MB", 1) };
132
119
  }
133
- function ue(n) {
134
- const t = U();
120
+ function ie(n) {
121
+ const t = O();
135
122
  if (!t.enabled) return !1;
136
123
  switch (n) {
137
124
  case "fs":
@@ -146,12 +133,12 @@ function ue(n) {
146
133
  return !1;
147
134
  }
148
135
  }
149
- function B(n, t, s, o) {
150
- let a;
136
+ function K(n, t, a, o) {
137
+ let s;
151
138
  try {
152
139
  switch (n) {
153
140
  case "fs":
154
- a = (function(i, e) {
141
+ s = (function(i, e) {
155
142
  const r = {};
156
143
  switch (i) {
157
144
  case "readFile":
@@ -187,10 +174,10 @@ function B(n, t, s, o) {
187
174
  r.argsCount = e.length - 1;
188
175
  }
189
176
  return r;
190
- })(t, s);
177
+ })(t, a);
191
178
  break;
192
179
  case "dns":
193
- a = (function(i, e) {
180
+ s = (function(i, e) {
194
181
  const r = {};
195
182
  switch (i) {
196
183
  case "lookup":
@@ -212,10 +199,10 @@ function B(n, t, s, o) {
212
199
  r.argsCount = e.length - 1;
213
200
  }
214
201
  return r;
215
- })(t, s);
202
+ })(t, a);
216
203
  break;
217
204
  case "crypto":
218
- a = (function(i, e) {
205
+ s = (function(i, e) {
219
206
  const r = {};
220
207
  switch (i) {
221
208
  case "pbkdf2":
@@ -234,28 +221,28 @@ function B(n, t, s, o) {
234
221
  r.argsCount = e.length - 1;
235
222
  }
236
223
  return r;
237
- })(t, s);
224
+ })(t, a);
238
225
  break;
239
226
  case "zlib":
240
- a = (function(i, e) {
227
+ s = (function(i, e) {
241
228
  const r = {};
242
229
  return Buffer.isBuffer(e[0]) ? (r.inputType = "Buffer", r.inputSize = e[0].length) : typeof e[0] == "string" ? (r.inputType = "string", r.inputSize = e[0].length) : r.inputType = typeof e[0], e[1] && typeof e[1] == "object" && typeof e[1] != "function" && (r.options = { ...e[1] }), r;
243
- })(0, s);
230
+ })(0, a);
244
231
  break;
245
232
  default:
246
233
  return null;
247
234
  }
248
- return o > 0 ? K(a, o) : a;
235
+ return o > 0 ? w(s, o) : s;
249
236
  } catch {
250
- return { error: "Failed to capture arguments", argsCount: s.length - 1 };
237
+ return { error: "Failed to capture arguments", argsCount: a.length - 1 };
251
238
  }
252
239
  }
253
- function M(n, t, s, o) {
254
- let a;
240
+ function B(n, t, a, o) {
241
+ let s;
255
242
  try {
256
243
  switch (n) {
257
244
  case "fs":
258
- a = (function(i, e) {
245
+ s = (function(i, e) {
259
246
  if (!e) return null;
260
247
  switch (i) {
261
248
  case "readFile":
@@ -275,10 +262,10 @@ function M(n, t, s, o) {
275
262
  default:
276
263
  return e;
277
264
  }
278
- })(t, s);
265
+ })(t, a);
279
266
  break;
280
267
  case "dns":
281
- a = (function(i, e) {
268
+ s = (function(i, e) {
282
269
  if (!e) return null;
283
270
  switch (i) {
284
271
  case "lookup":
@@ -296,10 +283,10 @@ function M(n, t, s, o) {
296
283
  default:
297
284
  return e;
298
285
  }
299
- })(t, s);
286
+ })(t, a);
300
287
  break;
301
288
  case "crypto":
302
- a = (function(i, e) {
289
+ s = (function(i, e) {
303
290
  if (!e) return null;
304
291
  switch (i) {
305
292
  case "pbkdf2":
@@ -311,57 +298,57 @@ function M(n, t, s, o) {
311
298
  default:
312
299
  return e;
313
300
  }
314
- })(t, s);
301
+ })(t, a);
315
302
  break;
316
303
  case "zlib":
317
- a = (function(i, e) {
304
+ s = (function(i, e) {
318
305
  return e ? Buffer.isBuffer(e) ? { type: "Buffer", size: e.length } : typeof e == "string" ? { type: "string", size: e.length } : { type: typeof e } : null;
319
- })(0, s);
306
+ })(0, a);
320
307
  break;
321
308
  default:
322
309
  return null;
323
310
  }
324
- return o > 0 ? K(a, o) : a;
311
+ return o > 0 ? w(s, o) : s;
325
312
  } catch {
326
- return { error: "Failed to capture result", type: typeof s };
313
+ return { error: "Failed to capture result", type: typeof a };
327
314
  }
328
315
  }
329
- function G(n) {
316
+ function q(n) {
330
317
  return n.operationType === "worker_pool";
331
318
  }
332
- class Q extends x {
319
+ class G extends x {
333
320
  constructor() {
334
321
  super(), this.operationName = "CollectFunctionSpans";
335
322
  }
336
323
  send(t) {
337
- const s = f().sfDebug;
338
- s && console.log(`[FunctionSpanTransmitter] Preparing to send ${t.length} function span(s)`);
324
+ const a = m().sfDebug;
325
+ a && console.log(`[FunctionSpanTransmitter] Preparing to send ${t.length} function span(s)`);
339
326
  for (const o of t) try {
340
- if (G(o)) {
341
- this.sendWorkerPoolSpan(o, s);
327
+ if (q(o)) {
328
+ this.sendWorkerPoolSpan(o, a);
342
329
  continue;
343
330
  }
344
- const a = o;
331
+ const s = o;
345
332
  let i;
346
- if (a.result !== void 0 && a.result !== null) {
347
- const r = typeof a.result;
348
- i = JSON.stringify({ type: r, has_value: !0, value: a.result });
349
- } else i = a.result === null ? JSON.stringify({ type: "null", has_value: !0, value: null }) : JSON.stringify({ type: "undefined", has_value: !1, value: null });
350
- const e = this.getVariables({ library: "JS/TS BACKEND", version: f().version, spanId: a.spanId, parentSpanId: a.parentSpanId, filePath: a.filePath, lineNumber: a.metadata.line, columnNumber: a.metadata.column, functionName: a.functionName, arguments: JSON.stringify(a.args || {}), returnValue: i, startTimeNs: (1e6 * Date.now() - 1e6 * a.duration).toString(), durationNs: (1e6 * a.duration).toString() });
351
- s && (console.log(`[FunctionSpanTransmitter] Sending GraphQL mutation to ${this.endpoint}`), console.log("[FunctionSpanTransmitter] Variables:", JSON.stringify(e, null, 2))), D(this.endpoint, this.operationName, this.getQuery(), e), s && console.log(`[FunctionSpanTransmitter] Queued function span for ${a.functionName}`);
352
- } catch (a) {
353
- console.error(`[FunctionSpanTransmitter] Error preparing function span for ${o.functionName}:`, a);
333
+ if (s.result !== void 0 && s.result !== null) {
334
+ const r = typeof s.result;
335
+ i = JSON.stringify({ type: r, has_value: !0, value: s.result });
336
+ } else i = s.result === null ? JSON.stringify({ type: "null", has_value: !0, value: null }) : JSON.stringify({ type: "undefined", has_value: !1, value: null });
337
+ const e = this.getVariables({ library: "JS/TS BACKEND", version: m().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() });
338
+ a && (console.log(`[FunctionSpanTransmitter] Sending GraphQL mutation to ${this.endpoint}`), console.log("[FunctionSpanTransmitter] Variables:", JSON.stringify(e, null, 2))), C(this.endpoint, this.operationName, this.getQuery(), e), a && console.log(`[FunctionSpanTransmitter] Queued function span for ${s.functionName}`);
339
+ } catch (s) {
340
+ console.error(`[FunctionSpanTransmitter] Error preparing function span for ${o.functionName}:`, s);
354
341
  }
355
342
  }
356
- sendWorkerPoolSpan(t, s) {
343
+ sendWorkerPoolSpan(t, a) {
357
344
  try {
358
345
  let o;
359
346
  if (t.result !== void 0 && t.result !== null) {
360
347
  const i = typeof t.result;
361
348
  o = JSON.stringify({ type: i, has_value: !0, value: t.result });
362
349
  } else o = t.result === null ? JSON.stringify({ type: "null", has_value: !0, value: null }) : JSON.stringify({ type: "undefined", has_value: !1, value: null });
363
- const a = this.getVariables({ library: "JS/TS BACKEND", version: f().version, spanId: t.spanId, operationName: t.operationName, moduleName: t.moduleName, methodName: t.methodName, startTimeNs: t.startTimeNs, durationNs: t.durationNs, arguments: JSON.stringify(t.args || {}), returnValue: o, error: t.error, pid: t.pid, threadId: t.threadId });
364
- s && (console.log(`[FunctionSpanTransmitter] Sending worker pool span: ${t.operationName}`), console.log("[FunctionSpanTransmitter] Variables:", JSON.stringify(a, null, 2))), D(this.endpoint, "CollectWorkerPoolSpans", this.getWorkerPoolQuery(), a), s && console.log(`[FunctionSpanTransmitter] Queued worker pool span for ${t.operationName}`);
350
+ const s = this.getVariables({ library: "JS/TS BACKEND", version: m().version, spanId: t.spanId, operationName: t.operationName, moduleName: t.moduleName, methodName: t.methodName, startTimeNs: t.startTimeNs, durationNs: t.durationNs, arguments: JSON.stringify(t.args || {}), returnValue: o, error: t.error, pid: t.pid, threadId: t.threadId });
351
+ a && (console.log(`[FunctionSpanTransmitter] Sending worker pool span: ${t.operationName}`), console.log("[FunctionSpanTransmitter] Variables:", JSON.stringify(s, null, 2))), C(this.endpoint, "CollectWorkerPoolSpans", this.getWorkerPoolQuery(), s), a && console.log(`[FunctionSpanTransmitter] Queued worker pool span for ${t.operationName}`);
365
352
  } catch (o) {
366
353
  console.error(`[FunctionSpanTransmitter] Error preparing worker pool span for ${t.operationName}:`, o);
367
354
  }
@@ -453,76 +440,76 @@ class Q extends x {
453
440
  `;
454
441
  }
455
442
  }
456
- let F = null;
457
- function le(n, t, s, o, a) {
458
- const i = A(), e = i?.sfDebug || !1;
443
+ let v = null;
444
+ function ue(n, t, a, o, s) {
445
+ const i = P(), e = i?.sfDebug || !1;
459
446
  e && console.log(`[WorkerPool] Capturing ${n}.${t}`);
460
- const r = U(), u = O.getInstance().getCurrentFunctionSpanId(), d = w();
447
+ const r = O(), u = k.getInstance().getCurrentFunctionSpanId(), d = D();
461
448
  e && console.log(`[WorkerPool] Span ID: ${d}, Parent: ${u || "none"}`);
462
- const l = new z("WorkerPoolOperation"), p = process.hrtime.bigint();
449
+ const l = new J("WorkerPoolOperation"), p = process.hrtime.bigint();
463
450
  let c = null;
464
- r.captureArguments && (c = B(n, t, o, r.argLimitMb));
451
+ r.captureArguments && (c = K(n, t, o, r.argLimitMb));
465
452
  const g = o.findIndex((N) => typeof N == "function");
466
- if (g === -1) return e && console.log(`[WorkerPool] No callback found for ${n}.${t}`), s.apply(a, o);
467
- const m = o[g], h = [...o];
453
+ if (g === -1) return e && console.log(`[WorkerPool] No callback found for ${n}.${t}`), a.apply(s, o);
454
+ const f = o[g], h = [...o];
468
455
  return h[g] = function(N, ...b) {
469
- const v = process.hrtime.bigint() - p, R = Number(v) / 1e6;
470
- m(N, ...b), l.runInAsyncScope(() => {
471
- e && console.log(`[WorkerPool] ${n}.${t} completed in ${R.toFixed(3)}ms (${v}ns)`);
472
- let C = null, E = null;
473
- N ? E = N?.message || String(N) : r.captureReturnValue && b.length > 0 && (C = M(n, t, b[0], r.returnLimitMb)), P({ operationType: "worker_pool", operationName: `${n}.${t}`, moduleName: n, methodName: t, duration: R, durationNs: v.toString(), startTimeNs: p.toString(), args: c, result: C, error: E, spanId: d, parentSpanId: u, pid: process.pid, threadId: T });
456
+ const I = process.hrtime.bigint() - p, A = Number(I) / 1e6;
457
+ f(N, ...b), l.runInAsyncScope(() => {
458
+ e && console.log(`[WorkerPool] ${n}.${t} completed in ${A.toFixed(3)}ms (${I}ns)`);
459
+ let U = null, R = null;
460
+ N ? R = N?.message || String(N) : r.captureReturnValue && b.length > 0 && (U = B(n, t, b[0], r.returnLimitMb)), T({ operationType: "worker_pool", operationName: `${n}.${t}`, moduleName: n, methodName: t, duration: A, durationNs: I.toString(), startTimeNs: p.toString(), args: c, result: U, error: R, spanId: d, parentSpanId: u, pid: process.pid, threadId: F });
474
461
  }), l.emitDestroy();
475
- }, s.apply(a, h);
462
+ }, a.apply(s, h);
476
463
  }
477
- function ce(n, t, s, o, a) {
478
- const i = A(), e = i?.sfDebug || !1;
464
+ function le(n, t, a, o, s) {
465
+ const i = P(), e = i?.sfDebug || !1;
479
466
  e && console.log(`[WorkerPool] Capturing ${n}.${t} (Promise)`);
480
- const r = U(), u = O.getInstance().getCurrentFunctionSpanId(), d = w();
467
+ const r = O(), u = k.getInstance().getCurrentFunctionSpanId(), d = D();
481
468
  e && console.log(`[WorkerPool] Span ID: ${d}, Parent: ${u || "none"}`);
482
469
  const l = process.hrtime.bigint();
483
470
  let p = null;
484
- return r.captureArguments && (p = B(n, t, o, r.argLimitMb)), s.apply(a, o).then((c) => {
485
- const g = process.hrtime.bigint() - l, m = Number(g) / 1e6;
486
- e && console.log(`[WorkerPool] ${n}.${t} completed in ${m.toFixed(3)}ms (${g}ns)`);
471
+ return r.captureArguments && (p = K(n, t, o, r.argLimitMb)), a.apply(s, o).then((c) => {
472
+ const g = process.hrtime.bigint() - l, f = Number(g) / 1e6;
473
+ e && console.log(`[WorkerPool] ${n}.${t} completed in ${f.toFixed(3)}ms (${g}ns)`);
487
474
  let h = null;
488
- return r.captureReturnValue && (h = M(n, t, c, r.returnLimitMb)), P({ operationType: "worker_pool", operationName: `${n}.${t}`, moduleName: n, methodName: t, duration: m, durationNs: g.toString(), startTimeNs: l.toString(), args: p, result: h, error: null, spanId: d, parentSpanId: u, pid: process.pid, threadId: T }), c;
475
+ return r.captureReturnValue && (h = B(n, t, c, r.returnLimitMb)), T({ operationType: "worker_pool", operationName: `${n}.${t}`, moduleName: n, methodName: t, duration: f, durationNs: g.toString(), startTimeNs: l.toString(), args: p, result: h, error: null, spanId: d, parentSpanId: u, pid: process.pid, threadId: F }), c;
489
476
  }, (c) => {
490
- const g = process.hrtime.bigint() - l, m = Number(g) / 1e6;
491
- throw e && console.log(`[WorkerPool] ${n}.${t} failed in ${m.toFixed(3)}ms: ${c?.message || c}`), P({ operationType: "worker_pool", operationName: `${n}.${t}`, moduleName: n, methodName: t, duration: m, durationNs: g.toString(), startTimeNs: l.toString(), args: p, result: null, error: c?.message || String(c), spanId: d, parentSpanId: u, pid: process.pid, threadId: T }), c;
477
+ const g = process.hrtime.bigint() - l, f = Number(g) / 1e6;
478
+ throw e && console.log(`[WorkerPool] ${n}.${t} failed in ${f.toFixed(3)}ms: ${c?.message || c}`), T({ operationType: "worker_pool", operationName: `${n}.${t}`, moduleName: n, methodName: t, duration: f, durationNs: g.toString(), startTimeNs: l.toString(), args: p, result: null, error: c?.message || String(c), spanId: d, parentSpanId: u, pid: process.pid, threadId: F }), c;
492
479
  });
493
480
  }
494
- function P(n) {
495
- const t = A(), s = t?.sfDebug || !1;
496
- s && console.log("[WorkerPool] Capturing span:", { operation: n.operationName, duration: `${n.duration}ms`, error: n.error, spanId: n.spanId, parentSpanId: n.parentSpanId }), process.env.SF_FUNCSPAN_CONSOLE_OUTPUT === "true" && console.log(`
481
+ function T(n) {
482
+ const t = P(), a = t?.sfDebug || !1;
483
+ a && console.log("[WorkerPool] Capturing span:", { operation: n.operationName, duration: `${n.duration}ms`, error: n.error, spanId: n.spanId, parentSpanId: n.parentSpanId }), process.env.SF_FUNCSPAN_CONSOLE_OUTPUT === "true" && console.log(`
497
484
  ⚙️ Worker Pool Operation:`, { operation: n.operationName, duration: `${n.duration.toFixed(2)}ms`, arguments: n.args, result: n.error ? `Error: ${n.error}` : n.result, spanId: n.spanId, parentSpanId: n.parentSpanId || "none" });
498
485
  const o = process.env.SF_FUNCSPAN_JSONL_FILE;
499
486
  if (o) try {
500
- const a = o === "true" || o === "1" ? "funcspans.jsonl" : o, i = Date.now(), e = process.hrtime.bigint(), r = BigInt(n.startTimeNs), u = Number(e - r) / 1e6, d = new Date(i - u).toISOString(), l = JSON.stringify({ timestamp: d, operationType: n.operationType, operationName: n.operationName, moduleName: n.moduleName, methodName: n.methodName, duration: n.duration, durationNs: n.durationNs, startTimeNs: n.startTimeNs, arguments: n.args, returnValue: n.error ? { error: String(n.error) } : n.result, spanId: n.spanId, parentSpanId: n.parentSpanId, pid: n.pid, threadId: n.threadId }) + `
487
+ const s = o === "true" || o === "1" ? "funcspans.jsonl" : o, i = Date.now(), e = process.hrtime.bigint(), r = BigInt(n.startTimeNs), u = Number(e - r) / 1e6, d = new Date(i - u).toISOString(), l = JSON.stringify({ timestamp: d, operationType: n.operationType, operationName: n.operationName, moduleName: n.moduleName, methodName: n.methodName, duration: n.duration, durationNs: n.durationNs, startTimeNs: n.startTimeNs, arguments: n.args, returnValue: n.error ? { error: String(n.error) } : n.result, spanId: n.spanId, parentSpanId: n.parentSpanId, pid: n.pid, threadId: n.threadId }) + `
501
488
  `;
502
- j(a, l, "utf-8");
503
- } catch (a) {
504
- console.error("[WorkerPool] Error writing to JSONL file:", a);
489
+ z(s, l, "utf-8");
490
+ } catch (s) {
491
+ console.error("[WorkerPool] Error writing to JSONL file:", s);
505
492
  }
506
- if (s && console.log("[WorkerPool] Sending span to transmitter"), process.env.SF_FUNCSPAN_SKIP_BACKEND !== "true") try {
507
- (F || (F = new Q()), F).send([n]), s && console.log("[WorkerPool] Span sent successfully");
508
- } catch (a) {
509
- s && console.error("[WorkerPool] Error sending span:", a);
493
+ if (a && console.log("[WorkerPool] Sending span to transmitter"), process.env.SF_FUNCSPAN_SKIP_BACKEND !== "true") try {
494
+ (v || (v = new G()), v).send([n]), a && console.log("[WorkerPool] Span sent successfully");
495
+ } catch (s) {
496
+ a && console.error("[WorkerPool] Error sending span:", s);
510
497
  }
511
498
  }
512
499
  export {
513
500
  x as B,
514
- Q as F,
515
- te as a,
516
- ne as b,
517
- le as c,
518
- ce as d,
519
- oe as e,
520
- k as f,
501
+ G as F,
502
+ ee as a,
503
+ te as b,
504
+ ue as c,
505
+ le as d,
506
+ se as e,
507
+ L as f,
521
508
  ae as g,
522
- ue as i,
523
- ie as m,
524
- D as n,
525
- re as p,
526
- se as s,
527
- K as t
509
+ ie as i,
510
+ oe as m,
511
+ C as n,
512
+ ne as p,
513
+ re as s,
514
+ w as t
528
515
  };
@@ -0,0 +1,83 @@
1
+ "use strict";const L=require("async_hooks"),W=require("fs"),v=require("worker_threads"),l=require("./contextManager-BkETRITg.cjs");class w{apiKey;endpoint;queryType="mutation";operationName="";serviceUUID=l.getConfig().serviceUUID;contextManager;constructor(){this.apiKey=l.getConfig().apiKey,this.endpoint=l.getConfig().apiGraphqlEndpoint,this.contextManager=l.ContextManager.getInstance()}get queryName(){return this.operationName?this.operationName.charAt(0).toLowerCase()+this.operationName.slice(1):""}getDefaultVariables(){const t=Date.now().toString(),o=this.contextManager.getOrSetSfTraceId(),s=this.contextManager.getCurrentFunctionSpanId();return{apiKey:this.apiKey,serviceUuid:this.serviceUUID,sessionId:o,timestampMs:t,parentSpanId:s}}getVariables(t={}){return{...this.getDefaultVariables(),...t}}setOperationName(t){this.operationName=t}setEndpoint(t){this.endpoint=t}setServiceUUID(t){this.serviceUUID=t}}const B=fetch;let _=!1;async function P(n,t,o,s){try{const a=l.getConfig();let i;try{i=JSON.stringify({query:o,variables:s,operationName:t})}catch{i=JSON.stringify({query:o,operationName:t})}_=!0,B(n,{method:"POST",headers:{"Content-Type":"application/json"},body:i}).then(async e=>{if(_=!1,!e.ok)return void(a.sfDebug&&console.error(`GraphQL request failed with status ${e.status} for ${t}`));const r=await e.json();r.errors?.length?(function(u,g,c){const d=u&&typeof u=="object"&&!Array.isArray(u)?Object.keys(u)[0]:void 0;console.error(d==="identifyServiceDetails"?`IdentifyServiceDetails NOT sent successfully for service: UUID=${c.serviceUUID}`:`GraphQL request failed with errors: ${JSON.stringify(g)} for operation key ${d}`)})(r.data,r.errors,a):a.sfDebug&&(function(u,g,c){const d=u&&typeof u=="object"&&!Array.isArray(u)?Object.keys(u)[0]:void 0,p=u[d]||!1;d==="identifyServiceDetails"&&(c.setServiceIdentificationReceived(p),l.getConfig().sfDebug&&console.log(`IdentifyServiceDetails sent successfully for service: UUID=${c.serviceUUID}; serviceIdentificationReceived=${d==="identifyServiceDetails"?p:"N/A"}`))})(r.data,0,a)}).catch(e=>{_=!1,a.sfDebug&&(console.error(`[RequestUtils] Fetch error for ${t} to ${n}:`,e),e.cause&&console.error("[RequestUtils] Error cause:",e.cause))})}catch(a){_=!1,l.getConfig().sfDebug&&console.error("Error sending data to GraphQL server:",a)}}function N(n,t){if(!n)return t;const o=n.toLowerCase();return o==="true"||o==="1"||o==="yes"}const I=new L.AsyncLocalStorage;function O(n,t){try{const o=JSON.stringify(n).length/1048576;return o<=t?n:{_truncated:!0,_originalSizeMB:o.toFixed(2),_limitMB:t,_preview:JSON.stringify(n).substring(0,500)+"..."}}catch{return{_error:"Failed to serialize data",_type:typeof n}}}function S(n,t){const o=process.env[n];return o===void 0?t:o==="true"||o==="1"}function R(n,t){const o=process.env[n];if(o===void 0)return t;const s=parseFloat(o);return isNaN(s)?t:s}function T(){return{enabled:S("SF_WORKER_POOL_ENABLED",!0),trackFs:S("SF_WORKER_POOL_TRACK_FS",!1),trackDns:S("SF_WORKER_POOL_TRACK_DNS",!0),trackCrypto:S("SF_WORKER_POOL_TRACK_CRYPTO",!1),trackZlib:S("SF_WORKER_POOL_TRACK_ZLIB",!1),captureArguments:S("SF_WORKER_POOL_CAPTURE_ARGUMENTS",!0),captureReturnValue:S("SF_WORKER_POOL_CAPTURE_RETURN_VALUE",!0),argLimitMb:R("SF_WORKER_POOL_ARG_LIMIT_MB",1),returnLimitMb:R("SF_WORKER_POOL_RETURN_LIMIT_MB",1)}}function E(n,t,o,s){let a;try{switch(n){case"fs":a=(function(i,e){const r={};switch(i){case"readFile":case"writeFile":case"appendFile":r.path=String(e[0]||""),e[1]&&typeof e[1]=="object"?(r.encoding=e[1].encoding||null,r.flag=e[1].flag||null):typeof e[1]=="string"&&(r.encoding=e[1]),i!=="writeFile"&&i!=="appendFile"||(Buffer.isBuffer(e[1])?(r.dataType="Buffer",r.dataSize=e[1].length):typeof e[1]=="string"&&(r.dataType="string",r.dataSize=e[1].length));break;case"readdir":case"stat":case"lstat":case"access":case"chmod":case"mkdir":case"rmdir":case"unlink":r.path=String(e[0]||""),e[1]&&typeof e[1]=="object"&&(r.options={...e[1]},delete r.options.callback);break;case"rename":r.oldPath=String(e[0]||""),r.newPath=String(e[1]||"");break;case"open":r.path=String(e[0]||""),r.flags=e[1],r.mode=e[2];break;case"close":case"fstat":r.fd=e[0];break;case"read":case"write":r.fd=e[0],Buffer.isBuffer(e[1])&&(r.bufferSize=e[1].length),r.offset=e[2],r.length=e[3],r.position=e[4];break;default:r.argsCount=e.length-1}return r})(t,o);break;case"dns":a=(function(i,e){const r={};switch(i){case"lookup":r.hostname=String(e[0]||""),typeof e[1]=="object"?(r.family=e[1].family,r.all=e[1].all):typeof e[1]=="number"&&(r.family=e[1]);break;case"resolve":case"resolve4":case"resolve6":case"resolveAny":case"resolveMx":case"resolveNs":case"resolveTxt":r.hostname=String(e[0]||"");break;case"reverse":r.ip=String(e[0]||"");break;default:r.argsCount=e.length-1}return r})(t,o);break;case"crypto":a=(function(i,e){const r={};switch(i){case"pbkdf2":r.passwordType=typeof e[0],r.saltType=typeof e[1],r.iterations=e[2],r.keylen=e[3],r.digest=e[4];break;case"scrypt":r.passwordType=typeof e[0],r.saltType=typeof e[1],r.keylen=e[2],typeof e[3]=="object"&&(r.N=e[3].N,r.r=e[3].r,r.p=e[3].p);break;case"randomBytes":r.size=e[0];break;case"generateKeyPair":r.type=e[0],typeof e[1]=="object"&&(r.modulusLength=e[1].modulusLength,r.namedCurve=e[1].namedCurve);break;default:r.argsCount=e.length-1}return r})(t,o);break;case"zlib":a=(function(i,e){const r={};return Buffer.isBuffer(e[0])?(r.inputType="Buffer",r.inputSize=e[0].length):typeof e[0]=="string"?(r.inputType="string",r.inputSize=e[0].length):r.inputType=typeof e[0],e[1]&&typeof e[1]=="object"&&typeof e[1]!="function"&&(r.options={...e[1]}),r})(0,o);break;default:return null}return s>0?O(a,s):a}catch{return{error:"Failed to capture arguments",argsCount:o.length-1}}}function D(n,t,o,s){let a;try{switch(n){case"fs":a=(function(i,e){if(!e)return null;switch(i){case"readFile":return Buffer.isBuffer(e)?{type:"Buffer",size:e.length}:typeof e=="string"?{type:"string",size:e.length}:{type:typeof e};case"readdir":return{count:Array.isArray(e)?e.length:0,items:e};case"stat":case"lstat":case"fstat":return{size:e.size,mode:e.mode,isFile:e.isFile(),isDirectory:e.isDirectory()};case"open":return{fd:e};case"read":return{bytesRead:e};case"write":return{bytesWritten:e};default:return e}})(t,o);break;case"dns":a=(function(i,e){if(!e)return null;switch(i){case"lookup":return Array.isArray(e)?{count:e.length,addresses:e}:e;case"resolve":case"resolve4":case"resolve6":case"resolveAny":case"resolveMx":case"resolveNs":case"resolveTxt":return{count:Array.isArray(e)?e.length:0,records:e};case"reverse":return{hostnames:e};default:return e}})(t,o);break;case"crypto":a=(function(i,e){if(!e)return null;switch(i){case"pbkdf2":case"scrypt":case"randomBytes":return Buffer.isBuffer(e)?{type:"Buffer",size:e.length}:{type:typeof e};case"generateKeyPair":return{hasPublicKey:!!e?.publicKey,hasPrivateKey:!!e?.privateKey};default:return e}})(t,o);break;case"zlib":a=(function(i,e){return e?Buffer.isBuffer(e)?{type:"Buffer",size:e.length}:typeof e=="string"?{type:"string",size:e.length}:{type:typeof e}:null})(0,o);break;default:return null}return s>0?O(a,s):a}catch{return{error:"Failed to capture result",type:typeof o}}}function K(n){return n.operationType==="worker_pool"}class M extends w{constructor(){super(),this.operationName="CollectFunctionSpans"}send(t){const o=l.getConfig().sfDebug;o&&console.log(`[FunctionSpanTransmitter] Preparing to send ${t.length} function span(s)`);for(const s of t)try{if(K(s)){this.sendWorkerPoolSpan(s,o);continue}const a=s;let i;if(a.result!==void 0&&a.result!==null){const r=typeof a.result;i=JSON.stringify({type:r,has_value:!0,value:a.result})}else i=a.result===null?JSON.stringify({type:"null",has_value:!0,value:null}):JSON.stringify({type:"undefined",has_value:!1,value:null});const e=this.getVariables({library:"JS/TS BACKEND",version:l.getConfig().version,spanId:a.spanId,parentSpanId:a.parentSpanId,filePath:a.filePath,lineNumber:a.metadata.line,columnNumber:a.metadata.column,functionName:a.functionName,arguments:JSON.stringify(a.args||{}),returnValue:i,startTimeNs:(1e6*Date.now()-1e6*a.duration).toString(),durationNs:(1e6*a.duration).toString()});o&&(console.log(`[FunctionSpanTransmitter] Sending GraphQL mutation to ${this.endpoint}`),console.log("[FunctionSpanTransmitter] Variables:",JSON.stringify(e,null,2))),P(this.endpoint,this.operationName,this.getQuery(),e),o&&console.log(`[FunctionSpanTransmitter] Queued function span for ${a.functionName}`)}catch(a){console.error(`[FunctionSpanTransmitter] Error preparing function span for ${s.functionName}:`,a)}}sendWorkerPoolSpan(t,o){try{let s;if(t.result!==void 0&&t.result!==null){const i=typeof t.result;s=JSON.stringify({type:i,has_value:!0,value:t.result})}else s=t.result===null?JSON.stringify({type:"null",has_value:!0,value:null}):JSON.stringify({type:"undefined",has_value:!1,value:null});const a=this.getVariables({library:"JS/TS BACKEND",version:l.getConfig().version,spanId:t.spanId,operationName:t.operationName,moduleName:t.moduleName,methodName:t.methodName,startTimeNs:t.startTimeNs,durationNs:t.durationNs,arguments:JSON.stringify(t.args||{}),returnValue:s,error:t.error,pid:t.pid,threadId:t.threadId});o&&(console.log(`[FunctionSpanTransmitter] Sending worker pool span: ${t.operationName}`),console.log("[FunctionSpanTransmitter] Variables:",JSON.stringify(a,null,2))),P(this.endpoint,"CollectWorkerPoolSpans",this.getWorkerPoolQuery(),a),o&&console.log(`[FunctionSpanTransmitter] Queued worker pool span for ${t.operationName}`)}catch(s){console.error(`[FunctionSpanTransmitter] Error preparing worker pool span for ${t.operationName}:`,s)}}getWorkerPoolQuery(){return`
2
+ mutation CollectWorkerPoolSpans(
3
+ $apiKey: String!,
4
+ $serviceUuid: String!,
5
+ $sessionId: String!,
6
+ $timestampMs: String!,
7
+ $library: String!,
8
+ $version: String!,
9
+ $spanId: String!,
10
+ $operationName: String!,
11
+ $moduleName: String!,
12
+ $methodName: String!,
13
+ $startTimeNs: String!,
14
+ $durationNs: String!,
15
+ $parentSpanId: String,
16
+ $arguments: String,
17
+ $returnValue: String,
18
+ $error: String,
19
+ $pid: Int,
20
+ $threadId: Int
21
+ ) {
22
+ collectWorkerPoolSpans(
23
+ apiKey: $apiKey,
24
+ serviceUuid: $serviceUuid,
25
+ sessionId: $sessionId,
26
+ timestampMs: $timestampMs,
27
+ library: $library,
28
+ version: $version,
29
+ spanId: $spanId,
30
+ operationName: $operationName,
31
+ moduleName: $moduleName,
32
+ methodName: $methodName,
33
+ startTimeNs: $startTimeNs,
34
+ durationNs: $durationNs,
35
+ parentSpanId: $parentSpanId,
36
+ arguments: $arguments,
37
+ returnValue: $returnValue,
38
+ error: $error,
39
+ pid: $pid,
40
+ threadId: $threadId
41
+ )
42
+ }
43
+ `}getQuery(){return`
44
+ ${this.queryType} ${this.operationName}(
45
+ $apiKey: String!,
46
+ $serviceUuid: String!,
47
+ $sessionId: String!,
48
+ $timestampMs: String!,
49
+ $parentSpanId: String,
50
+ $library: String!,
51
+ $version: String!,
52
+ $spanId: String!,
53
+ $filePath: String!,
54
+ $lineNumber: Int!,
55
+ $columnNumber: Int!,
56
+ $functionName: String!,
57
+ $arguments: String!,
58
+ $returnValue: String,
59
+ $startTimeNs: String!,
60
+ $durationNs: String!
61
+ ) {
62
+ ${this.queryName}(
63
+ apiKey: $apiKey,
64
+ serviceUuid: $serviceUuid,
65
+ sessionId: $sessionId,
66
+ timestampMs: $timestampMs,
67
+ parentSpanId: $parentSpanId,
68
+ library: $library,
69
+ version: $version,
70
+ spanId: $spanId,
71
+ filePath: $filePath,
72
+ lineNumber: $lineNumber,
73
+ columnNumber: $columnNumber,
74
+ functionName: $functionName,
75
+ arguments: $arguments,
76
+ returnValue: $returnValue,
77
+ startTimeNs: $startTimeNs,
78
+ durationNs: $durationNs
79
+ )
80
+ }
81
+ `}}let F=null;function k(n){const t=l.getGlobalConfigUnsafe(),o=t?.sfDebug||!1;o&&console.log("[WorkerPool] Capturing span:",{operation:n.operationName,duration:`${n.duration}ms`,error:n.error,spanId:n.spanId,parentSpanId:n.parentSpanId}),process.env.SF_FUNCSPAN_CONSOLE_OUTPUT==="true"&&console.log(`
82
+ ⚙️ Worker Pool Operation:`,{operation:n.operationName,duration:`${n.duration.toFixed(2)}ms`,arguments:n.args,result:n.error?`Error: ${n.error}`:n.result,spanId:n.spanId,parentSpanId:n.parentSpanId||"none"});const s=process.env.SF_FUNCSPAN_JSONL_FILE;if(s)try{const a=s==="true"||s==="1"?"funcspans.jsonl":s,i=Date.now(),e=process.hrtime.bigint(),r=BigInt(n.startTimeNs),u=Number(e-r)/1e6,g=new Date(i-u).toISOString(),c=JSON.stringify({timestamp:g,operationType:n.operationType,operationName:n.operationName,moduleName:n.moduleName,methodName:n.methodName,duration:n.duration,durationNs:n.durationNs,startTimeNs:n.startTimeNs,arguments:n.args,returnValue:n.error?{error:String(n.error)}:n.result,spanId:n.spanId,parentSpanId:n.parentSpanId,pid:n.pid,threadId:n.threadId})+`
83
+ `;W.appendFileSync(a,c,"utf-8")}catch(a){console.error("[WorkerPool] Error writing to JSONL file:",a)}if(o&&console.log("[WorkerPool] Sending span to transmitter"),process.env.SF_FUNCSPAN_SKIP_BACKEND!=="true")try{(F||(F=new M),F).send([n]),o&&console.log("[WorkerPool] Span sent successfully")}catch(a){o&&console.error("[WorkerPool] Error sending span:",a)}}exports.BaseTransmitter=w,exports.FunctionSpanTransmitter=M,exports.captureWorkerPoolOperation=function(n,t,o,s,a){const i=l.getGlobalConfigUnsafe(),e=i?.sfDebug||!1;e&&console.log(`[WorkerPool] Capturing ${n}.${t}`);const r=T(),u=l.ContextManager.getInstance().getCurrentFunctionSpanId(),g=l.v4();e&&console.log(`[WorkerPool] Span ID: ${g}, Parent: ${u||"none"}`);const c=new L.AsyncResource("WorkerPoolOperation"),d=process.hrtime.bigint();let p=null;r.captureArguments&&(p=E(n,t,s,r.argLimitMb));const f=s.findIndex(y=>typeof y=="function");if(f===-1)return e&&console.log(`[WorkerPool] No callback found for ${n}.${t}`),o.apply(a,s);const m=s[f],h=[...s];return h[f]=function(y,...$){const b=process.hrtime.bigint()-d,C=Number(b)/1e6;m(y,...$),c.runInAsyncScope(()=>{e&&console.log(`[WorkerPool] ${n}.${t} completed in ${C.toFixed(3)}ms (${b}ns)`);let A=null,U=null;y?U=y?.message||String(y):r.captureReturnValue&&$.length>0&&(A=D(n,t,$[0],r.returnLimitMb)),k({operationType:"worker_pool",operationName:`${n}.${t}`,moduleName:n,methodName:t,duration:C,durationNs:b.toString(),startTimeNs:d.toString(),args:p,result:A,error:U,spanId:g,parentSpanId:u,pid:process.pid,threadId:v.threadId})}),c.emitDestroy()},o.apply(a,h)},exports.captureWorkerPoolPromiseOperation=function(n,t,o,s,a){const i=l.getGlobalConfigUnsafe(),e=i?.sfDebug||!1;e&&console.log(`[WorkerPool] Capturing ${n}.${t} (Promise)`);const r=T(),u=l.ContextManager.getInstance().getCurrentFunctionSpanId(),g=l.v4();e&&console.log(`[WorkerPool] Span ID: ${g}, Parent: ${u||"none"}`);const c=process.hrtime.bigint();let d=null;return r.captureArguments&&(d=E(n,t,s,r.argLimitMb)),o.apply(a,s).then(p=>{const f=process.hrtime.bigint()-c,m=Number(f)/1e6;e&&console.log(`[WorkerPool] ${n}.${t} completed in ${m.toFixed(3)}ms (${f}ns)`);let h=null;return r.captureReturnValue&&(h=D(n,t,p,r.returnLimitMb)),k({operationType:"worker_pool",operationName:`${n}.${t}`,moduleName:n,methodName:t,duration:m,durationNs:f.toString(),startTimeNs:c.toString(),args:d,result:h,error:null,spanId:g,parentSpanId:u,pid:process.pid,threadId:v.threadId}),p},p=>{const f=process.hrtime.bigint()-c,m=Number(f)/1e6;throw e&&console.log(`[WorkerPool] ${n}.${t} failed in ${m.toFixed(3)}ms: ${p?.message||p}`),k({operationType:"worker_pool",operationName:`${n}.${t}`,moduleName:n,methodName:t,duration:m,durationNs:f.toString(),startTimeNs:c.toString(),args:d,result:null,error:p?.message||String(p),spanId:g,parentSpanId:u,pid:process.pid,threadId:v.threadId}),p})},exports.clearFuncspanOverride=function(){},exports.funcspanOverrideStorage=I,exports.getDefaultConfig=function(){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}},exports.getEnvConfig=function(){return{capture_arguments:N(process.env.SF_FUNCSPAN_CAPTURE_ARGUMENTS,!0),capture_return_value:N(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:N(process.env.SF_FUNCSPAN_AUTOCAPTURE_ALL_CHILD_FUNCTIONS,!1),sample_rate:parseFloat(process.env.SF_FUNCSPAN_SAMPLE_RATE||"1.0"),enable_sampling:N(process.env.SF_FUNCSPAN_ENABLE_SAMPLING,!1),capture_sf_veritas:N(process.env.SF_FUNCSPAN_CAPTURE_SF_VERITAS,!1),parse_json_strings:N(process.env.SF_FUNCSPAN_PARSE_JSON_STRINGS,!1)}},exports.getFuncspanOverride=function(){return I.getStore()},exports.isModuleTrackingEnabled=function(n){const t=T();if(!t.enabled)return!1;switch(n){case"fs":return t.trackFs;case"dns":return t.trackDns;case"crypto":return t.trackCrypto;case"zlib":return t.trackZlib;default:return!1}},exports.mergeConfigs=function(...n){const t={};for(const o of n)for(const s in o)o[s]!==void 0&&(t[s]=o[s]);return t},exports.nonBlockingPost=P,exports.parseHeaderOverride=function(n){try{const t=n.split("-");return t.length!==9?(console.error(`[FuncSpan] Invalid header format: expected 9 parts, got ${t.length}`),null):{capture_arguments:t[0]==="1",capture_return_value:t[1]==="1",arg_limit_mb:parseInt(t[2],10),return_limit_mb:parseInt(t[3],10),autocapture_all_child_functions:t[4]==="1",sample_rate:parseFloat(t[5]),enable_sampling:t[6]==="1",capture_sf_veritas:t[7]==="1",parse_json_strings:t[8]==="1"}}catch(t){return console.error(`[FuncSpan] Failed to parse header override "${n}":`,t),null}},exports.setFuncspanOverride=function(n){I.enterWith(n)},exports.truncateToLimit=O;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sailfish-ai/sf-veritas",
3
- "version": "0.2.11",
3
+ "version": "0.2.13",
4
4
  "publishPublicly": true,
5
5
  "description": "A versatile Edge Runtime-compatible package for JavaScript and TypeScript backend systems and scripts.",
6
6
  "main": "./dist/sf-veritas.cjs",
@@ -60,11 +60,15 @@
60
60
  },
61
61
  "scripts": {
62
62
  "build:types": "vite build --mode types",
63
+ "build:esm": "vite build",
64
+ "build:cjs": "vite build --config vite.config.node.ts",
63
65
  "dev": "vite",
64
66
  "lint": "eslint ./src --ext .ts",
65
67
  "test": "vitest",
68
+ "test:fake-document": "node scripts/test-fake-document.js",
69
+ "check:no-dom-in-cjs": "node -e \"const fs=require('fs'),g=require('glob');const files=g.sync('dist/**/*.cjs');let bad=false;for(const f of files){const s=fs.readFileSync(f,'utf8');if(/document\\.|currentScript|baseURI/.test(s)){console.error('DOM polyfill in:',f);bad=true;}}if(bad)process.exit(1);console.log('No DOM polyfills in CJS');\"",
66
70
  "prebuild": "node --import 'data:text/javascript,import { register } from \"node:module\"; import { pathToFileURL } from \"node:url\"; register(\"ts-node/esm\", pathToFileURL(\"./\"));' scripts/build-script.ts",
67
- "build": "vite build && tsc --emitDeclarationOnly && npm run prebuild",
71
+ "build": "npm run build:esm && npm run build:cjs && npm run check:no-dom-in-cjs && tsc --emitDeclarationOnly && npm run prebuild",
68
72
  "check-types": "tsc --noEmit",
69
73
  "prepublish": "npm run build && npm run check-types",
70
74
  "artifactregistry-login": "npx google-artifactregistry-auth",