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