@sailfish-ai/sf-veritas 0.3.2 → 0.4.1

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.
Files changed (38) hide show
  1. package/dist/contextManager-B1hI1vbB.cjs +1 -0
  2. package/dist/{contextManager-CZy0w11U.js → contextManager-CE9FcHd2.js} +55 -47
  3. package/dist/plugins/funcspanEsbuildPlugin.cjs +1 -1
  4. package/dist/plugins/funcspanEsbuildPlugin.mjs +1 -1
  5. package/dist/plugins/funcspanRollupPlugin.cjs +1 -1
  6. package/dist/plugins/funcspanRollupPlugin.mjs +1 -1
  7. package/dist/plugins/funcspanTscPlugin.cjs +1 -1
  8. package/dist/plugins/funcspanTscPlugin.mjs +1 -1
  9. package/dist/plugins/funcspanVitePlugin.cjs +1 -1
  10. package/dist/plugins/funcspanVitePlugin.mjs +1 -1
  11. package/dist/plugins/funcspanWebpackPlugin.cjs +1 -1
  12. package/dist/plugins/funcspanWebpackPlugin.mjs +1 -1
  13. package/dist/{runtimeConfig-ButdW4zP.js → runtimeConfig-B6ERoLRD.js} +279 -277
  14. package/dist/{runtimeConfig-C4_zc4Zg.cjs → runtimeConfig-BgTE3gmS.cjs} +4 -4
  15. package/dist/sf-veritas.cjs +27 -19
  16. package/dist/sf-veritas.mjs +1657 -612
  17. package/dist/types/baseTransmitter.d.ts +1 -0
  18. package/dist/types/constants.d.ts +6 -0
  19. package/dist/types/contextManager.d.ts +15 -0
  20. package/dist/types/index.d.ts +2 -0
  21. package/dist/types/patches/asyncQueues/_stubs/bee-queue.d.ts +10 -0
  22. package/dist/types/patches/asyncQueues/_stubs/rabbitmq.d.ts +11 -0
  23. package/dist/types/patches/asyncQueues/_stubs/sqs.d.ts +9 -0
  24. package/dist/types/patches/asyncQueues/asyncQueueTracer.d.ts +127 -0
  25. package/dist/types/patches/asyncQueues/asyncQueues.bench.d.ts +1 -0
  26. package/dist/types/patches/asyncQueues/bullmq.d.ts +27 -0
  27. package/dist/types/patches/asyncQueues/bullmqPro.d.ts +3 -0
  28. package/dist/types/patches/asyncQueues/confluentKafkaJs.d.ts +3 -0
  29. package/dist/types/patches/asyncQueues/index.d.ts +15 -0
  30. package/dist/types/patches/asyncQueues/kafkajs.d.ts +7 -0
  31. package/dist/types/setupConfig.d.ts +3 -0
  32. package/dist/worker-pool-capture.cjs +1 -1
  33. package/dist/worker-pool-capture.mjs +1 -1
  34. package/dist/{workerPoolSpanCapture-BomWTMM2.js → workerPoolSpanCapture-B5AjE5B9.js} +115 -115
  35. package/dist/workerPoolSpanCapture-CVp5eCI6.cjs +83 -0
  36. package/package.json +2 -1
  37. package/dist/contextManager-qXvO_a5y.cjs +0 -1
  38. package/dist/workerPoolSpanCapture-BUFN_RMW.cjs +0 -83
@@ -1,5 +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,Ly8gc3JjL2RlYnVnZ2VyV29ya2VyLnRzCmltcG9ydCB7IFNlc3Npb24gfSBmcm9tICJpbnNwZWN0b3IvcHJvbWlzZXMiOwppbXBvcnQgeyBwYXJlbnRQb3J0LCB3b3JrZXJEYXRhIH0gZnJvbSAid29ya2VyX3RocmVhZHMiOwpnbG9iYWwuc2ZEZWJ1ZyA9IHZvaWQgMDsKZ2xvYmFsLnN0YWNrRGVwdGhMb2NhbHMgPSB2b2lkIDA7Cmdsb2JhbC5ub2RlTW9kdWxlc1RvQ29sbGVjdExvY2FsVmFyaWFibGVzT24gPSB2b2lkIDA7CnZ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iOwogICAgICAgIGxldCBmaWxlID0gIiI7CiAgICAgICAgaWYgKHVybCAmJiB1cmwudHJpbSgpICE9PSAiIikgewogICAgICAgICAgZmlsZSA9IHVybDsKICAgICAgICB9IGVsc2UgaWYgKGRlc2NyaXB0aW9uTGluZXNbaW5kZXhdKSB7CiAgICAgICAgICBmaWxlID0gZGVzY3JpcHRpb25MaW5lc1tpbmRleF0udHJpbSgpOwogICAgICAgIH0gZWxzZSB7CiAgICAgICAgICBmaWxlID0gIjx1bmtub3duPiI7CiAgICAgICAgfQogICAgICAgIGlmIChsb2NhdGlvbiAmJiBsb2NhdGlvbi5zY3JpcHRJZCkgewogICAgICAgICAgY29uc3Qgc2NyaXB0SWQgPSBsb2NhdGlvbi5zY3JpcHRJZDsKICAgICAgICAgIHRyeSB7CiAgICAgICAgICAgIGxldCBzY3JpcHRTb3VyY2UgPSBzY3JpcHRTb3VyY2VDYWNoZS5nZXQoc2NyaXB0SWQpOwogICAgICAgICAgICBpZiAoc2NyaXB0U291cmNlID09PSB2b2lkIDApIHsKICAgICAgICAgICAgICBjb25zdCByZXN1bHQgPSBhd2FpdCBzZXNzaW9uLnBvc3QoCiAgICAgICAgICAgICAgICAiRGVidWdnZXIuZ2V0U2NyaXB0U291cmNlIiwKICAgICAgICAgICAgICAgIHsKICAgICAgICAgICAgICAgICAgc2NyaXB0SWQKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICApOwogICAgICAgICAgICAgIHNjcmlwdFNvdXJjZSA9IHJlc3VsdC5zY3JpcHRTb3VyY2U7CiAgICAgICAgICAgICAgc2NyaXB0U291cmNlQ2FjaGUuc2V0KHNjcmlwdElkLCBzY3JpcHRTb3VyY2UpOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGNvbnN0IHNvdXJjZUxpbmVzID0gc2NyaXB0U291cmNlLnNwbGl0KCJcbiIpOwogICAgICAgICAgICBjb2RlID0gc291cmNlTGluZXNbbG9jYXRpb24ubGluZU51bWJlcl0gfHwgIjxub3QgY2FwdHVyZWQ+IjsKICAgICAgICAgIH0gY2F0Y2ggKGVycikgewogICAgICAgICAgICBpZiAoZ2xvYmFsLnNmRGVidWcpIHsKICAgICAgICAgICAgICBjb25zb2xlLmVycm9yKCJbV29ya2VyXSBGYWlsZWQgdG8gZmV0Y2ggc2NyaXB0IHNvdXJjZToiLCBlcnIpOwogICAgICAgICAgICB9CiAgICAgICAgICB9CiAgICAgICAgfQogICAgICAgIGNvbnN0IGxvY2FscyA9IGxvY2FsU2NvcGU/Lm9iamVjdD8ub2JqZWN0SWQgPyBhd2FpdCBmZXRjaExvY2FsVmFyaWFibGVzKHNlc3Npb24sIGxvY2FsU2NvcGUub2JqZWN0Lm9iamVjdElkKSA6IHt9OwogICAgICAgIHJldHVybiB7CiAgICAgICAgICBmdW5jdGlvbjogZnVuY3Rpb25OYW1lIHx8ICI8YW5vbnltb3VzPiIsCiAgICAgICAgICBsb2NhbHMsCiAgICAgICAgICBmaWxlLAogICAgICAgICAgbGluZTogbG9jYXRpb24/LmxpbmVOdW1iZXIgfHwgMCwKICAgICAgICAgIGNvZGUKICAgICAgICB9OwogICAgICB9IGNhdGNoIChlcnJvcikgewogICAgICAgIGlmIChnbG9iYWwuc2ZEZWJ1ZykgewogICAgICAgICAgY29uc29sZS5lcnJvcigiW1dvcmtlcl0gRXJyb3IgcHJvY2Vzc2luZyBjYWxsIGZyYW1lOiIsIGVycm9yKTsKICAgICAgICB9CiAgICAgICAgcmV0dXJuIHsKICAgICAgICAgIGZ1bmN0aW9uOiAiPGVycm9yPiIsCiAgICAgICAgICBsb2NhbHM6IHt9LAogICAgICAgICAgZmlsZTogIjx1bmtub3duPiIsCiAgICAgICAgICBsaW5lOiAwLAogICAgICAgICAgY29kZTogIjxub3QgY2FwdHVyZWQ+IgogICAgICAgIH07CiAgICAgIH0KICAgIH0pCiAgKTsKICBwYXJlbnRQb3J0Py5wb3N0TWVzc2FnZSh7IHR5cGU6ICJleGNlcHRpb24iLCBmcmFtZXMgfSk7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c29sZS5lcnJvcigiW1dvcmtlcl0gRmFpbGVkIHRvIGZldGNoIGxvY2FsIHZhcmlhYmxlczoiLCBlcnIpOwogICAgfQogICAgcmV0dXJuIHt9OwogIH0KfQpzdGFydERlYnVnZ2VyKCkuY2F0Y2goKGVycm9yKSA9PiB7CiAgaWYgKGdsb2JhbC5zZkRlYnVnKSB7CiAgICBjb25zb2xlLmVycm9yKCJbV29ya2VyXSBGYWlsZWQgdG8gc3RhcnQgZGVidWdnZXI6IiwgZXJyb3IpOwogIH0KfSk7CnNldEludGVydmFsKCgpID0+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(`
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"),A=require("./contextManager-B1hI1vbB.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 r=i.substring(5,c),Z=parseInt(i.substring(c+1),10);return isNaN(Z)?[null,null,!1]:[r,Z,!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=(r,Z)=>Z;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 d=!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 r=t.get(this);if(r>=20)return;t.set(this,r+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){A.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(r){const Z=E("http://169.254.169.254/latest/meta-data/",{},r),m=E("http://metadata.google.internal/computeMetadata/v1/instance/",{"Metadata-Flavor":"Google"},r),o=E("http://169.254.169.254/metadata/instance?api-version=2021-02-01",{Metadata:"true"},r);return(await Promise.allSettled([Z,m,o])).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,Ly8gc3JjL2RlYn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oCiAgICBsaW1pdGVkQ2FsbEZyYW1lcy5tYXAoYXN5bmMgKGZyYW1lLCBpbmRleCkgPT4gewogICAgICB0cnkgewogICAgICAgIGNvbnN0IHsgZnVuY3Rpb25OYW1lLCBsb2NhdGlvbiwgdXJsLCBzY29wZUNoYWluIH0gPSBmcmFtZTsKICAgICAgICBjb25zdCBsb2NhbFNjb3BlID0gc2NvcGVDaGFpbi5maW5kKChzY29wZSkgPT4gc2NvcGUudHlwZSA9PT0gImxvY2FsIik7CiAgICAgICAgbGV0IGNvZGUgPSAiPG5vdCBjYXB0dXJlZD4iOwogICAgICAgIGxldCBmaWxlID0gIiI7CiAgICAgICAgaWYgKHVybCAmJiB1cmwudHJpbSgpICE9PSAiIikgewogICAgICAgICAgZmlsZSA9IHVybDsKICAgICAgICB9IGVsc2UgaWYgKGRlc2NyaXB0aW9uTGluZXNbaW5kZXhdKSB7CiAgICAgICAgICBmaWxlID0gZGVzY3JpcHRpb25MaW5lc1tpbmRleF0udHJpbSgpOwogICAgICAgIH0gZWxzZSB7CiAgICAgICAgICBmaWxlID0gIjx1bmtub3duPiI7CiAgICAgICAgfQogICAgICAgIGlmIChsb2NhdGlvbiAmJiBsb2NhdGlvbi5zY3JpcHRJZCkgewogICAgICAgICAgY29uc3Qgc2NyaXB0SWQgPSBsb2NhdGlvbi5zY3JpcHRJZDsKICAgICAgICAgIHRyeSB7CiAgICAgICAgICAgIGxldCBzY3JpcHRTb3VyY2UgPSBzY3JpcHRTb3VyY2VDYWNoZS5nZXQoc2NyaXB0SWQpOwogICAgICAgICAgICBpZiAoc2NyaXB0U291cmNlID09PSB2b2lkIDApIHsKICAgICAgICAgICAgICBjb25zdCByZXN1bHQgPSBhd2FpdCBzZXNzaW9uLnBvc3QoCiAgICAgICAgICAgICAgICAiRGVidWdnZXIuZ2V0U2NyaXB0U291cmNlIiwKICAgICAgICAgICAgICAgIHsKICAgICAgICAgICAgICAgICAgc2NyaXB0SWQKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICApOwogICAgICAgICAgICAgIHNjcmlwdFNvdXJjZSA9IHJlc3VsdC5zY3JpcHRTb3VyY2U7CiAgICAgICAgICAgICAgc2NyaXB0U291cmNlQ2FjaGUuc2V0KHNjcmlwdElkLCBzY3JpcHRTb3VyY2UpOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGNvbnN0IHNvdXJjZUxpbmVzID0gc2NyaXB0U291cmNlLnNwbGl0KCJcbiIpOwogICAgICAgICAgICBjb2RlID0gc291cmNlTGluZXNbbG9jYXRpb24ubGluZU51bWJlcl0gfHwgIjxub3QgY2FwdHVyZWQ+IjsKICAgICAgICAgIH0gY2F0Y2ggKGVycikgewogICAgICAgICAgICBpZiAoZ2xvYmFsLnNmRGVidWcpIHsKICAgICAgICAgICAgICBjb25zb2xlLmVycm9yKCJbV29ya2VyXSBGYWlsZWQgdG8gZmV0Y2ggc2NyaXB0IHNvdXJjZToiLCBlcnIpOwogICAgICAgICAgICB9CiAgICAgICAgICB9CiAgICAgICAgfQogICAgICAgIGNvbnN0IGxvY2FscyA9IGxvY2FsU2NvcGU/Lm9iamVjdD8ub2JqZWN0SWQgPyBhd2FpdCBmZXRjaExvY2FsVmFyaWFibGVzKHNlc3Npb24sIGxvY2FsU2NvcGUub2JqZWN0Lm9iamVjdElkKSA6IHt9OwogICAgICAgIHJldHVybiB7CiAgICAgICAgICBmdW5jdGlvbjogZnVuY3Rpb25OYW1lIHx8ICI8YW5vbnltb3VzPiIsCiAgICAgICAgICBsb2NhbHMsCiAgICAgICAgICBmaWxlLAogICAgICAgICAgbGluZTogbG9jYXRpb24/LmxpbmVOdW1iZXIgfHwgMCwKICAgICAgICAgIGNvZGUKICAgICAgICB9OwogICAgICB9IGNhdGNoIChlcnJvcikgewogICAgICAgIGlmIChnbG9iYWwuc2ZEZWJ1ZykgewogICAgICAgICAgY29uc29sZS5lcnJvcigiW1dvcmtlcl0gRXJyb3IgcHJvY2Vzc2luZyBjYWxsIGZyYW1lOiIsIGVyc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S5vYmplY3RJZDsKICAgICAgICAgIGF3YWl0IHVucm9sbE9iamVjdChzZXNzaW9uLCBpZCwgcHJvcC5uYW1lLCB2YXJpYWJsZXMpOwogICAgICAgIH0gZWxzZSBpZiAocHJvcD8udmFsdWUpIHsKICAgICAgICAgIHVucm9sbE90aGVyKHByb3AsIHZhcmlhYmxlcyk7CiAgICAgICAgfQogICAgICB9CiAgICAgIHJldHVybiB2YXJpYWJsZXM7CiAgICB9CiAgfSBjYXRjaCAoZXJyKSB7CiAgICBpZiAoZ2xvYmFsLnNmRGVidWcpIHsKICAgICAgY29uc29sZS5lcnJvcigiW1dvcmtlcl0gRmFpbGVkIHRvIGZldGNoIGxvY2FsIHZhcmlhYmxlczoiLCBlcnIpOwogICAgfQogICAgcmV0dXJuIHt9OwogIH0KfQpzdGFydERlYnVnZ2VyKCkuY2F0Y2goKGVycm9yKSA9PiB7CiAgaWYgKGdsb2JhbC5zZkRlYnVnKSB7CiAgICBjb25zb2xlLmVycm9yKCJbV29ya2VyXSBGYWlsZWQgdG8gc3RhcnQgZGVidWdnZXI6IiwgZXJyb3IpOwogIH0KfSk7CnNldEludGVydmFsKCgpID0+IHsKfSwgMWU0KTsKZXhwb3J0IHsKICBwcm9jZXNzQ2FsbEZyYW1lcwp9Owo="),{workerData:{captureAllExceptions:!0}});let C=null;const I=new WeakMap;g.on("message",async e=>{if(typeof e=="string"&&A.getConfig().sfDebug&&G(`[Worker] ${e}`),e.readyToGetParameters&&g.postMessage({sfDebug:A.getConfig().sfDebug,stackDepthLocals:A.getConfig().stackDepthLocals,nodeModulesToCollectLocalVariablesOn:A.getConfig().nodeModulesToCollectLocalVariablesOn}),e.type==="exception"){const{frames:i}=e,c=C;if(!c)return;const r=(function(m){return m?m.split(`
3
+ `).slice(1).map(o=>{const f=/at (.+?) \((.+):(\d+):(\d+)\)/.exec(o)||/at (.+):(\d+):(\d+)/.exec(o);if(f){const[,W,B,u,a]=f;return new K({function:W||"<anonymous>",locals:{},file:B||"<unknown>",line:parseInt(u,10)||0,code:"<not captured>",column:parseInt(a)||0})}return new K({function:"<unknown>",locals:{},file:"<unknown>",line:0,code:"<not captured>",column:0})}):[]})(Q(c.stack)),Z=(function(m,o){const f=[];let W=-1,B=-1;for(let u=0;u<m.length;u++){const a=Jn(m[u].file);if(B=u,a!=="<unknown>"){for(let b=0;b<o.length;b++){const y=o[b];if(on(y,a)||typeof y.file=="string"&&y.file.includes(a)){W=b,X=0,A.getConfig().sfDebug&&G(`✅ Matched Frame Found: ${a} @ Debugger Frame ${b}`);break}}if(W!==-1)break}}if(W===-1)return X===10?(X=0,m):(++X,A.getConfig().sfDebug&&G(`"❌ No matching frame found. Checking once again, Attempt N ${X}"`),[]);A.getConfig().sfDebug&&G(`🔄 Merging from matched index ${W} onward...`);for(let u=0;u<o.length;u++){const a=m[B+u],b=o[W+u];f.push(new K({function:b?.function||a?.function||"<anonymous>",locals:b?.locals||a?.locals||{},file:a?.file||b?.file||"<unknown>",line:b?.line||a?.line||0,code:b?.code||a?.code||"<not captured>"}))}return f})(r,i||[]);if(Z.length!==0){C=null;const m=A.getConfig().stackDepthCodeTraceDepth,o=m===-1?Z:Z.slice(0,m+1);if(!A.getConfig().exceptionCaptureLocals)for(const a of o)a.locals={};const f=Math.min(o.length,r.length);await Promise.all(Array.from({length:f},async(a,b)=>{const y=await(async function(An,un,bn){const V=(function(s){s.startsWith("at ")&&(s=s.slice(3).trim());const h=s.match(/^(.*?)(:\d+)+(\.map)?$/);return h?h[1]:s})(An);if(!V||V==="<unknown>")return null;const J=V+".map";try{let s=S.get(J);if(s===void 0){const v=await Bn.readFile(J,"utf-8");s=v?JSON.parse(v):null,gn(J,s)}if(!s)return null;let h=new Wn.sourceMapExports.SourceMapConsumer(s).originalPositionFor({line:un,column:bn});if(V&&h.source){const v=nn(V),D=s.sources.findIndex(R=>nn(R)===v);if(D===-1)A.getConfig().sfDebug&&G(`Source file "${V}" not found in the source map.`);else{const R=s.sourcesContent[D],an=s.names.join(",");if(R)return{content:R.split(`
4
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;
5
+ `),name:an,file:h.source};A.getConfig().sfDebug&&G(`No source content available for file "${V}".`)}}return{content:s.sourcesContent[0],name:s.names[0],file:s.file}}catch(s){A.getConfig().sfDebug&&G(`Cant read/parse "${J}: Error - ".`,s),gn(J,null)}return null})(o[b].file,r[b].line,r[b].column);y&&(y.content!=null&&(o[b].code=y.content),y.file!=null&&(o[b].file=y.file))})),n.setOperationName("CollectExceptions");const W=c.message?`${c.name}: ${c.message}`:c.name;A.getConfig().sfDebug&&G("error message is : ",W);const B=A.ContextManager.getInstance(),u=I.get(c);u?(B.setTraceIdFor(u,u),B.runWithSession(u,()=>{B.setTraceId(u),n.doSend(W,o)})):n.doSend(W,o)}}}),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 r=A.ContextManager.getInstance().getTraceId();I.set(c,r)}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,r){const Z=A.getGlobalConfigUnsafe();if(Z?.logIgnoreRegex&&Z.logIgnoreRegex.test(i))return;const[m,o]=ln(2,c,r);n.setOperationName("CollectLogs"),n.doSend([i,e,m,o])}const C=console.log=(...e)=>{if(d)j(...p(e));else{d=!0;try{const i=p(e);g("INFO",w(i),C,e),j(...i)}finally{d=!1}}},I=console.error=(...e)=>{if(d)O(...p(e));else{d=!0;try{const i=p(e);g("ERROR",w(i),I,e),O(...i)}finally{d=!1}}},t=console.warn=(...e)=>{if(d)_(...p(e));else{d=!0;try{const i=p(e);g("WARN",w(i),t,e),_(...i)}finally{d=!1}}},l=console.info=(...e)=>{if(d)q(...p(e));else{d=!0;try{const i=p(e);g("INFO",w(i),l,e),q(...i)}finally{d=!1}}};if(A.getConfig().logLevel==="DEBUG"){const e=console.debug=(...i)=>{if(d)$(...p(i));else{d=!0;try{const c=p(i);g("DEBUG",w(c),e,i),$(...c)}finally{d=!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 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=`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("./contextManager-B1hI1vbB.cjs"),I=require("./workerPoolSpanCapture-CVp5eCI6.cjs"),P=require("./runtimeConfig-BgTE3gmS.cjs"),dt=require("node:module"),$e=require("fs"),x=require("http"),V=require("https"),ft=require("./source-map-rHHEdpre.cjs"),pt=require("fs/promises"),gt=require("path"),ht=require("glob"),yt=require("async_hooks"),X=require("worker_threads"),re=require("./funcSpanTransformer-D0W2t41q.cjs");function _e(n){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const e in n)if(e!=="default"){const o=Object.getOwnPropertyDescriptor(n,e);Object.defineProperty(t,e,o.get?o:{enumerable:!0,get:()=>n[e]})}}return t.default=n,Object.freeze(t)}const mt=_e($e),we=_e(pt),A=_e(gt);class z extends I.BaseTransmitter{constructor(){super(),this.setOperationName("IdentifyServiceDetails")}async doSend(t){if(!p.getConfig().serviceIdentificationReceived)try{this.send()}catch(e){p.getConfig().sfDebug&&console.error(" Error during service identification:",e)}}async send(){const t=`
2
2
  ${this.queryType} ${this.operationName}(
3
3
  $apiKey: String!,
4
4
  $timestampMs: String!,
@@ -16,6 +16,7 @@
16
16
  $framework: String,
17
17
  $additionalFrameworks: JSON,
18
18
  $serviceRole: String,
19
+ $dataSensitivityLevel: String,
19
20
  ) {
20
21
  ${this.queryName}(
21
22
  apiKey: $apiKey,
@@ -34,13 +35,14 @@
34
35
  framework: $framework,
35
36
  additionalFrameworks: $additionalFrameworks,
36
37
  serviceRole: $serviceRole,
38
+ dataSensitivityLevel: $dataSensitivityLevel,
37
39
  )
38
40
  }
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`
41
+ `,e=p.getConfig(),o=this.getVariables({serviceIdentifier:e.serviceIdentifier,serviceVersion:e.serviceVersion,library:e.packageLibraryType,version:e.version,serviceAdditionalMetadata:e.serviceAdditionalMetadata,gitSha:e.gitSha||"",gitOrg:e.gitOrg||void 0,gitRepo:e.gitRepo||void 0,gitProvider:e.gitProvider||void 0,serviceDisplayName:e.serviceDisplayName||void 0,framework:e.framework||void 0,additionalFrameworks:e.additionalFrameworks.length>0?e.additionalFrameworks:void 0,serviceRole:e.serviceRole||void 0});I.nonBlockingPost(this.endpoint,this.operationName,t,o)}}class St extends I.BaseTransmitter{serviceIdentifier=new z;constructor(){super(),this.setOperationName("CollectMetadata")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const t=setInterval(()=>{p.getConfig().serviceIdentificationReceived?clearInterval(t):this.serviceIdentifier.doSend({})},5e3);t&&typeof t=="object"&&"unref"in t&&t.unref()}async doSend(t,e,o,r){this.startBackgroundIdentify(),this.send(t,e,o,r)}async send(t,e,o,r){if(!e&&!r)throw new Error('Must pass in either traits or traits_json to "add_or_update_traits"');let s=[];if(!r){const l=P.serializeJsonWithExclusions(e);r=l.traitsJson,s=l.excludedFields}const d=this.getVariables({userId:t,traitsJson:r,excludedFields:s,override:o,library:p.getConfig().packageLibraryType,version:p.getConfig().version});I.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),d)}getQuery(){return`
40
42
  mutation ${this.operationName}($apiKey: String!, $serviceUuid: String!, $sessionId: String!, $userId: String!, $traitsJson: String!, $excludedFields: [String!]!, $library: String!, $timestampMs: String!, $version: String!, $override: Boolean!) {
41
43
  ${this.queryName}(apiKey: $apiKey, serviceUuid: $serviceUuid, sessionId: $sessionId, userId: $userId, traitsJson: $traitsJson, excludedFields: $excludedFields, library: $library, timestampMs: $timestampMs, version: $version, override: $override)
42
44
  }
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`
45
+ `}}class ke{constructor(t){this.apiKey=t,this.metadataTransmitter=new St}metadataTransmitter;identify(t,e,o,r=!1){e||o?this.addOrUpdateMetadata(t,e,o,r):this.addOrUpdateMetadata(t,{},void 0,r)}addOrUpdateMetadata(t,e={},o,r=!1){if(!e&&!o)throw new Error('Must pass in either traits or traitsJson to "addOrUpdateMetadata"');p.getConfig().sfDebug&&console.log(" [[DEBUG - addOrUpdateMetadata]] Starting operation"),p.getConfig().sfDebug&&console.log(" addOrUpdateMetadata...SENDING DATA...",t,e,o),this.metadataTransmitter.doSend(t,e,r,o)}}class Ce extends I.BaseTransmitter{serviceIdentifier=new z;constructor(){super()}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const t=setInterval(()=>{p.getConfig().serviceIdentificationReceived?clearInterval(t):this.serviceIdentifier.doSend({})},5e3);t&&typeof t=="object"&&"unref"in t&&t.unref()}async doSend(t){this.startBackgroundIdentify(),this.send(t)}async send(t){try{const e=Array.isArray(t)?t:[t,"default",null,null],o=this.getVariables({contents:e[0],level:e[1],sourceFile:e[2]||void 0,sourceLine:e[3]||void 0});I.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),o)}catch(e){p.getConfig().sfDebug&&console.error("🚨 Error in send():",e)}}getQuery(){return`
44
46
  ${this.queryType} ${this.operationName}(
45
47
  $apiKey: String!,
46
48
  $serviceUuid: String!,
@@ -50,7 +52,8 @@
50
52
  $contents: String!,
51
53
  $parentSpanId: String,
52
54
  $sourceFile: String,
53
- $sourceLine: Int
55
+ $sourceLine: Int,
56
+ $dataSensitivityLevel: String
54
57
  ) {
55
58
  ${this.queryName}(
56
59
  apiKey: $apiKey,
@@ -61,10 +64,11 @@
61
64
  contents: $contents,
62
65
  parentSpanId: $parentSpanId,
63
66
  sourceFile: $sourceFile,
64
- sourceLine: $sourceLine
67
+ sourceLine: $sourceLine,
68
+ dataSensitivityLevel: $dataSensitivityLevel
65
69
  )
66
70
  }
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`
71
+ `}}class bt extends I.BaseTransmitter{serviceIdentifier=new z;supplementalFields={};setSupplementalFields(t){this.supplementalFields={...this.supplementalFields,...t}}normalizedSupplementalForGraphQL(){const{isFromLocalService:t}=this.supplementalFields,e={};return t!==void 0&&(e.isFromLocalService=t),e}constructor(){super(),this.setOperationName("CollectExceptions")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const t=setInterval(()=>{p.getConfig().serviceIdentificationReceived?clearInterval(t):this.serviceIdentifier.doSend({})},5e3);t&&typeof t=="object"&&"unref"in t&&t.unref()}async doSend(t,e){this.startBackgroundIdentify(),this.send(t,e)}async send(t,e){p.getConfig().sfDebug&&console.log(" SENDING EXCEPTION...");const o=JSON.stringify(P.CustomJSONEncoderForFrameInfo.encode(e)),r=this.normalizedSupplementalForGraphQL(),s=this.getVariables({exceptionMessage:t,traceJson:o,reentrancyGuardPreactive:!1,library:p.getConfig().packageLibraryType,version:p.getConfig().version,...r});I.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),s)}getQuery(){return`
68
72
  mutation ${this.operationName}(
69
73
  $apiKey: String!,
70
74
  $serviceUuid: String!,
@@ -76,7 +80,8 @@
76
80
  $timestampMs: String!,
77
81
  $version: String!,
78
82
  $isFromLocalService: Boolean,
79
- $parentSpanId: String
83
+ $parentSpanId: String,
84
+ $dataSensitivityLevel: String
80
85
  ) {
81
86
  ${this.queryName}(
82
87
  apiKey: $apiKey,
@@ -89,10 +94,11 @@
89
94
  timestampMs: $timestampMs,
90
95
  version: $version,
91
96
  isFromLocalService: $isFromLocalService,
92
- parentSpanId: $parentSpanId
97
+ parentSpanId: $parentSpanId,
98
+ dataSensitivityLevel: $dataSensitivityLevel
93
99
  )
94
100
  }
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=`
101
+ `}}const Q="X-Sf3-Rid",Ue="X-Sf4-Prid",Pe="getting request source code";var ee=(n=>(n.UNKNOWN="unknown",n.ANONYMOUS="anonymous",n.NOT_CAPTURED="not captured",n))(ee||{});const Fe="http:",vt=dt.createRequire(require("node:url").pathToFileURL(__filename).href);let De=!1;function It(){const n=p.getConfig().sfDebug;if(De)return void(n&&P.internalLog("[patchNodeHttpInbound] Already installed, skipping."));let t;De=!0;try{t=vt("node:http"),n&&P.internalLog("[patchNodeHttpInbound] node:http required successfully.")}catch(r){return void P.internalError("Failed to require node:http:",r)}if(!t?.Server?.prototype)return void(n&&P.internalLog("[patchNodeHttpInbound] http.Server.prototype not found."));const e=t.Server.prototype,o=e.emit;o&&!e.__sf_inbound_patched__?(Object.defineProperty(e,"__sf_inbound_patched__",{value:!0,enumerable:!1,configurable:!1,writable:!1}),n&&P.internalLog("[patchNodeHttpInbound] Patching http.Server.prototype.emit."),e.emit=function(r,...s){if(r!=="request")return n&&P.internalLog(`[patchNodeHttpInbound] Passing through event: ${r}`),o.call(this,r,...s);const d=s[0],l=s[1],c=(function(m){const g={};if(!m)return g;for(const[y,S]of Object.entries(m))S!=null&&(Array.isArray(S)?g[y.toLowerCase()]=S.join(", "):g[y.toLowerCase()]=String(S));return g})(d?.headers),i=c["x-sf3-rid"],u=c["x-sf3-functionspancaptureoverride"];n&&(P.internalLog("[patchNodeHttpInbound] Intercepted request event."),P.internalLog("[patchNodeHttpInbound] Inbound headers:",c),P.internalLog("[patchNodeHttpInbound] Trace header:",i),P.internalLog("[patchNodeHttpInbound] FuncSpan override header:",u));const a=p.ContextManager.getInstance();a.setTraceId(i);const f=a.getTraceId();n&&P.internalLog("[patchNodeHttpInbound] Context traceId set:",f);const h=()=>a.runWith({inboundHeaders:c,...i?{traceId:i}:{}},()=>{i&&a.setTraceId(i),n&&P.internalLog("[patchNodeHttpInbound] Running request handler in context.");const m=()=>{n&&P.internalLog("[patchNodeHttpInbound] Response finished/closed for traceId:",a.getTraceId())};return l.on("finish",m),l.on("close",m),o.call(this,r,d,l)});if(!u)return h();try{return I.funcspanOverrideStorage.run(u,()=>h())}catch{return h()}}):n&&P.internalLog("[patchNodeHttpInbound] Already patched, skipping.")}const Ne=new Map;function oe(n,t){const e=`${n}|${t}`;let o=Ne.get(e);return o||(o=new RegExp(n,t),Ne.set(e,o)),o}function ie(n,t){let e,o;if(typeof n=="string"?e=n:typeof URL<"u"&&n instanceof URL?e=n.href:typeof Request<"u"&&n instanceof Request?e=n.url:n!=null&&typeof n.toString=="function"&&(e=n.toString()),!e)return!1;try{o=new URL(e,"http://localhost/")}catch{return!1}const{hostname:r,pathname:s,port:d,protocol:l}=o;if(!/^https?:$/.test(l))return!1;const c=r.startsWith("www.")?r.slice(4).toLowerCase():r.toLowerCase();return t.some(i=>{const u=String(i||"").replace(/^[a-zA-Z]+:\/\//,"");if(!u)return!1;let[a,f]=u.split("/",2),h="";a.includes(":")&&([a,h]=a.split(":"));const m=oe(`^${a.replace(/\./g,"\\.").replace(/\*/g,".*")}$`,"i"),g=c.startsWith("www.")?c.slice(4):c;if(h&&d!==h)return!1;if(a.startsWith("*.")){const y=a.slice(2).toLowerCase();return c===y||g===y||c.endsWith("."+y)?f?oe(`^/${f.replace(/\*/g,".*").replace(/\/$/,"")}`,"i").test(s):!0:!1}return!m.test(g)&&!m.test(c)?!1:f?oe(`^/${f.replace(/\*/g,".*").replace(/\/$/,"")}`,"i").test(s):!0})}class Et extends Ce{constructor(){super(),this.setOperationName("DomainsToNotPassHeaderTo")}async doSend(t){this.send(t)}async send(t){const e=`
96
102
  ${this.queryType} ${this.operationName}(
97
103
  $apiKey: String!,
98
104
  $serviceUuid: String!,
@@ -104,7 +110,7 @@
104
110
  domains: $domains
105
111
  )
106
112
  }
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`
113
+ `,o={apiKey:this.apiKey,serviceUuid:this.serviceUUID,domains:t};I.nonBlockingPost(this.endpoint,this.operationName,e,o)}}class $t extends I.BaseTransmitter{serviceIdentifier=new z;constructor(){super(),this.setOperationName("CollectNetworkHops")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const t=setInterval(()=>{p.getConfig().serviceIdentificationReceived?clearInterval(t):this.serviceIdentifier.doSend({})},5e3);t&&typeof t=="object"&&"unref"in t&&t.unref()}async doSend(t){this.startBackgroundIdentify(),this.send(t)}async send(t){const{name:e,column:o,line:r,entrypoint:s,retryWithoutTraceId:d}=t,l=this.getVariables({name:e,column:o,line:r,entrypoint:s,retryWithoutTraceId:d});I.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),l)}getQuery(){return`
108
114
  mutation ${this.operationName}(
109
115
  $apiKey: String!,
110
116
  $sessionId: String!,
@@ -113,7 +119,8 @@
113
119
  $column: String!,
114
120
  $name: String!,
115
121
  $entrypoint: String!,
116
- $serviceUuid: String
122
+ $serviceUuid: String,
123
+ $dataSensitivityLevel: String
117
124
  ${this.operationName==="CollectNetworkHops"?", $retryWithoutTraceId: Boolean":""}
118
125
  ) {
119
126
  ${this.queryName}(
@@ -124,19 +131,20 @@
124
131
  column: $column,
125
132
  name: $name,
126
133
  entrypoint: $entrypoint,
127
- serviceUuid: $serviceUuid
134
+ serviceUuid: $serviceUuid,
135
+ dataSensitivityLevel: $dataSensitivityLevel
128
136
  ${this.operationName==="CollectNetworkHops"?", retryWithoutTraceId: $retryWithoutTraceId":""}
129
137
  )
130
138
  }
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`
139
+ `}}class Ze extends I.BaseTransmitter{serviceIdentifier=new z;constructor(){super(),this.setOperationName("CollectNetworkRequest")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const t=setInterval(()=>{p.getConfig().serviceIdentificationReceived?clearInterval(t):this.serviceIdentifier.doSend({})},5e3);t&&typeof t=="object"&&"unref"in t&&t.unref()}async doSend(t){this.startBackgroundIdentify(),this.send(t)}getQuery(){return`
132
140
  mutation ${this.operationName}(
133
141
  $data: NetworkRequestInput!
134
142
  ) {
135
143
  ${this.queryName}(
136
144
  data: $data)
137
145
  }
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=`
146
+ `}async send(t){const e={data:{...t,dataSensitivityLevel:p.getConfig().dataSensitivityLevel}};await I.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),e)}}const se=[400,403];function ae(n,t){return t!=="none"&&(t==="all"||n==="GET"||n==="HEAD"||n==="OPTIONS")}class _t{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(t=[]){this.contextManager=p.ContextManager.getInstance(),t?.forEach(e=>{typeof e=="string"&&e.trim()&&this.contextManager.getExcludedDomains().add(e)}),p.getConfig().sfDebug&&console.log("[RequestInterceptor] Initialized with static excluded domains.")}extractIdsFromTraceHeader(t,e=this.HEADER_TRACING){let o;if(t instanceof Headers)o=t.get(e)??void 0;else{const s=e.toLowerCase();for(const[d,l]of Object.entries(t))if(d.toLowerCase()===s){o=l;break}}if(!o)return{};const r=o.split("/").filter(Boolean);return r.length<3?{}:{sessionId:r[0],pageVisitId:r[1],requestId:r[r.length-1]}}parseStackFrame(t){const e=/\((.*):(\d+):(\d+)\)$/.exec(t.trim());if(!e)return null;const[,o,r,s]=e;return{filePath:o,line:parseInt(r,10),column:parseInt(s,10)}}async getOriginalPosition(t,e,o){let r={source:t,line:e,column:o,name:null};if(t.includes("://"))return{originalPos:r};const s=t+".map";try{const d=JSON.parse($e.readFileSync(s,"utf-8"));let l=(await new ft.sourceMapExports.SourceMapConsumer(d)).originalPositionFor({line:e,column:o});l.source&&(r=l)}catch(d){p.getConfig().sfDebug&&console.error(`Could not read/parse map file at ${s}:`,d)}return{originalPos:r}}captureFirstUserLines(t,e=10,o=!1){const r=p.getConfig().sfDebug?10:e,s=Error.stackTraceLimit;Error.stackTraceLimit=Math.max(s,r);const d=new Error(Pe);Pe in Error&&Error.captureStackTrace(d,this.captureFirstUserLines);const l=P.stackToString(d.stack);Error.stackTraceLimit=s;const c=l.split(`
147
+ `).slice(1),i=[];for(const u of c)if(!(u.includes("node:internal")||u.includes("internal/modules")||u.includes("internal/process")||u.includes("node_modules")||u.includes(".next/server/chunks")||u.includes("RequestInterceptor")||u.includes("contextManager")||u.includes("setupConfig"))&&(i.push(u.trim()),i.length>=e))break;for(const u of i){const a=this.parseStackFrame(u);a?(async()=>{const{originalPos:f}=await this.getOriginalPosition(a.filePath,a.line,a.column);if(f){p.getConfig().sfDebug&&console.log("[RequestInterceptor] First user code line:",f);const h={line:f.line?.toString()||ee.UNKNOWN,column:f.column?.toString()||ee.NOT_CAPTURED,name:f.name||ee.NOT_CAPTURED,entrypoint:f.source,retryWithoutTraceId:o};t.doSend(h)}})():p.getConfig().sfDebug&&console.error("Could not parse stack line:",u)}}addReentrancyGuardHeaders(t){t.set(this.HEADER_LOG_GUARD,"true"),t.set(this.HEADER_PRINT_GUARD,"true"),t.set(this.HEADER_EXCEPTION_GUARD,"true")}shouldPropagateHeaders(t){const e=p.getConfig(),o=e.domainsToPropagateHeadersTo,r=e.domainsToNotPropagateHeadersTo||[],s=Array.from(p.DEFAULT_DOMAINS_TO_EXCLUDE);return!!ie(t,o)&&!(r.length>0&&ie(t,r))&&!ie(t,s)}addTracingHeaders(t,e){const o=this.shouldPropagateHeaders(e);if(o)this.addTracingHeader(t,e);else if(p.getConfig().sfDebug){let r=e;try{r=new URL(e).hostname}catch{}console.error(`[RequestInterceptor] Excluded domain: ${r}`)}return o}deriveTraceBaseAndParent(t){const e=t.split("/").filter(Boolean);return e.length<2?{base:t,parent:t}:{base:`${e[0]}/${e[1]}`,parent:t}}addTracingHeader(t,e){const o=I.getFuncspanOverride();if(o){const c=I.parseHeaderOverride(o);if(c&&c.sample_rate===0)return void(p.getConfig().sfDebug&&console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${e}`))}const r=this.contextManager.getOrSetSfTraceId(),{base:s,parent:d}=this.deriveTraceBaseAndParent(r),l=p.v4();t.set(this.HEADER_TRACING,`${s}/${l}`),t.set(Ue,d),p.getConfig().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${e}`)}patchFetch(t,e){const o=globalThis.fetch;typeof o=="function"?globalThis.fetch=async(r,s)=>{const d=new Headers(s?.headers);if(d.get(this.HEADER_LOG_GUARD)==="true"||d.get(this.HEADER_PRINT_GUARD)==="true"||d.get(this.HEADER_EXCEPTION_GUARD)==="true")return o(r,s);this.captureFirstUserLines(t);const l=Date.now();let c,i="GET";if(typeof r=="string"||r instanceof URL)c=r.toString(),i=(s?.method||"GET").toUpperCase();else{if(!(r instanceof Request))return p.getConfig().sfDebug&&console.error("[Sailfish RequestInterceptor] Invalid fetch input."),o(r,s);c=r.url,i=r.method.toUpperCase(),r.headers.forEach((v,E)=>{d.set(E,v)})}p.getConfig().sfDebug&&console.log("[RequestInterceptor] Fetching request to:",c);let u="unknown";try{u=new URL(c).hostname}catch{return p.getConfig().sfDebug&&console.warn(`[RequestInterceptor] Could not parse URL '${c}' — passing through without tracing headers.`),o(r,s)}const a=new Headers(d),f=this.addTracingHeaders(d,c),h=v=>r instanceof Request?[new Request(r,{...s||{},headers:v}),void 0]:[c,{...s,headers:v}],m=p.getConfig().retryOnClientError;let g,y=!1;try{const[v,E]=h(d);if(g=await o(v,E),f&&ae(i,m)&&se.includes(g.status)){const[C,$]=h(a);g=await o(C,$),y=!0;try{this.captureFirstUserLines(t,10,y)}catch(k){p.getConfig().sfDebug&&console.error("[RequestInterceptor] captureFirstUserLines (retry) failed:",k)}}else try{this.contextManager.addSupportedDomains(u)}catch(C){p.getConfig().sfDebug&&console.error("[RequestInterceptor] addSupportedDomains failed:",C)}}catch(v){const E=Date.now();p.getConfig().sfDebug&&console.error(`[RequestInterceptor] Fetch failed: ${c}, Error: ${v}, Duration: ${E-l}ms`);try{const{sessionId:C,pageVisitId:$,requestId:k}=this.extractIdsFromTraceHeader(d),T=p.getConfig();e.doSend({apiKey:T.apiKey,requestId:k,pageVisitId:$,recordingSessionId:C,serviceUuid:T.serviceUUID,timestampStart:l.toString(),timestampEnd:E.toString(),responseCode:0,success:!1,error:v instanceof Error?v.message:typeof v=="string"?v:JSON.stringify(v),url:c,method:i,retryWithoutTraceId:y,parentSpanId:p.getCurrentFunctionSpanId()})}catch(C){p.getConfig().sfDebug&&console.error("[RequestInterceptor] Error telemetry send failed:",C)}throw v}const S=Date.now();try{p.getConfig().sfDebug&&console.log(`[RequestInterceptor] Fetch completed: ${c}, Status: ${g.status}, Duration: ${S-l}ms`);const{sessionId:v,pageVisitId:E,requestId:C}=this.extractIdsFromTraceHeader(d),$=p.getConfig(),k={apiKey:$.apiKey,requestId:C,pageVisitId:E,recordingSessionId:v,serviceUuid:$.serviceUUID,timestampStart:l.toString(),timestampEnd:S.toString(),responseCode:g.status,success:!0,error:null,url:c,method:i,retryWithoutTraceId:y,parentSpanId:p.getCurrentFunctionSpanId()};if($.captureRequestHeaders){const _={};d.forEach((N,F)=>{_[F]=N}),k.requestHeaders=_}if($.captureResponseHeaders){const _={};g.headers.forEach((N,F)=>{_[F]=N}),k.responseHeaders=_}if($.captureRequestBody&&s?.body){const _=s.body,N=$.requestBodyLimitBytes;try{if(typeof _=="string")k.requestBody=_.length>N?_.substring(0,N)+"...[truncated]":_;else if(_ instanceof URLSearchParams){const F=_.toString();k.requestBody=F.length>N?F.substring(0,N)+"...[truncated]":F}else if(typeof ArrayBuffer<"u"&&(_ instanceof ArrayBuffer||ArrayBuffer.isView(_))){const F=_.byteLength??_.byteLength;k.requestBody=`[binary body, ${F} bytes — not captured]`}else if(typeof Blob<"u"&&_ instanceof Blob)k.requestBody=`[Blob, ${_.size} bytes, type=${_.type||"unknown"} — not captured]`;else if(typeof FormData<"u"&&_ instanceof FormData)k.requestBody="[FormData — not captured]";else if(typeof ReadableStream<"u"&&_ instanceof ReadableStream)k.requestBody="[ReadableStream — not captured]";else{const F=JSON.stringify(_);F&&F!=="{}"&&(k.requestBody=F.length>N?F.substring(0,N)+"...[truncated]":F)}}catch{}}let T;if($.captureResponseBody){const _=(g.headers.get("content-type")||"").toLowerCase();if(!_||_.includes("json")||_.includes("xml")||_.includes("text/")||_.includes("javascript")||_.includes("ecmascript")||_.includes("x-www-form-urlencoded")||_.includes("application/graphql")){const N=g.clone(),F=$.responseBodyLimitBytes;T=(async()=>{try{const M=await N.text(),H=M.length>F?M.substring(0,F)+"...[truncated]":M;try{e.doSend({...k,responseBody:H})}catch{}}catch{}})(),T.catch(()=>{})}else k.responseBody=`[non-text body, content-type=${_} — not captured]`}T||e.doSend(k)}catch(v){p.getConfig().sfDebug&&console.error("[RequestInterceptor] Post-fetch telemetry failed (response still returned):",v)}return g}:p.getConfig().sfDebug&&console.error("[RequestInterceptor] Fetch not available.")}setHeader(t,e,o){t instanceof Headers?t.set(e,o):t[e]=o}addTracingHeadersToPlainObject(t,e){const o=this.shouldPropagateHeaders(e);if(o){const r=I.getFuncspanOverride();if(r){const i=I.parseHeaderOverride(r);if(i&&i.sample_rate===0)return p.getConfig().sfDebug&&console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${e}`),!1}const s=this.contextManager.getOrSetSfTraceId(),{base:d,parent:l}=this.deriveTraceBaseAndParent(s),c=p.v4();t[this.HEADER_TRACING]=`${d}/${c}`,t[Ue]=l,p.getConfig().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${e}`)}else if(p.getConfig().sfDebug){let r=e;try{r=new URL(e).hostname}catch{}console.error(`[RequestInterceptor] Excluded domain: ${r}`)}return o}patchHttp(t,e){if(p.getConfig().sfDebug&&console.log("[RequestInterceptor] Initializing HTTP/HTTPS request patch..."),!x||typeof x.request!="function")return void(p.getConfig().sfDebug&&console.log("[RequestInterceptor] HTTP/HTTPS not available."));const o=x.request.bind(x),r=V.request.bind(V),s=(c,i,u,a=Fe)=>{let f,h;if(typeof c=="string"||c instanceof URL){const m=typeof c=="string"?new URL(c):c;f={...typeof i=="object"&&i!==null?i:{},protocol:m.protocol||a,hostname:m.hostname,port:m.port||void 0,path:m.pathname+m.search},h=typeof i=="function"?i:u}else f={...c},f.protocol||(f.protocol=a),h=typeof i=="function"?i:void 0;return f.headers||(f.headers={}),[f,h]},d=(c,i,u)=>{const[a,f]=s(c,i,u,Fe);try{const y=`${a.protocol}//${a.hostname}`;this.addTracingHeadersToPlainObject(a.headers,y),this.captureFirstUserLines(t)}catch(y){p.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTP request options:",y)}const h=(a.method||"GET").toUpperCase(),m=p.getConfig().retryOnClientError,g=(y,S,v)=>{try{const{sessionId:E,pageVisitId:C,requestId:$}=this.extractIdsFromTraceHeader(a.headers);e.doSend({apiKey:p.getConfig().apiKey,requestId:$,pageVisitId:C,recordingSessionId:E,serviceUuid:p.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:y.statusCode||0,success:!!y.statusCode&&y.statusCode<400,error:null,url:S,method:h,retryWithoutTraceId:v,parentSpanId:p.getCurrentFunctionSpanId()})}catch{}f?.(y)};return o(a,y=>{const S=`${a.protocol}//${a.hostname}`;let v=!1;try{v=this.shouldPropagateHeaders(S)}catch{v=!1}if(v&&ae(h,m)&&se.includes(y.statusCode||0)){y.resume();try{const{sessionId:C,pageVisitId:$,requestId:k}=this.extractIdsFromTraceHeader(a.headers);e.doSend({apiKey:p.getConfig().apiKey,requestId:k,pageVisitId:$,recordingSessionId:C,serviceUuid:p.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:y.statusCode||0,success:!1,error:null,url:S,method:h,retryWithoutTraceId:!1,parentSpanId:p.getCurrentFunctionSpanId()})}catch{}try{this.captureFirstUserLines(t,10,!0)}catch{}const E={...a,headers:{...a.headers}};return delete E.headers[this.HEADER_TRACING],void o(E,C=>{g(C,S,!0)}).end()}g(y,S,!1)})},l=(c,i,u)=>{const[a,f]=s(c,i,u,"https:");try{const y=`${a.protocol}//${a.hostname}`;this.addTracingHeadersToPlainObject(a.headers,y),this.captureFirstUserLines(t)}catch(y){p.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTPS request options:",y)}const h=(a.method||"GET").toUpperCase(),m=p.getConfig().retryOnClientError,g=(y,S,v)=>{try{const{sessionId:E,pageVisitId:C,requestId:$}=this.extractIdsFromTraceHeader(a.headers);e.doSend({apiKey:p.getConfig().apiKey,requestId:$,pageVisitId:C,recordingSessionId:E,serviceUuid:p.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:y.statusCode||0,success:!!y.statusCode&&y.statusCode<400,error:null,url:S,method:h,retryWithoutTraceId:v,parentSpanId:p.getCurrentFunctionSpanId()})}catch{}f?.(y)};return r(a,y=>{const S=`${a.protocol}//${a.hostname}`;let v=!1;try{v=this.shouldPropagateHeaders(S)}catch{v=!1}if(v&&ae(h,m)&&se.includes(y.statusCode||0)){y.resume();try{const{sessionId:C,pageVisitId:$,requestId:k}=this.extractIdsFromTraceHeader(a.headers);e.doSend({apiKey:p.getConfig().apiKey,requestId:k,pageVisitId:$,recordingSessionId:C,serviceUuid:p.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:y.statusCode||0,success:!1,error:null,url:S,method:h,retryWithoutTraceId:!1,parentSpanId:p.getCurrentFunctionSpanId()})}catch{}try{this.captureFirstUserLines(t,10,!0)}catch{}const E={...a,headers:{...a.headers}};return delete E.headers[this.HEADER_TRACING],void r(E,C=>{g(C,S,!0)}).end()}g(y,S,!1)})};x.request=d,V.request=l,x.get=(c,i,u)=>{const a=d(c,i,u);return a.end(),a},V.get=(c,i,u)=>{const a=l(c,i,u);return a.end(),a},p.getConfig().sfDebug&&console.log("✅ HTTP and HTTPS request/get methods patched globally.")}tryPatch(t,e){try{require.resolve(e),t()}catch{}}getExcludedDomains(){return[...this.contextManager.getExcludedDomains()]}}class Ct extends Ce{constructor(){super(),this.setOperationName("UpdateServiceDetails")}async doSend(){this.send()}async send(){const t=`
140
148
  ${this.queryType} ${this.operationName}(
141
149
  $apiKey: String!,
142
150
  $serviceUuid: String!,
@@ -178,7 +186,7 @@
178
186
  serviceRole: $serviceRole,
179
187
  )
180
188
  }
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}}};
189
+ `,e=p.getConfig(),o=this.getVariables({serviceIdentifier:e.serviceIdentifier,serviceVersion:e.serviceVersion,serviceAdditionalMetadata:e.serviceAdditionalMetadata,gitSha:e.gitSha||"",gitOrg:e.gitOrg||void 0,gitRepo:e.gitRepo||void 0,gitProvider:e.gitProvider||void 0,serviceDisplayName:e.serviceDisplayName||void 0,infrastructureType:e.infrastructureType||void 0,infrastructureDetails:e.infrastructureDetails||void 0,setupInterceptorsFile:e.setupInterceptorsFile||void 0,setupInterceptorsLine:e.setupInterceptorsLine||void 0,framework:e.framework||void 0,additionalFrameworks:e.additionalFrameworks?.length>0?e.additionalFrameworks:void 0,serviceRole:e.serviceRole||void 0});I.nonBlockingPost(this.endpoint,this.operationName,t,o)}}class wt{rootPaths;fileConfigs=new Map;functionConfigs=new Map;directoryConfigs=new Map;hasSailfishFiles=!1;runtimeModeEnabled=!1;debug;constructor(t=[process.cwd()],e=!1){this.rootPaths=t,this.debug=e||process.env.SF_DEBUG==="true"}async loadAllConfigs(){this.debug&&console.log("[FuncSpan ConfigLoader] Scanning for .sailfish files in:",this.rootPaths);const t=[];for(const e of this.rootPaths)mt.existsSync(e)?await this._walkDirectory(e,t):this.debug&&console.log(`[FuncSpan ConfigLoader] Root path does not exist: ${e}`);t.length>0?(this.hasSailfishFiles=!0,this.debug&&(console.log(`[FuncSpan ConfigLoader] Found ${t.length} .sailfish files:`),t.forEach(e=>console.log(`[FuncSpan ConfigLoader] - ${e}`)))):this.debug&&console.log("[FuncSpan ConfigLoader] No .sailfish files found - function spans disabled by default");for(const e of t)await this._loadConfigFile(e);await this._resolveInheritance(),this.debug&&console.log(`[FuncSpan ConfigLoader] Loaded ${this.fileConfigs.size} file configs, ${this.functionConfigs.size} function configs`)}getConfig(t,e){const o=this.hasSailfishFiles?I.getEnvConfig():I.getDefaultConfig(),r=this._getDirectoryConfig(t),s=A.normalize(t),d=this.fileConfigs.get(s)||{};let l={};if(e){const c=this.functionConfigs.get(s);c&&(l=c.get(e)||{})}return I.mergeConfigs(o,r,d,l)}hasRuntimeMode(){return this.runtimeModeEnabled}async _walkDirectory(t,e){try{const o=await we.readdir(t,{withFileTypes:!0});for(const r of o){const s=A.join(t,r.name);r.isFile()&&r.name===".sailfish"?e.push(s):r.name==="node_modules"||r.isDirectory()&&r.name.startsWith(".")&&r.name!==".sailfish"||r.isDirectory()&&await this._walkDirectory(s,e)}}catch(o){this.debug&&console.error(`[FuncSpan ConfigLoader] Error walking directory ${t}:`,o)}}async _loadConfigFile(t){try{const e=await we.readFile(t,"utf-8"),o=A.dirname(t);let r=null;try{r=JSON.parse(e)}catch{try{r=require("toml").parse(e)}catch{try{r=require("js-yaml").load(e)}catch(s){return void(this.debug&&console.error(`[FuncSpan ConfigLoader] Failed to parse ${t} as JSON, TOML, or YAML:`,s))}}}if(!r)return;r.runtime_mode===!0&&(this.runtimeModeEnabled=!0,this.debug&&console.log(`[FuncSpan ConfigLoader] Runtime mode ENABLED in ${t}`)),r.default&&this.directoryConfigs.set(o,r.default),r.files&&await this._expandFileGlobs(o,r.files,r.default||{}),r.functions&&this._storeFunctionConfigs(o,r.functions,r.default||{}),this.debug&&(console.log(`[FuncSpan ConfigLoader] Loaded config from ${t}`),console.log(`[FuncSpan ConfigLoader] Directory: ${o}`),console.log(`[FuncSpan ConfigLoader] Has default: ${!!r.default}`),console.log(`[FuncSpan ConfigLoader] File patterns: ${Object.keys(r.files||{}).length}`),console.log(`[FuncSpan ConfigLoader] Functions: ${Object.keys(r.functions||{}).length}`))}catch(e){this.debug&&console.error(`[FuncSpan ConfigLoader] Error loading ${t}:`,e)}}async _expandFileGlobs(t,e,o){for(const[r,s]of Object.entries(e))try{const d=A.join(t,r),l=await ht.glob(d,{absolute:!0,nodir:!0,ignore:["**/node_modules/**","**/.git/**"]});this.debug&&console.log(`[FuncSpan ConfigLoader] Pattern '${r}' matched ${l.length} files`);for(const c of l){const i=A.normalize(c),u=I.mergeConfigs(o,s);this.fileConfigs.set(i,u),this.debug&&l.length<=5&&console.log(`[FuncSpan ConfigLoader] - ${c}`)}}catch(d){this.debug&&console.error(`[FuncSpan ConfigLoader] Error expanding glob '${r}':`,d)}}_storeFunctionConfigs(t,e,o){for(const[r,s]of Object.entries(e)){const d=r.split("::");if(d.length!==2){this.debug&&console.warn(`[FuncSpan ConfigLoader] Invalid function pattern '${r}' (expected format: 'file.ts::functionName')`);continue}const[l,c]=d,i=A.normalize(A.join(t,l));this.functionConfigs.has(i)||this.functionConfigs.set(i,new Map);const u=this.functionConfigs.get(i),a=I.mergeConfigs(o,s);u.set(c,a),this.debug&&console.log(`[FuncSpan ConfigLoader] Function config: ${i}::${c}`)}}async _resolveInheritance(){}_getDirectoryConfig(t){let e=A.dirname(A.normalize(t));const o=[];for(;e&&e!==A.dirname(e);){const r=this.directoryConfigs.get(e);r&&o.unshift(r),e=A.dirname(e)}return o.reduce((r,s)=>I.mergeConfigs(r,s),{})}}const et="__sf_globalConfigLoader";function tt(){return globalThis[et]??null}async function Te(n,t){const e=new wt(n,t);(function(o){globalThis[et]=o})(e),await e.loadAllConfigs()}function qe(n,t){const e=tt();return e?e.getConfig(n,t):(process.env.SF_DEBUG==="true"&&console.log("[FuncSpan ConfigLoader] Config loader not initialized, using default config (disabled)"),I.getDefaultConfig())}function Le(){return tt()!==null}const kt=["readFile","writeFile","appendFile","readdir","stat","lstat","fstat","access","open","close","read","write","chmod","mkdir","rmdir","unlink","rename"],Ae=["lookup","resolve","resolve4","resolve6","resolveAny","resolveMx","resolveNs","resolveTxt","reverse"],Ut=["pbkdf2","randomBytes","scrypt","generateKeyPair"],Pt=["gzip","gunzip","deflate","inflate","deflateRaw","inflateRaw","brotliCompress","brotliDecompress"];let Be=!1;function Ft(n){if(typeof n!="string")return!1;const t=process.env.SF_FUNCSPAN_JSONL_FILE;if(t&&n.includes(t))return!0;const e=process.env.SF_WORKER_POOL_JSONL_FILE;return!(!e||!n.includes(e))}let Oe=!1;function Re(n){if(typeof n!="string")return!1;if(n==="localhost"||n==="127.0.0.1"||n==="::1")return!0;try{const t=process.env.API_GRAPHQL_ENDPOINT;if(t&&n===new URL(t).hostname)return!0}catch{}return!1}function Dt(){if(!Oe)try{let n;if(typeof require>"u")return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Skipping dns patching in pure ESM environment (require unavailable)"));try{n=require("node:dns")}catch(t){return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Failed to require dns module:",t))}if(n.__sf_worker_pool_patched__)return;Object.defineProperty(n,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Ae)if(typeof n[t]=="function"){const e=n[t];n[t]=function(...o){return I.isSendingInternalTelemetry()?e.apply(this,o):Re(o[0])?e.apply(this,o):typeof o[o.length-1]=="function"?I.captureWorkerPoolOperation("dns",t,e,o,this):e.apply(this,o)},Object.defineProperty(n[t],"name",{value:t,writable:!1})}(function(t){if(!t.promises)return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises not available, skipping"));if(!t.promises.__sf_worker_pool_patched__){Object.defineProperty(t.promises,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of Ae)if(typeof t.promises[e]=="function"){const o=t.promises[e];t.promises[e]=function(...r){return I.isSendingInternalTelemetry()?o.apply(this,r):Re(r[0])?o.apply(this,r):I.captureWorkerPoolPromiseOperation("dns",e,o,r,this)},Object.defineProperty(t.promises[e],"name",{value:e,writable:!1})}process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises module patched successfully")}})(n),Oe=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns module patched successfully")}catch(n){console.error("[WorkerPool] Error patching dns module:",n)}}let Me=!1,He=!1,pe=!1;function xe(){if(pe)return;const n=process.env.SF_DEBUG==="true";n&&console.log("[WorkerPool] Initializing worker pool patching..."),I.isModuleTrackingEnabled("fs")&&(n&&console.log("[WorkerPool] Patching fs module..."),(function(){if(!Be)try{const t=require("node:fs");if(t.__sf_worker_pool_patched__)return;Object.defineProperty(t,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of kt)if(typeof t[e]=="function"){const o=t[e];t[e]=function(...r){return Ft(r[0])?o.apply(this,r):typeof r[r.length-1]=="function"?I.captureWorkerPoolOperation("fs",e,o,r,this):o.apply(this,r)},Object.defineProperty(t[e],"name",{value:e,writable:!1})}Be=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] fs module patched successfully")}catch(t){console.error("[WorkerPool] Error patching fs module:",t)}})()),I.isModuleTrackingEnabled("dns")&&(n&&console.log("[WorkerPool] Patching dns module..."),Dt()),I.isModuleTrackingEnabled("crypto")&&(n&&console.log("[WorkerPool] Patching crypto module..."),(function(){if(!Me)try{const t=require("node:crypto");if(t.__sf_worker_pool_patched__)return;Object.defineProperty(t,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of Ut)if(typeof t[e]=="function"){const o=t[e];t[e]=function(...r){return typeof r[r.length-1]=="function"?I.captureWorkerPoolOperation("crypto",e,o,r,this):o.apply(this,r)},Object.defineProperty(t[e],"name",{value:e,writable:!1})}Me=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] crypto module patched successfully")}catch(t){console.error("[WorkerPool] Error patching crypto module:",t)}})()),I.isModuleTrackingEnabled("zlib")&&(n&&console.log("[WorkerPool] Patching zlib module..."),(function(){if(!He)try{const t=require("node:zlib");if(t.__sf_worker_pool_patched__)return;Object.defineProperty(t,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of Pt)if(typeof t[e]=="function"){const o=t[e];t[e]=function(...r){return typeof r[r.length-1]=="function"?I.captureWorkerPoolOperation("zlib",e,o,r,this):o.apply(this,r)},Object.defineProperty(t[e],"name",{value:e,writable:!1})}He=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] zlib module patched successfully")}catch(t){console.error("[WorkerPool] Error patching zlib module:",t)}})()),pe=!0,n&&console.log("[WorkerPool] Worker pool patching initialized")}function je(){return pe}const Ke=Q.toLowerCase();function K(n){if(n!=null){if(Array.isArray(n)){for(const t of n)if(!(!t||typeof t!="object")&&We(t.key)===Ke)return t.value}else if(typeof n=="object"){for(const[t,e]of Object.entries(n))if(We(t)===Ke)return Array.isArray(e)?e.length===0?void 0:e[0]:e}}}function We(n){if(typeof n=="string")return n.toLowerCase();if(Buffer.isBuffer(n))try{return n.toString("utf8").toLowerCase()}catch{return null}if(n instanceof Uint8Array)try{return Buffer.from(n).toString("utf8").toLowerCase()}catch{return null}return null}let ce=null;function nt(){return ce||(ce=new Ze),ce}function rt(n){if(!n)return null;const t=n.split("/").filter(Boolean);return t.length<3?null:{sessionId:t[0],pageVisitId:t[1],requestId:t[t.length-1]}}const Nt=/^[A-Za-z0-9._:-]{1,128}$/;function W(n){if(typeof n!="string"||n.length===0||n.length>1024)return!1;const t=n.split("/").filter(Boolean);if(t.length<3||t.length>6)return!1;for(const e of t)if(!Nt.test(e))return!1;return!0}function J(n){const t=n.split("/");return t.length>=3?(t[t.length-1]=p.v4(),t.join("/")):`${n}/${p.v4()}`}function Tt(n){if(n==null)return null;if(typeof n=="string")return n;if(Buffer.isBuffer(n))try{return n.toString("utf8")}catch{return null}try{return JSON.stringify(ge(n))}catch{return null}}function ge(n,t=0){if(t>10)return"[truncated-depth]";if(n==null)return n;const e=typeof n;if(e==="string"||e==="number"||e==="boolean")return n;if(e==="bigint")return n.toString();if(e!=="object")return;if(Buffer.isBuffer(n))return`[Buffer ${n.length}b]`;if(ArrayBuffer.isView(n)){const r=n;return`[${r.constructor?.name??"TypedArray"} ${r.byteLength}b]`}if(n instanceof Date)try{return n.toISOString()}catch{return"[Date]"}if(n instanceof Map)return`[Map size=${n.size}]`;if(n instanceof Set)return`[Set size=${n.size}]`;if(Array.isArray(n))return n.map(r=>ge(r,t+1));const o={};for(const r of Object.getOwnPropertyNames(n)){const s=Object.getOwnPropertyDescriptor(n,r);s&&typeof s.get!="function"&&typeof s.set!="function"&&(o[r]=ge(s.value,t+1))}return o}function ot(n){if(!n)return null;try{const t=n.message;if(typeof t=="string"&&t.length>0)return t}catch{}try{const t=String(n);if(typeof t=="string"&&t.length>0)return t}catch{}try{const t=n.name;if(typeof t=="string"&&t.length>0)return t}catch{}return"[unstringifiable error]"}function D(n){const t=p.ContextManager.getInstance().getOrSetSfTraceId(),e=J(t),o=rt(e),r=Date.now(),s=p.getConfig(),d=n.queueUri,l=n.method??"ENQUEUE",c=it(n.messagePayload,s);return{traceId:e,hopEnd:i=>{try{if(!o)return;const u=Date.now();let a=null;try{a=p.getCurrentFunctionSpanId()??null}catch{}const f={apiKey:s.apiKey,requestId:o.requestId,pageVisitId:o.pageVisitId,recordingSessionId:o.sessionId,serviceUuid:s.serviceUUID??null,timestampStart:r.toString(),timestampEnd:u.toString(),responseCode:i?500:0,success:!i,error:ot(i),url:d,method:l,parentSpanId:a};c!==null&&(f.requestBody=c),st(f);try{nt().doSend(f)}catch(h){s.sfDebug&&console.warn("[asyncQueues] producer hop transmit failed:",h)}}catch{}}}}function it(n,t){if(!t.captureRequestBody||n===void 0)return null;const e=Tt(n);return e?(function(o,r){return!r||r<=0?o:o.length>r?o.substring(0,r)+"...[truncated]":o})(e,t.requestBodyLimitBytes):null}function O(n,t){if(Je.getStore()===!0)return Promise.resolve(t());const e=p.ContextManager.getInstance(),o=p.getConfig(),r=n.incomingTraceId!==void 0&&W(n.incomingTraceId)?n.incomingTraceId:`${p.NONSESSION_APPLOGS}-v3/${o.apiKey}/${p.v4()}`,s=n.queueUri,d=n.method,l=n.library,c=it(n.messagePayload,o);return Je.run(!0,()=>e.runScoped({traceId:r},async()=>{const i=Date.now();let u=null;try{const a=await Promise.resolve(t());return await(function(f){return f!==null&&typeof f=="object"&&typeof f.subscribe=="function"?new Promise((h,m)=>{let g,y=!1;try{f.subscribe({next:S=>{g=S,y=!0},error:S=>m(S),complete:()=>h(y?g:void 0)})}catch(S){m(S)}}):f})(a)}catch(a){throw u=a instanceof Error?a:new Error(String(a)),a}finally{(function(a,f,h,m,g,y){try{const S=rt(h);if(!S)return;const v=p.getConfig(),{graceful:E,tag:C}=(function(M){if(!M)return{graceful:!0,tag:null};let H;try{H=M.name}catch{return{graceful:!1,tag:null}}return H==="AbortError"?{graceful:!0,tag:"CONSUME_CANCELLED"}:H==="DelayedError"?{graceful:!0,tag:"CONSUME_RESCHEDULED"}:H==="WaitingChildrenError"?{graceful:!0,tag:"CONSUME_WAITING_CHILDREN"}:{graceful:!1,tag:null}})(y),$=!y&&a.method?a.method:C??a.method??"CONSUME",k=!y||E,T=y&&!E?500:0,_=y&&!E?ot(y):null;let N=null;try{N=p.getCurrentFunctionSpanId()??null}catch{}const F={apiKey:v.apiKey,requestId:S.requestId,pageVisitId:S.pageVisitId,recordingSessionId:S.sessionId,serviceUuid:v.serviceUUID??null,timestampStart:m.toString(),timestampEnd:g.toString(),responseCode:T,success:k,error:_,url:a.queueUri,method:$,parentSpanId:N};f!==null&&(F.requestBody=f),st(F);try{nt().doSend(F)}catch(M){v.sfDebug&&console.warn("[asyncQueues] consumer hop transmit failed:",M)}}catch{}})({library:l,queueUri:s,method:d},c,r,i,Date.now(),u)}}))}const Je=new yt.AsyncLocalStorage;let he=null;function st(n){if(he!==null)try{he(n)}catch{}}const b=Symbol.for("sailfish.async-queues.patched"),w=Symbol.for("sailfish.async-queues.instance-wrapped"),ye=[];function U(n,t,e){if(ye.some(r=>r.proto===n&&r.key===t))return!1;const o=typeof n?.[t]=="function"?n[t]:void 0;try{return n[t]=e,ye.push({proto:n,key:t,original:o}),!0}catch(r){if(p.getConfig().sfDebug){const s=n?.constructor?.name??"<unknown>";console.warn(`[asyncQueues] could not install patch on ${s}.prototype.${t} (frozen / non-writable?):`,r)}return!1}}function L(n,t){try{return n()}catch(e){return p.getConfig().sfDebug&&console.warn(`[asyncQueues] instrumentation rewrite threw in ${t} — falling back to original args, no hop emitted:`,e),null}}function q(n,t){let e=n||"unknown";if(typeof e=="string"){e.startsWith("bull:")&&(e=e.slice(5));const o=/^\{([^}]+)\}:(.+)$/.exec(e);o&&(e=`${o[1]}/${o[2]}`)}return`bullmq://redis/${e}/${t||"unknown"}`}function te(n){return n?.queueQualifiedName??n?.queueName??n?.queue?.name??void 0}function B(n,t){const e=n?{...n}:{},o=e.sf&&typeof e.sf=="object"?e.sf:{};return e.sf={...o,rid:t},e}function qt(n){let t=n;if(!t)try{t=require("bullmq")}catch{return"not-installed"}(function(c){try{const i=c?.version??c?.Queue?.version;if(typeof i!="string")return;parseInt(i.split(".")[0]??"0",10)<3&&p.getConfig().sfDebug&&console.warn(`[sf-veritas] BullMQ ${i} detected. Async-queue tracing is best-supported on BullMQ ≥ 3.0. Some APIs (FlowProducer, upsertJobScheduler, Job.promote) may be missing on older versions and will be skipped silently.`)}catch{}})(t);const e=t.Queue,o=t.Worker;if(!e?.prototype||!o?.prototype)return p.getConfig().sfDebug&&console.warn("[asyncQueues][bullmq] Expected Queue/Worker classes not found on module — skipping patch."),"failed";(function(c){const i=c.prototype.add;if(typeof i!="function"||i[b])return;const u=async function(a,f,h){if(h?.sf?.rid)return i.call(this,a,f,h);const m=L(()=>{const y=D({library:"bullmq",queueUri:q(this?.name,a),messagePayload:f});return{handle:y,nextOpts:B(h,y.traceId)}},"bullmq.Queue.add");if(m===null)return i.call(this,a,f,h);let g=null;try{return await i.call(this,a,f,m.nextOpts)}catch(y){throw g=y instanceof Error?y:new Error(String(y)),y}finally{m.handle.hopEnd(g)}};u[b]=!0,U(c.prototype,"add",u)})(e),(function(c){const i=c.prototype.addBulk;if(typeof i!="function"||i[b])return;const u=async function(a){if(!Array.isArray(a)||a.length===0)return i.call(this,a);if(a.every(g=>g?.opts?.sf?.rid))return i.call(this,a);const f=p.getConfig().bullmqBulkAggregateMode,h=L(()=>{if(f){const S=D({library:"bullmq",queueUri:q(this?.name,`__bulk_${a.length}`),method:"ENQUEUE_BULK",messagePayload:{batchSize:a.length}}),v=a.map(E=>({...E,opts:B(E?.opts,S.traceId)}));return{handles:[S],out:v}}const g=a.map(S=>D({library:"bullmq",queueUri:q(this?.name,S?.name),messagePayload:S?.data})),y=a.map((S,v)=>({...S,opts:B(S?.opts,g[v].traceId)}));return{handles:g,out:y}},"bullmq.Queue.addBulk");if(h===null)return i.call(this,a);let m=null;try{return await i.call(this,h.out)}catch(g){throw m=g instanceof Error?g:new Error(String(g)),g}finally{for(const g of h.handles)g.hopEnd(m)}};u[b]=!0,U(c.prototype,"addBulk",u)})(e),(function(c){const i=c.prototype.upsertJobScheduler;if(typeof i!="function"||i[b])return;const u=async function(a,f,h){const m=L(()=>{const y=D({library:"bullmq",queueUri:q(this?.name,h?.name??a),method:"ENQUEUE"});let S;if(h!==void 0){const v={...h,opts:B(h.opts,y.traceId)};S=[a,f,v]}else S=[a,f];return{handle:y,callArgs:S}},"bullmq.Queue.upsertJobScheduler");if(m===null){const y=h!==void 0?[a,f,h]:[a,f];return i.call(this,...y)}let g=null;try{return await i.call(this,...m.callArgs)}catch(y){throw g=y instanceof Error?y:new Error(String(y)),y}finally{m.handle.hopEnd(g)}};u[b]=!0,U(c.prototype,"upsertJobScheduler",u)})(e),(function(c){const i=c.prototype.getNextJob;if(typeof i!="function"||i[b])return;const u=async function(...a){const f=await i.apply(this,a);if(f&&W(f.opts?.sf?.rid))try{p.ContextManager.getInstance().setTraceId(f.opts.sf.rid)}catch{}return f};u[b]=!0,U(c.prototype,"getNextJob",u)})(e),(function(c){const i=c.prototype.getJob;if(typeof i!="function"||i[b])return;const u=async function(...a){const f=await i.apply(this,a);if(f&&W(f.opts?.sf?.rid))try{const m=p.ContextManager.getInstance();(!(h=m.getTraceId())||h.startsWith("nonsession-applogs-v3/"))&&m.setTraceId(f.opts.sf.rid)}catch{}var h;return f};u[b]=!0,U(c.prototype,"getJob",u)})(e),(function(c){const i=c.prototype.processJob;if(typeof i!="function"||i[b])return;const u=function(a,...f){const h=a?.opts?.sf?.rid,m=typeof a?.attemptsMade=="number"?a.attemptsMade:0,g=typeof a?.stalledCounter=="number"?a.stalledCounter:0,y=a?.repeatJobKey!=null||a?.opts?.repeat!=null,S=h&&(m>0||g>0||y)?J(h):h;let v;return g>0?v="CONSUME_STALLED":y&&m===0&&(v="CONSUME_SCHEDULED"),O({library:"bullmq",queueUri:q(te(a)??this?.name,a?.name),incomingTraceId:S,messagePayload:a?.data,method:v},()=>i.call(this,a,...f))};u[b]=!0,U(c.prototype,"processJob",u)})(o);const r=t.Job;r?.prototype&&(function(c){const i=["retry","moveToDelayed","promote"];for(const u of i){const a=c.prototype[u];if(typeof a!="function"||a[b])continue;const f=u==="promote"?"PROMOTE":u==="moveToDelayed"?"RESCHEDULE":"ENQUEUE_RETRY",h=async function(...m){const g=this?.opts?.sf?.rid;let y;if(g)y=J(g);else{const E=D({queueUri:q(te(this)??this?.name,this?.name),method:f});let C=null;try{return await a.apply(this,m)}catch($){throw C=$ instanceof Error?$:new Error(String($)),$}finally{E.hopEnd(C)}}this.opts&&(this.opts={...this.opts,sf:{...this.opts.sf||{},rid:y}});const S=D({queueUri:q(te(this)??this?.name,this?.name),method:f});let v=null;try{return await a.apply(this,m)}catch(E){throw v=E instanceof Error?E:new Error(String(E)),E}finally{S.hopEnd(v)}};h[b]=!0,U(c.prototype,u,h)}})(r);const s=t.QueueEvents;s?.prototype&&(s.prototype[b]=!1);const d=t.FlowProducer;return d?.prototype&&((function(c){const i=c.prototype.add;if(typeof i!="function"||i[b])return;const u=async function(a,...f){if(!a||typeof a!="object")return i.call(this,a,...f);if(a?.opts?.sf?.rid)return i.call(this,a,...f);const h=L(()=>{const g=[];return{hops:g,out:me(a,g)}},"bullmq.FlowProducer.add");if(h===null)return i.call(this,a,...f);let m=null;try{return await i.call(this,h.out,...f)}catch(g){throw m=g instanceof Error?g:new Error(String(g)),g}finally{for(const g of h.hops)g.hopEnd(m)}};u[b]=!0,U(c.prototype,"add",u)})(d),(function(c){const i=c.prototype.addBulk;if(typeof i!="function"||i[b])return;const u=async function(a){if(!Array.isArray(a)||a.length===0)return i.call(this,a);if(a.every(g=>g?.opts?.sf?.rid))return i.call(this,a);const f=p.getConfig().bullmqBulkAggregateMode,h=L(()=>{if(f){const S=$=>{let k=1;if(Array.isArray($?.children))for(const T of $.children)k+=S(T);return k},v=a.reduce(($,k)=>$+S(k),0),E=D({library:"bullmq-flow",queueUri:q(a[0]?.queueName,`__flow_bulk_${a.length}`),method:"ENQUEUE_BULK",messagePayload:{batchSize:a.length,totalNodes:v}}),C=a.map($=>at($,E.traceId));return{hops:[E],out:C}}const g=[],y=a.map(S=>me(S,g));return{hops:g,out:y}},"bullmq.FlowProducer.addBulk");if(h===null)return i.call(this,a);let m=null;try{return await i.call(this,h.out)}catch(g){throw m=g instanceof Error?g:new Error(String(g)),g}finally{for(const g of h.hops)g.hopEnd(m)}};u[b]=!0,U(c.prototype,"addBulk",u)})(d)),t.QueueScheduler?.prototype&&p.getConfig().sfDebug&&console.log("[sf-veritas] BullMQ QueueScheduler detected (v4 API). No direct instrumentation needed — delayed/repeatable jobs are traced when the Worker picks them up via the Worker.processJob wrap."),"installed"}function me(n,t){const e=D({queueUri:q(n?.queueName,n?.name),messagePayload:n?.data});t.push(e);const o={...n,opts:B(n?.opts,e.traceId)};return Array.isArray(n?.children)&&n.children.length>0&&(o.children=n.children.map(r=>me(r,t))),o}function at(n,t){const e={...n,opts:B(n?.opts,t)};return Array.isArray(n?.children)&&n.children.length>0&&(e.children=n.children.map(o=>at(o,t))),e}function Lt(n){let t=n;if(!t)try{t=require("@taskforcesh/bullmq-pro")}catch{return"not-installed"}const e=t.QueuePro,o=t.WorkerPro;t.JobPro;const r=t.FlowProducerPro;return e?.prototype||o?.prototype?(e?.prototype&&((function(s){const d=s.prototype.add;if(typeof d!="function"||d[b])return;const l=async function(c,i,u){if(u?.sf?.rid)return d.call(this,c,i,u);const a=L(()=>{const h=D({library:"bullmq-pro",queueUri:q(this?.name,c),messagePayload:i});return{handle:h,nextOpts:B(u,h.traceId)}},"bullmq-pro.QueuePro.add");if(a===null)return d.call(this,c,i,u);let f=null;try{return await d.call(this,c,i,a.nextOpts)}catch(h){throw f=h instanceof Error?h:new Error(String(h)),h}finally{a.handle.hopEnd(f)}};l[b]=!0,U(s.prototype,"add",l)})(e),(function(s){const d=s.prototype.addBulk;if(typeof d!="function"||d[b])return;const l=async function(c){if(!Array.isArray(c)||c.length===0)return d.call(this,c);if(c.every(f=>f?.opts?.sf?.rid))return d.call(this,c);const i=p.getConfig().bullmqBulkAggregateMode,u=L(()=>{if(i){const m=D({library:"bullmq-pro",queueUri:q(this?.name,`__bulk_${c.length}`),method:"ENQUEUE_BULK",messagePayload:{batchSize:c.length}}),g=c.map(y=>({...y,opts:B(y?.opts,m.traceId)}));return{handles:[m],out:g}}const f=c.map(m=>D({library:"bullmq-pro",queueUri:q(this?.name,m?.name),messagePayload:m?.data})),h=c.map((m,g)=>({...m,opts:B(m?.opts,f[g].traceId)}));return{handles:f,out:h}},"bullmq-pro.QueuePro.addBulk");if(u===null)return d.call(this,c);let a=null;try{return await d.call(this,u.out)}catch(f){throw a=f instanceof Error?f:new Error(String(f)),f}finally{for(const f of u.handles)f.hopEnd(a)}};l[b]=!0,U(s.prototype,"addBulk",l)})(e)),o?.prototype&&((function(s){const d=s.prototype.processJob;typeof d!="function"||d[b]||Qe(s,"processJob",d)})(o),(function(s){const d=s.prototype.getNextJob;if(typeof d!="function"||d[b])return;const l=async function(...c){const i=await d.apply(this,c);if(i&&W(i.opts?.sf?.rid))try{const a=p.ContextManager.getInstance();(!(u=a.getTraceId())||u.startsWith("nonsession-applogs-v3/"))&&a.setTraceId(i.opts.sf.rid)}catch{}var u;return i};l[b]=!0,U(s.prototype,"getNextJob",l)})(o),typeof o.prototype.callProcessJob=="function"&&(function(s){const d=s.prototype.callProcessJob;typeof d!="function"||d[b]||Qe(s,"callProcessJob",d)})(o)),r?.prototype&&(function(s){const d=s.prototype.add;if(typeof d!="function"||d[b])return;const l=async function(c,...i){if(!c||typeof c!="object")return d.call(this,c,...i);if(c?.opts?.sf?.rid)return d.call(this,c,...i);const u=L(()=>{const f=[];return{hops:f,out:ct(c,f)}},"bullmq-pro.FlowProducerPro.add");if(u===null)return d.call(this,c,...i);let a=null;try{return await d.call(this,u.out,...i)}catch(f){throw a=f instanceof Error?f:new Error(String(f)),f}finally{for(const f of u.hops)f.hopEnd(a)}};l[b]=!0,U(s.prototype,"add",l)})(r),"installed"):(p.getConfig().sfDebug&&console.warn("[asyncQueues][bullmq-pro] No QueuePro/WorkerPro found — patch no-op."),"failed")}function Qe(n,t,e){const o=function(r,...s){const d=r?.opts?.sf?.rid,l=typeof r?.attemptsMade=="number"?r.attemptsMade:0,c=typeof r?.stalledCounter=="number"?r.stalledCounter:0,i=r?.repeatJobKey!=null||r?.opts?.repeat!=null,u=W(d)&&(l>0||c>0||i)?J(d):W(d)?d:void 0;let a;return c>0?a="CONSUME_STALLED":i&&l===0&&(a="CONSUME_SCHEDULED"),O({library:"bullmq-pro",queueUri:q(te(r)??this?.name,r?.name),incomingTraceId:u,messagePayload:r?.data,method:a},()=>e.call(this,r,...s))};o[b]=!0,U(n.prototype,t,o)}function ct(n,t,e=0){if(e>100)return n;const o=D({queueUri:q(n?.queueName,n?.name),messagePayload:n?.data});t.push(o);const r={...n,opts:B(n?.opts,o.traceId)};return Array.isArray(n?.children)&&n.children.length>0&&(r.children=n.children.map(s=>ct(s,t,e+1))),r}const Se=Q.toLowerCase();function j(n){if(n!=null){if(typeof n=="string")return n;if(Buffer.isBuffer(n))try{return n.toString("utf8")}catch{return}if(n instanceof Uint8Array)try{return Buffer.from(n).toString("utf8")}catch{return}return String(n)}}function R(n,t="broker"){return`kafka://${t}/${n??"unknown"}`}function G(n){if(Array.isArray(n))for(const t of n){if(!t||typeof t!="object")continue;const e=t.key;if(typeof e=="string"&&e.toLowerCase()===Se)return j(t.value)}}function ut(n,t){const e=[];if(Array.isArray(n)){for(const o of n)if(o&&typeof o=="object"){const r=o.key,s=o.value;typeof r=="string"&&r.toLowerCase()===Se||e.push({key:String(r),value:Buffer.isBuffer(s)?s:Buffer.from(String(s??""))})}}else if(n&&typeof n=="object")for(const[o,r]of Object.entries(n))o.toLowerCase()!==Se&&e.push({key:o,value:Buffer.isBuffer(r)?r:Buffer.from(String(r??""))});return e.push({key:Q,value:Buffer.from(t)}),e}function At(n){let t=n;if(!t)try{t=require("@confluentinc/kafka-javascript")}catch{return"not-installed"}let e=!1;t.KafkaProducer?.prototype&&((function(r){const s=r.prototype.produce;if(typeof s!="function"||s[b])return;const d=function(...l){return l.length===1&&l[0]&&typeof l[0]=="object"&&Array.isArray(l[0].messages)?Bt.call(this,s,l[0]):Ot.call(this,s,l)};d[b]=!0,U(r.prototype,"produce",d)})(t.KafkaProducer),e=!0),t.KafkaConsumer?.prototype&&((function(r){const s=r.prototype.on;if(typeof s!="function"||s[b])return;const d=function(l,c){if(l!=="data"||typeof c!="function")return s.call(this,l,c);const i=function(u){const a=G(u?.headers),f=u?.topic,h=j(u?.value)??u?.value;return O({library:"confluent-kafka-js",queueUri:R(f),incomingTraceId:a,messagePayload:h},()=>c.call(this,u))};return s.call(this,l,i)};d[b]=!0,U(r.prototype,"on",d)})(t.KafkaConsumer),e=!0);const o=t.KafkaJS??t;return o?.Producer?.prototype?.send&&((function(r){const s=r.prototype.send;if(typeof s=="function"&&!s[b]){const c=be(s);c[b]=!0,U(r.prototype,"send",c)}const d=r.prototype.sendBatch;if(typeof d=="function"&&!d[b]){const c=ve(d);c[b]=!0,U(r.prototype,"sendBatch",c)}const l=r.prototype.transaction;if(typeof l=="function"&&!l[b]){const c=ze(l);c[b]=!0,U(r.prototype,"transaction",c)}})(o.Producer),e=!0),o?.Consumer?.prototype?.run&&((function(r){const s=r.prototype.run;if(typeof s!="function"||s[b])return;const d=async function(l){if(!l||typeof l!="object")return s.call(this,l);const c={...l};if(typeof l.eachMessage=="function"){const i=l.eachMessage;c.eachMessage=u=>{const a=j(K(u?.message?.headers))??G(u?.message?.headers),f=typeof u?.attempt=="number"?u.attempt:0,h=a&&f>0?J(a):a;return O({library:"confluent-kafka-js",queueUri:R(u?.topic),incomingTraceId:h},()=>i(u))}}if(typeof l.eachBatch=="function"){const i=l.eachBatch;c.eachBatch=u=>{let a=!1;try{typeof u?.isStale=="function"&&(a=!!u.isStale())}catch{}if(a)return i(u);const f=Array.isArray(u?.batch?.messages)?u.batch.messages[0]:void 0,h=j(K(f?.headers))??G(f?.headers);return O({library:"confluent-kafka-js",queueUri:R(u?.batch?.topic),incomingTraceId:h},()=>i(u))}}return s.call(this,c)};d[b]=!0,U(r.prototype,"run",d)})(o.Consumer),e=!0),typeof o?.Kafka=="function"&&o.Kafka.prototype&&((function(r){const s=r.prototype.producer;if(typeof s=="function"&&!s[b]){const l=function(...c){const i=s.apply(this,c);return i&&typeof i.send=="function"&&!i.send[w]&&(i.send=be(i.send.bind(i)),i.send[w]=!0),i&&typeof i.sendBatch=="function"&&!i.sendBatch[w]&&(i.sendBatch=ve(i.sendBatch.bind(i)),i.sendBatch[w]=!0),i&&typeof i.transaction=="function"&&!i.transaction[w]&&(i.transaction=ze(i.transaction.bind(i)),i.transaction[w]=!0),i};l[b]=!0,U(r.prototype,"producer",l)}const d=r.prototype.consumer;if(typeof d=="function"&&!d[b]){const l=function(...c){const i=d.apply(this,c);if(i&&typeof i.run=="function"&&!i.run[w]){const u=i.run.bind(i);i.run=async function(a){if(!a||typeof a!="object")return u(a);const f={...a};if(typeof a.eachMessage=="function"){const h=a.eachMessage;f.eachMessage=m=>{const g=j(K(m?.message?.headers))??G(m?.message?.headers);return O({library:"confluent-kafka-js",queueUri:R(m?.topic),incomingTraceId:g},()=>h(m))}}if(typeof a.eachBatch=="function"){const h=a.eachBatch;f.eachBatch=m=>{let g=!1;try{typeof m?.isStale=="function"&&(g=!!m.isStale())}catch{}if(g)return h(m);const y=Array.isArray(m?.batch?.messages)?m.batch.messages[0]:void 0,S=j(K(y?.headers))??G(y?.headers);return O({library:"confluent-kafka-js",queueUri:R(m?.batch?.topic),incomingTraceId:S},()=>h(m))}}return u(f)},i.run[w]=!0}return i};l[b]=!0,U(r.prototype,"consumer",l)}})(o.Kafka),e=!0),e?"installed":(p.getConfig().sfDebug&&console.warn("[asyncQueues][confluentKafkaJs] No recognizable Producer/Consumer/Kafka class — patch no-op."),"failed")}function Bt(n,t){const e=L(()=>{const r=t?.topic,s=t.messages.map(()=>D({library:"confluent-kafka-js",queueUri:R(r),method:"ENQUEUE_BUFFERED"})),d=t.messages.map((l,c)=>({...l,headers:ut(l?.headers,s[c].traceId)}));return{handles:s,outOptions:{...t,messages:d}}},"confluentKafkaJs.KafkaProducer.produce(object)");if(e===null)return n.call(this,t);let o=null;try{return n.call(this,e.outOptions)}catch(r){throw o=r instanceof Error?r:new Error(String(r)),r}finally{for(const r of e.handles)r.hopEnd(o)}}function Ot(n,t){const[e,o,r,s,d,l,c]=t,i=L(()=>{const a=D({library:"confluent-kafka-js",queueUri:R(typeof e=="string"?e:void 0),method:"ENQUEUE_BUFFERED"});return{handle:a,injectedHeaders:ut(c,a.traceId)}},"confluentKafkaJs.KafkaProducer.produce(positional)");if(i===null)return n.call(this,e,o,r,s,d,l,c);let u=null;try{return n.call(this,e,o,r,s,d,l,i.injectedHeaders)}catch(a){throw u=a instanceof Error?a:new Error(String(a)),a}finally{i.handle.hopEnd(u)}}function be(n,t={}){const e=t.method??"ENQUEUE",o=t.library??"confluent-kafka-js";return async function(r){if(!r||!Array.isArray(r.messages))return n.call(this,r);const s=L(()=>{const l=r.messages.map(()=>D({library:o,queueUri:R(r.topic),method:e})),c=r.messages.map((i,u)=>({...i,headers:{...i?.headers||{},[Q]:Buffer.from(l[u].traceId)}}));return{handles:l,outPayload:{...r,messages:c}}},`confluentKafkaJs.Producer.${e}`);if(s===null)return n.call(this,r);let d=null;try{return await n.call(this,s.outPayload)}catch(l){throw d=l instanceof Error?l:new Error(String(l)),l}finally{for(const l of s.handles)l.hopEnd(d)}}}function ve(n,t={}){const e=t.method??"ENQUEUE",o=t.library??"confluent-kafka-js";return async function(r){if(!r||!Array.isArray(r.topicMessages))return n.call(this,r);const s=L(()=>{const l=[],c=r.topicMessages.map(i=>{const u=(Array.isArray(i?.messages)?i.messages:[]).map(a=>{const f=D({library:o,queueUri:R(i?.topic),method:e});return l.push(f),{...a,headers:{...a?.headers||{},[Q]:Buffer.from(f.traceId)}}});return{...i,messages:u}});return{handles:l,outPayload:{...r,topicMessages:c}}},`confluentKafkaJs.Producer.sendBatch[${e}]`);if(s===null)return n.call(this,r);let d=null;try{return await n.call(this,s.outPayload)}catch(l){throw d=l instanceof Error?l:new Error(String(l)),l}finally{for(const l of s.handles)l.hopEnd(d)}}}function Ge(n,t){return async function(...e){const o=D({queueUri:"kafka://broker/_tx",method:t});let r=null;try{return await n.apply(this,e)}catch(s){throw r=s instanceof Error?s:new Error(String(s)),s}finally{o.hopEnd(r)}}}function ze(n){return async function(...t){const e=await n.apply(this,t);return e&&typeof e.send=="function"&&!e.send[w]&&(e.send=be(e.send.bind(e),{method:"ENQUEUE_TX",library:"confluent-kafka-js-tx"}),e.send[w]=!0),e&&typeof e.sendBatch=="function"&&!e.sendBatch[w]&&(e.sendBatch=ve(e.sendBatch.bind(e),{method:"ENQUEUE_TX",library:"confluent-kafka-js-tx"}),e.sendBatch[w]=!0),e&&typeof e.commit=="function"&&!e.commit[w]&&(e.commit=Ge(e.commit.bind(e),"COMMIT_TX"),e.commit[w]=!0),e&&typeof e.abort=="function"&&!e.abort[w]&&(e.abort=Ge(e.abort.bind(e),"ABORT_TX"),e.abort[w]=!0),e}}function ue(n){if(n!=null){if(typeof n=="string")return n;if(Buffer.isBuffer(n))try{return n.toString("utf8")}catch{return}if(n instanceof Uint8Array)try{return Buffer.from(n).toString("utf8")}catch{return}return String(n)}}function ne(n,t){return`kafka://broker/${n??"unknown"}`}function Rt(n){let t=n;if(!t)try{t=require("kafkajs")}catch{return"not-installed"}const e=t.Producer,o=t.Consumer;e?.prototype&&typeof e.prototype.send=="function"&&(function(s){const d=s.prototype.send;if(typeof d=="function"&&!d[b]){const i=Ie(d);i[b]=!0,U(s.prototype,"send",i)}const l=s.prototype.sendBatch;if(typeof l=="function"&&!l[b]){const i=Ee(l);i[b]=!0,U(s.prototype,"sendBatch",i)}const c=s.prototype.transaction;if(typeof c=="function"&&!c[b]){const i=Xe(c);i[b]=!0,U(s.prototype,"transaction",i)}})(e),o?.prototype&&typeof o.prototype.run=="function"&&(function(s){const d=s.prototype.run;if(typeof d!="function"||d[b])return;const l=Ye(d);l[b]=!0,U(s.prototype,"run",l)})(o);const r=t.Kafka;if(typeof r=="function"&&r.prototype)(function(s){const d=s.prototype.producer;if(typeof d=="function"&&!d[b]){const c=function(...i){const u=d.apply(this,i);return u&&typeof u.send=="function"&&!u.send[w]&&(u.send=Ie(u.send.bind(u)),u.send[w]=!0),u&&typeof u.sendBatch=="function"&&!u.sendBatch[w]&&(u.sendBatch=Ee(u.sendBatch.bind(u)),u.sendBatch[w]=!0),u&&typeof u.transaction=="function"&&!u.transaction[w]&&(u.transaction=Xe(u.transaction.bind(u)),u.transaction[w]=!0),u};c[b]=!0,U(s.prototype,"producer",c)}const l=s.prototype.consumer;if(typeof l=="function"&&!l[b]){const c=function(...i){const u=l.apply(this,i);return u&&typeof u.run=="function"&&!u.run[w]&&(u.run=Ye(u.run.bind(u)),u.run[w]=!0),u};c[b]=!0,U(s.prototype,"consumer",c)}})(r);else if(!e?.prototype&&!o?.prototype)return p.getConfig().sfDebug&&console.warn("[asyncQueues][kafkajs] No Kafka/Producer/Consumer class found — patch no-op."),"failed";return"installed"}function Ie(n,t={}){const e=t.method??"ENQUEUE",o=t.library??"kafkajs";return async function(r){if(!r||!Array.isArray(r.messages))return n.call(this,r);const s=L(()=>{const l=r.topic,c=r.messages.map(()=>D({library:o,queueUri:ne(l),method:e})),i=r.messages.map((a,f)=>lt(a,c[f].traceId)),u={...r,messages:i};return{handles:c,outPayload:u}},`kafkajs.Producer.${e}`);if(s===null)return n.call(this,r);let d=null;try{return await n.call(this,s.outPayload)}catch(l){throw d=l instanceof Error?l:new Error(String(l)),l}finally{for(const l of s.handles)l.hopEnd(d)}}}function Ee(n,t={}){const e=t.method??"ENQUEUE",o=t.library??"kafkajs";return async function(r){if(!r||!Array.isArray(r.topicMessages))return n.call(this,r);const s=L(()=>{const l=[],c=r.topicMessages.map(u=>{const a=u?.topic,f=(Array.isArray(u?.messages)?u.messages:[]).map(h=>{const m=D({library:o,queueUri:ne(a),method:e});return l.push(m),lt(h,m.traceId)});return{...u,messages:f}}),i={...r,topicMessages:c};return{handles:l,outPayload:i}},`kafkajs.Producer.sendBatch[${e}]`);if(s===null)return n.call(this,r);let d=null;try{return await n.call(this,s.outPayload)}catch(l){throw d=l instanceof Error?l:new Error(String(l)),l}finally{for(const l of s.handles)l.hopEnd(d)}}}function Ve(n,t){return async function(...e){const o=D({queueUri:"kafka://broker/_tx",method:t});let r=null;try{return await n.apply(this,e)}catch(s){throw r=s instanceof Error?s:new Error(String(s)),s}finally{o.hopEnd(r)}}}function Xe(n){return async function(...t){const e=await n.apply(this,t);return e&&typeof e.send=="function"&&!e.send[w]&&(e.send=Ie(e.send.bind(e),{method:"ENQUEUE_TX",library:"kafkajs-tx"}),e.send[w]=!0),e&&typeof e.sendBatch=="function"&&!e.sendBatch[w]&&(e.sendBatch=Ee(e.sendBatch.bind(e),{method:"ENQUEUE_TX",library:"kafkajs-tx"}),e.sendBatch[w]=!0),e&&typeof e.commit=="function"&&!e.commit[w]&&(e.commit=Ve(e.commit.bind(e),"COMMIT_TX"),e.commit[w]=!0),e&&typeof e.abort=="function"&&!e.abort[w]&&(e.abort=Ve(e.abort.bind(e),"ABORT_TX"),e.abort[w]=!0),e}}function lt(n,t){const e={...n?.headers||{}};return e[Q]=Buffer.from(t),{...n,headers:e}}function Ye(n){return async function(t){if(!t||typeof t!="object")return n.call(this,t);const e={...t};if(typeof t.eachMessage=="function"){const o=t.eachMessage;e.eachMessage=r=>(async function(s,d){const l=s?.topic,c=s?.message,i=ue(K(c?.headers)),u=typeof s?.attempt=="number"?s.attempt:0,a=i&&u>0?J(i):i,f=ue(c?.value)??c?.value;return O({library:"kafkajs",queueUri:ne(l),incomingTraceId:a,messagePayload:f},()=>d(s))})(r,o)}if(typeof t.eachBatch=="function"){const o=t.eachBatch;e.eachBatch=r=>(async function(s,d){let l=!1;try{typeof s?.isStale=="function"&&(l=!!s.isStale())}catch{}if(l)return d(s);const c=s?.batch?.topic,i=Array.isArray(s?.batch?.messages)?s.batch.messages[0]:void 0,u=ue(K(i?.headers));return O({library:"kafkajs",queueUri:ne(c),incomingTraceId:u},()=>d(s))})(r,o)}return n.call(this,e)}}function Mt(n){return process.env[n]==="true"}const Ht=[{name:"bullmq",envDisableKey:"SF_DISABLE_BULLMQ",install:()=>qt()},{name:"@taskforcesh/bullmq-pro",envDisableKey:"SF_DISABLE_BULLMQ_PRO",install:()=>Lt()},{name:"kafkajs",envDisableKey:"SF_DISABLE_KAFKAJS",install:()=>Rt()},{name:"@confluentinc/kafka-javascript",envDisableKey:"SF_DISABLE_CONFLUENT_KAFKA_JS",install:()=>At()}];let Y=!1,le=!1,de=!1,fe=null;function Z(n){const t=p.getGlobalConfigUnsafe(),e=t?.sfDebug||!1;e&&console.log("[FuncSpan] captureSpanData called for:",{function:n.functionName,file:n.filePath,duration:`${n.duration}ms`,async:n.async,error:n.error,spanId:n.spanId});const o={functionName:n.functionName,filePath:n.filePath,metadata:n.metadata,args:n.args,result:n.result,error:n.error,duration:n.duration,durationNs:n.durationNs,async:n.async,spanId:n.spanId,parentSpanId:n.parentSpanId};process.env.SF_FUNCSPAN_CONSOLE_OUTPUT==="true"&&console.log(`
190
+ 📊 Function Span:`,{function:`${n.functionName} (${n.filePath}:${n.metadata.line}:${n.metadata.column})`,duration:`${n.duration.toFixed(2)}ms`,arguments:n.args,result:n.error?`Error: ${n.error}`:n.result,spanId:n.spanId,parentSpanId:n.parentSpanId||"none"});const r=process.env.SF_FUNCSPAN_JSONL_FILE;if(r)try{const s=r==="true"||r==="1"?"funcspans.jsonl":r,d=Date.now(),l=process.hrtime.bigint(),c=BigInt(n.startTimeNs),i=Number(l-c)/1e6,u=new Date(d-i).toISOString(),a=JSON.stringify({timestamp:u,functionName:n.functionName,filePath:n.filePath,line:n.metadata.line,column:n.metadata.column,duration:n.duration,durationNs:n.durationNs,startTimeNs:n.startTimeNs,arguments:n.args,returnValue:n.error?{error:String(n.error)}:n.result,spanId:n.spanId,parentSpanId:n.parentSpanId,async:n.async,pid:n.pid,threadId:n.threadId})+`
191
+ `;$e.appendFileSync(s,a,"utf-8")}catch(s){console.error("[FuncSpan] Error writing to JSONL file:",s)}if(e&&console.log("[FuncSpan] Sending function span to transmitter:",o),process.env.SF_FUNCSPAN_SKIP_BACKEND!=="true")try{(fe||(fe=new I.FunctionSpanTransmitter),fe).send([o]),e&&console.log("[FuncSpan] Function span sent successfully")}catch(s){e&&console.error("[FuncSpan] Error sending function span:",s)}}exports.ContextManager=p.ContextManager,exports.getCurrentFunctionSpanId=p.getCurrentFunctionSpanId,exports.runWithContext=p.runWithContext,exports.clearFuncspanOverride=I.clearFuncspanOverride,exports.getDefaultConfig=I.getDefaultConfig,exports.getEnvConfig=I.getEnvConfig,exports.getFuncspanOverride=I.getFuncspanOverride,exports.parseHeaderOverride=I.parseHeaderOverride,exports.setFuncspanOverride=I.setFuncspanOverride,exports.isProductionEnvironment=P.isProductionEnvironment,exports.isRuntimeModeEnabled=P.isRuntimeModeEnabled,exports.shouldEnableRuntimeHooks=P.shouldEnableRuntimeHooks,exports.setSkipTypeScriptPlugin=re.setSkipTypeScriptPlugin,exports.transformFunctionSpans=re.transformFunctionSpans,exports.transformFunctionSpansSync=re.transformFunctionSpansSync,exports._setAsyncQueueHopSpy=function(n){he=n},exports.addOrUpdateMetadata=function(n,t={},e,o=!1){const r=p.getConfig();new ke(r.apiKey).addOrUpdateMetadata(n,t,e,o)},exports.captureFunctionSpan=function(n,t,e,o){const r=function(...s){const d=p.getGlobalConfigUnsafe(),l=d?.sfDebug||!1;l&&console.log(`[FuncSpan] captureFunctionSpan wrapper called for ${e}::${t}`);const c=(function(g,y){const S=I.getFuncspanOverride();if(S){const v=I.parseHeaderOverride(S);if(v)return process.env.SF_DEBUG==="true"&&console.log(`[FuncSpan] Using HTTP header override for ${g}::${y}`),v}try{return qe(g,y)}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}}})(e,t);if(l&&console.log(`[FuncSpan] Config for ${e}::${t}:`,c),c.enable_sampling&&c.sample_rate<1&&Math.random()>c.sample_rate)return l&&console.log(`[FuncSpan] Skipping ${t} due to sampling`),n.apply(this,s);if(c.sample_rate===0)return l&&console.log(`[FuncSpan] Skipping ${t} - sample_rate is 0.0`),n.apply(this,s);l&&console.log(`[FuncSpan] Capturing function span for ${t}`);const i=p.ContextManager.getInstance(),u=i.getCurrentFunctionSpanId(),a=p.v4();i.setCurrentFunctionSpanId(a);const f=process.hrtime.bigint(),h=Date.now();let m=null;c.capture_arguments&&(m={},o.paramNames.forEach((g,y)=>{y<s.length&&(m[g]=s[y])}),m&&c.arg_limit_mb>0&&(m=I.truncateToLimit(m,c.arg_limit_mb)));try{const g=n.apply(this,s);if(g&&typeof g.then=="function")return u?i.setCurrentFunctionSpanId(u):i.clearCurrentFunctionSpanId(),g.then(C=>{const $=process.hrtime.bigint(),k=Date.now(),T=Number($-f);let _=null;return c.capture_return_value&&c.return_limit_mb>0&&(_=I.truncateToLimit(C,c.return_limit_mb)),Z({functionName:t,filePath:e,metadata:o,args:m,result:_,error:null,duration:k-h,durationNs:T,startTimeNs:f.toString(),async:!0,spanId:a,parentSpanId:u,pid:process.pid,threadId:X.threadId}),C},C=>{const $=process.hrtime.bigint(),k=Date.now(),T=Number($-f);throw Z({functionName:t,filePath:e,metadata:o,args:m,result:null,error:C?.message||String(C),duration:k-h,durationNs:T,startTimeNs:f.toString(),async:!0,spanId:a,parentSpanId:u,pid:process.pid,threadId:X.threadId}),C});const y=process.hrtime.bigint(),S=Date.now(),v=Number(y-f);let E=null;return c.capture_return_value&&c.return_limit_mb>0&&(E=I.truncateToLimit(g,c.return_limit_mb)),Z({functionName:t,filePath:e,metadata:o,args:m,result:E,error:null,duration:S-h,durationNs:v,startTimeNs:f.toString(),async:!1,spanId:a,parentSpanId:u,pid:process.pid,threadId:X.threadId}),u?i.setCurrentFunctionSpanId(u):i.clearCurrentFunctionSpanId(),g}catch(g){const y=process.hrtime.bigint(),S=Date.now(),v=Number(y-f);throw Z({functionName:t,filePath:e,metadata:o,args:m,result:null,error:g?.message||String(g),duration:S-h,durationNs:v,startTimeNs:f.toString(),async:!1,spanId:a,parentSpanId:u,pid:process.pid,threadId:X.threadId}),u?i.setCurrentFunctionSpanId(u):i.clearCurrentFunctionSpanId(),g}};Object.defineProperty(r,"name",{value:t,writable:!1});for(const s in n)n.hasOwnProperty(s)&&(r[s]=n[s]);return r},exports.getGlobalConfig=qe,exports.identify=function(n,t,e,o=!1){const r=p.getConfig();new ke(r.apiKey).identify(n,t,e,o)},exports.initializeConfigLoader=Te,exports.initializeWorkerPoolPatching=xe,exports.isAlreadyInstrumented=function(n){return!!n.includes("captureFunctionSpan(")||!!n.includes("@sailfish-ai/sf-veritas")||!(!n.includes("/* @sailfish-instrumented */")&&!n.includes("// @sailfish-instrumented"))},exports.isAsyncQueuePatchesInstalled=function(){return Y},exports.isConfigLoaderInitialized=Le,exports.isSetupInterceptorsInitialized=function(){return le},exports.isWorkerPoolInitialized=je,exports.setupInterceptors=function(n){if(de)console.warn("[setupInterceptors] ⚠️ Recursive call detected and blocked!");else if(!le){de=!0,I.registerShutdownHooks();try{let t,e;const o=P.stackToString(new Error().stack);if(o){const l=o.split(`
192
+ `)[2]||"",c=l.match(/\((.+):(\d+):\d+\)/)||l.match(/at (.+):(\d+):\d+/);c&&(t=c[1],e=parseInt(c[2],10))}if(!n||!n.apiKey){const l=`The required API Key is not provided: ${JSON.stringify(n)}`;console.error(l)}const{config:r}=p.getOrCreateConfig(n);if(p.backfillGitInfoAsync(r).catch(()=>{}),t&&(r.setupInterceptorsFile=t),e&&(r.setupInterceptorsLine=e),r.sfDebug&&console.log("Updated configuration after applying options:",r),!r.apiKey||!r.apiGraphqlEndpoint){const l=`The required config is not provided: ${JSON.stringify(r)}`;throw console.error(l),new Error(l)}Le()||Te(void 0,r.sfDebug).catch(l=>{r.sfDebug&&console.error("[FuncSpan] Failed to initialize config loader:",l)}),process.env.SF_WORKER_POOL_DISABLED==="true"?r.sfDebug&&console.log("[setupInterceptors] Worker pool patching DISABLED (SF_WORKER_POOL_DISABLED=true)"):je()||(xe(),r.sfDebug&&console.log("[setupInterceptors] Worker pool patching initialized (DNS tracking enabled)"));const s=new Ce;s.setServiceUUID(r.serviceUUID),P.initializeLogInterceptor(s),(function(l=[]){const c=new _t(l);new Et().doSend(c.getExcludedDomains());const i=new $t,u=new Ze;c.patchFetch(i,u),c.patchHttp(i,u)})(r.domainsToNotPropagateHeadersTo);const d=new bt;d.setServiceUUID(r.serviceUUID),P.initializeExceptionInterceptor(d),It(),new Ct().send(),(function(){if(Y)return;if(Y=!0,process.env.SF_DISABLE_QUEUE_PATCHES==="true")return void(p.getConfig().sfDebug&&console.log("[sf-veritas] Async queue tracing DISABLED via SF_DISABLE_QUEUE_PATCHES=true"));const l=p.getConfig(),c=[],i=[],u=[],a=[];for(const{name:h,envDisableKey:m,install:g}of Ht){if(Mt(m)){u.push(h);continue}let y="failed";try{y=g()}catch(S){l.sfDebug&&console.warn(`[asyncQueues] Failed to install ${h} patch:`,S),a.push(h);continue}y==="installed"?c.push(h):y==="not-installed"?i.push(h):a.push(h)}const f=[`active: ${c.length?c.join(", "):"(none)"}`];i.length&&f.push(`skipped (not installed): ${i.join(", ")}`),u.length&&f.push(`disabled by env: ${u.join(", ")}`),a.length&&f.push(`failed: ${a.join(", ")}`),(l.sfDebug||a.length>0)&&console.log(`[sf-veritas] Async queue tracing — ${f.join("; ")}`)})(),le=!0,r.sfDebug&&console.log("[setupInterceptors] ✅ Initialization complete")}finally{de=!1}}},exports.uninstallAsyncQueuePatches=function(){const n=(function(){let t=0;for(const{proto:e,key:o,original:r}of ye.splice(0))try{r===void 0?delete e[o]:e[o]=r,t+=1}catch{}return t})();return Y=!1,n};