@sailfish-ai/sf-veritas 0.2.2 → 0.2.4

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 +1 @@
1
- "use strict";var b=Object.defineProperty;var f=(o,e,t)=>e in o?b(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var d=(o,e,t)=>f(o,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});function g(o){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const t in o)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>o[t]})}}return e.default=o,Object.freeze(e)}const m=g(require("path"));class i{constructor(e={}){d(this,"options");this.options={enabled:!0,includeNodeModules:[],debug:!1,...e}}apply(e){const{enabled:t,includeNodeModules:n,debug:c}=this.options;if(!t)return;const u="FuncspanWebpackPlugin";e.hooks.compilation.tap(u,l=>{l.hooks.buildModule.tap(u,r=>{r.resource&&r.resource.match(/\.(js|ts|jsx|tsx)$/)&&(!r.resource.includes("node_modules")||n?.some(s=>r.resource.includes(`node_modules/${s}`)))}),e.webpack.NormalModule.getCompilationHooks(l).loader.tap(u,(r,s)=>{if(!s.resource||!s.resource.match(/\.(js|ts|jsx|tsx)$/)||s.resource.includes("node_modules")&&!n?.some(p=>s.resource.includes(`node_modules/${p}`)))return;const a=m.join(__dirname,"funcspanWebpackLoader.cjs");s.loaders.push({loader:a,options:{projectRoot:e.context,includeNodeModules:n,debug:c}})})}),c&&console.log("[FuncSpan Webpack] Plugin initialized")}}exports.FuncspanWebpackPlugin=i,exports.default=i;
1
+ "use strict";var g=Object.defineProperty;var j=(o,e,n)=>e in o?g(o,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):o[e]=n;var i=(o,e,n)=>j(o,typeof e!="symbol"?e+"":e,n);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const p=require("path"),_=require("url");var c=typeof document<"u"?document.currentScript:null;function h(o){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const n in o)if(n!=="default"){const u=Object.getOwnPropertyDescriptor(o,n);Object.defineProperty(e,n,u.get?u:{enumerable:!0,get:()=>o[n]})}}return e.default=o,Object.freeze(e)}const k=h(p);class a{constructor(e={}){i(this,"options");this.options={enabled:!0,includeNodeModules:[],debug:!1,...e}}apply(e){const{enabled:n,includeNodeModules:u,debug:d}=this.options;if(!n)return;const s="FuncspanWebpackPlugin";e.hooks.compilation.tap(s,l=>{l.hooks.buildModule.tap(s,r=>{r.resource&&r.resource.match(/\.(js|ts|jsx|tsx)$/)&&(!r.resource.includes("node_modules")||u?.some(t=>r.resource.includes(`node_modules/${t}`)))}),e.webpack.NormalModule.getCompilationHooks(l).loader.tap(s,(r,t)=>{if(!t.resource||!t.resource.match(/\.(js|ts|jsx|tsx)$/)||t.resource.includes("node_modules")&&!u?.some(b=>t.resource.includes(`node_modules/${b}`)))return;const f=typeof __dirname<"u"?__dirname:p.dirname(_.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:c&&c.tagName.toUpperCase()==="SCRIPT"&&c.src||new URL("plugins/funcspanWebpackPlugin.cjs",document.baseURI).href)),m=k.join(f,"funcspanWebpackLoader.cjs");t.loaders.push({loader:m,options:{projectRoot:e.context,includeNodeModules:u,debug:d}})})}),d&&console.log("[FuncSpan Webpack] Plugin initialized")}}exports.FuncspanWebpackPlugin=a,exports.default=a;
@@ -1,28 +1,30 @@
1
- var p = Object.defineProperty;
2
- var m = (s, e, n) => e in s ? p(s, e, { enumerable: !0, configurable: !0, writable: !0, value: n }) : s[e] = n;
3
- var d = (s, e, n) => m(s, typeof e != "symbol" ? e + "" : e, n);
1
+ var m = Object.defineProperty;
2
+ var f = (s, e, n) => e in s ? m(s, e, { enumerable: !0, configurable: !0, writable: !0, value: n }) : s[e] = n;
3
+ var a = (s, e, n) => f(s, typeof e != "symbol" ? e + "" : e, n);
4
4
  import * as b from "path";
5
- class k {
5
+ import { dirname as g } from "path";
6
+ import { fileURLToPath as h } from "url";
7
+ class x {
6
8
  constructor(e = {}) {
7
- d(this, "options");
9
+ a(this, "options");
8
10
  this.options = { enabled: !0, includeNodeModules: [], debug: !1, ...e };
9
11
  }
10
12
  apply(e) {
11
- const { enabled: n, includeNodeModules: c, debug: t } = this.options;
13
+ const { enabled: n, includeNodeModules: r, debug: i } = this.options;
12
14
  if (!n) return;
13
- const r = "FuncspanWebpackPlugin";
14
- e.hooks.compilation.tap(r, (l) => {
15
- l.hooks.buildModule.tap(r, (u) => {
16
- u.resource && u.resource.match(/\.(js|ts|jsx|tsx)$/) && (!u.resource.includes("node_modules") || c?.some((o) => u.resource.includes(`node_modules/${o}`)));
17
- }), e.webpack.NormalModule.getCompilationHooks(l).loader.tap(r, (u, o) => {
18
- if (!o.resource || !o.resource.match(/\.(js|ts|jsx|tsx)$/) || o.resource.includes("node_modules") && !c?.some((a) => o.resource.includes(`node_modules/${a}`))) return;
19
- const i = b.join(__dirname, "funcspanWebpackLoader.cjs");
20
- o.loaders.push({ loader: i, options: { projectRoot: e.context, includeNodeModules: c, debug: t } });
15
+ const t = "FuncspanWebpackPlugin";
16
+ e.hooks.compilation.tap(t, (c) => {
17
+ c.hooks.buildModule.tap(t, (u) => {
18
+ u.resource && u.resource.match(/\.(js|ts|jsx|tsx)$/) && (!u.resource.includes("node_modules") || r?.some((o) => u.resource.includes(`node_modules/${o}`)));
19
+ }), e.webpack.NormalModule.getCompilationHooks(c).loader.tap(t, (u, o) => {
20
+ if (!o.resource || !o.resource.match(/\.(js|ts|jsx|tsx)$/) || o.resource.includes("node_modules") && !r?.some((p) => o.resource.includes(`node_modules/${p}`))) return;
21
+ const d = typeof __dirname < "u" ? __dirname : g(h(import.meta.url)), l = b.join(d, "funcspanWebpackLoader.cjs");
22
+ o.loaders.push({ loader: l, options: { projectRoot: e.context, includeNodeModules: r, debug: i } });
21
23
  });
22
- }), t && console.log("[FuncSpan Webpack] Plugin initialized");
24
+ }), i && console.log("[FuncSpan Webpack] Plugin initialized");
23
25
  }
24
26
  }
25
27
  export {
26
- k as FuncspanWebpackPlugin,
27
- k as default
28
+ x as FuncspanWebpackPlugin,
29
+ x as default
28
30
  };
@@ -1,4 +1,4 @@
1
- "use strict";var We=Object.defineProperty;var Fe=(o,e,t)=>e in o?We(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var u=(o,e,t)=>Fe(o,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ne=require("async_hooks"),ie=require("fs"),fe=require("./source-map-rHHEdpre.cjs"),Ve=require("worker_threads"),we=require("path"),He=require("glob");function ye(o){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const t in o)if(t!=="default"){const i=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:()=>o[t]})}}return e.default=o,Object.freeze(e)}const k=ye(ie),v=ye(we),S=[];for(let o=0;o<256;++o)S.push((o+256).toString(16).slice(1));let O;const Re=new Uint8Array(16),se={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function H(o,e,t){if(se.randomUUID&&!o)return se.randomUUID();const i=(o=o||{}).random??o.rng?.()??(function(){if(!O){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");O=crypto.getRandomValues.bind(crypto)}return O(Re)})();if(i.length<16)throw new Error("Random bytes length must be >= 16");return i[6]=15&i[6]|64,i[8]=63&i[8]|128,(function(n,s=0){return(S[n[s+0]]+S[n[s+1]]+S[n[s+2]]+S[n[s+3]]+"-"+S[n[s+4]]+S[n[s+5]]+"-"+S[n[s+6]]+S[n[s+7]]+"-"+S[n[s+8]]+S[n[s+9]]+"-"+S[n[s+10]]+S[n[s+11]]+S[n[s+12]]+S[n[s+13]]+S[n[s+14]]+S[n[s+15]]).toLowerCase()})(i)}class Ye{constructor(e){u(this,"apiKey");u(this,"apiGraphqlEndpoint");u(this,"sfDebug");u(this,"serviceIdentifier");u(this,"serviceVersion");u(this,"serviceUUID");u(this,"serviceAdditionalMetadata");u(this,"profilingModeEnabled");u(this,"profilingMaxDepth");u(this,"profilingMaxVariableSizeKb");u(this,"domainsToNotPropagateHeadersTo");u(this,"nodeModulesToCollectLocalVariablesOn");u(this,"printConfigurationStatuses");u(this,"logLevel");u(this,"stackDepthLocals");u(this,"stackDepthCodeTraceDepth");u(this,"packageLibraryType");u(this,"version");u(this,"gitSha");u(this,"_serviceIdentificationReceived",!1);this.apiKey=e.apiKey,this.apiGraphqlEndpoint=e?.apiGraphqlEndpoint||process.env.SAILFISH_GRAPHQL_ENDPOINT||"https://api-service.sailfishqa.com/graphql/",this.sfDebug=e?.debug===!0||process.env.SF_DEBUG==="true",this.serviceIdentifier=e?.serviceIdentifier||process.env.SERVICE_IDENTIFIER,this.serviceUUID=H(),this.serviceVersion=e?.serviceVersion||process.env.SERVICE_VERSION,this.gitSha=e?.gitSha||process.env.GIT_SHA||process.env.VERCEL_GIT_COMMIT_SHA,this.serviceAdditionalMetadata=e?.serviceAdditionalMetadata||{},this.profilingModeEnabled=e?.profilingModeEnabled??!1,this.profilingMaxDepth=e?.profilingMaxDepth??5,this.profilingMaxVariableSizeKb=e?.profilingMaxVariableSizeKb??25,this.domainsToNotPropagateHeadersTo=e?.domainsToNotPropagateHeadersTo||[],this.nodeModulesToCollectLocalVariablesOn=e?.nodeModulesToCollectLocalVariablesOn||["_all_"],this.printConfigurationStatuses=process.env.PRINT_CONFIGURATION_STATUSES||"true",this.logLevel=process.env.LOG_LEVEL||"INFO",this.stackDepthLocals=process.env.SAILFISH_EXCEPTION_STACK_DEPTH_LOCALS!==void 0?parseInt(process.env.SAILFISH_EXCEPTION_STACK_DEPTH_LOCALS,10):5,isNaN(this.stackDepthLocals)&&(this.stackDepthLocals=-1),this.stackDepthCodeTraceDepth=process.env.SAILFISH_EXCEPTION_STACK_DEPTH_CODE_TRACE_DEPTH!==void 0?parseInt(process.env.SAILFISH_EXCEPTION_STACK_DEPTH_CODE_TRACE_DEPTH,10):-1,isNaN(this.stackDepthCodeTraceDepth)&&(this.stackDepthCodeTraceDepth=-1),this.packageLibraryType="JS/TS BACKEND",this.version=this.getPackageVersion()}getPackageVersion(){return"0.1.15"}get serviceIdentificationReceived(){return this._serviceIdentificationReceived}setServiceIdentificationReceived(e){this._serviceIdentificationReceived=e}}const Se=Symbol.for("sailfish.sf_config");function Ze(){return globalThis[Se]}function Ke(o){const e=Ze();if(e)return{config:e};const t=new Ye(o);return(function(i){globalThis[Se]=i})(t),t.sfDebug&&console.log("[[getOrCreateConfig]] Created global config:",t),{config:t}}function l(){const o=Ze();if(!o)throw new Error("Configuration has not been initialized. Call getOrCreateConfig(options) first.");return o}const re=Symbol.for("sf.ctx.storeAls"),W=globalThis,P=W[re]??(W[re]=new ne.AsyncLocalStorage),Ge=["identitytoolkit.googleapis.com","t.co","*.twitter.com","*.gravatar.com","*.googleapis.com","*.amazonaws.com","*.smooch.io","*.zendesk.com"],ae=Symbol.for("sf.ctx.als"),U=W[ae]??(W[ae]=new ne.AsyncLocalStorage),ce=Symbol.for("sf.ctx.sessionRegistry"),Y=W[ce]??(W[ce]=new Map),_={handledExceptions:new Set,reentrancyGuardLoggingActive:!1,reentrancyGuardLoggingPreActive:!1,reentrancyGuardPrintActive:!1,reentrancyGuardPrintPreActive:!1,reentrancyGuardExceptionActive:!1,reentrancyGuardExceptionPreActive:!1,excludedDomains:new Set(Ge),supportedDomains:new Set},V=class V{constructor(){}current(){return P.getStore()}ensureStore(){const e=this.current();if(e)return e;const t=new Map;return P.enterWith(t),t}runWith(e,t){const i=this.current()??new Map,n=new Map(i);for(const[s,a]of Object.entries(e))n.set(s,a);return P.run(n,t)}static getInstance(){return W[V.GLOBAL_MANAGER_SYMBOL]||(W[V.GLOBAL_MANAGER_SYMBOL]=new V),W[V.GLOBAL_MANAGER_SYMBOL]}getCurrentContext(){return U.getStore()||_}setCurrentContext(e){const t=U.getStore()||_;U.enterWith({...t,...e})}ensureSession(e){let t=Y.get(e);return t||(t={..._},Y.set(e,t)),t}getContextFor(e){return Y.get(e)??_}updateContextFor(e,t){const i=this.ensureSession(e);Y.set(e,{...i,...t})}runWithSession(e,t){const i={...this.ensureSession(e)};return U.run(i,t)}deleteSession(e){Y.delete(e)}getTraceId(){return this.getCurrentContext().traceId}getPageVisitUUID(){return this.getCurrentContext().pageVisitUUID}setTraceId(e){this.setCurrentContext({traceId:e})}setPageVisitUUID(e){this.setCurrentContext({pageVisitUUID:e})}getCurrentFunctionSpanId(){return this.getCurrentContext().currentFunctionSpanId}setCurrentFunctionSpanId(e){this.setCurrentContext({currentFunctionSpanId:e})}clearCurrentFunctionSpanId(){this.setCurrentContext({currentFunctionSpanId:void 0})}getOrSetSfTraceId(e,t=!1){let i=this.getTraceId();return i||(i=e||(t?H():`nonsession-applogs-v3/${l().apiKey}/${H()}`),this.setTraceId(i),l().sfDebug&&console.log(" Created new trace ID:",i),i)}getOrSetPageVisitUUID(){let e=this.getPageVisitUUID();return e||(e=H(),this.setPageVisitUUID(e),l().sfDebug&&console.log(" Created new page visit UUID:",e),e)}getHandledExceptions(){return this.getCurrentContext().handledExceptions}markExceptionHandled(e){const t=this.getHandledExceptions();t.add(e),this.setCurrentContext({handledExceptions:t})}hasHandledException(e){return this.getHandledExceptions().has(e)}resetHandledExceptions(){this.setCurrentContext({handledExceptions:new Set})}getExcludedDomains(){return this.getCurrentContext().excludedDomains}getSupportedDomains(){return this.getCurrentContext().supportedDomains}addSupportedDomains(e){this.getCurrentContext().supportedDomains.add(e.toLowerCase().trim())}setTraceIdFor(e,t){this.updateContextFor(e,{traceId:t})}setPageVisitUUIDFor(e,t){this.updateContextFor(e,{pageVisitUUID:t})}};u(V,"GLOBAL_MANAGER_SYMBOL",Symbol.for("sf.ctx.manager"));let G=V;function ve(o){const e={...G.getInstance().getCurrentContext()};U.run(e,()=>{o()})}function L(){return G.getInstance().getCurrentFunctionSpanId()}class R{constructor(){u(this,"apiKey");u(this,"endpoint");u(this,"queryType","mutation");u(this,"operationName","");u(this,"serviceUUID",l().serviceUUID);u(this,"contextManager");this.apiKey=l().apiKey,this.endpoint=l().apiGraphqlEndpoint,this.contextManager=G.getInstance()}get queryName(){return this.operationName?this.operationName.charAt(0).toLowerCase()+this.operationName.slice(1):""}getDefaultVariables(){const e=Date.now().toString(),t=this.contextManager.getOrSetSfTraceId(),i=this.contextManager.getCurrentFunctionSpanId();return{apiKey:this.apiKey,serviceUuid:this.serviceUUID,sessionId:t,timestampMs:e,parentSpanId:i}}getVariables(e={}){return{...this.getDefaultVariables(),...e}}setOperationName(e){this.operationName=e}setEndpoint(e){this.endpoint=e}setServiceUUID(e){this.serviceUUID=e}}const Ue=fetch;async function F(o,e,t,i){try{const n=l();let s;try{s=JSON.stringify({query:t,variables:i,operationName:e})}catch{s=JSON.stringify({query:t,operationName:e})}Ue(o,{method:"POST",headers:{"Content-Type":"application/json"},body:s}).then(async a=>{if(!a.ok)return void(n.sfDebug&&console.error(`GraphQL request failed with status ${a.status} for ${e}`));const r=await a.json();r.errors?.length?(function(g,c,I){const d=g&&typeof g=="object"&&!Array.isArray(g)?Object.keys(g)[0]:void 0;console.error(d==="identifyServiceDetails"?`IdentifyServiceDetails NOT sent successfully for service: UUID=${I.serviceUUID}`:`GraphQL request failed with errors: ${JSON.stringify(c)} for operation key ${d}`)})(r.data,r.errors,n):n.sfDebug&&(function(g,c,I){const d=g&&typeof g=="object"&&!Array.isArray(g)?Object.keys(g)[0]:void 0,C=g[d]||!1;d==="identifyServiceDetails"&&(I.setServiceIdentificationReceived(C),l().sfDebug&&console.log(`IdentifyServiceDetails sent successfully for service: UUID=${I.serviceUUID}; serviceIdentificationReceived=${d==="identifyServiceDetails"?C:"N/A"}`))})(r.data,0,n)}).catch(a=>{n.sfDebug&&console.error("Fetch error:",a)})}catch(n){l().sfDebug&&console.error("Error sending data to GraphQL server:",n)}}class T extends R{constructor(){super(),this.setOperationName("IdentifyServiceDetails")}async doSend(e){if(!l().serviceIdentificationReceived)try{this.send()}catch(t){l().sfDebug&&console.error(" Error during service identification:",t)}}async send(){const e=`
1
+ "use strict";var Ve=Object.defineProperty;var we=(o,e,t)=>e in o?Ve(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var C=(o,e,t)=>we(o,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const se=require("async_hooks"),re=require("fs"),Ze=require("./source-map-rHHEdpre.cjs"),He=require("worker_threads"),Re=require("path"),Ye=require("glob");function ve(o){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const t in o)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>o[t]})}}return e.default=o,Object.freeze(e)}const O=ve(re),G=ve(Re),Z=[];for(let o=0;o<256;++o)Z.push((o+256).toString(16).slice(1));let P;const Ue=new Uint8Array(16),le={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function R(o,e,t){if(le.randomUUID&&!o)return le.randomUUID();const n=(o=o||{}).random??o.rng?.()??(function(){if(!P){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");P=crypto.getRandomValues.bind(crypto)}return P(Ue)})();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=15&n[6]|64,n[8]=63&n[8]|128,(function(i,s=0){return(Z[i[s+0]]+Z[i[s+1]]+Z[i[s+2]]+Z[i[s+3]]+"-"+Z[i[s+4]]+Z[i[s+5]]+"-"+Z[i[s+6]]+Z[i[s+7]]+"-"+Z[i[s+8]]+Z[i[s+9]]+"-"+Z[i[s+10]]+Z[i[s+11]]+Z[i[s+12]]+Z[i[s+13]]+Z[i[s+14]]+Z[i[s+15]]).toLowerCase()})(n)}class Ke{constructor(e){C(this,"apiKey");C(this,"apiGraphqlEndpoint");C(this,"sfDebug");C(this,"serviceIdentifier");C(this,"serviceVersion");C(this,"serviceUUID");C(this,"serviceAdditionalMetadata");C(this,"profilingModeEnabled");C(this,"profilingMaxDepth");C(this,"profilingMaxVariableSizeKb");C(this,"domainsToNotPropagateHeadersTo");C(this,"nodeModulesToCollectLocalVariablesOn");C(this,"printConfigurationStatuses");C(this,"logLevel");C(this,"stackDepthLocals");C(this,"stackDepthCodeTraceDepth");C(this,"packageLibraryType");C(this,"version");C(this,"gitSha");C(this,"_serviceIdentificationReceived",!1);this.apiKey=e.apiKey,this.apiGraphqlEndpoint=e?.apiGraphqlEndpoint||process.env.SAILFISH_GRAPHQL_ENDPOINT||"https://api-service.sailfishqa.com/graphql/",this.sfDebug=e?.debug===!0||process.env.SF_DEBUG==="true",this.serviceIdentifier=e?.serviceIdentifier||process.env.SERVICE_IDENTIFIER,this.serviceUUID=R(),this.serviceVersion=e?.serviceVersion||process.env.SERVICE_VERSION,this.gitSha=e?.gitSha||process.env.GIT_SHA||process.env.VERCEL_GIT_COMMIT_SHA,this.serviceAdditionalMetadata=e?.serviceAdditionalMetadata||{},this.profilingModeEnabled=e?.profilingModeEnabled??!1,this.profilingMaxDepth=e?.profilingMaxDepth??5,this.profilingMaxVariableSizeKb=e?.profilingMaxVariableSizeKb??25,this.domainsToNotPropagateHeadersTo=e?.domainsToNotPropagateHeadersTo||[],this.nodeModulesToCollectLocalVariablesOn=e?.nodeModulesToCollectLocalVariablesOn||["_all_"],this.printConfigurationStatuses=process.env.PRINT_CONFIGURATION_STATUSES||"true",this.logLevel=process.env.LOG_LEVEL||"INFO",this.stackDepthLocals=process.env.SAILFISH_EXCEPTION_STACK_DEPTH_LOCALS!==void 0?parseInt(process.env.SAILFISH_EXCEPTION_STACK_DEPTH_LOCALS,10):5,isNaN(this.stackDepthLocals)&&(this.stackDepthLocals=-1),this.stackDepthCodeTraceDepth=process.env.SAILFISH_EXCEPTION_STACK_DEPTH_CODE_TRACE_DEPTH!==void 0?parseInt(process.env.SAILFISH_EXCEPTION_STACK_DEPTH_CODE_TRACE_DEPTH,10):-1,isNaN(this.stackDepthCodeTraceDepth)&&(this.stackDepthCodeTraceDepth=-1),this.packageLibraryType="JS/TS BACKEND",this.version=this.getPackageVersion()}getPackageVersion(){return"0.1.15"}get serviceIdentificationReceived(){return this._serviceIdentificationReceived}setServiceIdentificationReceived(e){this._serviceIdentificationReceived=e}}const Ge=Symbol.for("sailfish.sf_config");function x(){return globalThis[Ge]}function Te(o){const e=x();if(e)return{config:e};const t=new Ke(o);return(function(n){globalThis[Ge]=n})(t),t.sfDebug&&console.log("[[getOrCreateConfig]] Created global config:",t),{config:t}}function l(){const o=x();if(!o)throw new Error("Configuration has not been initialized. Call getOrCreateConfig(options) first.");return o}const de=Symbol.for("sf.ctx.storeAls"),W=globalThis,M=W[de]??(W[de]=new se.AsyncLocalStorage),Ne=["identitytoolkit.googleapis.com","t.co","*.twitter.com","*.gravatar.com","*.googleapis.com","*.amazonaws.com","*.smooch.io","*.zendesk.com"],Ie=Symbol.for("sf.ctx.als"),K=W[Ie]??(W[Ie]=new se.AsyncLocalStorage),ue=Symbol.for("sf.ctx.sessionRegistry"),Y=W[ue]??(W[ue]=new Map),E={handledExceptions:new Set,reentrancyGuardLoggingActive:!1,reentrancyGuardLoggingPreActive:!1,reentrancyGuardPrintActive:!1,reentrancyGuardPrintPreActive:!1,reentrancyGuardExceptionActive:!1,reentrancyGuardExceptionPreActive:!1,excludedDomains:new Set(Ne),supportedDomains:new Set},V=class V{constructor(){}current(){return M.getStore()}ensureStore(){const e=this.current();if(e)return e;const t=new Map;return M.enterWith(t),t}runWith(e,t){const n=this.current()??new Map,i=new Map(n);for(const[s,g]of Object.entries(e))i.set(s,g);return M.run(i,t)}static getInstance(){return W[V.GLOBAL_MANAGER_SYMBOL]||(W[V.GLOBAL_MANAGER_SYMBOL]=new V),W[V.GLOBAL_MANAGER_SYMBOL]}getCurrentContext(){return K.getStore()||E}setCurrentContext(e){const t=K.getStore()||E;K.enterWith({...t,...e})}ensureSession(e){let t=Y.get(e);return t||(t={...E},Y.set(e,t)),t}getContextFor(e){return Y.get(e)??E}updateContextFor(e,t){const n=this.ensureSession(e);Y.set(e,{...n,...t})}runWithSession(e,t){const n={...this.ensureSession(e)};return K.run(n,t)}deleteSession(e){Y.delete(e)}getTraceId(){return this.getCurrentContext().traceId}getPageVisitUUID(){return this.getCurrentContext().pageVisitUUID}setTraceId(e){this.setCurrentContext({traceId:e})}setPageVisitUUID(e){this.setCurrentContext({pageVisitUUID:e})}getCurrentFunctionSpanId(){return this.getCurrentContext().currentFunctionSpanId}setCurrentFunctionSpanId(e){this.setCurrentContext({currentFunctionSpanId:e})}clearCurrentFunctionSpanId(){this.setCurrentContext({currentFunctionSpanId:void 0})}getOrSetSfTraceId(e,t=!1){let n=this.getTraceId();return n||(n=e||(t?R():`nonsession-applogs-v3/${l().apiKey}/${R()}`),this.setTraceId(n),l().sfDebug&&console.log(" Created new trace ID:",n),n)}getOrSetPageVisitUUID(){let e=this.getPageVisitUUID();return e||(e=R(),this.setPageVisitUUID(e),l().sfDebug&&console.log(" Created new page visit UUID:",e),e)}getHandledExceptions(){return this.getCurrentContext().handledExceptions}markExceptionHandled(e){const t=this.getHandledExceptions();t.add(e),this.setCurrentContext({handledExceptions:t})}hasHandledException(e){return this.getHandledExceptions().has(e)}resetHandledExceptions(){this.setCurrentContext({handledExceptions:new Set})}getExcludedDomains(){return this.getCurrentContext().excludedDomains}getSupportedDomains(){return this.getCurrentContext().supportedDomains}addSupportedDomains(e){this.getCurrentContext().supportedDomains.add(e.toLowerCase().trim())}setTraceIdFor(e,t){this.updateContextFor(e,{traceId:t})}setPageVisitUUIDFor(e,t){this.updateContextFor(e,{pageVisitUUID:t})}};C(V,"GLOBAL_MANAGER_SYMBOL",Symbol.for("sf.ctx.manager"));let v=V;function $(){return v.getInstance().getCurrentFunctionSpanId()}class w{constructor(){C(this,"apiKey");C(this,"endpoint");C(this,"queryType","mutation");C(this,"operationName","");C(this,"serviceUUID",l().serviceUUID);C(this,"contextManager");this.apiKey=l().apiKey,this.endpoint=l().apiGraphqlEndpoint,this.contextManager=v.getInstance()}get queryName(){return this.operationName?this.operationName.charAt(0).toLowerCase()+this.operationName.slice(1):""}getDefaultVariables(){const e=Date.now().toString(),t=this.contextManager.getOrSetSfTraceId(),n=this.contextManager.getCurrentFunctionSpanId();return{apiKey:this.apiKey,serviceUuid:this.serviceUUID,sessionId:t,timestampMs:e,parentSpanId:n}}getVariables(e={}){return{...this.getDefaultVariables(),...e}}setOperationName(e){this.operationName=e}setEndpoint(e){this.endpoint=e}setServiceUUID(e){this.serviceUUID=e}}const Je=fetch;async function F(o,e,t,n){try{const i=l();let s;try{s=JSON.stringify({query:t,variables:n,operationName:e})}catch{s=JSON.stringify({query:t,operationName:e})}Je(o,{method:"POST",headers:{"Content-Type":"application/json"},body:s}).then(async g=>{if(!g.ok)return void(i.sfDebug&&console.error(`GraphQL request failed with status ${g.status} for ${e}`));const r=await g.json();r.errors?.length?(function(a,c,d){const I=a&&typeof a=="object"&&!Array.isArray(a)?Object.keys(a)[0]:void 0;console.error(I==="identifyServiceDetails"?`IdentifyServiceDetails NOT sent successfully for service: UUID=${d.serviceUUID}`:`GraphQL request failed with errors: ${JSON.stringify(c)} for operation key ${I}`)})(r.data,r.errors,i):i.sfDebug&&(function(a,c,d){const I=a&&typeof a=="object"&&!Array.isArray(a)?Object.keys(a)[0]:void 0,h=a[I]||!1;I==="identifyServiceDetails"&&(d.setServiceIdentificationReceived(h),l().sfDebug&&console.log(`IdentifyServiceDetails sent successfully for service: UUID=${d.serviceUUID}; serviceIdentificationReceived=${I==="identifyServiceDetails"?h:"N/A"}`))})(r.data,0,i)}).catch(g=>{i.sfDebug&&(console.error(`[RequestUtils] Fetch error for ${e} to ${o}:`,g),g.cause&&console.error("[RequestUtils] Error cause:",g.cause))})}catch(i){l().sfDebug&&console.error("Error sending data to GraphQL server:",i)}}class X extends w{constructor(){super(),this.setOperationName("IdentifyServiceDetails")}async doSend(e){if(!l().serviceIdentificationReceived)try{this.send()}catch(t){l().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!,
@@ -22,11 +22,11 @@
22
22
  gitSha: $gitSha,
23
23
  )
24
24
  }
25
- `,t=this.getVariables({serviceIdentifier:l().serviceIdentifier,serviceVersion:l().serviceVersion,library:l().packageLibraryType,version:l().version,serviceAdditionalMetadata:l().serviceAdditionalMetadata,gitSha:l().gitSha||""});F(this.endpoint,this.operationName,e,t)}}function Xe(o){try{return JSON.stringify(o),!0}catch{return!1}}class Je extends R{constructor(){super();u(this,"serviceIdentifier",new T);this.setOperationName("CollectMetadata")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t,i,n,s){this.sendAppIdentifier(),this.send(t,i,n,s)}async send(t,i,n,s){if(!i&&!s)throw new Error('Must pass in either traits or traits_json to "add_or_update_traits"');let a=[];if(!s){const g=(function(c){const I={},d=[];if(c)for(const[C,p]of Object.entries(c))Xe(p)?I[C]=p:d.push(C);return{traitsJson:JSON.stringify(I),excludedFields:d}})(i);s=g.traitsJson,a=g.excludedFields}const r=this.getVariables({userId:t,traitsJson:s,excludedFields:a,override:n,library:l().packageLibraryType,version:l().version});F(this.endpoint,this.operationName,this.getQuery(),r)}getQuery(){return`
25
+ `,t=this.getVariables({serviceIdentifier:l().serviceIdentifier,serviceVersion:l().serviceVersion,library:l().packageLibraryType,version:l().version,serviceAdditionalMetadata:l().serviceAdditionalMetadata,gitSha:l().gitSha||""});F(this.endpoint,this.operationName,e,t)}}function Xe(o){try{return JSON.stringify(o),!0}catch{return!1}}class Ee extends w{constructor(){super();C(this,"serviceIdentifier",new X);this.setOperationName("CollectMetadata")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t,n,i,s){this.sendAppIdentifier(),this.send(t,n,i,s)}async send(t,n,i,s){if(!n&&!s)throw new Error('Must pass in either traits or traits_json to "add_or_update_traits"');let g=[];if(!s){const a=(function(c){const d={},I=[];if(c)for(const[h,p]of Object.entries(c))Xe(p)?d[h]=p:I.push(h);return{traitsJson:JSON.stringify(d),excludedFields:I}})(n);s=a.traitsJson,g=a.excludedFields}const r=this.getVariables({userId:t,traitsJson:s,excludedFields:g,override:i,library:l().packageLibraryType,version:l().version});F(this.endpoint,this.operationName,this.getQuery(),r)}getQuery(){return`
26
26
  mutation ${this.operationName}($apiKey: String!, $serviceUuid: String!, $sessionId: String!, $userId: String!, $traitsJson: String!, $excludedFields: [String!]!, $library: String!, $timestampMs: String!, $version: String!, $override: Boolean!) {
27
27
  ${this.queryName}(apiKey: $apiKey, serviceUuid: $serviceUuid, sessionId: $sessionId, userId: $userId, traitsJson: $traitsJson, excludedFields: $excludedFields, library: $library, timestampMs: $timestampMs, version: $version, override: $override)
28
28
  }
29
- `}}class ge{constructor(e){u(this,"metadataTransmitter");this.apiKey=e,this.metadataTransmitter=new Je}identify(e,t,i,n=!1){t||i?this.addOrUpdateMetadata(e,t,i,n):this.addOrUpdateMetadata(e,{},void 0,n)}addOrUpdateMetadata(e,t={},i,n=!1){if(!t&&!i)throw new Error('Must pass in either traits or traitsJson to "addOrUpdateMetadata"');l().sfDebug&&console.log(" [[DEBUG - addOrUpdateMetadata]] Starting operation"),l().sfDebug&&console.log(" addOrUpdateMetadata...SENDING DATA...",e,t,i),this.metadataTransmitter.doSend(e,t,n,i)}}class oe extends R{constructor(){super();u(this,"serviceIdentifier",new T)}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t){this.sendAppIdentifier(),this.send(t)}async send(t){try{const i=Array.isArray(t)?t:[t,"default"],n=this.getVariables({contents:i[0],level:i[1]});F(this.endpoint,this.operationName,this.getQuery(),n)}catch(i){l().sfDebug&&console.error("🚨 Error in send():",i)}}getQuery(){return`
29
+ `}}class Ce{constructor(e){C(this,"metadataTransmitter");this.apiKey=e,this.metadataTransmitter=new Ee}identify(e,t,n,i=!1){t||n?this.addOrUpdateMetadata(e,t,n,i):this.addOrUpdateMetadata(e,{},void 0,i)}addOrUpdateMetadata(e,t={},n,i=!1){if(!t&&!n)throw new Error('Must pass in either traits or traitsJson to "addOrUpdateMetadata"');l().sfDebug&&console.log(" [[DEBUG - addOrUpdateMetadata]] Starting operation"),l().sfDebug&&console.log(" addOrUpdateMetadata...SENDING DATA...",e,t,n),this.metadataTransmitter.doSend(e,t,i,n)}}class ae extends w{constructor(){super();C(this,"serviceIdentifier",new X)}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t){this.sendAppIdentifier(),this.send(t)}async send(t){try{const n=Array.isArray(t)?t:[t,"default"],i=this.getVariables({contents:n[0],level:n[1]});F(this.endpoint,this.operationName,this.getQuery(),i)}catch(n){l().sfDebug&&console.error("🚨 Error in send():",n)}}getQuery(){return`
30
30
  ${this.queryType} ${this.operationName}(
31
31
  $apiKey: String!,
32
32
  $serviceUuid: String!,
@@ -46,11 +46,11 @@
46
46
  parentSpanId: $parentSpanId
47
47
  )
48
48
  }
49
- `}}const B={};class X{constructor({file:e,line:t,function:i,code:n,locals:s={},offender:a=!1,column:r}){u(this,"file");u(this,"line");u(this,"function");u(this,"code");u(this,"locals");u(this,"offender");u(this,"column");this.file=e,this.line=t,this.function=i,this.code=n,this.locals=s,this.offender=a,this.column=r}toDict(){const e={file:this.file,line:this.line,function:this.function,code:this.code,locals:Object.fromEntries(Object.entries(this.locals).map(([t,i])=>[t,String(i)]))};return this.offender&&(e.offender=this.offender),this.column!==void 0&&(e.column=this.column),e}toJson(){return JSON.stringify(this.toDict())}}class x{static encode(e){return e instanceof X?e.toDict():Array.isArray(e)?e.map(t=>x.encode(t)):typeof e=="object"&&e!==null?JSON.stringify(e):e}static stringify(e){return JSON.stringify(x.encode(e),(t,i)=>i instanceof X?i.toDict():i)}}let N,K=0;function Te(o){l().sfDebug&&console.log("Initializing Exception Interceptor...");try{const r=(function(){if(N!==void 0)return N;const g=process.env||{},c=de(g.SF_IS_LOCAL);if(c!==void 0)return N=c;const I=(g.SF_ENV||g.NODE_ENV||"").toLowerCase();if(["local","dev","development"].includes(I))return N=!0;if(["KUBERNETES_SERVICE_HOST","AWS_EXECUTION_ENV","ECS_CONTAINER_METADATA_URI","ECS_CONTAINER_METADATA_URI_V4","GAE_ENV","K_SERVICE","GOOGLE_CLOUD_PROJECT","WEBSITE_INSTANCE_ID","VERCEL","NETLIFY","DYNO","RENDER","FLY_APP_NAME","RAILWAY_STATIC_URL","CF_PAGES","CLOUDFLARE"].some(C=>!!g[C]))return N=!1;const d=(B.hostname?.()||g.HOSTNAME||"").toLowerCase();return d==="localhost"||d.endsWith(".local")||d.includes("local")?N=!0:N=!1})();o?.setSupplementalFields?.({isFromLocalService:r}),(async function(g){if(Ie)return;Ie=!0;const c=process.env||{};if(de(c.SF_IS_LOCAL)===void 0)try{await(async function(I){const d=M("http://169.254.169.254/latest/meta-data/",{},I),C=M("http://metadata.google.internal/computeMetadata/v1/instance/",{"Metadata-Flavor":"Google"},I),p=M("http://169.254.169.254/metadata/instance?api-version=2021-02-01",{Metadata:"true"},I);return(await Promise.allSettled([d,C,p])).some(h=>h.status==="fulfilled"&&(h.value==="ok"||h.value==="http_error"))})(150)&&N&&(N=!1,g?.setSupplementalFields?.({isFromLocalService:!1}))}catch{}})(o).catch(()=>{})}catch{}const e=new Ve.Worker(new URL("data:application/javascript;base64,aW1wb3J0IHsgU2Vzc2lvbiB9IGZyb20gImluc3BlY3Rvci9wcm9taXNlcyI7CmltcG9ydCB7IHBhcmVudFBvcnQsIHdvcmtlckRhdGEgfSBmcm9tICJ3b3JrZXJfdGhyZWFkcyI7CgpnbG9iYWwuc2ZEZWJ1ZyA9IHVuZGVmaW5lZDsKZ2xvYmFsLnN0YWNrRGVw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vbnN0IHsgc2NyaXB0U291cmNlIH0gPSBhd2FpdCBzZXNzaW9uLnBvc3QoCiAgICAgICAgICAgICAgIkRlYnVnZ2VyLmdldFNjcmlwdFNvdXJjZSIsCiAgICAgICAgICAgICAgewogICAgICAgICAgICAgICAgc2NyaXB0SWQsCiAgICAgICAgICAgICAgfSwKICAgICAgICAgICAgKTsKICAgICAgICAgICAgY29uc3Qgc291cmNlTGluZXMgPSBzY3JpcHRTb3VyY2Uuc3BsaXQoIlxuIik7CiAgICAgICAgICAgIGNvZGUgPSBzb3VyY2VMaW5lc1tsb2NhdGlvbi5saW5lTnVtYmVyXSB8fCAiPG5vdCBjYXB0dXJlZD4iOwogICAgICAgICAgfSBjYXRjaCAoZXJyKSB7CiAgICAgICAgICAgIGlmIChnbG9iYWwuc2ZEZWJ1ZykgewogICAgICAgICAgICAgIGNvbnNvbGUuZXJyb3IoIltXb3JrZXJdIEZhaWxlZCB0byBmZXRjaCBzY3JpcHQgc291cmNlOiIsIGVycik7CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KICAgICAgICB9CgogICAgICAgIC8vIEZldGNoIGxvY2FsIHZhcmlhYmxlcyBpZiB0aGVyZSdzIGFuIG9iamVjdElkCiAgICAgICAgY29uc3QgbG9jYWxzID0gbG9jYWxTY29wZT8ub2JqZWN0Py5vYmplY3RJZAogICAgICAgICAgPyBhd2FpdCBmZXRjaExvY2FsVmFyaWFibGVzKHNlc3Npb24sIGxvY2FsU2NvcGUub2JqZWN0Lm9iamVjdElkKQogICAgICAgICAgOiB7fTsKCiAgICAgICAgcmV0dXJuIHsKICAgICAgICAgIGZ1bmN0aW9uOiBmdW5jdGlvbk5hbWUgfHwgIjxhbm9ueW1vdXM+IiwKICAgICAgICAgIGxvY2FscywKICAgICAgICAgIGZpbGUsCiAgICAgICAgICBsaW5lOiBsb2NhdGlvbj8ubGluZU51bWJlciB8fCAwLAogICAgICAgICAgY29kZSwKICAgICAgICB9OwogICAgICB9IGNhdGNoIChlcnJvc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gY2FwdHVyaW5nIGZyb20KICAgICAgICBjb25zdCBpc0Zyb21BbGxvd2VkTm9kZU1vZHVsZSA9IG5vZGVNb2R1bGVzTGlzdC5zb21lKChtb2R1bGVOYW1lKSA9PgogICAgICAgICAgZmlyc3RGcmFtZUxpbmUuaW5jbHVkZXMoYCR7bW9kdWxlTmFtZX1gKSwKICAgICAgICApOwoKICAgICAgICBpZiAoIWlzRnJvbUFsbG93ZWROb2RlTW9kdWxlKSB7CiAgICAgICAgICAvLyBOb3QgZnJvbSBhbiBhbGxvd2VkIG5vZGUgbW9kdWxlID0+IHJldHVybiBlYXJseQogICAgICAgICAgaWYgKGdsb2JhbC5zZkRlYnVnKSB7CiAgICAgICAgICAgIGNvbnNvbGUubG9nKAogICAgICAgICAgICAgICJbV29ya2VyXSBFcnJvciBhcHBlYXJzIHRvIGJlIHRyaWdnZXJlZCBmcm9tIG5vbi1hcHBsaWNhdGlvbiBzb3VyY2VzOyBpZ25vcmluZy4iLAogICAgICAgICAgICApOwogICAgICAgICAgfQogICAgICAgICAgcmV0dXJuOwogICAgICAgIH0KICAgICAgICAvLyBPdGhlcndpc2UsIGl0J3MgZnJvbSBhbiBhbGxvd2VkIG5vZGUgbW9kdWxlLCBzbyBjb250aW51ZQogICAgICB9IGVsc2UgewogICAgICAgIC8vIElmIHRoZSBsaXN0IGlzIGVtcHR5LCBwcmVzZXJ2ZSBleGlzdGluZyBiZWhhdmlvciBhbmQgaWdub3JlIG5vbi1hcHBsaWNhdGlvbiBlcnJvcnMKICAgICAgICBpZiAoZ2xvYmFsLnNmRGVidWcpIHsKICAgICAgICAgIGNvbnNvbGUubG9nKAogICAgICAgICAgICAiW1dvcmtlcl0gRXJyb3IgYXBwZWFycyB0byBiZSB0cmlnZ2VyZWQgZnJvbSBub24tYXBwbGljYXRpb24gc291cmNlczsgaWdub3JpbmcuIiwKICAgICAgICAgICk7CiAgICAgICAgfQogICAgICAgIHJldHVybjsKICAgICAgfQogICAgfQoKICAgIC8vIElmI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pYWJsZXM6IiwgZXJyKTsKICAgIH0KICAgIHJldHVybiB7fTsKICB9Cn0KCnN0YXJ0RGVidWdnZXIoKS5jYXRjaCgoZXJyb3IpID0+IHsKICBpZiAoZ2xvYmFsLnNmRGVidWcpIHsKICAgIGNvbnNvbGUuZXJyb3IoIltXb3JrZXJdIEZhaWxlZCB0byBzdGFydCBkZWJ1Z2dlcjoiLCBlcnJvcik7CiAgfQp9KTsKCi8vIEtlZXAgdGhlIHdvcmtlciBhbGl2ZQpzZXRJbnRlcnZhbCgoKSA9PiB7fSwgMTAwMDApOwo="),{workerData:{captureAllExceptions:!0}});let t=null;const i=new WeakMap;e.on("message",r=>{if(typeof r=="string"&&l().sfDebug&&console.log(`[Worker] ${r}`),r.readyToGetParameters&&e.postMessage({sfDebug:l().sfDebug,stackDepthLocals:l().stackDepthLocals,nodeModulesToCollectLocalVariablesOn:l().nodeModulesToCollectLocalVariablesOn}),r.type==="exception"){const{frames:g}=r,c=t;if(!c)return;const I=i.get(c),d=(function(p){return p?p.split(`
50
- `).slice(1).map(h=>{const A=/at (.+?) \((.+):(\d+):(\d+)\)/.exec(h)||/at (.+):(\d+):(\d+)/.exec(h);if(A){const[,m,Z,f,b]=A;return new X({function:m||"<anonymous>",locals:{},file:Z||"<unknown>",line:parseInt(f,10)||0,code:"<not captured>",column:parseInt(b)||0})}return new X({function:"<unknown>",locals:{},file:"<unknown>",line:0,code:"<not captured>",column:0})}):[]})(c.stack),C=(function(p,h){const A=[];let m=-1,Z=-1;for(let f=0;f<p.length;f++){const b=Ee(p[f].file);if(Z=f,b!=="<unknown>"){for(let y=0;y<h.length;y++){const $=h[y];if(Be($,b)||typeof $.file=="string"&&$.file.includes(b)){m=y,K=0,l().sfDebug&&console.log(`✅ Matched Frame Found: ${b} @ Debugger Frame ${y}`);break}}if(m!==-1)break}}if(m===-1)return K===10?(K=0,p):(++K,l().sfDebug&&console.log(`"❌ No matching frame found. Checking once again, Attempt N ${K}"`),[]);l().sfDebug&&console.log(`🔄 Merging from matched index ${m} onward...`);for(let f=0;f<h.length;f++){const b=p[Z+f],y=h[m+f];A.push(new X({function:y?.function||b?.function||"<anonymous>",locals:y?.locals||b?.locals||{},file:b?.file||y?.file||"<unknown>",line:y?.line||b?.line||0,code:y?.code||b?.code||"<not captured>"}))}return A})(d,g||[]);if(C.length!==0){t=null;const p=l().stackDepthCodeTraceDepth,h=p===-1?C:C.slice(0,p+1),A=Math.min(h.length,d.length);for(let b=0;b<A;b++)(async()=>{const y=_e(h[b].file,d[b].line,d[b].column);y&&(y.content!=null&&(h[b].code=y.content),y.file!=null&&(h[b].file=y.file))})();o.setOperationName("CollectExceptions");const m=c.message?`${c.name}: ${c.message}`:c.name;l().sfDebug&&console.log("error message is : ",m);const Z=G.getInstance(),f=i.get(c);f?(Z.setTraceIdFor(f,f),Z.runWithSession(f,()=>{Z.setTraceId(f),o.doSend(m,h)})):o.doSend(m,h),I?G.getInstance().runWithSession(I,()=>{o.doSend(m,h)}):o.doSend(m,h)}}}),e.on("error",r=>{console.error("[Worker Error]",r)}),e.on("exit",r=>{console.error(`[Worker] Exited with code ${r}`)}),e.unref();const n=Error,s=new Set;function a(...r){const g=Reflect.construct(n,r);Reflect.setPrototypeOf(g,a.prototype);try{const I=G.getInstance().getTraceId();i.set(g,I)}catch{}n.captureStackTrace&&n.captureStackTrace(g,a);const c=`${g.message}:${g.stack?.split(`
51
- `)[1]?.trim()}`;if(!s.has(c)){s.add(c),t=g;const I=G.getInstance().getTraceId();i.set(g,I),e.postMessage({type:"processException",error:g.message})}return g}a.prototype=Object.create(n.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),Object.setPrototypeOf(a,n),globalThis.Error=a}function le(o){return o=(o=(o=o.replace(/^webpack:\/\/[^\/]+\/\.?\//,"")).replace(/^.*\/pages\//,"pages/")).replace(/\.(js|ts)$/,"")}function _e(o,e,t){const i=(function(s){s.startsWith("at ")&&(s=s.slice(3).trim());const a=s.match(/^(.*?)(:\d+)+(\.map)?$/);return a?a[1]:s})(o);if(!i||i==="<unknown>")return null;const n=i+".map";try{const s=ie.readFileSync(n,"utf-8");if(s){const a=JSON.parse(s);let r=new fe.sourceMapExports.SourceMapConsumer(a).originalPositionFor({line:e,column:t});if(i&&r.source){const g=le(i),c=a.sources.findIndex(I=>le(I)===g);if(c===-1)l().sfDebug&&console.log(`Source file "${i}" not found in the source map.`);else{const I=a.sourcesContent[c],d=a.names.join(",");if(I)return{content:I.split(`
49
+ `}}const N={};class T{constructor({file:e,line:t,function:n,code:i,locals:s={},offender:g=!1,column:r}){C(this,"file");C(this,"line");C(this,"function");C(this,"code");C(this,"locals");C(this,"offender");C(this,"column");this.file=e,this.line=t,this.function=n,this.code=i,this.locals=s,this.offender=g,this.column=r}toDict(){const e={file:this.file,line:this.line,function:this.function,code:this.code,locals:Object.fromEntries(Object.entries(this.locals).map(([t,n])=>[t,String(n)]))};return this.offender&&(e.offender=this.offender),this.column!==void 0&&(e.column=this.column),e}toJson(){return JSON.stringify(this.toDict())}}class z{static encode(e){return e instanceof T?e.toDict():Array.isArray(e)?e.map(t=>z.encode(t)):typeof e=="object"&&e!==null?JSON.stringify(e):e}static stringify(e){return JSON.stringify(z.encode(e),(t,n)=>n instanceof T?n.toDict():n)}}let B,U=0;function _e(o){l().sfDebug&&console.log("Initializing Exception Interceptor...");try{const r=(function(){if(B!==void 0)return B;const a=process.env||{},c=Ae(a.SF_IS_LOCAL);if(c!==void 0)return B=c;const d=(a.SF_ENV||a.NODE_ENV||"").toLowerCase();if(["local","dev","development"].includes(d))return B=!0;if(["KUBERNETES_SERVICE_HOST","AWS_EXECUTION_ENV","ECS_CONTAINER_METADATA_URI","ECS_CONTAINER_METADATA_URI_V4","GAE_ENV","K_SERVICE","GOOGLE_CLOUD_PROJECT","WEBSITE_INSTANCE_ID","VERCEL","NETLIFY","DYNO","RENDER","FLY_APP_NAME","RAILWAY_STATIC_URL","CF_PAGES","CLOUDFLARE"].some(h=>!!a[h]))return B=!1;const I=(N.hostname?.()||a.HOSTNAME||"").toLowerCase();return I==="localhost"||I.endsWith(".local")||I.includes("local")?B=!0:B=!1})();o?.setSupplementalFields?.({isFromLocalService:r}),(async function(a){if(he)return;he=!0;const c=process.env||{};if(Ae(c.SF_IS_LOCAL)===void 0)try{await(async function(d){const I=j("http://169.254.169.254/latest/meta-data/",{},d),h=j("http://metadata.google.internal/computeMetadata/v1/instance/",{"Metadata-Flavor":"Google"},d),p=j("http://169.254.169.254/metadata/instance?api-version=2021-02-01",{Metadata:"true"},d);return(await Promise.allSettled([I,h,p])).some(u=>u.status==="fulfilled"&&(u.value==="ok"||u.value==="http_error"))})(150)&&B&&(B=!1,a?.setSupplementalFields?.({isFromLocalService:!1}))}catch{}})(o).catch(()=>{})}catch{}const e=new He.Worker(new URL("data:application/javascript;base64,aW1wb3J0IHsgU2Vzc2lvbiB9IGZyb20gImluc3BlY3Rvci9wcm9taXNlcyI7CmltcG9ydCB7IHBhcmVudFBvcnQsIHdvcmtlckRhdGEgfSBmcm9tICJ3b3JrZXJfdGhyZWFkcyI7CgpnbG9iYWwuc2ZEZWJ1ZyA9IHVuZGVmaW5lZDsKZ2xvYmFsLnN0YWNrRGVwdGhMb2NhbHMgPSB1bmRlZmluZWQ7Cmdsb2JhbC5ub2RlTW9kdWxlc1RvQ29sbGVjdExvY2FsVmFyaWFibGVzT24gPSB1bmRlZmluZWQ7CgovKioKICogUHJvY2Vzc2VzIGNhbGwgZnJhbWVzIGZyb20gYW4gZXhjZXB0aW9uIGFuZCBwb3N0cyB0aGVtIHZpYSB0aGUgV29ya2Vy4oCZcyBwYXJlbnRQb3J0LgogKgogKiBAcGFyYW0gc2Vzc2lvbiAtIFRoZSBEZXZUb29scyBzZXNzaW9uIG9yIHNpbWlsYXIgb2JqZWN0IHlvdSB1c2UgdG8gcXVlcnkgZm9yIHNjcmlwdCBzb3VyY2VzLgogKiBAcGFyYW0gY2FsbEZyYW1lcyAtIEFuIGFycmF5IG9mIGNhbGwgZnJhbWU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ZEZWJ1ZykgewogICAgICAgICAgICAgIGNvbnNvbGUuZXJyb3IoIltXb3JrZXJdIEZhaWxlZCB0byBmZXRjaCBzY3JpcHQgc291cmNlOiIsIGVycik7CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KICAgICAgICB9CgogICAgICAgIC8vIEZldGNoIGxvY2FsIHZhcmlhYmxlcyBpZiB0aGVyZSdzIGFuIG9iamVjdElkCiAgICAgICAgY29uc3QgbG9jYWxzID0gbG9jYWxTY29wZT8ub2JqZWN0Py5vYmplY3RJZAogICAgICAgICAgPyBhd2FpdCBmZXRjaExvY2FsVmFyaWFibGVzKHNlc3Npb24sIGxvY2FsU2NvcGUub2JqZWN0Lm9iamVjdElkKQogICAgICAgICAgOiB7fTsKCiAgICAgICAgcmV0dXJuIHsKICAgICAgICAgIGZ1bmN0aW9uOiBmdW5jdGlvbk5hbWUgfHwgIjxhbm9ueW1vdXM+IiwKICAgICAgICAgIGxvY2FscywKICAgICAgICAgIGZpbGUsCiAgICAgICAgICBsaW5lOiBsb2NhdGlvbj8ubGluZU51bWJlciB8fCAwLAogICAgICAgICAgY29kZSwKICAgICAgICB9OwogICAgICB9IGNhdGNoIChlcnJvcikgewogICAgICAgIGlmIChnbG9iYWwuc2ZEZWJ1ZykgewogICAgICAgICAgY29uc29sZS5lcnJvcigiW1dvcmtlcl0gRXJyb3IgcHJvY2Vzc2luZyBjYWxsIGZyYW1lOiIsIGVycm9yKTsKICAgICAgICB9CiAgICAgICAgcmV0dXJuIHsKICAgICAgICAgIGZ1bmN0aW9uOiAiPGVycm9yPiIsCiAgICAgICAgICBsb2NhbHM6IHt9LAogICAgICAgICAgZmlsZTogIjx1bmtub3duPiIsCiAgICAgICAgICBsaW5lOiAwLAogICAgICAgICAgY29kZTogIjxub3QgY2FwdHVyZWQ+IiwKICAgICAgICB9OwogICAgICB9CiAgICB9KSwKICApOwogIC8vIFBvc3QgZXhjZXB0aW9uIGRhdGEKICBwYXJlbnRQb3J0Py5wb3N0TWVz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ICAgICAgICBhd2FpdCB1bnJvbGxBcnJheShzZXNzaW9uLCBpZCwgcHJvcC5uYW1lLCB2YXJpYWJsZXMpOwogICAgICAgIH0gZWxzZSBpZiAoCiAgICAgICAgICBwcm9wPy52YWx1ZT8ub2JqZWN0SWQgJiYKICAgICAgICAgIHByb3A/LnZhbHVlPy5jbGFzc05hbWUgPT09ICJPYmplY3QiCiAgICAgICAgKSB7CiAgICAgICAgICBjb25zdCBpZCA9IHByb3AudmFsdWUub2JqZWN0SWQ7CiAgICAgICAgICBhd2FpdCB1bnJvbGxPYmplY3Qoc2Vzc2lvbiwgaWQsIHByb3AubmFtZSwgdmFyaWFibGVzKTsKICAgICAgICB9IGVsc2UgaWYgKHByb3A/LnZhbHVlKSB7CiAgICAgICAgICB1bnJvbGxPdGhlcihwcm9wLCB2YXJpYWJsZXMpOwogICAgICAgIH0KICAgICAgfQogICAgICByZXR1cm4gdmFyaWFibGVzOwogICAgfQogIH0gY2F0Y2ggKGVycikgewogICAgaWYgKGdsb2JhbC5zZkRlYnVnKSB7CiAgICAgIGNvbnNvbGUuZXJyb3IoIltXb3JrZXJdIEZhaWxlZCB0byBmZXRjaCBsb2NhbCB2YXJpYWJsZXM6IiwgZXJyKTsKICAgIH0KICAgIHJldHVybiB7fTsKICB9Cn0KCnN0YXJ0RGVidWdnZXIoKS5jYXRjaCgoZXJyb3IpID0+IHsKICBpZiAoZ2xvYmFsLnNmRGVidWcpIHsKICAgIGNvbnNvbGUuZXJyb3IoIltXb3JrZXJdIEZhaWxlZCB0byBzdGFydCBkZWJ1Z2dlcjoiLCBlcnJvcik7CiAgfQp9KTsKCi8vIEtlZXAgdGhlIHdvcmtlciBhbGl2ZQpzZXRJbnRlcnZhbCgoKSA9PiB7fSwgMTAwMDApOwo="),{workerData:{captureAllExceptions:!0}});let t=null;const n=new WeakMap;e.on("message",r=>{if(typeof r=="string"&&l().sfDebug&&console.log(`[Worker] ${r}`),r.readyToGetParameters&&e.postMessage({sfDebug:l().sfDebug,stackDepthLocals:l().stackDepthLocals,nodeModulesToCollectLocalVariablesOn:l().nodeModulesToCollectLocalVariablesOn}),r.type==="exception"){const{frames:a}=r,c=t;if(!c)return;const d=n.get(c),I=(function(p){return p?p.split(`
50
+ `).slice(1).map(u=>{const A=/at (.+?) \((.+):(\d+):(\d+)\)/.exec(u)||/at (.+):(\d+):(\d+)/.exec(u);if(A){const[,m,y,b,f]=A;return new T({function:m||"<anonymous>",locals:{},file:y||"<unknown>",line:parseInt(b,10)||0,code:"<not captured>",column:parseInt(f)||0})}return new T({function:"<unknown>",locals:{},file:"<unknown>",line:0,code:"<not captured>",column:0})}):[]})(c.stack),h=(function(p,u){const A=[];let m=-1,y=-1;for(let b=0;b<p.length;b++){const f=$e(p[b].file);if(y=b,f!=="<unknown>"){for(let S=0;S<u.length;S++){const k=u[S];if(Be(k,f)||typeof k.file=="string"&&k.file.includes(f)){m=S,U=0,l().sfDebug&&console.log(`✅ Matched Frame Found: ${f} @ Debugger Frame ${S}`);break}}if(m!==-1)break}}if(m===-1)return U===10?(U=0,p):(++U,l().sfDebug&&console.log(`"❌ No matching frame found. Checking once again, Attempt N ${U}"`),[]);l().sfDebug&&console.log(`🔄 Merging from matched index ${m} onward...`);for(let b=0;b<u.length;b++){const f=p[y+b],S=u[m+b];A.push(new T({function:S?.function||f?.function||"<anonymous>",locals:S?.locals||f?.locals||{},file:f?.file||S?.file||"<unknown>",line:S?.line||f?.line||0,code:S?.code||f?.code||"<not captured>"}))}return A})(I,a||[]);if(h.length!==0){t=null;const p=l().stackDepthCodeTraceDepth,u=p===-1?h:h.slice(0,p+1),A=Math.min(u.length,I.length);for(let f=0;f<A;f++)(async()=>{const S=De(u[f].file,I[f].line,I[f].column);S&&(S.content!=null&&(u[f].code=S.content),S.file!=null&&(u[f].file=S.file))})();o.setOperationName("CollectExceptions");const m=c.message?`${c.name}: ${c.message}`:c.name;l().sfDebug&&console.log("error message is : ",m);const y=v.getInstance(),b=n.get(c);b?(y.setTraceIdFor(b,b),y.runWithSession(b,()=>{y.setTraceId(b),o.doSend(m,u)})):o.doSend(m,u),d?v.getInstance().runWithSession(d,()=>{o.doSend(m,u)}):o.doSend(m,u)}}}),e.on("error",r=>{console.error("[Worker Error]",r)}),e.on("exit",r=>{console.error(`[Worker] Exited with code ${r}`)}),e.unref();const i=Error,s=new Set;function g(...r){const a=Reflect.construct(i,r);Reflect.setPrototypeOf(a,g.prototype);try{const d=v.getInstance().getTraceId();n.set(a,d)}catch{}i.captureStackTrace&&i.captureStackTrace(a,g);const c=`${a.message}:${a.stack?.split(`
51
+ `)[1]?.trim()}`;if(!s.has(c)){s.add(c),t=a;const d=v.getInstance().getTraceId();n.set(a,d),e.postMessage({type:"processException",error:a.message})}return a}g.prototype=Object.create(i.prototype,{constructor:{value:g,enumerable:!1,writable:!0,configurable:!0}}),Object.setPrototypeOf(g,i),globalThis.Error=g}function pe(o){return o=(o=(o=o.replace(/^webpack:\/\/[^\/]+\/\.?\//,"")).replace(/^.*\/pages\//,"pages/")).replace(/\.(js|ts)$/,"")}function De(o,e,t){const n=(function(s){s.startsWith("at ")&&(s=s.slice(3).trim());const g=s.match(/^(.*?)(:\d+)+(\.map)?$/);return g?g[1]:s})(o);if(!n||n==="<unknown>")return null;const i=n+".map";try{const s=re.readFileSync(i,"utf-8");if(s){const g=JSON.parse(s);let r=new Ze.sourceMapExports.SourceMapConsumer(g).originalPositionFor({line:e,column:t});if(n&&r.source){const a=pe(n),c=g.sources.findIndex(d=>pe(d)===a);if(c===-1)l().sfDebug&&console.log(`Source file "${n}" not found in the source map.`);else{const d=g.sourcesContent[c],I=g.names.join(",");if(d)return{content:d.split(`
52
52
  `).slice(r.line-1,r.line+20).join(`
53
- `),name:d,file:r.source};l().sfDebug&&console.log(`No source content available for file "${i}".`)}}return{content:a.sourcesContent[0],name:a.names[0],file:a.file}}}catch(s){l().sfDebug&&console.log(`Cant read/parse "${n}: Error - ".`,s)}return null}function Ee(o){return o?.split("/").pop()||"<unknown>"}function Be(o,e){if(!o||typeof o!="object")return!1;for(const t of Object.values(o))if(typeof t=="string"&&t.includes(e)||typeof t=="object"&&Be(t,e))return!0;return!1}let Ie=!1;function de(o){if(!o)return;const e=o.toLowerCase().trim();return!!["1","true","yes","on"].includes(e)||!["0","false","no","off"].includes(e)&&void 0}function M(o,e,t){return new Promise(i=>{try{const n=new URL(o),s=(n.protocol,B).request({method:"GET",hostname:n.hostname,port:n.port||(n.protocol==="https:"?443:80),path:n.pathname+(n.search||""),headers:e},a=>{a.resume(),a.statusCode&&a.statusCode>=200&&a.statusCode<400?i("ok"):i("http_error")});s.on("error",()=>i("error")),s.setTimeout(t,()=>{s.destroy(),i("timeout")}),s.end()}catch{i("error")}})}class De extends R{constructor(){super();u(this,"serviceIdentifier",new T);u(this,"supplementalFields",{});this.setOperationName("CollectExceptions")}setSupplementalFields(t){this.supplementalFields={...this.supplementalFields,...t}}normalizedSupplementalForGraphQL(){const{isFromLocalService:t}=this.supplementalFields,i={};return t!==void 0&&(i.isFromLocalService=t),i}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t,i){this.sendAppIdentifier(),this.send(t,i)}async send(t,i){l().sfDebug&&console.log(" SENDING EXCEPTION...");const n=JSON.stringify(x.encode(i)),s=this.normalizedSupplementalForGraphQL(),a=this.getVariables({exceptionMessage:t,traceJson:n,reentrancyGuardPreactive:!1,library:l().packageLibraryType,version:l().version,...s});F(this.endpoint,this.operationName,this.getQuery(),a)}getQuery(){return`
53
+ `),name:I,file:r.source};l().sfDebug&&console.log(`No source content available for file "${n}".`)}}return{content:g.sourcesContent[0],name:g.names[0],file:g.file}}}catch(s){l().sfDebug&&console.log(`Cant read/parse "${i}: Error - ".`,s)}return null}function $e(o){return o?.split("/").pop()||"<unknown>"}function Be(o,e){if(!o||typeof o!="object")return!1;for(const t of Object.values(o))if(typeof t=="string"&&t.includes(e)||typeof t=="object"&&Be(t,e))return!0;return!1}let he=!1;function Ae(o){if(!o)return;const e=o.toLowerCase().trim();return!!["1","true","yes","on"].includes(e)||!["0","false","no","off"].includes(e)&&void 0}function j(o,e,t){return new Promise(n=>{try{const i=new URL(o),s=(i.protocol,N).request({method:"GET",hostname:i.hostname,port:i.port||(i.protocol==="https:"?443:80),path:i.pathname+(i.search||""),headers:e},g=>{g.resume(),g.statusCode&&g.statusCode>=200&&g.statusCode<400?n("ok"):n("http_error")});s.on("error",()=>n("error")),s.setTimeout(t,()=>{s.destroy(),n("timeout")}),s.end()}catch{n("error")}})}class Le extends w{constructor(){super();C(this,"serviceIdentifier",new X);C(this,"supplementalFields",{});this.setOperationName("CollectExceptions")}setSupplementalFields(t){this.supplementalFields={...this.supplementalFields,...t}}normalizedSupplementalForGraphQL(){const{isFromLocalService:t}=this.supplementalFields,n={};return t!==void 0&&(n.isFromLocalService=t),n}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t,n){this.sendAppIdentifier(),this.send(t,n)}async send(t,n){l().sfDebug&&console.log(" SENDING EXCEPTION...");const i=JSON.stringify(z.encode(n)),s=this.normalizedSupplementalForGraphQL(),g=this.getVariables({exceptionMessage:t,traceJson:i,reentrancyGuardPreactive:!1,library:l().packageLibraryType,version:l().version,...s});F(this.endpoint,this.operationName,this.getQuery(),g)}getQuery(){return`
54
54
  mutation ${this.operationName}(
55
55
  $apiKey: String!,
56
56
  $serviceUuid: String!,
@@ -78,7 +78,7 @@
78
78
  parentSpanId: $parentSpanId
79
79
  )
80
80
  }
81
- `}}const ue="getting request source code";var z=(o=>(o.UNKNOWN="unknown",o.ANONYMOUS="anonymous",o.NOT_CAPTURED="not captured",o))(z||{});const j="http:",Q="https:";let Ce=!1;function Le(){const o=l().sfDebug;if(Ce)return void(o&&console.log("[patchNodeHttpInbound] Already installed, skipping."));let e;Ce=!0;try{e=require("node:http"),o&&console.log("[patchNodeHttpInbound] node:http required successfully.")}catch(n){return void console.error("Failed to require node:http:",n)}if(!e?.Server?.prototype)return void(o&&console.log("[patchNodeHttpInbound] http.Server.prototype not found."));const t=e.Server.prototype,i=t.emit;i&&!t.__sf_inbound_patched__?(Object.defineProperty(t,"__sf_inbound_patched__",{value:!0,enumerable:!1,configurable:!1,writable:!1}),o&&console.log("[patchNodeHttpInbound] Patching http.Server.prototype.emit."),t.emit=function(n,...s){if(n!=="request")return o&&console.log(`[patchNodeHttpInbound] Passing through event: ${n}`),i.call(this,n,...s);const a=s[0],r=s[1],g=(function(C){const p={};if(!C)return p;for(const[h,A]of Object.entries(C))A!=null&&(Array.isArray(A)?p[h.toLowerCase()]=A.join(", "):p[h.toLowerCase()]=String(A));return p})(a?.headers),c=g["x-sf3-rid"];o&&(console.log("[patchNodeHttpInbound] Intercepted request event."),console.log("[patchNodeHttpInbound] Inbound headers:",g),console.log("[patchNodeHttpInbound] Trace header:",c));const I=G.getInstance();I.setTraceId(c);const d=I.getTraceId();return o&&console.log("[patchNodeHttpInbound] Context traceId set:",d),I.runWith({inboundHeaders:g,...c?{traceId:c}:{}},()=>{c&&I.setTraceId(c),o&&console.log("[patchNodeHttpInbound] Running request handler in context.");const C=()=>{o&&console.log("[patchNodeHttpInbound] Response finished/closed for traceId:",I.getTraceId())};return r.on("finish",C),r.on("close",C),i.call(this,n,a,r)})}):o&&console.log("[patchNodeHttpInbound] Already patched, skipping.")}class ze extends oe{constructor(){super(),this.setOperationName("DomainsToNotPassHeaderTo")}async doSend(e){this.sendAppIdentifier(),this.send(e)}async send(e){const t=`
81
+ `}}const me="getting request source code";var L=(o=>(o.UNKNOWN="unknown",o.ANONYMOUS="anonymous",o.NOT_CAPTURED="not captured",o))(L||{});const Q="http:",q="https:";function ce(){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)}}function ze(){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}}function ie(o){try{const e=o.split("-");return e.length!==9?(console.error(`[FuncSpan] Invalid header format: expected 9 parts, got ${e.length}`),null):{capture_arguments:e[0]==="1",capture_return_value:e[1]==="1",arg_limit_mb:parseInt(e[2],10),return_limit_mb:parseInt(e[3],10),autocapture_all_child_functions:e[4]==="1",sample_rate:parseFloat(e[5]),enable_sampling:e[6]==="1",capture_sf_veritas:e[7]==="1",parse_json_strings:e[8]==="1"}}catch(e){return console.error(`[FuncSpan] Failed to parse header override "${o}":`,e),null}}function H(o,e){if(!o)return e;const t=o.toLowerCase();return t==="true"||t==="1"||t==="yes"}const ge=new se.AsyncLocalStorage;function We(o){ge.enterWith(o)}function oe(){return ge.getStore()}function Fe(){ge.enterWith(void 0)}function _(...o){const e={};for(const t of o)for(const n in t)t[n]!==void 0&&(e[n]=t[n]);return e}function ee(o,e){try{const t=JSON.stringify(o).length/1048576;return t<=e?o:{_truncated:!0,_originalSizeMB:t.toFixed(2),_limitMB:e,_preview:JSON.stringify(o).substring(0,500)+"..."}}catch{return{_error:"Failed to serialize data",_type:typeof o}}}let be=!1;function xe(){const o=l().sfDebug;if(be)return void(o&&console.log("[patchNodeHttpInbound] Already installed, skipping."));let e;be=!0;try{e=require("node:http"),o&&console.log("[patchNodeHttpInbound] node:http required successfully.")}catch(i){return void console.error("Failed to require node:http:",i)}if(!e?.Server?.prototype)return void(o&&console.log("[patchNodeHttpInbound] http.Server.prototype not found."));const t=e.Server.prototype,n=t.emit;n&&!t.__sf_inbound_patched__?(Object.defineProperty(t,"__sf_inbound_patched__",{value:!0,enumerable:!1,configurable:!1,writable:!1}),o&&console.log("[patchNodeHttpInbound] Patching http.Server.prototype.emit."),t.emit=function(i,...s){if(i!=="request")return o&&console.log(`[patchNodeHttpInbound] Passing through event: ${i}`),n.call(this,i,...s);const g=s[0],r=s[1],a=(function(p){const u={};if(!p)return u;for(const[A,m]of Object.entries(p))m!=null&&(Array.isArray(m)?u[A.toLowerCase()]=m.join(", "):u[A.toLowerCase()]=String(m));return u})(g?.headers),c=a["x-sf3-rid"],d=a["x-sf3-functionspancaptureoverride"];o&&(console.log("[patchNodeHttpInbound] Intercepted request event."),console.log("[patchNodeHttpInbound] Inbound headers:",a),console.log("[patchNodeHttpInbound] Trace header:",c),console.log("[patchNodeHttpInbound] FuncSpan override header:",d));const I=v.getInstance();I.setTraceId(c);const h=I.getTraceId();return o&&console.log("[patchNodeHttpInbound] Context traceId set:",h),I.runWith({inboundHeaders:a,...c?{traceId:c}:{}},()=>{c&&I.setTraceId(c),d&&(We(d),o&&console.log("[patchNodeHttpInbound] FuncSpan override set:",d)),o&&console.log("[patchNodeHttpInbound] Running request handler in context.");const p=()=>{o&&console.log("[patchNodeHttpInbound] Response finished/closed for traceId:",I.getTraceId()),d&&(Fe(),o&&console.log("[patchNodeHttpInbound] FuncSpan override cleared"))};return r.on("finish",p),r.on("close",p),n.call(this,i,g,r)})}):o&&console.log("[patchNodeHttpInbound] Already patched, skipping.")}class ke extends ae{constructor(){super(),this.setOperationName("DomainsToNotPassHeaderTo")}async doSend(e){this.sendAppIdentifier(),this.send(e)}async send(e){const t=`
82
82
  ${this.queryType} ${this.operationName}(
83
83
  $apiKey: String!,
84
84
  $serviceUuid: String!,
@@ -90,7 +90,7 @@
90
90
  domains: $domains
91
91
  )
92
92
  }
93
- `,i={apiKey:this.apiKey,serviceUuid:this.serviceUUID,domains:e};F(this.endpoint,this.operationName,t,i)}}class xe extends R{constructor(){super();u(this,"serviceIdentifier",new T);this.setOperationName("CollectNetworkHops")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t){this.sendAppIdentifier(),this.send(t)}async send(t){const{name:i,column:n,line:s,entrypoint:a,retryWithoutTraceId:r}=t,g=this.getVariables({name:i,column:n,line:s,entrypoint:a,retryWithoutTraceId:r});F(this.endpoint,this.operationName,this.getQuery(),g)}getQuery(){return`
93
+ `,n={apiKey:this.apiKey,serviceUuid:this.serviceUUID,domains:e};F(this.endpoint,this.operationName,t,n)}}class Oe extends w{constructor(){super();C(this,"serviceIdentifier",new X);this.setOperationName("CollectNetworkHops")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t){this.sendAppIdentifier(),this.send(t)}async send(t){const{name:n,column:i,line:s,entrypoint:g,retryWithoutTraceId:r}=t,a=this.getVariables({name:n,column:i,line:s,entrypoint:g,retryWithoutTraceId:r});F(this.endpoint,this.operationName,this.getQuery(),a)}getQuery(){return`
94
94
  mutation ${this.operationName}(
95
95
  $apiKey: String!,
96
96
  $sessionId: String!,
@@ -114,15 +114,15 @@
114
114
  ${this.operationName==="CollectNetworkHops"?", retryWithoutTraceId: $retryWithoutTraceId":""}
115
115
  )
116
116
  }
117
- `}}class $e extends R{constructor(){super();u(this,"serviceIdentifier",new T);this.setOperationName("CollectNetworkRequest")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t){this.sendAppIdentifier(),this.send(t)}getQuery(){return`
117
+ `}}class Pe extends w{constructor(){super();C(this,"serviceIdentifier",new X);this.setOperationName("CollectNetworkRequest")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t){this.sendAppIdentifier(),this.send(t)}getQuery(){return`
118
118
  mutation ${this.operationName}(
119
119
  $data: NetworkRequestInput!
120
120
  ) {
121
121
  ${this.queryName}(
122
122
  data: $data)
123
123
  }
124
- `}async send(t){const i={data:{...t}};await F(this.endpoint,this.operationName,this.getQuery(),i)}}const q=[400,403];class ke{constructor(e=[]){u(this,"HEADER_TRACING","X-Sf3-Rid");u(this,"HEADER_LOG_GUARD","reentrancy_guard_logging_preactive");u(this,"HEADER_PRINT_GUARD","reentrancy_guard_print_preactive");u(this,"HEADER_EXCEPTION_GUARD","reentrancy_guard_exception_preactive");u(this,"contextManager");this.contextManager=G.getInstance(),e?.forEach(t=>{typeof t=="string"&&t.trim()&&this.contextManager.getExcludedDomains().add(t)}),l().sfDebug&&console.log("[RequestInterceptor] Initialized with static excluded domains.")}extractIdsFromTraceHeader(e,t=this.HEADER_TRACING){let i;if(e instanceof Headers)i=e.get(t)??void 0;else{const s=t.toLowerCase();for(const[a,r]of Object.entries(e))if(a.toLowerCase()===s){i=r;break}}if(!i)return{};const n=i.split("/").filter(Boolean);return n.length<3?{}:{sessionId:n[0],pageVisitId:n[1],requestId:n[n.length-1]}}parseStackFrame(e){const t=/\((.*):(\d+):(\d+)\)$/.exec(e.trim());if(!t)return null;const[,i,n,s]=t;return{filePath:i,line:parseInt(n,10),column:parseInt(s,10)}}async getOriginalPosition(e,t,i){let n={source:e,line:t,column:i,name:null};const s=e+".map";try{const a=JSON.parse(ie.readFileSync(s,"utf-8"));let r=(await new fe.sourceMapExports.SourceMapConsumer(a)).originalPositionFor({line:t,column:i});r.source&&(n=r)}catch(a){l().sfDebug&&console.error(`Could not read/parse map file at ${s}:`,a)}return{originalPos:n}}captureFirstUserLines(e,t=10,i=!1){const n=l().sfDebug?10:t,s=Error.stackTraceLimit;Error.stackTraceLimit=Math.max(s,n);const a=new Error(ue);ue in Error&&Error.captureStackTrace(a,this.captureFirstUserLines);const r=a.stack||"";Error.stackTraceLimit=s;const g=r.split(`
125
- `).slice(1),c=[];for(const I of g)if(!(I.includes("node:internal")||I.includes("internal/modules")||I.includes("internal/process")||I.includes("node_modules")||I.includes(".next/server/chunks")||I.includes("RequestInterceptor")||I.includes("contextManager")||I.includes("setupConfig"))&&(c.push(I.trim()),c.length>=t))break;for(const I of c){const d=this.parseStackFrame(I);d?(async()=>{const{originalPos:C}=await this.getOriginalPosition(d.filePath,d.line,d.column);if(C){l().sfDebug&&console.log("[RequestInterceptor] First user code line:",C);const p={line:C.line?.toString()||z.UNKNOWN,column:C.column?.toString()||z.NOT_CAPTURED,name:C.name||z.NOT_CAPTURED,entrypoint:C.source,retryWithoutTraceId:i};e.doSend(p)}})():l().sfDebug&&console.error("Could not parse stack line:",I)}}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!Ge.some(t=>new RegExp(`^${t.replace(/\*/g,".*")}$`).test(e))}addTracingHeaders(e,t){const i=new URL(t).hostname,n=this.shouldPropagateHeaders(i);return n?this.addTracingHeader(e,t):l().sfDebug&&console.error(`[RequestInterceptor] Excluded domain: ${i}`),n}addTracingHeader(e,t){const i=this.contextManager.getOrSetSfTraceId(),n=this.contextManager.getOrSetPageVisitUUID(),s=H();e.set(this.HEADER_TRACING,`${i}/${n}/${s}`),l().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${t}`)}patchFetch(e,t){const i=globalThis.fetch;typeof i=="function"?globalThis.fetch=async(n,s)=>{this.captureFirstUserLines(e);const a=Date.now(),r=new Headers(s?.headers);let g;typeof n=="string"||n instanceof URL?g=n.toString():n instanceof Request?(g=n.url,n.headers.forEach((h,A)=>{r.set(A,h)})):l().sfDebug&&console.error("[Sailfish RequestInterceptor] Invalid fetch input."),l().sfDebug&&console.log("[RequestInterceptor] Fetching request to:",g);const c=new URL(g).hostname,I=new Headers(r),d=this.addTracingHeaders(r,g),C={...s,headers:r};let p;try{let h=!1;this.addTracingHeaders(I,g),p=await i(g,C),d&&q.includes(p.status)?(p=await i(g,{...s,headers:I}),h=!0,this.captureFirstUserLines(e,10,h)):this.contextManager.addSupportedDomains(c);const A=Date.now();l().sfDebug&&console.log(`[RequestInterceptor] Fetch completed: ${g}, Status: ${p.status}, Duration: ${A-a}ms`);const{sessionId:m,pageVisitId:Z,requestId:f}=this.extractIdsFromTraceHeader(r);return t.doSend({apiKey:l().apiKey,requestId:f,pageVisitId:Z,recordingSessionId:m,serviceUuid:l().serviceUUID,timestampStart:a.toString(),timestampEnd:A.toString(),responseCode:p.status,success:!0,error:null,url:g,method:C.method||"GET",retryWithoutTraceId:h,parentSpanId:L()}),p}catch(h){const A=Date.now();l().sfDebug&&console.error(`[RequestInterceptor] Fetch failed: ${g}, Error: ${h}, Duration: ${A-a}ms`)}}:l().sfDebug&&console.error("[RequestInterceptor] Fetch not available.")}patchHttp(e,t){if(l().sfDebug&&console.log("[RequestInterceptor] Initializing HTTP/HTTPS request patch..."),!B||typeof B.request!="function")return void(l().sfDebug&&console.log("[RequestInterceptor] HTTP/HTTPS not available."));const i=B.request.bind(B),n=B.request.bind(B);B.request=function(s,a){let r;try{if(typeof s=="string"){const c=new URL(s);r={protocol:c.protocol||j,hostname:c.hostname,path:c.pathname+c.search,headers:{}}}else s instanceof URL?r={protocol:s.protocol||j,hostname:s.hostname,path:s.pathname+s.search,headers:{}}:(r={...s},r.protocol||(r.protocol=j));if(r.headers){const c=`${r.protocol}//${r.hostname}`;this.addTracingHeaders(r.headers,c),this.captureFirstUserLines(e)}else l().sfDebug&&console.warn("[RequestInterceptor] No headers found in HTTP request options. Skipping header addition.")}catch(c){throw l().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTP request options:",c),c}let g=!1;return i(r,c=>{const I=`${r.protocol}//${r.hostname}`;if(r.headers&&this.shouldPropagateHeaders(new URL(I).hostname)&&q.includes(c.statusCode||0)){r.hostname;const h={...r,headers:{...r.headers}};delete h.headers[this.HEADER_TRACING],i(h,a),g=!0,this.captureFirstUserLines(e,10,g)}const{sessionId:d,pageVisitId:C,requestId:p}=this.extractIdsFromTraceHeader(r.headers);t.doSend({apiKey:l().apiKey,requestId:p,pageVisitId:C,recordingSessionId:d,serviceUuid:l().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:c.statusCode||0,success:!!c.statusCode&&c.statusCode<400,error:null,url:I,method:r.method||"GET",retryWithoutTraceId:g,parentSpanId:L()}),a?.(c)})},B.request=function(s,a){let r;try{if(typeof s=="string"){const c=new URL(s);r={protocol:c.protocol||Q,hostname:c.hostname,path:c.pathname+c.search,headers:{}}}else s instanceof URL?r={protocol:s.protocol||Q,hostname:s.hostname,path:s.pathname+s.search,headers:{}}:(r={...s},r.protocol||(r.protocol=Q));if(r.headers){const c=`${r.protocol}//${r.hostname}`;this.addTracingHeaders(r.headers,c)}else l().sfDebug&&console.warn("[RequestInterceptor] No headers found in HTTPS request options. Skipping header addition.")}catch(c){throw l().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTPS request options:",c),c}let g=!1;return n(r,c=>{const I=`${r.protocol}//${r.hostname}`;if(r.headers&&this.shouldPropagateHeaders(new URL(I).hostname)&&q.includes(c.statusCode||0)){const h={...r,headers:{...r.headers}};delete h.headers[this.HEADER_TRACING],n(h,a),g=!0,this.captureFirstUserLines(e,10,g)}const{sessionId:d,pageVisitId:C,requestId:p}=this.extractIdsFromTraceHeader(r.headers);t.doSend({apiKey:l().apiKey,requestId:p,pageVisitId:C,recordingSessionId:d,serviceUuid:l().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:c.statusCode||0,success:!!c.statusCode&&c.statusCode<400,error:null,url:I,method:r.method||"GET",retryWithoutTraceId:g,parentSpanId:L()}),a?.(c)})},l().sfDebug&&console.log("✅ HTTP and HTTPS request methods patched globally.")}tryPatch(e,t){try{require.resolve(t),e(),console.log(`[RequestInterceptor] Patched ${t}`)}catch(i){console.warn(`[RequestInterceptor] Could not patch ${t}: ${i.message}`)}}getExcludedDomains(){return[...this.contextManager.getExcludedDomains()]}}class Oe extends oe{constructor(){super(),this.setOperationName("UpdateServiceDetails")}async doSend(){this.sendAppIdentifier(),this.send()}async send(){const e=`
124
+ `}async send(t){const n={data:{...t}};await F(this.endpoint,this.operationName,this.getQuery(),n)}}const te=[400,403];class Me{constructor(e=[]){C(this,"HEADER_TRACING","X-Sf3-Rid");C(this,"HEADER_LOG_GUARD","reentrancy_guard_logging_preactive");C(this,"HEADER_PRINT_GUARD","reentrancy_guard_print_preactive");C(this,"HEADER_EXCEPTION_GUARD","reentrancy_guard_exception_preactive");C(this,"contextManager");this.contextManager=v.getInstance(),e?.forEach(t=>{typeof t=="string"&&t.trim()&&this.contextManager.getExcludedDomains().add(t)}),l().sfDebug&&console.log("[RequestInterceptor] Initialized with static excluded domains.")}extractIdsFromTraceHeader(e,t=this.HEADER_TRACING){let n;if(e instanceof Headers)n=e.get(t)??void 0;else{const s=t.toLowerCase();for(const[g,r]of Object.entries(e))if(g.toLowerCase()===s){n=r;break}}if(!n)return{};const i=n.split("/").filter(Boolean);return i.length<3?{}:{sessionId:i[0],pageVisitId:i[1],requestId:i[i.length-1]}}parseStackFrame(e){const t=/\((.*):(\d+):(\d+)\)$/.exec(e.trim());if(!t)return null;const[,n,i,s]=t;return{filePath:n,line:parseInt(i,10),column:parseInt(s,10)}}async getOriginalPosition(e,t,n){let i={source:e,line:t,column:n,name:null};const s=e+".map";try{const g=JSON.parse(re.readFileSync(s,"utf-8"));let r=(await new Ze.sourceMapExports.SourceMapConsumer(g)).originalPositionFor({line:t,column:n});r.source&&(i=r)}catch(g){l().sfDebug&&console.error(`Could not read/parse map file at ${s}:`,g)}return{originalPos:i}}captureFirstUserLines(e,t=10,n=!1){const i=l().sfDebug?10:t,s=Error.stackTraceLimit;Error.stackTraceLimit=Math.max(s,i);const g=new Error(me);me in Error&&Error.captureStackTrace(g,this.captureFirstUserLines);const r=g.stack||"";Error.stackTraceLimit=s;const a=r.split(`
125
+ `).slice(1),c=[];for(const d of a)if(!(d.includes("node:internal")||d.includes("internal/modules")||d.includes("internal/process")||d.includes("node_modules")||d.includes(".next/server/chunks")||d.includes("RequestInterceptor")||d.includes("contextManager")||d.includes("setupConfig"))&&(c.push(d.trim()),c.length>=t))break;for(const d of c){const I=this.parseStackFrame(d);I?(async()=>{const{originalPos:h}=await this.getOriginalPosition(I.filePath,I.line,I.column);if(h){l().sfDebug&&console.log("[RequestInterceptor] First user code line:",h);const p={line:h.line?.toString()||L.UNKNOWN,column:h.column?.toString()||L.NOT_CAPTURED,name:h.name||L.NOT_CAPTURED,entrypoint:h.source,retryWithoutTraceId:n};e.doSend(p)}})():l().sfDebug&&console.error("Could not parse stack line:",d)}}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!Ne.some(t=>new RegExp(`^${t.replace(/\*/g,".*")}$`).test(e))}addTracingHeaders(e,t){const n=new URL(t).hostname,i=this.shouldPropagateHeaders(n);return i?this.addTracingHeader(e,t):l().sfDebug&&console.error(`[RequestInterceptor] Excluded domain: ${n}`),i}addTracingHeader(e,t){const n=oe();if(n){const r=ie(n);if(r&&r.sample_rate===0)return void(l().sfDebug&&console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${t}`))}const i=this.contextManager.getOrSetSfTraceId(),s=this.contextManager.getOrSetPageVisitUUID(),g=R();e.set(this.HEADER_TRACING,`${i}/${s}/${g}`),l().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${t}`)}patchFetch(e,t){const n=globalThis.fetch;typeof n=="function"?globalThis.fetch=async(i,s)=>{const g=new Headers(s?.headers);if(g.get(this.HEADER_LOG_GUARD)==="true"||g.get(this.HEADER_PRINT_GUARD)==="true"||g.get(this.HEADER_EXCEPTION_GUARD)==="true")return n(i,s);this.captureFirstUserLines(e);const r=Date.now();let a;typeof i=="string"||i instanceof URL?a=i.toString():i instanceof Request?(a=i.url,i.headers.forEach((u,A)=>{g.set(A,u)})):l().sfDebug&&console.error("[Sailfish RequestInterceptor] Invalid fetch input."),l().sfDebug&&console.log("[RequestInterceptor] Fetching request to:",a);const c=new URL(a).hostname,d=new Headers(g),I=this.addTracingHeaders(g,a),h={...s,headers:g};let p;try{let u=!1;this.addTracingHeaders(d,a),p=await n(a,h),I&&te.includes(p.status)?(p=await n(a,{...s,headers:d}),u=!0,this.captureFirstUserLines(e,10,u)):this.contextManager.addSupportedDomains(c);const A=Date.now();l().sfDebug&&console.log(`[RequestInterceptor] Fetch completed: ${a}, Status: ${p.status}, Duration: ${A-r}ms`);const{sessionId:m,pageVisitId:y,requestId:b}=this.extractIdsFromTraceHeader(g);return t.doSend({apiKey:l().apiKey,requestId:b,pageVisitId:y,recordingSessionId:m,serviceUuid:l().serviceUUID,timestampStart:r.toString(),timestampEnd:A.toString(),responseCode:p.status,success:!0,error:null,url:a,method:h.method||"GET",retryWithoutTraceId:u,parentSpanId:$()}),p}catch(u){const A=Date.now();l().sfDebug&&console.error(`[RequestInterceptor] Fetch failed: ${a}, Error: ${u}, Duration: ${A-r}ms`)}}:l().sfDebug&&console.error("[RequestInterceptor] Fetch not available.")}patchHttp(e,t){if(l().sfDebug&&console.log("[RequestInterceptor] Initializing HTTP/HTTPS request patch..."),!N||typeof N.request!="function")return void(l().sfDebug&&console.log("[RequestInterceptor] HTTP/HTTPS not available."));const n=N.request.bind(N),i=N.request.bind(N);N.request=function(s,g){let r;try{if(typeof s=="string"){const c=new URL(s);r={protocol:c.protocol||Q,hostname:c.hostname,path:c.pathname+c.search,headers:{}}}else s instanceof URL?r={protocol:s.protocol||Q,hostname:s.hostname,path:s.pathname+s.search,headers:{}}:(r={...s},r.protocol||(r.protocol=Q));if(r.headers){const c=`${r.protocol}//${r.hostname}`;this.addTracingHeaders(r.headers,c),this.captureFirstUserLines(e)}else l().sfDebug&&console.warn("[RequestInterceptor] No headers found in HTTP request options. Skipping header addition.")}catch(c){throw l().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTP request options:",c),c}let a=!1;return n(r,c=>{const d=`${r.protocol}//${r.hostname}`;if(r.headers&&this.shouldPropagateHeaders(new URL(d).hostname)&&te.includes(c.statusCode||0)){r.hostname;const u={...r,headers:{...r.headers}};delete u.headers[this.HEADER_TRACING],n(u,g),a=!0,this.captureFirstUserLines(e,10,a)}const{sessionId:I,pageVisitId:h,requestId:p}=this.extractIdsFromTraceHeader(r.headers);t.doSend({apiKey:l().apiKey,requestId:p,pageVisitId:h,recordingSessionId:I,serviceUuid:l().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:c.statusCode||0,success:!!c.statusCode&&c.statusCode<400,error:null,url:d,method:r.method||"GET",retryWithoutTraceId:a,parentSpanId:$()}),g?.(c)})},N.request=function(s,g){let r;try{if(typeof s=="string"){const c=new URL(s);r={protocol:c.protocol||q,hostname:c.hostname,path:c.pathname+c.search,headers:{}}}else s instanceof URL?r={protocol:s.protocol||q,hostname:s.hostname,path:s.pathname+s.search,headers:{}}:(r={...s},r.protocol||(r.protocol=q));if(r.headers){const c=`${r.protocol}//${r.hostname}`;this.addTracingHeaders(r.headers,c)}else l().sfDebug&&console.warn("[RequestInterceptor] No headers found in HTTPS request options. Skipping header addition.")}catch(c){throw l().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTPS request options:",c),c}let a=!1;return i(r,c=>{const d=`${r.protocol}//${r.hostname}`;if(r.headers&&this.shouldPropagateHeaders(new URL(d).hostname)&&te.includes(c.statusCode||0)){const u={...r,headers:{...r.headers}};delete u.headers[this.HEADER_TRACING],i(u,g),a=!0,this.captureFirstUserLines(e,10,a)}const{sessionId:I,pageVisitId:h,requestId:p}=this.extractIdsFromTraceHeader(r.headers);t.doSend({apiKey:l().apiKey,requestId:p,pageVisitId:h,recordingSessionId:I,serviceUuid:l().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:c.statusCode||0,success:!!c.statusCode&&c.statusCode<400,error:null,url:d,method:r.method||"GET",retryWithoutTraceId:a,parentSpanId:$()}),g?.(c)})},l().sfDebug&&console.log("✅ HTTP and HTTPS request methods patched globally.")}tryPatch(e,t){try{require.resolve(t),e(),console.log(`[RequestInterceptor] Patched ${t}`)}catch(n){console.warn(`[RequestInterceptor] Could not patch ${t}: ${n.message}`)}}getExcludedDomains(){return[...this.contextManager.getExcludedDomains()]}}class je extends ae{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,4 +142,42 @@
142
142
  gitSha: $gitSha,
143
143
  )
144
144
  }
145
- `,t=this.getVariables({serviceIdentifier:l().serviceIdentifier,serviceVersion:l().serviceVersion,serviceAdditionalMetadata:l().serviceAdditionalMetadata,gitSha:l().gitSha||""});F(this.endpoint,this.operationName,e,t)}}function Ne(){return{capture_arguments:w(process.env.SF_FUNCSPAN_CAPTURE_ARGUMENTS,!0),capture_return_value:w(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:w(process.env.SF_FUNCSPAN_AUTOCAPTURE_ALL_CHILD_FUNCTIONS,!1),sample_rate:parseFloat(process.env.SF_FUNCSPAN_SAMPLE_RATE||"1.0"),enable_sampling:w(process.env.SF_FUNCSPAN_ENABLE_SAMPLING,!1),capture_sf_veritas:w(process.env.SF_FUNCSPAN_CAPTURE_SF_VERITAS,!1),parse_json_strings:w(process.env.SF_FUNCSPAN_PARSE_JSON_STRINGS,!1)}}function Pe(){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}}function pe(o){try{const e=o.split("-");return e.length!==9?(console.error(`[FuncSpan] Invalid header format: expected 9 parts, got ${e.length}`),null):{capture_arguments:e[0]==="1",capture_return_value:e[1]==="1",arg_limit_mb:parseInt(e[2],10),return_limit_mb:parseInt(e[3],10),autocapture_all_child_functions:e[4]==="1",sample_rate:parseFloat(e[5]),enable_sampling:e[6]==="1",capture_sf_veritas:e[7]==="1",parse_json_strings:e[8]==="1"}}catch(e){return console.error(`[FuncSpan] Failed to parse header override "${o}":`,e),null}}function w(o,e){if(!o)return e;const t=o.toLowerCase();return t==="true"||t==="1"||t==="yes"}const te=new ne.AsyncLocalStorage;function he(){return te.getStore()}function E(...o){const e={};for(const t of o)for(const i in t)t[i]!==void 0&&(e[i]=t[i]);return e}function ee(o,e){try{const t=JSON.stringify(o).length/1048576;return t<=e?o:{_truncated:!0,_originalSizeMB:t.toFixed(2),_limitMB:e,_preview:JSON.stringify(o).substring(0,500)+"..."}}catch{return{_error:"Failed to serialize data",_type:typeof o}}}class Me{constructor(e=[process.cwd()],t=!1){u(this,"rootPaths");u(this,"fileConfigs",new Map);u(this,"functionConfigs",new Map);u(this,"directoryConfigs",new Map);u(this,"hasSailfishFiles",!1);u(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 i=this.hasSailfishFiles?Ne():{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},n=this._getDirectoryConfig(e),s=v.normalize(e),a=this.fileConfigs.get(s)||{};let r={};if(t){const g=this.functionConfigs.get(s);g&&(r=g.get(t)||{})}return E(i,n,a,r)}async _walkDirectory(e,t){try{const i=k.readdirSync(e,{withFileTypes:!0});for(const n of i){const s=v.join(e,n.name);n.name==="node_modules"||n.name===".git"||n.name.startsWith(".")||(n.isDirectory()?await this._walkDirectory(s,t):n.name===".sailfish"&&t.push(s))}}catch(i){this.debug&&console.error(`[FuncSpan ConfigLoader] Error walking directory ${e}:`,i)}}async _loadConfigFile(e){try{const t=k.readFileSync(e,"utf-8"),i=v.dirname(e);let n=null;try{n=JSON.parse(t)}catch{try{n=require("js-yaml").load(t)}catch(s){return void(this.debug&&console.error(`[FuncSpan ConfigLoader] Failed to parse ${e} as JSON or YAML:`,s))}}if(!n)return;n.default&&this.directoryConfigs.set(i,n.default),n.files&&await this._expandFileGlobs(i,n.files,n.default||{}),n.functions&&this._storeFunctionConfigs(i,n.functions,n.default||{}),this.debug&&(console.log(`[FuncSpan ConfigLoader] Loaded config from ${e}`),console.log(`[FuncSpan ConfigLoader] Directory: ${i}`),console.log(`[FuncSpan ConfigLoader] Has default: ${!!n.default}`),console.log(`[FuncSpan ConfigLoader] File patterns: ${Object.keys(n.files||{}).length}`),console.log(`[FuncSpan ConfigLoader] Functions: ${Object.keys(n.functions||{}).length}`))}catch(t){this.debug&&console.error(`[FuncSpan ConfigLoader] Error loading ${e}:`,t)}}async _expandFileGlobs(e,t,i){for(const[n,s]of Object.entries(t))try{const a=v.join(e,n),r=await He.glob(a,{absolute:!0,nodir:!0,ignore:["**/node_modules/**","**/.git/**"]});this.debug&&console.log(`[FuncSpan ConfigLoader] Pattern '${n}' matched ${r.length} files`);for(const g of r){const c=v.normalize(g),I=E(i,s);this.fileConfigs.set(c,I),this.debug&&r.length<=5&&console.log(`[FuncSpan ConfigLoader] - ${g}`)}}catch(a){this.debug&&console.error(`[FuncSpan ConfigLoader] Error expanding glob '${n}':`,a)}}_storeFunctionConfigs(e,t,i){for(const[n,s]of Object.entries(t)){const a=n.split("::");if(a.length!==2){this.debug&&console.warn(`[FuncSpan ConfigLoader] Invalid function pattern '${n}' (expected format: 'file.ts::functionName')`);continue}const[r,g]=a,c=v.normalize(v.join(e,r));this.functionConfigs.has(c)||this.functionConfigs.set(c,new Map);const I=this.functionConfigs.get(c),d=E(i,s);I.set(g,d),this.debug&&console.log(`[FuncSpan ConfigLoader] Function config: ${c}::${g}`)}}async _resolveInheritance(){}_getDirectoryConfig(e){let t=v.dirname(v.normalize(e));const i=[];for(;t&&t!==v.dirname(t);){const n=this.directoryConfigs.get(t);n&&i.unshift(n),t=v.dirname(t)}return i.reduce((n,s)=>E(n,s),{})}}let J=null;async function Ae(o,e){J=new Me(o,e),await J.loadAllConfigs()}function be(o,e){return J?J.getConfig(o,e):{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}}function me(){return J!==null}function D(o){process.env.SF_VERITAS_DEBUG==="true"&&console.log("[FuncSpan Capture]",{function:o.functionName,file:o.filePath,duration:`${o.duration}ms`,async:o.async,error:o.error}),ve(()=>{})}exports.ContextManager=G,exports.addOrUpdateMetadata=function(o,e={},t,i=!1){const n=l();new ge(n.apiKey).addOrUpdateMetadata(o,e,t,i)},exports.captureFunctionSpan=function(o,e,t,i){const n=function(...s){const a=(function(C,p){const h=he();if(h){const A=pe(h);if(A)return process.env.SF_DEBUG==="true"&&console.log(`[FuncSpan] Using HTTP header override for ${C}::${p}`),A}return be(C,p)})(t,e);if(a.enable_sampling&&a.sample_rate<1&&Math.random()>a.sample_rate)return o.apply(this,s);if(a.sample_rate===0)return o.apply(this,s);const r=G.getInstance(),g=r.getCurrentFunctionSpanId(),c=H();r.setCurrentFunctionSpanId(c);const I=Date.now();let d=null;a.capture_arguments&&(d={},i.paramNames.forEach((C,p)=>{p<s.length&&(d[C]=s[p])}),d&&a.arg_limit_mb>0&&(d=ee(d,a.arg_limit_mb)));try{const C=o.apply(this,s);if(C&&typeof C.then=="function")return C.then(A=>{const m=Date.now();let Z=null;return a.capture_return_value&&a.return_limit_mb>0&&(Z=ee(A,a.return_limit_mb)),D({functionName:e,filePath:t,metadata:i,args:d,result:Z,error:null,duration:m-I,async:!0,spanId:c}),g?r.setCurrentFunctionSpanId(g):r.clearCurrentFunctionSpanId(),A},A=>{const m=Date.now();throw D({functionName:e,filePath:t,metadata:i,args:d,result:null,error:A?.message||String(A),duration:m-I,async:!0,spanId:c}),g?r.setCurrentFunctionSpanId(g):r.clearCurrentFunctionSpanId(),A});const p=Date.now();let h=null;return a.capture_return_value&&a.return_limit_mb>0&&(h=ee(C,a.return_limit_mb)),D({functionName:e,filePath:t,metadata:i,args:d,result:h,error:null,duration:p-I,async:!1,spanId:c}),g?r.setCurrentFunctionSpanId(g):r.clearCurrentFunctionSpanId(),C}catch(C){const p=Date.now();throw D({functionName:e,filePath:t,error:C?.message||String(C),duration:p-I,async:!1}),g?r.setCurrentFunctionSpanId(g):r.clearCurrentFunctionSpanId(),C}};Object.defineProperty(n,"name",{value:e,writable:!1});for(const s in o)o.hasOwnProperty(s)&&(n[s]=o[s]);return n},exports.clearFuncspanOverride=function(){te.enterWith(void 0)},exports.getCurrentFunctionSpanId=L,exports.getDefaultConfig=Pe,exports.getEnvConfig=Ne,exports.getFuncspanOverride=he,exports.getGlobalConfig=be,exports.identify=function(o,e,t,i=!1){const n=l();new ge(n.apiKey).identify(o,e,t,i)},exports.initializeConfigLoader=Ae,exports.isConfigLoaderInitialized=me,exports.parseHeaderOverride=pe,exports.runWithContext=ve,exports.setFuncspanOverride=function(o){te.enterWith(o)},exports.setupInterceptors=function(o){if(!o||!o.apiKey){const n=`The required API Key is not provided: ${JSON.stringify(o)}`;console.error(n)}const{config:e}=Ke(o);if(e.sfDebug&&console.log("Updated configuration after applying options:",e),!e.apiKey||!e.apiGraphqlEndpoint){const n=`The required config is not provided: ${JSON.stringify(e)}`;throw console.error(n),new Error(n)}me()||Ae(void 0,e.sfDebug).catch(n=>{e.sfDebug&&console.error("[FuncSpan] Failed to initialize config loader:",n)});const t=new oe;t.setServiceUUID(e.serviceUUID),(function(n){function s(d,C){n.setOperationName("CollectLogs"),n.doSend([C,d])}const a=console.log.bind(console),r=console.error.bind(console),g=console.warn.bind(console),c=console.info.bind(console),I=console.debug.bind(console);console.log=(...d)=>{s("INFO",d.join(" ")),a(...d)},console.error=(...d)=>{s("ERROR",d.join(" ")),r(...d)},console.warn=(...d)=>{s("WARN",d.join(" ")),g(...d)},console.info=(...d)=>{s("INFO",d.join(" ")),c(...d)},l().logLevel==="DEBUG"&&(console.debug=(...d)=>{s("DEBUG",d.join(" ")),I(...d)})})(t),(function(n=[]){const s=new ke(n);new ze().doSend(s.getExcludedDomains());const a=new xe,r=new $e;s.patchFetch(a,r),s.patchHttp(a,r)})(e.domainsToNotPropagateHeadersTo);const i=new De;i.setServiceUUID(e.serviceUUID),Te(i),Le(),new Oe().send()};
145
+ `,t=this.getVariables({serviceIdentifier:l().serviceIdentifier,serviceVersion:l().serviceVersion,serviceAdditionalMetadata:l().serviceAdditionalMetadata,gitSha:l().gitSha||""});F(this.endpoint,this.operationName,e,t)}}class Qe{constructor(e=[process.cwd()],t=!1){C(this,"rootPaths");C(this,"fileConfigs",new Map);C(this,"functionConfigs",new Map);C(this,"directoryConfigs",new Map);C(this,"hasSailfishFiles",!1);C(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)O.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 n=this.hasSailfishFiles?ce():{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},i=this._getDirectoryConfig(e),s=G.normalize(e),g=this.fileConfigs.get(s)||{};let r={};if(t){const a=this.functionConfigs.get(s);a&&(r=a.get(t)||{})}return _(n,i,g,r)}async _walkDirectory(e,t){try{const n=O.readdirSync(e,{withFileTypes:!0});for(const i of n){const s=G.join(e,i.name);i.isFile()&&i.name===".sailfish"?t.push(s):i.name==="node_modules"||i.isDirectory()&&i.name.startsWith(".")&&i.name!==".sailfish"||i.isDirectory()&&await this._walkDirectory(s,t)}}catch(n){this.debug&&console.error(`[FuncSpan ConfigLoader] Error walking directory ${e}:`,n)}}async _loadConfigFile(e){try{const t=O.readFileSync(e,"utf-8"),n=G.dirname(e);let i=null;try{i=JSON.parse(t)}catch{try{i=require("js-yaml").load(t)}catch(s){return void(this.debug&&console.error(`[FuncSpan ConfigLoader] Failed to parse ${e} as JSON or YAML:`,s))}}if(!i)return;i.default&&this.directoryConfigs.set(n,i.default),i.files&&await this._expandFileGlobs(n,i.files,i.default||{}),i.functions&&this._storeFunctionConfigs(n,i.functions,i.default||{}),this.debug&&(console.log(`[FuncSpan ConfigLoader] Loaded config from ${e}`),console.log(`[FuncSpan ConfigLoader] Directory: ${n}`),console.log(`[FuncSpan ConfigLoader] Has default: ${!!i.default}`),console.log(`[FuncSpan ConfigLoader] File patterns: ${Object.keys(i.files||{}).length}`),console.log(`[FuncSpan ConfigLoader] Functions: ${Object.keys(i.functions||{}).length}`))}catch(t){this.debug&&console.error(`[FuncSpan ConfigLoader] Error loading ${e}:`,t)}}async _expandFileGlobs(e,t,n){for(const[i,s]of Object.entries(t))try{const g=G.join(e,i),r=await Ye.glob(g,{absolute:!0,nodir:!0,ignore:["**/node_modules/**","**/.git/**"]});this.debug&&console.log(`[FuncSpan ConfigLoader] Pattern '${i}' matched ${r.length} files`);for(const a of r){const c=G.normalize(a),d=_(n,s);this.fileConfigs.set(c,d),this.debug&&r.length<=5&&console.log(`[FuncSpan ConfigLoader] - ${a}`)}}catch(g){this.debug&&console.error(`[FuncSpan ConfigLoader] Error expanding glob '${i}':`,g)}}_storeFunctionConfigs(e,t,n){for(const[i,s]of Object.entries(t)){const g=i.split("::");if(g.length!==2){this.debug&&console.warn(`[FuncSpan ConfigLoader] Invalid function pattern '${i}' (expected format: 'file.ts::functionName')`);continue}const[r,a]=g,c=G.normalize(G.join(e,r));this.functionConfigs.has(c)||this.functionConfigs.set(c,new Map);const d=this.functionConfigs.get(c),I=_(n,s);d.set(a,I),this.debug&&console.log(`[FuncSpan ConfigLoader] Function config: ${c}::${a}`)}}async _resolveInheritance(){}_getDirectoryConfig(e){let t=G.dirname(G.normalize(e));const n=[];for(;t&&t!==G.dirname(t);){const i=this.directoryConfigs.get(t);i&&n.unshift(i),t=G.dirname(t)}return n.reduce((i,s)=>_(i,s),{})}}let J=null;async function fe(o,e){J=new Qe(o,e),await J.loadAllConfigs()}function ye(o,e){return J?J.getConfig(o,e):(process.env.SF_DEBUG==="true"&&console.log("[FuncSpan ConfigLoader] Config loader not initialized, using env config for worker process"),ce())}function Se(){return J!==null}class qe extends w{constructor(){super(),this.operationName="CollectFunctionSpans"}send(e){const t=l().sfDebug;t&&console.log(`[FunctionSpanTransmitter] Preparing to send ${e.length} function span(s)`);for(const n of e)try{let i;if(n.result!==void 0&&n.result!==null){const g=typeof n.result;i=JSON.stringify({type:g,has_value:!0,value:n.result})}else i=n.result===null?JSON.stringify({type:"null",has_value:!0,value:null}):JSON.stringify({type:"undefined",has_value:!1,value:null});const s=this.getVariables({library:"JS/TS BACKEND",version:l().version,spanId:n.spanId,parentSpanId:n.parentSpanId,filePath:n.filePath,lineNumber:n.metadata.line,columnNumber:n.metadata.column,functionName:n.functionName,arguments:JSON.stringify(n.args||{}),returnValue:i,startTimeNs:(1e6*Date.now()-1e6*n.duration).toString(),durationNs:(1e6*n.duration).toString()});t&&(console.log(`[FunctionSpanTransmitter] Sending GraphQL mutation to ${this.endpoint}`),console.log("[FunctionSpanTransmitter] Variables:",JSON.stringify(s,null,2))),F(this.endpoint,this.operationName,this.getQuery(),s),t&&console.log(`[FunctionSpanTransmitter] Queued function span for ${n.functionName}`)}catch(i){console.error(`[FunctionSpanTransmitter] Error preparing function span for ${n.functionName}:`,i)}}getQuery(){return`
146
+ ${this.queryType} ${this.operationName}(
147
+ $apiKey: String!,
148
+ $serviceUuid: String!,
149
+ $sessionId: String!,
150
+ $timestampMs: String!,
151
+ $parentSpanId: String,
152
+ $library: String!,
153
+ $version: String!,
154
+ $spanId: String!,
155
+ $filePath: String!,
156
+ $lineNumber: Int!,
157
+ $columnNumber: Int!,
158
+ $functionName: String!,
159
+ $arguments: String!,
160
+ $returnValue: String,
161
+ $startTimeNs: String!,
162
+ $durationNs: String!
163
+ ) {
164
+ ${this.queryName}(
165
+ apiKey: $apiKey,
166
+ serviceUuid: $serviceUuid,
167
+ sessionId: $sessionId,
168
+ timestampMs: $timestampMs,
169
+ parentSpanId: $parentSpanId,
170
+ library: $library,
171
+ version: $version,
172
+ spanId: $spanId,
173
+ filePath: $filePath,
174
+ lineNumber: $lineNumber,
175
+ columnNumber: $columnNumber,
176
+ functionName: $functionName,
177
+ arguments: $arguments,
178
+ returnValue: $returnValue,
179
+ startTimeNs: $startTimeNs,
180
+ durationNs: $durationNs
181
+ )
182
+ }
183
+ `}}let ne=null;function D(o){const e=x(),t=e?.sfDebug||!1;t&&console.log("[FuncSpan] captureSpanData called for:",{function:o.functionName,file:o.filePath,duration:`${o.duration}ms`,async:o.async,error:o.error,spanId:o.spanId});const n={functionName:o.functionName,filePath:o.filePath,metadata:o.metadata,args:o.args,result:o.result,error:o.error,duration:o.duration,async:o.async,spanId:o.spanId,parentSpanId:o.parentSpanId};t&&console.log("[FuncSpan] Sending function span to transmitter:",n);try{(ne||(ne=new qe),ne).send([n]),t&&console.log("[FuncSpan] Function span sent successfully")}catch(i){console.error("[FuncSpan] Error sending function span:",i)}}exports.ContextManager=v,exports.addOrUpdateMetadata=function(o,e={},t,n=!1){const i=l();new Ce(i.apiKey).addOrUpdateMetadata(o,e,t,n)},exports.captureFunctionSpan=function(o,e,t,n){const i=function(...s){const g=x(),r=g?.sfDebug||!1;r&&console.log(`[FuncSpan] captureFunctionSpan wrapper called for ${t}::${e}`);const a=(function(u,A){const m=oe();if(m){const y=ie(m);if(y)return process.env.SF_DEBUG==="true"&&console.log(`[FuncSpan] Using HTTP header override for ${u}::${A}`),y}return ye(u,A)})(t,e);if(r&&console.log(`[FuncSpan] Config for ${t}::${e}:`,a),a.enable_sampling&&a.sample_rate<1&&Math.random()>a.sample_rate)return r&&console.log(`[FuncSpan] Skipping ${e} due to sampling`),o.apply(this,s);if(a.sample_rate===0)return r&&console.log(`[FuncSpan] Skipping ${e} - sample_rate is 0.0`),o.apply(this,s);r&&console.log(`[FuncSpan] Capturing function span for ${e}`);const c=v.getInstance(),d=c.getCurrentFunctionSpanId(),I=R();c.setCurrentFunctionSpanId(I);const h=Date.now();let p=null;a.capture_arguments&&(p={},n.paramNames.forEach((u,A)=>{A<s.length&&(p[u]=s[A])}),p&&a.arg_limit_mb>0&&(p=ee(p,a.arg_limit_mb)));try{const u=o.apply(this,s);if(u&&typeof u.then=="function")return u.then(y=>{const b=Date.now();let f=null;return a.capture_return_value&&a.return_limit_mb>0&&(f=ee(y,a.return_limit_mb)),D({functionName:e,filePath:t,metadata:n,args:p,result:f,error:null,duration:b-h,async:!0,spanId:I,parentSpanId:d}),d?c.setCurrentFunctionSpanId(d):c.clearCurrentFunctionSpanId(),y},y=>{const b=Date.now();throw D({functionName:e,filePath:t,metadata:n,args:p,result:null,error:y?.message||String(y),duration:b-h,async:!0,spanId:I,parentSpanId:d}),d?c.setCurrentFunctionSpanId(d):c.clearCurrentFunctionSpanId(),y});const A=Date.now();let m=null;return a.capture_return_value&&a.return_limit_mb>0&&(m=ee(u,a.return_limit_mb)),D({functionName:e,filePath:t,metadata:n,args:p,result:m,error:null,duration:A-h,async:!1,spanId:I,parentSpanId:d}),d?c.setCurrentFunctionSpanId(d):c.clearCurrentFunctionSpanId(),u}catch(u){const A=Date.now();throw D({functionName:e,filePath:t,metadata:n,args:p,result:null,error:u?.message||String(u),duration:A-h,async:!1,spanId:I,parentSpanId:d}),d?c.setCurrentFunctionSpanId(d):c.clearCurrentFunctionSpanId(),u}};Object.defineProperty(i,"name",{value:e,writable:!1});for(const s in o)o.hasOwnProperty(s)&&(i[s]=o[s]);return i},exports.clearFuncspanOverride=Fe,exports.getCurrentFunctionSpanId=$,exports.getDefaultConfig=ze,exports.getEnvConfig=ce,exports.getFuncspanOverride=oe,exports.getGlobalConfig=ye,exports.identify=function(o,e,t,n=!1){const i=l();new Ce(i.apiKey).identify(o,e,t,n)},exports.initializeConfigLoader=fe,exports.isConfigLoaderInitialized=Se,exports.parseHeaderOverride=ie,exports.runWithContext=function(o){const e={...v.getInstance().getCurrentContext()};K.run(e,()=>{o()})},exports.setFuncspanOverride=We,exports.setupInterceptors=function(o){if(!o||!o.apiKey){const i=`The required API Key is not provided: ${JSON.stringify(o)}`;console.error(i)}const{config:e}=Te(o);if(e.sfDebug&&console.log("Updated configuration after applying options:",e),!e.apiKey||!e.apiGraphqlEndpoint){const i=`The required config is not provided: ${JSON.stringify(e)}`;throw console.error(i),new Error(i)}Se()||fe(void 0,e.sfDebug).catch(i=>{e.sfDebug&&console.error("[FuncSpan] Failed to initialize config loader:",i)});const t=new ae;t.setServiceUUID(e.serviceUUID),(function(i){function s(I,h){i.setOperationName("CollectLogs"),i.doSend([h,I])}const g=console.log.bind(console),r=console.error.bind(console),a=console.warn.bind(console),c=console.info.bind(console),d=console.debug.bind(console);console.log=(...I)=>{s("INFO",I.join(" ")),g(...I)},console.error=(...I)=>{s("ERROR",I.join(" ")),r(...I)},console.warn=(...I)=>{s("WARN",I.join(" ")),a(...I)},console.info=(...I)=>{s("INFO",I.join(" ")),c(...I)},l().logLevel==="DEBUG"&&(console.debug=(...I)=>{s("DEBUG",I.join(" ")),d(...I)})})(t),(function(i=[]){const s=new Me(i);new ke().doSend(s.getExcludedDomains());const g=new Oe,r=new Pe;s.patchFetch(g,r),s.patchHttp(g,r)})(e.domainsToNotPropagateHeadersTo);const n=new Le;n.setServiceUUID(e.serviceUUID),_e(n),xe(),new je().send()};