@sailfish-ai/sf-veritas 0.2.20 → 0.2.21

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 c=require("./contextManager-DQMeQfS_.cjs"),u=require("./workerPoolSpanCapture-CAM2z9Jx.cjs"),g=require("./runtimeConfig-DmD4lUhG.cjs"),ae=require("node:module"),H=require("fs"),ce=require("./source-map-rHHEdpre.cjs"),de=require("fs/promises"),le=require("path"),ue=require("glob"),E=require("worker_threads"),O=require("./funcSpanTransformer-D0W2t41q.cjs");function x(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const i=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const pe=x(H),W=x(de),F=x(le);class P extends u.BaseTransmitter{constructor(){super(),this.setOperationName("IdentifyServiceDetails")}async doSend(e){if(!c.getConfig().serviceIdentificationReceived)try{this.send()}catch(t){c.getConfig().sfDebug&&console.error(" Error during service identification:",t)}}async send(){const e=`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("./contextManager-0D8uHQ1_.cjs"),g=require("./workerPoolSpanCapture-DFnbcpkU.cjs"),S=require("./runtimeConfig-sm_7bnKx.cjs"),ce=require("node:module"),H=require("fs"),P=require("http"),E=require("https"),de=require("./source-map-rHHEdpre.cjs"),le=require("fs/promises"),ue=require("path"),pe=require("glob"),T=require("worker_threads"),L=require("./funcSpanTransformer-D0W2t41q.cjs");function x(r){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const e in r)if(e!=="default"){const i=Object.getOwnPropertyDescriptor(r,e);Object.defineProperty(t,e,i.get?i:{enumerable:!0,get:()=>r[e]})}}return t.default=r,Object.freeze(t)}const ge=x(H),W=x(le),N=x(ue);class w extends g.BaseTransmitter{constructor(){super(),this.setOperationName("IdentifyServiceDetails")}async doSend(t){if(!a.getConfig().serviceIdentificationReceived)try{this.send()}catch(e){a.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!,
@@ -13,6 +13,9 @@
13
13
  $gitRepo: String,
14
14
  $gitProvider: String,
15
15
  $serviceDisplayName: String,
16
+ $framework: String,
17
+ $additionalFrameworks: JSON,
18
+ $serviceRole: String,
16
19
  ) {
17
20
  ${this.queryName}(
18
21
  apiKey: $apiKey,
@@ -28,13 +31,16 @@
28
31
  gitRepo: $gitRepo,
29
32
  gitProvider: $gitProvider,
30
33
  serviceDisplayName: $serviceDisplayName,
34
+ framework: $framework,
35
+ additionalFrameworks: $additionalFrameworks,
36
+ serviceRole: $serviceRole,
31
37
  )
32
38
  }
33
- `,t=this.getVariables({serviceIdentifier:c.getConfig().serviceIdentifier,serviceVersion:c.getConfig().serviceVersion,library:c.getConfig().packageLibraryType,version:c.getConfig().version,serviceAdditionalMetadata:c.getConfig().serviceAdditionalMetadata,gitSha:c.getConfig().gitSha||"",gitOrg:c.getConfig().gitOrg||void 0,gitRepo:c.getConfig().gitRepo||void 0,gitProvider:c.getConfig().gitProvider||void 0,serviceDisplayName:c.getConfig().serviceDisplayName||void 0});u.nonBlockingPost(this.endpoint,this.operationName,e,t)}}class ge extends u.BaseTransmitter{serviceIdentifier=new P;constructor(){super(),this.setOperationName("CollectMetadata")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(e,t,i,n){this.sendAppIdentifier(),this.send(e,t,i,n)}async send(e,t,i,n){if(!t&&!n)throw new Error('Must pass in either traits or traits_json to "add_or_update_traits"');let s=[];if(!n){const o=g.serializeJsonWithExclusions(t);n=o.traitsJson,s=o.excludedFields}const l=this.getVariables({userId:e,traitsJson:n,excludedFields:s,override:i,library:c.getConfig().packageLibraryType,version:c.getConfig().version});u.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),l)}getQuery(){return`
39
+ `,e=a.getConfig(),i=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});g.nonBlockingPost(this.endpoint,this.operationName,t,i)}}class fe extends g.BaseTransmitter{serviceIdentifier=new w;constructor(){super(),this.setOperationName("CollectMetadata")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t,e,i,n){this.sendAppIdentifier(),this.send(t,e,i,n)}async send(t,e,i,n){if(!e&&!n)throw new Error('Must pass in either traits or traits_json to "add_or_update_traits"');let o=[];if(!n){const c=S.serializeJsonWithExclusions(e);n=c.traitsJson,o=c.excludedFields}const f=this.getVariables({userId:t,traitsJson:n,excludedFields:o,override:i,library:a.getConfig().packageLibraryType,version:a.getConfig().version});g.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),f)}getQuery(){return`
34
40
  mutation ${this.operationName}($apiKey: String!, $serviceUuid: String!, $sessionId: String!, $userId: String!, $traitsJson: String!, $excludedFields: [String!]!, $library: String!, $timestampMs: String!, $version: String!, $override: Boolean!) {
35
41
  ${this.queryName}(apiKey: $apiKey, serviceUuid: $serviceUuid, sessionId: $sessionId, userId: $userId, traitsJson: $traitsJson, excludedFields: $excludedFields, library: $library, timestampMs: $timestampMs, version: $version, override: $override)
36
42
  }
37
- `}}class K{constructor(e){this.apiKey=e,this.metadataTransmitter=new ge}metadataTransmitter;identify(e,t,i,n=!1){t||i?this.addOrUpdateMetadata(e,t,i,n):this.addOrUpdateMetadata(e,{},void 0,n)}addOrUpdateMetadata(e,t={},i,n=!1){if(!t&&!i)throw new Error('Must pass in either traits or traitsJson to "addOrUpdateMetadata"');c.getConfig().sfDebug&&console.log(" [[DEBUG - addOrUpdateMetadata]] Starting operation"),c.getConfig().sfDebug&&console.log(" addOrUpdateMetadata...SENDING DATA...",e,t,i),this.metadataTransmitter.doSend(e,t,n,i)}}class B extends u.BaseTransmitter{serviceIdentifier=new P;constructor(){super()}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(e){this.sendAppIdentifier(),this.send(e)}async send(e){try{const t=Array.isArray(e)?e:[e,"default",null,null],i=this.getVariables({contents:t[0],level:t[1],sourceFile:t[2]||void 0,sourceLine:t[3]||void 0});u.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),i)}catch(t){c.getConfig().sfDebug&&console.error("🚨 Error in send():",t)}}getQuery(){return`
43
+ `}}class K{constructor(t){this.apiKey=t,this.metadataTransmitter=new fe}metadataTransmitter;identify(t,e,i,n=!1){e||i?this.addOrUpdateMetadata(t,e,i,n):this.addOrUpdateMetadata(t,{},void 0,n)}addOrUpdateMetadata(t,e={},i,n=!1){if(!e&&!i)throw new Error('Must pass in either traits or traitsJson to "addOrUpdateMetadata"');a.getConfig().sfDebug&&console.log(" [[DEBUG - addOrUpdateMetadata]] Starting operation"),a.getConfig().sfDebug&&console.log(" addOrUpdateMetadata...SENDING DATA...",t,e,i),this.metadataTransmitter.doSend(t,e,n,i)}}class B extends g.BaseTransmitter{serviceIdentifier=new w;constructor(){super()}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t){this.sendAppIdentifier(),this.send(t)}async send(t){try{const e=Array.isArray(t)?t:[t,"default",null,null],i=this.getVariables({contents:e[0],level:e[1],sourceFile:e[2]||void 0,sourceLine:e[3]||void 0});g.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),i)}catch(e){a.getConfig().sfDebug&&console.error("🚨 Error in send():",e)}}getQuery(){return`
38
44
  ${this.queryType} ${this.operationName}(
39
45
  $apiKey: String!,
40
46
  $serviceUuid: String!,
@@ -58,7 +64,7 @@
58
64
  sourceLine: $sourceLine
59
65
  )
60
66
  }
61
- `}}class fe extends u.BaseTransmitter{serviceIdentifier=new P;supplementalFields={};setSupplementalFields(e){this.supplementalFields={...this.supplementalFields,...e}}normalizedSupplementalForGraphQL(){const{isFromLocalService:e}=this.supplementalFields,t={};return e!==void 0&&(t.isFromLocalService=e),t}constructor(){super(),this.setOperationName("CollectExceptions")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(e,t){this.sendAppIdentifier(),this.send(e,t)}async send(e,t){c.getConfig().sfDebug&&console.log(" SENDING EXCEPTION...");const i=JSON.stringify(g.CustomJSONEncoderForFrameInfo.encode(t)),n=this.normalizedSupplementalForGraphQL(),s=this.getVariables({exceptionMessage:e,traceJson:i,reentrancyGuardPreactive:!1,library:c.getConfig().packageLibraryType,version:c.getConfig().version,...n});u.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),s)}getQuery(){return`
67
+ `}}class he extends g.BaseTransmitter{serviceIdentifier=new w;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")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t,e){this.sendAppIdentifier(),this.send(t,e)}async send(t,e){a.getConfig().sfDebug&&console.log(" SENDING EXCEPTION...");const i=JSON.stringify(S.CustomJSONEncoderForFrameInfo.encode(e)),n=this.normalizedSupplementalForGraphQL(),o=this.getVariables({exceptionMessage:t,traceJson:i,reentrancyGuardPreactive:!1,library:a.getConfig().packageLibraryType,version:a.getConfig().version,...n});g.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),o)}getQuery(){return`
62
68
  mutation ${this.operationName}(
63
69
  $apiKey: String!,
64
70
  $serviceUuid: String!,
@@ -86,7 +92,7 @@
86
92
  parentSpanId: $parentSpanId
87
93
  )
88
94
  }
89
- `}}const z="getting request source code";var w=(r=>(r.UNKNOWN="unknown",r.ANONYMOUS="anonymous",r.NOT_CAPTURED="not captured",r))(w||{});const L="http:",U="https:",he=ae.createRequire(require("node:url").pathToFileURL(__filename).href);let j=!1;function me(){const r=c.getConfig().sfDebug;if(j)return void(r&&g.internalLog("[patchNodeHttpInbound] Already installed, skipping."));let e;j=!0;try{e=he("node:http"),r&&g.internalLog("[patchNodeHttpInbound] node:http required successfully.")}catch(n){return void g.internalError("Failed to require node:http:",n)}if(!e?.Server?.prototype)return void(r&&g.internalLog("[patchNodeHttpInbound] http.Server.prototype not found."));const t=e.Server.prototype,i=t.emit;i&&!t.__sf_inbound_patched__?(Object.defineProperty(t,"__sf_inbound_patched__",{value:!0,enumerable:!1,configurable:!1,writable:!1}),r&&g.internalLog("[patchNodeHttpInbound] Patching http.Server.prototype.emit."),t.emit=function(n,...s){if(n!=="request")return r&&g.internalLog(`[patchNodeHttpInbound] Passing through event: ${n}`),i.call(this,n,...s);const l=s[0],o=s[1],d=(function(f){const m={};if(!f)return m;for(const[v,_]of Object.entries(f))_!=null&&(Array.isArray(_)?m[v.toLowerCase()]=_.join(", "):m[v.toLowerCase()]=String(_));return m})(l?.headers),a=d["x-sf3-rid"],p=d["x-sf3-functionspancaptureoverride"];r&&(g.internalLog("[patchNodeHttpInbound] Intercepted request event."),g.internalLog("[patchNodeHttpInbound] Inbound headers:",d),g.internalLog("[patchNodeHttpInbound] Trace header:",a),g.internalLog("[patchNodeHttpInbound] FuncSpan override header:",p));const h=c.ContextManager.getInstance();h.setTraceId(a);const y=h.getTraceId();r&&g.internalLog("[patchNodeHttpInbound] Context traceId set:",y);const S=()=>h.runWith({inboundHeaders:d,...a?{traceId:a}:{}},()=>{a&&h.setTraceId(a),r&&g.internalLog("[patchNodeHttpInbound] Running request handler in context.");const f=()=>{r&&g.internalLog("[patchNodeHttpInbound] Response finished/closed for traceId:",h.getTraceId())};return o.on("finish",f),o.on("close",f),i.call(this,n,l,o)});if(!p)return S();try{return u.funcspanOverrideStorage.run(p,()=>S())}catch{return S()}}):r&&g.internalLog("[patchNodeHttpInbound] Already patched, skipping.")}class ye extends B{constructor(){super(),this.setOperationName("DomainsToNotPassHeaderTo")}async doSend(e){this.sendAppIdentifier(),this.send(e)}async send(e){const t=`
95
+ `}}const j="getting request source code";var k=(r=>(r.UNKNOWN="unknown",r.ANONYMOUS="anonymous",r.NOT_CAPTURED="not captured",r))(k||{});const z="http:",me=ce.createRequire(require("node:url").pathToFileURL(__filename).href);let J=!1;function ye(){const r=a.getConfig().sfDebug;if(J)return void(r&&S.internalLog("[patchNodeHttpInbound] Already installed, skipping."));let t;J=!0;try{t=me("node:http"),r&&S.internalLog("[patchNodeHttpInbound] node:http required successfully.")}catch(n){return void S.internalError("Failed to require node:http:",n)}if(!t?.Server?.prototype)return void(r&&S.internalLog("[patchNodeHttpInbound] http.Server.prototype not found."));const e=t.Server.prototype,i=e.emit;i&&!e.__sf_inbound_patched__?(Object.defineProperty(e,"__sf_inbound_patched__",{value:!0,enumerable:!1,configurable:!1,writable:!1}),r&&S.internalLog("[patchNodeHttpInbound] Patching http.Server.prototype.emit."),e.emit=function(n,...o){if(n!=="request")return r&&S.internalLog(`[patchNodeHttpInbound] Passing through event: ${n}`),i.call(this,n,...o);const f=o[0],c=o[1],s=(function(u){const m={};if(!u)return m;for(const[I,$]of Object.entries(u))$!=null&&(Array.isArray($)?m[I.toLowerCase()]=$.join(", "):m[I.toLowerCase()]=String($));return m})(f?.headers),l=s["x-sf3-rid"],p=s["x-sf3-functionspancaptureoverride"];r&&(S.internalLog("[patchNodeHttpInbound] Intercepted request event."),S.internalLog("[patchNodeHttpInbound] Inbound headers:",s),S.internalLog("[patchNodeHttpInbound] Trace header:",l),S.internalLog("[patchNodeHttpInbound] FuncSpan override header:",p));const d=a.ContextManager.getInstance();d.setTraceId(l);const h=d.getTraceId();r&&S.internalLog("[patchNodeHttpInbound] Context traceId set:",h);const y=()=>d.runWith({inboundHeaders:s,...l?{traceId:l}:{}},()=>{l&&d.setTraceId(l),r&&S.internalLog("[patchNodeHttpInbound] Running request handler in context.");const u=()=>{r&&S.internalLog("[patchNodeHttpInbound] Response finished/closed for traceId:",d.getTraceId())};return c.on("finish",u),c.on("close",u),i.call(this,n,f,c)});if(!p)return y();try{return g.funcspanOverrideStorage.run(p,()=>y())}catch{return y()}}):r&&S.internalLog("[patchNodeHttpInbound] Already patched, skipping.")}class Se extends B{constructor(){super(),this.setOperationName("DomainsToNotPassHeaderTo")}async doSend(t){this.sendAppIdentifier(),this.send(t)}async send(t){const e=`
90
96
  ${this.queryType} ${this.operationName}(
91
97
  $apiKey: String!,
92
98
  $serviceUuid: String!,
@@ -98,7 +104,7 @@
98
104
  domains: $domains
99
105
  )
100
106
  }
101
- `,i={apiKey:this.apiKey,serviceUuid:this.serviceUUID,domains:e};u.nonBlockingPost(this.endpoint,this.operationName,t,i)}}class Se extends u.BaseTransmitter{serviceIdentifier=new P;constructor(){super(),this.setOperationName("CollectNetworkHops")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(e){this.sendAppIdentifier(),this.send(e)}async send(e){const{name:t,column:i,line:n,entrypoint:s,retryWithoutTraceId:l}=e,o=this.getVariables({name:t,column:i,line:n,entrypoint:s,retryWithoutTraceId:l});u.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),o)}getQuery(){return`
107
+ `,i={apiKey:this.apiKey,serviceUuid:this.serviceUUID,domains:t};g.nonBlockingPost(this.endpoint,this.operationName,e,i)}}class ve extends g.BaseTransmitter{serviceIdentifier=new w;constructor(){super(),this.setOperationName("CollectNetworkHops")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t){this.sendAppIdentifier(),this.send(t)}async send(t){const{name:e,column:i,line:n,entrypoint:o,retryWithoutTraceId:f}=t,c=this.getVariables({name:e,column:i,line:n,entrypoint:o,retryWithoutTraceId:f});g.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),c)}getQuery(){return`
102
108
  mutation ${this.operationName}(
103
109
  $apiKey: String!,
104
110
  $sessionId: String!,
@@ -122,15 +128,15 @@
122
128
  ${this.operationName==="CollectNetworkHops"?", retryWithoutTraceId: $retryWithoutTraceId":""}
123
129
  )
124
130
  }
125
- `}}class Ie extends u.BaseTransmitter{serviceIdentifier=new P;constructor(){super(),this.setOperationName("CollectNetworkRequest")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(e){this.sendAppIdentifier(),this.send(e)}getQuery(){return`
131
+ `}}class Ie extends g.BaseTransmitter{serviceIdentifier=new w;constructor(){super(),this.setOperationName("CollectNetworkRequest")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t){this.sendAppIdentifier(),this.send(t)}getQuery(){return`
126
132
  mutation ${this.operationName}(
127
133
  $data: NetworkRequestInput!
128
134
  ) {
129
135
  ${this.queryName}(
130
136
  data: $data)
131
137
  }
132
- `}async send(e){const t={data:{...e}};await u.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),t)}}const R=[400,403];class ve{HEADER_TRACING="X-Sf3-Rid";HEADER_LOG_GUARD="reentrancy_guard_logging_preactive";HEADER_PRINT_GUARD="reentrancy_guard_print_preactive";HEADER_EXCEPTION_GUARD="reentrancy_guard_exception_preactive";contextManager;constructor(e=[]){this.contextManager=c.ContextManager.getInstance(),e?.forEach(t=>{typeof t=="string"&&t.trim()&&this.contextManager.getExcludedDomains().add(t)}),c.getConfig().sfDebug&&console.log("[RequestInterceptor] Initialized with static excluded domains.")}extractIdsFromTraceHeader(e,t=this.HEADER_TRACING){let i;if(e instanceof Headers)i=e.get(t)??void 0;else{const s=t.toLowerCase();for(const[l,o]of Object.entries(e))if(l.toLowerCase()===s){i=o;break}}if(!i)return{};const n=i.split("/").filter(Boolean);return n.length<3?{}:{sessionId:n[0],pageVisitId:n[1],requestId:n[n.length-1]}}parseStackFrame(e){const t=/\((.*):(\d+):(\d+)\)$/.exec(e.trim());if(!t)return null;const[,i,n,s]=t;return{filePath:i,line:parseInt(n,10),column:parseInt(s,10)}}async getOriginalPosition(e,t,i){let n={source:e,line:t,column:i,name:null};if(e.includes("://"))return{originalPos:n};const s=e+".map";try{const l=JSON.parse(H.readFileSync(s,"utf-8"));let o=(await new ce.sourceMapExports.SourceMapConsumer(l)).originalPositionFor({line:t,column:i});o.source&&(n=o)}catch(l){c.getConfig().sfDebug&&console.error(`Could not read/parse map file at ${s}:`,l)}return{originalPos:n}}captureFirstUserLines(e,t=10,i=!1){const n=c.getConfig().sfDebug?10:t,s=Error.stackTraceLimit;Error.stackTraceLimit=Math.max(s,n);const l=new Error(z);z in Error&&Error.captureStackTrace(l,this.captureFirstUserLines);const o=g.stackToString(l.stack);Error.stackTraceLimit=s;const d=o.split(`
133
- `).slice(1),a=[];for(const p of d)if(!(p.includes("node:internal")||p.includes("internal/modules")||p.includes("internal/process")||p.includes("node_modules")||p.includes(".next/server/chunks")||p.includes("RequestInterceptor")||p.includes("contextManager")||p.includes("setupConfig"))&&(a.push(p.trim()),a.length>=t))break;for(const p of a){const h=this.parseStackFrame(p);h?(async()=>{const{originalPos:y}=await this.getOriginalPosition(h.filePath,h.line,h.column);if(y){c.getConfig().sfDebug&&console.log("[RequestInterceptor] First user code line:",y);const S={line:y.line?.toString()||w.UNKNOWN,column:y.column?.toString()||w.NOT_CAPTURED,name:y.name||w.NOT_CAPTURED,entrypoint:y.source,retryWithoutTraceId:i};e.doSend(S)}})():c.getConfig().sfDebug&&console.error("Could not parse stack line:",p)}}addReentrancyGuardHeaders(e){e.set(this.HEADER_LOG_GUARD,"true"),e.set(this.HEADER_PRINT_GUARD,"true"),e.set(this.HEADER_EXCEPTION_GUARD,"true")}shouldPropagateHeaders(e){return!c.DEFAULT_DOMAINS_TO_EXCLUDE.some(t=>new RegExp(`^${t.replace(/\*/g,".*")}$`).test(e))}addTracingHeaders(e,t){const i=new URL(t).hostname,n=this.shouldPropagateHeaders(i);return n?this.addTracingHeader(e,t):c.getConfig().sfDebug&&console.error(`[RequestInterceptor] Excluded domain: ${i}`),n}addTracingHeader(e,t){const i=u.getFuncspanOverride();if(i){const o=u.parseHeaderOverride(i);if(o&&o.sample_rate===0)return void(c.getConfig().sfDebug&&console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${t}`))}const n=this.contextManager.getOrSetSfTraceId(),s=this.contextManager.getOrSetPageVisitUUID(),l=c.v4();e.set(this.HEADER_TRACING,`${n}/${s}/${l}`),c.getConfig().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${t}`)}patchFetch(e,t){const i=globalThis.fetch;typeof i=="function"?globalThis.fetch=async(n,s)=>{const l=new Headers(s?.headers);if(l.get(this.HEADER_LOG_GUARD)==="true"||l.get(this.HEADER_PRINT_GUARD)==="true"||l.get(this.HEADER_EXCEPTION_GUARD)==="true")return i(n,s);this.captureFirstUserLines(e);const o=Date.now();let d;typeof n=="string"||n instanceof URL?d=n.toString():n instanceof Request?(d=n.url,n.headers.forEach((f,m)=>{l.set(m,f)})):c.getConfig().sfDebug&&console.error("[Sailfish RequestInterceptor] Invalid fetch input."),c.getConfig().sfDebug&&console.log("[RequestInterceptor] Fetching request to:",d);const a=new URL(d).hostname,p=new Headers(l),h=this.addTracingHeaders(l,d),y={...s,headers:l};let S;try{let f=!1;this.addTracingHeaders(p,d),S=await i(d,y),h&&R.includes(S.status)?(S=await i(d,{...s,headers:p}),f=!0,this.captureFirstUserLines(e,10,f)):this.contextManager.addSupportedDomains(a);const m=Date.now();c.getConfig().sfDebug&&console.log(`[RequestInterceptor] Fetch completed: ${d}, Status: ${S.status}, Duration: ${m-o}ms`);const{sessionId:v,pageVisitId:_,requestId:N}=this.extractIdsFromTraceHeader(l),$=c.getConfig(),b={apiKey:$.apiKey,requestId:N,pageVisitId:_,recordingSessionId:v,serviceUuid:$.serviceUUID,timestampStart:o.toString(),timestampEnd:m.toString(),responseCode:S.status,success:!0,error:null,url:d,method:y.method||"GET",retryWithoutTraceId:f,parentSpanId:c.getCurrentFunctionSpanId()};if($.captureRequestHeaders){const I={};l.forEach((C,D)=>{I[D]=C}),b.requestHeaders=I}if($.captureResponseHeaders){const I={};S.headers.forEach((C,D)=>{I[D]=C}),b.responseHeaders=I}if($.captureRequestBody&&s?.body)try{const I=typeof s.body=="string"?s.body:JSON.stringify(s.body);b.requestBody=I.length>$.requestBodyLimitBytes?I.substring(0,$.requestBodyLimitBytes)+"...[truncated]":I}catch{}if($.captureResponseBody)try{const I=S.clone(),C=await I.text();b.responseBody=C.length>$.responseBodyLimitBytes?C.substring(0,$.responseBodyLimitBytes)+"...[truncated]":C}catch{}return t.doSend(b),S}catch(f){const m=Date.now();c.getConfig().sfDebug&&console.error(`[RequestInterceptor] Fetch failed: ${d}, Error: ${f}, Duration: ${m-o}ms`)}}:c.getConfig().sfDebug&&console.error("[RequestInterceptor] Fetch not available.")}patchHttp(e,t){if(c.getConfig().sfDebug&&console.log("[RequestInterceptor] Initializing HTTP/HTTPS request patch..."),!g.https||typeof g.https.request!="function")return void(c.getConfig().sfDebug&&console.log("[RequestInterceptor] HTTP/HTTPS not available."));const i=g.https.request.bind(g.https),n=g.https.request.bind(g.https);g.https.request=function(s,l){let o;try{if(typeof s=="string"){const a=new URL(s);o={protocol:a.protocol||L,hostname:a.hostname,path:a.pathname+a.search,headers:{}}}else s instanceof URL?o={protocol:s.protocol||L,hostname:s.hostname,path:s.pathname+s.search,headers:{}}:(o={...s},o.protocol||(o.protocol=L));if(o.headers){const a=`${o.protocol}//${o.hostname}`;this.addTracingHeaders(o.headers,a),this.captureFirstUserLines(e)}else c.getConfig().sfDebug&&console.warn("[RequestInterceptor] No headers found in HTTP request options. Skipping header addition.")}catch(a){throw c.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTP request options:",a),a}let d=!1;return i(o,a=>{const p=`${o.protocol}//${o.hostname}`;if(o.headers&&this.shouldPropagateHeaders(new URL(p).hostname)&&R.includes(a.statusCode||0)){o.hostname;const f={...o,headers:{...o.headers}};delete f.headers[this.HEADER_TRACING],i(f,l),d=!0,this.captureFirstUserLines(e,10,d)}const{sessionId:h,pageVisitId:y,requestId:S}=this.extractIdsFromTraceHeader(o.headers);t.doSend({apiKey:c.getConfig().apiKey,requestId:S,pageVisitId:y,recordingSessionId:h,serviceUuid:c.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:a.statusCode||0,success:!!a.statusCode&&a.statusCode<400,error:null,url:p,method:o.method||"GET",retryWithoutTraceId:d,parentSpanId:c.getCurrentFunctionSpanId()}),l?.(a)})},g.https.request=function(s,l){let o;try{if(typeof s=="string"){const a=new URL(s);o={protocol:a.protocol||U,hostname:a.hostname,path:a.pathname+a.search,headers:{}}}else s instanceof URL?o={protocol:s.protocol||U,hostname:s.hostname,path:s.pathname+s.search,headers:{}}:(o={...s},o.protocol||(o.protocol=U));if(o.headers){const a=`${o.protocol}//${o.hostname}`;this.addTracingHeaders(o.headers,a)}else c.getConfig().sfDebug&&console.warn("[RequestInterceptor] No headers found in HTTPS request options. Skipping header addition.")}catch(a){throw c.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTPS request options:",a),a}let d=!1;return n(o,a=>{const p=`${o.protocol}//${o.hostname}`;if(o.headers&&this.shouldPropagateHeaders(new URL(p).hostname)&&R.includes(a.statusCode||0)){const f={...o,headers:{...o.headers}};delete f.headers[this.HEADER_TRACING],n(f,l),d=!0,this.captureFirstUserLines(e,10,d)}const{sessionId:h,pageVisitId:y,requestId:S}=this.extractIdsFromTraceHeader(o.headers);t.doSend({apiKey:c.getConfig().apiKey,requestId:S,pageVisitId:y,recordingSessionId:h,serviceUuid:c.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:a.statusCode||0,success:!!a.statusCode&&a.statusCode<400,error:null,url:p,method:o.method||"GET",retryWithoutTraceId:d,parentSpanId:c.getCurrentFunctionSpanId()}),l?.(a)})},c.getConfig().sfDebug&&console.log("✅ HTTP and HTTPS request methods patched globally.")}tryPatch(e,t){try{require.resolve(t),e()}catch{}}getExcludedDomains(){return[...this.contextManager.getExcludedDomains()]}}class _e extends B{constructor(){super(),this.setOperationName("UpdateServiceDetails")}async doSend(){this.sendAppIdentifier(),this.send()}async send(){const e=`
138
+ `}async send(t){const e={data:{...t}};await g.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),e)}}const R=[400,403];class $e{HEADER_TRACING="X-Sf3-Rid";HEADER_LOG_GUARD="reentrancy_guard_logging_preactive";HEADER_PRINT_GUARD="reentrancy_guard_print_preactive";HEADER_EXCEPTION_GUARD="reentrancy_guard_exception_preactive";contextManager;constructor(t=[]){this.contextManager=a.ContextManager.getInstance(),t?.forEach(e=>{typeof e=="string"&&e.trim()&&this.contextManager.getExcludedDomains().add(e)}),a.getConfig().sfDebug&&console.log("[RequestInterceptor] Initialized with static excluded domains.")}extractIdsFromTraceHeader(t,e=this.HEADER_TRACING){let i;if(t instanceof Headers)i=t.get(e)??void 0;else{const o=e.toLowerCase();for(const[f,c]of Object.entries(t))if(f.toLowerCase()===o){i=c;break}}if(!i)return{};const n=i.split("/").filter(Boolean);return n.length<3?{}:{sessionId:n[0],pageVisitId:n[1],requestId:n[n.length-1]}}parseStackFrame(t){const e=/\((.*):(\d+):(\d+)\)$/.exec(t.trim());if(!e)return null;const[,i,n,o]=e;return{filePath:i,line:parseInt(n,10),column:parseInt(o,10)}}async getOriginalPosition(t,e,i){let n={source:t,line:e,column:i,name:null};if(t.includes("://"))return{originalPos:n};const o=t+".map";try{const f=JSON.parse(H.readFileSync(o,"utf-8"));let c=(await new de.sourceMapExports.SourceMapConsumer(f)).originalPositionFor({line:e,column:i});c.source&&(n=c)}catch(f){a.getConfig().sfDebug&&console.error(`Could not read/parse map file at ${o}:`,f)}return{originalPos:n}}captureFirstUserLines(t,e=10,i=!1){const n=a.getConfig().sfDebug?10:e,o=Error.stackTraceLimit;Error.stackTraceLimit=Math.max(o,n);const f=new Error(j);j in Error&&Error.captureStackTrace(f,this.captureFirstUserLines);const c=S.stackToString(f.stack);Error.stackTraceLimit=o;const s=c.split(`
139
+ `).slice(1),l=[];for(const p of s)if(!(p.includes("node:internal")||p.includes("internal/modules")||p.includes("internal/process")||p.includes("node_modules")||p.includes(".next/server/chunks")||p.includes("RequestInterceptor")||p.includes("contextManager")||p.includes("setupConfig"))&&(l.push(p.trim()),l.length>=e))break;for(const p of l){const d=this.parseStackFrame(p);d?(async()=>{const{originalPos:h}=await this.getOriginalPosition(d.filePath,d.line,d.column);if(h){a.getConfig().sfDebug&&console.log("[RequestInterceptor] First user code line:",h);const y={line:h.line?.toString()||k.UNKNOWN,column:h.column?.toString()||k.NOT_CAPTURED,name:h.name||k.NOT_CAPTURED,entrypoint:h.source,retryWithoutTraceId:i};t.doSend(y)}})():a.getConfig().sfDebug&&console.error("Could not parse stack line:",p)}}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){return!a.DEFAULT_DOMAINS_TO_EXCLUDE.some(e=>new RegExp(`^${e.replace(/\*/g,".*")}$`).test(t))}addTracingHeaders(t,e){const i=new URL(e).hostname,n=this.shouldPropagateHeaders(i);return n?this.addTracingHeader(t,e):a.getConfig().sfDebug&&console.error(`[RequestInterceptor] Excluded domain: ${i}`),n}addTracingHeader(t,e){const i=g.getFuncspanOverride();if(i){const c=g.parseHeaderOverride(i);if(c&&c.sample_rate===0)return void(a.getConfig().sfDebug&&console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${e}`))}const n=this.contextManager.getOrSetSfTraceId(),o=this.contextManager.getOrSetPageVisitUUID(),f=a.v4();t.set(this.HEADER_TRACING,`${n}/${o}/${f}`),a.getConfig().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${e}`)}patchFetch(t,e){const i=globalThis.fetch;typeof i=="function"?globalThis.fetch=async(n,o)=>{const f=new Headers(o?.headers);if(f.get(this.HEADER_LOG_GUARD)==="true"||f.get(this.HEADER_PRINT_GUARD)==="true"||f.get(this.HEADER_EXCEPTION_GUARD)==="true")return i(n,o);this.captureFirstUserLines(t);const c=Date.now();let s;typeof n=="string"||n instanceof URL?s=n.toString():n instanceof Request?(s=n.url,n.headers.forEach((u,m)=>{f.set(m,u)})):a.getConfig().sfDebug&&console.error("[Sailfish RequestInterceptor] Invalid fetch input."),a.getConfig().sfDebug&&console.log("[RequestInterceptor] Fetching request to:",s);const l=new URL(s).hostname,p=new Headers(f),d=this.addTracingHeaders(f,s),h={...o,headers:f};let y;try{let u=!1;this.addTracingHeaders(p,s),y=await i(s,h),d&&R.includes(y.status)?(y=await i(s,{...o,headers:p}),u=!0,this.captureFirstUserLines(t,10,u)):this.contextManager.addSupportedDomains(l);const m=Date.now();a.getConfig().sfDebug&&console.log(`[RequestInterceptor] Fetch completed: ${s}, Status: ${y.status}, Duration: ${m-c}ms`);const{sessionId:I,pageVisitId:$,requestId:b}=this.extractIdsFromTraceHeader(f),v=a.getConfig(),F={apiKey:v.apiKey,requestId:b,pageVisitId:$,recordingSessionId:I,serviceUuid:v.serviceUUID,timestampStart:c.toString(),timestampEnd:m.toString(),responseCode:y.status,success:!0,error:null,url:s,method:h.method||"GET",retryWithoutTraceId:u,parentSpanId:a.getCurrentFunctionSpanId()};if(v.captureRequestHeaders){const _={};f.forEach((C,D)=>{_[D]=C}),F.requestHeaders=_}if(v.captureResponseHeaders){const _={};y.headers.forEach((C,D)=>{_[D]=C}),F.responseHeaders=_}if(v.captureRequestBody&&o?.body)try{const _=typeof o.body=="string"?o.body:JSON.stringify(o.body);F.requestBody=_.length>v.requestBodyLimitBytes?_.substring(0,v.requestBodyLimitBytes)+"...[truncated]":_}catch{}if(v.captureResponseBody)try{const _=y.clone(),C=await _.text();F.responseBody=C.length>v.responseBodyLimitBytes?C.substring(0,v.responseBodyLimitBytes)+"...[truncated]":C}catch{}return e.doSend(F),y}catch(u){const m=Date.now();a.getConfig().sfDebug&&console.error(`[RequestInterceptor] Fetch failed: ${s}, Error: ${u}, Duration: ${m-c}ms`)}}:a.getConfig().sfDebug&&console.error("[RequestInterceptor] Fetch not available.")}setHeader(t,e,i){t instanceof Headers?t.set(e,i):t[e]=i}addTracingHeadersToPlainObject(t,e){const i=new URL(e).hostname,n=this.shouldPropagateHeaders(i);if(n){const o=g.getFuncspanOverride();if(o){const l=g.parseHeaderOverride(o);if(l&&l.sample_rate===0)return a.getConfig().sfDebug&&console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${e}`),!1}const f=this.contextManager.getOrSetSfTraceId(),c=this.contextManager.getOrSetPageVisitUUID(),s=a.v4();t[this.HEADER_TRACING]=`${f}/${c}/${s}`,a.getConfig().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${e}`)}else a.getConfig().sfDebug&&console.error(`[RequestInterceptor] Excluded domain: ${i}`);return n}patchHttp(t,e){if(a.getConfig().sfDebug&&console.log("[RequestInterceptor] Initializing HTTP/HTTPS request patch..."),!P||typeof P.request!="function")return void(a.getConfig().sfDebug&&console.log("[RequestInterceptor] HTTP/HTTPS not available."));const i=P.request.bind(P),n=E.request.bind(E),o=(s,l,p,d=z)=>{let h,y;if(typeof s=="string"||s instanceof URL){const u=typeof s=="string"?new URL(s):s;h={...typeof l=="object"&&l!==null?l:{},protocol:u.protocol||d,hostname:u.hostname,port:u.port||void 0,path:u.pathname+u.search},y=typeof l=="function"?l:p}else h={...s},h.protocol||(h.protocol=d),y=typeof l=="function"?l:void 0;return h.headers||(h.headers={}),[h,y]},f=(s,l,p)=>{const[d,h]=o(s,l,p,z);try{const u=`${d.protocol}//${d.hostname}`;this.addTracingHeadersToPlainObject(d.headers,u),this.captureFirstUserLines(t)}catch(u){a.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTP request options:",u)}let y=!1;return i(d,u=>{const m=`${d.protocol}//${d.hostname}`;if(this.shouldPropagateHeaders(new URL(m).hostname)&&R.includes(u.statusCode||0)){const v={...d,headers:{...d.headers}};delete v.headers[this.HEADER_TRACING],i(v,h),y=!0,this.captureFirstUserLines(t,10,y)}const{sessionId:I,pageVisitId:$,requestId:b}=this.extractIdsFromTraceHeader(d.headers);e.doSend({apiKey:a.getConfig().apiKey,requestId:b,pageVisitId:$,recordingSessionId:I,serviceUuid:a.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:u.statusCode||0,success:!!u.statusCode&&u.statusCode<400,error:null,url:m,method:d.method||"GET",retryWithoutTraceId:y,parentSpanId:a.getCurrentFunctionSpanId()}),h?.(u)})},c=(s,l,p)=>{const[d,h]=o(s,l,p,"https:");try{const u=`${d.protocol}//${d.hostname}`;this.addTracingHeadersToPlainObject(d.headers,u),this.captureFirstUserLines(t)}catch(u){a.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTPS request options:",u)}let y=!1;return n(d,u=>{const m=`${d.protocol}//${d.hostname}`;if(this.shouldPropagateHeaders(new URL(m).hostname)&&R.includes(u.statusCode||0)){const v={...d,headers:{...d.headers}};delete v.headers[this.HEADER_TRACING],n(v,h),y=!0,this.captureFirstUserLines(t,10,y)}const{sessionId:I,pageVisitId:$,requestId:b}=this.extractIdsFromTraceHeader(d.headers);e.doSend({apiKey:a.getConfig().apiKey,requestId:b,pageVisitId:$,recordingSessionId:I,serviceUuid:a.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:u.statusCode||0,success:!!u.statusCode&&u.statusCode<400,error:null,url:m,method:d.method||"GET",retryWithoutTraceId:y,parentSpanId:a.getCurrentFunctionSpanId()}),h?.(u)})};P.request=f,E.request=c,P.get=(s,l,p)=>{const d=f(s,l,p);return d.end(),d},E.get=(s,l,p)=>{const d=c(s,l,p);return d.end(),d},a.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 _e extends B{constructor(){super(),this.setOperationName("UpdateServiceDetails")}async doSend(){this.sendAppIdentifier(),this.send()}async send(){const t=`
134
140
  ${this.queryType} ${this.operationName}(
135
141
  $apiKey: String!,
136
142
  $serviceUuid: String!,
@@ -147,6 +153,9 @@
147
153
  $infrastructureDetails: JSON,
148
154
  $setupInterceptorsFile: String,
149
155
  $setupInterceptorsLine: Int,
156
+ $framework: String,
157
+ $additionalFrameworks: JSON,
158
+ $serviceRole: String,
150
159
  ) {
151
160
  ${this.queryName}(
152
161
  apiKey: $apiKey,
@@ -164,9 +173,12 @@
164
173
  infrastructureDetails: $infrastructureDetails,
165
174
  setupInterceptorsFile: $setupInterceptorsFile,
166
175
  setupInterceptorsLine: $setupInterceptorsLine,
176
+ framework: $framework,
177
+ additionalFrameworks: $additionalFrameworks,
178
+ serviceRole: $serviceRole,
167
179
  )
168
180
  }
169
- `,t=c.getConfig(),i=this.getVariables({serviceIdentifier:t.serviceIdentifier,serviceVersion:t.serviceVersion,serviceAdditionalMetadata:t.serviceAdditionalMetadata,gitSha:t.gitSha||"",gitOrg:t.gitOrg||void 0,gitRepo:t.gitRepo||void 0,gitProvider:t.gitProvider||void 0,serviceDisplayName:t.serviceDisplayName||void 0,infrastructureType:t.infrastructureType||void 0,infrastructureDetails:t.infrastructureDetails||void 0,setupInterceptorsFile:t.setupInterceptorsFile||void 0,setupInterceptorsLine:t.setupInterceptorsLine||void 0});u.nonBlockingPost(this.endpoint,this.operationName,e,i)}}class $e{rootPaths;fileConfigs=new Map;functionConfigs=new Map;directoryConfigs=new Map;hasSailfishFiles=!1;runtimeModeEnabled=!1;debug;constructor(e=[process.cwd()],t=!1){this.rootPaths=e,this.debug=t||process.env.SF_DEBUG==="true"}async loadAllConfigs(){this.debug&&console.log("[FuncSpan ConfigLoader] Scanning for .sailfish files in:",this.rootPaths);const e=[];for(const t of this.rootPaths)pe.existsSync(t)?await this._walkDirectory(t,e):this.debug&&console.log(`[FuncSpan ConfigLoader] Root path does not exist: ${t}`);e.length>0?(this.hasSailfishFiles=!0,this.debug&&(console.log(`[FuncSpan ConfigLoader] Found ${e.length} .sailfish files:`),e.forEach(t=>console.log(`[FuncSpan ConfigLoader] - ${t}`)))):this.debug&&console.log("[FuncSpan ConfigLoader] No .sailfish files found - function spans disabled by default");for(const t of e)await this._loadConfigFile(t);await this._resolveInheritance(),this.debug&&console.log(`[FuncSpan ConfigLoader] Loaded ${this.fileConfigs.size} file configs, ${this.functionConfigs.size} function configs`)}getConfig(e,t){const i=this.hasSailfishFiles?u.getEnvConfig():u.getDefaultConfig(),n=this._getDirectoryConfig(e),s=F.normalize(e),l=this.fileConfigs.get(s)||{};let o={};if(t){const d=this.functionConfigs.get(s);d&&(o=d.get(t)||{})}return u.mergeConfigs(i,n,l,o)}hasRuntimeMode(){return this.runtimeModeEnabled}async _walkDirectory(e,t){try{const i=await W.readdir(e,{withFileTypes:!0});for(const n of i){const s=F.join(e,n.name);n.isFile()&&n.name===".sailfish"?t.push(s):n.name==="node_modules"||n.isDirectory()&&n.name.startsWith(".")&&n.name!==".sailfish"||n.isDirectory()&&await this._walkDirectory(s,t)}}catch(i){this.debug&&console.error(`[FuncSpan ConfigLoader] Error walking directory ${e}:`,i)}}async _loadConfigFile(e){try{const t=await W.readFile(e,"utf-8"),i=F.dirname(e);let n=null;try{n=JSON.parse(t)}catch{try{n=require("toml").parse(t)}catch{try{n=require("js-yaml").load(t)}catch(s){return void(this.debug&&console.error(`[FuncSpan ConfigLoader] Failed to parse ${e} as JSON, TOML, or YAML:`,s))}}}if(!n)return;n.runtime_mode===!0&&(this.runtimeModeEnabled=!0,this.debug&&console.log(`[FuncSpan ConfigLoader] Runtime mode ENABLED in ${e}`)),n.default&&this.directoryConfigs.set(i,n.default),n.files&&await this._expandFileGlobs(i,n.files,n.default||{}),n.functions&&this._storeFunctionConfigs(i,n.functions,n.default||{}),this.debug&&(console.log(`[FuncSpan ConfigLoader] Loaded config from ${e}`),console.log(`[FuncSpan ConfigLoader] Directory: ${i}`),console.log(`[FuncSpan ConfigLoader] Has default: ${!!n.default}`),console.log(`[FuncSpan ConfigLoader] File patterns: ${Object.keys(n.files||{}).length}`),console.log(`[FuncSpan ConfigLoader] Functions: ${Object.keys(n.functions||{}).length}`))}catch(t){this.debug&&console.error(`[FuncSpan ConfigLoader] Error loading ${e}:`,t)}}async _expandFileGlobs(e,t,i){for(const[n,s]of Object.entries(t))try{const l=F.join(e,n),o=await ue.glob(l,{absolute:!0,nodir:!0,ignore:["**/node_modules/**","**/.git/**"]});this.debug&&console.log(`[FuncSpan ConfigLoader] Pattern '${n}' matched ${o.length} files`);for(const d of o){const a=F.normalize(d),p=u.mergeConfigs(i,s);this.fileConfigs.set(a,p),this.debug&&o.length<=5&&console.log(`[FuncSpan ConfigLoader] - ${d}`)}}catch(l){this.debug&&console.error(`[FuncSpan ConfigLoader] Error expanding glob '${n}':`,l)}}_storeFunctionConfigs(e,t,i){for(const[n,s]of Object.entries(t)){const l=n.split("::");if(l.length!==2){this.debug&&console.warn(`[FuncSpan ConfigLoader] Invalid function pattern '${n}' (expected format: 'file.ts::functionName')`);continue}const[o,d]=l,a=F.normalize(F.join(e,o));this.functionConfigs.has(a)||this.functionConfigs.set(a,new Map);const p=this.functionConfigs.get(a),h=u.mergeConfigs(i,s);p.set(d,h),this.debug&&console.log(`[FuncSpan ConfigLoader] Function config: ${a}::${d}`)}}async _resolveInheritance(){}_getDirectoryConfig(e){let t=F.dirname(F.normalize(e));const i=[];for(;t&&t!==F.dirname(t);){const n=this.directoryConfigs.get(t);n&&i.unshift(n),t=F.dirname(t)}return i.reduce((n,s)=>u.mergeConfigs(n,s),{})}}const oe="__sf_globalConfigLoader";function se(){return globalThis[oe]??null}async function J(r,e){const t=new $e(r,e);(function(i){globalThis[oe]=i})(t),await t.loadAllConfigs()}function V(r,e){const t=se();return t?t.getConfig(r,e):(process.env.SF_DEBUG==="true"&&console.log("[FuncSpan ConfigLoader] Config loader not initialized, using default config (disabled)"),u.getDefaultConfig())}function Q(){return se()!==null}const be=["readFile","writeFile","appendFile","readdir","stat","lstat","fstat","access","open","close","read","write","chmod","mkdir","rmdir","unlink","rename"],X=["lookup","resolve","resolve4","resolve6","resolveAny","resolveMx","resolveNs","resolveTxt","reverse"],Ce=["pbkdf2","randomBytes","scrypt","generateKeyPair"],Fe=["gzip","gunzip","deflate","inflate","deflateRaw","inflateRaw","brotliCompress","brotliDecompress"];let Y=!1;function Ne(r){if(typeof r!="string")return!1;const e=process.env.SF_FUNCSPAN_JSONL_FILE;if(e&&r.includes(e))return!0;const t=process.env.SF_WORKER_POOL_JSONL_FILE;return!(!t||!r.includes(t))}let Z=!1;function ee(r){if(typeof r!="string")return!1;if(r==="localhost"||r==="127.0.0.1"||r==="::1")return!0;try{const e=process.env.API_GRAPHQL_ENDPOINT;if(e&&r===new URL(e).hostname)return!0}catch{}return!1}function De(){if(!Z)try{let r;if(typeof require>"u")return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Skipping dns patching in pure ESM environment (require unavailable)"));try{r=require("node:dns")}catch(e){return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Failed to require dns module:",e))}if(r.__sf_worker_pool_patched__)return;Object.defineProperty(r,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of X)if(typeof r[e]=="function"){const t=r[e];r[e]=function(...i){return u.isSendingInternalTelemetry()?t.apply(this,i):ee(i[0])?t.apply(this,i):typeof i[i.length-1]=="function"?u.captureWorkerPoolOperation("dns",e,t,i,this):t.apply(this,i)},Object.defineProperty(r[e],"name",{value:e,writable:!1})}(function(e){if(!e.promises)return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises not available, skipping"));if(!e.promises.__sf_worker_pool_patched__){Object.defineProperty(e.promises,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of X)if(typeof e.promises[t]=="function"){const i=e.promises[t];e.promises[t]=function(...n){return u.isSendingInternalTelemetry()?i.apply(this,n):ee(n[0])?i.apply(this,n):u.captureWorkerPoolPromiseOperation("dns",t,i,n,this)},Object.defineProperty(e.promises[t],"name",{value:t,writable:!1})}process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises module patched successfully")}})(r),Z=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns module patched successfully")}catch(r){console.error("[WorkerPool] Error patching dns module:",r)}}let te=!1,ne=!1,M=!1;function re(){if(M)return;const r=process.env.SF_DEBUG==="true";r&&console.log("[WorkerPool] Initializing worker pool patching..."),u.isModuleTrackingEnabled("fs")&&(r&&console.log("[WorkerPool] Patching fs module..."),(function(){if(!Y)try{const e=require("node:fs");if(e.__sf_worker_pool_patched__)return;Object.defineProperty(e,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of be)if(typeof e[t]=="function"){const i=e[t];e[t]=function(...n){return Ne(n[0])?i.apply(this,n):typeof n[n.length-1]=="function"?u.captureWorkerPoolOperation("fs",t,i,n,this):i.apply(this,n)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}Y=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] fs module patched successfully")}catch(e){console.error("[WorkerPool] Error patching fs module:",e)}})()),u.isModuleTrackingEnabled("dns")&&(r&&console.log("[WorkerPool] Patching dns module..."),De()),u.isModuleTrackingEnabled("crypto")&&(r&&console.log("[WorkerPool] Patching crypto module..."),(function(){if(!te)try{const e=require("node:crypto");if(e.__sf_worker_pool_patched__)return;Object.defineProperty(e,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Ce)if(typeof e[t]=="function"){const i=e[t];e[t]=function(...n){return typeof n[n.length-1]=="function"?u.captureWorkerPoolOperation("crypto",t,i,n,this):i.apply(this,n)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}te=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] crypto module patched successfully")}catch(e){console.error("[WorkerPool] Error patching crypto module:",e)}})()),u.isModuleTrackingEnabled("zlib")&&(r&&console.log("[WorkerPool] Patching zlib module..."),(function(){if(!ne)try{const e=require("node:zlib");if(e.__sf_worker_pool_patched__)return;Object.defineProperty(e,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Fe)if(typeof e[t]=="function"){const i=e[t];e[t]=function(...n){return typeof n[n.length-1]=="function"?u.captureWorkerPoolOperation("zlib",t,i,n,this):i.apply(this,n)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}ne=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] zlib module patched successfully")}catch(e){console.error("[WorkerPool] Error patching zlib module:",e)}})()),M=!0,r&&console.log("[WorkerPool] Worker pool patching initialized")}function ie(){return M}let k=!1,q=!1,A=null;function T(r){const e=c.getGlobalConfigUnsafe(),t=e?.sfDebug||!1;t&&console.log("[FuncSpan] captureSpanData called for:",{function:r.functionName,file:r.filePath,duration:`${r.duration}ms`,async:r.async,error:r.error,spanId:r.spanId});const i={functionName:r.functionName,filePath:r.filePath,metadata:r.metadata,args:r.args,result:r.result,error:r.error,duration:r.duration,durationNs:r.durationNs,async:r.async,spanId:r.spanId,parentSpanId:r.parentSpanId};process.env.SF_FUNCSPAN_CONSOLE_OUTPUT==="true"&&console.log(`
170
- 📊 Function Span:`,{function:`${r.functionName} (${r.filePath}:${r.metadata.line}:${r.metadata.column})`,duration:`${r.duration.toFixed(2)}ms`,arguments:r.args,result:r.error?`Error: ${r.error}`:r.result,spanId:r.spanId,parentSpanId:r.parentSpanId||"none"});const n=process.env.SF_FUNCSPAN_JSONL_FILE;if(n)try{const s=n==="true"||n==="1"?"funcspans.jsonl":n,l=Date.now(),o=process.hrtime.bigint(),d=BigInt(r.startTimeNs),a=Number(o-d)/1e6,p=new Date(l-a).toISOString(),h=JSON.stringify({timestamp:p,functionName:r.functionName,filePath:r.filePath,line:r.metadata.line,column:r.metadata.column,duration:r.duration,durationNs:r.durationNs,startTimeNs:r.startTimeNs,arguments:r.args,returnValue:r.error?{error:String(r.error)}:r.result,spanId:r.spanId,parentSpanId:r.parentSpanId,async:r.async,pid:r.pid,threadId:r.threadId})+`
171
- `;H.appendFileSync(s,h,"utf-8")}catch(s){console.error("[FuncSpan] Error writing to JSONL file:",s)}if(t&&console.log("[FuncSpan] Sending function span to transmitter:",i),process.env.SF_FUNCSPAN_SKIP_BACKEND!=="true")try{(A||(A=new u.FunctionSpanTransmitter),A).send([i]),t&&console.log("[FuncSpan] Function span sent successfully")}catch(s){t&&console.error("[FuncSpan] Error sending function span:",s)}}exports.ContextManager=c.ContextManager,exports.getCurrentFunctionSpanId=c.getCurrentFunctionSpanId,exports.runWithContext=c.runWithContext,exports.clearFuncspanOverride=u.clearFuncspanOverride,exports.getDefaultConfig=u.getDefaultConfig,exports.getEnvConfig=u.getEnvConfig,exports.getFuncspanOverride=u.getFuncspanOverride,exports.parseHeaderOverride=u.parseHeaderOverride,exports.setFuncspanOverride=u.setFuncspanOverride,exports.isProductionEnvironment=g.isProductionEnvironment,exports.isRuntimeModeEnabled=g.isRuntimeModeEnabled,exports.shouldEnableRuntimeHooks=g.shouldEnableRuntimeHooks,exports.setSkipTypeScriptPlugin=O.setSkipTypeScriptPlugin,exports.transformFunctionSpans=O.transformFunctionSpans,exports.transformFunctionSpansSync=O.transformFunctionSpansSync,exports.addOrUpdateMetadata=function(r,e={},t,i=!1){const n=c.getConfig();new K(n.apiKey).addOrUpdateMetadata(r,e,t,i)},exports.captureFunctionSpan=function(r,e,t,i){const n=function(...s){const l=c.getGlobalConfigUnsafe(),o=l?.sfDebug||!1;o&&console.log(`[FuncSpan] captureFunctionSpan wrapper called for ${t}::${e}`);const d=(function(m,v){const _=u.getFuncspanOverride();if(_){const N=u.parseHeaderOverride(_);if(N)return process.env.SF_DEBUG==="true"&&console.log(`[FuncSpan] Using HTTP header override for ${m}::${v}`),N}try{return V(m,v)}catch{return{sample_rate:process.env.SF_FUNCSPAN_SAMPLE_RATE?parseFloat(process.env.SF_FUNCSPAN_SAMPLE_RATE):1,capture_arguments:!0,capture_return_value:!0,arg_limit_mb:1,return_limit_mb:1,enable_sampling:!1,autocapture_all_child_functions:!1,capture_sf_veritas:!1,parse_json_strings:!1}}})(t,e);if(o&&console.log(`[FuncSpan] Config for ${t}::${e}:`,d),d.enable_sampling&&d.sample_rate<1&&Math.random()>d.sample_rate)return o&&console.log(`[FuncSpan] Skipping ${e} due to sampling`),r.apply(this,s);if(d.sample_rate===0)return o&&console.log(`[FuncSpan] Skipping ${e} - sample_rate is 0.0`),r.apply(this,s);o&&console.log(`[FuncSpan] Capturing function span for ${e}`);const a=c.ContextManager.getInstance(),p=a.getCurrentFunctionSpanId(),h=c.v4();a.setCurrentFunctionSpanId(h);const y=process.hrtime.bigint(),S=Date.now();let f=null;d.capture_arguments&&(f={},i.paramNames.forEach((m,v)=>{v<s.length&&(f[m]=s[v])}),f&&d.arg_limit_mb>0&&(f=u.truncateToLimit(f,d.arg_limit_mb)));try{const m=r.apply(this,s);if(m&&typeof m.then=="function")return p?a.setCurrentFunctionSpanId(p):a.clearCurrentFunctionSpanId(),m.then(b=>{const I=process.hrtime.bigint(),C=Date.now(),D=Number(I-y);let G=null;return d.capture_return_value&&d.return_limit_mb>0&&(G=u.truncateToLimit(b,d.return_limit_mb)),T({functionName:e,filePath:t,metadata:i,args:f,result:G,error:null,duration:C-S,durationNs:D,startTimeNs:y.toString(),async:!0,spanId:h,parentSpanId:p,pid:process.pid,threadId:E.threadId}),b},b=>{const I=process.hrtime.bigint(),C=Date.now(),D=Number(I-y);throw T({functionName:e,filePath:t,metadata:i,args:f,result:null,error:b?.message||String(b),duration:C-S,durationNs:D,startTimeNs:y.toString(),async:!0,spanId:h,parentSpanId:p,pid:process.pid,threadId:E.threadId}),b});const v=process.hrtime.bigint(),_=Date.now(),N=Number(v-y);let $=null;return d.capture_return_value&&d.return_limit_mb>0&&($=u.truncateToLimit(m,d.return_limit_mb)),T({functionName:e,filePath:t,metadata:i,args:f,result:$,error:null,duration:_-S,durationNs:N,startTimeNs:y.toString(),async:!1,spanId:h,parentSpanId:p,pid:process.pid,threadId:E.threadId}),p?a.setCurrentFunctionSpanId(p):a.clearCurrentFunctionSpanId(),m}catch(m){const v=process.hrtime.bigint(),_=Date.now(),N=Number(v-y);throw T({functionName:e,filePath:t,metadata:i,args:f,result:null,error:m?.message||String(m),duration:_-S,durationNs:N,startTimeNs:y.toString(),async:!1,spanId:h,parentSpanId:p,pid:process.pid,threadId:E.threadId}),p?a.setCurrentFunctionSpanId(p):a.clearCurrentFunctionSpanId(),m}};Object.defineProperty(n,"name",{value:e,writable:!1});for(const s in r)r.hasOwnProperty(s)&&(n[s]=r[s]);return n},exports.getGlobalConfig=V,exports.identify=function(r,e,t,i=!1){const n=c.getConfig();new K(n.apiKey).identify(r,e,t,i)},exports.initializeConfigLoader=J,exports.initializeWorkerPoolPatching=re,exports.isAlreadyInstrumented=function(r){return!!r.includes("captureFunctionSpan(")||!!r.includes("@sailfish-ai/sf-veritas")||!(!r.includes("/* @sailfish-instrumented */")&&!r.includes("// @sailfish-instrumented"))},exports.isConfigLoaderInitialized=Q,exports.isSetupInterceptorsInitialized=function(){return k},exports.isWorkerPoolInitialized=ie,exports.setupInterceptors=function(r){if(q)console.warn("[setupInterceptors] ⚠️ Recursive call detected and blocked!");else if(!k){q=!0;try{let e,t;const i=g.stackToString(new Error().stack);if(i){const o=i.split(`
172
- `)[2]||"",d=o.match(/\((.+):(\d+):\d+\)/)||o.match(/at (.+):(\d+):\d+/);d&&(e=d[1],t=parseInt(d[2],10))}if(!r||!r.apiKey){const o=`The required API Key is not provided: ${JSON.stringify(r)}`;console.error(o)}const{config:n}=c.getOrCreateConfig(r);if(c.backfillGitInfoAsync(n).catch(()=>{}),e&&(n.setupInterceptorsFile=e),t&&(n.setupInterceptorsLine=t),n.sfDebug&&console.log("Updated configuration after applying options:",n),!n.apiKey||!n.apiGraphqlEndpoint){const o=`The required config is not provided: ${JSON.stringify(n)}`;throw console.error(o),new Error(o)}Q()||J(void 0,n.sfDebug).catch(o=>{n.sfDebug&&console.error("[FuncSpan] Failed to initialize config loader:",o)}),process.env.SF_WORKER_POOL_DISABLED==="true"?n.sfDebug&&console.log("[setupInterceptors] Worker pool patching DISABLED (SF_WORKER_POOL_DISABLED=true)"):ie()||(re(),n.sfDebug&&console.log("[setupInterceptors] Worker pool patching initialized (DNS tracking enabled)"));const s=new B;s.setServiceUUID(n.serviceUUID),g.initializeLogInterceptor(s),(function(o=[]){const d=new ve(o);new ye().doSend(d.getExcludedDomains());const a=new Se,p=new Ie;d.patchFetch(a,p),d.patchHttp(a,p)})(n.domainsToNotPropagateHeadersTo);const l=new fe;l.setServiceUUID(n.serviceUUID),g.initializeExceptionInterceptor(l),me(),new _e().send(),k=!0,n.sfDebug&&console.log("[setupInterceptors] ✅ Initialization complete")}finally{q=!1}}};
181
+ `,e=a.getConfig(),i=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});g.nonBlockingPost(this.endpoint,this.operationName,t,i)}}class be{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)ge.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 i=this.hasSailfishFiles?g.getEnvConfig():g.getDefaultConfig(),n=this._getDirectoryConfig(t),o=N.normalize(t),f=this.fileConfigs.get(o)||{};let c={};if(e){const s=this.functionConfigs.get(o);s&&(c=s.get(e)||{})}return g.mergeConfigs(i,n,f,c)}hasRuntimeMode(){return this.runtimeModeEnabled}async _walkDirectory(t,e){try{const i=await W.readdir(t,{withFileTypes:!0});for(const n of i){const o=N.join(t,n.name);n.isFile()&&n.name===".sailfish"?e.push(o):n.name==="node_modules"||n.isDirectory()&&n.name.startsWith(".")&&n.name!==".sailfish"||n.isDirectory()&&await this._walkDirectory(o,e)}}catch(i){this.debug&&console.error(`[FuncSpan ConfigLoader] Error walking directory ${t}:`,i)}}async _loadConfigFile(t){try{const e=await W.readFile(t,"utf-8"),i=N.dirname(t);let n=null;try{n=JSON.parse(e)}catch{try{n=require("toml").parse(e)}catch{try{n=require("js-yaml").load(e)}catch(o){return void(this.debug&&console.error(`[FuncSpan ConfigLoader] Failed to parse ${t} as JSON, TOML, or YAML:`,o))}}}if(!n)return;n.runtime_mode===!0&&(this.runtimeModeEnabled=!0,this.debug&&console.log(`[FuncSpan ConfigLoader] Runtime mode ENABLED in ${t}`)),n.default&&this.directoryConfigs.set(i,n.default),n.files&&await this._expandFileGlobs(i,n.files,n.default||{}),n.functions&&this._storeFunctionConfigs(i,n.functions,n.default||{}),this.debug&&(console.log(`[FuncSpan ConfigLoader] Loaded config from ${t}`),console.log(`[FuncSpan ConfigLoader] Directory: ${i}`),console.log(`[FuncSpan ConfigLoader] Has default: ${!!n.default}`),console.log(`[FuncSpan ConfigLoader] File patterns: ${Object.keys(n.files||{}).length}`),console.log(`[FuncSpan ConfigLoader] Functions: ${Object.keys(n.functions||{}).length}`))}catch(e){this.debug&&console.error(`[FuncSpan ConfigLoader] Error loading ${t}:`,e)}}async _expandFileGlobs(t,e,i){for(const[n,o]of Object.entries(e))try{const f=N.join(t,n),c=await pe.glob(f,{absolute:!0,nodir:!0,ignore:["**/node_modules/**","**/.git/**"]});this.debug&&console.log(`[FuncSpan ConfigLoader] Pattern '${n}' matched ${c.length} files`);for(const s of c){const l=N.normalize(s),p=g.mergeConfigs(i,o);this.fileConfigs.set(l,p),this.debug&&c.length<=5&&console.log(`[FuncSpan ConfigLoader] - ${s}`)}}catch(f){this.debug&&console.error(`[FuncSpan ConfigLoader] Error expanding glob '${n}':`,f)}}_storeFunctionConfigs(t,e,i){for(const[n,o]of Object.entries(e)){const f=n.split("::");if(f.length!==2){this.debug&&console.warn(`[FuncSpan ConfigLoader] Invalid function pattern '${n}' (expected format: 'file.ts::functionName')`);continue}const[c,s]=f,l=N.normalize(N.join(t,c));this.functionConfigs.has(l)||this.functionConfigs.set(l,new Map);const p=this.functionConfigs.get(l),d=g.mergeConfigs(i,o);p.set(s,d),this.debug&&console.log(`[FuncSpan ConfigLoader] Function config: ${l}::${s}`)}}async _resolveInheritance(){}_getDirectoryConfig(t){let e=N.dirname(N.normalize(t));const i=[];for(;e&&e!==N.dirname(e);){const n=this.directoryConfigs.get(e);n&&i.unshift(n),e=N.dirname(e)}return i.reduce((n,o)=>g.mergeConfigs(n,o),{})}}const se="__sf_globalConfigLoader";function ae(){return globalThis[se]??null}async function V(r,t){const e=new be(r,t);(function(i){globalThis[se]=i})(e),await e.loadAllConfigs()}function Q(r,t){const e=ae();return e?e.getConfig(r,t):(process.env.SF_DEBUG==="true"&&console.log("[FuncSpan ConfigLoader] Config loader not initialized, using default config (disabled)"),g.getDefaultConfig())}function X(){return ae()!==null}const Fe=["readFile","writeFile","appendFile","readdir","stat","lstat","fstat","access","open","close","read","write","chmod","mkdir","rmdir","unlink","rename"],Y=["lookup","resolve","resolve4","resolve6","resolveAny","resolveMx","resolveNs","resolveTxt","reverse"],Ce=["pbkdf2","randomBytes","scrypt","generateKeyPair"],Ne=["gzip","gunzip","deflate","inflate","deflateRaw","inflateRaw","brotliCompress","brotliDecompress"];let Z=!1;function De(r){if(typeof r!="string")return!1;const t=process.env.SF_FUNCSPAN_JSONL_FILE;if(t&&r.includes(t))return!0;const e=process.env.SF_WORKER_POOL_JSONL_FILE;return!(!e||!r.includes(e))}let ee=!1;function te(r){if(typeof r!="string")return!1;if(r==="localhost"||r==="127.0.0.1"||r==="::1")return!0;try{const t=process.env.API_GRAPHQL_ENDPOINT;if(t&&r===new URL(t).hostname)return!0}catch{}return!1}function Pe(){if(!ee)try{let r;if(typeof require>"u")return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Skipping dns patching in pure ESM environment (require unavailable)"));try{r=require("node:dns")}catch(t){return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Failed to require dns module:",t))}if(r.__sf_worker_pool_patched__)return;Object.defineProperty(r,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Y)if(typeof r[t]=="function"){const e=r[t];r[t]=function(...i){return g.isSendingInternalTelemetry()?e.apply(this,i):te(i[0])?e.apply(this,i):typeof i[i.length-1]=="function"?g.captureWorkerPoolOperation("dns",t,e,i,this):e.apply(this,i)},Object.defineProperty(r[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 Y)if(typeof t.promises[e]=="function"){const i=t.promises[e];t.promises[e]=function(...n){return g.isSendingInternalTelemetry()?i.apply(this,n):te(n[0])?i.apply(this,n):g.captureWorkerPoolPromiseOperation("dns",e,i,n,this)},Object.defineProperty(t.promises[e],"name",{value:e,writable:!1})}process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises module patched successfully")}})(r),ee=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns module patched successfully")}catch(r){console.error("[WorkerPool] Error patching dns module:",r)}}let ne=!1,re=!1,M=!1;function ie(){if(M)return;const r=process.env.SF_DEBUG==="true";r&&console.log("[WorkerPool] Initializing worker pool patching..."),g.isModuleTrackingEnabled("fs")&&(r&&console.log("[WorkerPool] Patching fs module..."),(function(){if(!Z)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 Fe)if(typeof t[e]=="function"){const i=t[e];t[e]=function(...n){return De(n[0])?i.apply(this,n):typeof n[n.length-1]=="function"?g.captureWorkerPoolOperation("fs",e,i,n,this):i.apply(this,n)},Object.defineProperty(t[e],"name",{value:e,writable:!1})}Z=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] fs module patched successfully")}catch(t){console.error("[WorkerPool] Error patching fs module:",t)}})()),g.isModuleTrackingEnabled("dns")&&(r&&console.log("[WorkerPool] Patching dns module..."),Pe()),g.isModuleTrackingEnabled("crypto")&&(r&&console.log("[WorkerPool] Patching crypto module..."),(function(){if(!ne)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 Ce)if(typeof t[e]=="function"){const i=t[e];t[e]=function(...n){return typeof n[n.length-1]=="function"?g.captureWorkerPoolOperation("crypto",e,i,n,this):i.apply(this,n)},Object.defineProperty(t[e],"name",{value:e,writable:!1})}ne=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] crypto module patched successfully")}catch(t){console.error("[WorkerPool] Error patching crypto module:",t)}})()),g.isModuleTrackingEnabled("zlib")&&(r&&console.log("[WorkerPool] Patching zlib module..."),(function(){if(!re)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 Ne)if(typeof t[e]=="function"){const i=t[e];t[e]=function(...n){return typeof n[n.length-1]=="function"?g.captureWorkerPoolOperation("zlib",e,i,n,this):i.apply(this,n)},Object.defineProperty(t[e],"name",{value:e,writable:!1})}re=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] zlib module patched successfully")}catch(t){console.error("[WorkerPool] Error patching zlib module:",t)}})()),M=!0,r&&console.log("[WorkerPool] Worker pool patching initialized")}function oe(){return M}let U=!1,A=!1,q=null;function O(r){const t=a.getGlobalConfigUnsafe(),e=t?.sfDebug||!1;e&&console.log("[FuncSpan] captureSpanData called for:",{function:r.functionName,file:r.filePath,duration:`${r.duration}ms`,async:r.async,error:r.error,spanId:r.spanId});const i={functionName:r.functionName,filePath:r.filePath,metadata:r.metadata,args:r.args,result:r.result,error:r.error,duration:r.duration,durationNs:r.durationNs,async:r.async,spanId:r.spanId,parentSpanId:r.parentSpanId};process.env.SF_FUNCSPAN_CONSOLE_OUTPUT==="true"&&console.log(`
182
+ 📊 Function Span:`,{function:`${r.functionName} (${r.filePath}:${r.metadata.line}:${r.metadata.column})`,duration:`${r.duration.toFixed(2)}ms`,arguments:r.args,result:r.error?`Error: ${r.error}`:r.result,spanId:r.spanId,parentSpanId:r.parentSpanId||"none"});const n=process.env.SF_FUNCSPAN_JSONL_FILE;if(n)try{const o=n==="true"||n==="1"?"funcspans.jsonl":n,f=Date.now(),c=process.hrtime.bigint(),s=BigInt(r.startTimeNs),l=Number(c-s)/1e6,p=new Date(f-l).toISOString(),d=JSON.stringify({timestamp:p,functionName:r.functionName,filePath:r.filePath,line:r.metadata.line,column:r.metadata.column,duration:r.duration,durationNs:r.durationNs,startTimeNs:r.startTimeNs,arguments:r.args,returnValue:r.error?{error:String(r.error)}:r.result,spanId:r.spanId,parentSpanId:r.parentSpanId,async:r.async,pid:r.pid,threadId:r.threadId})+`
183
+ `;H.appendFileSync(o,d,"utf-8")}catch(o){console.error("[FuncSpan] Error writing to JSONL file:",o)}if(e&&console.log("[FuncSpan] Sending function span to transmitter:",i),process.env.SF_FUNCSPAN_SKIP_BACKEND!=="true")try{(q||(q=new g.FunctionSpanTransmitter),q).send([i]),e&&console.log("[FuncSpan] Function span sent successfully")}catch(o){e&&console.error("[FuncSpan] Error sending function span:",o)}}exports.ContextManager=a.ContextManager,exports.getCurrentFunctionSpanId=a.getCurrentFunctionSpanId,exports.runWithContext=a.runWithContext,exports.clearFuncspanOverride=g.clearFuncspanOverride,exports.getDefaultConfig=g.getDefaultConfig,exports.getEnvConfig=g.getEnvConfig,exports.getFuncspanOverride=g.getFuncspanOverride,exports.parseHeaderOverride=g.parseHeaderOverride,exports.setFuncspanOverride=g.setFuncspanOverride,exports.isProductionEnvironment=S.isProductionEnvironment,exports.isRuntimeModeEnabled=S.isRuntimeModeEnabled,exports.shouldEnableRuntimeHooks=S.shouldEnableRuntimeHooks,exports.setSkipTypeScriptPlugin=L.setSkipTypeScriptPlugin,exports.transformFunctionSpans=L.transformFunctionSpans,exports.transformFunctionSpansSync=L.transformFunctionSpansSync,exports.addOrUpdateMetadata=function(r,t={},e,i=!1){const n=a.getConfig();new K(n.apiKey).addOrUpdateMetadata(r,t,e,i)},exports.captureFunctionSpan=function(r,t,e,i){const n=function(...o){const f=a.getGlobalConfigUnsafe(),c=f?.sfDebug||!1;c&&console.log(`[FuncSpan] captureFunctionSpan wrapper called for ${e}::${t}`);const s=(function(m,I){const $=g.getFuncspanOverride();if($){const b=g.parseHeaderOverride($);if(b)return process.env.SF_DEBUG==="true"&&console.log(`[FuncSpan] Using HTTP header override for ${m}::${I}`),b}try{return Q(m,I)}catch{return{sample_rate:process.env.SF_FUNCSPAN_SAMPLE_RATE?parseFloat(process.env.SF_FUNCSPAN_SAMPLE_RATE):1,capture_arguments:!0,capture_return_value:!0,arg_limit_mb:1,return_limit_mb:1,enable_sampling:!1,autocapture_all_child_functions:!1,capture_sf_veritas:!1,parse_json_strings:!1}}})(e,t);if(c&&console.log(`[FuncSpan] Config for ${e}::${t}:`,s),s.enable_sampling&&s.sample_rate<1&&Math.random()>s.sample_rate)return c&&console.log(`[FuncSpan] Skipping ${t} due to sampling`),r.apply(this,o);if(s.sample_rate===0)return c&&console.log(`[FuncSpan] Skipping ${t} - sample_rate is 0.0`),r.apply(this,o);c&&console.log(`[FuncSpan] Capturing function span for ${t}`);const l=a.ContextManager.getInstance(),p=l.getCurrentFunctionSpanId(),d=a.v4();l.setCurrentFunctionSpanId(d);const h=process.hrtime.bigint(),y=Date.now();let u=null;s.capture_arguments&&(u={},i.paramNames.forEach((m,I)=>{I<o.length&&(u[m]=o[I])}),u&&s.arg_limit_mb>0&&(u=g.truncateToLimit(u,s.arg_limit_mb)));try{const m=r.apply(this,o);if(m&&typeof m.then=="function")return p?l.setCurrentFunctionSpanId(p):l.clearCurrentFunctionSpanId(),m.then(F=>{const _=process.hrtime.bigint(),C=Date.now(),D=Number(_-h);let G=null;return s.capture_return_value&&s.return_limit_mb>0&&(G=g.truncateToLimit(F,s.return_limit_mb)),O({functionName:t,filePath:e,metadata:i,args:u,result:G,error:null,duration:C-y,durationNs:D,startTimeNs:h.toString(),async:!0,spanId:d,parentSpanId:p,pid:process.pid,threadId:T.threadId}),F},F=>{const _=process.hrtime.bigint(),C=Date.now(),D=Number(_-h);throw O({functionName:t,filePath:e,metadata:i,args:u,result:null,error:F?.message||String(F),duration:C-y,durationNs:D,startTimeNs:h.toString(),async:!0,spanId:d,parentSpanId:p,pid:process.pid,threadId:T.threadId}),F});const I=process.hrtime.bigint(),$=Date.now(),b=Number(I-h);let v=null;return s.capture_return_value&&s.return_limit_mb>0&&(v=g.truncateToLimit(m,s.return_limit_mb)),O({functionName:t,filePath:e,metadata:i,args:u,result:v,error:null,duration:$-y,durationNs:b,startTimeNs:h.toString(),async:!1,spanId:d,parentSpanId:p,pid:process.pid,threadId:T.threadId}),p?l.setCurrentFunctionSpanId(p):l.clearCurrentFunctionSpanId(),m}catch(m){const I=process.hrtime.bigint(),$=Date.now(),b=Number(I-h);throw O({functionName:t,filePath:e,metadata:i,args:u,result:null,error:m?.message||String(m),duration:$-y,durationNs:b,startTimeNs:h.toString(),async:!1,spanId:d,parentSpanId:p,pid:process.pid,threadId:T.threadId}),p?l.setCurrentFunctionSpanId(p):l.clearCurrentFunctionSpanId(),m}};Object.defineProperty(n,"name",{value:t,writable:!1});for(const o in r)r.hasOwnProperty(o)&&(n[o]=r[o]);return n},exports.getGlobalConfig=Q,exports.identify=function(r,t,e,i=!1){const n=a.getConfig();new K(n.apiKey).identify(r,t,e,i)},exports.initializeConfigLoader=V,exports.initializeWorkerPoolPatching=ie,exports.isAlreadyInstrumented=function(r){return!!r.includes("captureFunctionSpan(")||!!r.includes("@sailfish-ai/sf-veritas")||!(!r.includes("/* @sailfish-instrumented */")&&!r.includes("// @sailfish-instrumented"))},exports.isConfigLoaderInitialized=X,exports.isSetupInterceptorsInitialized=function(){return U},exports.isWorkerPoolInitialized=oe,exports.setupInterceptors=function(r){if(A)console.warn("[setupInterceptors] ⚠️ Recursive call detected and blocked!");else if(!U){A=!0;try{let t,e;const i=S.stackToString(new Error().stack);if(i){const c=i.split(`
184
+ `)[2]||"",s=c.match(/\((.+):(\d+):\d+\)/)||c.match(/at (.+):(\d+):\d+/);s&&(t=s[1],e=parseInt(s[2],10))}if(!r||!r.apiKey){const c=`The required API Key is not provided: ${JSON.stringify(r)}`;console.error(c)}const{config:n}=a.getOrCreateConfig(r);if(a.backfillGitInfoAsync(n).catch(()=>{}),t&&(n.setupInterceptorsFile=t),e&&(n.setupInterceptorsLine=e),n.sfDebug&&console.log("Updated configuration after applying options:",n),!n.apiKey||!n.apiGraphqlEndpoint){const c=`The required config is not provided: ${JSON.stringify(n)}`;throw console.error(c),new Error(c)}X()||V(void 0,n.sfDebug).catch(c=>{n.sfDebug&&console.error("[FuncSpan] Failed to initialize config loader:",c)}),process.env.SF_WORKER_POOL_DISABLED==="true"?n.sfDebug&&console.log("[setupInterceptors] Worker pool patching DISABLED (SF_WORKER_POOL_DISABLED=true)"):oe()||(ie(),n.sfDebug&&console.log("[setupInterceptors] Worker pool patching initialized (DNS tracking enabled)"));const o=new B;o.setServiceUUID(n.serviceUUID),S.initializeLogInterceptor(o),(function(c=[]){const s=new $e(c);new Se().doSend(s.getExcludedDomains());const l=new ve,p=new Ie;s.patchFetch(l,p),s.patchHttp(l,p)})(n.domainsToNotPropagateHeadersTo);const f=new he;f.setServiceUUID(n.serviceUUID),S.initializeExceptionInterceptor(f),ye(),new _e().send(),U=!0,n.sfDebug&&console.log("[setupInterceptors] ✅ Initialization complete")}finally{A=!1}}};