@sailfish-ai/sf-veritas 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ "use strict";const dn=require("fs/promises"),mn=require("http"),Zn=require("https"),fn=require("os"),Wn=require("./source-map-rHHEdpre.cjs"),pn=require("worker_threads"),b=require("./contextManager-qXvO_a5y.cjs"),Gn=require("path");function yn(n){const g=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const C in n)if(C!=="default"){const I=Object.getOwnPropertyDescriptor(n,C);Object.defineProperty(g,C,I.get?I:{enumerable:!0,get:()=>n[C]})}}return g.default=n,Object.freeze(g)}const Bn=yn(dn);function Q(n){return typeof n=="string"?n:n==null?"":Array.isArray(n)?n.map(g=>String(g)).join(`
2
+ `):String(n)}function Yn(n){try{return JSON.stringify(n),!0}catch{return!1}}class K{file;line;function;code;locals;offender;column;constructor({file:g,line:C,function:I,code:t,locals:l={},offender:e=!1,column:i}){this.file=g,this.line=C,this.function=I,this.code=t,this.locals=l,this.offender=e,this.column=i}toDict(){const g={file:this.file,line:this.line,function:this.function,code:this.code,locals:Object.fromEntries(Object.entries(this.locals).map(([C,I])=>[C,String(I)]))};return this.offender&&(g.offender=this.offender),this.column!==void 0&&(g.column=this.column),g}toJson(){return JSON.stringify(this.toDict())}}class L{static encode(g){return g instanceof K?g.toDict():Array.isArray(g)?g.map(C=>L.encode(C)):typeof g=="object"&&g!==null?JSON.stringify(g):g}static stringify(g){return JSON.stringify(L.encode(g),(C,I)=>I instanceof K?I.toDict():I)}}const N=process.env.SF_LOG_LOCATION||"auto";let F=null,U=!1;const cn="__sf:",Cn=Error.prepareStackTrace,P=["/sf-veritas/","/@sailfish-ai/","/node_modules/","/dist/","/<","/internal/","node:"];function Vn(n){for(let g=0;g<P.length;g++)if(n.includes(P[g]))return!0;return!1}function T(n){let g=n;g.startsWith("file://")&&(g=g.substring(7)),process.platform==="win32"&&g.startsWith("/")&&g.length>2&&g[2]===":"&&(g=g.substring(1));try{return Gn.resolve(g)}catch{return n}}const hn=process.env.SF_LOG_LOCATION_WALK_FRAMES==="true";function M(n){const g=Error.stackTraceLimit;Error.stackTraceLimit=8,Error.prepareStackTrace=(l,e)=>e;const C={};Error.captureStackTrace(C,n);const I=C.stack;if(Error.prepareStackTrace=Cn,Error.stackTraceLimit=g,!I||I.length===0)return[null,null];for(let l=0;l<I.length;l++){const e=I[l].getFileName();if(e&&!Vn(e))return[T(e),I[l].getLineNumber()]}const t=I[0].getFileName();return t?[T(t),I[0].getLineNumber()]:[null,null]}function ln(n,g,C){if(N==="off")return[null,null];if(C&&(N==="auto"||N==="build-inject")){const[I,t,l]=(function(e){if(e.length===0)return[null,null,!1];const i=e[e.length-1];if(typeof i!="string"||!i.startsWith(cn))return[null,null,!1];const c=i.lastIndexOf(":");if(c<=5)return[null,null,!1];const s=i.substring(5,c),m=parseInt(i.substring(c+1),10);return isNaN(m)?[null,null,!1]:[s,m,!0]})(C);if(l)return[I,t];if(N==="build-inject")return[null,null]}if(N==="native"){const I=(function(){if(U)return F;U=!0;try{const t=require("../native/build/Release/sf_source_location.node");typeof t?.getCallerLocation=="function"&&(F=t)}catch{}return F})();if(I){const[t,l]=I.getCallerLocation(n??2);if(t)return[t,l]}if(N==="native"&&F)return[null,null]}return g?hn?M(g):(function(I){const t=Error.stackTraceLimit;Error.stackTraceLimit=1,Error.prepareStackTrace=(s,m)=>m;const l={};Error.captureStackTrace(l,I);const e=l.stack;if(Error.prepareStackTrace=Cn,Error.stackTraceLimit=t,!e||e.length===0)return[null,null];const i=e[0],c=i.getFileName();return c?[T(c),i.getLineNumber()]:[null,null]})(g):M(ln)}function p(n){if(n.length===0)return n;const g=n[n.length-1];return typeof g=="string"&&g.startsWith(cn)?n.slice(0,-1):n}const j=console.log.bind(console),O=console.error.bind(console),_=console.warn.bind(console),q=console.info.bind(console),$=console.debug.bind(console),G=j,x=O;let a=!1;const k=8192;function Nn(n){if(n===null)return"null";if(n===void 0)return"undefined";const g=typeof n;if(g==="string")return n;if(g==="number"||g==="boolean")return String(n);if(g==="bigint")return n.toString()+"n";if(g==="symbol")return n.toString();if(g==="function")return`[Function: ${n.name||"anonymous"}]`;if(n instanceof Error)return n.stack||`${n.name}: ${n.message}`;try{const C=new WeakSet,I=[],t=new Map,l=JSON.stringify(n,function(i,c){if(typeof c=="bigint")return c.toString()+"n";if(typeof c=="function")return`[Function: ${c.name||"anonymous"}]`;if(typeof c=="symbol")return c.toString();if(c===void 0)return"[undefined]";if(i!==""&&t.has(this)){const s=t.get(this);if(s>=20)return;t.set(this,s+1)}if(c!==null&&typeof c=="object"){if(C.has(c))return"[Circular]";for(;I.length>0&&I[I.length-1]!==this;)I.pop();if(I.length>=3)return Array.isArray(c)?`[Array(${c.length})]`:"[Object]";C.add(c),I.push(c),!Array.isArray(c)&&Object.keys(c).length>20&&t.set(c,0)}return c});if(l===void 0)return String(n);let e=l;if(t.size>0&&!Array.isArray(n)&&t.has(n)){const i=Object.keys(n).length;e=e.slice(0,-1)+`,"...":"${i-20} more keys"}`}return e.length>500?e.substring(0,500)+"...[truncated]":e}catch{return String(n)}}function w(n){if(n.length===0)return"";if(n.length===1&&typeof n[0]=="string"){const I=n[0];return I.length>k?I.substring(0,k)+"...[truncated]":I}let g,C=!0;for(let I=0;I<n.length;I++){const t=typeof n[I];if(t==="object"&&n[I]!==null||t==="function"||t==="symbol"){C=!1;break}}if(C){const I=new Array(n.length);for(let t=0;t<n.length;t++){const l=n[t];I[t]=l===null?"null":l===void 0?"undefined":typeof l=="string"?l:String(l)}g=I.join(" ")}else g=n.map(Nn).join(" ");return g.length>k?g.substring(0,k)+"...[truncated]":g}let X=0;function nn(n){return n=(n=(n=n.replace(/^webpack:\/\/[^\/]+\/\.?\//,"")).replace(/^.*\/pages\//,"pages/")).replace(/\.(js|ts)$/,"")}const Hn=50,S=new Map;function gn(n,g){if(S.size>=Hn){const C=S.keys().next().value;S.delete(C)}S.set(n,g)}function Jn(n){return n?.split("/").pop()||"<unknown>"}function on(n,g){if(!n||typeof n!="object")return!1;for(const C of Object.values(n))if(typeof C=="string"&&C.includes(g)||typeof C=="object"&&on(C,g))return!0;return!1}let Y,H,z,In=!1;function sn(n){if(!n)return;const g=n.toLowerCase().trim();return!!["1","true","yes","on"].includes(g)||!["0","false","no","off"].includes(g)&&void 0}function rn(){if(Y!==void 0)return Y;const n=process.env||{},g=sn(n.SF_IS_LOCAL);if(g!==void 0)return Y=g;const C=(n.SF_ENV||n.NODE_ENV||"").toLowerCase();if(["local","dev","development"].includes(C))return Y=!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(t=>!!n[t]))return Y=!1;const I=(fn.hostname?.()||n.HOSTNAME||"").toLowerCase();return Y=!(I!=="localhost"&&!I.endsWith(".local")&&!I.includes("local"))}function E(n,g,C){return new Promise(I=>{try{const t=new URL(n),l=(t.protocol==="https:"?Zn:mn).request({method:"GET",hostname:t.hostname,port:t.port||(t.protocol==="https:"?443:80),path:t.pathname+(t.search||""),headers:g},e=>{e.resume(),e.statusCode&&e.statusCode>=200&&e.statusCode<400?I("ok"):I("http_error")});l.on("error",()=>I("error")),l.setTimeout(C,()=>{l.destroy(),I("timeout")}),l.end()}catch{I("error")}})}function en(){if(H!==void 0)return H;const n=process.env.SF_FUNCSPAN_RUNTIME_ENABLED;if(n==="true"||n==="1")return H=!0,!0;if(n==="false"||n==="0")return H=!1,!1;try{const{isRuntimeModeConfigured:g}=require("../funcSpanConfigLoader");if(g&&g())return H=!0,!0}catch{}return H=!1,!1}function tn(){return z!==void 0||(z=!rn()),z}exports.CustomJSONEncoderForFrameInfo=L,exports.initializeExceptionInterceptor=function(n){b.getConfig().sfDebug&&G("Initializing Exception Interceptor...");try{const e=rn();n?.setSupplementalFields?.({isFromLocalService:e}),(async function(i){if(In)return;In=!0;const c=process.env||{};if(sn(c.SF_IS_LOCAL)===void 0)try{await(async function(s){const m=E("http://169.254.169.254/latest/meta-data/",{},s),d=E("http://metadata.google.internal/computeMetadata/v1/instance/",{"Metadata-Flavor":"Google"},s),r=E("http://169.254.169.254/metadata/instance?api-version=2021-02-01",{Metadata:"true"},s);return(await Promise.allSettled([m,d,r])).some(f=>f.status==="fulfilled"&&(f.value==="ok"||f.value==="http_error"))})(150)&&Y&&(Y=!1,i?.setSupplementalFields?.({isFromLocalService:!1}))}catch{}})(n).catch(()=>{})}catch{}const g=new pn.Worker(new URL("data:application/javascript;base64,Ly8gc3JjL2RlYnVnZ2VyV29ya2VyLnRzCmltcG9ydCB7IFNlc3Npb24gfSBmcm9tICJpbnNwZWN0b3IvcHJvbWlzZXMiOwppbXBvcnQgeyBwYXJlbnRQb3J0LCB3b3JrZXJEYXRhIH0gZnJvbSAid29ya2VyX3RocmVhZHMiOwpnbG9iYWwuc2ZEZWJ1ZyA9IHZvaWQgMDsKZ2xvYmFsLnN0YWNrRGVwdGhMb2NhbHMgPSB2b2lkIDA7Cmdsb2JhbC5ub2RlTW9kdWxlc1RvQ29sbGVjdExvY2FsVmFyaWFibGVzT24gPSB2b2lkIDA7CnZhciBzY3JpcHRTb3VyY2VDYWNoZSA9IC8qIEBfX1BVUkVfXyAqLyBuZXcgTWFwKCk7CnZhciBub25BcHBGcmFtZVBhdHRlcm5zID0gWwogIC9ub2RlOmludGVybmFsLywKICAvaW50ZXJuYWxcLy8sCiAgL25vZGVfbW9kdWxlcy8sCiAgL25vZGU6ZnMvCl07CmFzeW5jIGZ1bmN0aW9uIHByb2Nlc3NDYWxsRnJhbWVzKHNlc3Npb24sIGNhbGxGcmFtZXMsIGRlc2NyaXB0aW9uTGluZXMpIHsKICBjb25zdCBsaW1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Chsb2NhdGlvbiAmJiBsb2NhdGlvbi5zY3JpcHRJZCkgewogICAgICAgICAgY29uc3Qgc2NyaXB0SWQgPSBsb2NhdGlvbi5zY3JpcHRJZDsKICAgICAgICAgIHRyeSB7CiAgICAgICAgICAgIGxldCBzY3JpcHRTb3VyY2UgPSBzY3JpcHRTb3VyY2VDYWNoZS5nZXQoc2NyaXB0SWQpOwogICAgICAgICAgICBpZiAoc2NyaXB0U291cmNlID09PSB2b2lkIDApIHsKICAgICAgICAgICAgICBjb25zdCByZXN1bHQgPSBhd2FpdCBzZXNzaW9uLnBvc3QoCiAgICAgICAgICAgICAgICAiRGVidWdnZXIuZ2V0U2NyaXB0U291cmNlIiwKICAgICAgICAgICAgICAgIHsKICAgICAgICAgICAgICAgICAgc2NyaXB0SWQKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICApOwogICAgICAgICAgICAgIHNjcmlwdFNvdXJjZSA9IHJlc3VsdC5zY3JpcHRTb3VyY2U7CiAgICAgICAgICAgICAgc2NyaXB0U291cmNlQ2FjaGUuc2V0KHNjcmlwdElkLCBzY3JpcHRTb3VyY2UpOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGNvbnN0IHNvdXJjZUxpbmVzID0gc2NyaXB0U291cmNlLnNwbGl0KCJcbiIpOwogICAgICAgICAgICBjb2RlID0gc291cmNlTGluZXNbbG9jYXRpb24ubGluZU51bWJlcl0gfHwgIjxub3QgY2FwdHVyZWQ+IjsKICAgICAgICAgIH0gY2F0Y2ggKGVycikgewogICAgICAgICAgICBpZiAoZ2xvYmFsLnNmRGVidWcpIHsKICAgICAgICAgICAgICBjb25zb2xlLmVycm9yKCJbV29ya2VyXSBGYWlsZWQgdG8gZmV0Y2ggc2NyaXB0IHNvdXJjZToiLCBlcnIpOwogICAgICAgICAgICB9CiAgICAgICAgICB9CiAgICAgICAgfQogICAgICAgIGNvbnN0IGxvY2FscyA9IGxvY2FsU2NvcGU/Lm9iamVjdD8ub2JqZWN0SWQgPyBhd2FpdCBmZXRjaExvY2FsVmFyaWFibGVzKHNlc3Npb24sIGxvY2FsU2NvcGUub2JqZWN0Lm9iamVjdElkKSA6IHt9OwogICAgICAgIHJldHVybiB7CiAgICAgICAgICBmdW5jdGlvbjogZnVuY3Rpb25OYW1lIHx8ICI8YW5vbnltb3VzPiIsCiAgICAgICAgICBsb2NhbHMsCiAgICAgICAgICBmaWxlLAogICAgICAgICAgbGluZTogbG9jYXRpb24/LmxpbmVOdW1iZXIgfHwgMCwKICAgICAgICAgIGNvZGUKICAgICAgICB9OwogICAgICB9IGNhdGNoIChlcnJvcikgewogICAgICAgIGlmIChnbG9iYWwuc2ZEZWJ1ZykgewogICAgICAgICAgY29uc29sZS5lcnJvcigiW1dvcmtlcl0gRXJyb3IgcHJvY2Vzc2luZyBjYWxsIGZyYW1lOiIsIGVycm9yKTsKICAgICAgICB9CiAgICAgICAgcmV0dXJuIHsKICAgICAgICAgIGZ1bmN0aW9uOiAiPGVycm9yPiIsCiAgICAgICAgICBsb2NhbHM6IHt9LAogICAgICAgICAgZmlsZTogIjx1bmtub3duPiIsCiAgICAgICAgICBsaW5lOiAwLAogICAgICAgICAgY29kZTogIjxub3QgY2FwdHVyZWQ+IgogICAgICAgIH07CiAgICAgIH0KICAgIH0pCiAgKTsKICBwYXJlbnRQb3J0Py5wb3N0TWVzc2FnZSh7IHR5cGU6ICJleGNlcHRpb24iLCBmcmFtZXMgfSk7Cn0KYXN5bmMgZnVuY3Rpb24gaGFuZGxlUGF1c2VkKHNlc3Npb24sIHBhcmFtcykgewogIGNvbnN0IHsgcmVhc29uLCBkYXRhLCBjYWxsRnJhbWVzIH0gPSBwYXJhbXM7CiAgaWYgKHJlYXNvbiAhPT0gImV4Y2VwdGlvbiIgJiYgcmVhc29uICE9PSAicHJvbWlzZVJlamVjdGlvbiIpIHsKICAgIHJldHVybjsKICB9CiAgY29uc3Qgbm9uQXBwUGF0dGVybnMgPSBbCiAgICAvbm9kZTppbnRlcm5hbC8sCiAgICAva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0+IHsKfSwgMWU0KTsKZXhwb3J0IHsKICBwcm9jZXNzQ2FsbEZyYW1lcwp9Owo="),{workerData:{captureAllExceptions:!0}});let C=null;const I=new WeakMap;g.on("message",async e=>{if(typeof e=="string"&&b.getConfig().sfDebug&&G(`[Worker] ${e}`),e.readyToGetParameters&&g.postMessage({sfDebug:b.getConfig().sfDebug,stackDepthLocals:b.getConfig().stackDepthLocals,nodeModulesToCollectLocalVariablesOn:b.getConfig().nodeModulesToCollectLocalVariablesOn}),e.type==="exception"){const{frames:i}=e,c=C;if(!c)return;const s=(function(d){return d?d.split(`
3
+ `).slice(1).map(r=>{const f=/at (.+?) \((.+):(\d+):(\d+)\)/.exec(r)||/at (.+):(\d+):(\d+)/.exec(r);if(f){const[,W,B,A,Z]=f;return new K({function:W||"<anonymous>",locals:{},file:B||"<unknown>",line:parseInt(A,10)||0,code:"<not captured>",column:parseInt(Z)||0})}return new K({function:"<unknown>",locals:{},file:"<unknown>",line:0,code:"<not captured>",column:0})}):[]})(Q(c.stack)),m=(function(d,r){const f=[];let W=-1,B=-1;for(let A=0;A<d.length;A++){const Z=Jn(d[A].file);if(B=A,Z!=="<unknown>"){for(let u=0;u<r.length;u++){const y=r[u];if(on(y,Z)||typeof y.file=="string"&&y.file.includes(Z)){W=u,X=0,b.getConfig().sfDebug&&G(`✅ Matched Frame Found: ${Z} @ Debugger Frame ${u}`);break}}if(W!==-1)break}}if(W===-1)return X===10?(X=0,d):(++X,b.getConfig().sfDebug&&G(`"❌ No matching frame found. Checking once again, Attempt N ${X}"`),[]);b.getConfig().sfDebug&&G(`🔄 Merging from matched index ${W} onward...`);for(let A=0;A<r.length;A++){const Z=d[B+A],u=r[W+A];f.push(new K({function:u?.function||Z?.function||"<anonymous>",locals:u?.locals||Z?.locals||{},file:Z?.file||u?.file||"<unknown>",line:u?.line||Z?.line||0,code:u?.code||Z?.code||"<not captured>"}))}return f})(s,i||[]);if(m.length!==0){C=null;const d=b.getConfig().stackDepthCodeTraceDepth,r=d===-1?m:m.slice(0,d+1),f=Math.min(r.length,s.length);await Promise.all(Array.from({length:f},async(Z,u)=>{const y=await(async function(An,un,bn){const V=(function(o){o.startsWith("at ")&&(o=o.slice(3).trim());const h=o.match(/^(.*?)(:\d+)+(\.map)?$/);return h?h[1]:o})(An);if(!V||V==="<unknown>")return null;const J=V+".map";try{let o=S.get(J);if(o===void 0){const v=await Bn.readFile(J,"utf-8");o=v?JSON.parse(v):null,gn(J,o)}if(!o)return null;let h=new Wn.sourceMapExports.SourceMapConsumer(o).originalPositionFor({line:un,column:bn});if(V&&h.source){const v=nn(V),D=o.sources.findIndex(R=>nn(R)===v);if(D===-1)b.getConfig().sfDebug&&G(`Source file "${V}" not found in the source map.`);else{const R=o.sourcesContent[D],an=o.names.join(",");if(R)return{content:R.split(`
4
+ `).slice(h.line-1,h.line+20).join(`
5
+ `),name:an,file:h.source};b.getConfig().sfDebug&&G(`No source content available for file "${V}".`)}}return{content:o.sourcesContent[0],name:o.names[0],file:o.file}}catch(o){b.getConfig().sfDebug&&G(`Cant read/parse "${J}: Error - ".`,o),gn(J,null)}return null})(r[u].file,s[u].line,s[u].column);y&&(y.content!=null&&(r[u].code=y.content),y.file!=null&&(r[u].file=y.file))})),n.setOperationName("CollectExceptions");const W=c.message?`${c.name}: ${c.message}`:c.name;b.getConfig().sfDebug&&G("error message is : ",W);const B=b.ContextManager.getInstance(),A=I.get(c);A?(B.setTraceIdFor(A,A),B.runWithSession(A,()=>{B.setTraceId(A),n.doSend(W,r)})):n.doSend(W,r)}}}),g.on("error",e=>{x("[Worker Error]",e)}),g.on("exit",e=>{x(`[Worker] Exited with code ${e}`)}),g.unref();const t=Error;function l(...e){const i=new.target??l,c=Reflect.construct(t,e,i);try{const s=b.ContextManager.getInstance().getTraceId();I.set(c,s)}catch{}return t.captureStackTrace&&t.captureStackTrace(c,i),C=c,g.postMessage({type:"processException",error:c.message}),c}l.prototype=t.prototype,Object.setPrototypeOf(l,t),globalThis.Error=l},exports.initializeLogInterceptor=function(n){function g(e,i,c,s){const m=b.getGlobalConfigUnsafe();if(m?.logIgnoreRegex&&m.logIgnoreRegex.test(i))return;const[d,r]=ln(2,c,s);n.setOperationName("CollectLogs"),n.doSend([i,e,d,r])}const C=console.log=(...e)=>{if(a)j(...p(e));else{a=!0;try{const i=p(e);g("INFO",w(i),C,e),j(...i)}finally{a=!1}}},I=console.error=(...e)=>{if(a)O(...p(e));else{a=!0;try{const i=p(e);g("ERROR",w(i),I,e),O(...i)}finally{a=!1}}},t=console.warn=(...e)=>{if(a)_(...p(e));else{a=!0;try{const i=p(e);g("WARN",w(i),t,e),_(...i)}finally{a=!1}}},l=console.info=(...e)=>{if(a)q(...p(e));else{a=!0;try{const i=p(e);g("INFO",w(i),l,e),q(...i)}finally{a=!1}}};if(b.getConfig().logLevel==="DEBUG"){const e=console.debug=(...i)=>{if(a)$(...p(i));else{a=!0;try{const c=p(i);g("DEBUG",w(c),e,i),$(...c)}finally{a=!1}}}}},exports.internalError=x,exports.internalLog=G,exports.isProductionEnvironment=tn,exports.isRuntimeModeEnabled=en,exports.serializeJsonWithExclusions=function(n){const g={},C=[];if(n)for(const[I,t]of Object.entries(n))Yn(t)?g[I]=t:C.push(I);return{traitsJson:JSON.stringify(g),excludedFields:C}},exports.shouldEnableRuntimeHooks=function(){return!!en()&&(!tn()||(console.warn("[FuncSpan Runtime] DISABLED in production environment"),!1))},exports.stackToString=Q;
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("./contextManager-0D8uHQ1_.cjs"),p=require("./workerPoolSpanCapture-Bg5av6gn.cjs"),S=require("./runtimeConfig-CWpFWsmz.cjs"),ce=require("node:module"),A=require("fs"),P=require("http"),E=require("https"),de=require("./source-map-rHHEdpre.cjs"),le=require("fs/promises"),ue=require("path"),pe=require("glob"),T=require("worker_threads"),R=require("./funcSpanTransformer-D0W2t41q.cjs");function x(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const i=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const ge=x(A),W=x(le),N=x(ue);class w extends p.BaseTransmitter{constructor(){super(),this.setOperationName("IdentifyServiceDetails")}async doSend(e){if(!a.getConfig().serviceIdentificationReceived)try{this.send()}catch(t){a.getConfig().sfDebug&&console.error(" Error during service identification:",t)}}async send(){const e=`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./contextManager-qXvO_a5y.cjs"),g=require("./workerPoolSpanCapture-BUFN_RMW.cjs"),F=require("./runtimeConfig-C4_zc4Zg.cjs"),ye=require("node:module"),z=require("fs"),P=require("http"),k=require("https"),Se=require("./source-map-rHHEdpre.cjs"),Ie=require("fs/promises"),ve=require("path"),$e=require("glob"),O=require("worker_threads"),A=require("./funcSpanTransformer-D0W2t41q.cjs");function V(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const i=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const be=V(z),Q=V(Ie),E=V(ve);class R extends g.BaseTransmitter{constructor(){super(),this.setOperationName("IdentifyServiceDetails")}async doSend(e){if(!o.getConfig().serviceIdentificationReceived)try{this.send()}catch(t){o.getConfig().sfDebug&&console.error(" Error during service identification:",t)}}async send(){const e=`
2
2
  ${this.queryType} ${this.operationName}(
3
3
  $apiKey: String!,
4
4
  $timestampMs: String!,
@@ -36,11 +36,11 @@
36
36
  serviceRole: $serviceRole,
37
37
  )
38
38
  }
39
- `,t=a.getConfig(),i=this.getVariables({serviceIdentifier:t.serviceIdentifier,serviceVersion:t.serviceVersion,library:t.packageLibraryType,version:t.version,serviceAdditionalMetadata:t.serviceAdditionalMetadata,gitSha:t.gitSha||"",gitOrg:t.gitOrg||void 0,gitRepo:t.gitRepo||void 0,gitProvider:t.gitProvider||void 0,serviceDisplayName:t.serviceDisplayName||void 0,framework:t.framework||void 0,additionalFrameworks:t.additionalFrameworks.length>0?t.additionalFrameworks:void 0,serviceRole:t.serviceRole||void 0});p.nonBlockingPost(this.endpoint,this.operationName,e,i)}}class fe extends p.BaseTransmitter{serviceIdentifier=new w;constructor(){super(),this.setOperationName("CollectMetadata")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const e=setInterval(()=>{a.getConfig().serviceIdentificationReceived?clearInterval(e):this.serviceIdentifier.doSend({})},5e3);e&&typeof e=="object"&&"unref"in e&&e.unref()}async doSend(e,t,i,n){this.startBackgroundIdentify(),this.send(e,t,i,n)}async send(e,t,i,n){if(!t&&!n)throw new Error('Must pass in either traits or traits_json to "add_or_update_traits"');let o=[];if(!n){const c=S.serializeJsonWithExclusions(t);n=c.traitsJson,o=c.excludedFields}const f=this.getVariables({userId:e,traitsJson:n,excludedFields:o,override:i,library:a.getConfig().packageLibraryType,version:a.getConfig().version});p.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),f)}getQuery(){return`
39
+ `,t=o.getConfig(),i=this.getVariables({serviceIdentifier:t.serviceIdentifier,serviceVersion:t.serviceVersion,library:t.packageLibraryType,version:t.version,serviceAdditionalMetadata:t.serviceAdditionalMetadata,gitSha:t.gitSha||"",gitOrg:t.gitOrg||void 0,gitRepo:t.gitRepo||void 0,gitProvider:t.gitProvider||void 0,serviceDisplayName:t.serviceDisplayName||void 0,framework:t.framework||void 0,additionalFrameworks:t.additionalFrameworks.length>0?t.additionalFrameworks:void 0,serviceRole:t.serviceRole||void 0});g.nonBlockingPost(this.endpoint,this.operationName,e,i)}}class _e extends g.BaseTransmitter{serviceIdentifier=new R;constructor(){super(),this.setOperationName("CollectMetadata")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const e=setInterval(()=>{o.getConfig().serviceIdentificationReceived?clearInterval(e):this.serviceIdentifier.doSend({})},5e3);e&&typeof e=="object"&&"unref"in e&&e.unref()}async doSend(e,t,i,n){this.startBackgroundIdentify(),this.send(e,t,i,n)}async send(e,t,i,n){if(!t&&!n)throw new Error('Must pass in either traits or traits_json to "add_or_update_traits"');let a=[];if(!n){const d=F.serializeJsonWithExclusions(t);n=d.traitsJson,a=d.excludedFields}const p=this.getVariables({userId:e,traitsJson:n,excludedFields:a,override:i,library:o.getConfig().packageLibraryType,version:o.getConfig().version});g.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),p)}getQuery(){return`
40
40
  mutation ${this.operationName}($apiKey: String!, $serviceUuid: String!, $sessionId: String!, $userId: String!, $traitsJson: String!, $excludedFields: [String!]!, $library: String!, $timestampMs: String!, $version: String!, $override: Boolean!) {
41
41
  ${this.queryName}(apiKey: $apiKey, serviceUuid: $serviceUuid, sessionId: $sessionId, userId: $userId, traitsJson: $traitsJson, excludedFields: $excludedFields, library: $library, timestampMs: $timestampMs, version: $version, override: $override)
42
42
  }
43
- `}}class K{constructor(e){this.apiKey=e,this.metadataTransmitter=new fe}metadataTransmitter;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"');a.getConfig().sfDebug&&console.log(" [[DEBUG - addOrUpdateMetadata]] Starting operation"),a.getConfig().sfDebug&&console.log(" addOrUpdateMetadata...SENDING DATA...",e,t,i),this.metadataTransmitter.doSend(e,t,n,i)}}class B extends p.BaseTransmitter{serviceIdentifier=new w;constructor(){super()}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const e=setInterval(()=>{a.getConfig().serviceIdentificationReceived?clearInterval(e):this.serviceIdentifier.doSend({})},5e3);e&&typeof e=="object"&&"unref"in e&&e.unref()}async doSend(e){this.startBackgroundIdentify(),this.send(e)}async send(e){try{const t=Array.isArray(e)?e:[e,"default",null,null],i=this.getVariables({contents:t[0],level:t[1],sourceFile:t[2]||void 0,sourceLine:t[3]||void 0});p.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),i)}catch(t){a.getConfig().sfDebug&&console.error("🚨 Error in send():",t)}}getQuery(){return`
43
+ `}}class X{constructor(e){this.apiKey=e,this.metadataTransmitter=new _e}metadataTransmitter;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"');o.getConfig().sfDebug&&console.log(" [[DEBUG - addOrUpdateMetadata]] Starting operation"),o.getConfig().sfDebug&&console.log(" addOrUpdateMetadata...SENDING DATA...",e,t,i),this.metadataTransmitter.doSend(e,t,n,i)}}class J extends g.BaseTransmitter{serviceIdentifier=new R;constructor(){super()}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const e=setInterval(()=>{o.getConfig().serviceIdentificationReceived?clearInterval(e):this.serviceIdentifier.doSend({})},5e3);e&&typeof e=="object"&&"unref"in e&&e.unref()}async doSend(e){this.startBackgroundIdentify(),this.send(e)}async send(e){try{const t=Array.isArray(e)?e:[e,"default",null,null],i=this.getVariables({contents:t[0],level:t[1],sourceFile:t[2]||void 0,sourceLine:t[3]||void 0});g.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),i)}catch(t){o.getConfig().sfDebug&&console.error("🚨 Error in send():",t)}}getQuery(){return`
44
44
  ${this.queryType} ${this.operationName}(
45
45
  $apiKey: String!,
46
46
  $serviceUuid: String!,
@@ -64,7 +64,7 @@
64
64
  sourceLine: $sourceLine
65
65
  )
66
66
  }
67
- `}}class he extends p.BaseTransmitter{serviceIdentifier=new w;supplementalFields={};setSupplementalFields(e){this.supplementalFields={...this.supplementalFields,...e}}normalizedSupplementalForGraphQL(){const{isFromLocalService:e}=this.supplementalFields,t={};return e!==void 0&&(t.isFromLocalService=e),t}constructor(){super(),this.setOperationName("CollectExceptions")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const e=setInterval(()=>{a.getConfig().serviceIdentificationReceived?clearInterval(e):this.serviceIdentifier.doSend({})},5e3);e&&typeof e=="object"&&"unref"in e&&e.unref()}async doSend(e,t){this.startBackgroundIdentify(),this.send(e,t)}async send(e,t){a.getConfig().sfDebug&&console.log(" SENDING EXCEPTION...");const i=JSON.stringify(S.CustomJSONEncoderForFrameInfo.encode(t)),n=this.normalizedSupplementalForGraphQL(),o=this.getVariables({exceptionMessage:e,traceJson:i,reentrancyGuardPreactive:!1,library:a.getConfig().packageLibraryType,version:a.getConfig().version,...n});p.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),o)}getQuery(){return`
67
+ `}}class Ce extends g.BaseTransmitter{serviceIdentifier=new R;supplementalFields={};setSupplementalFields(e){this.supplementalFields={...this.supplementalFields,...e}}normalizedSupplementalForGraphQL(){const{isFromLocalService:e}=this.supplementalFields,t={};return e!==void 0&&(t.isFromLocalService=e),t}constructor(){super(),this.setOperationName("CollectExceptions")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const e=setInterval(()=>{o.getConfig().serviceIdentificationReceived?clearInterval(e):this.serviceIdentifier.doSend({})},5e3);e&&typeof e=="object"&&"unref"in e&&e.unref()}async doSend(e,t){this.startBackgroundIdentify(),this.send(e,t)}async send(e,t){o.getConfig().sfDebug&&console.log(" SENDING EXCEPTION...");const i=JSON.stringify(F.CustomJSONEncoderForFrameInfo.encode(t)),n=this.normalizedSupplementalForGraphQL(),a=this.getVariables({exceptionMessage:e,traceJson:i,reentrancyGuardPreactive:!1,library:o.getConfig().packageLibraryType,version:o.getConfig().version,...n});g.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),a)}getQuery(){return`
68
68
  mutation ${this.operationName}(
69
69
  $apiKey: String!,
70
70
  $serviceUuid: String!,
@@ -92,7 +92,7 @@
92
92
  parentSpanId: $parentSpanId
93
93
  )
94
94
  }
95
- `}}const j="getting request source code";var O=(r=>(r.UNKNOWN="unknown",r.ANONYMOUS="anonymous",r.NOT_CAPTURED="not captured",r))(O||{});const z="http:",me=ce.createRequire(require("node:url").pathToFileURL(__filename).href);let J=!1;function ye(){const r=a.getConfig().sfDebug;if(J)return void(r&&S.internalLog("[patchNodeHttpInbound] Already installed, skipping."));let e;J=!0;try{e=me("node:http"),r&&S.internalLog("[patchNodeHttpInbound] node:http required successfully.")}catch(n){return void S.internalError("Failed to require node:http:",n)}if(!e?.Server?.prototype)return void(r&&S.internalLog("[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}),r&&S.internalLog("[patchNodeHttpInbound] Patching http.Server.prototype.emit."),t.emit=function(n,...o){if(n!=="request")return r&&S.internalLog(`[patchNodeHttpInbound] Passing through event: ${n}`),i.call(this,n,...o);const f=o[0],c=o[1],s=(function(u){const m={};if(!u)return m;for(const[I,$]of Object.entries(u))$!=null&&(Array.isArray($)?m[I.toLowerCase()]=$.join(", "):m[I.toLowerCase()]=String($));return m})(f?.headers),l=s["x-sf3-rid"],g=s["x-sf3-functionspancaptureoverride"];r&&(S.internalLog("[patchNodeHttpInbound] Intercepted request event."),S.internalLog("[patchNodeHttpInbound] Inbound headers:",s),S.internalLog("[patchNodeHttpInbound] Trace header:",l),S.internalLog("[patchNodeHttpInbound] FuncSpan override header:",g));const d=a.ContextManager.getInstance();d.setTraceId(l);const h=d.getTraceId();r&&S.internalLog("[patchNodeHttpInbound] Context traceId set:",h);const y=()=>d.runWith({inboundHeaders:s,...l?{traceId:l}:{}},()=>{l&&d.setTraceId(l),r&&S.internalLog("[patchNodeHttpInbound] Running request handler in context.");const u=()=>{r&&S.internalLog("[patchNodeHttpInbound] Response finished/closed for traceId:",d.getTraceId())};return c.on("finish",u),c.on("close",u),i.call(this,n,f,c)});if(!g)return y();try{return p.funcspanOverrideStorage.run(g,()=>y())}catch{return y()}}):r&&S.internalLog("[patchNodeHttpInbound] Already patched, skipping.")}class Se extends B{constructor(){super(),this.setOperationName("DomainsToNotPassHeaderTo")}async doSend(e){this.send(e)}async send(e){const t=`
95
+ `}}const Y="X-Sf4-Prid",Z="getting request source code";var L=(r=>(r.UNKNOWN="unknown",r.ANONYMOUS="anonymous",r.NOT_CAPTURED="not captured",r))(L||{});const ee="http:",Fe=ye.createRequire(require("node:url").pathToFileURL(__filename).href);let te=!1;function we(){const r=o.getConfig().sfDebug;if(te)return void(r&&F.internalLog("[patchNodeHttpInbound] Already installed, skipping."));let e;te=!0;try{e=Fe("node:http"),r&&F.internalLog("[patchNodeHttpInbound] node:http required successfully.")}catch(n){return void F.internalError("Failed to require node:http:",n)}if(!e?.Server?.prototype)return void(r&&F.internalLog("[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}),r&&F.internalLog("[patchNodeHttpInbound] Patching http.Server.prototype.emit."),t.emit=function(n,...a){if(n!=="request")return r&&F.internalLog(`[patchNodeHttpInbound] Passing through event: ${n}`),i.call(this,n,...a);const p=a[0],d=a[1],s=(function(I){const h={};if(!I)return h;for(const[f,$]of Object.entries(I))$!=null&&(Array.isArray($)?h[f.toLowerCase()]=$.join(", "):h[f.toLowerCase()]=String($));return h})(p?.headers),u=s["x-sf3-rid"],l=s["x-sf3-functionspancaptureoverride"];r&&(F.internalLog("[patchNodeHttpInbound] Intercepted request event."),F.internalLog("[patchNodeHttpInbound] Inbound headers:",s),F.internalLog("[patchNodeHttpInbound] Trace header:",u),F.internalLog("[patchNodeHttpInbound] FuncSpan override header:",l));const c=o.ContextManager.getInstance();c.setTraceId(u);const y=c.getTraceId();r&&F.internalLog("[patchNodeHttpInbound] Context traceId set:",y);const v=()=>c.runWith({inboundHeaders:s,...u?{traceId:u}:{}},()=>{u&&c.setTraceId(u),r&&F.internalLog("[patchNodeHttpInbound] Running request handler in context.");const I=()=>{r&&F.internalLog("[patchNodeHttpInbound] Response finished/closed for traceId:",c.getTraceId())};return d.on("finish",I),d.on("close",I),i.call(this,n,p,d)});if(!l)return v();try{return g.funcspanOverrideStorage.run(l,()=>v())}catch{return v()}}):r&&F.internalLog("[patchNodeHttpInbound] Already patched, skipping.")}const ne=new Map;function H(r,e){const t=`${r}|${e}`;let i=ne.get(t);return i||(i=new RegExp(r,e),ne.set(t,i)),i}function M(r,e){let t,i;if(typeof r=="string"?t=r:typeof URL<"u"&&r instanceof URL?t=r.href:typeof Request<"u"&&r instanceof Request?t=r.url:r!=null&&typeof r.toString=="function"&&(t=r.toString()),!t)return!1;try{i=new URL(t,"http://localhost/")}catch{return!1}const{hostname:n,pathname:a,port:p,protocol:d}=i;if(!/^https?:$/.test(d))return!1;const s=n.startsWith("www.")?n.slice(4).toLowerCase():n.toLowerCase();return e.some(u=>{const l=String(u||"").replace(/^[a-zA-Z]+:\/\//,"");if(!l)return!1;let[c,y]=l.split("/",2),v="";c.includes(":")&&([c,v]=c.split(":"));const I=H(`^${c.replace(/\./g,"\\.").replace(/\*/g,".*")}$`,"i"),h=s.startsWith("www.")?s.slice(4):s;if(v&&p!==v)return!1;if(c.startsWith("*.")){const f=c.slice(2).toLowerCase();return s===f||h===f||s.endsWith("."+f)?y?H(`^/${y.replace(/\*/g,".*").replace(/\/$/,"")}`,"i").test(a):!0:!1}return!I.test(h)&&!I.test(s)?!1:y?H(`^/${y.replace(/\*/g,".*").replace(/\/$/,"")}`,"i").test(a):!0})}class De extends J{constructor(){super(),this.setOperationName("DomainsToNotPassHeaderTo")}async doSend(e){this.send(e)}async send(e){const t=`
96
96
  ${this.queryType} ${this.operationName}(
97
97
  $apiKey: String!,
98
98
  $serviceUuid: String!,
@@ -104,7 +104,7 @@
104
104
  domains: $domains
105
105
  )
106
106
  }
107
- `,i={apiKey:this.apiKey,serviceUuid:this.serviceUUID,domains:e};p.nonBlockingPost(this.endpoint,this.operationName,t,i)}}class ve extends p.BaseTransmitter{serviceIdentifier=new w;constructor(){super(),this.setOperationName("CollectNetworkHops")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const e=setInterval(()=>{a.getConfig().serviceIdentificationReceived?clearInterval(e):this.serviceIdentifier.doSend({})},5e3);e&&typeof e=="object"&&"unref"in e&&e.unref()}async doSend(e){this.startBackgroundIdentify(),this.send(e)}async send(e){const{name:t,column:i,line:n,entrypoint:o,retryWithoutTraceId:f}=e,c=this.getVariables({name:t,column:i,line:n,entrypoint:o,retryWithoutTraceId:f});p.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),c)}getQuery(){return`
107
+ `,i={apiKey:this.apiKey,serviceUuid:this.serviceUUID,domains:e};g.nonBlockingPost(this.endpoint,this.operationName,t,i)}}class Ne extends g.BaseTransmitter{serviceIdentifier=new R;constructor(){super(),this.setOperationName("CollectNetworkHops")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const e=setInterval(()=>{o.getConfig().serviceIdentificationReceived?clearInterval(e):this.serviceIdentifier.doSend({})},5e3);e&&typeof e=="object"&&"unref"in e&&e.unref()}async doSend(e){this.startBackgroundIdentify(),this.send(e)}async send(e){const{name:t,column:i,line:n,entrypoint:a,retryWithoutTraceId:p}=e,d=this.getVariables({name:t,column:i,line:n,entrypoint:a,retryWithoutTraceId:p});g.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),d)}getQuery(){return`
108
108
  mutation ${this.operationName}(
109
109
  $apiKey: String!,
110
110
  $sessionId: String!,
@@ -128,15 +128,15 @@
128
128
  ${this.operationName==="CollectNetworkHops"?", retryWithoutTraceId: $retryWithoutTraceId":""}
129
129
  )
130
130
  }
131
- `}}class Ie extends p.BaseTransmitter{serviceIdentifier=new w;constructor(){super(),this.setOperationName("CollectNetworkRequest")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const e=setInterval(()=>{a.getConfig().serviceIdentificationReceived?clearInterval(e):this.serviceIdentifier.doSend({})},5e3);e&&typeof e=="object"&&"unref"in e&&e.unref()}async doSend(e){this.startBackgroundIdentify(),this.send(e)}getQuery(){return`
131
+ `}}class Ee extends g.BaseTransmitter{serviceIdentifier=new R;constructor(){super(),this.setOperationName("CollectNetworkRequest")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const e=setInterval(()=>{o.getConfig().serviceIdentificationReceived?clearInterval(e):this.serviceIdentifier.doSend({})},5e3);e&&typeof e=="object"&&"unref"in e&&e.unref()}async doSend(e){this.startBackgroundIdentify(),this.send(e)}getQuery(){return`
132
132
  mutation ${this.operationName}(
133
133
  $data: NetworkRequestInput!
134
134
  ) {
135
135
  ${this.queryName}(
136
136
  data: $data)
137
137
  }
138
- `}async send(e){const t={data:{...e}};await p.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),t)}}const L=[400,403];class $e{HEADER_TRACING="X-Sf3-Rid";HEADER_LOG_GUARD="reentrancy_guard_logging_preactive";HEADER_PRINT_GUARD="reentrancy_guard_print_preactive";HEADER_EXCEPTION_GUARD="reentrancy_guard_exception_preactive";contextManager;constructor(e=[]){this.contextManager=a.ContextManager.getInstance(),e?.forEach(t=>{typeof t=="string"&&t.trim()&&this.contextManager.getExcludedDomains().add(t)}),a.getConfig().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 o=t.toLowerCase();for(const[f,c]of Object.entries(e))if(f.toLowerCase()===o){i=c;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,o]=t;return{filePath:i,line:parseInt(n,10),column:parseInt(o,10)}}async getOriginalPosition(e,t,i){let n={source:e,line:t,column:i,name:null};if(e.includes("://"))return{originalPos:n};const o=e+".map";try{const f=JSON.parse(A.readFileSync(o,"utf-8"));let c=(await new de.sourceMapExports.SourceMapConsumer(f)).originalPositionFor({line:t,column:i});c.source&&(n=c)}catch(f){a.getConfig().sfDebug&&console.error(`Could not read/parse map file at ${o}:`,f)}return{originalPos:n}}captureFirstUserLines(e,t=10,i=!1){const n=a.getConfig().sfDebug?10:t,o=Error.stackTraceLimit;Error.stackTraceLimit=Math.max(o,n);const f=new Error(j);j in Error&&Error.captureStackTrace(f,this.captureFirstUserLines);const c=S.stackToString(f.stack);Error.stackTraceLimit=o;const s=c.split(`
139
- `).slice(1),l=[];for(const g of s)if(!(g.includes("node:internal")||g.includes("internal/modules")||g.includes("internal/process")||g.includes("node_modules")||g.includes(".next/server/chunks")||g.includes("RequestInterceptor")||g.includes("contextManager")||g.includes("setupConfig"))&&(l.push(g.trim()),l.length>=t))break;for(const g of l){const d=this.parseStackFrame(g);d?(async()=>{const{originalPos:h}=await this.getOriginalPosition(d.filePath,d.line,d.column);if(h){a.getConfig().sfDebug&&console.log("[RequestInterceptor] First user code line:",h);const y={line:h.line?.toString()||O.UNKNOWN,column:h.column?.toString()||O.NOT_CAPTURED,name:h.name||O.NOT_CAPTURED,entrypoint:h.source,retryWithoutTraceId:i};e.doSend(y)}})():a.getConfig().sfDebug&&console.error("Could not parse stack line:",g)}}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!a.DEFAULT_DOMAINS_TO_EXCLUDE.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):a.getConfig().sfDebug&&console.error(`[RequestInterceptor] Excluded domain: ${i}`),n}addTracingHeader(e,t){const i=p.getFuncspanOverride();if(i){const c=p.parseHeaderOverride(i);if(c&&c.sample_rate===0)return void(a.getConfig().sfDebug&&console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${t}`))}const n=this.contextManager.getOrSetSfTraceId(),o=this.contextManager.getOrSetPageVisitUUID(),f=a.v4();e.set(this.HEADER_TRACING,`${n}/${o}/${f}`),a.getConfig().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${t}`)}patchFetch(e,t){const i=globalThis.fetch;typeof i=="function"?globalThis.fetch=async(n,o)=>{const f=new Headers(o?.headers);if(f.get(this.HEADER_LOG_GUARD)==="true"||f.get(this.HEADER_PRINT_GUARD)==="true"||f.get(this.HEADER_EXCEPTION_GUARD)==="true")return i(n,o);this.captureFirstUserLines(e);const c=Date.now();let s;typeof n=="string"||n instanceof URL?s=n.toString():n instanceof Request?(s=n.url,n.headers.forEach((u,m)=>{f.set(m,u)})):a.getConfig().sfDebug&&console.error("[Sailfish RequestInterceptor] Invalid fetch input."),a.getConfig().sfDebug&&console.log("[RequestInterceptor] Fetching request to:",s);const l=new URL(s).hostname,g=new Headers(f),d=this.addTracingHeaders(f,s),h={...o,headers:f};let y;try{let u=!1;this.addTracingHeaders(g,s),y=await i(s,h),d&&L.includes(y.status)?(y=await i(s,{...o,headers:g}),u=!0,this.captureFirstUserLines(e,10,u)):this.contextManager.addSupportedDomains(l);const m=Date.now();a.getConfig().sfDebug&&console.log(`[RequestInterceptor] Fetch completed: ${s}, Status: ${y.status}, Duration: ${m-c}ms`);const{sessionId:I,pageVisitId:$,requestId:b}=this.extractIdsFromTraceHeader(f),v=a.getConfig(),F={apiKey:v.apiKey,requestId:b,pageVisitId:$,recordingSessionId:I,serviceUuid:v.serviceUUID,timestampStart:c.toString(),timestampEnd:m.toString(),responseCode:y.status,success:!0,error:null,url:s,method:h.method||"GET",retryWithoutTraceId:u,parentSpanId:a.getCurrentFunctionSpanId()};if(v.captureRequestHeaders){const _={};f.forEach((C,D)=>{_[D]=C}),F.requestHeaders=_}if(v.captureResponseHeaders){const _={};y.headers.forEach((C,D)=>{_[D]=C}),F.responseHeaders=_}if(v.captureRequestBody&&o?.body)try{const _=typeof o.body=="string"?o.body:JSON.stringify(o.body);F.requestBody=_.length>v.requestBodyLimitBytes?_.substring(0,v.requestBodyLimitBytes)+"...[truncated]":_}catch{}if(v.captureResponseBody)try{const _=y.clone(),C=await _.text();F.responseBody=C.length>v.responseBodyLimitBytes?C.substring(0,v.responseBodyLimitBytes)+"...[truncated]":C}catch{}return t.doSend(F),y}catch(u){const m=Date.now();a.getConfig().sfDebug&&console.error(`[RequestInterceptor] Fetch failed: ${s}, Error: ${u}, Duration: ${m-c}ms`)}}:a.getConfig().sfDebug&&console.error("[RequestInterceptor] Fetch not available.")}setHeader(e,t,i){e instanceof Headers?e.set(t,i):e[t]=i}addTracingHeadersToPlainObject(e,t){const i=new URL(t).hostname,n=this.shouldPropagateHeaders(i);if(n){const o=p.getFuncspanOverride();if(o){const l=p.parseHeaderOverride(o);if(l&&l.sample_rate===0)return a.getConfig().sfDebug&&console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${t}`),!1}const f=this.contextManager.getOrSetSfTraceId(),c=this.contextManager.getOrSetPageVisitUUID(),s=a.v4();e[this.HEADER_TRACING]=`${f}/${c}/${s}`,a.getConfig().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${t}`)}else a.getConfig().sfDebug&&console.error(`[RequestInterceptor] Excluded domain: ${i}`);return n}patchHttp(e,t){if(a.getConfig().sfDebug&&console.log("[RequestInterceptor] Initializing HTTP/HTTPS request patch..."),!P||typeof P.request!="function")return void(a.getConfig().sfDebug&&console.log("[RequestInterceptor] HTTP/HTTPS not available."));const i=P.request.bind(P),n=E.request.bind(E),o=(s,l,g,d=z)=>{let h,y;if(typeof s=="string"||s instanceof URL){const u=typeof s=="string"?new URL(s):s;h={...typeof l=="object"&&l!==null?l:{},protocol:u.protocol||d,hostname:u.hostname,port:u.port||void 0,path:u.pathname+u.search},y=typeof l=="function"?l:g}else h={...s},h.protocol||(h.protocol=d),y=typeof l=="function"?l:void 0;return h.headers||(h.headers={}),[h,y]},f=(s,l,g)=>{const[d,h]=o(s,l,g,z);try{const u=`${d.protocol}//${d.hostname}`;this.addTracingHeadersToPlainObject(d.headers,u),this.captureFirstUserLines(e)}catch(u){a.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTP request options:",u)}let y=!1;return i(d,u=>{const m=`${d.protocol}//${d.hostname}`;if(this.shouldPropagateHeaders(new URL(m).hostname)&&L.includes(u.statusCode||0)){const v={...d,headers:{...d.headers}};delete v.headers[this.HEADER_TRACING],i(v,h),y=!0,this.captureFirstUserLines(e,10,y)}const{sessionId:I,pageVisitId:$,requestId:b}=this.extractIdsFromTraceHeader(d.headers);t.doSend({apiKey:a.getConfig().apiKey,requestId:b,pageVisitId:$,recordingSessionId:I,serviceUuid:a.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:u.statusCode||0,success:!!u.statusCode&&u.statusCode<400,error:null,url:m,method:d.method||"GET",retryWithoutTraceId:y,parentSpanId:a.getCurrentFunctionSpanId()}),h?.(u)})},c=(s,l,g)=>{const[d,h]=o(s,l,g,"https:");try{const u=`${d.protocol}//${d.hostname}`;this.addTracingHeadersToPlainObject(d.headers,u),this.captureFirstUserLines(e)}catch(u){a.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTPS request options:",u)}let y=!1;return n(d,u=>{const m=`${d.protocol}//${d.hostname}`;if(this.shouldPropagateHeaders(new URL(m).hostname)&&L.includes(u.statusCode||0)){const v={...d,headers:{...d.headers}};delete v.headers[this.HEADER_TRACING],n(v,h),y=!0,this.captureFirstUserLines(e,10,y)}const{sessionId:I,pageVisitId:$,requestId:b}=this.extractIdsFromTraceHeader(d.headers);t.doSend({apiKey:a.getConfig().apiKey,requestId:b,pageVisitId:$,recordingSessionId:I,serviceUuid:a.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:u.statusCode||0,success:!!u.statusCode&&u.statusCode<400,error:null,url:m,method:d.method||"GET",retryWithoutTraceId:y,parentSpanId:a.getCurrentFunctionSpanId()}),h?.(u)})};P.request=f,E.request=c,P.get=(s,l,g)=>{const d=f(s,l,g);return d.end(),d},E.get=(s,l,g)=>{const d=c(s,l,g);return d.end(),d},a.getConfig().sfDebug&&console.log("✅ HTTP and HTTPS request/get methods patched globally.")}tryPatch(e,t){try{require.resolve(t),e()}catch{}}getExcludedDomains(){return[...this.contextManager.getExcludedDomains()]}}class _e extends B{constructor(){super(),this.setOperationName("UpdateServiceDetails")}async doSend(){this.send()}async send(){const e=`
138
+ `}async send(e){const t={data:{...e}};await g.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),t)}}const B=[400,403];function x(r,e){return e!=="none"&&(e==="all"||r==="GET"||r==="HEAD"||r==="OPTIONS")}class Te{HEADER_TRACING="X-Sf3-Rid";HEADER_LOG_GUARD="reentrancy_guard_logging_preactive";HEADER_PRINT_GUARD="reentrancy_guard_print_preactive";HEADER_EXCEPTION_GUARD="reentrancy_guard_exception_preactive";contextManager;constructor(e=[]){this.contextManager=o.ContextManager.getInstance(),e?.forEach(t=>{typeof t=="string"&&t.trim()&&this.contextManager.getExcludedDomains().add(t)}),o.getConfig().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 a=t.toLowerCase();for(const[p,d]of Object.entries(e))if(p.toLowerCase()===a){i=d;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,a]=t;return{filePath:i,line:parseInt(n,10),column:parseInt(a,10)}}async getOriginalPosition(e,t,i){let n={source:e,line:t,column:i,name:null};if(e.includes("://"))return{originalPos:n};const a=e+".map";try{const p=JSON.parse(z.readFileSync(a,"utf-8"));let d=(await new Se.sourceMapExports.SourceMapConsumer(p)).originalPositionFor({line:t,column:i});d.source&&(n=d)}catch(p){o.getConfig().sfDebug&&console.error(`Could not read/parse map file at ${a}:`,p)}return{originalPos:n}}captureFirstUserLines(e,t=10,i=!1){const n=o.getConfig().sfDebug?10:t,a=Error.stackTraceLimit;Error.stackTraceLimit=Math.max(a,n);const p=new Error(Z);Z in Error&&Error.captureStackTrace(p,this.captureFirstUserLines);const d=F.stackToString(p.stack);Error.stackTraceLimit=a;const s=d.split(`
139
+ `).slice(1),u=[];for(const l of s)if(!(l.includes("node:internal")||l.includes("internal/modules")||l.includes("internal/process")||l.includes("node_modules")||l.includes(".next/server/chunks")||l.includes("RequestInterceptor")||l.includes("contextManager")||l.includes("setupConfig"))&&(u.push(l.trim()),u.length>=t))break;for(const l of u){const c=this.parseStackFrame(l);c?(async()=>{const{originalPos:y}=await this.getOriginalPosition(c.filePath,c.line,c.column);if(y){o.getConfig().sfDebug&&console.log("[RequestInterceptor] First user code line:",y);const v={line:y.line?.toString()||L.UNKNOWN,column:y.column?.toString()||L.NOT_CAPTURED,name:y.name||L.NOT_CAPTURED,entrypoint:y.source,retryWithoutTraceId:i};e.doSend(v)}})():o.getConfig().sfDebug&&console.error("Could not parse stack line:",l)}}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){const t=o.getConfig(),i=t.domainsToPropagateHeadersTo,n=t.domainsToNotPropagateHeadersTo||[],a=Array.from(o.DEFAULT_DOMAINS_TO_EXCLUDE);return!!M(e,i)&&!(n.length>0&&M(e,n))&&!M(e,a)}addTracingHeaders(e,t){const i=this.shouldPropagateHeaders(t);if(i)this.addTracingHeader(e,t);else if(o.getConfig().sfDebug){let n=t;try{n=new URL(t).hostname}catch{}console.error(`[RequestInterceptor] Excluded domain: ${n}`)}return i}deriveTraceBaseAndParent(e){const t=e.split("/").filter(Boolean);return t.length<2?{base:e,parent:e}:{base:`${t[0]}/${t[1]}`,parent:e}}addTracingHeader(e,t){const i=g.getFuncspanOverride();if(i){const s=g.parseHeaderOverride(i);if(s&&s.sample_rate===0)return void(o.getConfig().sfDebug&&console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${t}`))}const n=this.contextManager.getOrSetSfTraceId(),{base:a,parent:p}=this.deriveTraceBaseAndParent(n),d=o.v4();e.set(this.HEADER_TRACING,`${a}/${d}`),e.set(Y,p),o.getConfig().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${t}`)}patchFetch(e,t){const i=globalThis.fetch;typeof i=="function"?globalThis.fetch=async(n,a)=>{const p=new Headers(a?.headers);if(p.get(this.HEADER_LOG_GUARD)==="true"||p.get(this.HEADER_PRINT_GUARD)==="true"||p.get(this.HEADER_EXCEPTION_GUARD)==="true")return i(n,a);this.captureFirstUserLines(e);const d=Date.now();let s,u="GET";if(typeof n=="string"||n instanceof URL)s=n.toString(),u=(a?.method||"GET").toUpperCase();else{if(!(n instanceof Request))return o.getConfig().sfDebug&&console.error("[Sailfish RequestInterceptor] Invalid fetch input."),i(n,a);s=n.url,u=n.method.toUpperCase(),n.headers.forEach((m,w)=>{p.set(w,m)})}o.getConfig().sfDebug&&console.log("[RequestInterceptor] Fetching request to:",s);let l="unknown";try{l=new URL(s).hostname}catch{return o.getConfig().sfDebug&&console.warn(`[RequestInterceptor] Could not parse URL '${s}' — passing through without tracing headers.`),i(n,a)}const c=new Headers(p),y=this.addTracingHeaders(p,s),v=m=>n instanceof Request?[new Request(n,{...a||{},headers:m}),void 0]:[s,{...a,headers:m}],I=o.getConfig().retryOnClientError;let h,f=!1;try{const[m,w]=v(p);if(h=await i(m,w),y&&x(u,I)&&B.includes(h.status)){const[b,_]=v(c);h=await i(b,_),f=!0;try{this.captureFirstUserLines(e,10,f)}catch(C){o.getConfig().sfDebug&&console.error("[RequestInterceptor] captureFirstUserLines (retry) failed:",C)}}else try{this.contextManager.addSupportedDomains(l)}catch(b){o.getConfig().sfDebug&&console.error("[RequestInterceptor] addSupportedDomains failed:",b)}}catch(m){const w=Date.now();o.getConfig().sfDebug&&console.error(`[RequestInterceptor] Fetch failed: ${s}, Error: ${m}, Duration: ${w-d}ms`);try{const{sessionId:b,pageVisitId:_,requestId:C}=this.extractIdsFromTraceHeader(p),T=o.getConfig();t.doSend({apiKey:T.apiKey,requestId:C,pageVisitId:_,recordingSessionId:b,serviceUuid:T.serviceUUID,timestampStart:d.toString(),timestampEnd:w.toString(),responseCode:0,success:!1,error:m instanceof Error?m.message:typeof m=="string"?m:JSON.stringify(m),url:s,method:u,retryWithoutTraceId:f,parentSpanId:o.getCurrentFunctionSpanId()})}catch(b){o.getConfig().sfDebug&&console.error("[RequestInterceptor] Error telemetry send failed:",b)}throw m}const $=Date.now();try{o.getConfig().sfDebug&&console.log(`[RequestInterceptor] Fetch completed: ${s}, Status: ${h.status}, Duration: ${$-d}ms`);const{sessionId:m,pageVisitId:w,requestId:b}=this.extractIdsFromTraceHeader(p),_=o.getConfig(),C={apiKey:_.apiKey,requestId:b,pageVisitId:w,recordingSessionId:m,serviceUuid:_.serviceUUID,timestampStart:d.toString(),timestampEnd:$.toString(),responseCode:h.status,success:!0,error:null,url:s,method:u,retryWithoutTraceId:f,parentSpanId:o.getCurrentFunctionSpanId()};if(_.captureRequestHeaders){const S={};p.forEach((N,D)=>{S[D]=N}),C.requestHeaders=S}if(_.captureResponseHeaders){const S={};h.headers.forEach((N,D)=>{S[D]=N}),C.responseHeaders=S}if(_.captureRequestBody&&a?.body){const S=a.body,N=_.requestBodyLimitBytes;try{if(typeof S=="string")C.requestBody=S.length>N?S.substring(0,N)+"...[truncated]":S;else if(S instanceof URLSearchParams){const D=S.toString();C.requestBody=D.length>N?D.substring(0,N)+"...[truncated]":D}else if(typeof ArrayBuffer<"u"&&(S instanceof ArrayBuffer||ArrayBuffer.isView(S))){const D=S.byteLength??S.byteLength;C.requestBody=`[binary body, ${D} bytes — not captured]`}else if(typeof Blob<"u"&&S instanceof Blob)C.requestBody=`[Blob, ${S.size} bytes, type=${S.type||"unknown"} — not captured]`;else if(typeof FormData<"u"&&S instanceof FormData)C.requestBody="[FormData — not captured]";else if(typeof ReadableStream<"u"&&S instanceof ReadableStream)C.requestBody="[ReadableStream — not captured]";else{const D=JSON.stringify(S);D&&D!=="{}"&&(C.requestBody=D.length>N?D.substring(0,N)+"...[truncated]":D)}}catch{}}let T;if(_.captureResponseBody){const S=(h.headers.get("content-type")||"").toLowerCase();if(!S||S.includes("json")||S.includes("xml")||S.includes("text/")||S.includes("javascript")||S.includes("ecmascript")||S.includes("x-www-form-urlencoded")||S.includes("application/graphql")){const N=h.clone(),D=_.responseBodyLimitBytes;T=(async()=>{try{const q=await N.text(),me=q.length>D?q.substring(0,D)+"...[truncated]":q;try{t.doSend({...C,responseBody:me})}catch{}}catch{}})(),T.catch(()=>{})}else C.responseBody=`[non-text body, content-type=${S} — not captured]`}T||t.doSend(C)}catch(m){o.getConfig().sfDebug&&console.error("[RequestInterceptor] Post-fetch telemetry failed (response still returned):",m)}return h}:o.getConfig().sfDebug&&console.error("[RequestInterceptor] Fetch not available.")}setHeader(e,t,i){e instanceof Headers?e.set(t,i):e[t]=i}addTracingHeadersToPlainObject(e,t){const i=this.shouldPropagateHeaders(t);if(i){const n=g.getFuncspanOverride();if(n){const u=g.parseHeaderOverride(n);if(u&&u.sample_rate===0)return o.getConfig().sfDebug&&console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${t}`),!1}const a=this.contextManager.getOrSetSfTraceId(),{base:p,parent:d}=this.deriveTraceBaseAndParent(a),s=o.v4();e[this.HEADER_TRACING]=`${p}/${s}`,e[Y]=d,o.getConfig().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${t}`)}else if(o.getConfig().sfDebug){let n=t;try{n=new URL(t).hostname}catch{}console.error(`[RequestInterceptor] Excluded domain: ${n}`)}return i}patchHttp(e,t){if(o.getConfig().sfDebug&&console.log("[RequestInterceptor] Initializing HTTP/HTTPS request patch..."),!P||typeof P.request!="function")return void(o.getConfig().sfDebug&&console.log("[RequestInterceptor] HTTP/HTTPS not available."));const i=P.request.bind(P),n=k.request.bind(k),a=(s,u,l,c=ee)=>{let y,v;if(typeof s=="string"||s instanceof URL){const I=typeof s=="string"?new URL(s):s;y={...typeof u=="object"&&u!==null?u:{},protocol:I.protocol||c,hostname:I.hostname,port:I.port||void 0,path:I.pathname+I.search},v=typeof u=="function"?u:l}else y={...s},y.protocol||(y.protocol=c),v=typeof u=="function"?u:void 0;return y.headers||(y.headers={}),[y,v]},p=(s,u,l)=>{const[c,y]=a(s,u,l,ee);try{const f=`${c.protocol}//${c.hostname}`;this.addTracingHeadersToPlainObject(c.headers,f),this.captureFirstUserLines(e)}catch(f){o.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTP request options:",f)}const v=(c.method||"GET").toUpperCase(),I=o.getConfig().retryOnClientError,h=(f,$,m)=>{try{const{sessionId:w,pageVisitId:b,requestId:_}=this.extractIdsFromTraceHeader(c.headers);t.doSend({apiKey:o.getConfig().apiKey,requestId:_,pageVisitId:b,recordingSessionId:w,serviceUuid:o.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:f.statusCode||0,success:!!f.statusCode&&f.statusCode<400,error:null,url:$,method:v,retryWithoutTraceId:m,parentSpanId:o.getCurrentFunctionSpanId()})}catch{}y?.(f)};return i(c,f=>{const $=`${c.protocol}//${c.hostname}`;let m=!1;try{m=this.shouldPropagateHeaders($)}catch{m=!1}if(m&&x(v,I)&&B.includes(f.statusCode||0)){f.resume();try{const{sessionId:b,pageVisitId:_,requestId:C}=this.extractIdsFromTraceHeader(c.headers);t.doSend({apiKey:o.getConfig().apiKey,requestId:C,pageVisitId:_,recordingSessionId:b,serviceUuid:o.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:f.statusCode||0,success:!1,error:null,url:$,method:v,retryWithoutTraceId:!1,parentSpanId:o.getCurrentFunctionSpanId()})}catch{}try{this.captureFirstUserLines(e,10,!0)}catch{}const w={...c,headers:{...c.headers}};return delete w.headers[this.HEADER_TRACING],void i(w,b=>{h(b,$,!0)}).end()}h(f,$,!1)})},d=(s,u,l)=>{const[c,y]=a(s,u,l,"https:");try{const f=`${c.protocol}//${c.hostname}`;this.addTracingHeadersToPlainObject(c.headers,f),this.captureFirstUserLines(e)}catch(f){o.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTPS request options:",f)}const v=(c.method||"GET").toUpperCase(),I=o.getConfig().retryOnClientError,h=(f,$,m)=>{try{const{sessionId:w,pageVisitId:b,requestId:_}=this.extractIdsFromTraceHeader(c.headers);t.doSend({apiKey:o.getConfig().apiKey,requestId:_,pageVisitId:b,recordingSessionId:w,serviceUuid:o.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:f.statusCode||0,success:!!f.statusCode&&f.statusCode<400,error:null,url:$,method:v,retryWithoutTraceId:m,parentSpanId:o.getCurrentFunctionSpanId()})}catch{}y?.(f)};return n(c,f=>{const $=`${c.protocol}//${c.hostname}`;let m=!1;try{m=this.shouldPropagateHeaders($)}catch{m=!1}if(m&&x(v,I)&&B.includes(f.statusCode||0)){f.resume();try{const{sessionId:b,pageVisitId:_,requestId:C}=this.extractIdsFromTraceHeader(c.headers);t.doSend({apiKey:o.getConfig().apiKey,requestId:C,pageVisitId:_,recordingSessionId:b,serviceUuid:o.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:f.statusCode||0,success:!1,error:null,url:$,method:v,retryWithoutTraceId:!1,parentSpanId:o.getCurrentFunctionSpanId()})}catch{}try{this.captureFirstUserLines(e,10,!0)}catch{}const w={...c,headers:{...c.headers}};return delete w.headers[this.HEADER_TRACING],void n(w,b=>{h(b,$,!0)}).end()}h(f,$,!1)})};P.request=p,k.request=d,P.get=(s,u,l)=>{const c=p(s,u,l);return c.end(),c},k.get=(s,u,l)=>{const c=d(s,u,l);return c.end(),c},o.getConfig().sfDebug&&console.log("✅ HTTP and HTTPS request/get methods patched globally.")}tryPatch(e,t){try{require.resolve(t),e()}catch{}}getExcludedDomains(){return[...this.contextManager.getExcludedDomains()]}}class Pe extends J{constructor(){super(),this.setOperationName("UpdateServiceDetails")}async doSend(){this.send()}async send(){const e=`
140
140
  ${this.queryType} ${this.operationName}(
141
141
  $apiKey: String!,
142
142
  $serviceUuid: String!,
@@ -178,7 +178,7 @@
178
178
  serviceRole: $serviceRole,
179
179
  )
180
180
  }
181
- `,t=a.getConfig(),i=this.getVariables({serviceIdentifier:t.serviceIdentifier,serviceVersion:t.serviceVersion,serviceAdditionalMetadata:t.serviceAdditionalMetadata,gitSha:t.gitSha||"",gitOrg:t.gitOrg||void 0,gitRepo:t.gitRepo||void 0,gitProvider:t.gitProvider||void 0,serviceDisplayName:t.serviceDisplayName||void 0,infrastructureType:t.infrastructureType||void 0,infrastructureDetails:t.infrastructureDetails||void 0,setupInterceptorsFile:t.setupInterceptorsFile||void 0,setupInterceptorsLine:t.setupInterceptorsLine||void 0,framework:t.framework||void 0,additionalFrameworks:t.additionalFrameworks?.length>0?t.additionalFrameworks:void 0,serviceRole:t.serviceRole||void 0});p.nonBlockingPost(this.endpoint,this.operationName,e,i)}}class be{rootPaths;fileConfigs=new Map;functionConfigs=new Map;directoryConfigs=new Map;hasSailfishFiles=!1;runtimeModeEnabled=!1;debug;constructor(e=[process.cwd()],t=!1){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)ge.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?p.getEnvConfig():p.getDefaultConfig(),n=this._getDirectoryConfig(e),o=N.normalize(e),f=this.fileConfigs.get(o)||{};let c={};if(t){const s=this.functionConfigs.get(o);s&&(c=s.get(t)||{})}return p.mergeConfigs(i,n,f,c)}hasRuntimeMode(){return this.runtimeModeEnabled}async _walkDirectory(e,t){try{const i=await W.readdir(e,{withFileTypes:!0});for(const n of i){const o=N.join(e,n.name);n.isFile()&&n.name===".sailfish"?t.push(o):n.name==="node_modules"||n.isDirectory()&&n.name.startsWith(".")&&n.name!==".sailfish"||n.isDirectory()&&await this._walkDirectory(o,t)}}catch(i){this.debug&&console.error(`[FuncSpan ConfigLoader] Error walking directory ${e}:`,i)}}async _loadConfigFile(e){try{const t=await W.readFile(e,"utf-8"),i=N.dirname(e);let n=null;try{n=JSON.parse(t)}catch{try{n=require("toml").parse(t)}catch{try{n=require("js-yaml").load(t)}catch(o){return void(this.debug&&console.error(`[FuncSpan ConfigLoader] Failed to parse ${e} as JSON, TOML, or YAML:`,o))}}}if(!n)return;n.runtime_mode===!0&&(this.runtimeModeEnabled=!0,this.debug&&console.log(`[FuncSpan ConfigLoader] Runtime mode ENABLED in ${e}`)),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,o]of Object.entries(t))try{const f=N.join(e,n),c=await pe.glob(f,{absolute:!0,nodir:!0,ignore:["**/node_modules/**","**/.git/**"]});this.debug&&console.log(`[FuncSpan ConfigLoader] Pattern '${n}' matched ${c.length} files`);for(const s of c){const l=N.normalize(s),g=p.mergeConfigs(i,o);this.fileConfigs.set(l,g),this.debug&&c.length<=5&&console.log(`[FuncSpan ConfigLoader] - ${s}`)}}catch(f){this.debug&&console.error(`[FuncSpan ConfigLoader] Error expanding glob '${n}':`,f)}}_storeFunctionConfigs(e,t,i){for(const[n,o]of Object.entries(t)){const f=n.split("::");if(f.length!==2){this.debug&&console.warn(`[FuncSpan ConfigLoader] Invalid function pattern '${n}' (expected format: 'file.ts::functionName')`);continue}const[c,s]=f,l=N.normalize(N.join(e,c));this.functionConfigs.has(l)||this.functionConfigs.set(l,new Map);const g=this.functionConfigs.get(l),d=p.mergeConfigs(i,o);g.set(s,d),this.debug&&console.log(`[FuncSpan ConfigLoader] Function config: ${l}::${s}`)}}async _resolveInheritance(){}_getDirectoryConfig(e){let t=N.dirname(N.normalize(e));const i=[];for(;t&&t!==N.dirname(t);){const n=this.directoryConfigs.get(t);n&&i.unshift(n),t=N.dirname(t)}return i.reduce((n,o)=>p.mergeConfigs(n,o),{})}}const se="__sf_globalConfigLoader";function ae(){return globalThis[se]??null}async function V(r,e){const t=new be(r,e);(function(i){globalThis[se]=i})(t),await t.loadAllConfigs()}function Q(r,e){const t=ae();return t?t.getConfig(r,e):(process.env.SF_DEBUG==="true"&&console.log("[FuncSpan ConfigLoader] Config loader not initialized, using default config (disabled)"),p.getDefaultConfig())}function X(){return ae()!==null}const Fe=["readFile","writeFile","appendFile","readdir","stat","lstat","fstat","access","open","close","read","write","chmod","mkdir","rmdir","unlink","rename"],Y=["lookup","resolve","resolve4","resolve6","resolveAny","resolveMx","resolveNs","resolveTxt","reverse"],Ce=["pbkdf2","randomBytes","scrypt","generateKeyPair"],Ne=["gzip","gunzip","deflate","inflate","deflateRaw","inflateRaw","brotliCompress","brotliDecompress"];let Z=!1;function De(r){if(typeof r!="string")return!1;const e=process.env.SF_FUNCSPAN_JSONL_FILE;if(e&&r.includes(e))return!0;const t=process.env.SF_WORKER_POOL_JSONL_FILE;return!(!t||!r.includes(t))}let ee=!1;function te(r){if(typeof r!="string")return!1;if(r==="localhost"||r==="127.0.0.1"||r==="::1")return!0;try{const e=process.env.API_GRAPHQL_ENDPOINT;if(e&&r===new URL(e).hostname)return!0}catch{}return!1}function Pe(){if(!ee)try{let r;if(typeof require>"u")return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Skipping dns patching in pure ESM environment (require unavailable)"));try{r=require("node:dns")}catch(e){return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Failed to require dns module:",e))}if(r.__sf_worker_pool_patched__)return;Object.defineProperty(r,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of Y)if(typeof r[e]=="function"){const t=r[e];r[e]=function(...i){return p.isSendingInternalTelemetry()?t.apply(this,i):te(i[0])?t.apply(this,i):typeof i[i.length-1]=="function"?p.captureWorkerPoolOperation("dns",e,t,i,this):t.apply(this,i)},Object.defineProperty(r[e],"name",{value:e,writable:!1})}(function(e){if(!e.promises)return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises not available, skipping"));if(!e.promises.__sf_worker_pool_patched__){Object.defineProperty(e.promises,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Y)if(typeof e.promises[t]=="function"){const i=e.promises[t];e.promises[t]=function(...n){return p.isSendingInternalTelemetry()?i.apply(this,n):te(n[0])?i.apply(this,n):p.captureWorkerPoolPromiseOperation("dns",t,i,n,this)},Object.defineProperty(e.promises[t],"name",{value:t,writable:!1})}process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises module patched successfully")}})(r),ee=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns module patched successfully")}catch(r){console.error("[WorkerPool] Error patching dns module:",r)}}let ne=!1,re=!1,H=!1;function ie(){if(H)return;const r=process.env.SF_DEBUG==="true";r&&console.log("[WorkerPool] Initializing worker pool patching..."),p.isModuleTrackingEnabled("fs")&&(r&&console.log("[WorkerPool] Patching fs module..."),(function(){if(!Z)try{const e=require("node:fs");if(e.__sf_worker_pool_patched__)return;Object.defineProperty(e,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Fe)if(typeof e[t]=="function"){const i=e[t];e[t]=function(...n){return De(n[0])?i.apply(this,n):typeof n[n.length-1]=="function"?p.captureWorkerPoolOperation("fs",t,i,n,this):i.apply(this,n)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}Z=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] fs module patched successfully")}catch(e){console.error("[WorkerPool] Error patching fs module:",e)}})()),p.isModuleTrackingEnabled("dns")&&(r&&console.log("[WorkerPool] Patching dns module..."),Pe()),p.isModuleTrackingEnabled("crypto")&&(r&&console.log("[WorkerPool] Patching crypto module..."),(function(){if(!ne)try{const e=require("node:crypto");if(e.__sf_worker_pool_patched__)return;Object.defineProperty(e,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Ce)if(typeof e[t]=="function"){const i=e[t];e[t]=function(...n){return typeof n[n.length-1]=="function"?p.captureWorkerPoolOperation("crypto",t,i,n,this):i.apply(this,n)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}ne=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] crypto module patched successfully")}catch(e){console.error("[WorkerPool] Error patching crypto module:",e)}})()),p.isModuleTrackingEnabled("zlib")&&(r&&console.log("[WorkerPool] Patching zlib module..."),(function(){if(!re)try{const e=require("node:zlib");if(e.__sf_worker_pool_patched__)return;Object.defineProperty(e,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Ne)if(typeof e[t]=="function"){const i=e[t];e[t]=function(...n){return typeof n[n.length-1]=="function"?p.captureWorkerPoolOperation("zlib",t,i,n,this):i.apply(this,n)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}re=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] zlib module patched successfully")}catch(e){console.error("[WorkerPool] Error patching zlib module:",e)}})()),H=!0,r&&console.log("[WorkerPool] Worker pool patching initialized")}function oe(){return H}let U=!1,q=!1,M=null;function k(r){const e=a.getGlobalConfigUnsafe(),t=e?.sfDebug||!1;t&&console.log("[FuncSpan] captureSpanData called for:",{function:r.functionName,file:r.filePath,duration:`${r.duration}ms`,async:r.async,error:r.error,spanId:r.spanId});const i={functionName:r.functionName,filePath:r.filePath,metadata:r.metadata,args:r.args,result:r.result,error:r.error,duration:r.duration,durationNs:r.durationNs,async:r.async,spanId:r.spanId,parentSpanId:r.parentSpanId};process.env.SF_FUNCSPAN_CONSOLE_OUTPUT==="true"&&console.log(`
182
- 📊 Function Span:`,{function:`${r.functionName} (${r.filePath}:${r.metadata.line}:${r.metadata.column})`,duration:`${r.duration.toFixed(2)}ms`,arguments:r.args,result:r.error?`Error: ${r.error}`:r.result,spanId:r.spanId,parentSpanId:r.parentSpanId||"none"});const n=process.env.SF_FUNCSPAN_JSONL_FILE;if(n)try{const o=n==="true"||n==="1"?"funcspans.jsonl":n,f=Date.now(),c=process.hrtime.bigint(),s=BigInt(r.startTimeNs),l=Number(c-s)/1e6,g=new Date(f-l).toISOString(),d=JSON.stringify({timestamp:g,functionName:r.functionName,filePath:r.filePath,line:r.metadata.line,column:r.metadata.column,duration:r.duration,durationNs:r.durationNs,startTimeNs:r.startTimeNs,arguments:r.args,returnValue:r.error?{error:String(r.error)}:r.result,spanId:r.spanId,parentSpanId:r.parentSpanId,async:r.async,pid:r.pid,threadId:r.threadId})+`
183
- `;A.appendFileSync(o,d,"utf-8")}catch(o){console.error("[FuncSpan] Error writing to JSONL file:",o)}if(t&&console.log("[FuncSpan] Sending function span to transmitter:",i),process.env.SF_FUNCSPAN_SKIP_BACKEND!=="true")try{(M||(M=new p.FunctionSpanTransmitter),M).send([i]),t&&console.log("[FuncSpan] Function span sent successfully")}catch(o){t&&console.error("[FuncSpan] Error sending function span:",o)}}exports.ContextManager=a.ContextManager,exports.getCurrentFunctionSpanId=a.getCurrentFunctionSpanId,exports.runWithContext=a.runWithContext,exports.clearFuncspanOverride=p.clearFuncspanOverride,exports.getDefaultConfig=p.getDefaultConfig,exports.getEnvConfig=p.getEnvConfig,exports.getFuncspanOverride=p.getFuncspanOverride,exports.parseHeaderOverride=p.parseHeaderOverride,exports.setFuncspanOverride=p.setFuncspanOverride,exports.isProductionEnvironment=S.isProductionEnvironment,exports.isRuntimeModeEnabled=S.isRuntimeModeEnabled,exports.shouldEnableRuntimeHooks=S.shouldEnableRuntimeHooks,exports.setSkipTypeScriptPlugin=R.setSkipTypeScriptPlugin,exports.transformFunctionSpans=R.transformFunctionSpans,exports.transformFunctionSpansSync=R.transformFunctionSpansSync,exports.addOrUpdateMetadata=function(r,e={},t,i=!1){const n=a.getConfig();new K(n.apiKey).addOrUpdateMetadata(r,e,t,i)},exports.captureFunctionSpan=function(r,e,t,i){const n=function(...o){const f=a.getGlobalConfigUnsafe(),c=f?.sfDebug||!1;c&&console.log(`[FuncSpan] captureFunctionSpan wrapper called for ${t}::${e}`);const s=(function(m,I){const $=p.getFuncspanOverride();if($){const b=p.parseHeaderOverride($);if(b)return process.env.SF_DEBUG==="true"&&console.log(`[FuncSpan] Using HTTP header override for ${m}::${I}`),b}try{return Q(m,I)}catch{return{sample_rate:process.env.SF_FUNCSPAN_SAMPLE_RATE?parseFloat(process.env.SF_FUNCSPAN_SAMPLE_RATE):1,capture_arguments:!0,capture_return_value:!0,arg_limit_mb:1,return_limit_mb:1,enable_sampling:!1,autocapture_all_child_functions:!1,capture_sf_veritas:!1,parse_json_strings:!1}}})(t,e);if(c&&console.log(`[FuncSpan] Config for ${t}::${e}:`,s),s.enable_sampling&&s.sample_rate<1&&Math.random()>s.sample_rate)return c&&console.log(`[FuncSpan] Skipping ${e} due to sampling`),r.apply(this,o);if(s.sample_rate===0)return c&&console.log(`[FuncSpan] Skipping ${e} - sample_rate is 0.0`),r.apply(this,o);c&&console.log(`[FuncSpan] Capturing function span for ${e}`);const l=a.ContextManager.getInstance(),g=l.getCurrentFunctionSpanId(),d=a.v4();l.setCurrentFunctionSpanId(d);const h=process.hrtime.bigint(),y=Date.now();let u=null;s.capture_arguments&&(u={},i.paramNames.forEach((m,I)=>{I<o.length&&(u[m]=o[I])}),u&&s.arg_limit_mb>0&&(u=p.truncateToLimit(u,s.arg_limit_mb)));try{const m=r.apply(this,o);if(m&&typeof m.then=="function")return g?l.setCurrentFunctionSpanId(g):l.clearCurrentFunctionSpanId(),m.then(F=>{const _=process.hrtime.bigint(),C=Date.now(),D=Number(_-h);let G=null;return s.capture_return_value&&s.return_limit_mb>0&&(G=p.truncateToLimit(F,s.return_limit_mb)),k({functionName:e,filePath:t,metadata:i,args:u,result:G,error:null,duration:C-y,durationNs:D,startTimeNs:h.toString(),async:!0,spanId:d,parentSpanId:g,pid:process.pid,threadId:T.threadId}),F},F=>{const _=process.hrtime.bigint(),C=Date.now(),D=Number(_-h);throw k({functionName:e,filePath:t,metadata:i,args:u,result:null,error:F?.message||String(F),duration:C-y,durationNs:D,startTimeNs:h.toString(),async:!0,spanId:d,parentSpanId:g,pid:process.pid,threadId:T.threadId}),F});const I=process.hrtime.bigint(),$=Date.now(),b=Number(I-h);let v=null;return s.capture_return_value&&s.return_limit_mb>0&&(v=p.truncateToLimit(m,s.return_limit_mb)),k({functionName:e,filePath:t,metadata:i,args:u,result:v,error:null,duration:$-y,durationNs:b,startTimeNs:h.toString(),async:!1,spanId:d,parentSpanId:g,pid:process.pid,threadId:T.threadId}),g?l.setCurrentFunctionSpanId(g):l.clearCurrentFunctionSpanId(),m}catch(m){const I=process.hrtime.bigint(),$=Date.now(),b=Number(I-h);throw k({functionName:e,filePath:t,metadata:i,args:u,result:null,error:m?.message||String(m),duration:$-y,durationNs:b,startTimeNs:h.toString(),async:!1,spanId:d,parentSpanId:g,pid:process.pid,threadId:T.threadId}),g?l.setCurrentFunctionSpanId(g):l.clearCurrentFunctionSpanId(),m}};Object.defineProperty(n,"name",{value:e,writable:!1});for(const o in r)r.hasOwnProperty(o)&&(n[o]=r[o]);return n},exports.getGlobalConfig=Q,exports.identify=function(r,e,t,i=!1){const n=a.getConfig();new K(n.apiKey).identify(r,e,t,i)},exports.initializeConfigLoader=V,exports.initializeWorkerPoolPatching=ie,exports.isAlreadyInstrumented=function(r){return!!r.includes("captureFunctionSpan(")||!!r.includes("@sailfish-ai/sf-veritas")||!(!r.includes("/* @sailfish-instrumented */")&&!r.includes("// @sailfish-instrumented"))},exports.isConfigLoaderInitialized=X,exports.isSetupInterceptorsInitialized=function(){return U},exports.isWorkerPoolInitialized=oe,exports.setupInterceptors=function(r){if(q)console.warn("[setupInterceptors] ⚠️ Recursive call detected and blocked!");else if(!U){q=!0,p.registerShutdownHooks();try{let e,t;const i=S.stackToString(new Error().stack);if(i){const c=i.split(`
184
- `)[2]||"",s=c.match(/\((.+):(\d+):\d+\)/)||c.match(/at (.+):(\d+):\d+/);s&&(e=s[1],t=parseInt(s[2],10))}if(!r||!r.apiKey){const c=`The required API Key is not provided: ${JSON.stringify(r)}`;console.error(c)}const{config:n}=a.getOrCreateConfig(r);if(a.backfillGitInfoAsync(n).catch(()=>{}),e&&(n.setupInterceptorsFile=e),t&&(n.setupInterceptorsLine=t),n.sfDebug&&console.log("Updated configuration after applying options:",n),!n.apiKey||!n.apiGraphqlEndpoint){const c=`The required config is not provided: ${JSON.stringify(n)}`;throw console.error(c),new Error(c)}X()||V(void 0,n.sfDebug).catch(c=>{n.sfDebug&&console.error("[FuncSpan] Failed to initialize config loader:",c)}),process.env.SF_WORKER_POOL_DISABLED==="true"?n.sfDebug&&console.log("[setupInterceptors] Worker pool patching DISABLED (SF_WORKER_POOL_DISABLED=true)"):oe()||(ie(),n.sfDebug&&console.log("[setupInterceptors] Worker pool patching initialized (DNS tracking enabled)"));const o=new B;o.setServiceUUID(n.serviceUUID),S.initializeLogInterceptor(o),(function(c=[]){const s=new $e(c);new Se().doSend(s.getExcludedDomains());const l=new ve,g=new Ie;s.patchFetch(l,g),s.patchHttp(l,g)})(n.domainsToNotPropagateHeadersTo);const f=new he;f.setServiceUUID(n.serviceUUID),S.initializeExceptionInterceptor(f),ye(),new _e().send(),U=!0,n.sfDebug&&console.log("[setupInterceptors] ✅ Initialization complete")}finally{q=!1}}};
181
+ `,t=o.getConfig(),i=this.getVariables({serviceIdentifier:t.serviceIdentifier,serviceVersion:t.serviceVersion,serviceAdditionalMetadata:t.serviceAdditionalMetadata,gitSha:t.gitSha||"",gitOrg:t.gitOrg||void 0,gitRepo:t.gitRepo||void 0,gitProvider:t.gitProvider||void 0,serviceDisplayName:t.serviceDisplayName||void 0,infrastructureType:t.infrastructureType||void 0,infrastructureDetails:t.infrastructureDetails||void 0,setupInterceptorsFile:t.setupInterceptorsFile||void 0,setupInterceptorsLine:t.setupInterceptorsLine||void 0,framework:t.framework||void 0,additionalFrameworks:t.additionalFrameworks?.length>0?t.additionalFrameworks:void 0,serviceRole:t.serviceRole||void 0});g.nonBlockingPost(this.endpoint,this.operationName,e,i)}}class Re{rootPaths;fileConfigs=new Map;functionConfigs=new Map;directoryConfigs=new Map;hasSailfishFiles=!1;runtimeModeEnabled=!1;debug;constructor(e=[process.cwd()],t=!1){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)be.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?g.getEnvConfig():g.getDefaultConfig(),n=this._getDirectoryConfig(e),a=E.normalize(e),p=this.fileConfigs.get(a)||{};let d={};if(t){const s=this.functionConfigs.get(a);s&&(d=s.get(t)||{})}return g.mergeConfigs(i,n,p,d)}hasRuntimeMode(){return this.runtimeModeEnabled}async _walkDirectory(e,t){try{const i=await Q.readdir(e,{withFileTypes:!0});for(const n of i){const a=E.join(e,n.name);n.isFile()&&n.name===".sailfish"?t.push(a):n.name==="node_modules"||n.isDirectory()&&n.name.startsWith(".")&&n.name!==".sailfish"||n.isDirectory()&&await this._walkDirectory(a,t)}}catch(i){this.debug&&console.error(`[FuncSpan ConfigLoader] Error walking directory ${e}:`,i)}}async _loadConfigFile(e){try{const t=await Q.readFile(e,"utf-8"),i=E.dirname(e);let n=null;try{n=JSON.parse(t)}catch{try{n=require("toml").parse(t)}catch{try{n=require("js-yaml").load(t)}catch(a){return void(this.debug&&console.error(`[FuncSpan ConfigLoader] Failed to parse ${e} as JSON, TOML, or YAML:`,a))}}}if(!n)return;n.runtime_mode===!0&&(this.runtimeModeEnabled=!0,this.debug&&console.log(`[FuncSpan ConfigLoader] Runtime mode ENABLED in ${e}`)),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,a]of Object.entries(t))try{const p=E.join(e,n),d=await $e.glob(p,{absolute:!0,nodir:!0,ignore:["**/node_modules/**","**/.git/**"]});this.debug&&console.log(`[FuncSpan ConfigLoader] Pattern '${n}' matched ${d.length} files`);for(const s of d){const u=E.normalize(s),l=g.mergeConfigs(i,a);this.fileConfigs.set(u,l),this.debug&&d.length<=5&&console.log(`[FuncSpan ConfigLoader] - ${s}`)}}catch(p){this.debug&&console.error(`[FuncSpan ConfigLoader] Error expanding glob '${n}':`,p)}}_storeFunctionConfigs(e,t,i){for(const[n,a]of Object.entries(t)){const p=n.split("::");if(p.length!==2){this.debug&&console.warn(`[FuncSpan ConfigLoader] Invalid function pattern '${n}' (expected format: 'file.ts::functionName')`);continue}const[d,s]=p,u=E.normalize(E.join(e,d));this.functionConfigs.has(u)||this.functionConfigs.set(u,new Map);const l=this.functionConfigs.get(u),c=g.mergeConfigs(i,a);l.set(s,c),this.debug&&console.log(`[FuncSpan ConfigLoader] Function config: ${u}::${s}`)}}async _resolveInheritance(){}_getDirectoryConfig(e){let t=E.dirname(E.normalize(e));const i=[];for(;t&&t!==E.dirname(t);){const n=this.directoryConfigs.get(t);n&&i.unshift(n),t=E.dirname(t)}return i.reduce((n,a)=>g.mergeConfigs(n,a),{})}}const fe="__sf_globalConfigLoader";function he(){return globalThis[fe]??null}async function re(r,e){const t=new Re(r,e);(function(i){globalThis[fe]=i})(t),await t.loadAllConfigs()}function ie(r,e){const t=he();return t?t.getConfig(r,e):(process.env.SF_DEBUG==="true"&&console.log("[FuncSpan ConfigLoader] Config loader not initialized, using default config (disabled)"),g.getDefaultConfig())}function oe(){return he()!==null}const ke=["readFile","writeFile","appendFile","readdir","stat","lstat","fstat","access","open","close","read","write","chmod","mkdir","rmdir","unlink","rename"],se=["lookup","resolve","resolve4","resolve6","resolveAny","resolveMx","resolveNs","resolveTxt","reverse"],Oe=["pbkdf2","randomBytes","scrypt","generateKeyPair"],Ue=["gzip","gunzip","deflate","inflate","deflateRaw","inflateRaw","brotliCompress","brotliDecompress"];let ae=!1;function Le(r){if(typeof r!="string")return!1;const e=process.env.SF_FUNCSPAN_JSONL_FILE;if(e&&r.includes(e))return!0;const t=process.env.SF_WORKER_POOL_JSONL_FILE;return!(!t||!r.includes(t))}let ce=!1;function de(r){if(typeof r!="string")return!1;if(r==="localhost"||r==="127.0.0.1"||r==="::1")return!0;try{const e=process.env.API_GRAPHQL_ENDPOINT;if(e&&r===new URL(e).hostname)return!0}catch{}return!1}function qe(){if(!ce)try{let r;if(typeof require>"u")return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Skipping dns patching in pure ESM environment (require unavailable)"));try{r=require("node:dns")}catch(e){return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Failed to require dns module:",e))}if(r.__sf_worker_pool_patched__)return;Object.defineProperty(r,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of se)if(typeof r[e]=="function"){const t=r[e];r[e]=function(...i){return g.isSendingInternalTelemetry()?t.apply(this,i):de(i[0])?t.apply(this,i):typeof i[i.length-1]=="function"?g.captureWorkerPoolOperation("dns",e,t,i,this):t.apply(this,i)},Object.defineProperty(r[e],"name",{value:e,writable:!1})}(function(e){if(!e.promises)return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises not available, skipping"));if(!e.promises.__sf_worker_pool_patched__){Object.defineProperty(e.promises,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of se)if(typeof e.promises[t]=="function"){const i=e.promises[t];e.promises[t]=function(...n){return g.isSendingInternalTelemetry()?i.apply(this,n):de(n[0])?i.apply(this,n):g.captureWorkerPoolPromiseOperation("dns",t,i,n,this)},Object.defineProperty(e.promises[t],"name",{value:t,writable:!1})}process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises module patched successfully")}})(r),ce=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns module patched successfully")}catch(r){console.error("[WorkerPool] Error patching dns module:",r)}}let ue=!1,le=!1,j=!1;function pe(){if(j)return;const r=process.env.SF_DEBUG==="true";r&&console.log("[WorkerPool] Initializing worker pool patching..."),g.isModuleTrackingEnabled("fs")&&(r&&console.log("[WorkerPool] Patching fs module..."),(function(){if(!ae)try{const e=require("node:fs");if(e.__sf_worker_pool_patched__)return;Object.defineProperty(e,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of ke)if(typeof e[t]=="function"){const i=e[t];e[t]=function(...n){return Le(n[0])?i.apply(this,n):typeof n[n.length-1]=="function"?g.captureWorkerPoolOperation("fs",t,i,n,this):i.apply(this,n)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}ae=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] fs module patched successfully")}catch(e){console.error("[WorkerPool] Error patching fs module:",e)}})()),g.isModuleTrackingEnabled("dns")&&(r&&console.log("[WorkerPool] Patching dns module..."),qe()),g.isModuleTrackingEnabled("crypto")&&(r&&console.log("[WorkerPool] Patching crypto module..."),(function(){if(!ue)try{const e=require("node:crypto");if(e.__sf_worker_pool_patched__)return;Object.defineProperty(e,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Oe)if(typeof e[t]=="function"){const i=e[t];e[t]=function(...n){return typeof n[n.length-1]=="function"?g.captureWorkerPoolOperation("crypto",t,i,n,this):i.apply(this,n)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}ue=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] crypto module patched successfully")}catch(e){console.error("[WorkerPool] Error patching crypto module:",e)}})()),g.isModuleTrackingEnabled("zlib")&&(r&&console.log("[WorkerPool] Patching zlib module..."),(function(){if(!le)try{const e=require("node:zlib");if(e.__sf_worker_pool_patched__)return;Object.defineProperty(e,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Ue)if(typeof e[t]=="function"){const i=e[t];e[t]=function(...n){return typeof n[n.length-1]=="function"?g.captureWorkerPoolOperation("zlib",t,i,n,this):i.apply(this,n)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}le=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] zlib module patched successfully")}catch(e){console.error("[WorkerPool] Error patching zlib module:",e)}})()),j=!0,r&&console.log("[WorkerPool] Worker pool patching initialized")}function ge(){return j}let W=!1,G=!1,K=null;function U(r){const e=o.getGlobalConfigUnsafe(),t=e?.sfDebug||!1;t&&console.log("[FuncSpan] captureSpanData called for:",{function:r.functionName,file:r.filePath,duration:`${r.duration}ms`,async:r.async,error:r.error,spanId:r.spanId});const i={functionName:r.functionName,filePath:r.filePath,metadata:r.metadata,args:r.args,result:r.result,error:r.error,duration:r.duration,durationNs:r.durationNs,async:r.async,spanId:r.spanId,parentSpanId:r.parentSpanId};process.env.SF_FUNCSPAN_CONSOLE_OUTPUT==="true"&&console.log(`
182
+ 📊 Function Span:`,{function:`${r.functionName} (${r.filePath}:${r.metadata.line}:${r.metadata.column})`,duration:`${r.duration.toFixed(2)}ms`,arguments:r.args,result:r.error?`Error: ${r.error}`:r.result,spanId:r.spanId,parentSpanId:r.parentSpanId||"none"});const n=process.env.SF_FUNCSPAN_JSONL_FILE;if(n)try{const a=n==="true"||n==="1"?"funcspans.jsonl":n,p=Date.now(),d=process.hrtime.bigint(),s=BigInt(r.startTimeNs),u=Number(d-s)/1e6,l=new Date(p-u).toISOString(),c=JSON.stringify({timestamp:l,functionName:r.functionName,filePath:r.filePath,line:r.metadata.line,column:r.metadata.column,duration:r.duration,durationNs:r.durationNs,startTimeNs:r.startTimeNs,arguments:r.args,returnValue:r.error?{error:String(r.error)}:r.result,spanId:r.spanId,parentSpanId:r.parentSpanId,async:r.async,pid:r.pid,threadId:r.threadId})+`
183
+ `;z.appendFileSync(a,c,"utf-8")}catch(a){console.error("[FuncSpan] Error writing to JSONL file:",a)}if(t&&console.log("[FuncSpan] Sending function span to transmitter:",i),process.env.SF_FUNCSPAN_SKIP_BACKEND!=="true")try{(K||(K=new g.FunctionSpanTransmitter),K).send([i]),t&&console.log("[FuncSpan] Function span sent successfully")}catch(a){t&&console.error("[FuncSpan] Error sending function span:",a)}}exports.ContextManager=o.ContextManager,exports.getCurrentFunctionSpanId=o.getCurrentFunctionSpanId,exports.runWithContext=o.runWithContext,exports.clearFuncspanOverride=g.clearFuncspanOverride,exports.getDefaultConfig=g.getDefaultConfig,exports.getEnvConfig=g.getEnvConfig,exports.getFuncspanOverride=g.getFuncspanOverride,exports.parseHeaderOverride=g.parseHeaderOverride,exports.setFuncspanOverride=g.setFuncspanOverride,exports.isProductionEnvironment=F.isProductionEnvironment,exports.isRuntimeModeEnabled=F.isRuntimeModeEnabled,exports.shouldEnableRuntimeHooks=F.shouldEnableRuntimeHooks,exports.setSkipTypeScriptPlugin=A.setSkipTypeScriptPlugin,exports.transformFunctionSpans=A.transformFunctionSpans,exports.transformFunctionSpansSync=A.transformFunctionSpansSync,exports.addOrUpdateMetadata=function(r,e={},t,i=!1){const n=o.getConfig();new X(n.apiKey).addOrUpdateMetadata(r,e,t,i)},exports.captureFunctionSpan=function(r,e,t,i){const n=function(...a){const p=o.getGlobalConfigUnsafe(),d=p?.sfDebug||!1;d&&console.log(`[FuncSpan] captureFunctionSpan wrapper called for ${t}::${e}`);const s=(function(h,f){const $=g.getFuncspanOverride();if($){const m=g.parseHeaderOverride($);if(m)return process.env.SF_DEBUG==="true"&&console.log(`[FuncSpan] Using HTTP header override for ${h}::${f}`),m}try{return ie(h,f)}catch{return{sample_rate:process.env.SF_FUNCSPAN_SAMPLE_RATE?parseFloat(process.env.SF_FUNCSPAN_SAMPLE_RATE):1,capture_arguments:!0,capture_return_value:!0,arg_limit_mb:1,return_limit_mb:1,enable_sampling:!1,autocapture_all_child_functions:!1,capture_sf_veritas:!1,parse_json_strings:!1}}})(t,e);if(d&&console.log(`[FuncSpan] Config for ${t}::${e}:`,s),s.enable_sampling&&s.sample_rate<1&&Math.random()>s.sample_rate)return d&&console.log(`[FuncSpan] Skipping ${e} due to sampling`),r.apply(this,a);if(s.sample_rate===0)return d&&console.log(`[FuncSpan] Skipping ${e} - sample_rate is 0.0`),r.apply(this,a);d&&console.log(`[FuncSpan] Capturing function span for ${e}`);const u=o.ContextManager.getInstance(),l=u.getCurrentFunctionSpanId(),c=o.v4();u.setCurrentFunctionSpanId(c);const y=process.hrtime.bigint(),v=Date.now();let I=null;s.capture_arguments&&(I={},i.paramNames.forEach((h,f)=>{f<a.length&&(I[h]=a[f])}),I&&s.arg_limit_mb>0&&(I=g.truncateToLimit(I,s.arg_limit_mb)));try{const h=r.apply(this,a);if(h&&typeof h.then=="function")return l?u.setCurrentFunctionSpanId(l):u.clearCurrentFunctionSpanId(),h.then(b=>{const _=process.hrtime.bigint(),C=Date.now(),T=Number(_-y);let S=null;return s.capture_return_value&&s.return_limit_mb>0&&(S=g.truncateToLimit(b,s.return_limit_mb)),U({functionName:e,filePath:t,metadata:i,args:I,result:S,error:null,duration:C-v,durationNs:T,startTimeNs:y.toString(),async:!0,spanId:c,parentSpanId:l,pid:process.pid,threadId:O.threadId}),b},b=>{const _=process.hrtime.bigint(),C=Date.now(),T=Number(_-y);throw U({functionName:e,filePath:t,metadata:i,args:I,result:null,error:b?.message||String(b),duration:C-v,durationNs:T,startTimeNs:y.toString(),async:!0,spanId:c,parentSpanId:l,pid:process.pid,threadId:O.threadId}),b});const f=process.hrtime.bigint(),$=Date.now(),m=Number(f-y);let w=null;return s.capture_return_value&&s.return_limit_mb>0&&(w=g.truncateToLimit(h,s.return_limit_mb)),U({functionName:e,filePath:t,metadata:i,args:I,result:w,error:null,duration:$-v,durationNs:m,startTimeNs:y.toString(),async:!1,spanId:c,parentSpanId:l,pid:process.pid,threadId:O.threadId}),l?u.setCurrentFunctionSpanId(l):u.clearCurrentFunctionSpanId(),h}catch(h){const f=process.hrtime.bigint(),$=Date.now(),m=Number(f-y);throw U({functionName:e,filePath:t,metadata:i,args:I,result:null,error:h?.message||String(h),duration:$-v,durationNs:m,startTimeNs:y.toString(),async:!1,spanId:c,parentSpanId:l,pid:process.pid,threadId:O.threadId}),l?u.setCurrentFunctionSpanId(l):u.clearCurrentFunctionSpanId(),h}};Object.defineProperty(n,"name",{value:e,writable:!1});for(const a in r)r.hasOwnProperty(a)&&(n[a]=r[a]);return n},exports.getGlobalConfig=ie,exports.identify=function(r,e,t,i=!1){const n=o.getConfig();new X(n.apiKey).identify(r,e,t,i)},exports.initializeConfigLoader=re,exports.initializeWorkerPoolPatching=pe,exports.isAlreadyInstrumented=function(r){return!!r.includes("captureFunctionSpan(")||!!r.includes("@sailfish-ai/sf-veritas")||!(!r.includes("/* @sailfish-instrumented */")&&!r.includes("// @sailfish-instrumented"))},exports.isConfigLoaderInitialized=oe,exports.isSetupInterceptorsInitialized=function(){return W},exports.isWorkerPoolInitialized=ge,exports.setupInterceptors=function(r){if(G)console.warn("[setupInterceptors] ⚠️ Recursive call detected and blocked!");else if(!W){G=!0,g.registerShutdownHooks();try{let e,t;const i=F.stackToString(new Error().stack);if(i){const d=i.split(`
184
+ `)[2]||"",s=d.match(/\((.+):(\d+):\d+\)/)||d.match(/at (.+):(\d+):\d+/);s&&(e=s[1],t=parseInt(s[2],10))}if(!r||!r.apiKey){const d=`The required API Key is not provided: ${JSON.stringify(r)}`;console.error(d)}const{config:n}=o.getOrCreateConfig(r);if(o.backfillGitInfoAsync(n).catch(()=>{}),e&&(n.setupInterceptorsFile=e),t&&(n.setupInterceptorsLine=t),n.sfDebug&&console.log("Updated configuration after applying options:",n),!n.apiKey||!n.apiGraphqlEndpoint){const d=`The required config is not provided: ${JSON.stringify(n)}`;throw console.error(d),new Error(d)}oe()||re(void 0,n.sfDebug).catch(d=>{n.sfDebug&&console.error("[FuncSpan] Failed to initialize config loader:",d)}),process.env.SF_WORKER_POOL_DISABLED==="true"?n.sfDebug&&console.log("[setupInterceptors] Worker pool patching DISABLED (SF_WORKER_POOL_DISABLED=true)"):ge()||(pe(),n.sfDebug&&console.log("[setupInterceptors] Worker pool patching initialized (DNS tracking enabled)"));const a=new J;a.setServiceUUID(n.serviceUUID),F.initializeLogInterceptor(a),(function(d=[]){const s=new Te(d);new De().doSend(s.getExcludedDomains());const u=new Ne,l=new Ee;s.patchFetch(u,l),s.patchHttp(u,l)})(n.domainsToNotPropagateHeadersTo);const p=new Ce;p.setServiceUUID(n.serviceUUID),F.initializeExceptionInterceptor(p),we(),new Pe().send(),W=!0,n.sfDebug&&console.log("[setupInterceptors] ✅ Initialization complete")}finally{G=!1}}};