@sailfish-ai/sf-veritas 0.2.11 → 0.2.12

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,6 +1,6 @@
1
1
  import { readFileSync as l } from "fs";
2
2
  import { t as d } from "../funcSpanTransformer-CWNEWRxq.js";
3
- import { s as r } from "../runtimeConfig-emBNO3lJ.js";
3
+ import { s as r } from "../runtimeConfig-CgLfwL3X.js";
4
4
  function h(o = {}) {
5
5
  try {
6
6
  if (r()) return console.warn("[FuncSpan Esbuild Plugin] Runtime mode active - build plugin DISABLED to prevent double-instrumentation"), { name: "sailfish-funcspan-esbuild-disabled", setup() {
@@ -1,5 +1,5 @@
1
1
  import { t as i } from "../funcSpanTransformer-CWNEWRxq.js";
2
- import { s as r } from "../runtimeConfig-emBNO3lJ.js";
2
+ import { s as r } from "../runtimeConfig-CgLfwL3X.js";
3
3
  function c(o = {}) {
4
4
  try {
5
5
  if (r()) return console.warn("[FuncSpan Rollup Plugin] Runtime mode active - build plugin DISABLED to prevent double-instrumentation"), { name: "sailfish-funcspan-rollup-disabled" };
@@ -2,7 +2,7 @@ import { readFileSync as m, writeFileSync as l } from "fs";
2
2
  import { sync as g } from "glob";
3
3
  import { resolve as C } from "path";
4
4
  import { t as _ } from "../funcSpanTransformer-CWNEWRxq.js";
5
- import { s as N } from "../runtimeConfig-emBNO3lJ.js";
5
+ import { s as N } from "../runtimeConfig-CgLfwL3X.js";
6
6
  async function D(n = {}) {
7
7
  try {
8
8
  if (N()) return void console.warn("[FuncSpan TSC Plugin] Runtime mode active - build plugin DISABLED to prevent double-instrumentation");
@@ -1,5 +1,5 @@
1
1
  import { t as o } from "../funcSpanTransformer-CWNEWRxq.js";
2
- import { s as l } from "../runtimeConfig-emBNO3lJ.js";
2
+ import { s as l } from "../runtimeConfig-CgLfwL3X.js";
3
3
  function d(u = {}) {
4
4
  try {
5
5
  if (l()) return console.warn("[FuncSpan Vite Plugin] Runtime mode active - build plugin DISABLED to prevent double-instrumentation"), { name: "sailfish-funcspan-vite-disabled" };
@@ -1,7 +1,7 @@
1
1
  var k = Object.defineProperty;
2
2
  var m = (r, o, s) => o in r ? k(r, o, { enumerable: !0, configurable: !0, writable: !0, value: s }) : r[o] = s;
3
3
  var c = (r, o, s) => m(r, typeof o != "symbol" ? o + "" : o, s);
4
- import { s as b } from "../runtimeConfig-emBNO3lJ.js";
4
+ import { s as b } from "../runtimeConfig-CgLfwL3X.js";
5
5
  import * as P from "path";
6
6
  import { dirname as T } from "path";
7
7
  import { fileURLToPath as f } from "url";
@@ -342,8 +342,8 @@ export {
342
342
  L as a,
343
343
  Zg as b,
344
344
  dg as c,
345
- ng as d,
346
- og as e,
345
+ og as d,
346
+ ng as e,
347
347
  j as h,
348
348
  W as i,
349
349
  Gg as s
@@ -1,4 +1,4 @@
1
- "use strict";var ce=Object.defineProperty;var de=(n,e,t)=>e in n?ce(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var I=(n,e,t)=>de(n,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("./contextManager-CGINtRN5.cjs"),p=require("./workerPoolSpanCapture-Dg_WGjmO.cjs"),h=require("./runtimeConfig-CpQ27dZD.cjs"),le=require("node:module"),W=require("fs"),ue=require("./source-map-rHHEdpre.cjs"),pe=require("path"),ge=require("glob"),E=require("worker_threads"),O=require("./funcSpanTransformer-B9WWl-g1.cjs");var L=typeof document<"u"?document.currentScript:null;function ae(n){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const t in n)if(t!=="default"){const o=Object.getOwnPropertyDescriptor(n,t);Object.defineProperty(e,t,o.get?o:{enumerable:!0,get:()=>n[t]})}}return e.default=n,Object.freeze(e)}const k=ae(W),$=ae(pe);class N extends p.BaseTransmitter{constructor(){super(),this.setOperationName("IdentifyServiceDetails")}async doSend(e){if(!c.getConfig().serviceIdentificationReceived)try{this.send()}catch(t){c.getConfig().sfDebug&&console.error(" Error during service identification:",t)}}async send(){const e=`
1
+ "use strict";var ce=Object.defineProperty;var de=(n,e,t)=>e in n?ce(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var I=(n,e,t)=>de(n,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("./contextManager-CGINtRN5.cjs"),p=require("./workerPoolSpanCapture-BQ3Pbkl2.cjs"),h=require("./runtimeConfig-CpQ27dZD.cjs"),le=require("node:module"),W=require("fs"),ue=require("./source-map-rHHEdpre.cjs"),pe=require("path"),ge=require("glob"),E=require("worker_threads"),O=require("./funcSpanTransformer-B9WWl-g1.cjs");var L=typeof document<"u"?document.currentScript:null;function ae(n){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const t in n)if(t!=="default"){const o=Object.getOwnPropertyDescriptor(n,t);Object.defineProperty(e,t,o.get?o:{enumerable:!0,get:()=>n[t]})}}return e.default=n,Object.freeze(e)}const k=ae(W),b=ae(pe);class N extends p.BaseTransmitter{constructor(){super(),this.setOperationName("IdentifyServiceDetails")}async doSend(e){if(!c.getConfig().serviceIdentificationReceived)try{this.send()}catch(t){c.getConfig().sfDebug&&console.error(" Error during service identification:",t)}}async send(){const e=`
2
2
  ${this.queryType} ${this.operationName}(
3
3
  $apiKey: String!,
4
4
  $timestampMs: String!,
@@ -121,8 +121,8 @@
121
121
  ${this.queryName}(
122
122
  data: $data)
123
123
  }
124
- `}async send(t){const o={data:{...t}};await p.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),o)}}const q=[400,403];class $e{constructor(e=[]){I(this,"HEADER_TRACING","X-Sf3-Rid");I(this,"HEADER_LOG_GUARD","reentrancy_guard_logging_preactive");I(this,"HEADER_PRINT_GUARD","reentrancy_guard_print_preactive");I(this,"HEADER_EXCEPTION_GUARD","reentrancy_guard_exception_preactive");I(this,"contextManager");this.contextManager=c.ContextManager.getInstance(),e?.forEach(t=>{typeof t=="string"&&t.trim()&&this.contextManager.getExcludedDomains().add(t)}),c.getConfig().sfDebug&&console.log("[RequestInterceptor] Initialized with static excluded domains.")}extractIdsFromTraceHeader(e,t=this.HEADER_TRACING){let o;if(e instanceof Headers)o=e.get(t)??void 0;else{const i=t.toLowerCase();for(const[l,s]of Object.entries(e))if(l.toLowerCase()===i){o=s;break}}if(!o)return{};const r=o.split("/").filter(Boolean);return r.length<3?{}:{sessionId:r[0],pageVisitId:r[1],requestId:r[r.length-1]}}parseStackFrame(e){const t=/\((.*):(\d+):(\d+)\)$/.exec(e.trim());if(!t)return null;const[,o,r,i]=t;return{filePath:o,line:parseInt(r,10),column:parseInt(i,10)}}async getOriginalPosition(e,t,o){let r={source:e,line:t,column:o,name:null};const i=e+".map";try{const l=JSON.parse(W.readFileSync(i,"utf-8"));let s=(await new ue.sourceMapExports.SourceMapConsumer(l)).originalPositionFor({line:t,column:o});s.source&&(r=s)}catch(l){c.getConfig().sfDebug&&console.error(`Could not read/parse map file at ${i}:`,l)}return{originalPos:r}}captureFirstUserLines(e,t=10,o=!1){const r=c.getConfig().sfDebug?10:t,i=Error.stackTraceLimit;Error.stackTraceLimit=Math.max(i,r);const l=new Error(J);J in Error&&Error.captureStackTrace(l,this.captureFirstUserLines);const s=l.stack||"";Error.stackTraceLimit=i;const d=s.split(`
125
- `).slice(1),a=[];for(const u of d)if(!(u.includes("node:internal")||u.includes("internal/modules")||u.includes("internal/process")||u.includes("node_modules")||u.includes(".next/server/chunks")||u.includes("RequestInterceptor")||u.includes("contextManager")||u.includes("setupConfig"))&&(a.push(u.trim()),a.length>=t))break;for(const u of a){const f=this.parseStackFrame(u);f?(async()=>{const{originalPos:m}=await this.getOriginalPosition(f.filePath,f.line,f.column);if(m){c.getConfig().sfDebug&&console.log("[RequestInterceptor] First user code line:",m);const y={line:m.line?.toString()||P.UNKNOWN,column:m.column?.toString()||P.NOT_CAPTURED,name:m.name||P.NOT_CAPTURED,entrypoint:m.source,retryWithoutTraceId:o};e.doSend(y)}})():c.getConfig().sfDebug&&console.error("Could not parse stack line:",u)}}addReentrancyGuardHeaders(e){e.set(this.HEADER_LOG_GUARD,"true"),e.set(this.HEADER_PRINT_GUARD,"true"),e.set(this.HEADER_EXCEPTION_GUARD,"true")}shouldPropagateHeaders(e){return!c.DEFAULT_DOMAINS_TO_EXCLUDE.some(t=>new RegExp(`^${t.replace(/\*/g,".*")}$`).test(e))}addTracingHeaders(e,t){const o=new URL(t).hostname,r=this.shouldPropagateHeaders(o);return r?this.addTracingHeader(e,t):c.getConfig().sfDebug&&console.error(`[RequestInterceptor] Excluded domain: ${o}`),r}addTracingHeader(e,t){const o=p.getFuncspanOverride();if(o){const s=p.parseHeaderOverride(o);if(s&&s.sample_rate===0)return void(c.getConfig().sfDebug&&console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${t}`))}const r=this.contextManager.getOrSetSfTraceId(),i=this.contextManager.getOrSetPageVisitUUID(),l=c.v4();e.set(this.HEADER_TRACING,`${r}/${i}/${l}`),c.getConfig().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${t}`)}patchFetch(e,t){const o=globalThis.fetch;typeof o=="function"?globalThis.fetch=async(r,i)=>{const l=new Headers(i?.headers);if(l.get(this.HEADER_LOG_GUARD)==="true"||l.get(this.HEADER_PRINT_GUARD)==="true"||l.get(this.HEADER_EXCEPTION_GUARD)==="true")return o(r,i);this.captureFirstUserLines(e);const s=Date.now();let d;typeof r=="string"||r instanceof URL?d=r.toString():r instanceof Request?(d=r.url,r.headers.forEach((g,S)=>{l.set(S,g)})):c.getConfig().sfDebug&&console.error("[Sailfish RequestInterceptor] Invalid fetch input."),c.getConfig().sfDebug&&console.log("[RequestInterceptor] Fetching request to:",d);const a=new URL(d).hostname,u=new Headers(l),f=this.addTracingHeaders(l,d),m={...i,headers:l};let y;try{let g=!1;this.addTracingHeaders(u,d),y=await o(d,m),f&&q.includes(y.status)?(y=await o(d,{...i,headers:u}),g=!0,this.captureFirstUserLines(e,10,g)):this.contextManager.addSupportedDomains(a);const S=Date.now();c.getConfig().sfDebug&&console.log(`[RequestInterceptor] Fetch completed: ${d}, Status: ${y.status}, Duration: ${S-s}ms`);const{sessionId:_,pageVisitId:v,requestId:b}=this.extractIdsFromTraceHeader(l);return t.doSend({apiKey:c.getConfig().apiKey,requestId:b,pageVisitId:v,recordingSessionId:_,serviceUuid:c.getConfig().serviceUUID,timestampStart:s.toString(),timestampEnd:S.toString(),responseCode:y.status,success:!0,error:null,url:d,method:m.method||"GET",retryWithoutTraceId:g,parentSpanId:c.getCurrentFunctionSpanId()}),y}catch(g){const S=Date.now();c.getConfig().sfDebug&&console.error(`[RequestInterceptor] Fetch failed: ${d}, Error: ${g}, Duration: ${S-s}ms`)}}:c.getConfig().sfDebug&&console.error("[RequestInterceptor] Fetch not available.")}patchHttp(e,t){if(c.getConfig().sfDebug&&console.log("[RequestInterceptor] Initializing HTTP/HTTPS request patch..."),!h.https||typeof h.https.request!="function")return void(c.getConfig().sfDebug&&console.log("[RequestInterceptor] HTTP/HTTPS not available."));const o=h.https.request.bind(h.https),r=h.https.request.bind(h.https);h.https.request=function(i,l){let s;try{if(typeof i=="string"){const a=new URL(i);s={protocol:a.protocol||R,hostname:a.hostname,path:a.pathname+a.search,headers:{}}}else i instanceof URL?s={protocol:i.protocol||R,hostname:i.hostname,path:i.pathname+i.search,headers:{}}:(s={...i},s.protocol||(s.protocol=R));if(s.headers){const a=`${s.protocol}//${s.hostname}`;this.addTracingHeaders(s.headers,a),this.captureFirstUserLines(e)}else c.getConfig().sfDebug&&console.warn("[RequestInterceptor] No headers found in HTTP request options. Skipping header addition.")}catch(a){throw c.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTP request options:",a),a}let d=!1;return o(s,a=>{const u=`${s.protocol}//${s.hostname}`;if(s.headers&&this.shouldPropagateHeaders(new URL(u).hostname)&&q.includes(a.statusCode||0)){s.hostname;const g={...s,headers:{...s.headers}};delete g.headers[this.HEADER_TRACING],o(g,l),d=!0,this.captureFirstUserLines(e,10,d)}const{sessionId:f,pageVisitId:m,requestId:y}=this.extractIdsFromTraceHeader(s.headers);t.doSend({apiKey:c.getConfig().apiKey,requestId:y,pageVisitId:m,recordingSessionId:f,serviceUuid:c.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:a.statusCode||0,success:!!a.statusCode&&a.statusCode<400,error:null,url:u,method:s.method||"GET",retryWithoutTraceId:d,parentSpanId:c.getCurrentFunctionSpanId()}),l?.(a)})},h.https.request=function(i,l){let s;try{if(typeof i=="string"){const a=new URL(i);s={protocol:a.protocol||A,hostname:a.hostname,path:a.pathname+a.search,headers:{}}}else i instanceof URL?s={protocol:i.protocol||A,hostname:i.hostname,path:i.pathname+i.search,headers:{}}:(s={...i},s.protocol||(s.protocol=A));if(s.headers){const a=`${s.protocol}//${s.hostname}`;this.addTracingHeaders(s.headers,a)}else c.getConfig().sfDebug&&console.warn("[RequestInterceptor] No headers found in HTTPS request options. Skipping header addition.")}catch(a){throw c.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTPS request options:",a),a}let d=!1;return r(s,a=>{const u=`${s.protocol}//${s.hostname}`;if(s.headers&&this.shouldPropagateHeaders(new URL(u).hostname)&&q.includes(a.statusCode||0)){const g={...s,headers:{...s.headers}};delete g.headers[this.HEADER_TRACING],r(g,l),d=!0,this.captureFirstUserLines(e,10,d)}const{sessionId:f,pageVisitId:m,requestId:y}=this.extractIdsFromTraceHeader(s.headers);t.doSend({apiKey:c.getConfig().apiKey,requestId:y,pageVisitId:m,recordingSessionId:f,serviceUuid:c.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:a.statusCode||0,success:!!a.statusCode&&a.statusCode<400,error:null,url:u,method:s.method||"GET",retryWithoutTraceId:d,parentSpanId:c.getCurrentFunctionSpanId()}),l?.(a)})},c.getConfig().sfDebug&&console.log("✅ HTTP and HTTPS request methods patched globally.")}tryPatch(e,t){try{require.resolve(t),e(),console.log(`[RequestInterceptor] Patched ${t}`)}catch(o){console.warn(`[RequestInterceptor] Could not patch ${t}: ${o.message}`)}}getExcludedDomains(){return[...this.contextManager.getExcludedDomains()]}}class be extends K{constructor(){super(),this.setOperationName("UpdateServiceDetails")}async doSend(){this.sendAppIdentifier(),this.send()}async send(){const e=`
124
+ `}async send(t){const o={data:{...t}};await p.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),o)}}const M=[400,403];class be{constructor(e=[]){I(this,"HEADER_TRACING","X-Sf3-Rid");I(this,"HEADER_LOG_GUARD","reentrancy_guard_logging_preactive");I(this,"HEADER_PRINT_GUARD","reentrancy_guard_print_preactive");I(this,"HEADER_EXCEPTION_GUARD","reentrancy_guard_exception_preactive");I(this,"contextManager");this.contextManager=c.ContextManager.getInstance(),e?.forEach(t=>{typeof t=="string"&&t.trim()&&this.contextManager.getExcludedDomains().add(t)}),c.getConfig().sfDebug&&console.log("[RequestInterceptor] Initialized with static excluded domains.")}extractIdsFromTraceHeader(e,t=this.HEADER_TRACING){let o;if(e instanceof Headers)o=e.get(t)??void 0;else{const i=t.toLowerCase();for(const[l,s]of Object.entries(e))if(l.toLowerCase()===i){o=s;break}}if(!o)return{};const r=o.split("/").filter(Boolean);return r.length<3?{}:{sessionId:r[0],pageVisitId:r[1],requestId:r[r.length-1]}}parseStackFrame(e){const t=/\((.*):(\d+):(\d+)\)$/.exec(e.trim());if(!t)return null;const[,o,r,i]=t;return{filePath:o,line:parseInt(r,10),column:parseInt(i,10)}}async getOriginalPosition(e,t,o){let r={source:e,line:t,column:o,name:null};const i=e+".map";try{const l=JSON.parse(W.readFileSync(i,"utf-8"));let s=(await new ue.sourceMapExports.SourceMapConsumer(l)).originalPositionFor({line:t,column:o});s.source&&(r=s)}catch(l){c.getConfig().sfDebug&&console.error(`Could not read/parse map file at ${i}:`,l)}return{originalPos:r}}captureFirstUserLines(e,t=10,o=!1){const r=c.getConfig().sfDebug?10:t,i=Error.stackTraceLimit;Error.stackTraceLimit=Math.max(i,r);const l=new Error(J);J in Error&&Error.captureStackTrace(l,this.captureFirstUserLines);const s=l.stack||"";Error.stackTraceLimit=i;const d=s.split(`
125
+ `).slice(1),a=[];for(const u of d)if(!(u.includes("node:internal")||u.includes("internal/modules")||u.includes("internal/process")||u.includes("node_modules")||u.includes(".next/server/chunks")||u.includes("RequestInterceptor")||u.includes("contextManager")||u.includes("setupConfig"))&&(a.push(u.trim()),a.length>=t))break;for(const u of a){const f=this.parseStackFrame(u);f?(async()=>{const{originalPos:m}=await this.getOriginalPosition(f.filePath,f.line,f.column);if(m){c.getConfig().sfDebug&&console.log("[RequestInterceptor] First user code line:",m);const y={line:m.line?.toString()||P.UNKNOWN,column:m.column?.toString()||P.NOT_CAPTURED,name:m.name||P.NOT_CAPTURED,entrypoint:m.source,retryWithoutTraceId:o};e.doSend(y)}})():c.getConfig().sfDebug&&console.error("Could not parse stack line:",u)}}addReentrancyGuardHeaders(e){e.set(this.HEADER_LOG_GUARD,"true"),e.set(this.HEADER_PRINT_GUARD,"true"),e.set(this.HEADER_EXCEPTION_GUARD,"true")}shouldPropagateHeaders(e){return!c.DEFAULT_DOMAINS_TO_EXCLUDE.some(t=>new RegExp(`^${t.replace(/\*/g,".*")}$`).test(e))}addTracingHeaders(e,t){const o=new URL(t).hostname,r=this.shouldPropagateHeaders(o);return r?this.addTracingHeader(e,t):c.getConfig().sfDebug&&console.error(`[RequestInterceptor] Excluded domain: ${o}`),r}addTracingHeader(e,t){const o=p.getFuncspanOverride();if(o){const s=p.parseHeaderOverride(o);if(s&&s.sample_rate===0)return void(c.getConfig().sfDebug&&console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${t}`))}const r=this.contextManager.getOrSetSfTraceId(),i=this.contextManager.getOrSetPageVisitUUID(),l=c.v4();e.set(this.HEADER_TRACING,`${r}/${i}/${l}`),c.getConfig().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${t}`)}patchFetch(e,t){const o=globalThis.fetch;typeof o=="function"?globalThis.fetch=async(r,i)=>{const l=new Headers(i?.headers);if(l.get(this.HEADER_LOG_GUARD)==="true"||l.get(this.HEADER_PRINT_GUARD)==="true"||l.get(this.HEADER_EXCEPTION_GUARD)==="true")return o(r,i);this.captureFirstUserLines(e);const s=Date.now();let d;typeof r=="string"||r instanceof URL?d=r.toString():r instanceof Request?(d=r.url,r.headers.forEach((g,S)=>{l.set(S,g)})):c.getConfig().sfDebug&&console.error("[Sailfish RequestInterceptor] Invalid fetch input."),c.getConfig().sfDebug&&console.log("[RequestInterceptor] Fetching request to:",d);const a=new URL(d).hostname,u=new Headers(l),f=this.addTracingHeaders(l,d),m={...i,headers:l};let y;try{let g=!1;this.addTracingHeaders(u,d),y=await o(d,m),f&&M.includes(y.status)?(y=await o(d,{...i,headers:u}),g=!0,this.captureFirstUserLines(e,10,g)):this.contextManager.addSupportedDomains(a);const S=Date.now();c.getConfig().sfDebug&&console.log(`[RequestInterceptor] Fetch completed: ${d}, Status: ${y.status}, Duration: ${S-s}ms`);const{sessionId:_,pageVisitId:v,requestId:$}=this.extractIdsFromTraceHeader(l);return t.doSend({apiKey:c.getConfig().apiKey,requestId:$,pageVisitId:v,recordingSessionId:_,serviceUuid:c.getConfig().serviceUUID,timestampStart:s.toString(),timestampEnd:S.toString(),responseCode:y.status,success:!0,error:null,url:d,method:m.method||"GET",retryWithoutTraceId:g,parentSpanId:c.getCurrentFunctionSpanId()}),y}catch(g){const S=Date.now();c.getConfig().sfDebug&&console.error(`[RequestInterceptor] Fetch failed: ${d}, Error: ${g}, Duration: ${S-s}ms`)}}:c.getConfig().sfDebug&&console.error("[RequestInterceptor] Fetch not available.")}patchHttp(e,t){if(c.getConfig().sfDebug&&console.log("[RequestInterceptor] Initializing HTTP/HTTPS request patch..."),!h.https||typeof h.https.request!="function")return void(c.getConfig().sfDebug&&console.log("[RequestInterceptor] HTTP/HTTPS not available."));const o=h.https.request.bind(h.https),r=h.https.request.bind(h.https);h.https.request=function(i,l){let s;try{if(typeof i=="string"){const a=new URL(i);s={protocol:a.protocol||R,hostname:a.hostname,path:a.pathname+a.search,headers:{}}}else i instanceof URL?s={protocol:i.protocol||R,hostname:i.hostname,path:i.pathname+i.search,headers:{}}:(s={...i},s.protocol||(s.protocol=R));if(s.headers){const a=`${s.protocol}//${s.hostname}`;this.addTracingHeaders(s.headers,a),this.captureFirstUserLines(e)}else c.getConfig().sfDebug&&console.warn("[RequestInterceptor] No headers found in HTTP request options. Skipping header addition.")}catch(a){throw c.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTP request options:",a),a}let d=!1;return o(s,a=>{const u=`${s.protocol}//${s.hostname}`;if(s.headers&&this.shouldPropagateHeaders(new URL(u).hostname)&&M.includes(a.statusCode||0)){s.hostname;const g={...s,headers:{...s.headers}};delete g.headers[this.HEADER_TRACING],o(g,l),d=!0,this.captureFirstUserLines(e,10,d)}const{sessionId:f,pageVisitId:m,requestId:y}=this.extractIdsFromTraceHeader(s.headers);t.doSend({apiKey:c.getConfig().apiKey,requestId:y,pageVisitId:m,recordingSessionId:f,serviceUuid:c.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:a.statusCode||0,success:!!a.statusCode&&a.statusCode<400,error:null,url:u,method:s.method||"GET",retryWithoutTraceId:d,parentSpanId:c.getCurrentFunctionSpanId()}),l?.(a)})},h.https.request=function(i,l){let s;try{if(typeof i=="string"){const a=new URL(i);s={protocol:a.protocol||A,hostname:a.hostname,path:a.pathname+a.search,headers:{}}}else i instanceof URL?s={protocol:i.protocol||A,hostname:i.hostname,path:i.pathname+i.search,headers:{}}:(s={...i},s.protocol||(s.protocol=A));if(s.headers){const a=`${s.protocol}//${s.hostname}`;this.addTracingHeaders(s.headers,a)}else c.getConfig().sfDebug&&console.warn("[RequestInterceptor] No headers found in HTTPS request options. Skipping header addition.")}catch(a){throw c.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTPS request options:",a),a}let d=!1;return r(s,a=>{const u=`${s.protocol}//${s.hostname}`;if(s.headers&&this.shouldPropagateHeaders(new URL(u).hostname)&&M.includes(a.statusCode||0)){const g={...s,headers:{...s.headers}};delete g.headers[this.HEADER_TRACING],r(g,l),d=!0,this.captureFirstUserLines(e,10,d)}const{sessionId:f,pageVisitId:m,requestId:y}=this.extractIdsFromTraceHeader(s.headers);t.doSend({apiKey:c.getConfig().apiKey,requestId:y,pageVisitId:m,recordingSessionId:f,serviceUuid:c.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:a.statusCode||0,success:!!a.statusCode&&a.statusCode<400,error:null,url:u,method:s.method||"GET",retryWithoutTraceId:d,parentSpanId:c.getCurrentFunctionSpanId()}),l?.(a)})},c.getConfig().sfDebug&&console.log("✅ HTTP and HTTPS request methods patched globally.")}tryPatch(e,t){try{require.resolve(t),e()}catch{}}getExcludedDomains(){return[...this.contextManager.getExcludedDomains()]}}class $e extends K{constructor(){super(),this.setOperationName("UpdateServiceDetails")}async doSend(){this.sendAppIdentifier(),this.send()}async send(){const e=`
126
126
  ${this.queryType} ${this.operationName}(
127
127
  $apiKey: String!,
128
128
  $serviceUuid: String!,
@@ -142,6 +142,6 @@
142
142
  gitSha: $gitSha,
143
143
  )
144
144
  }
145
- `,t=this.getVariables({serviceIdentifier:c.getConfig().serviceIdentifier,serviceVersion:c.getConfig().serviceVersion,serviceAdditionalMetadata:c.getConfig().serviceAdditionalMetadata,gitSha:c.getConfig().gitSha||""});p.nonBlockingPost(this.endpoint,this.operationName,e,t)}}class Ce{constructor(e=[process.cwd()],t=!1){I(this,"rootPaths");I(this,"fileConfigs",new Map);I(this,"functionConfigs",new Map);I(this,"directoryConfigs",new Map);I(this,"hasSailfishFiles",!1);I(this,"runtimeModeEnabled",!1);I(this,"debug");this.rootPaths=e,this.debug=t||process.env.SF_DEBUG==="true"}async loadAllConfigs(){this.debug&&console.log("[FuncSpan ConfigLoader] Scanning for .sailfish files in:",this.rootPaths);const e=[];for(const t of this.rootPaths)k.existsSync(t)?await this._walkDirectory(t,e):this.debug&&console.log(`[FuncSpan ConfigLoader] Root path does not exist: ${t}`);e.length>0?(this.hasSailfishFiles=!0,this.debug&&(console.log(`[FuncSpan ConfigLoader] Found ${e.length} .sailfish files:`),e.forEach(t=>console.log(`[FuncSpan ConfigLoader] - ${t}`)))):this.debug&&console.log("[FuncSpan ConfigLoader] No .sailfish files found - function spans disabled by default");for(const t of e)await this._loadConfigFile(t);await this._resolveInheritance(),this.debug&&console.log(`[FuncSpan ConfigLoader] Loaded ${this.fileConfigs.size} file configs, ${this.functionConfigs.size} function configs`)}getConfig(e,t){const o=this.hasSailfishFiles?p.getEnvConfig():p.getDefaultConfig(),r=this._getDirectoryConfig(e),i=$.normalize(e),l=this.fileConfigs.get(i)||{};let s={};if(t){const d=this.functionConfigs.get(i);d&&(s=d.get(t)||{})}return p.mergeConfigs(o,r,l,s)}hasRuntimeMode(){return this.runtimeModeEnabled}async _walkDirectory(e,t){try{const o=k.readdirSync(e,{withFileTypes:!0});for(const r of o){const i=$.join(e,r.name);r.isFile()&&r.name===".sailfish"?t.push(i):r.name==="node_modules"||r.isDirectory()&&r.name.startsWith(".")&&r.name!==".sailfish"||r.isDirectory()&&await this._walkDirectory(i,t)}}catch(o){this.debug&&console.error(`[FuncSpan ConfigLoader] Error walking directory ${e}:`,o)}}async _loadConfigFile(e){try{const t=k.readFileSync(e,"utf-8"),o=$.dirname(e);let r=null;try{r=JSON.parse(t)}catch{try{r=require("js-yaml").load(t)}catch(i){return void(this.debug&&console.error(`[FuncSpan ConfigLoader] Failed to parse ${e} as JSON or YAML:`,i))}}if(!r)return;r.runtime_mode===!0&&(this.runtimeModeEnabled=!0,this.debug&&console.log(`[FuncSpan ConfigLoader] Runtime mode ENABLED in ${e}`)),r.default&&this.directoryConfigs.set(o,r.default),r.files&&await this._expandFileGlobs(o,r.files,r.default||{}),r.functions&&this._storeFunctionConfigs(o,r.functions,r.default||{}),this.debug&&(console.log(`[FuncSpan ConfigLoader] Loaded config from ${e}`),console.log(`[FuncSpan ConfigLoader] Directory: ${o}`),console.log(`[FuncSpan ConfigLoader] Has default: ${!!r.default}`),console.log(`[FuncSpan ConfigLoader] File patterns: ${Object.keys(r.files||{}).length}`),console.log(`[FuncSpan ConfigLoader] Functions: ${Object.keys(r.functions||{}).length}`))}catch(t){this.debug&&console.error(`[FuncSpan ConfigLoader] Error loading ${e}:`,t)}}async _expandFileGlobs(e,t,o){for(const[r,i]of Object.entries(t))try{const l=$.join(e,r),s=await ge.glob(l,{absolute:!0,nodir:!0,ignore:["**/node_modules/**","**/.git/**"]});this.debug&&console.log(`[FuncSpan ConfigLoader] Pattern '${r}' matched ${s.length} files`);for(const d of s){const a=$.normalize(d),u=p.mergeConfigs(o,i);this.fileConfigs.set(a,u),this.debug&&s.length<=5&&console.log(`[FuncSpan ConfigLoader] - ${d}`)}}catch(l){this.debug&&console.error(`[FuncSpan ConfigLoader] Error expanding glob '${r}':`,l)}}_storeFunctionConfigs(e,t,o){for(const[r,i]of Object.entries(t)){const l=r.split("::");if(l.length!==2){this.debug&&console.warn(`[FuncSpan ConfigLoader] Invalid function pattern '${r}' (expected format: 'file.ts::functionName')`);continue}const[s,d]=l,a=$.normalize($.join(e,s));this.functionConfigs.has(a)||this.functionConfigs.set(a,new Map);const u=this.functionConfigs.get(a),f=p.mergeConfigs(o,i);u.set(d,f),this.debug&&console.log(`[FuncSpan ConfigLoader] Function config: ${a}::${d}`)}}async _resolveInheritance(){}_getDirectoryConfig(e){let t=$.dirname($.normalize(e));const o=[];for(;t&&t!==$.dirname(t);){const r=this.directoryConfigs.get(t);r&&o.unshift(r),t=$.dirname(t)}return o.reduce((r,i)=>p.mergeConfigs(r,i),{})}}let F=null;async function Q(n,e){F=new Ce(n,e),await F.loadAllConfigs()}function X(n,e){return F?F.getConfig(n,e):(process.env.SF_DEBUG==="true"&&console.log("[FuncSpan ConfigLoader] Config loader not initialized, using env config for worker process"),p.getEnvConfig())}function Y(){return F!==null}const Fe=["readFile","writeFile","appendFile","readdir","stat","lstat","fstat","access","open","close","read","write","chmod","mkdir","rmdir","unlink","rename"],Z=["lookup","resolve","resolve4","resolve6","resolveAny","resolveMx","resolveNs","resolveTxt","reverse"],Ne=["pbkdf2","randomBytes","scrypt","generateKeyPair"],Ee=["gzip","gunzip","deflate","inflate","deflateRaw","inflateRaw","brotliCompress","brotliDecompress"];let ee=!1;function De(n){if(typeof n!="string")return!1;const e=process.env.SF_FUNCSPAN_JSONL_FILE;if(e&&n.includes(e))return!0;const t=process.env.SF_WORKER_POOL_JSONL_FILE;return!(!t||!n.includes(t))}let te=!1;function ne(n){if(typeof n!="string")return!1;if(n==="localhost"||n==="127.0.0.1"||n==="::1")return!0;try{const e=process.env.API_GRAPHQL_ENDPOINT;if(e&&n===new URL(e).hostname)return!0}catch{}return!1}function Pe(){if(!te)try{let n;if(typeof require>"u")return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Skipping dns patching in pure ESM environment (require unavailable)"));try{n=require("node:dns")}catch(e){return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Failed to require dns module:",e))}if(n.__sf_worker_pool_patched__)return;Object.defineProperty(n,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of Z)if(typeof n[e]=="function"){const t=n[e];n[e]=function(...o){return ne(o[0])?t.apply(this,o):typeof o[o.length-1]=="function"?p.captureWorkerPoolOperation("dns",e,t,o,this):t.apply(this,o)},Object.defineProperty(n[e],"name",{value:e,writable:!1})}(function(e){if(!e.promises)return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises not available, skipping"));if(!e.promises.__sf_worker_pool_patched__){Object.defineProperty(e.promises,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Z)if(typeof e.promises[t]=="function"){const o=e.promises[t];e.promises[t]=function(...r){return ne(r[0])?o.apply(this,r):p.captureWorkerPoolPromiseOperation("dns",t,o,r,this)},Object.defineProperty(e.promises[t],"name",{value:t,writable:!1})}process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises module patched successfully")}})(n),te=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns module patched successfully")}catch(n){console.error("[WorkerPool] Error patching dns module:",n)}}let re=!1,oe=!1,G=!1;function ie(){if(G)return;const n=process.env.SF_DEBUG==="true";n&&console.log("[WorkerPool] Initializing worker pool patching..."),p.isModuleTrackingEnabled("fs")&&(n&&console.log("[WorkerPool] Patching fs module..."),(function(){if(!ee)try{const e=require("node:fs");if(e.__sf_worker_pool_patched__)return;Object.defineProperty(e,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Fe)if(typeof e[t]=="function"){const o=e[t];e[t]=function(...r){return De(r[0])?o.apply(this,r):typeof r[r.length-1]=="function"?p.captureWorkerPoolOperation("fs",t,o,r,this):o.apply(this,r)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}ee=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] fs module patched successfully")}catch(e){console.error("[WorkerPool] Error patching fs module:",e)}})()),p.isModuleTrackingEnabled("dns")&&(n&&console.log("[WorkerPool] Patching dns module..."),Pe()),p.isModuleTrackingEnabled("crypto")&&(n&&console.log("[WorkerPool] Patching crypto module..."),(function(){if(!re)try{const e=require("node:crypto");if(e.__sf_worker_pool_patched__)return;Object.defineProperty(e,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Ne)if(typeof e[t]=="function"){const o=e[t];e[t]=function(...r){return typeof r[r.length-1]=="function"?p.captureWorkerPoolOperation("crypto",t,o,r,this):o.apply(this,r)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}re=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] crypto module patched successfully")}catch(e){console.error("[WorkerPool] Error patching crypto module:",e)}})()),p.isModuleTrackingEnabled("zlib")&&(n&&console.log("[WorkerPool] Patching zlib module..."),(function(){if(!oe)try{const e=require("node:zlib");if(e.__sf_worker_pool_patched__)return;Object.defineProperty(e,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Ee)if(typeof e[t]=="function"){const o=e[t];e[t]=function(...r){return typeof r[r.length-1]=="function"?p.captureWorkerPoolOperation("zlib",t,o,r,this):o.apply(this,r)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}oe=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] zlib module patched successfully")}catch(e){console.error("[WorkerPool] Error patching zlib module:",e)}})()),G=!0,n&&console.log("[WorkerPool] Worker pool patching initialized")}function se(){return G}let M=!1,H=!1,x=null;function D(n){const e=c.getGlobalConfigUnsafe(),t=e?.sfDebug||!1;t&&console.log("[FuncSpan] captureSpanData called for:",{function:n.functionName,file:n.filePath,duration:`${n.duration}ms`,async:n.async,error:n.error,spanId:n.spanId});const o={functionName:n.functionName,filePath:n.filePath,metadata:n.metadata,args:n.args,result:n.result,error:n.error,duration:n.duration,durationNs:n.durationNs,async:n.async,spanId:n.spanId,parentSpanId:n.parentSpanId};process.env.SF_FUNCSPAN_CONSOLE_OUTPUT==="true"&&console.log(`
145
+ `,t=this.getVariables({serviceIdentifier:c.getConfig().serviceIdentifier,serviceVersion:c.getConfig().serviceVersion,serviceAdditionalMetadata:c.getConfig().serviceAdditionalMetadata,gitSha:c.getConfig().gitSha||""});p.nonBlockingPost(this.endpoint,this.operationName,e,t)}}class Ce{constructor(e=[process.cwd()],t=!1){I(this,"rootPaths");I(this,"fileConfigs",new Map);I(this,"functionConfigs",new Map);I(this,"directoryConfigs",new Map);I(this,"hasSailfishFiles",!1);I(this,"runtimeModeEnabled",!1);I(this,"debug");this.rootPaths=e,this.debug=t||process.env.SF_DEBUG==="true"}async loadAllConfigs(){this.debug&&console.log("[FuncSpan ConfigLoader] Scanning for .sailfish files in:",this.rootPaths);const e=[];for(const t of this.rootPaths)k.existsSync(t)?await this._walkDirectory(t,e):this.debug&&console.log(`[FuncSpan ConfigLoader] Root path does not exist: ${t}`);e.length>0?(this.hasSailfishFiles=!0,this.debug&&(console.log(`[FuncSpan ConfigLoader] Found ${e.length} .sailfish files:`),e.forEach(t=>console.log(`[FuncSpan ConfigLoader] - ${t}`)))):this.debug&&console.log("[FuncSpan ConfigLoader] No .sailfish files found - function spans disabled by default");for(const t of e)await this._loadConfigFile(t);await this._resolveInheritance(),this.debug&&console.log(`[FuncSpan ConfigLoader] Loaded ${this.fileConfigs.size} file configs, ${this.functionConfigs.size} function configs`)}getConfig(e,t){const o=this.hasSailfishFiles?p.getEnvConfig():p.getDefaultConfig(),r=this._getDirectoryConfig(e),i=b.normalize(e),l=this.fileConfigs.get(i)||{};let s={};if(t){const d=this.functionConfigs.get(i);d&&(s=d.get(t)||{})}return p.mergeConfigs(o,r,l,s)}hasRuntimeMode(){return this.runtimeModeEnabled}async _walkDirectory(e,t){try{const o=k.readdirSync(e,{withFileTypes:!0});for(const r of o){const i=b.join(e,r.name);r.isFile()&&r.name===".sailfish"?t.push(i):r.name==="node_modules"||r.isDirectory()&&r.name.startsWith(".")&&r.name!==".sailfish"||r.isDirectory()&&await this._walkDirectory(i,t)}}catch(o){this.debug&&console.error(`[FuncSpan ConfigLoader] Error walking directory ${e}:`,o)}}async _loadConfigFile(e){try{const t=k.readFileSync(e,"utf-8"),o=b.dirname(e);let r=null;try{r=JSON.parse(t)}catch{try{r=require("js-yaml").load(t)}catch(i){return void(this.debug&&console.error(`[FuncSpan ConfigLoader] Failed to parse ${e} as JSON or YAML:`,i))}}if(!r)return;r.runtime_mode===!0&&(this.runtimeModeEnabled=!0,this.debug&&console.log(`[FuncSpan ConfigLoader] Runtime mode ENABLED in ${e}`)),r.default&&this.directoryConfigs.set(o,r.default),r.files&&await this._expandFileGlobs(o,r.files,r.default||{}),r.functions&&this._storeFunctionConfigs(o,r.functions,r.default||{}),this.debug&&(console.log(`[FuncSpan ConfigLoader] Loaded config from ${e}`),console.log(`[FuncSpan ConfigLoader] Directory: ${o}`),console.log(`[FuncSpan ConfigLoader] Has default: ${!!r.default}`),console.log(`[FuncSpan ConfigLoader] File patterns: ${Object.keys(r.files||{}).length}`),console.log(`[FuncSpan ConfigLoader] Functions: ${Object.keys(r.functions||{}).length}`))}catch(t){this.debug&&console.error(`[FuncSpan ConfigLoader] Error loading ${e}:`,t)}}async _expandFileGlobs(e,t,o){for(const[r,i]of Object.entries(t))try{const l=b.join(e,r),s=await ge.glob(l,{absolute:!0,nodir:!0,ignore:["**/node_modules/**","**/.git/**"]});this.debug&&console.log(`[FuncSpan ConfigLoader] Pattern '${r}' matched ${s.length} files`);for(const d of s){const a=b.normalize(d),u=p.mergeConfigs(o,i);this.fileConfigs.set(a,u),this.debug&&s.length<=5&&console.log(`[FuncSpan ConfigLoader] - ${d}`)}}catch(l){this.debug&&console.error(`[FuncSpan ConfigLoader] Error expanding glob '${r}':`,l)}}_storeFunctionConfigs(e,t,o){for(const[r,i]of Object.entries(t)){const l=r.split("::");if(l.length!==2){this.debug&&console.warn(`[FuncSpan ConfigLoader] Invalid function pattern '${r}' (expected format: 'file.ts::functionName')`);continue}const[s,d]=l,a=b.normalize(b.join(e,s));this.functionConfigs.has(a)||this.functionConfigs.set(a,new Map);const u=this.functionConfigs.get(a),f=p.mergeConfigs(o,i);u.set(d,f),this.debug&&console.log(`[FuncSpan ConfigLoader] Function config: ${a}::${d}`)}}async _resolveInheritance(){}_getDirectoryConfig(e){let t=b.dirname(b.normalize(e));const o=[];for(;t&&t!==b.dirname(t);){const r=this.directoryConfigs.get(t);r&&o.unshift(r),t=b.dirname(t)}return o.reduce((r,i)=>p.mergeConfigs(r,i),{})}}let F=null;async function Q(n,e){F=new Ce(n,e),await F.loadAllConfigs()}function X(n,e){return F?F.getConfig(n,e):(process.env.SF_DEBUG==="true"&&console.log("[FuncSpan ConfigLoader] Config loader not initialized, using env config for worker process"),p.getEnvConfig())}function Y(){return F!==null}const Fe=["readFile","writeFile","appendFile","readdir","stat","lstat","fstat","access","open","close","read","write","chmod","mkdir","rmdir","unlink","rename"],Z=["lookup","resolve","resolve4","resolve6","resolveAny","resolveMx","resolveNs","resolveTxt","reverse"],Ne=["pbkdf2","randomBytes","scrypt","generateKeyPair"],Ee=["gzip","gunzip","deflate","inflate","deflateRaw","inflateRaw","brotliCompress","brotliDecompress"];let ee=!1;function De(n){if(typeof n!="string")return!1;const e=process.env.SF_FUNCSPAN_JSONL_FILE;if(e&&n.includes(e))return!0;const t=process.env.SF_WORKER_POOL_JSONL_FILE;return!(!t||!n.includes(t))}let te=!1;function ne(n){if(typeof n!="string")return!1;if(n==="localhost"||n==="127.0.0.1"||n==="::1")return!0;try{const e=process.env.API_GRAPHQL_ENDPOINT;if(e&&n===new URL(e).hostname)return!0}catch{}return!1}function Pe(){if(!te)try{let n;if(typeof require>"u")return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Skipping dns patching in pure ESM environment (require unavailable)"));try{n=require("node:dns")}catch(e){return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Failed to require dns module:",e))}if(n.__sf_worker_pool_patched__)return;Object.defineProperty(n,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of Z)if(typeof n[e]=="function"){const t=n[e];n[e]=function(...o){return ne(o[0])?t.apply(this,o):typeof o[o.length-1]=="function"?p.captureWorkerPoolOperation("dns",e,t,o,this):t.apply(this,o)},Object.defineProperty(n[e],"name",{value:e,writable:!1})}(function(e){if(!e.promises)return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises not available, skipping"));if(!e.promises.__sf_worker_pool_patched__){Object.defineProperty(e.promises,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Z)if(typeof e.promises[t]=="function"){const o=e.promises[t];e.promises[t]=function(...r){return ne(r[0])?o.apply(this,r):p.captureWorkerPoolPromiseOperation("dns",t,o,r,this)},Object.defineProperty(e.promises[t],"name",{value:t,writable:!1})}process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises module patched successfully")}})(n),te=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns module patched successfully")}catch(n){console.error("[WorkerPool] Error patching dns module:",n)}}let re=!1,oe=!1,G=!1;function ie(){if(G)return;const n=process.env.SF_DEBUG==="true";n&&console.log("[WorkerPool] Initializing worker pool patching..."),p.isModuleTrackingEnabled("fs")&&(n&&console.log("[WorkerPool] Patching fs module..."),(function(){if(!ee)try{const e=require("node:fs");if(e.__sf_worker_pool_patched__)return;Object.defineProperty(e,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Fe)if(typeof e[t]=="function"){const o=e[t];e[t]=function(...r){return De(r[0])?o.apply(this,r):typeof r[r.length-1]=="function"?p.captureWorkerPoolOperation("fs",t,o,r,this):o.apply(this,r)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}ee=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] fs module patched successfully")}catch(e){console.error("[WorkerPool] Error patching fs module:",e)}})()),p.isModuleTrackingEnabled("dns")&&(n&&console.log("[WorkerPool] Patching dns module..."),Pe()),p.isModuleTrackingEnabled("crypto")&&(n&&console.log("[WorkerPool] Patching crypto module..."),(function(){if(!re)try{const e=require("node:crypto");if(e.__sf_worker_pool_patched__)return;Object.defineProperty(e,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Ne)if(typeof e[t]=="function"){const o=e[t];e[t]=function(...r){return typeof r[r.length-1]=="function"?p.captureWorkerPoolOperation("crypto",t,o,r,this):o.apply(this,r)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}re=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] crypto module patched successfully")}catch(e){console.error("[WorkerPool] Error patching crypto module:",e)}})()),p.isModuleTrackingEnabled("zlib")&&(n&&console.log("[WorkerPool] Patching zlib module..."),(function(){if(!oe)try{const e=require("node:zlib");if(e.__sf_worker_pool_patched__)return;Object.defineProperty(e,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Ee)if(typeof e[t]=="function"){const o=e[t];e[t]=function(...r){return typeof r[r.length-1]=="function"?p.captureWorkerPoolOperation("zlib",t,o,r,this):o.apply(this,r)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}oe=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] zlib module patched successfully")}catch(e){console.error("[WorkerPool] Error patching zlib module:",e)}})()),G=!0,n&&console.log("[WorkerPool] Worker pool patching initialized")}function se(){return G}let q=!1,H=!1,x=null;function D(n){const e=c.getGlobalConfigUnsafe(),t=e?.sfDebug||!1;t&&console.log("[FuncSpan] captureSpanData called for:",{function:n.functionName,file:n.filePath,duration:`${n.duration}ms`,async:n.async,error:n.error,spanId:n.spanId});const o={functionName:n.functionName,filePath:n.filePath,metadata:n.metadata,args:n.args,result:n.result,error:n.error,duration:n.duration,durationNs:n.durationNs,async:n.async,spanId:n.spanId,parentSpanId:n.parentSpanId};process.env.SF_FUNCSPAN_CONSOLE_OUTPUT==="true"&&console.log(`
146
146
  📊 Function Span:`,{function:`${n.functionName} (${n.filePath}:${n.metadata.line}:${n.metadata.column})`,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 r=process.env.SF_FUNCSPAN_JSONL_FILE;if(r)try{const i=r==="true"||r==="1"?"funcspans.jsonl":r,l=Date.now(),s=process.hrtime.bigint(),d=BigInt(n.startTimeNs),a=Number(s-d)/1e6,u=new Date(l-a).toISOString(),f=JSON.stringify({timestamp:u,functionName:n.functionName,filePath:n.filePath,line:n.metadata.line,column:n.metadata.column,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,async:n.async,pid:n.pid,threadId:n.threadId})+`
147
- `;W.appendFileSync(i,f,"utf-8")}catch(i){console.error("[FuncSpan] Error writing to JSONL file:",i)}if(t&&console.log("[FuncSpan] Sending function span to transmitter:",o),process.env.SF_FUNCSPAN_SKIP_BACKEND!=="true")try{(x||(x=new p.FunctionSpanTransmitter),x).send([o]),t&&console.log("[FuncSpan] Function span sent successfully")}catch(i){t&&console.error("[FuncSpan] Error sending function span:",i)}}exports.ContextManager=c.ContextManager,exports.getCurrentFunctionSpanId=c.getCurrentFunctionSpanId,exports.runWithContext=c.runWithContext,exports.clearFuncspanOverride=p.clearFuncspanOverride,exports.getDefaultConfig=p.getDefaultConfig,exports.getEnvConfig=p.getEnvConfig,exports.getFuncspanOverride=p.getFuncspanOverride,exports.parseHeaderOverride=p.parseHeaderOverride,exports.setFuncspanOverride=p.setFuncspanOverride,exports.isProductionEnvironment=h.isProductionEnvironment,exports.isRuntimeModeEnabled=h.isRuntimeModeEnabled,exports.shouldEnableRuntimeHooks=h.shouldEnableRuntimeHooks,exports.setSkipTypeScriptPlugin=O.setSkipTypeScriptPlugin,exports.transformFunctionSpans=O.transformFunctionSpans,exports.transformFunctionSpansSync=O.transformFunctionSpansSync,exports.addOrUpdateMetadata=function(n,e={},t,o=!1){const r=c.getConfig();new z(r.apiKey).addOrUpdateMetadata(n,e,t,o)},exports.captureFunctionSpan=function(n,e,t,o){const r=function(...i){const l=c.getGlobalConfigUnsafe(),s=l?.sfDebug||!1;s&&console.log(`[FuncSpan] captureFunctionSpan wrapper called for ${t}::${e}`);const d=(function(S,_){const v=p.getFuncspanOverride();if(v){const b=p.parseHeaderOverride(v);if(b)return process.env.SF_DEBUG==="true"&&console.log(`[FuncSpan] Using HTTP header override for ${S}::${_}`),b}try{return X(S,_)}catch{return{sample_rate:process.env.SF_FUNCSPAN_SAMPLE_RATE?parseFloat(process.env.SF_FUNCSPAN_SAMPLE_RATE):1,capture_arguments:!0,capture_return_value:!0,arg_limit_mb:1,return_limit_mb:1,enable_sampling:!1,autocapture_all_child_functions:!1,capture_sf_veritas:!1,parse_json_strings:!1}}})(t,e);if(s&&console.log(`[FuncSpan] Config for ${t}::${e}:`,d),d.enable_sampling&&d.sample_rate<1&&Math.random()>d.sample_rate)return s&&console.log(`[FuncSpan] Skipping ${e} due to sampling`),n.apply(this,i);if(d.sample_rate===0)return s&&console.log(`[FuncSpan] Skipping ${e} - sample_rate is 0.0`),n.apply(this,i);s&&console.log(`[FuncSpan] Capturing function span for ${e}`);const a=c.ContextManager.getInstance(),u=a.getCurrentFunctionSpanId(),f=c.v4();a.setCurrentFunctionSpanId(f);const m=process.hrtime.bigint(),y=Date.now();let g=null;d.capture_arguments&&(g={},o.paramNames.forEach((S,_)=>{_<i.length&&(g[S]=i[_])}),g&&d.arg_limit_mb>0&&(g=p.truncateToLimit(g,d.arg_limit_mb)));try{const S=n.apply(this,i);if(S&&typeof S.then=="function")return u?a.setCurrentFunctionSpanId(u):a.clearCurrentFunctionSpanId(),S.then(C=>{const T=process.hrtime.bigint(),w=Date.now(),U=Number(T-m);let j=null;return d.capture_return_value&&d.return_limit_mb>0&&(j=p.truncateToLimit(C,d.return_limit_mb)),D({functionName:e,filePath:t,metadata:o,args:g,result:j,error:null,duration:w-y,durationNs:U,startTimeNs:m.toString(),async:!0,spanId:f,parentSpanId:u,pid:process.pid,threadId:E.threadId}),C},C=>{const T=process.hrtime.bigint(),w=Date.now(),U=Number(T-m);throw D({functionName:e,filePath:t,metadata:o,args:g,result:null,error:C?.message||String(C),duration:w-y,durationNs:U,startTimeNs:m.toString(),async:!0,spanId:f,parentSpanId:u,pid:process.pid,threadId:E.threadId}),C});const _=process.hrtime.bigint(),v=Date.now(),b=Number(_-m);let B=null;return d.capture_return_value&&d.return_limit_mb>0&&(B=p.truncateToLimit(S,d.return_limit_mb)),D({functionName:e,filePath:t,metadata:o,args:g,result:B,error:null,duration:v-y,durationNs:b,startTimeNs:m.toString(),async:!1,spanId:f,parentSpanId:u,pid:process.pid,threadId:E.threadId}),u?a.setCurrentFunctionSpanId(u):a.clearCurrentFunctionSpanId(),S}catch(S){const _=process.hrtime.bigint(),v=Date.now(),b=Number(_-m);throw D({functionName:e,filePath:t,metadata:o,args:g,result:null,error:S?.message||String(S),duration:v-y,durationNs:b,startTimeNs:m.toString(),async:!1,spanId:f,parentSpanId:u,pid:process.pid,threadId:E.threadId}),u?a.setCurrentFunctionSpanId(u):a.clearCurrentFunctionSpanId(),S}};Object.defineProperty(r,"name",{value:e,writable:!1});for(const i in n)n.hasOwnProperty(i)&&(r[i]=n[i]);return r},exports.getGlobalConfig=X,exports.identify=function(n,e,t,o=!1){const r=c.getConfig();new z(r.apiKey).identify(n,e,t,o)},exports.initializeConfigLoader=Q,exports.initializeWorkerPoolPatching=ie,exports.isAlreadyInstrumented=function(n){return!!n.includes("captureFunctionSpan(")||!!n.includes("@sailfish-ai/sf-veritas")||!(!n.includes("/* @sailfish-instrumented */")&&!n.includes("// @sailfish-instrumented"))},exports.isConfigLoaderInitialized=Y,exports.isSetupInterceptorsInitialized=function(){return M},exports.isWorkerPoolInitialized=se,exports.setupInterceptors=function(n){if(H)console.warn("[setupInterceptors] ⚠️ Recursive call detected and blocked!");else if(!M){H=!0;try{if(!n||!n.apiKey){const r=`The required API Key is not provided: ${JSON.stringify(n)}`;console.error(r)}const{config:e}=c.getOrCreateConfig(n);if(e.sfDebug&&console.log("Updated configuration after applying options:",e),!e.apiKey||!e.apiGraphqlEndpoint){const r=`The required config is not provided: ${JSON.stringify(e)}`;throw console.error(r),new Error(r)}Y()||Q(void 0,e.sfDebug).catch(r=>{e.sfDebug&&console.error("[FuncSpan] Failed to initialize config loader:",r)}),process.env.SF_WORKER_POOL_DISABLED==="true"?e.sfDebug&&console.log("[setupInterceptors] Worker pool patching DISABLED (SF_WORKER_POOL_DISABLED=true)"):se()||(ie(),e.sfDebug&&console.log("[setupInterceptors] Worker pool patching initialized (DNS tracking enabled)"));const t=new K;t.setServiceUUID(e.serviceUUID),h.initializeLogInterceptor(t),(function(r=[]){const i=new $e(r);new Ie().doSend(i.getExcludedDomains());const l=new _e,s=new ve;i.patchFetch(l,s),i.patchHttp(l,s)})(e.domainsToNotPropagateHeadersTo);const o=new me;o.setServiceUUID(e.serviceUUID),h.initializeExceptionInterceptor(o),ye(),new be().send(),M=!0,e.sfDebug&&console.log("[setupInterceptors] ✅ Initialization complete")}finally{H=!1}}};
147
+ `;W.appendFileSync(i,f,"utf-8")}catch(i){console.error("[FuncSpan] Error writing to JSONL file:",i)}if(t&&console.log("[FuncSpan] Sending function span to transmitter:",o),process.env.SF_FUNCSPAN_SKIP_BACKEND!=="true")try{(x||(x=new p.FunctionSpanTransmitter),x).send([o]),t&&console.log("[FuncSpan] Function span sent successfully")}catch(i){t&&console.error("[FuncSpan] Error sending function span:",i)}}exports.ContextManager=c.ContextManager,exports.getCurrentFunctionSpanId=c.getCurrentFunctionSpanId,exports.runWithContext=c.runWithContext,exports.clearFuncspanOverride=p.clearFuncspanOverride,exports.getDefaultConfig=p.getDefaultConfig,exports.getEnvConfig=p.getEnvConfig,exports.getFuncspanOverride=p.getFuncspanOverride,exports.parseHeaderOverride=p.parseHeaderOverride,exports.setFuncspanOverride=p.setFuncspanOverride,exports.isProductionEnvironment=h.isProductionEnvironment,exports.isRuntimeModeEnabled=h.isRuntimeModeEnabled,exports.shouldEnableRuntimeHooks=h.shouldEnableRuntimeHooks,exports.setSkipTypeScriptPlugin=O.setSkipTypeScriptPlugin,exports.transformFunctionSpans=O.transformFunctionSpans,exports.transformFunctionSpansSync=O.transformFunctionSpansSync,exports.addOrUpdateMetadata=function(n,e={},t,o=!1){const r=c.getConfig();new z(r.apiKey).addOrUpdateMetadata(n,e,t,o)},exports.captureFunctionSpan=function(n,e,t,o){const r=function(...i){const l=c.getGlobalConfigUnsafe(),s=l?.sfDebug||!1;s&&console.log(`[FuncSpan] captureFunctionSpan wrapper called for ${t}::${e}`);const d=(function(S,_){const v=p.getFuncspanOverride();if(v){const $=p.parseHeaderOverride(v);if($)return process.env.SF_DEBUG==="true"&&console.log(`[FuncSpan] Using HTTP header override for ${S}::${_}`),$}try{return X(S,_)}catch{return{sample_rate:process.env.SF_FUNCSPAN_SAMPLE_RATE?parseFloat(process.env.SF_FUNCSPAN_SAMPLE_RATE):1,capture_arguments:!0,capture_return_value:!0,arg_limit_mb:1,return_limit_mb:1,enable_sampling:!1,autocapture_all_child_functions:!1,capture_sf_veritas:!1,parse_json_strings:!1}}})(t,e);if(s&&console.log(`[FuncSpan] Config for ${t}::${e}:`,d),d.enable_sampling&&d.sample_rate<1&&Math.random()>d.sample_rate)return s&&console.log(`[FuncSpan] Skipping ${e} due to sampling`),n.apply(this,i);if(d.sample_rate===0)return s&&console.log(`[FuncSpan] Skipping ${e} - sample_rate is 0.0`),n.apply(this,i);s&&console.log(`[FuncSpan] Capturing function span for ${e}`);const a=c.ContextManager.getInstance(),u=a.getCurrentFunctionSpanId(),f=c.v4();a.setCurrentFunctionSpanId(f);const m=process.hrtime.bigint(),y=Date.now();let g=null;d.capture_arguments&&(g={},o.paramNames.forEach((S,_)=>{_<i.length&&(g[S]=i[_])}),g&&d.arg_limit_mb>0&&(g=p.truncateToLimit(g,d.arg_limit_mb)));try{const S=n.apply(this,i);if(S&&typeof S.then=="function")return u?a.setCurrentFunctionSpanId(u):a.clearCurrentFunctionSpanId(),S.then(C=>{const T=process.hrtime.bigint(),w=Date.now(),U=Number(T-m);let j=null;return d.capture_return_value&&d.return_limit_mb>0&&(j=p.truncateToLimit(C,d.return_limit_mb)),D({functionName:e,filePath:t,metadata:o,args:g,result:j,error:null,duration:w-y,durationNs:U,startTimeNs:m.toString(),async:!0,spanId:f,parentSpanId:u,pid:process.pid,threadId:E.threadId}),C},C=>{const T=process.hrtime.bigint(),w=Date.now(),U=Number(T-m);throw D({functionName:e,filePath:t,metadata:o,args:g,result:null,error:C?.message||String(C),duration:w-y,durationNs:U,startTimeNs:m.toString(),async:!0,spanId:f,parentSpanId:u,pid:process.pid,threadId:E.threadId}),C});const _=process.hrtime.bigint(),v=Date.now(),$=Number(_-m);let B=null;return d.capture_return_value&&d.return_limit_mb>0&&(B=p.truncateToLimit(S,d.return_limit_mb)),D({functionName:e,filePath:t,metadata:o,args:g,result:B,error:null,duration:v-y,durationNs:$,startTimeNs:m.toString(),async:!1,spanId:f,parentSpanId:u,pid:process.pid,threadId:E.threadId}),u?a.setCurrentFunctionSpanId(u):a.clearCurrentFunctionSpanId(),S}catch(S){const _=process.hrtime.bigint(),v=Date.now(),$=Number(_-m);throw D({functionName:e,filePath:t,metadata:o,args:g,result:null,error:S?.message||String(S),duration:v-y,durationNs:$,startTimeNs:m.toString(),async:!1,spanId:f,parentSpanId:u,pid:process.pid,threadId:E.threadId}),u?a.setCurrentFunctionSpanId(u):a.clearCurrentFunctionSpanId(),S}};Object.defineProperty(r,"name",{value:e,writable:!1});for(const i in n)n.hasOwnProperty(i)&&(r[i]=n[i]);return r},exports.getGlobalConfig=X,exports.identify=function(n,e,t,o=!1){const r=c.getConfig();new z(r.apiKey).identify(n,e,t,o)},exports.initializeConfigLoader=Q,exports.initializeWorkerPoolPatching=ie,exports.isAlreadyInstrumented=function(n){return!!n.includes("captureFunctionSpan(")||!!n.includes("@sailfish-ai/sf-veritas")||!(!n.includes("/* @sailfish-instrumented */")&&!n.includes("// @sailfish-instrumented"))},exports.isConfigLoaderInitialized=Y,exports.isSetupInterceptorsInitialized=function(){return q},exports.isWorkerPoolInitialized=se,exports.setupInterceptors=function(n){if(H)console.warn("[setupInterceptors] ⚠️ Recursive call detected and blocked!");else if(!q){H=!0;try{if(!n||!n.apiKey){const r=`The required API Key is not provided: ${JSON.stringify(n)}`;console.error(r)}const{config:e}=c.getOrCreateConfig(n);if(e.sfDebug&&console.log("Updated configuration after applying options:",e),!e.apiKey||!e.apiGraphqlEndpoint){const r=`The required config is not provided: ${JSON.stringify(e)}`;throw console.error(r),new Error(r)}Y()||Q(void 0,e.sfDebug).catch(r=>{e.sfDebug&&console.error("[FuncSpan] Failed to initialize config loader:",r)}),process.env.SF_WORKER_POOL_DISABLED==="true"?e.sfDebug&&console.log("[setupInterceptors] Worker pool patching DISABLED (SF_WORKER_POOL_DISABLED=true)"):se()||(ie(),e.sfDebug&&console.log("[setupInterceptors] Worker pool patching initialized (DNS tracking enabled)"));const t=new K;t.setServiceUUID(e.serviceUUID),h.initializeLogInterceptor(t),(function(r=[]){const i=new be(r);new Ie().doSend(i.getExcludedDomains());const l=new _e,s=new ve;i.patchFetch(l,s),i.patchHttp(l,s)})(e.domainsToNotPropagateHeadersTo);const o=new me;o.setServiceUUID(e.serviceUUID),h.initializeExceptionInterceptor(o),ye(),new $e().send(),q=!0,e.sfDebug&&console.log("[setupInterceptors] ✅ Initialization complete")}finally{H=!1}}};
@@ -3,18 +3,18 @@ var fe = (n, e, t) => e in n ? pe(n, e, { enumerable: !0, configurable: !0, writ
3
3
  var S = (n, e, t) => fe(n, typeof e != "symbol" ? e + "" : e, t);
4
4
  import { g as l, C as J, D as he, v as ie, b as q, c as ge, a as ae } from "./contextManager-CEPhVu9T.js";
5
5
  import { r as ft } from "./contextManager-CEPhVu9T.js";
6
- import { B as D, n as F, f as me, g as ce, p as de, a as le, b as Se, m as P, c as R, d as ye, i as C, t as M, F as Ie } from "./workerPoolSpanCapture-B5KN-q4b.js";
7
- import { e as gt, s as mt } from "./workerPoolSpanCapture-B5KN-q4b.js";
8
- import { C as _e, i as _, a as $e, h as b, b as ve, c as be } from "./runtimeConfig-emBNO3lJ.js";
9
- import { e as yt, d as It, s as _t } from "./runtimeConfig-emBNO3lJ.js";
6
+ import { B as D, n as F, f as me, g as ce, p as de, a as le, b as Se, m as P, c as R, d as ye, i as C, t as M, F as Ie } from "./workerPoolSpanCapture-BYaf3NOr.js";
7
+ import { e as gt, s as mt } from "./workerPoolSpanCapture-BYaf3NOr.js";
8
+ import { C as _e, i as _, a as ve, h as b, b as $e, c as be } from "./runtimeConfig-CgLfwL3X.js";
9
+ import { d as yt, e as It, s as _t } from "./runtimeConfig-CgLfwL3X.js";
10
10
  import { createRequire as Fe } from "node:module";
11
11
  import * as H from "fs";
12
12
  import { readFileSync as Ne, appendFileSync as De } from "fs";
13
13
  import { s as we } from "./source-map-Cr6YkjTd.js";
14
- import * as $ from "path";
14
+ import * as v from "path";
15
15
  import { glob as Ee } from "glob";
16
16
  import { threadId as T } from "worker_threads";
17
- import { s as vt, t as bt, a as Ft } from "./funcSpanTransformer-CWNEWRxq.js";
17
+ import { s as $t, t as bt, a as Ft } from "./funcSpanTransformer-CWNEWRxq.js";
18
18
  class E extends D {
19
19
  constructor() {
20
20
  super(), this.setOperationName("IdentifyServiceDetails");
@@ -225,7 +225,7 @@ function Re() {
225
225
  try {
226
226
  e = Ue("node:http"), n && _("[patchNodeHttpInbound] node:http required successfully.");
227
227
  } catch (r) {
228
- return void $e("Failed to require node:http:", r);
228
+ return void ve("Failed to require node:http:", r);
229
229
  }
230
230
  if (!e?.Server?.prototype) return void (n && _("[patchNodeHttpInbound] http.Server.prototype not found."));
231
231
  const t = e.Server.prototype, s = t.emit;
@@ -456,8 +456,8 @@ class ke {
456
456
  this.addTracingHeaders(u, c), m = await s(c, h), f && K.includes(m.status) ? (m = await s(c, { ...o, headers: u }), p = !0, this.captureFirstUserLines(e, 10, p)) : this.contextManager.addSupportedDomains(a);
457
457
  const g = Date.now();
458
458
  l().sfDebug && console.log(`[RequestInterceptor] Fetch completed: ${c}, Status: ${m.status}, Duration: ${g - i}ms`);
459
- const { sessionId: y, pageVisitId: I, requestId: v } = this.extractIdsFromTraceHeader(d);
460
- return t.doSend({ apiKey: l().apiKey, requestId: v, pageVisitId: I, recordingSessionId: y, serviceUuid: l().serviceUUID, timestampStart: i.toString(), timestampEnd: g.toString(), responseCode: m.status, success: !0, error: null, url: c, method: h.method || "GET", retryWithoutTraceId: p, parentSpanId: q() }), m;
459
+ const { sessionId: y, pageVisitId: I, requestId: $ } = this.extractIdsFromTraceHeader(d);
460
+ return t.doSend({ apiKey: l().apiKey, requestId: $, pageVisitId: I, recordingSessionId: y, serviceUuid: l().serviceUUID, timestampStart: i.toString(), timestampEnd: g.toString(), responseCode: m.status, success: !0, error: null, url: c, method: h.method || "GET", retryWithoutTraceId: p, parentSpanId: q() }), m;
461
461
  } catch (p) {
462
462
  const g = Date.now();
463
463
  l().sfDebug && console.error(`[RequestInterceptor] Fetch failed: ${c}, Error: ${p}, Duration: ${g - i}ms`);
@@ -520,9 +520,8 @@ class ke {
520
520
  }
521
521
  tryPatch(e, t) {
522
522
  try {
523
- require.resolve(t), e(), console.log(`[RequestInterceptor] Patched ${t}`);
524
- } catch (s) {
525
- console.warn(`[RequestInterceptor] Could not patch ${t}: ${s.message}`);
523
+ require.resolve(t), e();
524
+ } catch {
526
525
  }
527
526
  }
528
527
  getExcludedDomains() {
@@ -581,7 +580,7 @@ class Me {
581
580
  await this._resolveInheritance(), this.debug && console.log(`[FuncSpan ConfigLoader] Loaded ${this.fileConfigs.size} file configs, ${this.functionConfigs.size} function configs`);
582
581
  }
583
582
  getConfig(e, t) {
584
- const s = this.hasSailfishFiles ? le() : Se(), r = this._getDirectoryConfig(e), o = $.normalize(e), d = this.fileConfigs.get(o) || {};
583
+ const s = this.hasSailfishFiles ? le() : Se(), r = this._getDirectoryConfig(e), o = v.normalize(e), d = this.fileConfigs.get(o) || {};
585
584
  let i = {};
586
585
  if (t) {
587
586
  const c = this.functionConfigs.get(o);
@@ -596,7 +595,7 @@ class Me {
596
595
  try {
597
596
  const s = H.readdirSync(e, { withFileTypes: !0 });
598
597
  for (const r of s) {
599
- const o = $.join(e, r.name);
598
+ const o = v.join(e, r.name);
600
599
  r.isFile() && r.name === ".sailfish" ? t.push(o) : r.name === "node_modules" || r.isDirectory() && r.name.startsWith(".") && r.name !== ".sailfish" || r.isDirectory() && await this._walkDirectory(o, t);
601
600
  }
602
601
  } catch (s) {
@@ -605,7 +604,7 @@ class Me {
605
604
  }
606
605
  async _loadConfigFile(e) {
607
606
  try {
608
- const t = H.readFileSync(e, "utf-8"), s = $.dirname(e);
607
+ const t = H.readFileSync(e, "utf-8"), s = v.dirname(e);
609
608
  let r = null;
610
609
  try {
611
610
  r = JSON.parse(t);
@@ -624,10 +623,10 @@ class Me {
624
623
  }
625
624
  async _expandFileGlobs(e, t, s) {
626
625
  for (const [r, o] of Object.entries(t)) try {
627
- const d = $.join(e, r), i = await Ee(d, { absolute: !0, nodir: !0, ignore: ["**/node_modules/**", "**/.git/**"] });
626
+ const d = v.join(e, r), i = await Ee(d, { absolute: !0, nodir: !0, ignore: ["**/node_modules/**", "**/.git/**"] });
628
627
  this.debug && console.log(`[FuncSpan ConfigLoader] Pattern '${r}' matched ${i.length} files`);
629
628
  for (const c of i) {
630
- const a = $.normalize(c), u = P(s, o);
629
+ const a = v.normalize(c), u = P(s, o);
631
630
  this.fileConfigs.set(a, u), this.debug && i.length <= 5 && console.log(`[FuncSpan ConfigLoader] - ${c}`);
632
631
  }
633
632
  } catch (d) {
@@ -641,7 +640,7 @@ class Me {
641
640
  this.debug && console.warn(`[FuncSpan ConfigLoader] Invalid function pattern '${r}' (expected format: 'file.ts::functionName')`);
642
641
  continue;
643
642
  }
644
- const [i, c] = d, a = $.normalize($.join(e, i));
643
+ const [i, c] = d, a = v.normalize(v.join(e, i));
645
644
  this.functionConfigs.has(a) || this.functionConfigs.set(a, /* @__PURE__ */ new Map());
646
645
  const u = this.functionConfigs.get(a), f = P(s, o);
647
646
  u.set(c, f), this.debug && console.log(`[FuncSpan ConfigLoader] Function config: ${a}::${c}`);
@@ -650,11 +649,11 @@ class Me {
650
649
  async _resolveInheritance() {
651
650
  }
652
651
  _getDirectoryConfig(e) {
653
- let t = $.dirname($.normalize(e));
652
+ let t = v.dirname(v.normalize(e));
654
653
  const s = [];
655
- for (; t && t !== $.dirname(t); ) {
654
+ for (; t && t !== v.dirname(t); ) {
656
655
  const r = this.directoryConfigs.get(t);
657
- r && s.unshift(r), t = $.dirname(t);
656
+ r && s.unshift(r), t = v.dirname(t);
658
657
  }
659
658
  return s.reduce((r, o) => P(r, o), {});
660
659
  }
@@ -797,7 +796,7 @@ function ot(n) {
797
796
  e.sfDebug && console.error("[FuncSpan] Failed to initialize config loader:", r);
798
797
  }), process.env.SF_WORKER_POOL_DISABLED === "true" ? e.sfDebug && console.log("[setupInterceptors] Worker pool patching DISABLED (SF_WORKER_POOL_DISABLED=true)") : Ve() || (Je(), e.sfDebug && console.log("[setupInterceptors] Worker pool patching initialized (DNS tracking enabled)"));
799
798
  const t = new V();
800
- t.setServiceUUID(e.serviceUUID), ve(t), (function(r = []) {
799
+ t.setServiceUUID(e.serviceUUID), $e(t), (function(r = []) {
801
800
  const o = new ke(r);
802
801
  new Ae().doSend(o.getExcludedDomains());
803
802
  const d = new Oe(), i = new Le();
@@ -829,8 +828,8 @@ function dt(n, e, t, s) {
829
828
  const c = (function(g, y) {
830
829
  const I = ce();
831
830
  if (I) {
832
- const v = de(I);
833
- if (v) return process.env.SF_DEBUG === "true" && console.log(`[FuncSpan] Using HTTP header override for ${g}::${y}`), v;
831
+ const $ = de(I);
832
+ if ($) return process.env.SF_DEBUG === "true" && console.log(`[FuncSpan] Using HTTP header override for ${g}::${y}`), $;
834
833
  }
835
834
  try {
836
835
  return xe(g, y);
@@ -858,12 +857,12 @@ function dt(n, e, t, s) {
858
857
  const O = process.hrtime.bigint(), L = Date.now(), k = Number(O - h);
859
858
  throw U({ functionName: e, filePath: t, metadata: s, args: p, result: null, error: N?.message || String(N), duration: L - m, durationNs: k, startTimeNs: h.toString(), async: !0, spanId: f, parentSpanId: u, pid: process.pid, threadId: T }), N;
860
859
  });
861
- const y = process.hrtime.bigint(), I = Date.now(), v = Number(y - h);
860
+ const y = process.hrtime.bigint(), I = Date.now(), $ = Number(y - h);
862
861
  let Q = null;
863
- return c.capture_return_value && c.return_limit_mb > 0 && (Q = M(g, c.return_limit_mb)), U({ functionName: e, filePath: t, metadata: s, args: p, result: Q, error: null, duration: I - m, durationNs: v, startTimeNs: h.toString(), async: !1, spanId: f, parentSpanId: u, pid: process.pid, threadId: T }), u ? a.setCurrentFunctionSpanId(u) : a.clearCurrentFunctionSpanId(), g;
862
+ return c.capture_return_value && c.return_limit_mb > 0 && (Q = M(g, c.return_limit_mb)), U({ functionName: e, filePath: t, metadata: s, args: p, result: Q, error: null, duration: I - m, durationNs: $, startTimeNs: h.toString(), async: !1, spanId: f, parentSpanId: u, pid: process.pid, threadId: T }), u ? a.setCurrentFunctionSpanId(u) : a.clearCurrentFunctionSpanId(), g;
864
863
  } catch (g) {
865
- const y = process.hrtime.bigint(), I = Date.now(), v = Number(y - h);
866
- throw U({ functionName: e, filePath: t, metadata: s, args: p, result: null, error: g?.message || String(g), duration: I - m, durationNs: v, startTimeNs: h.toString(), async: !1, spanId: f, parentSpanId: u, pid: process.pid, threadId: T }), u ? a.setCurrentFunctionSpanId(u) : a.clearCurrentFunctionSpanId(), g;
864
+ const y = process.hrtime.bigint(), I = Date.now(), $ = Number(y - h);
865
+ throw U({ functionName: e, filePath: t, metadata: s, args: p, result: null, error: g?.message || String(g), duration: I - m, durationNs: $, startTimeNs: h.toString(), async: !1, spanId: f, parentSpanId: u, pid: process.pid, threadId: T }), u ? a.setCurrentFunctionSpanId(u) : a.clearCurrentFunctionSpanId(), g;
867
866
  }
868
867
  };
869
868
  Object.defineProperty(r, "name", { value: e, writable: !1 });
@@ -915,7 +914,7 @@ export {
915
914
  de as parseHeaderOverride,
916
915
  ft as runWithContext,
917
916
  mt as setFuncspanOverride,
918
- vt as setSkipTypeScriptPlugin,
917
+ $t as setSkipTypeScriptPlugin,
919
918
  ot as setupInterceptors,
920
919
  _t as shouldEnableRuntimeHooks,
921
920
  bt as transformFunctionSpans,
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./workerPoolSpanCapture-Dg_WGjmO.cjs");exports.captureWorkerPoolOperation=e.captureWorkerPoolOperation;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./workerPoolSpanCapture-BQ3Pbkl2.cjs");exports.captureWorkerPoolOperation=e.captureWorkerPoolOperation;
@@ -1,4 +1,4 @@
1
- import { c as e } from "./workerPoolSpanCapture-B5KN-q4b.js";
1
+ import { c as e } from "./workerPoolSpanCapture-BYaf3NOr.js";
2
2
  export {
3
3
  e as captureWorkerPoolOperation
4
4
  };
@@ -0,0 +1,83 @@
1
+ "use strict";var B=Object.defineProperty;var K=(n,t,o)=>t in n?B(n,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):n[t]=o;var S=(n,t,o)=>K(n,typeof t!="symbol"?t+"":t,o);const w=require("async_hooks"),V=require("fs"),I=require("worker_threads"),l=require("./contextManager-CGINtRN5.cjs");class M{constructor(){S(this,"apiKey");S(this,"endpoint");S(this,"queryType","mutation");S(this,"operationName","");S(this,"serviceUUID",l.getConfig().serviceUUID);S(this,"contextManager");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 J=fetch;let $=!1;async function O(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,J(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 h(n,t){if(!n)return t;const o=n.toLowerCase();return o==="true"||o==="1"||o==="yes"}const T=new w.AsyncLocalStorage;function C(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 y(n,t){const o=process.env[n];return o===void 0?t:o==="true"||o==="1"}function E(n,t){const o=process.env[n];if(o===void 0)return t;const s=parseFloat(o);return isNaN(s)?t:s}function F(){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)}}function D(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?C(a,s):a}catch{return{error:"Failed to capture arguments",argsCount:o.length-1}}}function L(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?C(a,s):a}catch{return{error:"Failed to capture result",type:typeof o}}}function x(n){return n.operationType==="worker_pool"}class W extends M{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(x(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))),O(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))),O(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 k=null;function P(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
+ `;V.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{(k||(k=new W),k).send([n]),o&&console.log("[WorkerPool] Span sent successfully")}catch(a){o&&console.error("[WorkerPool] Error sending span:",a)}}exports.BaseTransmitter=M,exports.FunctionSpanTransmitter=W,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=F(),u=l.ContextManager.getInstance().getCurrentFunctionSpanId(),g=l.v4();e&&console.log(`[WorkerPool] Span ID: ${g}, Parent: ${u||"none"}`);const c=new w.AsyncResource("WorkerPoolOperation"),d=process.hrtime.bigint();let p=null;r.captureArguments&&(p=D(n,t,s,r.argLimitMb));const f=s.findIndex(N=>typeof N=="function");if(f===-1)return e&&console.log(`[WorkerPool] No callback found for ${n}.${t}`),o.apply(a,s);const m=s[f],_=[...s];return _[f]=function(N,...b){const v=process.hrtime.bigint()-d,A=Number(v)/1e6;m(N,...b),c.runInAsyncScope(()=>{e&&console.log(`[WorkerPool] ${n}.${t} completed in ${A.toFixed(3)}ms (${v}ns)`);let U=null,R=null;N?R=N?.message||String(N):r.captureReturnValue&&b.length>0&&(U=L(n,t,b[0],r.returnLimitMb)),P({operationType:"worker_pool",operationName:`${n}.${t}`,moduleName:n,methodName:t,duration:A,durationNs:v.toString(),startTimeNs:d.toString(),args:p,result:U,error:R,spanId:g,parentSpanId:u,pid:process.pid,threadId:I.threadId})}),c.emitDestroy()},o.apply(a,_)},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=F(),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=D(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 _=null;return r.captureReturnValue&&(_=L(n,t,p,r.returnLimitMb)),P({operationType:"worker_pool",operationName:`${n}.${t}`,moduleName:n,methodName:t,duration:m,durationNs:f.toString(),startTimeNs:c.toString(),args:d,result:_,error:null,spanId:g,parentSpanId:u,pid:process.pid,threadId:I.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}`),P({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:I.threadId}),p})},exports.clearFuncspanOverride=function(){},exports.funcspanOverrideStorage=T,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:h(process.env.SF_FUNCSPAN_CAPTURE_ARGUMENTS,!0),capture_return_value:h(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:h(process.env.SF_FUNCSPAN_AUTOCAPTURE_ALL_CHILD_FUNCTIONS,!1),sample_rate:parseFloat(process.env.SF_FUNCSPAN_SAMPLE_RATE||"1.0"),enable_sampling:h(process.env.SF_FUNCSPAN_ENABLE_SAMPLING,!1),capture_sf_veritas:h(process.env.SF_FUNCSPAN_CAPTURE_SF_VERITAS,!1),parse_json_strings:h(process.env.SF_FUNCSPAN_PARSE_JSON_STRINGS,!1)}},exports.getFuncspanOverride=function(){return T.getStore()},exports.isModuleTrackingEnabled=function(n){const t=F();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=O,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){T.enterWith(n)},exports.truncateToLimit=C;
@@ -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
  };
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.12",
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",
@@ -1,86 +0,0 @@
1
- "use strict";var K=Object.defineProperty;var V=(n,t,o)=>t in n?K(n,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):n[t]=o;var S=(n,t,o)=>V(n,typeof t!="symbol"?t+"":t,o);const M=require("async_hooks"),J=require("fs"),F=require("worker_threads"),l=require("./contextManager-CGINtRN5.cjs");class W{constructor(){S(this,"apiKey");S(this,"endpoint");S(this,"queryType","mutation");S(this,"operationName","");S(this,"serviceUUID",l.getConfig().serviceUUID);S(this,"contextManager");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 x=fetch;let $=!1;async function C(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,x(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 h(n,t){if(!n)return t;const o=n.toLowerCase();return o==="true"||o==="1"||o==="yes"}const v=new M.AsyncLocalStorage;let T=!1;function A(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 y(n,t){const o=process.env[n];return o===void 0?t:o==="true"||o==="1"}function D(n,t){const o=process.env[n];if(o===void 0)return t;const s=parseFloat(o);return isNaN(s)?t:s}function k(){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:D("SF_WORKER_POOL_ARG_LIMIT_MB",1),returnLimitMb:D("SF_WORKER_POOL_RETURN_LIMIT_MB",1)}}function L(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?A(a,s):a}catch{return{error:"Failed to capture arguments",argsCount:o.length-1}}}function w(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?A(a,s):a}catch{return{error:"Failed to capture result",type:typeof o}}}function z(n){return n.operationType==="worker_pool"}class B 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(z(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))),C(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))),C(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 P=null;function O(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
- `;J.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{(P||(P=new B),P).send([n]),o&&console.log("[WorkerPool] Span sent successfully")}catch(a){o&&console.error("[WorkerPool] Error sending span:",a)}}exports.BaseTransmitter=W,exports.FunctionSpanTransmitter=B,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=k(),u=l.ContextManager.getInstance().getCurrentFunctionSpanId(),g=l.v4();e&&console.log(`[WorkerPool] Span ID: ${g}, Parent: ${u||"none"}`);const c=new M.AsyncResource("WorkerPoolOperation"),d=process.hrtime.bigint();let p=null;r.captureArguments&&(p=L(n,t,s,r.argLimitMb));const f=s.findIndex(N=>typeof N=="function");if(f===-1)return e&&console.log(`[WorkerPool] No callback found for ${n}.${t}`),o.apply(a,s);const m=s[f],_=[...s];return _[f]=function(N,...b){const I=process.hrtime.bigint()-d,U=Number(I)/1e6;m(N,...b),c.runInAsyncScope(()=>{e&&console.log(`[WorkerPool] ${n}.${t} completed in ${U.toFixed(3)}ms (${I}ns)`);let R=null,E=null;N?E=N?.message||String(N):r.captureReturnValue&&b.length>0&&(R=w(n,t,b[0],r.returnLimitMb)),O({operationType:"worker_pool",operationName:`${n}.${t}`,moduleName:n,methodName:t,duration:U,durationNs:I.toString(),startTimeNs:d.toString(),args:p,result:R,error:E,spanId:g,parentSpanId:u,pid:process.pid,threadId:F.threadId})}),c.emitDestroy()},o.apply(a,_)},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=k(),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=L(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 _=null;return r.captureReturnValue&&(_=w(n,t,p,r.returnLimitMb)),O({operationType:"worker_pool",operationName:`${n}.${t}`,moduleName:n,methodName:t,duration:m,durationNs:f.toString(),startTimeNs:c.toString(),args:d,result:_,error:null,spanId:g,parentSpanId:u,pid:process.pid,threadId:F.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}`),O({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:F.threadId}),p})},exports.clearFuncspanOverride=function(){},exports.funcspanOverrideStorage=v,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:h(process.env.SF_FUNCSPAN_CAPTURE_ARGUMENTS,!0),capture_return_value:h(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:h(process.env.SF_FUNCSPAN_AUTOCAPTURE_ALL_CHILD_FUNCTIONS,!1),sample_rate:parseFloat(process.env.SF_FUNCSPAN_SAMPLE_RATE||"1.0"),enable_sampling:h(process.env.SF_FUNCSPAN_ENABLE_SAMPLING,!1),capture_sf_veritas:h(process.env.SF_FUNCSPAN_CAPTURE_SF_VERITAS,!1),parse_json_strings:h(process.env.SF_FUNCSPAN_PARSE_JSON_STRINGS,!1)}},exports.getFuncspanOverride=function(){if(T)return v.getStore();try{T=!0;const n=v.getStore(),t=new Error().stack?.split(`
84
- `).slice(1,4).join(`
85
- `);return console.log(`[getFuncspanOverride] Called from:
86
- ${t}`),console.log("[getFuncspanOverride] Returned value:",n),n}catch(n){return void console.error("[getFuncspanOverride] ❌ Error:",n)}finally{T=!1}},exports.isModuleTrackingEnabled=function(n){const t=k();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=C,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){v.enterWith(n)},exports.truncateToLimit=A;