@sailfish-ai/sf-veritas 0.5.1 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("./contextManager-B4JXc4ak.cjs"),I=require("./workerPoolSpanCapture-DDrqOj7z.cjs"),D=require("./runtimeConfig-D18ZMMnT.cjs"),Jt=require("node:module"),je=require("fs"),W=require("http"),ae=require("https"),Wt=require("./source-map-rHHEdpre.cjs"),Qt=require("fs/promises"),Gt=require("path"),Ct=require("glob"),Vt=require("async_hooks"),zt=require("node:async_hooks"),Xt=require("node:path"),kt=require("crypto"),ce=require("worker_threads"),Se=require("./funcSpanTransformer-D0W2t41q.cjs");function me(n){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const e in n)if(e!=="default"){const o=Object.getOwnPropertyDescriptor(n,e);Object.defineProperty(t,e,o.get?o:{enumerable:!0,get:()=>n[e]})}}return t.default=n,Object.freeze(t)}const Yt=me(je),Je=me(Qt),O=me(Gt),ne=me(Xt);class se extends I.BaseTransmitter{constructor(){super(),this.setOperationName("IdentifyServiceDetails")}async doSend(t){if(!p.getConfig().serviceIdentificationReceived)try{this.send()}catch(e){p.getConfig().sfDebug&&console.error(" Error during service identification:",e)}}async send(){const t=`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("./contextManager-B4JXc4ak.cjs"),I=require("./workerPoolSpanCapture-DDrqOj7z.cjs"),D=require("./runtimeConfig-D18ZMMnT.cjs"),Wt=require("node:module"),He=require("fs"),W=require("http"),ae=require("https"),Qt=require("./source-map-rHHEdpre.cjs"),Gt=require("fs/promises"),Vt=require("path"),kt=require("glob"),zt=require("async_hooks"),Xt=require("node:async_hooks"),Yt=require("node:path"),Nt=require("crypto"),ce=require("worker_threads"),Se=require("./funcSpanTransformer-D0W2t41q.cjs");function me(n){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const e in n)if(e!=="default"){const o=Object.getOwnPropertyDescriptor(n,e);Object.defineProperty(t,e,o.get?o:{enumerable:!0,get:()=>n[e]})}}return t.default=n,Object.freeze(t)}const Zt=me(He),We=me(Gt),B=me(Vt),ne=me(Yt);class se extends I.BaseTransmitter{constructor(){super(),this.setOperationName("IdentifyServiceDetails")}async doSend(t){if(!g.getConfig().serviceIdentificationReceived)try{this.send()}catch(e){g.getConfig().sfDebug&&console.error(" Error during service identification:",e)}}async send(){const t=`
2
2
  ${this.queryType} ${this.operationName}(
3
3
  $apiKey: String!,
4
4
  $timestampMs: String!,
@@ -38,11 +38,11 @@
38
38
  dataSensitivityLevel: $dataSensitivityLevel,
39
39
  )
40
40
  }
41
- `,e=p.getConfig(),o=this.getVariables({serviceIdentifier:e.serviceIdentifier,serviceVersion:e.serviceVersion,library:e.packageLibraryType,version:e.version,serviceAdditionalMetadata:e.serviceAdditionalMetadata,gitSha:e.gitSha||"",gitOrg:e.gitOrg||void 0,gitRepo:e.gitRepo||void 0,gitProvider:e.gitProvider||void 0,serviceDisplayName:e.serviceDisplayName||void 0,framework:e.framework||void 0,additionalFrameworks:e.additionalFrameworks.length>0?e.additionalFrameworks:void 0,serviceRole:e.serviceRole||void 0});I.nonBlockingPost(this.endpoint,this.operationName,t,o)}}class Zt extends I.BaseTransmitter{serviceIdentifier=new se;constructor(){super(),this.setOperationName("CollectMetadata")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const t=setInterval(()=>{p.getConfig().serviceIdentificationReceived?clearInterval(t):this.serviceIdentifier.doSend({})},5e3);t&&typeof t=="object"&&"unref"in t&&t.unref()}async doSend(t,e,o,r){this.startBackgroundIdentify(),this.send(t,e,o,r)}async send(t,e,o,r){if(!e&&!r)throw new Error('Must pass in either traits or traits_json to "add_or_update_traits"');let s=[];if(!r){const u=D.serializeJsonWithExclusions(e);r=u.traitsJson,s=u.excludedFields}const d=this.getVariables({userId:t,traitsJson:r,excludedFields:s,override:o,library:p.getConfig().packageLibraryType,version:p.getConfig().version});I.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),d)}getQuery(){return`
41
+ `,e=g.getConfig(),o=this.getVariables({serviceIdentifier:e.serviceIdentifier,serviceVersion:e.serviceVersion,library:e.packageLibraryType,version:e.version,serviceAdditionalMetadata:e.serviceAdditionalMetadata,gitSha:e.gitSha||"",gitOrg:e.gitOrg||void 0,gitRepo:e.gitRepo||void 0,gitProvider:e.gitProvider||void 0,serviceDisplayName:e.serviceDisplayName||void 0,framework:e.framework||void 0,additionalFrameworks:e.additionalFrameworks.length>0?e.additionalFrameworks:void 0,serviceRole:e.serviceRole||void 0});I.nonBlockingPost(this.endpoint,this.operationName,t,o)}}class en extends I.BaseTransmitter{serviceIdentifier=new se;constructor(){super(),this.setOperationName("CollectMetadata")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const t=setInterval(()=>{g.getConfig().serviceIdentificationReceived?clearInterval(t):this.serviceIdentifier.doSend({})},5e3);t&&typeof t=="object"&&"unref"in t&&t.unref()}async doSend(t,e,o,r){this.startBackgroundIdentify(),this.send(t,e,o,r)}async send(t,e,o,r){if(!e&&!r)throw new Error('Must pass in either traits or traits_json to "add_or_update_traits"');let s=[];if(!r){const u=D.serializeJsonWithExclusions(e);r=u.traitsJson,s=u.excludedFields}const d=this.getVariables({userId:t,traitsJson:r,excludedFields:s,override:o,library:g.getConfig().packageLibraryType,version:g.getConfig().version});I.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),d)}getQuery(){return`
42
42
  mutation ${this.operationName}($apiKey: String!, $serviceUuid: String!, $sessionId: String!, $userId: String!, $traitsJson: String!, $excludedFields: [String!]!, $library: String!, $timestampMs: String!, $version: String!, $override: Boolean!) {
43
43
  ${this.queryName}(apiKey: $apiKey, serviceUuid: $serviceUuid, sessionId: $sessionId, userId: $userId, traitsJson: $traitsJson, excludedFields: $excludedFields, library: $library, timestampMs: $timestampMs, version: $version, override: $override)
44
44
  }
45
- `}}class We{constructor(t){this.apiKey=t,this.metadataTransmitter=new Zt}metadataTransmitter;identify(t,e,o,r=!1){e||o?this.addOrUpdateMetadata(t,e,o,r):this.addOrUpdateMetadata(t,{},void 0,r)}addOrUpdateMetadata(t,e={},o,r=!1){if(!e&&!o)throw new Error('Must pass in either traits or traitsJson to "addOrUpdateMetadata"');p.getConfig().sfDebug&&console.log(" [[DEBUG - addOrUpdateMetadata]] Starting operation"),p.getConfig().sfDebug&&console.log(" addOrUpdateMetadata...SENDING DATA...",t,e,o),this.metadataTransmitter.doSend(t,e,r,o)}}class He extends I.BaseTransmitter{serviceIdentifier=new se;constructor(){super()}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const t=setInterval(()=>{p.getConfig().serviceIdentificationReceived?clearInterval(t):this.serviceIdentifier.doSend({})},5e3);t&&typeof t=="object"&&"unref"in t&&t.unref()}async doSend(t){this.startBackgroundIdentify(),this.send(t)}async send(t){try{const e=Array.isArray(t)?t:[t,"default",null,null],o=this.getVariables({contents:e[0],level:e[1],sourceFile:e[2]||void 0,sourceLine:e[3]||void 0});I.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),o)}catch(e){p.getConfig().sfDebug&&console.error("🚨 Error in send():",e)}}getQuery(){return`
45
+ `}}class Qe{constructor(t){this.apiKey=t,this.metadataTransmitter=new en}metadataTransmitter;identify(t,e,o,r=!1){e||o?this.addOrUpdateMetadata(t,e,o,r):this.addOrUpdateMetadata(t,{},void 0,r)}addOrUpdateMetadata(t,e={},o,r=!1){if(!e&&!o)throw new Error('Must pass in either traits or traitsJson to "addOrUpdateMetadata"');g.getConfig().sfDebug&&console.log(" [[DEBUG - addOrUpdateMetadata]] Starting operation"),g.getConfig().sfDebug&&console.log(" addOrUpdateMetadata...SENDING DATA...",t,e,o),this.metadataTransmitter.doSend(t,e,r,o)}}class Ke extends I.BaseTransmitter{serviceIdentifier=new se;constructor(){super()}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const t=setInterval(()=>{g.getConfig().serviceIdentificationReceived?clearInterval(t):this.serviceIdentifier.doSend({})},5e3);t&&typeof t=="object"&&"unref"in t&&t.unref()}async doSend(t){this.startBackgroundIdentify(),this.send(t)}async send(t){try{const e=Array.isArray(t)?t:[t,"default",null,null],o=this.getVariables({contents:e[0],level:e[1],sourceFile:e[2]||void 0,sourceLine:e[3]||void 0});I.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),o)}catch(e){g.getConfig().sfDebug&&console.error("🚨 Error in send():",e)}}getQuery(){return`
46
46
  ${this.queryType} ${this.operationName}(
47
47
  $apiKey: String!,
48
48
  $serviceUuid: String!,
@@ -68,7 +68,7 @@
68
68
  dataSensitivityLevel: $dataSensitivityLevel
69
69
  )
70
70
  }
71
- `}}function en(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}class tn extends I.BaseTransmitter{serviceIdentifier=new se;supplementalFields={};setSupplementalFields(t){this.supplementalFields={...this.supplementalFields,...t}}normalizedSupplementalForGraphQL(){const{isFromLocalService:t}=this.supplementalFields,e={};return t!==void 0&&(e.isFromLocalService=t),e}constructor(){super(),this.setOperationName("CollectExceptions")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const t=setInterval(()=>{p.getConfig().serviceIdentificationReceived?clearInterval(t):this.serviceIdentifier.doSend({})},5e3);t&&typeof t=="object"&&"unref"in t&&t.unref()}async doSend(t,e){this.startBackgroundIdentify(),this.send(t,e)}async send(t,e){p.getConfig().sfDebug&&console.log(" SENDING EXCEPTION...");const o=JSON.stringify(D.CustomJSONEncoderForFrameInfo.encode(e)),r=this.normalizedSupplementalForGraphQL(),s=this.getVariables({exceptionMessage:t,traceJson:o,reentrancyGuardPreactive:!1,library:p.getConfig().packageLibraryType,version:p.getConfig().version,...r});I.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),s)}getQuery(){return`
71
+ `}}function tn(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}class nn extends I.BaseTransmitter{serviceIdentifier=new se;supplementalFields={};setSupplementalFields(t){this.supplementalFields={...this.supplementalFields,...t}}normalizedSupplementalForGraphQL(){const{isFromLocalService:t}=this.supplementalFields,e={};return t!==void 0&&(e.isFromLocalService=t),e}constructor(){super(),this.setOperationName("CollectExceptions")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const t=setInterval(()=>{g.getConfig().serviceIdentificationReceived?clearInterval(t):this.serviceIdentifier.doSend({})},5e3);t&&typeof t=="object"&&"unref"in t&&t.unref()}async doSend(t,e){this.startBackgroundIdentify(),this.send(t,e)}async send(t,e){g.getConfig().sfDebug&&console.log(" SENDING EXCEPTION...");const o=JSON.stringify(D.CustomJSONEncoderForFrameInfo.encode(e)),r=this.normalizedSupplementalForGraphQL(),s=this.getVariables({exceptionMessage:t,traceJson:o,reentrancyGuardPreactive:!1,library:g.getConfig().packageLibraryType,version:g.getConfig().version,...r});I.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),s)}getQuery(){return`
72
72
  mutation ${this.operationName}(
73
73
  $apiKey: String!,
74
74
  $serviceUuid: String!,
@@ -98,7 +98,7 @@
98
98
  dataSensitivityLevel: $dataSensitivityLevel
99
99
  )
100
100
  }
101
- `}}const te="X-Sf3-Rid",Qe="X-Sf4-Prid",Ge="getting request source code";var fe=(n=>(n.UNKNOWN="unknown",n.ANONYMOUS="anonymous",n.NOT_CAPTURED="not captured",n))(fe||{});const Ve="http:",nn=Jt.createRequire(require("node:url").pathToFileURL(__filename).href);let ze=!1;function rn(){const n=p.getConfig().sfDebug;if(ze)return void(n&&D.internalLog("[patchNodeHttpInbound] Already installed, skipping."));let t;ze=!0;try{t=nn("node:http"),n&&D.internalLog("[patchNodeHttpInbound] node:http required successfully.")}catch(r){return void D.internalError("Failed to require node:http:",r)}if(!t?.Server?.prototype)return void(n&&D.internalLog("[patchNodeHttpInbound] http.Server.prototype not found."));const e=t.Server.prototype,o=e.emit;o&&!e.__sf_inbound_patched__?(Object.defineProperty(e,"__sf_inbound_patched__",{value:!0,enumerable:!1,configurable:!1,writable:!1}),n&&D.internalLog("[patchNodeHttpInbound] Patching http.Server.prototype.emit."),e.emit=function(r,...s){if(r!=="request")return n&&D.internalLog(`[patchNodeHttpInbound] Passing through event: ${r}`),o.call(this,r,...s);const d=s[0],u=s[1],a=(function(m){const h={};if(!m)return h;for(const[y,S]of Object.entries(m))S!=null&&(Array.isArray(S)?h[y.toLowerCase()]=S.join(", "):h[y.toLowerCase()]=String(S));return h})(d?.headers),i=a["x-sf3-rid"],l=a["x-sf3-functionspancaptureoverride"];n&&(D.internalLog("[patchNodeHttpInbound] Intercepted request event."),D.internalLog("[patchNodeHttpInbound] Inbound headers:",a),D.internalLog("[patchNodeHttpInbound] Trace header:",i),D.internalLog("[patchNodeHttpInbound] FuncSpan override header:",l));const c=p.ContextManager.getInstance();c.setTraceId(i);const f=c.getTraceId();n&&D.internalLog("[patchNodeHttpInbound] Context traceId set:",f);const g=()=>c.runWith({inboundHeaders:a,...i?{traceId:i}:{}},()=>{i&&c.setTraceId(i),n&&D.internalLog("[patchNodeHttpInbound] Running request handler in context.");const m=()=>{n&&D.internalLog("[patchNodeHttpInbound] Response finished/closed for traceId:",c.getTraceId())};return u.on("finish",m),u.on("close",m),o.call(this,r,d,u)});if(!l)return g();try{return I.funcspanOverrideStorage.run(l,()=>g())}catch{return g()}}):n&&D.internalLog("[patchNodeHttpInbound] Already patched, skipping.")}const Xe=new Map;function be(n,t){const e=`${n}|${t}`;let o=Xe.get(e);return o||(o=new RegExp(n,t),Xe.set(e,o)),o}function ve(n,t){let e,o;if(typeof n=="string"?e=n:typeof URL<"u"&&n instanceof URL?e=n.href:typeof Request<"u"&&n instanceof Request?e=n.url:n!=null&&typeof n.toString=="function"&&(e=n.toString()),!e)return!1;try{o=new URL(e,"http://localhost/")}catch{return!1}const{hostname:r,pathname:s,port:d,protocol:u}=o;if(!/^https?:$/.test(u))return!1;const a=r.startsWith("www.")?r.slice(4).toLowerCase():r.toLowerCase();return t.some(i=>{const l=String(i||"").replace(/^[a-zA-Z]+:\/\//,"");if(!l)return!1;let[c,f]=l.split("/",2),g="";c.includes(":")&&([c,g]=c.split(":"));const m=be(`^${c.replace(/\./g,"\\.").replace(/\*/g,".*")}$`,"i"),h=a.startsWith("www.")?a.slice(4):a;if(g&&d!==g)return!1;if(c.startsWith("*.")){const y=c.slice(2).toLowerCase();return a===y||h===y||a.endsWith("."+y)?f?be(`^/${f.replace(/\*/g,".*").replace(/\/$/,"")}`,"i").test(s):!0:!1}return!m.test(h)&&!m.test(a)?!1:f?be(`^/${f.replace(/\*/g,".*").replace(/\/$/,"")}`,"i").test(s):!0})}class on extends He{constructor(){super(),this.setOperationName("DomainsToNotPassHeaderTo")}async doSend(t){this.send(t)}async send(t){const e=`
101
+ `}}const te="X-Sf3-Rid",Ge="X-Sf4-Prid",Ve="getting request source code";var fe=(n=>(n.UNKNOWN="unknown",n.ANONYMOUS="anonymous",n.NOT_CAPTURED="not captured",n))(fe||{});const be="http:",ze="https:",rn=Wt.createRequire(require("node:url").pathToFileURL(__filename).href);let Xe=!1;function on(){const n=g.getConfig().sfDebug;if(Xe)return void(n&&D.internalLog("[patchNodeHttpInbound] Already installed, skipping."));let t;Xe=!0;try{t=rn("node:http"),n&&D.internalLog("[patchNodeHttpInbound] node:http required successfully.")}catch(r){return void D.internalError("Failed to require node:http:",r)}if(!t?.Server?.prototype)return void(n&&D.internalLog("[patchNodeHttpInbound] http.Server.prototype not found."));const e=t.Server.prototype,o=e.emit;o&&!e.__sf_inbound_patched__?(Object.defineProperty(e,"__sf_inbound_patched__",{value:!0,enumerable:!1,configurable:!1,writable:!1}),n&&D.internalLog("[patchNodeHttpInbound] Patching http.Server.prototype.emit."),e.emit=function(r,...s){if(r!=="request")return n&&D.internalLog(`[patchNodeHttpInbound] Passing through event: ${r}`),o.call(this,r,...s);const d=s[0],u=s[1],a=(function(y){const h={};if(!y)return h;for(const[m,E]of Object.entries(y))E!=null&&(Array.isArray(E)?h[m.toLowerCase()]=E.join(", "):h[m.toLowerCase()]=String(E));return h})(d?.headers),i=a["x-sf3-rid"],c=a["x-sf3-functionspancaptureoverride"];n&&(D.internalLog("[patchNodeHttpInbound] Intercepted request event."),D.internalLog("[patchNodeHttpInbound] Inbound headers:",a),D.internalLog("[patchNodeHttpInbound] Trace header:",i),D.internalLog("[patchNodeHttpInbound] FuncSpan override header:",c));const l=g.ContextManager.getInstance();l.setTraceId(i);const f=l.getTraceId();n&&D.internalLog("[patchNodeHttpInbound] Context traceId set:",f);const p=()=>l.runWith({inboundHeaders:a,...i?{traceId:i}:{}},()=>{i&&l.setTraceId(i),n&&D.internalLog("[patchNodeHttpInbound] Running request handler in context.");const y=()=>{n&&D.internalLog("[patchNodeHttpInbound] Response finished/closed for traceId:",l.getTraceId())};return u.on("finish",y),u.on("close",y),o.call(this,r,d,u)});if(!c)return p();try{return I.funcspanOverrideStorage.run(c,()=>p())}catch{return p()}}):n&&D.internalLog("[patchNodeHttpInbound] Already patched, skipping.")}const Ye=new Map;function ve(n,t){const e=`${n}|${t}`;let o=Ye.get(e);return o||(o=new RegExp(n,t),Ye.set(e,o)),o}function Ie(n,t){let e,o;if(typeof n=="string"?e=n:typeof URL<"u"&&n instanceof URL?e=n.href:typeof Request<"u"&&n instanceof Request?e=n.url:n!=null&&typeof n.toString=="function"&&(e=n.toString()),!e)return!1;try{o=new URL(e,"http://localhost/")}catch{return!1}const{hostname:r,pathname:s,port:d,protocol:u}=o;if(!/^https?:$/.test(u))return!1;const a=r.startsWith("www.")?r.slice(4).toLowerCase():r.toLowerCase();return t.some(i=>{const c=String(i||"").replace(/^[a-zA-Z]+:\/\//,"");if(!c)return!1;let[l,f]=c.split("/",2),p="";l.includes(":")&&([l,p]=l.split(":"));const y=ve(`^${l.replace(/\./g,"\\.").replace(/\*/g,".*")}$`,"i"),h=a.startsWith("www.")?a.slice(4):a;if(p&&d!==p)return!1;if(l.startsWith("*.")){const m=l.slice(2).toLowerCase();return a===m||h===m||a.endsWith("."+m)?f?ve(`^/${f.replace(/\*/g,".*").replace(/\/$/,"")}`,"i").test(s):!0:!1}return!y.test(h)&&!y.test(a)?!1:f?ve(`^/${f.replace(/\*/g,".*").replace(/\/$/,"")}`,"i").test(s):!0})}class sn extends Ke{constructor(){super(),this.setOperationName("DomainsToNotPassHeaderTo")}async doSend(t){this.send(t)}async send(t){const e=`
102
102
  ${this.queryType} ${this.operationName}(
103
103
  $apiKey: String!,
104
104
  $serviceUuid: String!,
@@ -110,7 +110,7 @@
110
110
  domains: $domains
111
111
  )
112
112
  }
113
- `,o={apiKey:this.apiKey,serviceUuid:this.serviceUUID,domains:t};I.nonBlockingPost(this.endpoint,this.operationName,e,o)}}class sn extends I.BaseTransmitter{serviceIdentifier=new se;constructor(){super(),this.setOperationName("CollectNetworkHops")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const t=setInterval(()=>{p.getConfig().serviceIdentificationReceived?clearInterval(t):this.serviceIdentifier.doSend({})},5e3);t&&typeof t=="object"&&"unref"in t&&t.unref()}async doSend(t){this.startBackgroundIdentify(),this.send(t)}async send(t){const{name:e,column:o,line:r,entrypoint:s,retryWithoutTraceId:d}=t,u=this.getVariables({name:e,column:o,line:r,entrypoint:s,retryWithoutTraceId:d});I.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),u)}getQuery(){return`
113
+ `,o={apiKey:this.apiKey,serviceUuid:this.serviceUUID,domains:t};I.nonBlockingPost(this.endpoint,this.operationName,e,o)}}class an extends I.BaseTransmitter{serviceIdentifier=new se;constructor(){super(),this.setOperationName("CollectNetworkHops")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const t=setInterval(()=>{g.getConfig().serviceIdentificationReceived?clearInterval(t):this.serviceIdentifier.doSend({})},5e3);t&&typeof t=="object"&&"unref"in t&&t.unref()}async doSend(t){this.startBackgroundIdentify(),this.send(t)}async send(t){const{name:e,column:o,line:r,entrypoint:s,retryWithoutTraceId:d}=t,u=this.getVariables({name:e,column:o,line:r,entrypoint:s,retryWithoutTraceId:d});I.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),u)}getQuery(){return`
114
114
  mutation ${this.operationName}(
115
115
  $apiKey: String!,
116
116
  $sessionId: String!,
@@ -136,15 +136,15 @@
136
136
  ${this.operationName==="CollectNetworkHops"?", retryWithoutTraceId: $retryWithoutTraceId":""}
137
137
  )
138
138
  }
139
- `}}class Nt extends I.BaseTransmitter{serviceIdentifier=new se;constructor(){super(),this.setOperationName("CollectNetworkRequest")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const t=setInterval(()=>{p.getConfig().serviceIdentificationReceived?clearInterval(t):this.serviceIdentifier.doSend({})},5e3);t&&typeof t=="object"&&"unref"in t&&t.unref()}async doSend(t){this.startBackgroundIdentify(),this.send(t)}getQuery(){return`
139
+ `}}class Ut extends I.BaseTransmitter{serviceIdentifier=new se;constructor(){super(),this.setOperationName("CollectNetworkRequest")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const t=setInterval(()=>{g.getConfig().serviceIdentificationReceived?clearInterval(t):this.serviceIdentifier.doSend({})},5e3);t&&typeof t=="object"&&"unref"in t&&t.unref()}async doSend(t){this.startBackgroundIdentify(),this.send(t)}getQuery(){return`
140
140
  mutation ${this.operationName}(
141
141
  $data: NetworkRequestInput!
142
142
  ) {
143
143
  ${this.queryName}(
144
144
  data: $data)
145
145
  }
146
- `}async send(t){const e={data:{...t,dataSensitivityLevel:p.getConfig().dataSensitivityLevel}};await I.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),e)}}const Ie=[400,403];function Ee(n,t){return t!=="none"&&(t==="all"||n==="GET"||n==="HEAD"||n==="OPTIONS")}class an{HEADER_TRACING="X-Sf3-Rid";HEADER_LOG_GUARD="reentrancy_guard_logging_preactive";HEADER_PRINT_GUARD="reentrancy_guard_print_preactive";HEADER_EXCEPTION_GUARD="reentrancy_guard_exception_preactive";contextManager;constructor(t=[]){this.contextManager=p.ContextManager.getInstance(),t?.forEach(e=>{typeof e=="string"&&e.trim()&&this.contextManager.getExcludedDomains().add(e)}),p.getConfig().sfDebug&&console.log("[RequestInterceptor] Initialized with static excluded domains.")}extractIdsFromTraceHeader(t,e=this.HEADER_TRACING){let o;if(t instanceof Headers)o=t.get(e)??void 0;else{const s=e.toLowerCase();for(const[d,u]of Object.entries(t))if(d.toLowerCase()===s){o=u;break}}if(!o)return{};const r=o.split("/").filter(Boolean);return r.length<3?{}:{sessionId:r[0],pageVisitId:r[1],requestId:r[r.length-1]}}parseStackFrame(t){const e=/\((.*):(\d+):(\d+)\)$/.exec(t.trim());if(!e)return null;const[,o,r,s]=e;return{filePath:o,line:parseInt(r,10),column:parseInt(s,10)}}async getOriginalPosition(t,e,o){let r={source:t,line:e,column:o,name:null};if(t.includes("://"))return{originalPos:r};const s=t+".map";try{const d=JSON.parse(je.readFileSync(s,"utf-8"));let u=(await new Wt.sourceMapExports.SourceMapConsumer(d)).originalPositionFor({line:e,column:o});u.source&&(r=u)}catch(d){p.getConfig().sfDebug&&console.error(`Could not read/parse map file at ${s}:`,d)}return{originalPos:r}}captureFirstUserLines(t,e=10,o=!1){const r=p.getConfig().sfDebug?10:e,s=Error.stackTraceLimit;Error.stackTraceLimit=Math.max(s,r);const d=new Error(Ge);Ge in Error&&Error.captureStackTrace(d,this.captureFirstUserLines);const u=D.stackToString(d.stack);Error.stackTraceLimit=s;const a=u.split(`
147
- `).slice(1),i=[];for(const l of a)if(!(l.includes("node:internal")||l.includes("internal/modules")||l.includes("internal/process")||l.includes("node_modules")||l.includes(".next/server/chunks")||l.includes("RequestInterceptor")||l.includes("contextManager")||l.includes("setupConfig"))&&(i.push(l.trim()),i.length>=e))break;for(const l of i){const c=this.parseStackFrame(l);c?(async()=>{const{originalPos:f}=await this.getOriginalPosition(c.filePath,c.line,c.column);if(f){p.getConfig().sfDebug&&console.log("[RequestInterceptor] First user code line:",f);const g={line:f.line?.toString()||fe.UNKNOWN,column:f.column?.toString()||fe.NOT_CAPTURED,name:f.name||fe.NOT_CAPTURED,entrypoint:f.source,retryWithoutTraceId:o};t.doSend(g)}})():p.getConfig().sfDebug&&console.error("Could not parse stack line:",l)}}addReentrancyGuardHeaders(t){t.set(this.HEADER_LOG_GUARD,"true"),t.set(this.HEADER_PRINT_GUARD,"true"),t.set(this.HEADER_EXCEPTION_GUARD,"true")}shouldPropagateHeaders(t){const e=p.getConfig(),o=e.domainsToPropagateHeadersTo,r=e.domainsToNotPropagateHeadersTo||[],s=Array.from(p.DEFAULT_DOMAINS_TO_EXCLUDE);return!!ve(t,o)&&!(r.length>0&&ve(t,r))&&!ve(t,s)}addTracingHeaders(t,e){const o=this.shouldPropagateHeaders(e);if(o)this.addTracingHeader(t,e);else if(p.getConfig().sfDebug){let r=e;try{r=new URL(e).hostname}catch{}console.error(`[RequestInterceptor] Excluded domain: ${r}`)}return o}deriveTraceBaseAndParent(t){const e=t.split("/").filter(Boolean);return e.length<2?{base:t,parent:t}:{base:`${e[0]}/${e[1]}`,parent:t}}addTracingHeader(t,e){const o=I.getFuncspanOverride();if(o){const a=I.parseHeaderOverride(o);if(a&&a.sample_rate===0)return void(p.getConfig().sfDebug&&console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${e}`))}const r=this.contextManager.getOrSetSfTraceId(),{base:s,parent:d}=this.deriveTraceBaseAndParent(r),u=p.v4();t.set(this.HEADER_TRACING,`${s}/${u}`),t.set(Qe,d),p.getConfig().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${e}`)}patchFetch(t,e){const o=globalThis.fetch;typeof o=="function"?globalThis.fetch=async(r,s)=>{const d=new Headers(s?.headers);if(d.get(this.HEADER_LOG_GUARD)==="true"||d.get(this.HEADER_PRINT_GUARD)==="true"||d.get(this.HEADER_EXCEPTION_GUARD)==="true")return o(r,s);this.captureFirstUserLines(t);const u=Date.now();let a,i="GET";if(typeof r=="string"||r instanceof URL)a=r.toString(),i=(s?.method||"GET").toUpperCase();else{if(!(r instanceof Request))return p.getConfig().sfDebug&&console.error("[Sailfish RequestInterceptor] Invalid fetch input."),o(r,s);a=r.url,i=r.method.toUpperCase(),r.headers.forEach((E,_)=>{d.set(_,E)})}p.getConfig().sfDebug&&console.log("[RequestInterceptor] Fetching request to:",a);let l="unknown";try{l=new URL(a).hostname}catch{return p.getConfig().sfDebug&&console.warn(`[RequestInterceptor] Could not parse URL '${a}' — passing through without tracing headers.`),o(r,s)}const c=new Headers(d),f=this.addTracingHeaders(d,a),g=E=>r instanceof Request?[new Request(r,{...s||{},headers:E}),void 0]:[a,{...s,headers:E}],m=p.getConfig().retryOnClientError;let h,y=!1;try{const[E,_]=g(d);if(h=await o(E,_),f&&Ee(i,m)&&Ie.includes(h.status)){const[$,w]=g(c);h=await o($,w),y=!0;try{this.captureFirstUserLines(t,10,y)}catch(N){p.getConfig().sfDebug&&console.error("[RequestInterceptor] captureFirstUserLines (retry) failed:",N)}}else try{this.contextManager.addSupportedDomains(l)}catch($){p.getConfig().sfDebug&&console.error("[RequestInterceptor] addSupportedDomains failed:",$)}}catch(E){const _=Date.now();p.getConfig().sfDebug&&console.error(`[RequestInterceptor] Fetch failed: ${a}, Error: ${E}, Duration: ${_-u}ms`);try{const{sessionId:$,pageVisitId:w,requestId:N}=this.extractIdsFromTraceHeader(d),B=p.getConfig();e.doSend({apiKey:B.apiKey,requestId:N,pageVisitId:w,recordingSessionId:$,serviceUuid:B.serviceUUID,timestampStart:u.toString(),timestampEnd:_.toString(),responseCode:0,success:!1,error:E instanceof Error?E.message:typeof E=="string"?E:JSON.stringify(E),url:a,method:i,retryWithoutTraceId:y,parentSpanId:p.getCurrentFunctionSpanId()})}catch($){p.getConfig().sfDebug&&console.error("[RequestInterceptor] Error telemetry send failed:",$)}throw E}const S=Date.now();try{p.getConfig().sfDebug&&console.log(`[RequestInterceptor] Fetch completed: ${a}, Status: ${h.status}, Duration: ${S-u}ms`);const{sessionId:E,pageVisitId:_,requestId:$}=this.extractIdsFromTraceHeader(d),w=p.getConfig(),N={apiKey:w.apiKey,requestId:$,pageVisitId:_,recordingSessionId:E,serviceUuid:w.serviceUUID,timestampStart:u.toString(),timestampEnd:S.toString(),responseCode:h.status,success:!0,error:null,url:a,method:i,retryWithoutTraceId:y,parentSpanId:p.getCurrentFunctionSpanId()};if(w.captureRequestHeaders){const C={};d.forEach((T,P)=>{C[P]=T}),N.requestHeaders=C}if(w.captureResponseHeaders){const C={};h.headers.forEach((T,P)=>{C[P]=T}),N.responseHeaders=C}if(w.captureRequestBody&&s?.body){const C=s.body,T=w.requestBodyLimitBytes;try{if(typeof C=="string")N.requestBody=C.length>T?C.substring(0,T)+"...[truncated]":C;else if(C instanceof URLSearchParams){const P=C.toString();N.requestBody=P.length>T?P.substring(0,T)+"...[truncated]":P}else if(typeof ArrayBuffer<"u"&&(C instanceof ArrayBuffer||ArrayBuffer.isView(C))){const P=C.byteLength??C.byteLength;N.requestBody=`[binary body, ${P} bytes — not captured]`}else if(typeof Blob<"u"&&C instanceof Blob)N.requestBody=`[Blob, ${C.size} bytes, type=${C.type||"unknown"} — not captured]`;else if(typeof FormData<"u"&&C instanceof FormData)N.requestBody="[FormData — not captured]";else if(typeof ReadableStream<"u"&&C instanceof ReadableStream)N.requestBody="[ReadableStream — not captured]";else{const P=JSON.stringify(C);P&&P!=="{}"&&(N.requestBody=P.length>T?P.substring(0,T)+"...[truncated]":P)}}catch{}}let B;if(w.captureResponseBody){const C=(h.headers.get("content-type")||"").toLowerCase();if(!C||C.includes("json")||C.includes("xml")||C.includes("text/")||C.includes("javascript")||C.includes("ecmascript")||C.includes("x-www-form-urlencoded")||C.includes("application/graphql")){const T=h.clone(),P=w.responseBodyLimitBytes;B=(async()=>{try{const H=await T.text(),J=H.length>P?H.substring(0,P)+"...[truncated]":H;try{e.doSend({...N,responseBody:J})}catch{}}catch{}})(),B.catch(()=>{})}else N.responseBody=`[non-text body, content-type=${C} — not captured]`}B||e.doSend(N)}catch(E){p.getConfig().sfDebug&&console.error("[RequestInterceptor] Post-fetch telemetry failed (response still returned):",E)}return h}:p.getConfig().sfDebug&&console.error("[RequestInterceptor] Fetch not available.")}setHeader(t,e,o){t instanceof Headers?t.set(e,o):t[e]=o}addTracingHeadersToPlainObject(t,e){const o=this.shouldPropagateHeaders(e);if(o){const r=I.getFuncspanOverride();if(r){const i=I.parseHeaderOverride(r);if(i&&i.sample_rate===0)return p.getConfig().sfDebug&&console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${e}`),!1}const s=this.contextManager.getOrSetSfTraceId(),{base:d,parent:u}=this.deriveTraceBaseAndParent(s),a=p.v4();t[this.HEADER_TRACING]=`${d}/${a}`,t[Qe]=u,p.getConfig().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${e}`)}else if(p.getConfig().sfDebug){let r=e;try{r=new URL(e).hostname}catch{}console.error(`[RequestInterceptor] Excluded domain: ${r}`)}return o}patchHttp(t,e){if(p.getConfig().sfDebug&&console.log("[RequestInterceptor] Initializing HTTP/HTTPS request patch..."),!W||typeof W.request!="function")return void(p.getConfig().sfDebug&&console.log("[RequestInterceptor] HTTP/HTTPS not available."));const o=W.request.bind(W),r=ae.request.bind(ae),s=(a,i,l,c=Ve)=>{let f,g;if(typeof a=="string"||a instanceof URL){const m=typeof a=="string"?new URL(a):a;f={...typeof i=="object"&&i!==null?i:{},protocol:m.protocol||c,hostname:m.hostname,port:m.port||void 0,path:m.pathname+m.search},g=typeof i=="function"?i:l}else f={...a},f.protocol||(f.protocol=c),g=typeof i=="function"?i:void 0;return f.headers||(f.headers={}),[f,g]},d=(a,i,l)=>{const[c,f]=s(a,i,l,Ve);try{const y=`${c.protocol}//${c.hostname}`;this.addTracingHeadersToPlainObject(c.headers,y),this.captureFirstUserLines(t)}catch(y){p.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTP request options:",y)}const g=(c.method||"GET").toUpperCase(),m=p.getConfig().retryOnClientError,h=(y,S,E)=>{try{const{sessionId:_,pageVisitId:$,requestId:w}=this.extractIdsFromTraceHeader(c.headers);e.doSend({apiKey:p.getConfig().apiKey,requestId:w,pageVisitId:$,recordingSessionId:_,serviceUuid:p.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:y.statusCode||0,success:!!y.statusCode&&y.statusCode<400,error:null,url:S,method:g,retryWithoutTraceId:E,parentSpanId:p.getCurrentFunctionSpanId()})}catch{}f?.(y)};return o(c,y=>{const S=`${c.protocol}//${c.hostname}`;let E=!1;try{E=this.shouldPropagateHeaders(S)}catch{E=!1}if(E&&Ee(g,m)&&Ie.includes(y.statusCode||0)){y.resume();try{const{sessionId:$,pageVisitId:w,requestId:N}=this.extractIdsFromTraceHeader(c.headers);e.doSend({apiKey:p.getConfig().apiKey,requestId:N,pageVisitId:w,recordingSessionId:$,serviceUuid:p.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:y.statusCode||0,success:!1,error:null,url:S,method:g,retryWithoutTraceId:!1,parentSpanId:p.getCurrentFunctionSpanId()})}catch{}try{this.captureFirstUserLines(t,10,!0)}catch{}const _={...c,headers:{...c.headers}};return delete _.headers[this.HEADER_TRACING],void o(_,$=>{h($,S,!0)}).end()}h(y,S,!1)})},u=(a,i,l)=>{const[c,f]=s(a,i,l,"https:");try{const y=`${c.protocol}//${c.hostname}`;this.addTracingHeadersToPlainObject(c.headers,y),this.captureFirstUserLines(t)}catch(y){p.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTPS request options:",y)}const g=(c.method||"GET").toUpperCase(),m=p.getConfig().retryOnClientError,h=(y,S,E)=>{try{const{sessionId:_,pageVisitId:$,requestId:w}=this.extractIdsFromTraceHeader(c.headers);e.doSend({apiKey:p.getConfig().apiKey,requestId:w,pageVisitId:$,recordingSessionId:_,serviceUuid:p.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:y.statusCode||0,success:!!y.statusCode&&y.statusCode<400,error:null,url:S,method:g,retryWithoutTraceId:E,parentSpanId:p.getCurrentFunctionSpanId()})}catch{}f?.(y)};return r(c,y=>{const S=`${c.protocol}//${c.hostname}`;let E=!1;try{E=this.shouldPropagateHeaders(S)}catch{E=!1}if(E&&Ee(g,m)&&Ie.includes(y.statusCode||0)){y.resume();try{const{sessionId:$,pageVisitId:w,requestId:N}=this.extractIdsFromTraceHeader(c.headers);e.doSend({apiKey:p.getConfig().apiKey,requestId:N,pageVisitId:w,recordingSessionId:$,serviceUuid:p.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:y.statusCode||0,success:!1,error:null,url:S,method:g,retryWithoutTraceId:!1,parentSpanId:p.getCurrentFunctionSpanId()})}catch{}try{this.captureFirstUserLines(t,10,!0)}catch{}const _={...c,headers:{...c.headers}};return delete _.headers[this.HEADER_TRACING],void r(_,$=>{h($,S,!0)}).end()}h(y,S,!1)})};W.request=d,ae.request=u,W.get=(a,i,l)=>{const c=d(a,i,l);return c.end(),c},ae.get=(a,i,l)=>{const c=u(a,i,l);return c.end(),c},p.getConfig().sfDebug&&console.log("✅ HTTP and HTTPS request/get methods patched globally.")}tryPatch(t,e){try{require.resolve(e),t()}catch{}}getExcludedDomains(){return[...this.contextManager.getExcludedDomains()]}}class cn extends He{constructor(){super(),this.setOperationName("UpdateServiceDetails")}async doSend(){this.send()}async send(){const t=`
146
+ `}async send(t){const e={data:{...t,dataSensitivityLevel:g.getConfig().dataSensitivityLevel}};await I.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),e)}}const Ee=[400,403];function _e(n,t){return t!=="none"&&(t==="all"||n==="GET"||n==="HEAD"||n==="OPTIONS")}class cn{HEADER_TRACING="X-Sf3-Rid";HEADER_LOG_GUARD="reentrancy_guard_logging_preactive";HEADER_PRINT_GUARD="reentrancy_guard_print_preactive";HEADER_EXCEPTION_GUARD="reentrancy_guard_exception_preactive";contextManager;constructor(t=[]){this.contextManager=g.ContextManager.getInstance(),t?.forEach(e=>{typeof e=="string"&&e.trim()&&this.contextManager.getExcludedDomains().add(e)}),g.getConfig().sfDebug&&console.log("[RequestInterceptor] Initialized with static excluded domains.")}extractIdsFromTraceHeader(t,e=this.HEADER_TRACING){let o;if(t instanceof Headers)o=t.get(e)??void 0;else{const s=e.toLowerCase();for(const[d,u]of Object.entries(t))if(d.toLowerCase()===s){o=u;break}}if(!o)return{};const r=o.split("/").filter(Boolean);return r.length<3?{}:{sessionId:r[0],pageVisitId:r[1],requestId:r[r.length-1]}}parseStackFrame(t){const e=/\((.*):(\d+):(\d+)\)$/.exec(t.trim());if(!e)return null;const[,o,r,s]=e;return{filePath:o,line:parseInt(r,10),column:parseInt(s,10)}}async getOriginalPosition(t,e,o){let r={source:t,line:e,column:o,name:null};if(t.includes("://"))return{originalPos:r};const s=t+".map";try{const d=JSON.parse(He.readFileSync(s,"utf-8"));let u=(await new Qt.sourceMapExports.SourceMapConsumer(d)).originalPositionFor({line:e,column:o});u.source&&(r=u)}catch(d){g.getConfig().sfDebug&&console.error(`Could not read/parse map file at ${s}:`,d)}return{originalPos:r}}captureFirstUserLines(t,e=10,o=!1){const r=g.getConfig().sfDebug?10:e,s=Error.stackTraceLimit;Error.stackTraceLimit=Math.max(s,r);const d=new Error(Ve);Ve in Error&&Error.captureStackTrace(d,this.captureFirstUserLines);const u=D.stackToString(d.stack);Error.stackTraceLimit=s;const a=u.split(`
147
+ `).slice(1),i=[];for(const c of a)if(!(c.includes("node:internal")||c.includes("internal/modules")||c.includes("internal/process")||c.includes("node_modules")||c.includes(".next/server/chunks")||c.includes("RequestInterceptor")||c.includes("contextManager")||c.includes("setupConfig"))&&(i.push(c.trim()),i.length>=e))break;for(const c of i){const l=this.parseStackFrame(c);l?(async()=>{const{originalPos:f}=await this.getOriginalPosition(l.filePath,l.line,l.column);if(f){g.getConfig().sfDebug&&console.log("[RequestInterceptor] First user code line:",f);const p={line:f.line?.toString()||fe.UNKNOWN,column:f.column?.toString()||fe.NOT_CAPTURED,name:f.name||fe.NOT_CAPTURED,entrypoint:f.source,retryWithoutTraceId:o};t.doSend(p)}})():g.getConfig().sfDebug&&console.error("Could not parse stack line:",c)}}addReentrancyGuardHeaders(t){t.set(this.HEADER_LOG_GUARD,"true"),t.set(this.HEADER_PRINT_GUARD,"true"),t.set(this.HEADER_EXCEPTION_GUARD,"true")}shouldPropagateHeaders(t){const e=g.getConfig(),o=e.domainsToPropagateHeadersTo,r=e.domainsToNotPropagateHeadersTo||[],s=Array.from(g.DEFAULT_DOMAINS_TO_EXCLUDE);return!!Ie(t,o)&&!(r.length>0&&Ie(t,r))&&!Ie(t,s)}addTracingHeaders(t,e){const o=this.shouldPropagateHeaders(e);if(o)this.addTracingHeader(t,e);else if(g.getConfig().sfDebug){let r=e;try{r=new URL(e).hostname}catch{}console.error(`[RequestInterceptor] Excluded domain: ${r}`)}return o}deriveTraceBaseAndParent(t){const e=t.split("/").filter(Boolean);return e.length<2?{base:t,parent:t}:{base:`${e[0]}/${e[1]}`,parent:t}}addTracingHeader(t,e){const o=I.getFuncspanOverride();if(o){const a=I.parseHeaderOverride(o);if(a&&a.sample_rate===0)return void(g.getConfig().sfDebug&&console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${e}`))}const r=this.contextManager.getOrSetSfTraceId(),{base:s,parent:d}=this.deriveTraceBaseAndParent(r),u=g.v4();t.set(this.HEADER_TRACING,`${s}/${u}`),t.set(Ge,d),g.getConfig().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${e}`)}patchFetch(t,e){const o=globalThis.fetch;typeof o=="function"?globalThis.fetch=async(r,s)=>{const d=new Headers(s?.headers);if(d.get(this.HEADER_LOG_GUARD)==="true"||d.get(this.HEADER_PRINT_GUARD)==="true"||d.get(this.HEADER_EXCEPTION_GUARD)==="true")return o(r,s);this.captureFirstUserLines(t);const u=Date.now();let a,i="GET";if(typeof r=="string"||r instanceof URL)a=r.toString(),i=(s?.method||"GET").toUpperCase();else{if(!(r instanceof Request))return g.getConfig().sfDebug&&console.error("[Sailfish RequestInterceptor] Invalid fetch input."),o(r,s);a=r.url,i=r.method.toUpperCase(),r.headers.forEach((_,b)=>{d.set(b,_)})}g.getConfig().sfDebug&&console.log("[RequestInterceptor] Fetching request to:",a);let c="unknown";try{c=new URL(a).hostname}catch{return g.getConfig().sfDebug&&console.warn(`[RequestInterceptor] Could not parse URL '${a}' — passing through without tracing headers.`),o(r,s)}const l=new Headers(d),f=this.addTracingHeaders(d,a),p=_=>r instanceof Request?[new Request(r,{...s||{},headers:_}),void 0]:[a,{...s,headers:_}],y=g.getConfig().retryOnClientError;let h,m=!1;try{const[_,b]=p(d);if(h=await o(_,b),f&&_e(i,y)&&Ee.includes(h.status)){const[$,w]=p(l);h=await o($,w),m=!0;try{this.captureFirstUserLines(t,10,m)}catch(k){g.getConfig().sfDebug&&console.error("[RequestInterceptor] captureFirstUserLines (retry) failed:",k)}}else try{this.contextManager.addSupportedDomains(c)}catch($){g.getConfig().sfDebug&&console.error("[RequestInterceptor] addSupportedDomains failed:",$)}}catch(_){const b=Date.now();g.getConfig().sfDebug&&console.error(`[RequestInterceptor] Fetch failed: ${a}, Error: ${_}, Duration: ${b-u}ms`);try{const{sessionId:$,pageVisitId:w,requestId:k}=this.extractIdsFromTraceHeader(d),P=g.getConfig();e.doSend({apiKey:P.apiKey,requestId:k,pageVisitId:w,recordingSessionId:$,serviceUuid:P.serviceUUID,timestampStart:u.toString(),timestampEnd:b.toString(),responseCode:0,success:!1,error:_ instanceof Error?_.message:typeof _=="string"?_:JSON.stringify(_),url:a,method:i,retryWithoutTraceId:m,parentSpanId:g.getCurrentFunctionSpanId()})}catch($){g.getConfig().sfDebug&&console.error("[RequestInterceptor] Error telemetry send failed:",$)}throw _}const E=Date.now();try{g.getConfig().sfDebug&&console.log(`[RequestInterceptor] Fetch completed: ${a}, Status: ${h.status}, Duration: ${E-u}ms`);const{sessionId:_,pageVisitId:b,requestId:$}=this.extractIdsFromTraceHeader(d),w=g.getConfig(),k={apiKey:w.apiKey,requestId:$,pageVisitId:b,recordingSessionId:_,serviceUuid:w.serviceUUID,timestampStart:u.toString(),timestampEnd:E.toString(),responseCode:h.status,success:!0,error:null,url:a,method:i,retryWithoutTraceId:m,parentSpanId:g.getCurrentFunctionSpanId()};if(w.captureRequestHeaders){const C={};d.forEach((q,F)=>{C[F]=q}),k.requestHeaders=C}if(w.captureResponseHeaders){const C={};h.headers.forEach((q,F)=>{C[F]=q}),k.responseHeaders=C}if(w.captureRequestBody&&s?.body){const C=s.body,q=w.requestBodyLimitBytes;try{if(typeof C=="string")k.requestBody=C.length>q?C.substring(0,q)+"...[truncated]":C;else if(C instanceof URLSearchParams){const F=C.toString();k.requestBody=F.length>q?F.substring(0,q)+"...[truncated]":F}else if(typeof ArrayBuffer<"u"&&(C instanceof ArrayBuffer||ArrayBuffer.isView(C))){const F=C.byteLength??C.byteLength;k.requestBody=`[binary body, ${F} bytes — not captured]`}else if(typeof Blob<"u"&&C instanceof Blob)k.requestBody=`[Blob, ${C.size} bytes, type=${C.type||"unknown"} — not captured]`;else if(typeof FormData<"u"&&C instanceof FormData)k.requestBody="[FormData — not captured]";else if(typeof ReadableStream<"u"&&C instanceof ReadableStream)k.requestBody="[ReadableStream — not captured]";else{const F=JSON.stringify(C);F&&F!=="{}"&&(k.requestBody=F.length>q?F.substring(0,q)+"...[truncated]":F)}}catch{}}let P;if(w.captureResponseBody){const C=(h.headers.get("content-type")||"").toLowerCase();if(!C||C.includes("json")||C.includes("xml")||C.includes("text/")||C.includes("javascript")||C.includes("ecmascript")||C.includes("x-www-form-urlencoded")||C.includes("application/graphql")){const q=h.clone(),F=w.responseBodyLimitBytes;P=(async()=>{try{const H=await q.text(),J=H.length>F?H.substring(0,F)+"...[truncated]":H;try{e.doSend({...k,responseBody:J})}catch{}}catch{}})(),P.catch(()=>{})}else k.responseBody=`[non-text body, content-type=${C} — not captured]`}P||e.doSend(k)}catch(_){g.getConfig().sfDebug&&console.error("[RequestInterceptor] Post-fetch telemetry failed (response still returned):",_)}return h}:g.getConfig().sfDebug&&console.error("[RequestInterceptor] Fetch not available.")}setHeader(t,e,o){t instanceof Headers?t.set(e,o):t[e]=o}addTracingHeadersToPlainObject(t,e){const o=this.shouldPropagateHeaders(e);if(o){const r=I.getFuncspanOverride();if(r){const i=I.parseHeaderOverride(r);if(i&&i.sample_rate===0)return g.getConfig().sfDebug&&console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${e}`),!1}const s=this.contextManager.getOrSetSfTraceId(),{base:d,parent:u}=this.deriveTraceBaseAndParent(s),a=g.v4();t[this.HEADER_TRACING]=`${d}/${a}`,t[Ge]=u,g.getConfig().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${e}`)}else if(g.getConfig().sfDebug){let r=e;try{r=new URL(e).hostname}catch{}console.error(`[RequestInterceptor] Excluded domain: ${r}`)}return o}patchHttp(t,e){if(g.getConfig().sfDebug&&console.log("[RequestInterceptor] Initializing HTTP/HTTPS request patch..."),!W||typeof W.request!="function")return void(g.getConfig().sfDebug&&console.log("[RequestInterceptor] HTTP/HTTPS not available."));const o=W.request.bind(W),r=ae.request.bind(ae),s=i=>{const c=i.protocol||be;let l=i.hostname||i.host?.split(":")[0]||"localhost";l.includes(":")&&!l.startsWith("[")&&(l=`[${l}]`);let f=i.port!=null&&String(i.port)!==""?String(i.port):"";if(!f&&!i.hostname&&i.host){const p=/:(\d+)$/.exec(i.host);p&&(f=p[1])}return`${c}//${l}${f&&f!==(c===ze?"443":"80")?`:${f}`:""}${typeof i.path=="string"&&i.path?i.path:"/"}`},d=(i,c,l,f=be)=>{let p,y;if(typeof i=="string"||i instanceof URL){const h=typeof i=="string"?new URL(i):i;p={...typeof c=="object"&&c!==null?c:{},protocol:h.protocol||f,hostname:h.hostname,port:h.port||void 0,path:h.pathname+h.search},y=typeof c=="function"?c:l}else p={...i},p.protocol||(p.protocol=f),y=typeof c=="function"?c:void 0;return p.headers||(p.headers={}),[p,y]},u=(i,c,l)=>{const[f,p]=d(i,c,l,be),y=s(f),h=Date.now();try{this.addTracingHeadersToPlainObject(f.headers,y),this.captureFirstUserLines(t)}catch(b){g.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTP request options:",b)}const m=(f.method||"GET").toUpperCase(),E=g.getConfig().retryOnClientError,_=(b,$,w)=>{try{const{sessionId:k,pageVisitId:P,requestId:C}=this.extractIdsFromTraceHeader(f.headers);e.doSend({apiKey:g.getConfig().apiKey,requestId:C,pageVisitId:P,recordingSessionId:k,serviceUuid:g.getConfig().serviceUUID,timestampStart:h.toString(),timestampEnd:Date.now().toString(),responseCode:b.statusCode||0,success:!!b.statusCode&&b.statusCode<400,error:null,url:$,method:m,retryWithoutTraceId:w,parentSpanId:g.getCurrentFunctionSpanId()})}catch{}p?.(b)};return o(f,b=>{const $=y;let w=!1;try{w=this.shouldPropagateHeaders($)}catch{w=!1}if(w&&_e(m,E)&&Ee.includes(b.statusCode||0)){b.resume();try{const{sessionId:P,pageVisitId:C,requestId:q}=this.extractIdsFromTraceHeader(f.headers);e.doSend({apiKey:g.getConfig().apiKey,requestId:q,pageVisitId:C,recordingSessionId:P,serviceUuid:g.getConfig().serviceUUID,timestampStart:h.toString(),timestampEnd:Date.now().toString(),responseCode:b.statusCode||0,success:!1,error:null,url:$,method:m,retryWithoutTraceId:!1,parentSpanId:g.getCurrentFunctionSpanId()})}catch{}try{this.captureFirstUserLines(t,10,!0)}catch{}const k={...f,headers:{...f.headers}};return delete k.headers[this.HEADER_TRACING],void o(k,P=>{_(P,$,!0)}).end()}_(b,$,!1)})},a=(i,c,l)=>{const[f,p]=d(i,c,l,ze),y=s(f),h=Date.now();try{this.addTracingHeadersToPlainObject(f.headers,y),this.captureFirstUserLines(t)}catch(b){g.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTPS request options:",b)}const m=(f.method||"GET").toUpperCase(),E=g.getConfig().retryOnClientError,_=(b,$,w)=>{try{const{sessionId:k,pageVisitId:P,requestId:C}=this.extractIdsFromTraceHeader(f.headers);e.doSend({apiKey:g.getConfig().apiKey,requestId:C,pageVisitId:P,recordingSessionId:k,serviceUuid:g.getConfig().serviceUUID,timestampStart:h.toString(),timestampEnd:Date.now().toString(),responseCode:b.statusCode||0,success:!!b.statusCode&&b.statusCode<400,error:null,url:$,method:m,retryWithoutTraceId:w,parentSpanId:g.getCurrentFunctionSpanId()})}catch{}p?.(b)};return r(f,b=>{const $=y;let w=!1;try{w=this.shouldPropagateHeaders($)}catch{w=!1}if(w&&_e(m,E)&&Ee.includes(b.statusCode||0)){b.resume();try{const{sessionId:P,pageVisitId:C,requestId:q}=this.extractIdsFromTraceHeader(f.headers);e.doSend({apiKey:g.getConfig().apiKey,requestId:q,pageVisitId:C,recordingSessionId:P,serviceUuid:g.getConfig().serviceUUID,timestampStart:h.toString(),timestampEnd:Date.now().toString(),responseCode:b.statusCode||0,success:!1,error:null,url:$,method:m,retryWithoutTraceId:!1,parentSpanId:g.getCurrentFunctionSpanId()})}catch{}try{this.captureFirstUserLines(t,10,!0)}catch{}const k={...f,headers:{...f.headers}};return delete k.headers[this.HEADER_TRACING],void r(k,P=>{_(P,$,!0)}).end()}_(b,$,!1)})};W.request=u,ae.request=a,W.get=(i,c,l)=>{const f=u(i,c,l);return f.end(),f},ae.get=(i,c,l)=>{const f=a(i,c,l);return f.end(),f},g.getConfig().sfDebug&&console.log("✅ HTTP and HTTPS request/get methods patched globally.")}tryPatch(t,e){try{require.resolve(e),t()}catch{}}getExcludedDomains(){return[...this.contextManager.getExcludedDomains()]}}class un extends Ke{constructor(){super(),this.setOperationName("UpdateServiceDetails")}async doSend(){this.send()}async send(){const t=`
148
148
  ${this.queryType} ${this.operationName}(
149
149
  $apiKey: String!,
150
150
  $serviceUuid: String!,
@@ -186,7 +186,7 @@
186
186
  serviceRole: $serviceRole,
187
187
  )
188
188
  }
189
- `,e=p.getConfig(),o=this.getVariables({serviceIdentifier:e.serviceIdentifier,serviceVersion:e.serviceVersion,serviceAdditionalMetadata:e.serviceAdditionalMetadata,gitSha:e.gitSha||"",gitOrg:e.gitOrg||void 0,gitRepo:e.gitRepo||void 0,gitProvider:e.gitProvider||void 0,serviceDisplayName:e.serviceDisplayName||void 0,infrastructureType:e.infrastructureType||void 0,infrastructureDetails:e.infrastructureDetails||void 0,setupInterceptorsFile:e.setupInterceptorsFile||void 0,setupInterceptorsLine:e.setupInterceptorsLine||void 0,framework:e.framework||void 0,additionalFrameworks:e.additionalFrameworks?.length>0?e.additionalFrameworks:void 0,serviceRole:e.serviceRole||void 0});I.nonBlockingPost(this.endpoint,this.operationName,t,o)}}class un{rootPaths;fileConfigs=new Map;functionConfigs=new Map;directoryConfigs=new Map;hasSailfishFiles=!1;runtimeModeEnabled=!1;debug;constructor(t=[process.cwd()],e=!1){this.rootPaths=t,this.debug=e||process.env.SF_DEBUG==="true"}async loadAllConfigs(){this.debug&&console.log("[FuncSpan ConfigLoader] Scanning for .sailfish files in:",this.rootPaths);const t=[];for(const e of this.rootPaths)Yt.existsSync(e)?await this._walkDirectory(e,t):this.debug&&console.log(`[FuncSpan ConfigLoader] Root path does not exist: ${e}`);t.length>0?(this.hasSailfishFiles=!0,this.debug&&(console.log(`[FuncSpan ConfigLoader] Found ${t.length} .sailfish files:`),t.forEach(e=>console.log(`[FuncSpan ConfigLoader] - ${e}`)))):this.debug&&console.log("[FuncSpan ConfigLoader] No .sailfish files found - function spans disabled by default");for(const e of t)await this._loadConfigFile(e);await this._resolveInheritance(),this.debug&&console.log(`[FuncSpan ConfigLoader] Loaded ${this.fileConfigs.size} file configs, ${this.functionConfigs.size} function configs`)}getConfig(t,e){const o=this.hasSailfishFiles?I.getEnvConfig():I.getDefaultConfig(),r=this._getDirectoryConfig(t),s=O.normalize(t),d=this.fileConfigs.get(s)||{};let u={};if(e){const a=this.functionConfigs.get(s);a&&(u=a.get(e)||{})}return I.mergeConfigs(o,r,d,u)}hasRuntimeMode(){return this.runtimeModeEnabled}async _walkDirectory(t,e){try{const o=await Je.readdir(t,{withFileTypes:!0});for(const r of o){const s=O.join(t,r.name);r.isFile()&&r.name===".sailfish"?e.push(s):r.name==="node_modules"||r.isDirectory()&&r.name.startsWith(".")&&r.name!==".sailfish"||r.isDirectory()&&await this._walkDirectory(s,e)}}catch(o){this.debug&&console.error(`[FuncSpan ConfigLoader] Error walking directory ${t}:`,o)}}async _loadConfigFile(t){try{const e=await Je.readFile(t,"utf-8"),o=O.dirname(t);let r=null;try{r=JSON.parse(e)}catch{try{r=require("toml").parse(e)}catch{try{r=require("js-yaml").load(e)}catch(s){return void(this.debug&&console.error(`[FuncSpan ConfigLoader] Failed to parse ${t} as JSON, TOML, or YAML:`,s))}}}if(!r)return;r.runtime_mode===!0&&(this.runtimeModeEnabled=!0,this.debug&&console.log(`[FuncSpan ConfigLoader] Runtime mode ENABLED in ${t}`)),r.default&&this.directoryConfigs.set(o,r.default),r.files&&await this._expandFileGlobs(o,r.files,r.default||{}),r.functions&&this._storeFunctionConfigs(o,r.functions,r.default||{}),this.debug&&(console.log(`[FuncSpan ConfigLoader] Loaded config from ${t}`),console.log(`[FuncSpan ConfigLoader] Directory: ${o}`),console.log(`[FuncSpan ConfigLoader] Has default: ${!!r.default}`),console.log(`[FuncSpan ConfigLoader] File patterns: ${Object.keys(r.files||{}).length}`),console.log(`[FuncSpan ConfigLoader] Functions: ${Object.keys(r.functions||{}).length}`))}catch(e){this.debug&&console.error(`[FuncSpan ConfigLoader] Error loading ${t}:`,e)}}async _expandFileGlobs(t,e,o){for(const[r,s]of Object.entries(e))try{const d=O.join(t,r),u=await Ct.glob(d,{absolute:!0,nodir:!0,ignore:["**/node_modules/**","**/.git/**"]});this.debug&&console.log(`[FuncSpan ConfigLoader] Pattern '${r}' matched ${u.length} files`);for(const a of u){const i=O.normalize(a),l=I.mergeConfigs(o,s);this.fileConfigs.set(i,l),this.debug&&u.length<=5&&console.log(`[FuncSpan ConfigLoader] - ${a}`)}}catch(d){this.debug&&console.error(`[FuncSpan ConfigLoader] Error expanding glob '${r}':`,d)}}_storeFunctionConfigs(t,e,o){for(const[r,s]of Object.entries(e)){const d=r.split("::");if(d.length!==2){this.debug&&console.warn(`[FuncSpan ConfigLoader] Invalid function pattern '${r}' (expected format: 'file.ts::functionName')`);continue}const[u,a]=d,i=O.normalize(O.join(t,u));this.functionConfigs.has(i)||this.functionConfigs.set(i,new Map);const l=this.functionConfigs.get(i),c=I.mergeConfigs(o,s);l.set(a,c),this.debug&&console.log(`[FuncSpan ConfigLoader] Function config: ${i}::${a}`)}}async _resolveInheritance(){}_getDirectoryConfig(t){let e=O.dirname(O.normalize(t));const o=[];for(;e&&e!==O.dirname(e);){const r=this.directoryConfigs.get(e);r&&o.unshift(r),e=O.dirname(e)}return o.reduce((r,s)=>I.mergeConfigs(r,s),{})}}const Ut="__sf_globalConfigLoader";function Dt(){return globalThis[Ut]??null}async function Ye(n,t){const e=new un(n,t);(function(r){globalThis[Ut]=r})(e),await e.loadAllConfigs();const o=globalThis;o.__sf_configEpoch=(o.__sf_configEpoch??0)+1}function Pt(n,t){const e=Dt();return e?e.getConfig(n,t):(process.env.SF_DEBUG==="true"&&console.log("[FuncSpan ConfigLoader] Config loader not initialized, using default config (disabled)"),I.getDefaultConfig())}function Ze(){return Dt()!==null}const ln=["readFile","writeFile","appendFile","readdir","stat","lstat","fstat","access","open","close","read","write","chmod","mkdir","rmdir","unlink","rename"],et=["lookup","resolve","resolve4","resolve6","resolveAny","resolveMx","resolveNs","resolveTxt","reverse"],dn=["pbkdf2","randomBytes","scrypt","generateKeyPair"],fn=["gzip","gunzip","deflate","inflate","deflateRaw","inflateRaw","brotliCompress","brotliDecompress"];let tt=!1;function pn(n){if(typeof n!="string")return!1;const t=process.env.SF_FUNCSPAN_JSONL_FILE;if(t&&n.includes(t))return!0;const e=process.env.SF_WORKER_POOL_JSONL_FILE;return!(!e||!n.includes(e))}let nt=!1;function rt(n){if(typeof n!="string")return!1;if(n==="localhost"||n==="127.0.0.1"||n==="::1")return!0;try{const t=process.env.API_GRAPHQL_ENDPOINT;if(t&&n===new URL(t).hostname)return!0}catch{}return!1}function gn(){if(!nt)try{let n;if(typeof require>"u")return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Skipping dns patching in pure ESM environment (require unavailable)"));try{n=require("node:dns")}catch(t){return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Failed to require dns module:",t))}if(n.__sf_worker_pool_patched__)return;Object.defineProperty(n,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of et)if(typeof n[t]=="function"){const e=n[t];n[t]=function(...o){return I.isSendingInternalTelemetry()?e.apply(this,o):rt(o[0])?e.apply(this,o):typeof o[o.length-1]=="function"?I.captureWorkerPoolOperation("dns",t,e,o,this):e.apply(this,o)},Object.defineProperty(n[t],"name",{value:t,writable:!1})}(function(t){if(!t.promises)return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises not available, skipping"));if(!t.promises.__sf_worker_pool_patched__){Object.defineProperty(t.promises,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of et)if(typeof t.promises[e]=="function"){const o=t.promises[e];t.promises[e]=function(...r){return I.isSendingInternalTelemetry()?o.apply(this,r):rt(r[0])?o.apply(this,r):I.captureWorkerPoolPromiseOperation("dns",e,o,r,this)},Object.defineProperty(t.promises[e],"name",{value:e,writable:!1})}process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises module patched successfully")}})(n),nt=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns module patched successfully")}catch(n){console.error("[WorkerPool] Error patching dns module:",n)}}let ot=!1,it=!1,Pe=!1;function st(){if(Pe)return;const n=process.env.SF_DEBUG==="true";n&&console.log("[WorkerPool] Initializing worker pool patching..."),I.isModuleTrackingEnabled("fs")&&(n&&console.log("[WorkerPool] Patching fs module..."),(function(){if(!tt)try{const t=require("node:fs");if(t.__sf_worker_pool_patched__)return;Object.defineProperty(t,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of ln)if(typeof t[e]=="function"){const o=t[e];t[e]=function(...r){return pn(r[0])?o.apply(this,r):typeof r[r.length-1]=="function"?I.captureWorkerPoolOperation("fs",e,o,r,this):o.apply(this,r)},Object.defineProperty(t[e],"name",{value:e,writable:!1})}tt=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] fs module patched successfully")}catch(t){console.error("[WorkerPool] Error patching fs module:",t)}})()),I.isModuleTrackingEnabled("dns")&&(n&&console.log("[WorkerPool] Patching dns module..."),gn()),I.isModuleTrackingEnabled("crypto")&&(n&&console.log("[WorkerPool] Patching crypto module..."),(function(){if(!ot)try{const t=require("node:crypto");if(t.__sf_worker_pool_patched__)return;Object.defineProperty(t,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of dn)if(typeof t[e]=="function"){const o=t[e];t[e]=function(...r){return typeof r[r.length-1]=="function"?I.captureWorkerPoolOperation("crypto",e,o,r,this):o.apply(this,r)},Object.defineProperty(t[e],"name",{value:e,writable:!1})}ot=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] crypto module patched successfully")}catch(t){console.error("[WorkerPool] Error patching crypto module:",t)}})()),I.isModuleTrackingEnabled("zlib")&&(n&&console.log("[WorkerPool] Patching zlib module..."),(function(){if(!it)try{const t=require("node:zlib");if(t.__sf_worker_pool_patched__)return;Object.defineProperty(t,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of fn)if(typeof t[e]=="function"){const o=t[e];t[e]=function(...r){return typeof r[r.length-1]=="function"?I.captureWorkerPoolOperation("zlib",e,o,r,this):o.apply(this,r)},Object.defineProperty(t[e],"name",{value:e,writable:!1})}it=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] zlib module patched successfully")}catch(t){console.error("[WorkerPool] Error patching zlib module:",t)}})()),Pe=!0,n&&console.log("[WorkerPool] Worker pool patching initialized")}function at(){return Pe}const ct=te.toLowerCase();function z(n){if(n!=null){if(Array.isArray(n)){for(const t of n)if(!(!t||typeof t!="object")&&ut(t.key)===ct)return t.value}else if(typeof n=="object"){for(const[t,e]of Object.entries(n))if(ut(t)===ct)return Array.isArray(e)?e.length===0?void 0:e[0]:e}}}function ut(n){if(typeof n=="string")return n.toLowerCase();if(Buffer.isBuffer(n))try{return n.toString("utf8").toLowerCase()}catch{return null}if(n instanceof Uint8Array)try{return Buffer.from(n).toString("utf8").toLowerCase()}catch{return null}return null}let _e=null;function Ft(){return _e||(_e=new Nt),_e}function Tt(n){if(!n)return null;const t=n.split("/").filter(Boolean);return t.length<3?null:{sessionId:t[0],pageVisitId:t[1],requestId:t[t.length-1]}}const hn=/^[A-Za-z0-9._:-]{1,128}$/;function Z(n){if(typeof n!="string"||n.length===0||n.length>1024)return!1;const t=n.split("/").filter(Boolean);if(t.length<3||t.length>6)return!1;for(const e of t)if(!hn.test(e))return!1;return!0}function ee(n){const t=n.split("/");return t.length>=3?(t[t.length-1]=p.v4(),t.join("/")):`${n}/${p.v4()}`}function yn(n){if(n==null)return null;if(typeof n=="string")return n;if(Buffer.isBuffer(n))try{return n.toString("utf8")}catch{return null}try{return JSON.stringify(Fe(n))}catch{return null}}function Fe(n,t=0){if(t>10)return"[truncated-depth]";if(n==null)return n;const e=typeof n;if(e==="string"||e==="number"||e==="boolean")return n;if(e==="bigint")return n.toString();if(e!=="object")return;if(Buffer.isBuffer(n))return`[Buffer ${n.length}b]`;if(ArrayBuffer.isView(n)){const r=n;return`[${r.constructor?.name??"TypedArray"} ${r.byteLength}b]`}if(n instanceof Date)try{return n.toISOString()}catch{return"[Date]"}if(n instanceof Map)return`[Map size=${n.size}]`;if(n instanceof Set)return`[Set size=${n.size}]`;if(Array.isArray(n))return n.map(r=>Fe(r,t+1));const o={};for(const r of Object.getOwnPropertyNames(n)){const s=Object.getOwnPropertyDescriptor(n,r);s&&typeof s.get!="function"&&typeof s.set!="function"&&(o[r]=Fe(s.value,t+1))}return o}function qt(n){if(!n)return null;try{const t=n.message;if(typeof t=="string"&&t.length>0)return t}catch{}try{const t=String(n);if(typeof t=="string"&&t.length>0)return t}catch{}try{const t=n.name;if(typeof t=="string"&&t.length>0)return t}catch{}return"[unstringifiable error]"}function F(n){const t=p.ContextManager.getInstance().getOrSetSfTraceId(),e=ee(t),o=Tt(e),r=Date.now(),s=p.getConfig(),d=n.queueUri,u=n.method??"ENQUEUE",a=At(n.messagePayload,s);return{traceId:e,hopEnd:i=>{try{if(!o)return;const l=Date.now();let c=null;try{c=p.getCurrentFunctionSpanId()??null}catch{}const f={apiKey:s.apiKey,requestId:o.requestId,pageVisitId:o.pageVisitId,recordingSessionId:o.sessionId,serviceUuid:s.serviceUUID??null,timestampStart:r.toString(),timestampEnd:l.toString(),responseCode:i?500:0,success:!i,error:qt(i),url:d,method:u,parentSpanId:c};a!==null&&(f.requestBody=a),Lt(f);try{Ft().doSend(f)}catch(g){s.sfDebug&&console.warn("[asyncQueues] producer hop transmit failed:",g)}}catch{}}}}function At(n,t){if(!t.captureRequestBody||n===void 0)return null;const e=yn(n);return e?(function(o,r){return!r||r<=0?o:o.length>r?o.substring(0,r)+"...[truncated]":o})(e,t.requestBodyLimitBytes):null}function x(n,t){if(lt.getStore()===!0)return Promise.resolve(t());const e=p.ContextManager.getInstance(),o=p.getConfig(),r=n.incomingTraceId!==void 0&&Z(n.incomingTraceId)?n.incomingTraceId:`${p.NONSESSION_APPLOGS}-v3/${o.apiKey}/${p.v4()}`,s=n.queueUri,d=n.method,u=n.library,a=At(n.messagePayload,o);return lt.run(!0,()=>e.runScoped({traceId:r},async()=>{const i=Date.now();let l=null;try{const c=await Promise.resolve(t());return await(function(f){return f!==null&&typeof f=="object"&&typeof f.subscribe=="function"?new Promise((g,m)=>{let h,y=!1;try{f.subscribe({next:S=>{h=S,y=!0},error:S=>m(S),complete:()=>g(y?h:void 0)})}catch(S){m(S)}}):f})(c)}catch(c){throw l=c instanceof Error?c:new Error(String(c)),c}finally{(function(c,f,g,m,h,y){try{const S=Tt(g);if(!S)return;const E=p.getConfig(),{graceful:_,tag:$}=(function(H){if(!H)return{graceful:!0,tag:null};let J;try{J=H.name}catch{return{graceful:!1,tag:null}}return J==="AbortError"?{graceful:!0,tag:"CONSUME_CANCELLED"}:J==="DelayedError"?{graceful:!0,tag:"CONSUME_RESCHEDULED"}:J==="WaitingChildrenError"?{graceful:!0,tag:"CONSUME_WAITING_CHILDREN"}:{graceful:!1,tag:null}})(y),w=!y&&c.method?c.method:$??c.method??"CONSUME",N=!y||_,B=y&&!_?500:0,C=y&&!_?qt(y):null;let T=null;try{T=p.getCurrentFunctionSpanId()??null}catch{}const P={apiKey:E.apiKey,requestId:S.requestId,pageVisitId:S.pageVisitId,recordingSessionId:S.sessionId,serviceUuid:E.serviceUUID??null,timestampStart:m.toString(),timestampEnd:h.toString(),responseCode:B,success:N,error:C,url:c.queueUri,method:w,parentSpanId:T};f!==null&&(P.requestBody=f),Lt(P);try{Ft().doSend(P)}catch(H){E.sfDebug&&console.warn("[asyncQueues] consumer hop transmit failed:",H)}}catch{}})({library:u,queueUri:s,method:d},a,r,i,Date.now(),l)}}))}const lt=new Vt.AsyncLocalStorage;let Te=null;function Lt(n){if(Te!==null)try{Te(n)}catch{}}const v=Symbol.for("sailfish.async-queues.patched"),k=Symbol.for("sailfish.async-queues.instance-wrapped"),qe=[];function U(n,t,e){if(qe.some(r=>r.proto===n&&r.key===t))return!1;const o=typeof n?.[t]=="function"?n[t]:void 0;try{return n[t]=e,qe.push({proto:n,key:t,original:o}),!0}catch(r){if(p.getConfig().sfDebug){const s=n?.constructor?.name??"<unknown>";console.warn(`[asyncQueues] could not install patch on ${s}.prototype.${t} (frozen / non-writable?):`,r)}return!1}}function A(n,t){try{return n()}catch(e){return p.getConfig().sfDebug&&console.warn(`[asyncQueues] instrumentation rewrite threw in ${t} — falling back to original args, no hop emitted:`,e),null}}function q(n,t){let e=n||"unknown";if(typeof e=="string"){e.startsWith("bull:")&&(e=e.slice(5));const o=/^\{([^}]+)\}:(.+)$/.exec(e);o&&(e=`${o[1]}/${o[2]}`)}return`bullmq://redis/${e}/${t||"unknown"}`}function pe(n){return n?.queueQualifiedName??n?.queueName??n?.queue?.name??void 0}function M(n,t){const e=n?{...n}:{},o=e.sf&&typeof e.sf=="object"?e.sf:{};return e.sf={...o,rid:t},e}function mn(n){let t=n;if(!t)try{t=require("bullmq")}catch{return"not-installed"}(function(a){try{const i=a?.version??a?.Queue?.version;if(typeof i!="string")return;parseInt(i.split(".")[0]??"0",10)<3&&p.getConfig().sfDebug&&console.warn(`[sf-veritas] BullMQ ${i} detected. Async-queue tracing is best-supported on BullMQ ≥ 3.0. Some APIs (FlowProducer, upsertJobScheduler, Job.promote) may be missing on older versions and will be skipped silently.`)}catch{}})(t);const e=t.Queue,o=t.Worker;if(!e?.prototype||!o?.prototype)return p.getConfig().sfDebug&&console.warn("[asyncQueues][bullmq] Expected Queue/Worker classes not found on module — skipping patch."),"failed";(function(a){const i=a.prototype.add;if(typeof i!="function"||i[v])return;const l=async function(c,f,g){if(g?.sf?.rid)return i.call(this,c,f,g);const m=A(()=>{const y=F({library:"bullmq",queueUri:q(this?.name,c),messagePayload:f});return{handle:y,nextOpts:M(g,y.traceId)}},"bullmq.Queue.add");if(m===null)return i.call(this,c,f,g);let h=null;try{return await i.call(this,c,f,m.nextOpts)}catch(y){throw h=y instanceof Error?y:new Error(String(y)),y}finally{m.handle.hopEnd(h)}};l[v]=!0,U(a.prototype,"add",l)})(e),(function(a){const i=a.prototype.addBulk;if(typeof i!="function"||i[v])return;const l=async function(c){if(!Array.isArray(c)||c.length===0)return i.call(this,c);if(c.every(h=>h?.opts?.sf?.rid))return i.call(this,c);const f=p.getConfig().bullmqBulkAggregateMode,g=A(()=>{if(f){const S=F({library:"bullmq",queueUri:q(this?.name,`__bulk_${c.length}`),method:"ENQUEUE_BULK",messagePayload:{batchSize:c.length}}),E=c.map(_=>({..._,opts:M(_?.opts,S.traceId)}));return{handles:[S],out:E}}const h=c.map(S=>F({library:"bullmq",queueUri:q(this?.name,S?.name),messagePayload:S?.data})),y=c.map((S,E)=>({...S,opts:M(S?.opts,h[E].traceId)}));return{handles:h,out:y}},"bullmq.Queue.addBulk");if(g===null)return i.call(this,c);let m=null;try{return await i.call(this,g.out)}catch(h){throw m=h instanceof Error?h:new Error(String(h)),h}finally{for(const h of g.handles)h.hopEnd(m)}};l[v]=!0,U(a.prototype,"addBulk",l)})(e),(function(a){const i=a.prototype.upsertJobScheduler;if(typeof i!="function"||i[v])return;const l=async function(c,f,g){const m=A(()=>{const y=F({library:"bullmq",queueUri:q(this?.name,g?.name??c),method:"ENQUEUE"});let S;if(g!==void 0){const E={...g,opts:M(g.opts,y.traceId)};S=[c,f,E]}else S=[c,f];return{handle:y,callArgs:S}},"bullmq.Queue.upsertJobScheduler");if(m===null){const y=g!==void 0?[c,f,g]:[c,f];return i.call(this,...y)}let h=null;try{return await i.call(this,...m.callArgs)}catch(y){throw h=y instanceof Error?y:new Error(String(y)),y}finally{m.handle.hopEnd(h)}};l[v]=!0,U(a.prototype,"upsertJobScheduler",l)})(e),(function(a){const i=a.prototype.getNextJob;if(typeof i!="function"||i[v])return;const l=async function(...c){const f=await i.apply(this,c);if(f&&Z(f.opts?.sf?.rid))try{p.ContextManager.getInstance().setTraceId(f.opts.sf.rid)}catch{}return f};l[v]=!0,U(a.prototype,"getNextJob",l)})(e),(function(a){const i=a.prototype.getJob;if(typeof i!="function"||i[v])return;const l=async function(...c){const f=await i.apply(this,c);if(f&&Z(f.opts?.sf?.rid))try{const m=p.ContextManager.getInstance();(!(g=m.getTraceId())||g.startsWith("nonsession-applogs-v3/"))&&m.setTraceId(f.opts.sf.rid)}catch{}var g;return f};l[v]=!0,U(a.prototype,"getJob",l)})(e),(function(a){const i=a.prototype.processJob;if(typeof i!="function"||i[v])return;const l=function(c,...f){const g=c?.opts?.sf?.rid,m=typeof c?.attemptsMade=="number"?c.attemptsMade:0,h=typeof c?.stalledCounter=="number"?c.stalledCounter:0,y=c?.repeatJobKey!=null||c?.opts?.repeat!=null,S=g&&(m>0||h>0||y)?ee(g):g;let E;return h>0?E="CONSUME_STALLED":y&&m===0&&(E="CONSUME_SCHEDULED"),x({library:"bullmq",queueUri:q(pe(c)??this?.name,c?.name),incomingTraceId:S,messagePayload:c?.data,method:E},()=>i.call(this,c,...f))};l[v]=!0,U(a.prototype,"processJob",l)})(o);const r=t.Job;r?.prototype&&(function(a){const i=["retry","moveToDelayed","promote"];for(const l of i){const c=a.prototype[l];if(typeof c!="function"||c[v])continue;const f=l==="promote"?"PROMOTE":l==="moveToDelayed"?"RESCHEDULE":"ENQUEUE_RETRY",g=async function(...m){const h=this?.opts?.sf?.rid;let y;if(h)y=ee(h);else{const _=F({queueUri:q(pe(this)??this?.name,this?.name),method:f});let $=null;try{return await c.apply(this,m)}catch(w){throw $=w instanceof Error?w:new Error(String(w)),w}finally{_.hopEnd($)}}this.opts&&(this.opts={...this.opts,sf:{...this.opts.sf||{},rid:y}});const S=F({queueUri:q(pe(this)??this?.name,this?.name),method:f});let E=null;try{return await c.apply(this,m)}catch(_){throw E=_ instanceof Error?_:new Error(String(_)),_}finally{S.hopEnd(E)}};g[v]=!0,U(a.prototype,l,g)}})(r);const s=t.QueueEvents;s?.prototype&&(s.prototype[v]=!1);const d=t.FlowProducer;return d?.prototype&&((function(a){const i=a.prototype.add;if(typeof i!="function"||i[v])return;const l=async function(c,...f){if(!c||typeof c!="object")return i.call(this,c,...f);if(c?.opts?.sf?.rid)return i.call(this,c,...f);const g=A(()=>{const h=[];return{hops:h,out:Ae(c,h)}},"bullmq.FlowProducer.add");if(g===null)return i.call(this,c,...f);let m=null;try{return await i.call(this,g.out,...f)}catch(h){throw m=h instanceof Error?h:new Error(String(h)),h}finally{for(const h of g.hops)h.hopEnd(m)}};l[v]=!0,U(a.prototype,"add",l)})(d),(function(a){const i=a.prototype.addBulk;if(typeof i!="function"||i[v])return;const l=async function(c){if(!Array.isArray(c)||c.length===0)return i.call(this,c);if(c.every(h=>h?.opts?.sf?.rid))return i.call(this,c);const f=p.getConfig().bullmqBulkAggregateMode,g=A(()=>{if(f){const S=w=>{let N=1;if(Array.isArray(w?.children))for(const B of w.children)N+=S(B);return N},E=c.reduce((w,N)=>w+S(N),0),_=F({library:"bullmq-flow",queueUri:q(c[0]?.queueName,`__flow_bulk_${c.length}`),method:"ENQUEUE_BULK",messagePayload:{batchSize:c.length,totalNodes:E}}),$=c.map(w=>Ot(w,_.traceId));return{hops:[_],out:$}}const h=[],y=c.map(S=>Ae(S,h));return{hops:h,out:y}},"bullmq.FlowProducer.addBulk");if(g===null)return i.call(this,c);let m=null;try{return await i.call(this,g.out)}catch(h){throw m=h instanceof Error?h:new Error(String(h)),h}finally{for(const h of g.hops)h.hopEnd(m)}};l[v]=!0,U(a.prototype,"addBulk",l)})(d)),t.QueueScheduler?.prototype&&p.getConfig().sfDebug&&console.log("[sf-veritas] BullMQ QueueScheduler detected (v4 API). No direct instrumentation needed — delayed/repeatable jobs are traced when the Worker picks them up via the Worker.processJob wrap."),"installed"}function Ae(n,t){const e=F({queueUri:q(n?.queueName,n?.name),messagePayload:n?.data});t.push(e);const o={...n,opts:M(n?.opts,e.traceId)};return Array.isArray(n?.children)&&n.children.length>0&&(o.children=n.children.map(r=>Ae(r,t))),o}function Ot(n,t){const e={...n,opts:M(n?.opts,t)};return Array.isArray(n?.children)&&n.children.length>0&&(e.children=n.children.map(o=>Ot(o,t))),e}function Sn(n){let t=n;if(!t)try{t=require("@taskforcesh/bullmq-pro")}catch{return"not-installed"}const e=t.QueuePro,o=t.WorkerPro;t.JobPro;const r=t.FlowProducerPro;return e?.prototype||o?.prototype?(e?.prototype&&((function(s){const d=s.prototype.add;if(typeof d!="function"||d[v])return;const u=async function(a,i,l){if(l?.sf?.rid)return d.call(this,a,i,l);const c=A(()=>{const g=F({library:"bullmq-pro",queueUri:q(this?.name,a),messagePayload:i});return{handle:g,nextOpts:M(l,g.traceId)}},"bullmq-pro.QueuePro.add");if(c===null)return d.call(this,a,i,l);let f=null;try{return await d.call(this,a,i,c.nextOpts)}catch(g){throw f=g instanceof Error?g:new Error(String(g)),g}finally{c.handle.hopEnd(f)}};u[v]=!0,U(s.prototype,"add",u)})(e),(function(s){const d=s.prototype.addBulk;if(typeof d!="function"||d[v])return;const u=async function(a){if(!Array.isArray(a)||a.length===0)return d.call(this,a);if(a.every(f=>f?.opts?.sf?.rid))return d.call(this,a);const i=p.getConfig().bullmqBulkAggregateMode,l=A(()=>{if(i){const m=F({library:"bullmq-pro",queueUri:q(this?.name,`__bulk_${a.length}`),method:"ENQUEUE_BULK",messagePayload:{batchSize:a.length}}),h=a.map(y=>({...y,opts:M(y?.opts,m.traceId)}));return{handles:[m],out:h}}const f=a.map(m=>F({library:"bullmq-pro",queueUri:q(this?.name,m?.name),messagePayload:m?.data})),g=a.map((m,h)=>({...m,opts:M(m?.opts,f[h].traceId)}));return{handles:f,out:g}},"bullmq-pro.QueuePro.addBulk");if(l===null)return d.call(this,a);let c=null;try{return await d.call(this,l.out)}catch(f){throw c=f instanceof Error?f:new Error(String(f)),f}finally{for(const f of l.handles)f.hopEnd(c)}};u[v]=!0,U(s.prototype,"addBulk",u)})(e)),o?.prototype&&((function(s){const d=s.prototype.processJob;typeof d!="function"||d[v]||dt(s,"processJob",d)})(o),(function(s){const d=s.prototype.getNextJob;if(typeof d!="function"||d[v])return;const u=async function(...a){const i=await d.apply(this,a);if(i&&Z(i.opts?.sf?.rid))try{const c=p.ContextManager.getInstance();(!(l=c.getTraceId())||l.startsWith("nonsession-applogs-v3/"))&&c.setTraceId(i.opts.sf.rid)}catch{}var l;return i};u[v]=!0,U(s.prototype,"getNextJob",u)})(o),typeof o.prototype.callProcessJob=="function"&&(function(s){const d=s.prototype.callProcessJob;typeof d!="function"||d[v]||dt(s,"callProcessJob",d)})(o)),r?.prototype&&(function(s){const d=s.prototype.add;if(typeof d!="function"||d[v])return;const u=async function(a,...i){if(!a||typeof a!="object")return d.call(this,a,...i);if(a?.opts?.sf?.rid)return d.call(this,a,...i);const l=A(()=>{const f=[];return{hops:f,out:Bt(a,f)}},"bullmq-pro.FlowProducerPro.add");if(l===null)return d.call(this,a,...i);let c=null;try{return await d.call(this,l.out,...i)}catch(f){throw c=f instanceof Error?f:new Error(String(f)),f}finally{for(const f of l.hops)f.hopEnd(c)}};u[v]=!0,U(s.prototype,"add",u)})(r),"installed"):(p.getConfig().sfDebug&&console.warn("[asyncQueues][bullmq-pro] No QueuePro/WorkerPro found — patch no-op."),"failed")}function dt(n,t,e){const o=function(r,...s){const d=r?.opts?.sf?.rid,u=typeof r?.attemptsMade=="number"?r.attemptsMade:0,a=typeof r?.stalledCounter=="number"?r.stalledCounter:0,i=r?.repeatJobKey!=null||r?.opts?.repeat!=null,l=Z(d)&&(u>0||a>0||i)?ee(d):Z(d)?d:void 0;let c;return a>0?c="CONSUME_STALLED":i&&u===0&&(c="CONSUME_SCHEDULED"),x({library:"bullmq-pro",queueUri:q(pe(r)??this?.name,r?.name),incomingTraceId:l,messagePayload:r?.data,method:c},()=>e.call(this,r,...s))};o[v]=!0,U(n.prototype,t,o)}function Bt(n,t,e=0){if(e>100)return n;const o=F({queueUri:q(n?.queueName,n?.name),messagePayload:n?.data});t.push(o);const r={...n,opts:M(n?.opts,o.traceId)};return Array.isArray(n?.children)&&n.children.length>0&&(r.children=n.children.map(s=>Bt(s,t,e+1))),r}const Le=te.toLowerCase();function G(n){if(n!=null){if(typeof n=="string")return n;if(Buffer.isBuffer(n))try{return n.toString("utf8")}catch{return}if(n instanceof Uint8Array)try{return Buffer.from(n).toString("utf8")}catch{return}return String(n)}}function j(n,t="broker"){return`kafka://${t}/${n??"unknown"}`}function re(n){if(Array.isArray(n))for(const t of n){if(!t||typeof t!="object")continue;const e=t.key;if(typeof e=="string"&&e.toLowerCase()===Le)return G(t.value)}}function Rt(n,t){const e=[];if(Array.isArray(n)){for(const o of n)if(o&&typeof o=="object"){const r=o.key,s=o.value;typeof r=="string"&&r.toLowerCase()===Le||e.push({key:String(r),value:Buffer.isBuffer(s)?s:Buffer.from(String(s??""))})}}else if(n&&typeof n=="object")for(const[o,r]of Object.entries(n))o.toLowerCase()!==Le&&e.push({key:o,value:Buffer.isBuffer(r)?r:Buffer.from(String(r??""))});return e.push({key:te,value:Buffer.from(t)}),e}function bn(n){let t=n;if(!t)try{t=require("@confluentinc/kafka-javascript")}catch{return"not-installed"}let e=!1;t.KafkaProducer?.prototype&&((function(r){const s=r.prototype.produce;if(typeof s!="function"||s[v])return;const d=function(...u){return u.length===1&&u[0]&&typeof u[0]=="object"&&Array.isArray(u[0].messages)?vn.call(this,s,u[0]):In.call(this,s,u)};d[v]=!0,U(r.prototype,"produce",d)})(t.KafkaProducer),e=!0),t.KafkaConsumer?.prototype&&((function(r){const s=r.prototype.on;if(typeof s!="function"||s[v])return;const d=function(u,a){if(u!=="data"||typeof a!="function")return s.call(this,u,a);const i=function(l){const c=re(l?.headers),f=l?.topic,g=G(l?.value)??l?.value;return x({library:"confluent-kafka-js",queueUri:j(f),incomingTraceId:c,messagePayload:g},()=>a.call(this,l))};return s.call(this,u,i)};d[v]=!0,U(r.prototype,"on",d)})(t.KafkaConsumer),e=!0);const o=t.KafkaJS??t;return o?.Producer?.prototype?.send&&((function(r){const s=r.prototype.send;if(typeof s=="function"&&!s[v]){const a=Oe(s);a[v]=!0,U(r.prototype,"send",a)}const d=r.prototype.sendBatch;if(typeof d=="function"&&!d[v]){const a=Be(d);a[v]=!0,U(r.prototype,"sendBatch",a)}const u=r.prototype.transaction;if(typeof u=="function"&&!u[v]){const a=pt(u);a[v]=!0,U(r.prototype,"transaction",a)}})(o.Producer),e=!0),o?.Consumer?.prototype?.run&&((function(r){const s=r.prototype.run;if(typeof s!="function"||s[v])return;const d=async function(u){if(!u||typeof u!="object")return s.call(this,u);const a={...u};if(typeof u.eachMessage=="function"){const i=u.eachMessage;a.eachMessage=l=>{const c=G(z(l?.message?.headers))??re(l?.message?.headers),f=typeof l?.attempt=="number"?l.attempt:0,g=c&&f>0?ee(c):c;return x({library:"confluent-kafka-js",queueUri:j(l?.topic),incomingTraceId:g},()=>i(l))}}if(typeof u.eachBatch=="function"){const i=u.eachBatch;a.eachBatch=l=>{let c=!1;try{typeof l?.isStale=="function"&&(c=!!l.isStale())}catch{}if(c)return i(l);const f=Array.isArray(l?.batch?.messages)?l.batch.messages[0]:void 0,g=G(z(f?.headers))??re(f?.headers);return x({library:"confluent-kafka-js",queueUri:j(l?.batch?.topic),incomingTraceId:g},()=>i(l))}}return s.call(this,a)};d[v]=!0,U(r.prototype,"run",d)})(o.Consumer),e=!0),typeof o?.Kafka=="function"&&o.Kafka.prototype&&((function(r){const s=r.prototype.producer;if(typeof s=="function"&&!s[v]){const u=function(...a){const i=s.apply(this,a);return i&&typeof i.send=="function"&&!i.send[k]&&(i.send=Oe(i.send.bind(i)),i.send[k]=!0),i&&typeof i.sendBatch=="function"&&!i.sendBatch[k]&&(i.sendBatch=Be(i.sendBatch.bind(i)),i.sendBatch[k]=!0),i&&typeof i.transaction=="function"&&!i.transaction[k]&&(i.transaction=pt(i.transaction.bind(i)),i.transaction[k]=!0),i};u[v]=!0,U(r.prototype,"producer",u)}const d=r.prototype.consumer;if(typeof d=="function"&&!d[v]){const u=function(...a){const i=d.apply(this,a);if(i&&typeof i.run=="function"&&!i.run[k]){const l=i.run.bind(i);i.run=async function(c){if(!c||typeof c!="object")return l(c);const f={...c};if(typeof c.eachMessage=="function"){const g=c.eachMessage;f.eachMessage=m=>{const h=G(z(m?.message?.headers))??re(m?.message?.headers);return x({library:"confluent-kafka-js",queueUri:j(m?.topic),incomingTraceId:h},()=>g(m))}}if(typeof c.eachBatch=="function"){const g=c.eachBatch;f.eachBatch=m=>{let h=!1;try{typeof m?.isStale=="function"&&(h=!!m.isStale())}catch{}if(h)return g(m);const y=Array.isArray(m?.batch?.messages)?m.batch.messages[0]:void 0,S=G(z(y?.headers))??re(y?.headers);return x({library:"confluent-kafka-js",queueUri:j(m?.batch?.topic),incomingTraceId:S},()=>g(m))}}return l(f)},i.run[k]=!0}return i};u[v]=!0,U(r.prototype,"consumer",u)}})(o.Kafka),e=!0),e?"installed":(p.getConfig().sfDebug&&console.warn("[asyncQueues][confluentKafkaJs] No recognizable Producer/Consumer/Kafka class — patch no-op."),"failed")}function vn(n,t){const e=A(()=>{const r=t?.topic,s=t.messages.map(()=>F({library:"confluent-kafka-js",queueUri:j(r),method:"ENQUEUE_BUFFERED"})),d=t.messages.map((u,a)=>({...u,headers:Rt(u?.headers,s[a].traceId)}));return{handles:s,outOptions:{...t,messages:d}}},"confluentKafkaJs.KafkaProducer.produce(object)");if(e===null)return n.call(this,t);let o=null;try{return n.call(this,e.outOptions)}catch(r){throw o=r instanceof Error?r:new Error(String(r)),r}finally{for(const r of e.handles)r.hopEnd(o)}}function In(n,t){const[e,o,r,s,d,u,a]=t,i=A(()=>{const c=F({library:"confluent-kafka-js",queueUri:j(typeof e=="string"?e:void 0),method:"ENQUEUE_BUFFERED"});return{handle:c,injectedHeaders:Rt(a,c.traceId)}},"confluentKafkaJs.KafkaProducer.produce(positional)");if(i===null)return n.call(this,e,o,r,s,d,u,a);let l=null;try{return n.call(this,e,o,r,s,d,u,i.injectedHeaders)}catch(c){throw l=c instanceof Error?c:new Error(String(c)),c}finally{i.handle.hopEnd(l)}}function Oe(n,t={}){const e=t.method??"ENQUEUE",o=t.library??"confluent-kafka-js";return async function(r){if(!r||!Array.isArray(r.messages))return n.call(this,r);const s=A(()=>{const u=r.messages.map(()=>F({library:o,queueUri:j(r.topic),method:e})),a=r.messages.map((i,l)=>({...i,headers:{...i?.headers||{},[te]:Buffer.from(u[l].traceId)}}));return{handles:u,outPayload:{...r,messages:a}}},`confluentKafkaJs.Producer.${e}`);if(s===null)return n.call(this,r);let d=null;try{return await n.call(this,s.outPayload)}catch(u){throw d=u instanceof Error?u:new Error(String(u)),u}finally{for(const u of s.handles)u.hopEnd(d)}}}function Be(n,t={}){const e=t.method??"ENQUEUE",o=t.library??"confluent-kafka-js";return async function(r){if(!r||!Array.isArray(r.topicMessages))return n.call(this,r);const s=A(()=>{const u=[],a=r.topicMessages.map(i=>{const l=(Array.isArray(i?.messages)?i.messages:[]).map(c=>{const f=F({library:o,queueUri:j(i?.topic),method:e});return u.push(f),{...c,headers:{...c?.headers||{},[te]:Buffer.from(f.traceId)}}});return{...i,messages:l}});return{handles:u,outPayload:{...r,topicMessages:a}}},`confluentKafkaJs.Producer.sendBatch[${e}]`);if(s===null)return n.call(this,r);let d=null;try{return await n.call(this,s.outPayload)}catch(u){throw d=u instanceof Error?u:new Error(String(u)),u}finally{for(const u of s.handles)u.hopEnd(d)}}}function ft(n,t){return async function(...e){const o=F({queueUri:"kafka://broker/_tx",method:t});let r=null;try{return await n.apply(this,e)}catch(s){throw r=s instanceof Error?s:new Error(String(s)),s}finally{o.hopEnd(r)}}}function pt(n){return async function(...t){const e=await n.apply(this,t);return e&&typeof e.send=="function"&&!e.send[k]&&(e.send=Oe(e.send.bind(e),{method:"ENQUEUE_TX",library:"confluent-kafka-js-tx"}),e.send[k]=!0),e&&typeof e.sendBatch=="function"&&!e.sendBatch[k]&&(e.sendBatch=Be(e.sendBatch.bind(e),{method:"ENQUEUE_TX",library:"confluent-kafka-js-tx"}),e.sendBatch[k]=!0),e&&typeof e.commit=="function"&&!e.commit[k]&&(e.commit=ft(e.commit.bind(e),"COMMIT_TX"),e.commit[k]=!0),e&&typeof e.abort=="function"&&!e.abort[k]&&(e.abort=ft(e.abort.bind(e),"ABORT_TX"),e.abort[k]=!0),e}}function we(n){if(n!=null){if(typeof n=="string")return n;if(Buffer.isBuffer(n))try{return n.toString("utf8")}catch{return}if(n instanceof Uint8Array)try{return Buffer.from(n).toString("utf8")}catch{return}return String(n)}}function he(n,t){return`kafka://broker/${n??"unknown"}`}function En(n){let t=n;if(!t)try{t=require("kafkajs")}catch{return"not-installed"}const e=t.Producer,o=t.Consumer;e?.prototype&&typeof e.prototype.send=="function"&&(function(s){const d=s.prototype.send;if(typeof d=="function"&&!d[v]){const i=Re(d);i[v]=!0,U(s.prototype,"send",i)}const u=s.prototype.sendBatch;if(typeof u=="function"&&!u[v]){const i=Me(u);i[v]=!0,U(s.prototype,"sendBatch",i)}const a=s.prototype.transaction;if(typeof a=="function"&&!a[v]){const i=ht(a);i[v]=!0,U(s.prototype,"transaction",i)}})(e),o?.prototype&&typeof o.prototype.run=="function"&&(function(s){const d=s.prototype.run;if(typeof d!="function"||d[v])return;const u=yt(d);u[v]=!0,U(s.prototype,"run",u)})(o);const r=t.Kafka;if(typeof r=="function"&&r.prototype)(function(s){const d=s.prototype.producer;if(typeof d=="function"&&!d[v]){const a=function(...i){const l=d.apply(this,i);return l&&typeof l.send=="function"&&!l.send[k]&&(l.send=Re(l.send.bind(l)),l.send[k]=!0),l&&typeof l.sendBatch=="function"&&!l.sendBatch[k]&&(l.sendBatch=Me(l.sendBatch.bind(l)),l.sendBatch[k]=!0),l&&typeof l.transaction=="function"&&!l.transaction[k]&&(l.transaction=ht(l.transaction.bind(l)),l.transaction[k]=!0),l};a[v]=!0,U(s.prototype,"producer",a)}const u=s.prototype.consumer;if(typeof u=="function"&&!u[v]){const a=function(...i){const l=u.apply(this,i);return l&&typeof l.run=="function"&&!l.run[k]&&(l.run=yt(l.run.bind(l)),l.run[k]=!0),l};a[v]=!0,U(s.prototype,"consumer",a)}})(r);else if(!e?.prototype&&!o?.prototype)return p.getConfig().sfDebug&&console.warn("[asyncQueues][kafkajs] No Kafka/Producer/Consumer class found — patch no-op."),"failed";return"installed"}function Re(n,t={}){const e=t.method??"ENQUEUE",o=t.library??"kafkajs";return async function(r){if(!r||!Array.isArray(r.messages))return n.call(this,r);const s=A(()=>{const u=r.topic,a=r.messages.map(()=>F({library:o,queueUri:he(u),method:e})),i=r.messages.map((c,f)=>Mt(c,a[f].traceId)),l={...r,messages:i};return{handles:a,outPayload:l}},`kafkajs.Producer.${e}`);if(s===null)return n.call(this,r);let d=null;try{return await n.call(this,s.outPayload)}catch(u){throw d=u instanceof Error?u:new Error(String(u)),u}finally{for(const u of s.handles)u.hopEnd(d)}}}function Me(n,t={}){const e=t.method??"ENQUEUE",o=t.library??"kafkajs";return async function(r){if(!r||!Array.isArray(r.topicMessages))return n.call(this,r);const s=A(()=>{const u=[],a=r.topicMessages.map(l=>{const c=l?.topic,f=(Array.isArray(l?.messages)?l.messages:[]).map(g=>{const m=F({library:o,queueUri:he(c),method:e});return u.push(m),Mt(g,m.traceId)});return{...l,messages:f}}),i={...r,topicMessages:a};return{handles:u,outPayload:i}},`kafkajs.Producer.sendBatch[${e}]`);if(s===null)return n.call(this,r);let d=null;try{return await n.call(this,s.outPayload)}catch(u){throw d=u instanceof Error?u:new Error(String(u)),u}finally{for(const u of s.handles)u.hopEnd(d)}}}function gt(n,t){return async function(...e){const o=F({queueUri:"kafka://broker/_tx",method:t});let r=null;try{return await n.apply(this,e)}catch(s){throw r=s instanceof Error?s:new Error(String(s)),s}finally{o.hopEnd(r)}}}function ht(n){return async function(...t){const e=await n.apply(this,t);return e&&typeof e.send=="function"&&!e.send[k]&&(e.send=Re(e.send.bind(e),{method:"ENQUEUE_TX",library:"kafkajs-tx"}),e.send[k]=!0),e&&typeof e.sendBatch=="function"&&!e.sendBatch[k]&&(e.sendBatch=Me(e.sendBatch.bind(e),{method:"ENQUEUE_TX",library:"kafkajs-tx"}),e.sendBatch[k]=!0),e&&typeof e.commit=="function"&&!e.commit[k]&&(e.commit=gt(e.commit.bind(e),"COMMIT_TX"),e.commit[k]=!0),e&&typeof e.abort=="function"&&!e.abort[k]&&(e.abort=gt(e.abort.bind(e),"ABORT_TX"),e.abort[k]=!0),e}}function Mt(n,t){const e={...n?.headers||{}};return e[te]=Buffer.from(t),{...n,headers:e}}function yt(n){return async function(t){if(!t||typeof t!="object")return n.call(this,t);const e={...t};if(typeof t.eachMessage=="function"){const o=t.eachMessage;e.eachMessage=r=>(async function(s,d){const u=s?.topic,a=s?.message,i=we(z(a?.headers)),l=typeof s?.attempt=="number"?s.attempt:0,c=i&&l>0?ee(i):i,f=we(a?.value)??a?.value;return x({library:"kafkajs",queueUri:he(u),incomingTraceId:c,messagePayload:f},()=>d(s))})(r,o)}if(typeof t.eachBatch=="function"){const o=t.eachBatch;e.eachBatch=r=>(async function(s,d){let u=!1;try{typeof s?.isStale=="function"&&(u=!!s.isStale())}catch{}if(u)return d(s);const a=s?.batch?.topic,i=Array.isArray(s?.batch?.messages)?s.batch.messages[0]:void 0,l=we(z(i?.headers));return x({library:"kafkajs",queueUri:he(a),incomingTraceId:l},()=>d(s))})(r,o)}return n.call(this,e)}}function _n(n){return process.env[n]==="true"}const wn=[{name:"bullmq",envDisableKey:"SF_DISABLE_BULLMQ",install:()=>mn()},{name:"@taskforcesh/bullmq-pro",envDisableKey:"SF_DISABLE_BULLMQ_PRO",install:()=>Sn()},{name:"kafkajs",envDisableKey:"SF_DISABLE_KAFKAJS",install:()=>En()},{name:"@confluentinc/kafka-javascript",envDisableKey:"SF_DISABLE_CONFLUENT_KAFKA_JS",install:()=>bn()}];let ue=!1;var mt,St;const xt=en(St?mt:(St=1,mt=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")})),bt="__sf_funcSpanCaptureRules";function ye(){const n=globalThis;let t=n[bt];return t||(t={compiledRulesById:new Map,bucket:new Map,propagationStorage:new zt.AsyncLocalStorage,randomFn:Math.random},n[bt]=t),t}const $n=/[*?[]/;function Cn(n,t){const e=[],o=new Set,r=s=>{const d=ne.normalize(s);o.has(d)||(o.add(d),e.push(d))};if(!$n.test(n)){if(ne.isAbsolute(n))return r(n),e;for(const s of t)r(ne.join(s,n));return e}for(const s of t){const d=ne.isAbsolute(n)?n:ne.join(s,n);try{const u=Ct.globSync(d,{absolute:!0,nodir:!0});for(const a of u)r(a)}catch{}}return e}const kn={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",STARTS_WITH:"starts_with",CONTAINS:"contains"};function Nn(n){return kn[n]??n}function Q(n){if(typeof n=="number")return Number.isFinite(n)?n:null;if(typeof n=="boolean")return n?1:0;if(typeof n=="string"){if(n.trim()==="")return null;const t=Number(n);return Number.isFinite(t)?t:null}return null}function le(n){if(n===null)return"None";if(n===void 0)return"undefined";try{return String(n)}catch{return""}}function Un(n,t,e){try{switch(n){case"==":{const o=Q(t),r=Q(e);return o!==null&&r!==null?o===r:le(t)===e}case"!=":{const o=Q(t),r=Q(e);return o!==null&&r!==null?o!==r:le(t)!==e}case"<":case"<=":case">":case">=":{const o=Q(t),r=Q(e);if(o===null||r===null)return!1;switch(n){case"<":return o<r;case"<=":return o<=r;case">":return o>r;case">=":return o>=r}return!1}case"starts_with":return le(t).startsWith(e);case"contains":return le(t).includes(e);default:return!1}}catch{return!1}}function Dn(n,t,e,o){if(n.length===0)return!0;const r=[];for(const s of n){const d=s[o],u=s.op,a=s.value??"";if(!d||!u){r.push(!1);continue}const i=Nn(u),l=t&&typeof t=="object"?t[d]:void 0;r.push(Un(i,l,a))}return e==="or"?r.some(Boolean):r.every(Boolean)}function vt(n,t){const e=[process.cwd()],o=new Map,r=new Map;for(const d of n??[]){let u,a;try{if(!d||typeof d!="object"||d.ruleId===void 0||d.ruleId===null||!d.target||typeof d.target!="object"||d.target.filePattern===void 0||d.target.filePattern===null||d.target.functionName===void 0||d.target.functionName===null)continue;const i=d.capture??{},l=d.conditions??{},c=d.propagate??{enabled:!1,maxDepth:5};u={ruleId:String(d.ruleId),functionName:String(d.target.functionName),capture:{args:i.args===void 0||!!i.args,returnValue:i.returnValue===void 0||!!i.returnValue,argLimitMb:Number(i.argLimitMb??1),returnLimitMb:Number(i.returnLimitMb??1)},preCall:Array.isArray(l.preCall)?l.preCall:[],postCall:Array.isArray(l.postCall)?l.postCall:[],logic:String(l.logic??"and").toLowerCase()==="or"?"or":"and",propagateEnabled:!!c.enabled,propagateMaxDepth:Number(c.maxDepth??5),sampleRate:d.sampleRate!==void 0?Number(d.sampleRate):1}}catch{continue}o.set(u.ruleId,u);try{a=String(d.target.filePattern)}catch{continue}for(const i of Cn(a,e)){const l=`${i}::${u.functionName}`,c=r.get(l);c?c.push(u.ruleId):r.set(l,[u.ruleId])}}const s=ye();s.compiledRulesById=o,s.bucket=r}function jt(){return ye().compiledRulesById.size>0}function Pn(n,t,e){const o=(function(){const a=ye(),i=a.propagationStorage.getStore(),l=i&&i.length>0?i:(function(){const f=globalThis;let g=f[It];return g||(g=[],f[It]=g),g})();if(l.length===0)return null;const c=l.length;for(let f=l.length-1;f>=0;f--){const g=l[f];if(c-g.pushDepth<=g.maxDepth)return g.captureConfig}return null})();if(o!==null)return o;const r=ye(),s=`${n}::${t}`,d=r.bucket.get(s);if(!d||d.length===0)return null;const u=e&&typeof e=="object"?e:{};for(const a of d){const i=r.compiledRulesById.get(a);if(i){try{if(!Dn(i.preCall,u,i.logic,"arg"))continue}catch{continue}if(i.sampleRate<1&&(i.sampleRate<=0||r.randomFn()>i.sampleRate))continue;return{ruleId:i.ruleId,captureArgs:i.capture.args,captureReturnValue:i.capture.returnValue,argLimitMb:i.capture.argLimitMb,returnLimitMb:i.capture.returnLimitMb,propagate:i.propagateEnabled,propagateMaxDepth:i.propagateMaxDepth,hasPostCallConditions:i.postCall.length>0}}}return null}const It="__sf_funcSpanCaptureRulesFallbackStack";let K=null,L=null,Y=null,oe=!1,X=1e3;function Fn(n,t){const e=K;if(e&&e.readyState===xt.OPEN)try{e.send(JSON.stringify({type:"sessionExpired",sessionId:n.sessionId,reason:t,spansEmitted:n.spansEmitted,bytesEmitted:String(n.bytesEmitted)}))}catch{}}function Tn(n,t){const e=t?.rules??[];if(!Array.isArray(e)||e.length===0)return vt([]),void(I.isActive()&&I.deactivate("cancelled"));if(I.activate(t)){vt(e);try{n.send(JSON.stringify({type:"rulesAck",sessionId:t.sessionId,rulesVersion:t.rulesVersion,podId:p.getConfig().serviceUUID}))}catch{}}}function qn(n,t){let e;try{e=JSON.parse(t)}catch{return}switch(e?.type){case"backendFunctionSpanRules":Tn(n,e);break;case"ping":(function(o,r){try{o.send(JSON.stringify({type:"pong",ts:r?.ts}))}catch{}})(n,e)}}function $e(){if(oe||L)return;const n=.2*X*(2*Math.random()-1),t=Math.min(3e4,Math.max(1e3,X+n));L=setTimeout(()=>{L=null,Ke()},t),typeof L.unref=="function"&&L.unref(),X=Math.min(3e4,1.5*X)}function Ke(){if(oe)return;if(!p.getConfig().serviceIdentifier)return L?void 0:(L=setTimeout(()=>{L=null,Ke()},1e3),void(typeof L.unref=="function"&&L.unref()));const n=(function(){const o=p.getConfig();if(o.uplinkUrl)return o.uplinkUrl;const r=o.apiGraphqlEndpoint;if(!r)return null;let s;try{s=new URL(r)}catch{return null}if(s.protocol==="https:")s.protocol="wss:";else{if(s.protocol!=="http:")return null;s.protocol="ws:"}return s.pathname="/ws/notify/",s.search="",s.toString()})();if(!n)return void $e();const t=`${n}?${(function(){const o=p.getConfig(),r=new URLSearchParams;return o.apiKey&&r.set("apiKey",o.apiKey),o.serviceUUID&&r.set("serviceUuid",o.serviceUUID),o.serviceIdentifier&&r.set("serviceIdentifier",o.serviceIdentifier),o.serviceVersion&&r.set("serviceVersion",o.serviceVersion),r.set("clientKind","backendCollector"),r.toString()})()}`;let e;try{e=new xt(t,{headers:{"X-Sf3-TelemetryOutbound":"True","User-Agent":`sf-veritas-jsts/${p.getConfig().version}`}})}catch{return void $e()}K=e,e.on("open",()=>{X=1e3;try{e.send(JSON.stringify({type:"clientHello",sdkVersion:p.getConfig().version,runtime:"jsts",pid:process.pid}))}catch{}}),e.on("message",o=>{try{const r=o.toString();qn(e,r)}catch{}}),e.on("close",()=>{K===e&&(K=null),oe||$e()}),e.on("error",o=>{})}function An(){if(oe=!0,I.isActive()&&I.deactivate("shutdown"),L&&(clearTimeout(L),L=null),Y&&(clearInterval(Y),Y=null),K){try{K.close()}catch{}K=null}}let Et=!1,Ce=!1,ke=!1;const ie=2048;let xe=new Array(ie),V=0,ge=0,Ne=!1;function Ht(n){for(let t=0;t<ie;t++)n[t]=kt.randomUUID()}function Ln(){if(V<ge){const n=xe[V];return V++,ge-V<256&&(Ne||(Ne=!0,setImmediate(()=>{const t=new Array(ie);Ht(t),xe=t,V=0,ge=ie,Ne=!1}))),n}return kt.randomUUID()}Ht(xe),ge=ie,V=0;const Ue=new Map,On=process.env.SF_FUNCSPAN_SKIP_BACKEND==="true",Bn=process.env.SF_FUNCSPAN_CONSOLE_OUTPUT==="true",R=process.env.SF_FUNCSPAN_JSONL_FILE,_t='{"type":"null","has_value":true,"value":null}';let De=null;const Kt=Object.freeze({}),Rn=globalThis;let wt=-1;function $t(n,t,e=Kt){const o=I.getFuncspanOverride();if(o){const a=I.parseHeaderOverride(o);if(a)return a}if(jt())try{const a=Pn(n,t,e);if(a!==null)return{capture_arguments:a.captureArgs,capture_return_value:a.captureReturnValue,arg_limit_mb:a.argLimitMb,return_limit_mb:a.returnLimitMb,autocapture_all_child_functions:a.propagate,sample_rate:1,enable_sampling:!1,capture_sf_veritas:!1,parse_json_strings:!1}}catch{}const r=Rn.__sf_configEpoch??0;r!==wt&&(Ue.clear(),wt=r);const s=n+"::"+t,d=Ue.get(s);if(d!==void 0)return d;let u;try{u=Pt(n,t)}catch{u={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}}return Ue.set(s,u),u}const b={functionName:"",filePath:"",metadata:{line:0,column:0,paramNames:[]},argsJson:"",returnValueJson:"",error:null,duration:0,durationNs:0,startTimeNs:"",async:!1,spanId:"",parentSpanId:null,pid:0,threadId:0,debug:!1};function de(n){const t=n.debug;t&&console.log("[FuncSpan] captureSpanData called for:",{function:n.functionName,file:n.filePath,duration:`${n.duration}ms`,async:n.async,error:n.error,spanId:n.spanId}),Bn&&console.log(`
189
+ `,e=g.getConfig(),o=this.getVariables({serviceIdentifier:e.serviceIdentifier,serviceVersion:e.serviceVersion,serviceAdditionalMetadata:e.serviceAdditionalMetadata,gitSha:e.gitSha||"",gitOrg:e.gitOrg||void 0,gitRepo:e.gitRepo||void 0,gitProvider:e.gitProvider||void 0,serviceDisplayName:e.serviceDisplayName||void 0,infrastructureType:e.infrastructureType||void 0,infrastructureDetails:e.infrastructureDetails||void 0,setupInterceptorsFile:e.setupInterceptorsFile||void 0,setupInterceptorsLine:e.setupInterceptorsLine||void 0,framework:e.framework||void 0,additionalFrameworks:e.additionalFrameworks?.length>0?e.additionalFrameworks:void 0,serviceRole:e.serviceRole||void 0});I.nonBlockingPost(this.endpoint,this.operationName,t,o)}}class ln{rootPaths;fileConfigs=new Map;functionConfigs=new Map;directoryConfigs=new Map;hasSailfishFiles=!1;runtimeModeEnabled=!1;debug;constructor(t=[process.cwd()],e=!1){this.rootPaths=t,this.debug=e||process.env.SF_DEBUG==="true"}async loadAllConfigs(){this.debug&&console.log("[FuncSpan ConfigLoader] Scanning for .sailfish files in:",this.rootPaths);const t=[];for(const e of this.rootPaths)Zt.existsSync(e)?await this._walkDirectory(e,t):this.debug&&console.log(`[FuncSpan ConfigLoader] Root path does not exist: ${e}`);t.length>0?(this.hasSailfishFiles=!0,this.debug&&(console.log(`[FuncSpan ConfigLoader] Found ${t.length} .sailfish files:`),t.forEach(e=>console.log(`[FuncSpan ConfigLoader] - ${e}`)))):this.debug&&console.log("[FuncSpan ConfigLoader] No .sailfish files found - function spans disabled by default");for(const e of t)await this._loadConfigFile(e);await this._resolveInheritance(),this.debug&&console.log(`[FuncSpan ConfigLoader] Loaded ${this.fileConfigs.size} file configs, ${this.functionConfigs.size} function configs`)}getConfig(t,e){const o=this.hasSailfishFiles?I.getEnvConfig():I.getDefaultConfig(),r=this._getDirectoryConfig(t),s=B.normalize(t),d=this.fileConfigs.get(s)||{};let u={};if(e){const a=this.functionConfigs.get(s);a&&(u=a.get(e)||{})}return I.mergeConfigs(o,r,d,u)}hasRuntimeMode(){return this.runtimeModeEnabled}async _walkDirectory(t,e){try{const o=await We.readdir(t,{withFileTypes:!0});for(const r of o){const s=B.join(t,r.name);r.isFile()&&r.name===".sailfish"?e.push(s):r.name==="node_modules"||r.isDirectory()&&r.name.startsWith(".")&&r.name!==".sailfish"||r.isDirectory()&&await this._walkDirectory(s,e)}}catch(o){this.debug&&console.error(`[FuncSpan ConfigLoader] Error walking directory ${t}:`,o)}}async _loadConfigFile(t){try{const e=await We.readFile(t,"utf-8"),o=B.dirname(t);let r=null;try{r=JSON.parse(e)}catch{try{r=require("toml").parse(e)}catch{try{r=require("js-yaml").load(e)}catch(s){return void(this.debug&&console.error(`[FuncSpan ConfigLoader] Failed to parse ${t} as JSON, TOML, or YAML:`,s))}}}if(!r)return;r.runtime_mode===!0&&(this.runtimeModeEnabled=!0,this.debug&&console.log(`[FuncSpan ConfigLoader] Runtime mode ENABLED in ${t}`)),r.default&&this.directoryConfigs.set(o,r.default),r.files&&await this._expandFileGlobs(o,r.files,r.default||{}),r.functions&&this._storeFunctionConfigs(o,r.functions,r.default||{}),this.debug&&(console.log(`[FuncSpan ConfigLoader] Loaded config from ${t}`),console.log(`[FuncSpan ConfigLoader] Directory: ${o}`),console.log(`[FuncSpan ConfigLoader] Has default: ${!!r.default}`),console.log(`[FuncSpan ConfigLoader] File patterns: ${Object.keys(r.files||{}).length}`),console.log(`[FuncSpan ConfigLoader] Functions: ${Object.keys(r.functions||{}).length}`))}catch(e){this.debug&&console.error(`[FuncSpan ConfigLoader] Error loading ${t}:`,e)}}async _expandFileGlobs(t,e,o){for(const[r,s]of Object.entries(e))try{const d=B.join(t,r),u=await kt.glob(d,{absolute:!0,nodir:!0,ignore:["**/node_modules/**","**/.git/**"]});this.debug&&console.log(`[FuncSpan ConfigLoader] Pattern '${r}' matched ${u.length} files`);for(const a of u){const i=B.normalize(a),c=I.mergeConfigs(o,s);this.fileConfigs.set(i,c),this.debug&&u.length<=5&&console.log(`[FuncSpan ConfigLoader] - ${a}`)}}catch(d){this.debug&&console.error(`[FuncSpan ConfigLoader] Error expanding glob '${r}':`,d)}}_storeFunctionConfigs(t,e,o){for(const[r,s]of Object.entries(e)){const d=r.split("::");if(d.length!==2){this.debug&&console.warn(`[FuncSpan ConfigLoader] Invalid function pattern '${r}' (expected format: 'file.ts::functionName')`);continue}const[u,a]=d,i=B.normalize(B.join(t,u));this.functionConfigs.has(i)||this.functionConfigs.set(i,new Map);const c=this.functionConfigs.get(i),l=I.mergeConfigs(o,s);c.set(a,l),this.debug&&console.log(`[FuncSpan ConfigLoader] Function config: ${i}::${a}`)}}async _resolveInheritance(){}_getDirectoryConfig(t){let e=B.dirname(B.normalize(t));const o=[];for(;e&&e!==B.dirname(e);){const r=this.directoryConfigs.get(e);r&&o.unshift(r),e=B.dirname(e)}return o.reduce((r,s)=>I.mergeConfigs(r,s),{})}}const Dt="__sf_globalConfigLoader";function Pt(){return globalThis[Dt]??null}async function Ze(n,t){const e=new ln(n,t);(function(r){globalThis[Dt]=r})(e),await e.loadAllConfigs();const o=globalThis;o.__sf_configEpoch=(o.__sf_configEpoch??0)+1}function Ft(n,t){const e=Pt();return e?e.getConfig(n,t):(process.env.SF_DEBUG==="true"&&console.log("[FuncSpan ConfigLoader] Config loader not initialized, using default config (disabled)"),I.getDefaultConfig())}function et(){return Pt()!==null}const dn=["readFile","writeFile","appendFile","readdir","stat","lstat","fstat","access","open","close","read","write","chmod","mkdir","rmdir","unlink","rename"],tt=["lookup","resolve","resolve4","resolve6","resolveAny","resolveMx","resolveNs","resolveTxt","reverse"],fn=["pbkdf2","randomBytes","scrypt","generateKeyPair"],pn=["gzip","gunzip","deflate","inflate","deflateRaw","inflateRaw","brotliCompress","brotliDecompress"];let nt=!1;function gn(n){if(typeof n!="string")return!1;const t=process.env.SF_FUNCSPAN_JSONL_FILE;if(t&&n.includes(t))return!0;const e=process.env.SF_WORKER_POOL_JSONL_FILE;return!(!e||!n.includes(e))}let rt=!1;function ot(n){if(typeof n!="string")return!1;if(n==="localhost"||n==="127.0.0.1"||n==="::1")return!0;try{const t=process.env.API_GRAPHQL_ENDPOINT;if(t&&n===new URL(t).hostname)return!0}catch{}return!1}function hn(){if(!rt)try{let n;if(typeof require>"u")return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Skipping dns patching in pure ESM environment (require unavailable)"));try{n=require("node:dns")}catch(t){return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Failed to require dns module:",t))}if(n.__sf_worker_pool_patched__)return;Object.defineProperty(n,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of tt)if(typeof n[t]=="function"){const e=n[t];n[t]=function(...o){return I.isSendingInternalTelemetry()?e.apply(this,o):ot(o[0])?e.apply(this,o):typeof o[o.length-1]=="function"?I.captureWorkerPoolOperation("dns",t,e,o,this):e.apply(this,o)},Object.defineProperty(n[t],"name",{value:t,writable:!1})}(function(t){if(!t.promises)return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises not available, skipping"));if(!t.promises.__sf_worker_pool_patched__){Object.defineProperty(t.promises,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of tt)if(typeof t.promises[e]=="function"){const o=t.promises[e];t.promises[e]=function(...r){return I.isSendingInternalTelemetry()?o.apply(this,r):ot(r[0])?o.apply(this,r):I.captureWorkerPoolPromiseOperation("dns",e,o,r,this)},Object.defineProperty(t.promises[e],"name",{value:e,writable:!1})}process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises module patched successfully")}})(n),rt=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns module patched successfully")}catch(n){console.error("[WorkerPool] Error patching dns module:",n)}}let it=!1,st=!1,Fe=!1;function at(){if(Fe)return;const n=process.env.SF_DEBUG==="true";n&&console.log("[WorkerPool] Initializing worker pool patching..."),I.isModuleTrackingEnabled("fs")&&(n&&console.log("[WorkerPool] Patching fs module..."),(function(){if(!nt)try{const t=require("node:fs");if(t.__sf_worker_pool_patched__)return;Object.defineProperty(t,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of dn)if(typeof t[e]=="function"){const o=t[e];t[e]=function(...r){return gn(r[0])?o.apply(this,r):typeof r[r.length-1]=="function"?I.captureWorkerPoolOperation("fs",e,o,r,this):o.apply(this,r)},Object.defineProperty(t[e],"name",{value:e,writable:!1})}nt=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] fs module patched successfully")}catch(t){console.error("[WorkerPool] Error patching fs module:",t)}})()),I.isModuleTrackingEnabled("dns")&&(n&&console.log("[WorkerPool] Patching dns module..."),hn()),I.isModuleTrackingEnabled("crypto")&&(n&&console.log("[WorkerPool] Patching crypto module..."),(function(){if(!it)try{const t=require("node:crypto");if(t.__sf_worker_pool_patched__)return;Object.defineProperty(t,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of fn)if(typeof t[e]=="function"){const o=t[e];t[e]=function(...r){return typeof r[r.length-1]=="function"?I.captureWorkerPoolOperation("crypto",e,o,r,this):o.apply(this,r)},Object.defineProperty(t[e],"name",{value:e,writable:!1})}it=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] crypto module patched successfully")}catch(t){console.error("[WorkerPool] Error patching crypto module:",t)}})()),I.isModuleTrackingEnabled("zlib")&&(n&&console.log("[WorkerPool] Patching zlib module..."),(function(){if(!st)try{const t=require("node:zlib");if(t.__sf_worker_pool_patched__)return;Object.defineProperty(t,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of pn)if(typeof t[e]=="function"){const o=t[e];t[e]=function(...r){return typeof r[r.length-1]=="function"?I.captureWorkerPoolOperation("zlib",e,o,r,this):o.apply(this,r)},Object.defineProperty(t[e],"name",{value:e,writable:!1})}st=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] zlib module patched successfully")}catch(t){console.error("[WorkerPool] Error patching zlib module:",t)}})()),Fe=!0,n&&console.log("[WorkerPool] Worker pool patching initialized")}function ct(){return Fe}const ut=te.toLowerCase();function z(n){if(n!=null){if(Array.isArray(n)){for(const t of n)if(!(!t||typeof t!="object")&&lt(t.key)===ut)return t.value}else if(typeof n=="object"){for(const[t,e]of Object.entries(n))if(lt(t)===ut)return Array.isArray(e)?e.length===0?void 0:e[0]:e}}}function lt(n){if(typeof n=="string")return n.toLowerCase();if(Buffer.isBuffer(n))try{return n.toString("utf8").toLowerCase()}catch{return null}if(n instanceof Uint8Array)try{return Buffer.from(n).toString("utf8").toLowerCase()}catch{return null}return null}let we=null;function Tt(){return we||(we=new Ut),we}function qt(n){if(!n)return null;const t=n.split("/").filter(Boolean);return t.length<3?null:{sessionId:t[0],pageVisitId:t[1],requestId:t[t.length-1]}}const yn=/^[A-Za-z0-9._:-]{1,128}$/;function Z(n){if(typeof n!="string"||n.length===0||n.length>1024)return!1;const t=n.split("/").filter(Boolean);if(t.length<3||t.length>6)return!1;for(const e of t)if(!yn.test(e))return!1;return!0}function ee(n){const t=n.split("/");return t.length>=3?(t[t.length-1]=g.v4(),t.join("/")):`${n}/${g.v4()}`}function mn(n){if(n==null)return null;if(typeof n=="string")return n;if(Buffer.isBuffer(n))try{return n.toString("utf8")}catch{return null}try{return JSON.stringify(Te(n))}catch{return null}}function Te(n,t=0){if(t>10)return"[truncated-depth]";if(n==null)return n;const e=typeof n;if(e==="string"||e==="number"||e==="boolean")return n;if(e==="bigint")return n.toString();if(e!=="object")return;if(Buffer.isBuffer(n))return`[Buffer ${n.length}b]`;if(ArrayBuffer.isView(n)){const r=n;return`[${r.constructor?.name??"TypedArray"} ${r.byteLength}b]`}if(n instanceof Date)try{return n.toISOString()}catch{return"[Date]"}if(n instanceof Map)return`[Map size=${n.size}]`;if(n instanceof Set)return`[Set size=${n.size}]`;if(Array.isArray(n))return n.map(r=>Te(r,t+1));const o={};for(const r of Object.getOwnPropertyNames(n)){const s=Object.getOwnPropertyDescriptor(n,r);s&&typeof s.get!="function"&&typeof s.set!="function"&&(o[r]=Te(s.value,t+1))}return o}function At(n){if(!n)return null;try{const t=n.message;if(typeof t=="string"&&t.length>0)return t}catch{}try{const t=String(n);if(typeof t=="string"&&t.length>0)return t}catch{}try{const t=n.name;if(typeof t=="string"&&t.length>0)return t}catch{}return"[unstringifiable error]"}function T(n){const t=g.ContextManager.getInstance().getOrSetSfTraceId(),e=ee(t),o=qt(e),r=Date.now(),s=g.getConfig(),d=n.queueUri,u=n.method??"ENQUEUE",a=Lt(n.messagePayload,s);return{traceId:e,hopEnd:i=>{try{if(!o)return;const c=Date.now();let l=null;try{l=g.getCurrentFunctionSpanId()??null}catch{}const f={apiKey:s.apiKey,requestId:o.requestId,pageVisitId:o.pageVisitId,recordingSessionId:o.sessionId,serviceUuid:s.serviceUUID??null,timestampStart:r.toString(),timestampEnd:c.toString(),responseCode:i?500:0,success:!i,error:At(i),url:d,method:u,parentSpanId:l};a!==null&&(f.requestBody=a),Ot(f);try{Tt().doSend(f)}catch(p){s.sfDebug&&console.warn("[asyncQueues] producer hop transmit failed:",p)}}catch{}}}}function Lt(n,t){if(!t.captureRequestBody||n===void 0)return null;const e=mn(n);return e?(function(o,r){return!r||r<=0?o:o.length>r?o.substring(0,r)+"...[truncated]":o})(e,t.requestBodyLimitBytes):null}function x(n,t){if(dt.getStore()===!0)return Promise.resolve(t());const e=g.ContextManager.getInstance(),o=g.getConfig(),r=n.incomingTraceId!==void 0&&Z(n.incomingTraceId)?n.incomingTraceId:`${g.NONSESSION_APPLOGS}-v3/${o.apiKey}/${g.v4()}`,s=n.queueUri,d=n.method,u=n.library,a=Lt(n.messagePayload,o);return dt.run(!0,()=>e.runScoped({traceId:r},async()=>{const i=Date.now();let c=null;try{const l=await Promise.resolve(t());return await(function(f){return f!==null&&typeof f=="object"&&typeof f.subscribe=="function"?new Promise((p,y)=>{let h,m=!1;try{f.subscribe({next:E=>{h=E,m=!0},error:E=>y(E),complete:()=>p(m?h:void 0)})}catch(E){y(E)}}):f})(l)}catch(l){throw c=l instanceof Error?l:new Error(String(l)),l}finally{(function(l,f,p,y,h,m){try{const E=qt(p);if(!E)return;const _=g.getConfig(),{graceful:b,tag:$}=(function(H){if(!H)return{graceful:!0,tag:null};let J;try{J=H.name}catch{return{graceful:!1,tag:null}}return J==="AbortError"?{graceful:!0,tag:"CONSUME_CANCELLED"}:J==="DelayedError"?{graceful:!0,tag:"CONSUME_RESCHEDULED"}:J==="WaitingChildrenError"?{graceful:!0,tag:"CONSUME_WAITING_CHILDREN"}:{graceful:!1,tag:null}})(m),w=!m&&l.method?l.method:$??l.method??"CONSUME",k=!m||b,P=m&&!b?500:0,C=m&&!b?At(m):null;let q=null;try{q=g.getCurrentFunctionSpanId()??null}catch{}const F={apiKey:_.apiKey,requestId:E.requestId,pageVisitId:E.pageVisitId,recordingSessionId:E.sessionId,serviceUuid:_.serviceUUID??null,timestampStart:y.toString(),timestampEnd:h.toString(),responseCode:P,success:k,error:C,url:l.queueUri,method:w,parentSpanId:q};f!==null&&(F.requestBody=f),Ot(F);try{Tt().doSend(F)}catch(H){_.sfDebug&&console.warn("[asyncQueues] consumer hop transmit failed:",H)}}catch{}})({library:u,queueUri:s,method:d},a,r,i,Date.now(),c)}}))}const dt=new zt.AsyncLocalStorage;let qe=null;function Ot(n){if(qe!==null)try{qe(n)}catch{}}const v=Symbol.for("sailfish.async-queues.patched"),N=Symbol.for("sailfish.async-queues.instance-wrapped"),Ae=[];function U(n,t,e){if(Ae.some(r=>r.proto===n&&r.key===t))return!1;const o=typeof n?.[t]=="function"?n[t]:void 0;try{return n[t]=e,Ae.push({proto:n,key:t,original:o}),!0}catch(r){if(g.getConfig().sfDebug){const s=n?.constructor?.name??"<unknown>";console.warn(`[asyncQueues] could not install patch on ${s}.prototype.${t} (frozen / non-writable?):`,r)}return!1}}function L(n,t){try{return n()}catch(e){return g.getConfig().sfDebug&&console.warn(`[asyncQueues] instrumentation rewrite threw in ${t} — falling back to original args, no hop emitted:`,e),null}}function A(n,t){let e=n||"unknown";if(typeof e=="string"){e.startsWith("bull:")&&(e=e.slice(5));const o=/^\{([^}]+)\}:(.+)$/.exec(e);o&&(e=`${o[1]}/${o[2]}`)}return`bullmq://redis/${e}/${t||"unknown"}`}function pe(n){return n?.queueQualifiedName??n?.queueName??n?.queue?.name??void 0}function M(n,t){const e=n?{...n}:{},o=e.sf&&typeof e.sf=="object"?e.sf:{};return e.sf={...o,rid:t},e}function Sn(n){let t=n;if(!t)try{t=require("bullmq")}catch{return"not-installed"}(function(a){try{const i=a?.version??a?.Queue?.version;if(typeof i!="string")return;parseInt(i.split(".")[0]??"0",10)<3&&g.getConfig().sfDebug&&console.warn(`[sf-veritas] BullMQ ${i} detected. Async-queue tracing is best-supported on BullMQ ≥ 3.0. Some APIs (FlowProducer, upsertJobScheduler, Job.promote) may be missing on older versions and will be skipped silently.`)}catch{}})(t);const e=t.Queue,o=t.Worker;if(!e?.prototype||!o?.prototype)return g.getConfig().sfDebug&&console.warn("[asyncQueues][bullmq] Expected Queue/Worker classes not found on module — skipping patch."),"failed";(function(a){const i=a.prototype.add;if(typeof i!="function"||i[v])return;const c=async function(l,f,p){if(p?.sf?.rid)return i.call(this,l,f,p);const y=L(()=>{const m=T({library:"bullmq",queueUri:A(this?.name,l),messagePayload:f});return{handle:m,nextOpts:M(p,m.traceId)}},"bullmq.Queue.add");if(y===null)return i.call(this,l,f,p);let h=null;try{return await i.call(this,l,f,y.nextOpts)}catch(m){throw h=m instanceof Error?m:new Error(String(m)),m}finally{y.handle.hopEnd(h)}};c[v]=!0,U(a.prototype,"add",c)})(e),(function(a){const i=a.prototype.addBulk;if(typeof i!="function"||i[v])return;const c=async function(l){if(!Array.isArray(l)||l.length===0)return i.call(this,l);if(l.every(h=>h?.opts?.sf?.rid))return i.call(this,l);const f=g.getConfig().bullmqBulkAggregateMode,p=L(()=>{if(f){const E=T({library:"bullmq",queueUri:A(this?.name,`__bulk_${l.length}`),method:"ENQUEUE_BULK",messagePayload:{batchSize:l.length}}),_=l.map(b=>({...b,opts:M(b?.opts,E.traceId)}));return{handles:[E],out:_}}const h=l.map(E=>T({library:"bullmq",queueUri:A(this?.name,E?.name),messagePayload:E?.data})),m=l.map((E,_)=>({...E,opts:M(E?.opts,h[_].traceId)}));return{handles:h,out:m}},"bullmq.Queue.addBulk");if(p===null)return i.call(this,l);let y=null;try{return await i.call(this,p.out)}catch(h){throw y=h instanceof Error?h:new Error(String(h)),h}finally{for(const h of p.handles)h.hopEnd(y)}};c[v]=!0,U(a.prototype,"addBulk",c)})(e),(function(a){const i=a.prototype.upsertJobScheduler;if(typeof i!="function"||i[v])return;const c=async function(l,f,p){const y=L(()=>{const m=T({library:"bullmq",queueUri:A(this?.name,p?.name??l),method:"ENQUEUE"});let E;if(p!==void 0){const _={...p,opts:M(p.opts,m.traceId)};E=[l,f,_]}else E=[l,f];return{handle:m,callArgs:E}},"bullmq.Queue.upsertJobScheduler");if(y===null){const m=p!==void 0?[l,f,p]:[l,f];return i.call(this,...m)}let h=null;try{return await i.call(this,...y.callArgs)}catch(m){throw h=m instanceof Error?m:new Error(String(m)),m}finally{y.handle.hopEnd(h)}};c[v]=!0,U(a.prototype,"upsertJobScheduler",c)})(e),(function(a){const i=a.prototype.getNextJob;if(typeof i!="function"||i[v])return;const c=async function(...l){const f=await i.apply(this,l);if(f&&Z(f.opts?.sf?.rid))try{g.ContextManager.getInstance().setTraceId(f.opts.sf.rid)}catch{}return f};c[v]=!0,U(a.prototype,"getNextJob",c)})(e),(function(a){const i=a.prototype.getJob;if(typeof i!="function"||i[v])return;const c=async function(...l){const f=await i.apply(this,l);if(f&&Z(f.opts?.sf?.rid))try{const y=g.ContextManager.getInstance();(!(p=y.getTraceId())||p.startsWith("nonsession-applogs-v3/"))&&y.setTraceId(f.opts.sf.rid)}catch{}var p;return f};c[v]=!0,U(a.prototype,"getJob",c)})(e),(function(a){const i=a.prototype.processJob;if(typeof i!="function"||i[v])return;const c=function(l,...f){const p=l?.opts?.sf?.rid,y=typeof l?.attemptsMade=="number"?l.attemptsMade:0,h=typeof l?.stalledCounter=="number"?l.stalledCounter:0,m=l?.repeatJobKey!=null||l?.opts?.repeat!=null,E=p&&(y>0||h>0||m)?ee(p):p;let _;return h>0?_="CONSUME_STALLED":m&&y===0&&(_="CONSUME_SCHEDULED"),x({library:"bullmq",queueUri:A(pe(l)??this?.name,l?.name),incomingTraceId:E,messagePayload:l?.data,method:_},()=>i.call(this,l,...f))};c[v]=!0,U(a.prototype,"processJob",c)})(o);const r=t.Job;r?.prototype&&(function(a){const i=["retry","moveToDelayed","promote"];for(const c of i){const l=a.prototype[c];if(typeof l!="function"||l[v])continue;const f=c==="promote"?"PROMOTE":c==="moveToDelayed"?"RESCHEDULE":"ENQUEUE_RETRY",p=async function(...y){const h=this?.opts?.sf?.rid;let m;if(h)m=ee(h);else{const b=T({queueUri:A(pe(this)??this?.name,this?.name),method:f});let $=null;try{return await l.apply(this,y)}catch(w){throw $=w instanceof Error?w:new Error(String(w)),w}finally{b.hopEnd($)}}this.opts&&(this.opts={...this.opts,sf:{...this.opts.sf||{},rid:m}});const E=T({queueUri:A(pe(this)??this?.name,this?.name),method:f});let _=null;try{return await l.apply(this,y)}catch(b){throw _=b instanceof Error?b:new Error(String(b)),b}finally{E.hopEnd(_)}};p[v]=!0,U(a.prototype,c,p)}})(r);const s=t.QueueEvents;s?.prototype&&(s.prototype[v]=!1);const d=t.FlowProducer;return d?.prototype&&((function(a){const i=a.prototype.add;if(typeof i!="function"||i[v])return;const c=async function(l,...f){if(!l||typeof l!="object")return i.call(this,l,...f);if(l?.opts?.sf?.rid)return i.call(this,l,...f);const p=L(()=>{const h=[];return{hops:h,out:Le(l,h)}},"bullmq.FlowProducer.add");if(p===null)return i.call(this,l,...f);let y=null;try{return await i.call(this,p.out,...f)}catch(h){throw y=h instanceof Error?h:new Error(String(h)),h}finally{for(const h of p.hops)h.hopEnd(y)}};c[v]=!0,U(a.prototype,"add",c)})(d),(function(a){const i=a.prototype.addBulk;if(typeof i!="function"||i[v])return;const c=async function(l){if(!Array.isArray(l)||l.length===0)return i.call(this,l);if(l.every(h=>h?.opts?.sf?.rid))return i.call(this,l);const f=g.getConfig().bullmqBulkAggregateMode,p=L(()=>{if(f){const E=w=>{let k=1;if(Array.isArray(w?.children))for(const P of w.children)k+=E(P);return k},_=l.reduce((w,k)=>w+E(k),0),b=T({library:"bullmq-flow",queueUri:A(l[0]?.queueName,`__flow_bulk_${l.length}`),method:"ENQUEUE_BULK",messagePayload:{batchSize:l.length,totalNodes:_}}),$=l.map(w=>Bt(w,b.traceId));return{hops:[b],out:$}}const h=[],m=l.map(E=>Le(E,h));return{hops:h,out:m}},"bullmq.FlowProducer.addBulk");if(p===null)return i.call(this,l);let y=null;try{return await i.call(this,p.out)}catch(h){throw y=h instanceof Error?h:new Error(String(h)),h}finally{for(const h of p.hops)h.hopEnd(y)}};c[v]=!0,U(a.prototype,"addBulk",c)})(d)),t.QueueScheduler?.prototype&&g.getConfig().sfDebug&&console.log("[sf-veritas] BullMQ QueueScheduler detected (v4 API). No direct instrumentation needed — delayed/repeatable jobs are traced when the Worker picks them up via the Worker.processJob wrap."),"installed"}function Le(n,t){const e=T({queueUri:A(n?.queueName,n?.name),messagePayload:n?.data});t.push(e);const o={...n,opts:M(n?.opts,e.traceId)};return Array.isArray(n?.children)&&n.children.length>0&&(o.children=n.children.map(r=>Le(r,t))),o}function Bt(n,t){const e={...n,opts:M(n?.opts,t)};return Array.isArray(n?.children)&&n.children.length>0&&(e.children=n.children.map(o=>Bt(o,t))),e}function bn(n){let t=n;if(!t)try{t=require("@taskforcesh/bullmq-pro")}catch{return"not-installed"}const e=t.QueuePro,o=t.WorkerPro;t.JobPro;const r=t.FlowProducerPro;return e?.prototype||o?.prototype?(e?.prototype&&((function(s){const d=s.prototype.add;if(typeof d!="function"||d[v])return;const u=async function(a,i,c){if(c?.sf?.rid)return d.call(this,a,i,c);const l=L(()=>{const p=T({library:"bullmq-pro",queueUri:A(this?.name,a),messagePayload:i});return{handle:p,nextOpts:M(c,p.traceId)}},"bullmq-pro.QueuePro.add");if(l===null)return d.call(this,a,i,c);let f=null;try{return await d.call(this,a,i,l.nextOpts)}catch(p){throw f=p instanceof Error?p:new Error(String(p)),p}finally{l.handle.hopEnd(f)}};u[v]=!0,U(s.prototype,"add",u)})(e),(function(s){const d=s.prototype.addBulk;if(typeof d!="function"||d[v])return;const u=async function(a){if(!Array.isArray(a)||a.length===0)return d.call(this,a);if(a.every(f=>f?.opts?.sf?.rid))return d.call(this,a);const i=g.getConfig().bullmqBulkAggregateMode,c=L(()=>{if(i){const y=T({library:"bullmq-pro",queueUri:A(this?.name,`__bulk_${a.length}`),method:"ENQUEUE_BULK",messagePayload:{batchSize:a.length}}),h=a.map(m=>({...m,opts:M(m?.opts,y.traceId)}));return{handles:[y],out:h}}const f=a.map(y=>T({library:"bullmq-pro",queueUri:A(this?.name,y?.name),messagePayload:y?.data})),p=a.map((y,h)=>({...y,opts:M(y?.opts,f[h].traceId)}));return{handles:f,out:p}},"bullmq-pro.QueuePro.addBulk");if(c===null)return d.call(this,a);let l=null;try{return await d.call(this,c.out)}catch(f){throw l=f instanceof Error?f:new Error(String(f)),f}finally{for(const f of c.handles)f.hopEnd(l)}};u[v]=!0,U(s.prototype,"addBulk",u)})(e)),o?.prototype&&((function(s){const d=s.prototype.processJob;typeof d!="function"||d[v]||ft(s,"processJob",d)})(o),(function(s){const d=s.prototype.getNextJob;if(typeof d!="function"||d[v])return;const u=async function(...a){const i=await d.apply(this,a);if(i&&Z(i.opts?.sf?.rid))try{const l=g.ContextManager.getInstance();(!(c=l.getTraceId())||c.startsWith("nonsession-applogs-v3/"))&&l.setTraceId(i.opts.sf.rid)}catch{}var c;return i};u[v]=!0,U(s.prototype,"getNextJob",u)})(o),typeof o.prototype.callProcessJob=="function"&&(function(s){const d=s.prototype.callProcessJob;typeof d!="function"||d[v]||ft(s,"callProcessJob",d)})(o)),r?.prototype&&(function(s){const d=s.prototype.add;if(typeof d!="function"||d[v])return;const u=async function(a,...i){if(!a||typeof a!="object")return d.call(this,a,...i);if(a?.opts?.sf?.rid)return d.call(this,a,...i);const c=L(()=>{const f=[];return{hops:f,out:Rt(a,f)}},"bullmq-pro.FlowProducerPro.add");if(c===null)return d.call(this,a,...i);let l=null;try{return await d.call(this,c.out,...i)}catch(f){throw l=f instanceof Error?f:new Error(String(f)),f}finally{for(const f of c.hops)f.hopEnd(l)}};u[v]=!0,U(s.prototype,"add",u)})(r),"installed"):(g.getConfig().sfDebug&&console.warn("[asyncQueues][bullmq-pro] No QueuePro/WorkerPro found — patch no-op."),"failed")}function ft(n,t,e){const o=function(r,...s){const d=r?.opts?.sf?.rid,u=typeof r?.attemptsMade=="number"?r.attemptsMade:0,a=typeof r?.stalledCounter=="number"?r.stalledCounter:0,i=r?.repeatJobKey!=null||r?.opts?.repeat!=null,c=Z(d)&&(u>0||a>0||i)?ee(d):Z(d)?d:void 0;let l;return a>0?l="CONSUME_STALLED":i&&u===0&&(l="CONSUME_SCHEDULED"),x({library:"bullmq-pro",queueUri:A(pe(r)??this?.name,r?.name),incomingTraceId:c,messagePayload:r?.data,method:l},()=>e.call(this,r,...s))};o[v]=!0,U(n.prototype,t,o)}function Rt(n,t,e=0){if(e>100)return n;const o=T({queueUri:A(n?.queueName,n?.name),messagePayload:n?.data});t.push(o);const r={...n,opts:M(n?.opts,o.traceId)};return Array.isArray(n?.children)&&n.children.length>0&&(r.children=n.children.map(s=>Rt(s,t,e+1))),r}const Oe=te.toLowerCase();function G(n){if(n!=null){if(typeof n=="string")return n;if(Buffer.isBuffer(n))try{return n.toString("utf8")}catch{return}if(n instanceof Uint8Array)try{return Buffer.from(n).toString("utf8")}catch{return}return String(n)}}function j(n,t="broker"){return`kafka://${t}/${n??"unknown"}`}function re(n){if(Array.isArray(n))for(const t of n){if(!t||typeof t!="object")continue;const e=t.key;if(typeof e=="string"&&e.toLowerCase()===Oe)return G(t.value)}}function Mt(n,t){const e=[];if(Array.isArray(n)){for(const o of n)if(o&&typeof o=="object"){const r=o.key,s=o.value;typeof r=="string"&&r.toLowerCase()===Oe||e.push({key:String(r),value:Buffer.isBuffer(s)?s:Buffer.from(String(s??""))})}}else if(n&&typeof n=="object")for(const[o,r]of Object.entries(n))o.toLowerCase()!==Oe&&e.push({key:o,value:Buffer.isBuffer(r)?r:Buffer.from(String(r??""))});return e.push({key:te,value:Buffer.from(t)}),e}function vn(n){let t=n;if(!t)try{t=require("@confluentinc/kafka-javascript")}catch{return"not-installed"}let e=!1;t.KafkaProducer?.prototype&&((function(r){const s=r.prototype.produce;if(typeof s!="function"||s[v])return;const d=function(...u){return u.length===1&&u[0]&&typeof u[0]=="object"&&Array.isArray(u[0].messages)?In.call(this,s,u[0]):En.call(this,s,u)};d[v]=!0,U(r.prototype,"produce",d)})(t.KafkaProducer),e=!0),t.KafkaConsumer?.prototype&&((function(r){const s=r.prototype.on;if(typeof s!="function"||s[v])return;const d=function(u,a){if(u!=="data"||typeof a!="function")return s.call(this,u,a);const i=function(c){const l=re(c?.headers),f=c?.topic,p=G(c?.value)??c?.value;return x({library:"confluent-kafka-js",queueUri:j(f),incomingTraceId:l,messagePayload:p},()=>a.call(this,c))};return s.call(this,u,i)};d[v]=!0,U(r.prototype,"on",d)})(t.KafkaConsumer),e=!0);const o=t.KafkaJS??t;return o?.Producer?.prototype?.send&&((function(r){const s=r.prototype.send;if(typeof s=="function"&&!s[v]){const a=Be(s);a[v]=!0,U(r.prototype,"send",a)}const d=r.prototype.sendBatch;if(typeof d=="function"&&!d[v]){const a=Re(d);a[v]=!0,U(r.prototype,"sendBatch",a)}const u=r.prototype.transaction;if(typeof u=="function"&&!u[v]){const a=gt(u);a[v]=!0,U(r.prototype,"transaction",a)}})(o.Producer),e=!0),o?.Consumer?.prototype?.run&&((function(r){const s=r.prototype.run;if(typeof s!="function"||s[v])return;const d=async function(u){if(!u||typeof u!="object")return s.call(this,u);const a={...u};if(typeof u.eachMessage=="function"){const i=u.eachMessage;a.eachMessage=c=>{const l=G(z(c?.message?.headers))??re(c?.message?.headers),f=typeof c?.attempt=="number"?c.attempt:0,p=l&&f>0?ee(l):l;return x({library:"confluent-kafka-js",queueUri:j(c?.topic),incomingTraceId:p},()=>i(c))}}if(typeof u.eachBatch=="function"){const i=u.eachBatch;a.eachBatch=c=>{let l=!1;try{typeof c?.isStale=="function"&&(l=!!c.isStale())}catch{}if(l)return i(c);const f=Array.isArray(c?.batch?.messages)?c.batch.messages[0]:void 0,p=G(z(f?.headers))??re(f?.headers);return x({library:"confluent-kafka-js",queueUri:j(c?.batch?.topic),incomingTraceId:p},()=>i(c))}}return s.call(this,a)};d[v]=!0,U(r.prototype,"run",d)})(o.Consumer),e=!0),typeof o?.Kafka=="function"&&o.Kafka.prototype&&((function(r){const s=r.prototype.producer;if(typeof s=="function"&&!s[v]){const u=function(...a){const i=s.apply(this,a);return i&&typeof i.send=="function"&&!i.send[N]&&(i.send=Be(i.send.bind(i)),i.send[N]=!0),i&&typeof i.sendBatch=="function"&&!i.sendBatch[N]&&(i.sendBatch=Re(i.sendBatch.bind(i)),i.sendBatch[N]=!0),i&&typeof i.transaction=="function"&&!i.transaction[N]&&(i.transaction=gt(i.transaction.bind(i)),i.transaction[N]=!0),i};u[v]=!0,U(r.prototype,"producer",u)}const d=r.prototype.consumer;if(typeof d=="function"&&!d[v]){const u=function(...a){const i=d.apply(this,a);if(i&&typeof i.run=="function"&&!i.run[N]){const c=i.run.bind(i);i.run=async function(l){if(!l||typeof l!="object")return c(l);const f={...l};if(typeof l.eachMessage=="function"){const p=l.eachMessage;f.eachMessage=y=>{const h=G(z(y?.message?.headers))??re(y?.message?.headers);return x({library:"confluent-kafka-js",queueUri:j(y?.topic),incomingTraceId:h},()=>p(y))}}if(typeof l.eachBatch=="function"){const p=l.eachBatch;f.eachBatch=y=>{let h=!1;try{typeof y?.isStale=="function"&&(h=!!y.isStale())}catch{}if(h)return p(y);const m=Array.isArray(y?.batch?.messages)?y.batch.messages[0]:void 0,E=G(z(m?.headers))??re(m?.headers);return x({library:"confluent-kafka-js",queueUri:j(y?.batch?.topic),incomingTraceId:E},()=>p(y))}}return c(f)},i.run[N]=!0}return i};u[v]=!0,U(r.prototype,"consumer",u)}})(o.Kafka),e=!0),e?"installed":(g.getConfig().sfDebug&&console.warn("[asyncQueues][confluentKafkaJs] No recognizable Producer/Consumer/Kafka class — patch no-op."),"failed")}function In(n,t){const e=L(()=>{const r=t?.topic,s=t.messages.map(()=>T({library:"confluent-kafka-js",queueUri:j(r),method:"ENQUEUE_BUFFERED"})),d=t.messages.map((u,a)=>({...u,headers:Mt(u?.headers,s[a].traceId)}));return{handles:s,outOptions:{...t,messages:d}}},"confluentKafkaJs.KafkaProducer.produce(object)");if(e===null)return n.call(this,t);let o=null;try{return n.call(this,e.outOptions)}catch(r){throw o=r instanceof Error?r:new Error(String(r)),r}finally{for(const r of e.handles)r.hopEnd(o)}}function En(n,t){const[e,o,r,s,d,u,a]=t,i=L(()=>{const l=T({library:"confluent-kafka-js",queueUri:j(typeof e=="string"?e:void 0),method:"ENQUEUE_BUFFERED"});return{handle:l,injectedHeaders:Mt(a,l.traceId)}},"confluentKafkaJs.KafkaProducer.produce(positional)");if(i===null)return n.call(this,e,o,r,s,d,u,a);let c=null;try{return n.call(this,e,o,r,s,d,u,i.injectedHeaders)}catch(l){throw c=l instanceof Error?l:new Error(String(l)),l}finally{i.handle.hopEnd(c)}}function Be(n,t={}){const e=t.method??"ENQUEUE",o=t.library??"confluent-kafka-js";return async function(r){if(!r||!Array.isArray(r.messages))return n.call(this,r);const s=L(()=>{const u=r.messages.map(()=>T({library:o,queueUri:j(r.topic),method:e})),a=r.messages.map((i,c)=>({...i,headers:{...i?.headers||{},[te]:Buffer.from(u[c].traceId)}}));return{handles:u,outPayload:{...r,messages:a}}},`confluentKafkaJs.Producer.${e}`);if(s===null)return n.call(this,r);let d=null;try{return await n.call(this,s.outPayload)}catch(u){throw d=u instanceof Error?u:new Error(String(u)),u}finally{for(const u of s.handles)u.hopEnd(d)}}}function Re(n,t={}){const e=t.method??"ENQUEUE",o=t.library??"confluent-kafka-js";return async function(r){if(!r||!Array.isArray(r.topicMessages))return n.call(this,r);const s=L(()=>{const u=[],a=r.topicMessages.map(i=>{const c=(Array.isArray(i?.messages)?i.messages:[]).map(l=>{const f=T({library:o,queueUri:j(i?.topic),method:e});return u.push(f),{...l,headers:{...l?.headers||{},[te]:Buffer.from(f.traceId)}}});return{...i,messages:c}});return{handles:u,outPayload:{...r,topicMessages:a}}},`confluentKafkaJs.Producer.sendBatch[${e}]`);if(s===null)return n.call(this,r);let d=null;try{return await n.call(this,s.outPayload)}catch(u){throw d=u instanceof Error?u:new Error(String(u)),u}finally{for(const u of s.handles)u.hopEnd(d)}}}function pt(n,t){return async function(...e){const o=T({queueUri:"kafka://broker/_tx",method:t});let r=null;try{return await n.apply(this,e)}catch(s){throw r=s instanceof Error?s:new Error(String(s)),s}finally{o.hopEnd(r)}}}function gt(n){return async function(...t){const e=await n.apply(this,t);return e&&typeof e.send=="function"&&!e.send[N]&&(e.send=Be(e.send.bind(e),{method:"ENQUEUE_TX",library:"confluent-kafka-js-tx"}),e.send[N]=!0),e&&typeof e.sendBatch=="function"&&!e.sendBatch[N]&&(e.sendBatch=Re(e.sendBatch.bind(e),{method:"ENQUEUE_TX",library:"confluent-kafka-js-tx"}),e.sendBatch[N]=!0),e&&typeof e.commit=="function"&&!e.commit[N]&&(e.commit=pt(e.commit.bind(e),"COMMIT_TX"),e.commit[N]=!0),e&&typeof e.abort=="function"&&!e.abort[N]&&(e.abort=pt(e.abort.bind(e),"ABORT_TX"),e.abort[N]=!0),e}}function Ce(n){if(n!=null){if(typeof n=="string")return n;if(Buffer.isBuffer(n))try{return n.toString("utf8")}catch{return}if(n instanceof Uint8Array)try{return Buffer.from(n).toString("utf8")}catch{return}return String(n)}}function he(n,t){return`kafka://broker/${n??"unknown"}`}function _n(n){let t=n;if(!t)try{t=require("kafkajs")}catch{return"not-installed"}const e=t.Producer,o=t.Consumer;e?.prototype&&typeof e.prototype.send=="function"&&(function(s){const d=s.prototype.send;if(typeof d=="function"&&!d[v]){const i=Me(d);i[v]=!0,U(s.prototype,"send",i)}const u=s.prototype.sendBatch;if(typeof u=="function"&&!u[v]){const i=xe(u);i[v]=!0,U(s.prototype,"sendBatch",i)}const a=s.prototype.transaction;if(typeof a=="function"&&!a[v]){const i=yt(a);i[v]=!0,U(s.prototype,"transaction",i)}})(e),o?.prototype&&typeof o.prototype.run=="function"&&(function(s){const d=s.prototype.run;if(typeof d!="function"||d[v])return;const u=mt(d);u[v]=!0,U(s.prototype,"run",u)})(o);const r=t.Kafka;if(typeof r=="function"&&r.prototype)(function(s){const d=s.prototype.producer;if(typeof d=="function"&&!d[v]){const a=function(...i){const c=d.apply(this,i);return c&&typeof c.send=="function"&&!c.send[N]&&(c.send=Me(c.send.bind(c)),c.send[N]=!0),c&&typeof c.sendBatch=="function"&&!c.sendBatch[N]&&(c.sendBatch=xe(c.sendBatch.bind(c)),c.sendBatch[N]=!0),c&&typeof c.transaction=="function"&&!c.transaction[N]&&(c.transaction=yt(c.transaction.bind(c)),c.transaction[N]=!0),c};a[v]=!0,U(s.prototype,"producer",a)}const u=s.prototype.consumer;if(typeof u=="function"&&!u[v]){const a=function(...i){const c=u.apply(this,i);return c&&typeof c.run=="function"&&!c.run[N]&&(c.run=mt(c.run.bind(c)),c.run[N]=!0),c};a[v]=!0,U(s.prototype,"consumer",a)}})(r);else if(!e?.prototype&&!o?.prototype)return g.getConfig().sfDebug&&console.warn("[asyncQueues][kafkajs] No Kafka/Producer/Consumer class found — patch no-op."),"failed";return"installed"}function Me(n,t={}){const e=t.method??"ENQUEUE",o=t.library??"kafkajs";return async function(r){if(!r||!Array.isArray(r.messages))return n.call(this,r);const s=L(()=>{const u=r.topic,a=r.messages.map(()=>T({library:o,queueUri:he(u),method:e})),i=r.messages.map((l,f)=>xt(l,a[f].traceId)),c={...r,messages:i};return{handles:a,outPayload:c}},`kafkajs.Producer.${e}`);if(s===null)return n.call(this,r);let d=null;try{return await n.call(this,s.outPayload)}catch(u){throw d=u instanceof Error?u:new Error(String(u)),u}finally{for(const u of s.handles)u.hopEnd(d)}}}function xe(n,t={}){const e=t.method??"ENQUEUE",o=t.library??"kafkajs";return async function(r){if(!r||!Array.isArray(r.topicMessages))return n.call(this,r);const s=L(()=>{const u=[],a=r.topicMessages.map(c=>{const l=c?.topic,f=(Array.isArray(c?.messages)?c.messages:[]).map(p=>{const y=T({library:o,queueUri:he(l),method:e});return u.push(y),xt(p,y.traceId)});return{...c,messages:f}}),i={...r,topicMessages:a};return{handles:u,outPayload:i}},`kafkajs.Producer.sendBatch[${e}]`);if(s===null)return n.call(this,r);let d=null;try{return await n.call(this,s.outPayload)}catch(u){throw d=u instanceof Error?u:new Error(String(u)),u}finally{for(const u of s.handles)u.hopEnd(d)}}}function ht(n,t){return async function(...e){const o=T({queueUri:"kafka://broker/_tx",method:t});let r=null;try{return await n.apply(this,e)}catch(s){throw r=s instanceof Error?s:new Error(String(s)),s}finally{o.hopEnd(r)}}}function yt(n){return async function(...t){const e=await n.apply(this,t);return e&&typeof e.send=="function"&&!e.send[N]&&(e.send=Me(e.send.bind(e),{method:"ENQUEUE_TX",library:"kafkajs-tx"}),e.send[N]=!0),e&&typeof e.sendBatch=="function"&&!e.sendBatch[N]&&(e.sendBatch=xe(e.sendBatch.bind(e),{method:"ENQUEUE_TX",library:"kafkajs-tx"}),e.sendBatch[N]=!0),e&&typeof e.commit=="function"&&!e.commit[N]&&(e.commit=ht(e.commit.bind(e),"COMMIT_TX"),e.commit[N]=!0),e&&typeof e.abort=="function"&&!e.abort[N]&&(e.abort=ht(e.abort.bind(e),"ABORT_TX"),e.abort[N]=!0),e}}function xt(n,t){const e={...n?.headers||{}};return e[te]=Buffer.from(t),{...n,headers:e}}function mt(n){return async function(t){if(!t||typeof t!="object")return n.call(this,t);const e={...t};if(typeof t.eachMessage=="function"){const o=t.eachMessage;e.eachMessage=r=>(async function(s,d){const u=s?.topic,a=s?.message,i=Ce(z(a?.headers)),c=typeof s?.attempt=="number"?s.attempt:0,l=i&&c>0?ee(i):i,f=Ce(a?.value)??a?.value;return x({library:"kafkajs",queueUri:he(u),incomingTraceId:l,messagePayload:f},()=>d(s))})(r,o)}if(typeof t.eachBatch=="function"){const o=t.eachBatch;e.eachBatch=r=>(async function(s,d){let u=!1;try{typeof s?.isStale=="function"&&(u=!!s.isStale())}catch{}if(u)return d(s);const a=s?.batch?.topic,i=Array.isArray(s?.batch?.messages)?s.batch.messages[0]:void 0,c=Ce(z(i?.headers));return x({library:"kafkajs",queueUri:he(a),incomingTraceId:c},()=>d(s))})(r,o)}return n.call(this,e)}}function wn(n){return process.env[n]==="true"}const Cn=[{name:"bullmq",envDisableKey:"SF_DISABLE_BULLMQ",install:()=>Sn()},{name:"@taskforcesh/bullmq-pro",envDisableKey:"SF_DISABLE_BULLMQ_PRO",install:()=>bn()},{name:"kafkajs",envDisableKey:"SF_DISABLE_KAFKAJS",install:()=>_n()},{name:"@confluentinc/kafka-javascript",envDisableKey:"SF_DISABLE_CONFLUENT_KAFKA_JS",install:()=>vn()}];let ue=!1;var St,bt;const jt=tn(bt?St:(bt=1,St=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")})),vt="__sf_funcSpanCaptureRules";function ye(){const n=globalThis;let t=n[vt];return t||(t={compiledRulesById:new Map,bucket:new Map,propagationStorage:new Xt.AsyncLocalStorage,randomFn:Math.random},n[vt]=t),t}const $n=/[*?[]/;function kn(n,t){const e=[],o=new Set,r=s=>{const d=ne.normalize(s);o.has(d)||(o.add(d),e.push(d))};if(!$n.test(n)){if(ne.isAbsolute(n))return r(n),e;for(const s of t)r(ne.join(s,n));return e}for(const s of t){const d=ne.isAbsolute(n)?n:ne.join(s,n);try{const u=kt.globSync(d,{absolute:!0,nodir:!0});for(const a of u)r(a)}catch{}}return e}const Nn={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",STARTS_WITH:"starts_with",CONTAINS:"contains"};function Un(n){return Nn[n]??n}function Q(n){if(typeof n=="number")return Number.isFinite(n)?n:null;if(typeof n=="boolean")return n?1:0;if(typeof n=="string"){if(n.trim()==="")return null;const t=Number(n);return Number.isFinite(t)?t:null}return null}function le(n){if(n===null)return"None";if(n===void 0)return"undefined";try{return String(n)}catch{return""}}function Dn(n,t,e){try{switch(n){case"==":{const o=Q(t),r=Q(e);return o!==null&&r!==null?o===r:le(t)===e}case"!=":{const o=Q(t),r=Q(e);return o!==null&&r!==null?o!==r:le(t)!==e}case"<":case"<=":case">":case">=":{const o=Q(t),r=Q(e);if(o===null||r===null)return!1;switch(n){case"<":return o<r;case"<=":return o<=r;case">":return o>r;case">=":return o>=r}return!1}case"starts_with":return le(t).startsWith(e);case"contains":return le(t).includes(e);default:return!1}}catch{return!1}}function Pn(n,t,e,o){if(n.length===0)return!0;const r=[];for(const s of n){const d=s[o],u=s.op,a=s.value??"";if(!d||!u){r.push(!1);continue}const i=Un(u),c=t&&typeof t=="object"?t[d]:void 0;r.push(Dn(i,c,a))}return e==="or"?r.some(Boolean):r.every(Boolean)}function It(n,t){const e=[process.cwd()],o=new Map,r=new Map;for(const d of n??[]){let u,a;try{if(!d||typeof d!="object"||d.ruleId===void 0||d.ruleId===null||!d.target||typeof d.target!="object"||d.target.filePattern===void 0||d.target.filePattern===null||d.target.functionName===void 0||d.target.functionName===null)continue;const i=d.capture??{},c=d.conditions??{},l=d.propagate??{enabled:!1,maxDepth:5};u={ruleId:String(d.ruleId),functionName:String(d.target.functionName),capture:{args:i.args===void 0||!!i.args,returnValue:i.returnValue===void 0||!!i.returnValue,argLimitMb:Number(i.argLimitMb??1),returnLimitMb:Number(i.returnLimitMb??1)},preCall:Array.isArray(c.preCall)?c.preCall:[],postCall:Array.isArray(c.postCall)?c.postCall:[],logic:String(c.logic??"and").toLowerCase()==="or"?"or":"and",propagateEnabled:!!l.enabled,propagateMaxDepth:Number(l.maxDepth??5),sampleRate:d.sampleRate!==void 0?Number(d.sampleRate):1}}catch{continue}o.set(u.ruleId,u);try{a=String(d.target.filePattern)}catch{continue}for(const i of kn(a,e)){const c=`${i}::${u.functionName}`,l=r.get(c);l?l.push(u.ruleId):r.set(c,[u.ruleId])}}const s=ye();s.compiledRulesById=o,s.bucket=r}function Ht(){return ye().compiledRulesById.size>0}function Fn(n,t,e){const o=(function(){const a=ye(),i=a.propagationStorage.getStore(),c=i&&i.length>0?i:(function(){const f=globalThis;let p=f[Et];return p||(p=[],f[Et]=p),p})();if(c.length===0)return null;const l=c.length;for(let f=c.length-1;f>=0;f--){const p=c[f];if(l-p.pushDepth<=p.maxDepth)return p.captureConfig}return null})();if(o!==null)return o;const r=ye(),s=`${n}::${t}`,d=r.bucket.get(s);if(!d||d.length===0)return null;const u=e&&typeof e=="object"?e:{};for(const a of d){const i=r.compiledRulesById.get(a);if(i){try{if(!Pn(i.preCall,u,i.logic,"arg"))continue}catch{continue}if(i.sampleRate<1&&(i.sampleRate<=0||r.randomFn()>i.sampleRate))continue;return{ruleId:i.ruleId,captureArgs:i.capture.args,captureReturnValue:i.capture.returnValue,argLimitMb:i.capture.argLimitMb,returnLimitMb:i.capture.returnLimitMb,propagate:i.propagateEnabled,propagateMaxDepth:i.propagateMaxDepth,hasPostCallConditions:i.postCall.length>0}}}return null}const Et="__sf_funcSpanCaptureRulesFallbackStack";let K=null,O=null,Y=null,oe=!1,X=1e3;function Tn(n,t){const e=K;if(e&&e.readyState===jt.OPEN)try{e.send(JSON.stringify({type:"sessionExpired",sessionId:n.sessionId,reason:t,spansEmitted:n.spansEmitted,bytesEmitted:String(n.bytesEmitted)}))}catch{}}function qn(n,t){const e=t?.rules??[];if(!Array.isArray(e)||e.length===0)return It([]),void(I.isActive()&&I.deactivate("cancelled"));if(I.activate(t)){It(e);try{n.send(JSON.stringify({type:"rulesAck",sessionId:t.sessionId,rulesVersion:t.rulesVersion,podId:g.getConfig().serviceUUID}))}catch{}}}function An(n,t){let e;try{e=JSON.parse(t)}catch{return}switch(e?.type){case"backendFunctionSpanRules":qn(n,e);break;case"ping":(function(o,r){try{o.send(JSON.stringify({type:"pong",ts:r?.ts}))}catch{}})(n,e)}}function $e(){if(oe||O)return;const n=.2*X*(2*Math.random()-1),t=Math.min(3e4,Math.max(1e3,X+n));O=setTimeout(()=>{O=null,Je()},t),typeof O.unref=="function"&&O.unref(),X=Math.min(3e4,1.5*X)}function Je(){if(oe)return;if(!g.getConfig().serviceIdentifier)return O?void 0:(O=setTimeout(()=>{O=null,Je()},1e3),void(typeof O.unref=="function"&&O.unref()));const n=(function(){const o=g.getConfig();if(o.uplinkUrl)return o.uplinkUrl;const r=o.apiGraphqlEndpoint;if(!r)return null;let s;try{s=new URL(r)}catch{return null}if(s.protocol==="https:")s.protocol="wss:";else{if(s.protocol!=="http:")return null;s.protocol="ws:"}return s.pathname="/ws/notify/",s.search="",s.toString()})();if(!n)return void $e();const t=`${n}?${(function(){const o=g.getConfig(),r=new URLSearchParams;return o.apiKey&&r.set("apiKey",o.apiKey),o.serviceUUID&&r.set("serviceUuid",o.serviceUUID),o.serviceIdentifier&&r.set("serviceIdentifier",o.serviceIdentifier),o.serviceVersion&&r.set("serviceVersion",o.serviceVersion),r.set("clientKind","backendCollector"),r.toString()})()}`;let e;try{e=new jt(t,{headers:{"X-Sf3-TelemetryOutbound":"True","User-Agent":`sf-veritas-jsts/${g.getConfig().version}`}})}catch{return void $e()}K=e,e.on("open",()=>{X=1e3;try{e.send(JSON.stringify({type:"clientHello",sdkVersion:g.getConfig().version,runtime:"jsts",pid:process.pid}))}catch{}}),e.on("message",o=>{try{const r=o.toString();An(e,r)}catch{}}),e.on("close",()=>{K===e&&(K=null),oe||$e()}),e.on("error",o=>{})}function Ln(){if(oe=!0,I.isActive()&&I.deactivate("shutdown"),O&&(clearTimeout(O),O=null),Y&&(clearInterval(Y),Y=null),K){try{K.close()}catch{}K=null}}let _t=!1,ke=!1,Ne=!1;const ie=2048;let je=new Array(ie),V=0,ge=0,Ue=!1;function Kt(n){for(let t=0;t<ie;t++)n[t]=Nt.randomUUID()}function On(){if(V<ge){const n=je[V];return V++,ge-V<256&&(Ue||(Ue=!0,setImmediate(()=>{const t=new Array(ie);Kt(t),je=t,V=0,ge=ie,Ue=!1}))),n}return Nt.randomUUID()}Kt(je),ge=ie,V=0;const De=new Map,Bn=process.env.SF_FUNCSPAN_SKIP_BACKEND==="true",Rn=process.env.SF_FUNCSPAN_CONSOLE_OUTPUT==="true",R=process.env.SF_FUNCSPAN_JSONL_FILE,wt='{"type":"null","has_value":true,"value":null}';let Pe=null;const Jt=Object.freeze({}),Mn=globalThis;let Ct=-1;function $t(n,t,e=Jt){const o=I.getFuncspanOverride();if(o){const a=I.parseHeaderOverride(o);if(a)return a}if(Ht())try{const a=Fn(n,t,e);if(a!==null)return{capture_arguments:a.captureArgs,capture_return_value:a.captureReturnValue,arg_limit_mb:a.argLimitMb,return_limit_mb:a.returnLimitMb,autocapture_all_child_functions:a.propagate,sample_rate:1,enable_sampling:!1,capture_sf_veritas:!1,parse_json_strings:!1}}catch{}const r=Mn.__sf_configEpoch??0;r!==Ct&&(De.clear(),Ct=r);const s=n+"::"+t,d=De.get(s);if(d!==void 0)return d;let u;try{u=Ft(n,t)}catch{u={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}}return De.set(s,u),u}const S={functionName:"",filePath:"",metadata:{line:0,column:0,paramNames:[]},argsJson:"",returnValueJson:"",error:null,duration:0,durationNs:0,startTimeNs:"",async:!1,spanId:"",parentSpanId:null,pid:0,threadId:0,debug:!1};function de(n){const t=n.debug;t&&console.log("[FuncSpan] captureSpanData called for:",{function:n.functionName,file:n.filePath,duration:`${n.duration}ms`,async:n.async,error:n.error,spanId:n.spanId}),Rn&&console.log(`
190
190
  📊 Function Span:`,{function:`${n.functionName} (${n.filePath}:${n.metadata.line}:${n.metadata.column})`,duration:`${n.duration.toFixed(2)}ms`,arguments:JSON.parse(n.argsJson),result:n.error?`Error: ${n.error}`:JSON.parse(n.returnValueJson),spanId:n.spanId,parentSpanId:n.parentSpanId||"none"});const e=R;if(e)try{const o=e==="true"||e==="1"?"funcspans.jsonl":e,r=Date.now(),s=process.hrtime.bigint(),d=BigInt(n.startTimeNs),u=Number(s-d)/1e6,a=new Date(r-u).toISOString(),i=JSON.stringify({timestamp:a,functionName:n.functionName,filePath:n.filePath,line:n.metadata.line,column:n.metadata.column,duration:n.duration,durationNs:n.durationNs,startTimeNs:n.startTimeNs,arguments:JSON.parse(n.argsJson),returnValue:n.error?{error:String(n.error)}:JSON.parse(n.returnValueJson).value,spanId:n.spanId,parentSpanId:n.parentSpanId,async:n.async,pid:n.pid,threadId:n.threadId})+`
191
- `;je.appendFileSync(o,i,"utf-8")}catch(o){console.error("[FuncSpan] Error writing to JSONL file:",o)}if(t&&console.log("[FuncSpan] Sending function span to transmitter:",n),!On)try{(De||(De=new I.FunctionSpanTransmitter),De).sendOne(n),t&&console.log("[FuncSpan] Function span sent successfully")}catch(o){t&&console.error("[FuncSpan] Error sending function span:",o)}}exports.ContextManager=p.ContextManager,exports.getCurrentFunctionSpanId=p.getCurrentFunctionSpanId,exports.runWithContext=p.runWithContext,exports.clearFuncspanOverride=I.clearFuncspanOverride,exports.getDefaultConfig=I.getDefaultConfig,exports.getEnvConfig=I.getEnvConfig,exports.getFuncspanOverride=I.getFuncspanOverride,exports.parseHeaderOverride=I.parseHeaderOverride,exports.setFuncspanOverride=I.setFuncspanOverride,exports.isProductionEnvironment=D.isProductionEnvironment,exports.isRuntimeModeEnabled=D.isRuntimeModeEnabled,exports.shouldEnableRuntimeHooks=D.shouldEnableRuntimeHooks,exports.setSkipTypeScriptPlugin=Se.setSkipTypeScriptPlugin,exports.transformFunctionSpans=Se.transformFunctionSpans,exports.transformFunctionSpansSync=Se.transformFunctionSpansSync,exports._setAsyncQueueHopSpy=function(n){Te=n},exports.addOrUpdateMetadata=function(n,t={},e,o=!1){const r=p.getConfig();new We(r.apiKey).addOrUpdateMetadata(n,t,e,o)},exports.captureFunctionSpan=function(n,t,e,o){const r=function(...s){const d=p.getGlobalConfigUnsafe(),u=d?.sfDebug||!1;let a;if(u&&console.log(`[FuncSpan] captureFunctionSpan wrapper called for ${e}::${t}`),jt()){const h={};for(let y=0;y<o.paramNames.length&&y<s.length;y++)h[o.paramNames[y]]=s[y];a=$t(e,t,h)}else a=$t(e,t,Kt);if(u&&console.log(`[FuncSpan] Config for ${e}::${t}:`,a),a.enable_sampling&&a.sample_rate<1&&Math.random()>a.sample_rate)return u&&console.log(`[FuncSpan] Skipping ${t} due to sampling`),n.apply(this,s);if(a.sample_rate===0)return u&&console.log(`[FuncSpan] Skipping ${t} - sample_rate is 0.0`),n.apply(this,s);u&&console.log(`[FuncSpan] Capturing function span for ${t}`);const i=p.ContextManager.getInstance(),l=i.getCurrentFunctionSpanId(),c=Ln();i.setCurrentFunctionSpanId(c);const f=R?process.hrtime.bigint():0n,g=Date.now();let m;if(a.capture_arguments){const h=o.paramNames,y=h.length<s.length?h.length:s.length,S=I.serializePrimitiveArgsJson(h,s,y);if(S!==null&&S.length<=1024*a.arg_limit_mb*1024)m=S;else{const E={};for(let _=0;_<y;_++)E[h[_]]=s[_];m=I.serializeWithLimit(E,a.arg_limit_mb)}}else m="{}";try{const h=n.apply(this,s);if(h&&typeof h.then=="function")return l?i.setCurrentFunctionSpanId(l):i.clearCurrentFunctionSpanId(),h.then(_=>{const $=Date.now(),w=R?Number(process.hrtime.bigint()-f):1e6*($-g),N=I.serializeReturnEnvelope(_,a.capture_return_value,a.return_limit_mb);return b.functionName=t,b.filePath=e,b.metadata=o,b.argsJson=m,b.returnValueJson=N,b.error=null,b.duration=$-g,b.durationNs=w,b.startTimeNs=R?f.toString():"",b.async=!0,b.spanId=c,b.parentSpanId=l,b.pid=process.pid,b.threadId=ce.threadId,b.debug=u,de(b),_},_=>{const $=Date.now(),w=R?Number(process.hrtime.bigint()-f):1e6*($-g);throw b.functionName=t,b.filePath=e,b.metadata=o,b.argsJson=m,b.returnValueJson=_t,b.error=_?.message||String(_),b.duration=$-g,b.durationNs=w,b.startTimeNs=R?f.toString():"",b.async=!0,b.spanId=c,b.parentSpanId=l,b.pid=process.pid,b.threadId=ce.threadId,b.debug=u,de(b),_});const y=Date.now(),S=R?Number(process.hrtime.bigint()-f):1e6*(y-g),E=I.serializeReturnEnvelope(h,a.capture_return_value,a.return_limit_mb);return b.functionName=t,b.filePath=e,b.metadata=o,b.argsJson=m,b.returnValueJson=E,b.error=null,b.duration=y-g,b.durationNs=S,b.startTimeNs=R?f.toString():"",b.async=!1,b.spanId=c,b.parentSpanId=l,b.pid=process.pid,b.threadId=ce.threadId,b.debug=u,de(b),l?i.setCurrentFunctionSpanId(l):i.clearCurrentFunctionSpanId(),h}catch(h){const y=Date.now(),S=R?Number(process.hrtime.bigint()-f):1e6*(y-g);throw b.functionName=t,b.filePath=e,b.metadata=o,b.argsJson=m,b.returnValueJson=_t,b.error=h?.message||String(h),b.duration=y-g,b.durationNs=S,b.startTimeNs=R?f.toString():"",b.async=!1,b.spanId=c,b.parentSpanId=l,b.pid=process.pid,b.threadId=ce.threadId,b.debug=u,de(b),l?i.setCurrentFunctionSpanId(l):i.clearCurrentFunctionSpanId(),h}};Object.defineProperty(r,"name",{value:t,writable:!1});for(const s in n)n.hasOwnProperty(s)&&(r[s]=n[s]);return r},exports.getGlobalConfig=Pt,exports.identify=function(n,t,e,o=!1){const r=p.getConfig();new We(r.apiKey).identify(n,t,e,o)},exports.initializeConfigLoader=Ye,exports.initializeWorkerPoolPatching=st,exports.isAlreadyInstrumented=function(n){return!!n.includes("captureFunctionSpan(")||!!n.includes("@sailfish-ai/sf-veritas")||!(!n.includes("/* @sailfish-instrumented */")&&!n.includes("// @sailfish-instrumented"))},exports.isAsyncQueuePatchesInstalled=function(){return ue},exports.isConfigLoaderInitialized=Ze,exports.isSetupInterceptorsInitialized=function(){return Ce},exports.isWorkerPoolInitialized=at,exports.setupInterceptors=function(n){if(ke)console.warn("[setupInterceptors] ⚠️ Recursive call detected and blocked!");else if(!Ce){ke=!0,I.registerShutdownHooks();try{let t,e;const o=D.stackToString(new Error().stack);if(o){const u=o.split(`
192
- `)[2]||"",a=u.match(/\((.+):(\d+):\d+\)/)||u.match(/at (.+):(\d+):\d+/);a&&(t=a[1],e=parseInt(a[2],10))}if(!n||!n.apiKey){const u=`The required API Key is not provided: ${JSON.stringify(n)}`;console.error(u)}const{config:r}=p.getOrCreateConfig(n);if(p.backfillGitInfoAsync(r).catch(()=>{}),t&&(r.setupInterceptorsFile=t),e&&(r.setupInterceptorsLine=e),r.sfDebug&&console.log("Updated configuration after applying options:",r),!r.apiKey||!r.apiGraphqlEndpoint){const u=`The required config is not provided: ${JSON.stringify(r)}`;throw console.error(u),new Error(u)}Ze()||Ye(void 0,r.sfDebug).catch(u=>{r.sfDebug&&console.error("[FuncSpan] Failed to initialize config loader:",u)}),process.env.SF_WORKER_POOL_DISABLED==="true"?r.sfDebug&&console.log("[setupInterceptors] Worker pool patching DISABLED (SF_WORKER_POOL_DISABLED=true)"):at()||(st(),r.sfDebug&&console.log("[setupInterceptors] Worker pool patching initialized (DNS tracking enabled)"));const s=new He;s.setServiceUUID(r.serviceUUID),D.initializeLogInterceptor(s),(function(u=[]){const a=new an(u);new on().doSend(a.getExcludedDomains());const i=new sn,l=new Nt;a.patchFetch(i,l),a.patchHttp(i,l)})(r.domainsToNotPropagateHeadersTo);const d=new tn;d.setServiceUUID(r.serviceUUID),D.initializeExceptionInterceptor(d),rn(),new cn().send(),(function(){if(ue)return;if(ue=!0,process.env.SF_DISABLE_QUEUE_PATCHES==="true")return void(p.getConfig().sfDebug&&console.log("[sf-veritas] Async queue tracing DISABLED via SF_DISABLE_QUEUE_PATCHES=true"));const u=p.getConfig(),a=[],i=[],l=[],c=[];for(const{name:g,envDisableKey:m,install:h}of wn){if(_n(m)){l.push(g);continue}let y="failed";try{y=h()}catch(S){u.sfDebug&&console.warn(`[asyncQueues] Failed to install ${g} patch:`,S),c.push(g);continue}y==="installed"?a.push(g):y==="not-installed"?i.push(g):c.push(g)}const f=[`active: ${a.length?a.join(", "):"(none)"}`];i.length&&f.push(`skipped (not installed): ${i.join(", ")}`),l.length&&f.push(`disabled by env: ${l.join(", ")}`),c.length&&f.push(`failed: ${c.join(", ")}`),(u.sfDebug||c.length>0)&&console.log(`[sf-veritas] Async queue tracing — ${f.join("; ")}`)})();try{p.getConfig().uplinkEnable&&(K||L||(oe=!1,X=1e3,I.setDeactivateCallback(Fn),Y=setInterval(()=>{try{I.checkTtl()}catch{}},1e3),typeof Y.unref=="function"&&Y.unref(),Ke()))}catch(u){r.sfDebug&&console.error("[setupInterceptors] uplinkClient failed to start",u)}if(!Et){Et=!0;for(const u of["exit","SIGINT","SIGTERM"])process.on(u,()=>{try{An()}catch{}})}Ce=!0,r.sfDebug&&console.log("[setupInterceptors] ✅ Initialization complete")}finally{ke=!1}}},exports.uninstallAsyncQueuePatches=function(){const n=(function(){let t=0;for(const{proto:e,key:o,original:r}of qe.splice(0))try{r===void 0?delete e[o]:e[o]=r,t+=1}catch{}return t})();return ue=!1,n};
191
+ `;He.appendFileSync(o,i,"utf-8")}catch(o){console.error("[FuncSpan] Error writing to JSONL file:",o)}if(t&&console.log("[FuncSpan] Sending function span to transmitter:",n),!Bn)try{(Pe||(Pe=new I.FunctionSpanTransmitter),Pe).sendOne(n),t&&console.log("[FuncSpan] Function span sent successfully")}catch(o){t&&console.error("[FuncSpan] Error sending function span:",o)}}exports.ContextManager=g.ContextManager,exports.getCurrentFunctionSpanId=g.getCurrentFunctionSpanId,exports.runWithContext=g.runWithContext,exports.clearFuncspanOverride=I.clearFuncspanOverride,exports.getDefaultConfig=I.getDefaultConfig,exports.getEnvConfig=I.getEnvConfig,exports.getFuncspanOverride=I.getFuncspanOverride,exports.parseHeaderOverride=I.parseHeaderOverride,exports.setFuncspanOverride=I.setFuncspanOverride,exports.isProductionEnvironment=D.isProductionEnvironment,exports.isRuntimeModeEnabled=D.isRuntimeModeEnabled,exports.shouldEnableRuntimeHooks=D.shouldEnableRuntimeHooks,exports.setSkipTypeScriptPlugin=Se.setSkipTypeScriptPlugin,exports.transformFunctionSpans=Se.transformFunctionSpans,exports.transformFunctionSpansSync=Se.transformFunctionSpansSync,exports._setAsyncQueueHopSpy=function(n){qe=n},exports.addOrUpdateMetadata=function(n,t={},e,o=!1){const r=g.getConfig();new Qe(r.apiKey).addOrUpdateMetadata(n,t,e,o)},exports.captureFunctionSpan=function(n,t,e,o){const r=function(...s){const d=g.getGlobalConfigUnsafe(),u=d?.sfDebug||!1;let a;if(u&&console.log(`[FuncSpan] captureFunctionSpan wrapper called for ${e}::${t}`),Ht()){const h={};for(let m=0;m<o.paramNames.length&&m<s.length;m++)h[o.paramNames[m]]=s[m];a=$t(e,t,h)}else a=$t(e,t,Jt);if(u&&console.log(`[FuncSpan] Config for ${e}::${t}:`,a),a.enable_sampling&&a.sample_rate<1&&Math.random()>a.sample_rate)return u&&console.log(`[FuncSpan] Skipping ${t} due to sampling`),n.apply(this,s);if(a.sample_rate===0)return u&&console.log(`[FuncSpan] Skipping ${t} - sample_rate is 0.0`),n.apply(this,s);u&&console.log(`[FuncSpan] Capturing function span for ${t}`);const i=g.ContextManager.getInstance(),c=i.getCurrentFunctionSpanId(),l=On();i.setCurrentFunctionSpanId(l);const f=R?process.hrtime.bigint():0n,p=Date.now();let y;if(a.capture_arguments){const h=o.paramNames,m=h.length<s.length?h.length:s.length,E=I.serializePrimitiveArgsJson(h,s,m);if(E!==null&&E.length<=1024*a.arg_limit_mb*1024)y=E;else{const _={};for(let b=0;b<m;b++)_[h[b]]=s[b];y=I.serializeWithLimit(_,a.arg_limit_mb)}}else y="{}";try{const h=n.apply(this,s);if(h&&typeof h.then=="function")return c?i.setCurrentFunctionSpanId(c):i.clearCurrentFunctionSpanId(),h.then(b=>{const $=Date.now(),w=R?Number(process.hrtime.bigint()-f):1e6*($-p),k=I.serializeReturnEnvelope(b,a.capture_return_value,a.return_limit_mb);return S.functionName=t,S.filePath=e,S.metadata=o,S.argsJson=y,S.returnValueJson=k,S.error=null,S.duration=$-p,S.durationNs=w,S.startTimeNs=R?f.toString():"",S.async=!0,S.spanId=l,S.parentSpanId=c,S.pid=process.pid,S.threadId=ce.threadId,S.debug=u,de(S),b},b=>{const $=Date.now(),w=R?Number(process.hrtime.bigint()-f):1e6*($-p);throw S.functionName=t,S.filePath=e,S.metadata=o,S.argsJson=y,S.returnValueJson=wt,S.error=b?.message||String(b),S.duration=$-p,S.durationNs=w,S.startTimeNs=R?f.toString():"",S.async=!0,S.spanId=l,S.parentSpanId=c,S.pid=process.pid,S.threadId=ce.threadId,S.debug=u,de(S),b});const m=Date.now(),E=R?Number(process.hrtime.bigint()-f):1e6*(m-p),_=I.serializeReturnEnvelope(h,a.capture_return_value,a.return_limit_mb);return S.functionName=t,S.filePath=e,S.metadata=o,S.argsJson=y,S.returnValueJson=_,S.error=null,S.duration=m-p,S.durationNs=E,S.startTimeNs=R?f.toString():"",S.async=!1,S.spanId=l,S.parentSpanId=c,S.pid=process.pid,S.threadId=ce.threadId,S.debug=u,de(S),c?i.setCurrentFunctionSpanId(c):i.clearCurrentFunctionSpanId(),h}catch(h){const m=Date.now(),E=R?Number(process.hrtime.bigint()-f):1e6*(m-p);throw S.functionName=t,S.filePath=e,S.metadata=o,S.argsJson=y,S.returnValueJson=wt,S.error=h?.message||String(h),S.duration=m-p,S.durationNs=E,S.startTimeNs=R?f.toString():"",S.async=!1,S.spanId=l,S.parentSpanId=c,S.pid=process.pid,S.threadId=ce.threadId,S.debug=u,de(S),c?i.setCurrentFunctionSpanId(c):i.clearCurrentFunctionSpanId(),h}};Object.defineProperty(r,"name",{value:t,writable:!1});for(const s in n)n.hasOwnProperty(s)&&(r[s]=n[s]);return r},exports.getGlobalConfig=Ft,exports.identify=function(n,t,e,o=!1){const r=g.getConfig();new Qe(r.apiKey).identify(n,t,e,o)},exports.initializeConfigLoader=Ze,exports.initializeWorkerPoolPatching=at,exports.isAlreadyInstrumented=function(n){return!!n.includes("captureFunctionSpan(")||!!n.includes("@sailfish-ai/sf-veritas")||!(!n.includes("/* @sailfish-instrumented */")&&!n.includes("// @sailfish-instrumented"))},exports.isAsyncQueuePatchesInstalled=function(){return ue},exports.isConfigLoaderInitialized=et,exports.isSetupInterceptorsInitialized=function(){return ke},exports.isWorkerPoolInitialized=ct,exports.setupInterceptors=function(n){if(Ne)console.warn("[setupInterceptors] ⚠️ Recursive call detected and blocked!");else if(!ke){Ne=!0,I.registerShutdownHooks();try{let t,e;const o=D.stackToString(new Error().stack);if(o){const u=o.split(`
192
+ `)[2]||"",a=u.match(/\((.+):(\d+):\d+\)/)||u.match(/at (.+):(\d+):\d+/);a&&(t=a[1],e=parseInt(a[2],10))}if(!n||!n.apiKey){const u=`The required API Key is not provided: ${JSON.stringify(n)}`;console.error(u)}const{config:r}=g.getOrCreateConfig(n);if(g.backfillGitInfoAsync(r).catch(()=>{}),t&&(r.setupInterceptorsFile=t),e&&(r.setupInterceptorsLine=e),r.sfDebug&&console.log("Updated configuration after applying options:",r),!r.apiKey||!r.apiGraphqlEndpoint){const u=`The required config is not provided: ${JSON.stringify(r)}`;throw console.error(u),new Error(u)}et()||Ze(void 0,r.sfDebug).catch(u=>{r.sfDebug&&console.error("[FuncSpan] Failed to initialize config loader:",u)}),process.env.SF_WORKER_POOL_DISABLED==="true"?r.sfDebug&&console.log("[setupInterceptors] Worker pool patching DISABLED (SF_WORKER_POOL_DISABLED=true)"):ct()||(at(),r.sfDebug&&console.log("[setupInterceptors] Worker pool patching initialized (DNS tracking enabled)"));const s=new Ke;s.setServiceUUID(r.serviceUUID),D.initializeLogInterceptor(s),(function(u=[]){const a=new cn(u);new sn().doSend(a.getExcludedDomains());const i=new an,c=new Ut;a.patchFetch(i,c),a.patchHttp(i,c)})(r.domainsToNotPropagateHeadersTo);const d=new nn;d.setServiceUUID(r.serviceUUID),D.initializeExceptionInterceptor(d),on(),new un().send(),(function(){if(ue)return;if(ue=!0,process.env.SF_DISABLE_QUEUE_PATCHES==="true")return void(g.getConfig().sfDebug&&console.log("[sf-veritas] Async queue tracing DISABLED via SF_DISABLE_QUEUE_PATCHES=true"));const u=g.getConfig(),a=[],i=[],c=[],l=[];for(const{name:p,envDisableKey:y,install:h}of Cn){if(wn(y)){c.push(p);continue}let m="failed";try{m=h()}catch(E){u.sfDebug&&console.warn(`[asyncQueues] Failed to install ${p} patch:`,E),l.push(p);continue}m==="installed"?a.push(p):m==="not-installed"?i.push(p):l.push(p)}const f=[`active: ${a.length?a.join(", "):"(none)"}`];i.length&&f.push(`skipped (not installed): ${i.join(", ")}`),c.length&&f.push(`disabled by env: ${c.join(", ")}`),l.length&&f.push(`failed: ${l.join(", ")}`),(u.sfDebug||l.length>0)&&console.log(`[sf-veritas] Async queue tracing — ${f.join("; ")}`)})();try{g.getConfig().uplinkEnable&&(K||O||(oe=!1,X=1e3,I.setDeactivateCallback(Tn),Y=setInterval(()=>{try{I.checkTtl()}catch{}},1e3),typeof Y.unref=="function"&&Y.unref(),Je()))}catch(u){r.sfDebug&&console.error("[setupInterceptors] uplinkClient failed to start",u)}if(!_t){_t=!0;for(const u of["exit","SIGINT","SIGTERM"])process.on(u,()=>{try{Ln()}catch{}})}ke=!0,r.sfDebug&&console.log("[setupInterceptors] ✅ Initialization complete")}finally{Ne=!1}}},exports.uninstallAsyncQueuePatches=function(){const n=(function(){let t=0;for(const{proto:e,key:o,original:r}of Ae.splice(0))try{r===void 0?delete e[o]:e[o]=r,t+=1}catch{}return t})();return ue=!1,n};