@sailfish-ai/sf-veritas 0.3.0 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +88 -0
- package/dist/{contextManager-RxrMXs5c.js → contextManager-CZy0w11U.js} +118 -114
- package/dist/contextManager-qXvO_a5y.cjs +1 -0
- package/dist/plugins/funcspanEsbuildPlugin.cjs +1 -1
- package/dist/plugins/funcspanEsbuildPlugin.mjs +1 -1
- package/dist/plugins/funcspanRollupPlugin.cjs +1 -1
- package/dist/plugins/funcspanRollupPlugin.mjs +1 -1
- package/dist/plugins/funcspanTscPlugin.cjs +1 -1
- package/dist/plugins/funcspanTscPlugin.mjs +1 -1
- package/dist/plugins/funcspanVitePlugin.cjs +1 -1
- package/dist/plugins/funcspanVitePlugin.mjs +1 -1
- package/dist/plugins/funcspanWebpackPlugin.cjs +1 -1
- package/dist/plugins/funcspanWebpackPlugin.mjs +1 -1
- package/dist/{runtimeConfig-BZ61efqE.js → runtimeConfig-ButdW4zP.js} +329 -340
- package/dist/runtimeConfig-C4_zc4Zg.cjs +5 -0
- package/dist/sf-veritas.cjs +13 -13
- package/dist/sf-veritas.mjs +590 -424
- package/dist/types/constants.d.ts +7 -0
- package/dist/types/requestTransmitter.d.ts +75 -0
- package/dist/types/setupConfig.d.ts +39 -0
- package/dist/types/urlMatch.d.ts +19 -0
- package/dist/worker-pool-capture.cjs +1 -1
- package/dist/worker-pool-capture.mjs +1 -1
- package/dist/{workerPoolSpanCapture-Bg5av6gn.cjs → workerPoolSpanCapture-BUFN_RMW.cjs} +1 -1
- package/dist/{workerPoolSpanCapture-BjdZn3LE.js → workerPoolSpanCapture-BomWTMM2.js} +1 -1
- package/package.json +17 -1
- package/dist/contextManager-0D8uHQ1_.cjs +0 -1
- package/dist/runtimeConfig-CWpFWsmz.cjs +0 -6
|
@@ -3,6 +3,13 @@
|
|
|
3
3
|
* for a request (e.g., during stack trace or debugging).
|
|
4
4
|
*/
|
|
5
5
|
export declare const TRACE_HEADER = "x-sf3-rid";
|
|
6
|
+
/**
|
|
7
|
+
* Outbound parent-trace header (mirrors Python's PARENT_SESSION_ID_HEADER).
|
|
8
|
+
* Carries the FULL inbound trace id (3 segments) so server-side code can
|
|
9
|
+
* reconstruct the parent chain even though outbound X-Sf3-Rid uses a
|
|
10
|
+
* freshly-generated per-request UUID as its last segment.
|
|
11
|
+
*/
|
|
12
|
+
export declare const PARENT_TRACE_HEADER = "X-Sf4-Prid";
|
|
6
13
|
export declare const REQUEST_SOURCE_CODE_ERROR = "getting request source code";
|
|
7
14
|
/**
|
|
8
15
|
* Common constant values used across the application.
|
|
@@ -1 +1,76 @@
|
|
|
1
|
+
import { NetworkHopTransmitter } from "./networkHopTransmitter";
|
|
2
|
+
import { NetworkRequestTransmitter } from "./networkRequestTransmitter";
|
|
3
|
+
export declare class RequestInterceptor {
|
|
4
|
+
private readonly HEADER_TRACING;
|
|
5
|
+
private readonly HEADER_LOG_GUARD;
|
|
6
|
+
private readonly HEADER_PRINT_GUARD;
|
|
7
|
+
private readonly HEADER_EXCEPTION_GUARD;
|
|
8
|
+
private contextManager;
|
|
9
|
+
constructor(excludedDomains?: string[]);
|
|
10
|
+
private extractIdsFromTraceHeader;
|
|
11
|
+
private parseStackFrame;
|
|
12
|
+
/**
|
|
13
|
+
* Attempts to map a transpiled file location (line/column) back to the original source
|
|
14
|
+
* using the .map file. If the .map file is missing or cannot be parsed,
|
|
15
|
+
* returns a fallback original position constructed from the input parameters.
|
|
16
|
+
*
|
|
17
|
+
* @param bundlePath - The path to the transpiled bundle (e.g. ".next/server/chunks/106.js")
|
|
18
|
+
* @param line - The transpiled line number from a stack trace or instrumentation
|
|
19
|
+
* @param column - The transpiled column number
|
|
20
|
+
* @param count - How many context lines to retrieve in the source snippet
|
|
21
|
+
* @returns An object containing:
|
|
22
|
+
* - originalPos: the mapped original position (or fallback if unavailable)
|
|
23
|
+
* - snippet: an array of source code lines around the mapped position, or null
|
|
24
|
+
*/
|
|
25
|
+
private getOriginalPosition;
|
|
26
|
+
private captureFirstUserLines;
|
|
27
|
+
private addReentrancyGuardHeaders;
|
|
28
|
+
/**
|
|
29
|
+
* Decide whether the tracing header should be propagated for an
|
|
30
|
+
* outbound request to `url`. As of 0.3.2 this consults THREE lists:
|
|
31
|
+
*
|
|
32
|
+
* - allow: `SetupOptions.domainsToPropagateHeadersTo` (default `["*"]`)
|
|
33
|
+
* - deny: `SetupOptions.domainsToNotPropagateHeadersTo` (default `[]`)
|
|
34
|
+
* - builtin defaults: `DEFAULT_DOMAINS_TO_EXCLUDE`
|
|
35
|
+
*
|
|
36
|
+
* Deny wins on conflict:
|
|
37
|
+
*
|
|
38
|
+
* propagate = matches(url, allow)
|
|
39
|
+
* && NOT matches(url, deny)
|
|
40
|
+
* && NOT matches(url, defaults)
|
|
41
|
+
*
|
|
42
|
+
* Wildcard syntax is the same as jsts-frontend
|
|
43
|
+
* (`*`, `*.example.com`, `example.com/api/*`, `host:8080`).
|
|
44
|
+
*/
|
|
45
|
+
private shouldPropagateHeaders;
|
|
46
|
+
addTracingHeaders(headers: Headers, url: string): boolean;
|
|
47
|
+
/**
|
|
48
|
+
* Given a stored trace id (either Session-based `session/page/req`
|
|
49
|
+
* or nonsession-applogs `nonsession-applogs-v3/<apiKey>/<uuid>`),
|
|
50
|
+
* return the outbound header values per Python's
|
|
51
|
+
* `thread_local.py:1349` contract:
|
|
52
|
+
*
|
|
53
|
+
* X-Sf3-Rid = <first-2-segments-of-trace>/<fresh-uuid> (3 segs)
|
|
54
|
+
* X-Sf4-Prid = <full-trace-id> (parent)
|
|
55
|
+
*
|
|
56
|
+
* Fallback when the stored trace has fewer than 2 segments
|
|
57
|
+
* (a user-set 1-segment trace — rare): base = full trace.
|
|
58
|
+
*/
|
|
59
|
+
private deriveTraceBaseAndParent;
|
|
60
|
+
private addTracingHeader;
|
|
61
|
+
patchFetch(networkHopTransmitter: NetworkHopTransmitter, networkRequestTransmitter: NetworkRequestTransmitter): void;
|
|
62
|
+
/**
|
|
63
|
+
* Set a header on either a plain object (OutgoingHttpHeaders) or a Headers instance.
|
|
64
|
+
*/
|
|
65
|
+
private setHeader;
|
|
66
|
+
/**
|
|
67
|
+
* Add tracing headers to plain-object headers (used by http/https patches).
|
|
68
|
+
* Unlike addTracingHeaders() which expects a Headers instance, this works
|
|
69
|
+
* with the Record<string, string> style headers used by http.request().
|
|
70
|
+
*/
|
|
71
|
+
private addTracingHeadersToPlainObject;
|
|
72
|
+
patchHttp(networkHopTransmitter: NetworkHopTransmitter, networkRequestTransmitter: NetworkRequestTransmitter): void;
|
|
73
|
+
tryPatch(patchFunction: () => void, packageName: string): void;
|
|
74
|
+
getExcludedDomains(): string[];
|
|
75
|
+
}
|
|
1
76
|
export declare function patchRequests(domainsToNotPropagateHeadersTo?: string[]): void;
|
|
@@ -72,10 +72,47 @@ export interface SetupOptions {
|
|
|
72
72
|
* Optional list of domains for which headers should not be propagated.
|
|
73
73
|
*/
|
|
74
74
|
domainsToNotPropagateHeadersTo?: string[];
|
|
75
|
+
/**
|
|
76
|
+
* Optional allowlist of domains to which the tracing header WILL be
|
|
77
|
+
* propagated. Supports the same wildcard syntax as the jsts-frontend
|
|
78
|
+
* matcher: `"*"`, `"*.example.com"`, `"api.example.com:8080"`,
|
|
79
|
+
* `"api.example.com/v1/*"`, etc.
|
|
80
|
+
*
|
|
81
|
+
* Default: `["*"]` — allow all (preserves pre-0.3.2 behavior).
|
|
82
|
+
* Set to `[]` to block every outbound request from receiving the
|
|
83
|
+
* tracing header.
|
|
84
|
+
*
|
|
85
|
+
* Interaction with the deny-list (`domainsToNotPropagateHeadersTo`
|
|
86
|
+
* + built-in defaults): the deny-list wins. A request's header is
|
|
87
|
+
* propagated iff:
|
|
88
|
+
*
|
|
89
|
+
* matches(allowlist) AND NOT matches(denylist) AND NOT matches(defaults)
|
|
90
|
+
*/
|
|
91
|
+
domainsToPropagateHeadersTo?: string[];
|
|
75
92
|
/**
|
|
76
93
|
* Optional list of site and distribution packages for which local variables should be collected.
|
|
77
94
|
*/
|
|
78
95
|
nodeModulesToCollectLocalVariablesOn?: string[];
|
|
96
|
+
/**
|
|
97
|
+
* How to handle 400/403 responses on requests carrying our tracing
|
|
98
|
+
* header (X-Sf3-Rid). When a server rejects a request that carried
|
|
99
|
+
* the header, Sailfish can retry the request ONCE without the
|
|
100
|
+
* header so the customer's call succeeds transparently.
|
|
101
|
+
*
|
|
102
|
+
* - 'all' (default) — retry once without the tracing header for
|
|
103
|
+
* every method. Most transparent; matches pre-0.3.1 behavior.
|
|
104
|
+
* Recommended for backends that reject unknown headers at the
|
|
105
|
+
* edge (API gateways / WAFs) before any business logic runs.
|
|
106
|
+
* - 'idempotent' — retry only GET/HEAD/OPTIONS. Safer for
|
|
107
|
+
* backends that may commit side effects before returning 4xx
|
|
108
|
+
* (payment processors, booking systems, inventory APIs).
|
|
109
|
+
* - 'none' — never retry; callers see the original 4xx directly.
|
|
110
|
+
*
|
|
111
|
+
* If a specific domain consistently rejects the tracing header,
|
|
112
|
+
* prefer adding it to `domainsToNotPropagateHeadersTo` — that
|
|
113
|
+
* avoids the first 4xx round-trip entirely.
|
|
114
|
+
*/
|
|
115
|
+
retryOnClientError?: "all" | "idempotent" | "none";
|
|
79
116
|
}
|
|
80
117
|
export interface GetOrCreateConfig {
|
|
81
118
|
config: AppConfig;
|
|
@@ -92,6 +129,7 @@ declare class AppConfig {
|
|
|
92
129
|
profilingMaxDepth: number;
|
|
93
130
|
profilingMaxVariableSizeKb: number;
|
|
94
131
|
domainsToNotPropagateHeadersTo?: string[];
|
|
132
|
+
domainsToPropagateHeadersTo: string[];
|
|
95
133
|
nodeModulesToCollectLocalVariablesOn: string[];
|
|
96
134
|
printConfigurationStatuses: string;
|
|
97
135
|
logLevel: string;
|
|
@@ -118,6 +156,7 @@ declare class AppConfig {
|
|
|
118
156
|
captureResponseBody: boolean;
|
|
119
157
|
requestBodyLimitBytes: number;
|
|
120
158
|
responseBodyLimitBytes: number;
|
|
159
|
+
retryOnClientError: "all" | "idempotent" | "none";
|
|
121
160
|
private _serviceIdentificationReceived;
|
|
122
161
|
constructor(options: SetupOptions);
|
|
123
162
|
private getPackageVersion;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Returns true if `input` (a URL string, URL object, or object with a
|
|
3
|
+
* `.toString()`) matches any of the given wildcard `patterns`.
|
|
4
|
+
*
|
|
5
|
+
* Non-http(s) URLs and unparseable inputs return false.
|
|
6
|
+
* Null / empty patterns are skipped.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* matchUrlWithWildcard("https://api.example.com/v1/users", ["*.example.com"]) === true
|
|
10
|
+
* matchUrlWithWildcard("https://other.org", ["*.example.com"]) === false
|
|
11
|
+
* matchUrlWithWildcard("https://example.com:8080/", ["example.com:8080"]) === true
|
|
12
|
+
* matchUrlWithWildcard("https://example.com:8080/", ["example.com:9090"]) === false
|
|
13
|
+
* matchUrlWithWildcard("https://foo.com/api/users", ["foo.com/api/*"]) === true
|
|
14
|
+
* matchUrlWithWildcard("https://foo.com/health", ["foo.com/api/*"]) === false
|
|
15
|
+
* matchUrlWithWildcard("ws://foo.com", ["foo.com"]) === false // non-http
|
|
16
|
+
*/
|
|
17
|
+
export declare function matchUrlWithWildcard(input: unknown, patterns: string[]): boolean;
|
|
18
|
+
/** Test-only: clear the internal regex cache. */
|
|
19
|
+
export declare function __clearUrlMatchCache(): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./workerPoolSpanCapture-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./workerPoolSpanCapture-BUFN_RMW.cjs");exports.captureWorkerPoolOperation=e.captureWorkerPoolOperation;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";const j=require("async_hooks"),Q=require("fs"),$=require("worker_threads"),l=require("./contextManager-0D8uHQ1_.cjs"),z=require("path"),X=require("url");class G{apiKey;endpoint;queryType="mutation";operationName="";serviceUUID=l.getConfig().serviceUUID;contextManager;constructor(){this.apiKey=l.getConfig().apiKey,this.endpoint=l.getConfig().apiGraphqlEndpoint,this.contextManager=l.ContextManager.getInstance()}get queryName(){return this.operationName?this.operationName.charAt(0).toLowerCase()+this.operationName.slice(1):""}getDefaultVariables(){const t=Date.now().toString(),o=this.contextManager.getOrSetSfTraceId(),a=this.contextManager.getCurrentFunctionSpanId();return{apiKey:this.apiKey,serviceUuid:this.serviceUUID,sessionId:o,timestampMs:t,parentSpanId:a}}getVariables(t={}){return{...this.getDefaultVariables(),...t}}setOperationName(t){this.operationName=t}setEndpoint(t){this.endpoint=t}setServiceUUID(t){this.serviceUUID=t}}const Z=typeof __dirname<"u"?__dirname:z.dirname(X.fileURLToPath(require("node:url").pathToFileURL(__filename).href)),Y=fetch;let I=!1;const ee=process.env.SF_NBPOST_DISABLE_BATCHING==="1",k=parseInt(process.env.SF_MAIN_BATCH_SIZE||"0",10);let m=null,C=!1;function B(){if(C)return null;if(m)return m;try{const n=z.join(Z,"telemetryWorker.cjs");return m=new $.Worker(n,{env:{...process.env,SF_NBPOST_BATCH_MAX:process.env.SF_NBPOST_BATCH_MAX||"50",SF_FLUSH_TELEMETRY_IN_BATCH:process.env.SF_FLUSH_TELEMETRY_IN_BATCH||"0",SF_BATCH_FLUSH_INTERVAL_MS:process.env.SF_BATCH_FLUSH_INTERVAL_MS||"50",SF_WORKER_MAX_CONCURRENT:process.env.SF_WORKER_MAX_CONCURRENT||"10"}}),m.unref(),m.on("error",()=>{C=!0,m=null}),m.on("exit",()=>{m=null}),m}catch{return C=!0,null}}let S=[],b=!1;function U(){if(S.length===0)return;const n=B();if(!n){for(const t of S)L(t.url,t.item.operationName,t.item.query,t.item.variables);return S=[],void(b=!1)}S.length===1?n.postMessage(S[0]):n.postMessage({batch:S}),S=[],b=!1}async function E(n,t,o,a){if(ee)return L(n,t,o,a);const s={url:n,item:{query:o,variables:a,operationName:t}};if(k===1){const i=B();return i?void i.postMessage(s):L(n,t,o,a)}S.push(s),k>1&&S.length>=k?U():b||(b=!0,queueMicrotask(U))}async function L(n,t,o,a){try{const s=l.getConfig();let i;try{i=JSON.stringify({query:o,variables:a,operationName:t})}catch{i=JSON.stringify({query:o,operationName:t})}I=!0,Y(n,{method:"POST",headers:{"Content-Type":"application/json"},body:i}).then(async e=>{if(I=!1,!e.ok)return void(s.sfDebug&&console.error(`GraphQL request failed with status ${e.status} for ${t}`));const r=await e.json();r.errors?.length?(function(u,g,c){const d=u&&typeof u=="object"&&!Array.isArray(u)?Object.keys(u)[0]:void 0;console.error(d==="identifyServiceDetails"?`IdentifyServiceDetails NOT sent successfully for service: UUID=${c.serviceUUID}`:`GraphQL request failed with errors: ${JSON.stringify(g)} for operation key ${d}`)})(r.data,r.errors,s):s.sfDebug&&(function(u,g,c){const d=u&&typeof u=="object"&&!Array.isArray(u)?Object.keys(u)[0]:void 0,p=u[d]||!1;d==="identifyServiceDetails"&&(c.setServiceIdentificationReceived(p),l.getConfig().sfDebug&&console.log(`IdentifyServiceDetails sent successfully for service: UUID=${c.serviceUUID}; serviceIdentificationReceived=${d==="identifyServiceDetails"?p:"N/A"}`))})(r.data,0,s)}).catch(e=>{I=!1,s.sfDebug&&(console.error(`[RequestUtils] Fetch error for ${t} to ${n}:`,e),e.cause&&console.error("[RequestUtils] Error cause:",e.cause))})}catch(s){I=!1,l.getConfig().sfDebug&&console.error("Error sending data to GraphQL server:",s)}}let V=!1;function h(n,t){if(!n)return t;const o=n.toLowerCase();return o==="true"||o==="1"||o==="yes"}const M="__sf_funcspanOverrideStorage";globalThis[M]||(globalThis[M]=new j.AsyncLocalStorage);const P=globalThis[M];function D(n,t){try{const o=JSON.stringify(n).length/1048576;return o<=t?n:{_truncated:!0,_originalSizeMB:o.toFixed(2),_limitMB:t,_preview:JSON.stringify(n).substring(0,500)+"..."}}catch{return{_error:"Failed to serialize data",_type:typeof n}}}function y(n,t){const o=process.env[n];return o===void 0?t:o==="true"||o==="1"}function q(n,t){const o=process.env[n];if(o===void 0)return t;const a=parseFloat(o);return isNaN(a)?t:a}function A(){return{enabled:y("SF_WORKER_POOL_ENABLED",!0),trackFs:y("SF_WORKER_POOL_TRACK_FS",!1),trackDns:y("SF_WORKER_POOL_TRACK_DNS",!1),trackCrypto:y("SF_WORKER_POOL_TRACK_CRYPTO",!1),trackZlib:y("SF_WORKER_POOL_TRACK_ZLIB",!1),captureArguments:y("SF_WORKER_POOL_CAPTURE_ARGUMENTS",!0),captureReturnValue:y("SF_WORKER_POOL_CAPTURE_RETURN_VALUE",!0),argLimitMb:q("SF_WORKER_POOL_ARG_LIMIT_MB",1),returnLimitMb:q("SF_WORKER_POOL_RETURN_LIMIT_MB",1)}}function x(n,t,o,a){let s;try{switch(n){case"fs":s=(function(i,e){const r={};switch(i){case"readFile":case"writeFile":case"appendFile":r.path=String(e[0]||""),e[1]&&typeof e[1]=="object"?(r.encoding=e[1].encoding||null,r.flag=e[1].flag||null):typeof e[1]=="string"&&(r.encoding=e[1]),i!=="writeFile"&&i!=="appendFile"||(Buffer.isBuffer(e[1])?(r.dataType="Buffer",r.dataSize=e[1].length):typeof e[1]=="string"&&(r.dataType="string",r.dataSize=e[1].length));break;case"readdir":case"stat":case"lstat":case"access":case"chmod":case"mkdir":case"rmdir":case"unlink":r.path=String(e[0]||""),e[1]&&typeof e[1]=="object"&&(r.options={...e[1]},delete r.options.callback);break;case"rename":r.oldPath=String(e[0]||""),r.newPath=String(e[1]||"");break;case"open":r.path=String(e[0]||""),r.flags=e[1],r.mode=e[2];break;case"close":case"fstat":r.fd=e[0];break;case"read":case"write":r.fd=e[0],Buffer.isBuffer(e[1])&&(r.bufferSize=e[1].length),r.offset=e[2],r.length=e[3],r.position=e[4];break;default:r.argsCount=e.length-1}return r})(t,o);break;case"dns":s=(function(i,e){const r={};switch(i){case"lookup":r.hostname=String(e[0]||""),typeof e[1]=="object"?(r.family=e[1].family,r.all=e[1].all):typeof e[1]=="number"&&(r.family=e[1]);break;case"resolve":case"resolve4":case"resolve6":case"resolveAny":case"resolveMx":case"resolveNs":case"resolveTxt":r.hostname=String(e[0]||"");break;case"reverse":r.ip=String(e[0]||"");break;default:r.argsCount=e.length-1}return r})(t,o);break;case"crypto":s=(function(i,e){const r={};switch(i){case"pbkdf2":r.passwordType=typeof e[0],r.saltType=typeof e[1],r.iterations=e[2],r.keylen=e[3],r.digest=e[4];break;case"scrypt":r.passwordType=typeof e[0],r.saltType=typeof e[1],r.keylen=e[2],typeof e[3]=="object"&&(r.N=e[3].N,r.r=e[3].r,r.p=e[3].p);break;case"randomBytes":r.size=e[0];break;case"generateKeyPair":r.type=e[0],typeof e[1]=="object"&&(r.modulusLength=e[1].modulusLength,r.namedCurve=e[1].namedCurve);break;default:r.argsCount=e.length-1}return r})(t,o);break;case"zlib":s=(function(i,e){const r={};return Buffer.isBuffer(e[0])?(r.inputType="Buffer",r.inputSize=e[0].length):typeof e[0]=="string"?(r.inputType="string",r.inputSize=e[0].length):r.inputType=typeof e[0],e[1]&&typeof e[1]=="object"&&typeof e[1]!="function"&&(r.options={...e[1]}),r})(0,o);break;default:return null}return a>0?D(s,a):s}catch{return{error:"Failed to capture arguments",argsCount:o.length-1}}}function J(n,t,o,a){let s;try{switch(n){case"fs":s=(function(i,e){if(!e)return null;switch(i){case"readFile":return Buffer.isBuffer(e)?{type:"Buffer",size:e.length}:typeof e=="string"?{type:"string",size:e.length}:{type:typeof e};case"readdir":return{count:Array.isArray(e)?e.length:0,items:e};case"stat":case"lstat":case"fstat":return{size:e.size,mode:e.mode,isFile:e.isFile(),isDirectory:e.isDirectory()};case"open":return{fd:e};case"read":return{bytesRead:e};case"write":return{bytesWritten:e};default:return e}})(t,o);break;case"dns":s=(function(i,e){if(!e)return null;switch(i){case"lookup":return Array.isArray(e)?{count:e.length,addresses:e}:e;case"resolve":case"resolve4":case"resolve6":case"resolveAny":case"resolveMx":case"resolveNs":case"resolveTxt":return{count:Array.isArray(e)?e.length:0,records:e};case"reverse":return{hostnames:e};default:return e}})(t,o);break;case"crypto":s=(function(i,e){if(!e)return null;switch(i){case"pbkdf2":case"scrypt":case"randomBytes":return Buffer.isBuffer(e)?{type:"Buffer",size:e.length}:{type:typeof e};case"generateKeyPair":return{hasPublicKey:!!e?.publicKey,hasPrivateKey:!!e?.privateKey};default:return e}})(t,o);break;case"zlib":s=(function(i,e){return e?Buffer.isBuffer(e)?{type:"Buffer",size:e.length}:typeof e=="string"?{type:"string",size:e.length}:{type:typeof e}:null})(0,o);break;default:return null}return a>0?D(s,a):s}catch{return{error:"Failed to capture result",type:typeof o}}}function te(n){return n.operationType==="worker_pool"}class H extends G{constructor(){super(),this.operationName="CollectFunctionSpans"}send(t){const o=l.getConfig().sfDebug;o&&console.log(`[FunctionSpanTransmitter] Preparing to send ${t.length} function span(s)`);for(const a of t)try{if(te(a)){this.sendWorkerPoolSpan(a,o);continue}const s=a;let i;if(s.result!==void 0&&s.result!==null){const r=typeof s.result;i=JSON.stringify({type:r,has_value:!0,value:s.result})}else i=s.result===null?JSON.stringify({type:"null",has_value:!0,value:null}):JSON.stringify({type:"undefined",has_value:!1,value:null});const e=this.getVariables({library:"JS/TS BACKEND",version:l.getConfig().version,spanId:s.spanId,parentSpanId:s.parentSpanId,filePath:s.filePath,lineNumber:s.metadata.line,columnNumber:s.metadata.column,functionName:s.functionName,arguments:JSON.stringify(s.args||{}),returnValue:i,startTimeNs:(1e6*Date.now()-1e6*s.duration).toString(),durationNs:(1e6*s.duration).toString()});o&&(console.log(`[FunctionSpanTransmitter] Sending GraphQL mutation to ${this.endpoint}`),console.log("[FunctionSpanTransmitter] Variables:",JSON.stringify(e,null,2))),E(this.endpoint,this.operationName,this.getQuery(),e),o&&console.log(`[FunctionSpanTransmitter] Queued function span for ${s.functionName}`)}catch(s){console.error(`[FunctionSpanTransmitter] Error preparing function span for ${a.functionName}:`,s)}}sendWorkerPoolSpan(t,o){try{let a;if(t.result!==void 0&&t.result!==null){const i=typeof t.result;a=JSON.stringify({type:i,has_value:!0,value:t.result})}else a=t.result===null?JSON.stringify({type:"null",has_value:!0,value:null}):JSON.stringify({type:"undefined",has_value:!1,value:null});const s=this.getVariables({library:"JS/TS BACKEND",version:l.getConfig().version,spanId:t.spanId,operationName:t.operationName,moduleName:t.moduleName,methodName:t.methodName,startTimeNs:t.startTimeNs,durationNs:t.durationNs,arguments:JSON.stringify(t.args||{}),returnValue:a,error:t.error,pid:t.pid,threadId:t.threadId});o&&(console.log(`[FunctionSpanTransmitter] Sending worker pool span: ${t.operationName}`),console.log("[FunctionSpanTransmitter] Variables:",JSON.stringify(s,null,2))),E(this.endpoint,"CollectWorkerPoolSpans",this.getWorkerPoolQuery(),s),o&&console.log(`[FunctionSpanTransmitter] Queued worker pool span for ${t.operationName}`)}catch(a){console.error(`[FunctionSpanTransmitter] Error preparing worker pool span for ${t.operationName}:`,a)}}getWorkerPoolQuery(){return`
|
|
1
|
+
"use strict";const j=require("async_hooks"),Q=require("fs"),$=require("worker_threads"),l=require("./contextManager-qXvO_a5y.cjs"),z=require("path"),X=require("url");class G{apiKey;endpoint;queryType="mutation";operationName="";serviceUUID=l.getConfig().serviceUUID;contextManager;constructor(){this.apiKey=l.getConfig().apiKey,this.endpoint=l.getConfig().apiGraphqlEndpoint,this.contextManager=l.ContextManager.getInstance()}get queryName(){return this.operationName?this.operationName.charAt(0).toLowerCase()+this.operationName.slice(1):""}getDefaultVariables(){const t=Date.now().toString(),o=this.contextManager.getOrSetSfTraceId(),a=this.contextManager.getCurrentFunctionSpanId();return{apiKey:this.apiKey,serviceUuid:this.serviceUUID,sessionId:o,timestampMs:t,parentSpanId:a}}getVariables(t={}){return{...this.getDefaultVariables(),...t}}setOperationName(t){this.operationName=t}setEndpoint(t){this.endpoint=t}setServiceUUID(t){this.serviceUUID=t}}const Z=typeof __dirname<"u"?__dirname:z.dirname(X.fileURLToPath(require("node:url").pathToFileURL(__filename).href)),Y=fetch;let I=!1;const ee=process.env.SF_NBPOST_DISABLE_BATCHING==="1",k=parseInt(process.env.SF_MAIN_BATCH_SIZE||"0",10);let m=null,C=!1;function B(){if(C)return null;if(m)return m;try{const n=z.join(Z,"telemetryWorker.cjs");return m=new $.Worker(n,{env:{...process.env,SF_NBPOST_BATCH_MAX:process.env.SF_NBPOST_BATCH_MAX||"50",SF_FLUSH_TELEMETRY_IN_BATCH:process.env.SF_FLUSH_TELEMETRY_IN_BATCH||"0",SF_BATCH_FLUSH_INTERVAL_MS:process.env.SF_BATCH_FLUSH_INTERVAL_MS||"50",SF_WORKER_MAX_CONCURRENT:process.env.SF_WORKER_MAX_CONCURRENT||"10"}}),m.unref(),m.on("error",()=>{C=!0,m=null}),m.on("exit",()=>{m=null}),m}catch{return C=!0,null}}let S=[],b=!1;function U(){if(S.length===0)return;const n=B();if(!n){for(const t of S)L(t.url,t.item.operationName,t.item.query,t.item.variables);return S=[],void(b=!1)}S.length===1?n.postMessage(S[0]):n.postMessage({batch:S}),S=[],b=!1}async function E(n,t,o,a){if(ee)return L(n,t,o,a);const s={url:n,item:{query:o,variables:a,operationName:t}};if(k===1){const i=B();return i?void i.postMessage(s):L(n,t,o,a)}S.push(s),k>1&&S.length>=k?U():b||(b=!0,queueMicrotask(U))}async function L(n,t,o,a){try{const s=l.getConfig();let i;try{i=JSON.stringify({query:o,variables:a,operationName:t})}catch{i=JSON.stringify({query:o,operationName:t})}I=!0,Y(n,{method:"POST",headers:{"Content-Type":"application/json"},body:i}).then(async e=>{if(I=!1,!e.ok)return void(s.sfDebug&&console.error(`GraphQL request failed with status ${e.status} for ${t}`));const r=await e.json();r.errors?.length?(function(u,g,c){const d=u&&typeof u=="object"&&!Array.isArray(u)?Object.keys(u)[0]:void 0;console.error(d==="identifyServiceDetails"?`IdentifyServiceDetails NOT sent successfully for service: UUID=${c.serviceUUID}`:`GraphQL request failed with errors: ${JSON.stringify(g)} for operation key ${d}`)})(r.data,r.errors,s):s.sfDebug&&(function(u,g,c){const d=u&&typeof u=="object"&&!Array.isArray(u)?Object.keys(u)[0]:void 0,p=u[d]||!1;d==="identifyServiceDetails"&&(c.setServiceIdentificationReceived(p),l.getConfig().sfDebug&&console.log(`IdentifyServiceDetails sent successfully for service: UUID=${c.serviceUUID}; serviceIdentificationReceived=${d==="identifyServiceDetails"?p:"N/A"}`))})(r.data,0,s)}).catch(e=>{I=!1,s.sfDebug&&(console.error(`[RequestUtils] Fetch error for ${t} to ${n}:`,e),e.cause&&console.error("[RequestUtils] Error cause:",e.cause))})}catch(s){I=!1,l.getConfig().sfDebug&&console.error("Error sending data to GraphQL server:",s)}}let V=!1;function h(n,t){if(!n)return t;const o=n.toLowerCase();return o==="true"||o==="1"||o==="yes"}const M="__sf_funcspanOverrideStorage";globalThis[M]||(globalThis[M]=new j.AsyncLocalStorage);const P=globalThis[M];function D(n,t){try{const o=JSON.stringify(n).length/1048576;return o<=t?n:{_truncated:!0,_originalSizeMB:o.toFixed(2),_limitMB:t,_preview:JSON.stringify(n).substring(0,500)+"..."}}catch{return{_error:"Failed to serialize data",_type:typeof n}}}function y(n,t){const o=process.env[n];return o===void 0?t:o==="true"||o==="1"}function q(n,t){const o=process.env[n];if(o===void 0)return t;const a=parseFloat(o);return isNaN(a)?t:a}function A(){return{enabled:y("SF_WORKER_POOL_ENABLED",!0),trackFs:y("SF_WORKER_POOL_TRACK_FS",!1),trackDns:y("SF_WORKER_POOL_TRACK_DNS",!1),trackCrypto:y("SF_WORKER_POOL_TRACK_CRYPTO",!1),trackZlib:y("SF_WORKER_POOL_TRACK_ZLIB",!1),captureArguments:y("SF_WORKER_POOL_CAPTURE_ARGUMENTS",!0),captureReturnValue:y("SF_WORKER_POOL_CAPTURE_RETURN_VALUE",!0),argLimitMb:q("SF_WORKER_POOL_ARG_LIMIT_MB",1),returnLimitMb:q("SF_WORKER_POOL_RETURN_LIMIT_MB",1)}}function x(n,t,o,a){let s;try{switch(n){case"fs":s=(function(i,e){const r={};switch(i){case"readFile":case"writeFile":case"appendFile":r.path=String(e[0]||""),e[1]&&typeof e[1]=="object"?(r.encoding=e[1].encoding||null,r.flag=e[1].flag||null):typeof e[1]=="string"&&(r.encoding=e[1]),i!=="writeFile"&&i!=="appendFile"||(Buffer.isBuffer(e[1])?(r.dataType="Buffer",r.dataSize=e[1].length):typeof e[1]=="string"&&(r.dataType="string",r.dataSize=e[1].length));break;case"readdir":case"stat":case"lstat":case"access":case"chmod":case"mkdir":case"rmdir":case"unlink":r.path=String(e[0]||""),e[1]&&typeof e[1]=="object"&&(r.options={...e[1]},delete r.options.callback);break;case"rename":r.oldPath=String(e[0]||""),r.newPath=String(e[1]||"");break;case"open":r.path=String(e[0]||""),r.flags=e[1],r.mode=e[2];break;case"close":case"fstat":r.fd=e[0];break;case"read":case"write":r.fd=e[0],Buffer.isBuffer(e[1])&&(r.bufferSize=e[1].length),r.offset=e[2],r.length=e[3],r.position=e[4];break;default:r.argsCount=e.length-1}return r})(t,o);break;case"dns":s=(function(i,e){const r={};switch(i){case"lookup":r.hostname=String(e[0]||""),typeof e[1]=="object"?(r.family=e[1].family,r.all=e[1].all):typeof e[1]=="number"&&(r.family=e[1]);break;case"resolve":case"resolve4":case"resolve6":case"resolveAny":case"resolveMx":case"resolveNs":case"resolveTxt":r.hostname=String(e[0]||"");break;case"reverse":r.ip=String(e[0]||"");break;default:r.argsCount=e.length-1}return r})(t,o);break;case"crypto":s=(function(i,e){const r={};switch(i){case"pbkdf2":r.passwordType=typeof e[0],r.saltType=typeof e[1],r.iterations=e[2],r.keylen=e[3],r.digest=e[4];break;case"scrypt":r.passwordType=typeof e[0],r.saltType=typeof e[1],r.keylen=e[2],typeof e[3]=="object"&&(r.N=e[3].N,r.r=e[3].r,r.p=e[3].p);break;case"randomBytes":r.size=e[0];break;case"generateKeyPair":r.type=e[0],typeof e[1]=="object"&&(r.modulusLength=e[1].modulusLength,r.namedCurve=e[1].namedCurve);break;default:r.argsCount=e.length-1}return r})(t,o);break;case"zlib":s=(function(i,e){const r={};return Buffer.isBuffer(e[0])?(r.inputType="Buffer",r.inputSize=e[0].length):typeof e[0]=="string"?(r.inputType="string",r.inputSize=e[0].length):r.inputType=typeof e[0],e[1]&&typeof e[1]=="object"&&typeof e[1]!="function"&&(r.options={...e[1]}),r})(0,o);break;default:return null}return a>0?D(s,a):s}catch{return{error:"Failed to capture arguments",argsCount:o.length-1}}}function J(n,t,o,a){let s;try{switch(n){case"fs":s=(function(i,e){if(!e)return null;switch(i){case"readFile":return Buffer.isBuffer(e)?{type:"Buffer",size:e.length}:typeof e=="string"?{type:"string",size:e.length}:{type:typeof e};case"readdir":return{count:Array.isArray(e)?e.length:0,items:e};case"stat":case"lstat":case"fstat":return{size:e.size,mode:e.mode,isFile:e.isFile(),isDirectory:e.isDirectory()};case"open":return{fd:e};case"read":return{bytesRead:e};case"write":return{bytesWritten:e};default:return e}})(t,o);break;case"dns":s=(function(i,e){if(!e)return null;switch(i){case"lookup":return Array.isArray(e)?{count:e.length,addresses:e}:e;case"resolve":case"resolve4":case"resolve6":case"resolveAny":case"resolveMx":case"resolveNs":case"resolveTxt":return{count:Array.isArray(e)?e.length:0,records:e};case"reverse":return{hostnames:e};default:return e}})(t,o);break;case"crypto":s=(function(i,e){if(!e)return null;switch(i){case"pbkdf2":case"scrypt":case"randomBytes":return Buffer.isBuffer(e)?{type:"Buffer",size:e.length}:{type:typeof e};case"generateKeyPair":return{hasPublicKey:!!e?.publicKey,hasPrivateKey:!!e?.privateKey};default:return e}})(t,o);break;case"zlib":s=(function(i,e){return e?Buffer.isBuffer(e)?{type:"Buffer",size:e.length}:typeof e=="string"?{type:"string",size:e.length}:{type:typeof e}:null})(0,o);break;default:return null}return a>0?D(s,a):s}catch{return{error:"Failed to capture result",type:typeof o}}}function te(n){return n.operationType==="worker_pool"}class H extends G{constructor(){super(),this.operationName="CollectFunctionSpans"}send(t){const o=l.getConfig().sfDebug;o&&console.log(`[FunctionSpanTransmitter] Preparing to send ${t.length} function span(s)`);for(const a of t)try{if(te(a)){this.sendWorkerPoolSpan(a,o);continue}const s=a;let i;if(s.result!==void 0&&s.result!==null){const r=typeof s.result;i=JSON.stringify({type:r,has_value:!0,value:s.result})}else i=s.result===null?JSON.stringify({type:"null",has_value:!0,value:null}):JSON.stringify({type:"undefined",has_value:!1,value:null});const e=this.getVariables({library:"JS/TS BACKEND",version:l.getConfig().version,spanId:s.spanId,parentSpanId:s.parentSpanId,filePath:s.filePath,lineNumber:s.metadata.line,columnNumber:s.metadata.column,functionName:s.functionName,arguments:JSON.stringify(s.args||{}),returnValue:i,startTimeNs:(1e6*Date.now()-1e6*s.duration).toString(),durationNs:(1e6*s.duration).toString()});o&&(console.log(`[FunctionSpanTransmitter] Sending GraphQL mutation to ${this.endpoint}`),console.log("[FunctionSpanTransmitter] Variables:",JSON.stringify(e,null,2))),E(this.endpoint,this.operationName,this.getQuery(),e),o&&console.log(`[FunctionSpanTransmitter] Queued function span for ${s.functionName}`)}catch(s){console.error(`[FunctionSpanTransmitter] Error preparing function span for ${a.functionName}:`,s)}}sendWorkerPoolSpan(t,o){try{let a;if(t.result!==void 0&&t.result!==null){const i=typeof t.result;a=JSON.stringify({type:i,has_value:!0,value:t.result})}else a=t.result===null?JSON.stringify({type:"null",has_value:!0,value:null}):JSON.stringify({type:"undefined",has_value:!1,value:null});const s=this.getVariables({library:"JS/TS BACKEND",version:l.getConfig().version,spanId:t.spanId,operationName:t.operationName,moduleName:t.moduleName,methodName:t.methodName,startTimeNs:t.startTimeNs,durationNs:t.durationNs,arguments:JSON.stringify(t.args||{}),returnValue:a,error:t.error,pid:t.pid,threadId:t.threadId});o&&(console.log(`[FunctionSpanTransmitter] Sending worker pool span: ${t.operationName}`),console.log("[FunctionSpanTransmitter] Variables:",JSON.stringify(s,null,2))),E(this.endpoint,"CollectWorkerPoolSpans",this.getWorkerPoolQuery(),s),o&&console.log(`[FunctionSpanTransmitter] Queued worker pool span for ${t.operationName}`)}catch(a){console.error(`[FunctionSpanTransmitter] Error preparing worker pool span for ${t.operationName}:`,a)}}getWorkerPoolQuery(){return`
|
|
2
2
|
mutation CollectWorkerPoolSpans(
|
|
3
3
|
$apiKey: String!,
|
|
4
4
|
$serviceUuid: String!,
|
|
@@ -4,7 +4,7 @@ var y = (n, t, s) => X(n, typeof t != "symbol" ? t + "" : t, s);
|
|
|
4
4
|
import { AsyncLocalStorage as Z, AsyncResource as Y } from "async_hooks";
|
|
5
5
|
import { appendFileSync as ee } from "fs";
|
|
6
6
|
import { Worker as te, threadId as O } from "worker_threads";
|
|
7
|
-
import { g as S, C as L, v as j, a as M } from "./contextManager-
|
|
7
|
+
import { g as S, C as L, v as j, a as M } from "./contextManager-CZy0w11U.js";
|
|
8
8
|
import { dirname as ne, join as re } from "path";
|
|
9
9
|
import { fileURLToPath as se } from "url";
|
|
10
10
|
class oe {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sailfish-ai/sf-veritas",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.2",
|
|
4
4
|
"publishPublicly": true,
|
|
5
5
|
"description": "A versatile Edge Runtime-compatible package for JavaScript and TypeScript backend systems and scripts.",
|
|
6
6
|
"main": "./dist/sf-veritas.cjs",
|
|
@@ -102,19 +102,35 @@
|
|
|
102
102
|
}
|
|
103
103
|
},
|
|
104
104
|
"devDependencies": {
|
|
105
|
+
"@apollo/server": "^5.5.0",
|
|
106
|
+
"@hapi/hapi": "^21.4.8",
|
|
107
|
+
"@nestjs/common": "^11.1.19",
|
|
108
|
+
"@nestjs/core": "^11.1.19",
|
|
109
|
+
"@nestjs/platform-express": "^11.1.19",
|
|
105
110
|
"@rollup/plugin-terser": "^0.4.4",
|
|
106
111
|
"@types/babel__core": "^7.20.5",
|
|
107
112
|
"@types/babel__generator": "^7.6.8",
|
|
108
113
|
"@types/babel__traverse": "^7.20.6",
|
|
114
|
+
"@types/express": "^5.0.6",
|
|
109
115
|
"@types/js-yaml": "^4.0.9",
|
|
116
|
+
"@types/koa": "^3.0.2",
|
|
110
117
|
"@types/node": "^22.13.10",
|
|
111
118
|
"@types/uuid": "^10.0.0",
|
|
112
119
|
"@types/webpack": "^5.28.5",
|
|
113
120
|
"esbuild": "^0.23.0",
|
|
114
121
|
"eslint": "^9.22.0",
|
|
115
122
|
"eslint-config-next": "^15.2.3",
|
|
123
|
+
"express": "^5.2.1",
|
|
124
|
+
"fastify": "^5.8.5",
|
|
125
|
+
"graphql": "^16.13.2",
|
|
126
|
+
"graphql-http": "^1.22.4",
|
|
127
|
+
"graphql-yoga": "^5.21.0",
|
|
128
|
+
"koa": "^3.2.0",
|
|
129
|
+
"mercurius": "^16.9.0",
|
|
130
|
+
"reflect-metadata": "^0.2.2",
|
|
116
131
|
"rollup": "^3.29.5",
|
|
117
132
|
"rollup-plugin-dts": "^5.3.1",
|
|
133
|
+
"rxjs": "^7.8.2",
|
|
118
134
|
"ts-node": "^10.9.2",
|
|
119
135
|
"typescript": "^5.8.2",
|
|
120
136
|
"vite": "^6.2.2",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";const L=require("async_hooks"),x=require("child_process"),T=require("fs"),b=require("fs/promises"),G=require("os");function U(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const V=U(b),N=U(G),i=[];for(let s=0;s<256;++s)i.push((s+256).toString(16).slice(1));let f;const k=new Uint8Array(16),A={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function I(s,e,t){if(A.randomUUID&&!s)return A.randomUUID();const r=(s=s||{}).random??s.rng?.()??(function(){if(!f){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");f=crypto.getRandomValues.bind(crypto)}return f(k)})();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=15&r[6]|64,r[8]=63&r[8]|128,(function(n,o=0){return(i[n[o+0]]+i[n[o+1]]+i[n[o+2]]+i[n[o+3]]+"-"+i[n[o+4]]+i[n[o+5]]+"-"+i[n[o+6]]+i[n[o+7]]+"-"+i[n[o+8]]+i[n[o+9]]+"-"+i[n[o+10]]+i[n[o+11]]+i[n[o+12]]+i[n[o+13]]+i[n[o+14]]+i[n[o+15]]).toLowerCase()})(r)}class F{apiKey;apiGraphqlEndpoint;sfDebug;serviceIdentifier;serviceVersion;serviceUUID;serviceAdditionalMetadata;profilingModeEnabled;profilingMaxDepth;profilingMaxVariableSizeKb;domainsToNotPropagateHeadersTo;nodeModulesToCollectLocalVariablesOn;printConfigurationStatuses;logLevel;stackDepthLocals;stackDepthCodeTraceDepth;packageLibraryType;version;gitSha;gitOrg;gitRepo;gitProvider;serviceDisplayName;infrastructureType;infrastructureDetails;framework;additionalFrameworks;serviceRole;setupInterceptorsFile;setupInterceptorsLine;logIgnoreRegex;captureRequestHeaders;captureResponseHeaders;captureRequestBody;captureResponseBody;requestBodyLimitBytes;responseBodyLimitBytes;_serviceIdentificationReceived=!1;constructor(e){this.apiKey=e.apiKey,this.apiGraphqlEndpoint=e?.apiGraphqlEndpoint||process.env.SAILFISH_GRAPHQL_ENDPOINT||"https://api-service.sailfishqa.com/graphql/",this.sfDebug=e?.debug===!0||process.env.SF_DEBUG==="true",this.serviceIdentifier=e?.serviceIdentifier||process.env.SERVICE_IDENTIFIER,this.serviceUUID=I(),this.serviceVersion=e?.serviceVersion||process.env.SERVICE_VERSION,this.gitSha=e?.gitSha||process.env.GIT_SHA||process.env.GITHUB_SHA||process.env.CI_COMMIT_SHA||process.env.BITBUCKET_COMMIT||process.env.VERCEL_GIT_COMMIT_SHA||process.env.CIRCLE_SHA1||process.env.HEROKU_SLUG_COMMIT||process.env.RENDER_GIT_COMMIT||process.env.RAILWAY_GIT_COMMIT_SHA||process.env.CODEBUILD_RESOLVED_SOURCE_VERSION;const t=process.env.GITHUB_REPOSITORY?.split("/");this.gitOrg=e?.gitOrg||process.env.GIT_ORG||(t&&t.length>=2?t[0]:void 0)||process.env.CI_PROJECT_NAMESPACE||process.env.BITBUCKET_REPO_OWNER||process.env.VERCEL_GIT_REPO_OWNER||process.env.CIRCLE_PROJECT_USERNAME,this.gitRepo=e?.gitRepo||process.env.GIT_REPO||(t&&t.length>=2?t.slice(1).join("/"):void 0)||process.env.CI_PROJECT_NAME||process.env.BITBUCKET_REPO_SLUG||process.env.VERCEL_GIT_REPO_SLUG||process.env.CIRCLE_PROJECT_REPONAME,this.gitProvider=e?.gitProvider||process.env.GIT_PROVIDER||(process.env.GITHUB_ACTIONS?"github":void 0)||(process.env.GITLAB_CI?"gitlab":void 0)||(process.env.BITBUCKET_PIPELINE_UUID?"bitbucket":void 0)||(process.env.CIRCLECI?"circleci":void 0),this.serviceDisplayName=e?.serviceDisplayName||process.env.SERVICE_DISPLAY_NAME,this.serviceAdditionalMetadata=e?.serviceAdditionalMetadata||{},this.profilingModeEnabled=e?.profilingModeEnabled??!1,this.profilingMaxDepth=e?.profilingMaxDepth??5,this.profilingMaxVariableSizeKb=e?.profilingMaxVariableSizeKb??25,this.domainsToNotPropagateHeadersTo=e?.domainsToNotPropagateHeadersTo||[],this.nodeModulesToCollectLocalVariablesOn=e?.nodeModulesToCollectLocalVariablesOn||["_all_"],this.printConfigurationStatuses=process.env.PRINT_CONFIGURATION_STATUSES||"true",this.logLevel=process.env.LOG_LEVEL||"INFO",this.stackDepthLocals=process.env.SAILFISH_EXCEPTION_STACK_DEPTH_LOCALS!==void 0?parseInt(process.env.SAILFISH_EXCEPTION_STACK_DEPTH_LOCALS,10):5,isNaN(this.stackDepthLocals)&&(this.stackDepthLocals=-1),this.stackDepthCodeTraceDepth=process.env.SAILFISH_EXCEPTION_STACK_DEPTH_CODE_TRACE_DEPTH!==void 0?parseInt(process.env.SAILFISH_EXCEPTION_STACK_DEPTH_CODE_TRACE_DEPTH,10):-1,isNaN(this.stackDepthCodeTraceDepth)&&(this.stackDepthCodeTraceDepth=-1),this.packageLibraryType="JS/TS BACKEND",this.version=this.getPackageVersion();const r=(function(){return process.env.KUBERNETES_SERVICE_HOST||T.existsSync("/var/run/secrets/kubernetes.io/serviceaccount/token")?{type:"Kubernetes",details:{namespace:process.env.POD_NAMESPACE||"",podName:process.env.HOSTNAME||"",nodeName:process.env.NODE_NAME||""}}:process.env.AWS_LAMBDA_FUNCTION_NAME?{type:"AWS Lambda",details:{functionName:process.env.AWS_LAMBDA_FUNCTION_NAME||"",region:process.env.AWS_REGION||"",runtime:process.env.AWS_EXECUTION_ENV||""}}:process.env.AWS_EXECUTION_ENV?{type:"AWS",details:{executionEnv:process.env.AWS_EXECUTION_ENV||"",region:process.env.AWS_REGION||""}}:process.env.GOOGLE_CLOUD_PROJECT?{type:"Google Cloud",details:{project:process.env.GOOGLE_CLOUD_PROJECT||""}}:process.env.AZURE_FUNCTIONS_ENVIRONMENT?{type:"Azure Functions",details:{environment:process.env.AZURE_FUNCTIONS_ENVIRONMENT||""}}:process.env.VERCEL?{type:"Vercel",details:{env:process.env.VERCEL_ENV||"",region:process.env.VERCEL_REGION||""}}:process.env.NETLIFY?{type:"Netlify",details:{}}:process.env.FLY_APP_NAME?{type:"Fly.io",details:{appName:process.env.FLY_APP_NAME||"",region:process.env.FLY_REGION||""}}:process.env.RENDER_SERVICE_ID?{type:"Render",details:{serviceId:process.env.RENDER_SERVICE_ID||""}}:process.env.RAILWAY_ENVIRONMENT?{type:"Railway",details:{environment:process.env.RAILWAY_ENVIRONMENT||""}}:T.existsSync("/.dockerenv")?{type:"Docker",details:{}}:{type:"Unknown",details:{os:N.platform(),arch:N.arch(),nodeVersion:process.version}}})();this.infrastructureType=r.type,this.infrastructureDetails=r.details;const n=(function(){const g=[{pkg:"@nestjs/core",name:"nestjs"},{pkg:"@apollo/server",name:"apollo-server"},{pkg:"apollo-server",name:"apollo-server"},{pkg:"mercurius",name:"mercurius"},{pkg:"next",name:"nextjs"},{pkg:"nuxt",name:"nuxtjs"},{pkg:"express",name:"express"},{pkg:"fastify",name:"fastify"},{pkg:"koa",name:"koa"},{pkg:"@hapi/hapi",name:"hapi"},{pkg:"hono",name:"hono"}],u=[],l=new Set;for(const{pkg:h,name:S}of g)if(!l.has(S))try{require.resolve(h),u.push(S),l.add(S)}catch{}if(typeof process<"u"){if(!l.has("nuxtjs")&&globalThis._importMeta_!==void 0){let h=!1;try{(globalThis._importMeta_?.url||"").includes(".output/server")&&(h=!0)}catch{}h&&(u.unshift("nuxtjs"),l.add("nuxtjs"))}!l.has("meteorjs")&&process.env.METEOR_SHELL_DIR&&(u.unshift("meteorjs"),l.add("meteorjs"))}return{framework:u.length>0?u[0]:null,additionalFrameworks:u.slice(1),serviceRole:u.includes("nextjs")||u.includes("nuxtjs")?"fullstack":"backend"}})();this.framework=n.framework??void 0,this.additionalFrameworks=n.additionalFrameworks,this.serviceRole=n.serviceRole;const o=process.env.SF_LOG_IGNORE_REGEX;if(o)try{this.logIgnoreRegex=new RegExp(o)}catch{}this.captureRequestHeaders=process.env.SF_NETWORKHOP_CAPTURE_REQUEST_HEADERS==="true",this.captureResponseHeaders=process.env.SF_NETWORKHOP_CAPTURE_RESPONSE_HEADERS==="true",this.captureRequestBody=process.env.SF_NETWORKHOP_CAPTURE_REQUEST_BODY==="true",this.captureResponseBody=process.env.SF_NETWORKHOP_CAPTURE_RESPONSE_BODY==="true";const a=parseInt(process.env.SF_NETWORKHOP_REQUEST_LIMIT_MB||"1",10);this.requestBodyLimitBytes=1024*(isNaN(a)?1:a)*1024;const c=parseInt(process.env.SF_NETWORKHOP_RESPONSE_LIMIT_MB||"1",10);this.responseBodyLimitBytes=1024*(isNaN(c)?1:c)*1024}getPackageVersion(){return"0.2.14"}get serviceIdentificationReceived(){return this._serviceIdentificationReceived}setServiceIdentificationReceived(e){this._serviceIdentificationReceived=e}}const P=Symbol.for("sailfish.sf_config");function O(){return globalThis[P]}function C(){const s=O();if(!s)throw new Error("Configuration has not been initialized. Call getOrCreateConfig(options) first.");return s}const m=Symbol.for("sf.ctx.storeAls"),p=globalThis,R=p[m]??(p[m]=new L.AsyncLocalStorage),M=["identitytoolkit.googleapis.com","t.co","*.twitter.com","*.gravatar.com","*.googleapis.com","*.amazonaws.com","*.smooch.io","*.zendesk.com"],D=Symbol.for("sf.ctx.als"),_=p[D]??(p[D]=new L.AsyncLocalStorage),y=Symbol.for("sf.ctx.sessionRegistry"),E=p[y]??(p[y]=new Map),v={handledExceptions:new Set,reentrancyGuardLoggingActive:!1,reentrancyGuardLoggingPreActive:!1,reentrancyGuardPrintActive:!1,reentrancyGuardPrintPreActive:!1,reentrancyGuardExceptionActive:!1,reentrancyGuardExceptionPreActive:!1,excludedDomains:new Set(M),supportedDomains:new Set};class d{static GLOBAL_MANAGER_SYMBOL=Symbol.for("sf.ctx.manager");constructor(){}current(){return R.getStore()}ensureStore(){const e=this.current();if(e)return e;const t=new Map;return R.enterWith(t),t}runWith(e,t){const r=this.current()??new Map,n=new Map(r);for(const[o,a]of Object.entries(e))n.set(o,a);return R.run(n,t)}static getInstance(){return p[d.GLOBAL_MANAGER_SYMBOL]||(p[d.GLOBAL_MANAGER_SYMBOL]=new d),p[d.GLOBAL_MANAGER_SYMBOL]}getCurrentContext(){return _.getStore()||v}setCurrentContext(e){const t=_.getStore()||v;_.enterWith({...t,...e})}ensureSession(e){let t=E.get(e);return t||(t={...v},E.set(e,t)),t}getContextFor(e){return E.get(e)??v}updateContextFor(e,t){const r=this.ensureSession(e);E.set(e,{...r,...t})}runWithSession(e,t){const r={...this.ensureSession(e)};return _.run(r,t)}deleteSession(e){E.delete(e)}getTraceId(){return this.getCurrentContext().traceId}getPageVisitUUID(){return this.getCurrentContext().pageVisitUUID}setTraceId(e){this.setCurrentContext({traceId:e})}setPageVisitUUID(e){this.setCurrentContext({pageVisitUUID:e})}getCurrentFunctionSpanId(){return this.getCurrentContext().currentFunctionSpanId}setCurrentFunctionSpanId(e){this.setCurrentContext({currentFunctionSpanId:e})}clearCurrentFunctionSpanId(){this.setCurrentContext({currentFunctionSpanId:void 0})}getOrSetSfTraceId(e,t=!1){let r=this.getTraceId();return r||(r=e||(t?I():`nonsession-applogs-v3/${C().apiKey}/${I()}`),this.setTraceId(r),C().sfDebug&&console.log(" Created new trace ID:",r),r)}getOrSetPageVisitUUID(){let e=this.getPageVisitUUID();return e||(e=I(),this.setPageVisitUUID(e),C().sfDebug&&console.log(" Created new page visit UUID:",e),e)}getHandledExceptions(){return this.getCurrentContext().handledExceptions}markExceptionHandled(e){const t=this.getHandledExceptions();t.add(e),this.setCurrentContext({handledExceptions:t})}hasHandledException(e){return this.getHandledExceptions().has(e)}resetHandledExceptions(){this.setCurrentContext({handledExceptions:new Set})}getExcludedDomains(){return this.getCurrentContext().excludedDomains}getSupportedDomains(){return this.getCurrentContext().supportedDomains}addSupportedDomains(e){this.getCurrentContext().supportedDomains.add(e.toLowerCase().trim())}setTraceIdFor(e,t){this.updateContextFor(e,{traceId:t})}setPageVisitUUIDFor(e,t){this.updateContextFor(e,{pageVisitUUID:t})}}exports.ContextManager=d,exports.DEFAULT_DOMAINS_TO_EXCLUDE=M,exports.backfillGitInfoAsync=async function(s){if(!(s.gitOrg&&s.gitRepo&&s.gitProvider))try{const e=await(async function(){let t="";try{t=await new Promise((r,n)=>{x.execFile("git",["remote","get-url","origin"],{timeout:3e3},(o,a)=>{o?n(o):r((a||"").trim())})})}catch{try{const r=(await V.readFile(".git/config","utf-8")).match(/\[remote "origin"\][^[]*url\s*=\s*(.+)/m);r&&(t=r[1].trim())}catch{}}return t?(function(r){let n,o,a;if(r.includes("github.com")?n="github":r.includes("gitlab.com")?n="gitlab":r.includes("bitbucket.org")&&(n="bitbucket"),r.startsWith("https://")||r.startsWith("http://")){const c=r.split("/");c.length>=5&&(o=c[3],a=c[4].replace(/\.git$/,""))}else{const c=r.indexOf(":");if(c>0){const g=r.substring(c+1).replace(/\.git$/,"").split("/");g.length>=2&&(o=g[0],a=g[1])}}return{org:o,repo:a,provider:n}})(t):{}})();s.gitOrg||(s.gitOrg=e.org),s.gitRepo||(s.gitRepo=e.repo),s.gitProvider||(s.gitProvider=e.provider)}catch{}},exports.getConfig=C,exports.getCurrentFunctionSpanId=function(){return d.getInstance().getCurrentFunctionSpanId()},exports.getGlobalConfigUnsafe=O,exports.getOrCreateConfig=function(s){const e=O();if(e)return{config:e};const t=new F(s);return(function(r){globalThis[P]=r})(t),t.sfDebug&&console.log("[[getOrCreateConfig]] Created global config:",t),{config:t}},exports.runWithContext=function(s){const e={...d.getInstance().getCurrentContext()};_.run(e,()=>{s()})},exports.v4=I;
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
"use strict";const mn=require("fs/promises"),Zn=require("http"),fn=require("https"),Wn=require("os"),pn=require("./source-map-rHHEdpre.cjs"),Gn=require("worker_threads"),b=require("./contextManager-0D8uHQ1_.cjs"),yn=require("path");function Bn(n){const g=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const C in n)if(C!=="default"){const e=Object.getOwnPropertyDescriptor(n,C);Object.defineProperty(g,C,e.get?e:{enumerable:!0,get:()=>n[C]})}}return g.default=n,Object.freeze(g)}const Yn=Bn(mn);function E(n){return typeof n=="string"?n:n==null?"":Array.isArray(n)?n.map(g=>String(g)).join(`
|
|
2
|
-
`):String(n)}function Vn(n){try{return JSON.stringify(n),!0}catch{return!1}}class K{file;line;function;code;locals;offender;column;constructor({file:g,line:C,function:e,code:I,locals:l={},offender:t=!1,column:c}){this.file=g,this.line=C,this.function=e,this.code=I,this.locals=l,this.offender=t,this.column=c}toDict(){const g={file:this.file,line:this.line,function:this.function,code:this.code,locals:Object.fromEntries(Object.entries(this.locals).map(([C,e])=>[C,String(e)]))};return this.offender&&(g.offender=this.offender),this.column!==void 0&&(g.column=this.column),g}toJson(){return JSON.stringify(this.toDict())}}class x{static encode(g){return g instanceof K?g.toDict():Array.isArray(g)?g.map(C=>x.encode(C)):typeof g=="object"&&g!==null?JSON.stringify(g):g}static stringify(g){return JSON.stringify(x.encode(g),(C,e)=>e instanceof K?e.toDict():e)}}const H=process.env.SF_LOG_LOCATION||"auto";let k=null,P=!1;const Cn="__sf:",ln=Error.prepareStackTrace,M=["/sf-veritas/","/@sailfish-ai/","/node_modules/","/dist/","/<","/internal/","node:"];function hn(n){for(let g=0;g<M.length;g++)if(n.includes(M[g]))return!0;return!1}function O(n){let g=n;g.startsWith("file://")&&(g=g.substring(7)),process.platform==="win32"&&g.startsWith("/")&&g.length>2&&g[2]===":"&&(g=g.substring(1));try{return yn.resolve(g)}catch{return n}}const Nn=process.env.SF_LOG_LOCATION_WALK_FRAMES==="true";function _(n){const g=Error.stackTraceLimit;Error.stackTraceLimit=8,Error.prepareStackTrace=(l,t)=>t;const C={};Error.captureStackTrace(C,n);const e=C.stack;if(Error.prepareStackTrace=ln,Error.stackTraceLimit=g,!e||e.length===0)return[null,null];for(let l=0;l<e.length;l++){const t=e[l].getFileName();if(t&&!hn(t))return[O(t),e[l].getLineNumber()]}const I=e[0].getFileName();return I?[O(I),e[0].getLineNumber()]:[null,null]}function on(n,g,C){if(H==="off")return[null,null];if(C&&(H==="auto"||H==="build-inject")){const[e,I,l]=(function(t){if(t.length===0)return[null,null,!1];const c=t[t.length-1];if(typeof c!="string"||!c.startsWith(Cn))return[null,null,!1];const i=c.lastIndexOf(":");if(i<=5)return[null,null,!1];const o=c.substring(5,i),s=parseInt(c.substring(i+1),10);return isNaN(s)?[null,null,!1]:[o,s,!0]})(C);if(l)return[e,I];if(H==="build-inject")return[null,null]}if(H==="native"){const e=(function(){if(P)return k;P=!0;try{const I=require("../native/build/Release/sf_source_location.node");typeof I?.getCallerLocation=="function"&&(k=I)}catch{}return k})();if(e){const[I,l]=e.getCallerLocation(n??2);if(I)return[I,l]}if(H==="native"&&k)return[null,null]}return g?Nn?_(g):(function(e){const I=Error.stackTraceLimit;Error.stackTraceLimit=1,Error.prepareStackTrace=(o,s)=>s;const l={};Error.captureStackTrace(l,e);const t=l.stack;if(Error.prepareStackTrace=ln,Error.stackTraceLimit=I,!t||t.length===0)return[null,null];const c=t[0],i=c.getFileName();return i?[O(i),c.getLineNumber()]:[null,null]})(g):_(on)}function p(n){if(n.length===0)return n;const g=n[n.length-1];return typeof g=="string"&&g.startsWith(Cn)?n.slice(0,-1):n}const D=console.log.bind(console),Q=console.error.bind(console),$=console.warn.bind(console),q=console.info.bind(console),nn=console.debug.bind(console),G=D,T=Q;let d=!1;const z=8192;function Hn(n){if(n===null)return"null";if(n===void 0)return"undefined";const g=typeof n;if(g==="string")return n;if(g==="number"||g==="boolean")return String(n);if(g==="bigint")return n.toString()+"n";if(g==="symbol")return n.toString();if(g==="function")return`[Function: ${n.name||"anonymous"}]`;if(n instanceof Error)return n.stack||`${n.name}: ${n.message}`;try{const C=new WeakSet,e=[],I=new Map,l=JSON.stringify(n,function(c,i){if(typeof i=="bigint")return i.toString()+"n";if(typeof i=="function")return`[Function: ${i.name||"anonymous"}]`;if(typeof i=="symbol")return i.toString();if(i===void 0)return"[undefined]";if(c!==""&&I.has(this)){const o=I.get(this);if(o>=20)return;I.set(this,o+1)}if(i!==null&&typeof i=="object"){if(C.has(i))return"[Circular]";for(;e.length>0&&e[e.length-1]!==this;)e.pop();if(e.length>=3)return Array.isArray(i)?`[Array(${i.length})]`:"[Object]";C.add(i),e.push(i),!Array.isArray(i)&&Object.keys(i).length>20&&I.set(i,0)}return i});if(l===void 0)return String(n);let t=l;if(I.size>0&&!Array.isArray(n)&&I.has(n)){const c=Object.keys(n).length;t=t.slice(0,-1)+`,"...":"${c-20} more keys"}`}return t.length>500?t.substring(0,500)+"...[truncated]":t}catch{return String(n)}}function S(n){if(n.length===0)return"";if(n.length===1&&typeof n[0]=="string"){const e=n[0];return e.length>z?e.substring(0,z)+"...[truncated]":e}let g,C=!0;for(let e=0;e<n.length;e++){const I=typeof n[e];if(I==="object"&&n[e]!==null||I==="function"||I==="symbol"){C=!1;break}}if(C){const e=new Array(n.length);for(let I=0;I<n.length;I++){const l=n[I];e[I]=l===null?"null":l===void 0?"undefined":typeof l=="string"?l:String(l)}g=e.join(" ")}else g=n.map(Hn).join(" ");return g.length>z?g.substring(0,z)+"...[truncated]":g}let X=0;function gn(n){return n=(n=(n=n.replace(/^webpack:\/\/[^\/]+\/\.?\//,"")).replace(/^.*\/pages\//,"pages/")).replace(/\.(js|ts)$/,"")}const Jn=50,v=new Map;function en(n,g){if(v.size>=Jn){const C=v.keys().next().value;v.delete(C)}v.set(n,g)}function wn(n){return n?.split("/").pop()||"<unknown>"}function sn(n,g){if(!n||typeof n!="object")return!1;for(const C of Object.values(n))if(typeof C=="string"&&C.includes(g)||typeof C=="object"&&sn(C,g))return!0;return!1}let Y,J,L,tn=!1;function rn(n){if(!n)return;const g=n.toLowerCase().trim();return!!["1","true","yes","on"].includes(g)||!["0","false","no","off"].includes(g)&&void 0}function An(){if(Y!==void 0)return Y;const n=process.env||{},g=rn(n.SF_IS_LOCAL);if(g!==void 0)return Y=g;const C=(n.SF_ENV||n.NODE_ENV||"").toLowerCase();if(["local","dev","development"].includes(C))return Y=!0;if(["KUBERNETES_SERVICE_HOST","AWS_EXECUTION_ENV","ECS_CONTAINER_METADATA_URI","ECS_CONTAINER_METADATA_URI_V4","GAE_ENV","K_SERVICE","GOOGLE_CLOUD_PROJECT","WEBSITE_INSTANCE_ID","VERCEL","NETLIFY","DYNO","RENDER","FLY_APP_NAME","RAILWAY_STATIC_URL","CF_PAGES","CLOUDFLARE"].some(I=>!!n[I]))return Y=!1;const e=(Wn.hostname?.()||n.HOSTNAME||"").toLowerCase();return Y=!(e!=="localhost"&&!e.endsWith(".local")&&!e.includes("local"))}function j(n,g,C){return new Promise(e=>{try{const I=new URL(n),l=(I.protocol==="https:"?fn:Zn).request({method:"GET",hostname:I.hostname,port:I.port||(I.protocol==="https:"?443:80),path:I.pathname+(I.search||""),headers:g},t=>{t.resume(),t.statusCode&&t.statusCode>=200&&t.statusCode<400?e("ok"):e("http_error")});l.on("error",()=>e("error")),l.setTimeout(C,()=>{l.destroy(),e("timeout")}),l.end()}catch{e("error")}})}function In(){if(J!==void 0)return J;const n=process.env.SF_FUNCSPAN_RUNTIME_ENABLED;if(n==="true"||n==="1")return J=!0,!0;if(n==="false"||n==="0")return J=!1,!1;try{const{isRuntimeModeConfigured:g}=require("../funcSpanConfigLoader");if(g&&g())return J=!0,!0}catch{}return J=!1,!1}function cn(){return L!==void 0||(L=!An()),L}exports.CustomJSONEncoderForFrameInfo=x,exports.initializeExceptionInterceptor=function(n){b.getConfig().sfDebug&&G("Initializing Exception Interceptor...");try{const c=An();n?.setSupplementalFields?.({isFromLocalService:c}),(async function(i){if(tn)return;tn=!0;const o=process.env||{};if(rn(o.SF_IS_LOCAL)===void 0)try{await(async function(s){const V=j("http://169.254.169.254/latest/meta-data/",{},s),m=j("http://metadata.google.internal/computeMetadata/v1/instance/",{"Metadata-Flavor":"Google"},s),a=j("http://169.254.169.254/metadata/instance?api-version=2021-02-01",{Metadata:"true"},s);return(await Promise.allSettled([V,m,a])).some(f=>f.status==="fulfilled"&&(f.value==="ok"||f.value==="http_error"))})(150)&&Y&&(Y=!1,i?.setSupplementalFields?.({isFromLocalService:!1}))}catch{}})(n).catch(()=>{})}catch{}const g=new Gn.Worker(new URL("data:application/javascript;base64,Ly8gc3JjL2RlYnVnZ2VyV29ya2VyLnRzCmltcG9ydCB7IFNlc3Npb24gfSBmcm9tICJpbnNwZWN0b3IvcHJvbWlzZXMiOwppbXBvcnQgeyBwYXJlbnRQb3J0LCB3b3JrZXJEYXRhIH0gZnJvbSAid29ya2VyX3RocmVhZHMiOwpnbG9iYWwuc2ZEZWJ1ZyA9IHZvaWQgMDsKZ2xvYmFsLnN0YWNrRGVwdGhMb2NhbHMgPSB2b2lkIDA7Cmdsb2JhbC5ub2RlTW9kdWxlc1RvQ29sbGVjdExvY2FsVmFyaWFibGVzT24gPSB2b2lkIDA7CnZhciBzY3JpcHRTb3V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BmaWxlID0gIiI7CiAgICAgICAgaWYgKHVybCAmJiB1cmwudHJpbSgpICE9PSAiIikgewogICAgICAgICAgZmlsZSA9IHVybDsKICAgICAgICB9IGVsc2UgaWYgKGRlc2NyaXB0aW9uTGluZXNbaW5kZXhdKSB7CiAgICAgICAgICBmaWxlID0gZGVzY3JpcHRpb25MaW5lc1tpbmRleF0udHJpbSgpOwogICAgICAgIH0gZWxzZSB7CiAgICAgICAgICBmaWxlID0gIjx1bmtub3duPiI7CiAgICAgICAgfQogICAgICAgIGlmIChsb2NhdGlvbiAmJiBsb2NhdGlvbi5zY3JpcHRJZCkgewogICAgICAgICAgY29uc3Qgc2NyaXB0SWQgPSBsb2NhdGlvbi5zY3JpcHRJZDsKICAgICAgICAgIHRyeSB7CiAgICAgICAgICAgIGxldCBzY3JpcHRTb3VyY2UgPSBzY3JpcHRTb3VyY2VDYWNoZS5nZXQoc2NyaXB0SWQpOwogICAgICAgICAgICBpZiAoc2NyaXB0U291cmNlID09PSB2b2lkIDApIHsKICAgICAgICAgICAgICBjb25zdCByZXN1bHQgPSBhd2FpdCBzZXNzaW9uLnBvc3QoCiAgICAgICAgICAgICAgICAiRGVidWdnZXIuZ2V0U2NyaXB0U291cmNlIiwKICAgICAgICAgICAgICAgIHsKICAgICAgICAgICAgICAgICAgc2NyaXB0SWQKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICApOwogICAgICAgICAgICAgIHNjcmlwdFNvdXJjZSA9IHJlc3VsdC5zY3JpcHRTb3VyY2U7CiAgICAgICAgICAgICAgc2NyaXB0U291cmNlQ2FjaGUuc2V0KHNjcmlwdElkLCBzY3JpcHRTb3VyY2UpOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGNvbnN0IHNvdXJjZUxpbmVzID0gc2NyaXB0U291cmNlLnNwbGl0KCJcbiIpOwogICAgICAgICAgICBjb2RlID0gc291cmNlTGluZXNbbG9jYXRpb24ubGluZU51bWJlcl0gfHwgIjxub3QgY2FwdHVyZWQ+IjsKICAgICAgICAgIH0gY2F0Y2ggKGVycikgewogICAgICAgICAgICBpZiAoZ2xvYmFsLnNmRGVidWcpIHsKICAgICAgICAgICAgICBjb25zb2xlLmVycm9yKCJbV29ya2VyXSBGYWlsZWQgdG8gZmV0Y2ggc2NyaXB0IHNvdXJjZToiLCBlcnIpOwogICAgICAgICAgICB9CiAgICAgICAgICB9CiAgICAgICAgfQogICAgICAgIGNvbnN0IGxvY2FscyA9IGxvY2FsU2NvcGU/Lm9iamVjdD8ub2JqZWN0SWQgPyBhd2FpdCBmZXRjaExvY2FsVmFyaWFibGVzKHNlc3Npb24sIGxvY2FsU2NvcGUub2JqZWN0Lm9iamVjdElkKSA6IHt9OwogICAgICAgIHJldHVybiB7CiAgICAgICAgICBmdW5jdGlvbjogZnVuY3Rpb25OYW1lIHx8ICI8YW5vbnltb3VzPiIsCiAgICAgICAgICBsb2NhbHMsCiAgICAgICAgICBmaWxlLAogICAgICAgICAgbGluZTogbG9jYXRpb24/LmxpbmVOdW1iZXIgfHwgMCwKICAgICAgICAgIGNvZGUKICAgICAgICB9OwogICAgICB9IGNhdGNoIChlcnJvcikgewogICAgICAgIGlmIChnbG9iYWwuc2ZEZWJ1ZykgewogICAgICAgICAgY29uc29sZS5lcnJvcigiW1dvcmtlcl0gRXJyb3IgcHJvY2Vzc2luZyBjYWxsIGZyYW1lOiIsIGVycm9yKTsKICAgICAgICB9CiAgICAgICAgcmV0dXJuIHsKICAgICAgICAgIGZ1bmN0aW9uOiAiPGVycm9yPiIsCiAgICAgICAgICBsb2NhbHM6IHt9LAogICAgICAgICAgZmlsZTogIjx1bmtub3duPiIsCiAgICAgICAgICBsaW5lOiAwLAogICAgICAgICAgY29kZTogIjxub3QgY2FwdHVyZWQ+IgogICAgICAgIH07CiAgICAgIH0KICAgIH0pCiAgKTsKICBwYXJlbnRQb3J0Py5wb3N0TWVzc2FnZSh7IHR5cGU6ICJleGNlcHRpb24iLCBmcmFtZXMgfSk7Cn0KYXN5bmMgZnV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1dvcmtlcl0gRmFpbGVkIHRvIGZldGNoIGxvY2FsIHZhcmlhYmxlczoiLCBlcnIpOwogICAgfQogICAgcmV0dXJuIHt9OwogIH0KfQpzdGFydERlYnVnZ2VyKCkuY2F0Y2goKGVycm9yKSA9PiB7CiAgaWYgKGdsb2JhbC5zZkRlYnVnKSB7CiAgICBjb25zb2xlLmVycm9yKCJbV29ya2VyXSBGYWlsZWQgdG8gc3RhcnQgZGVidWdnZXI6IiwgZXJyb3IpOwogIH0KfSk7CnNldEludGVydmFsKCgpID0+IHsKfSwgMWU0KTsKZXhwb3J0IHsKICBwcm9jZXNzQ2FsbEZyYW1lcwp9Owo="),{workerData:{captureAllExceptions:process.env.SF_CAPTURE_ALL_EXCEPTIONS==="true"}});let C=null;const e=new WeakMap;g.on("message",async c=>{if(typeof c=="string"&&b.getConfig().sfDebug&&G(`[Worker] ${c}`),c.readyToGetParameters&&g.postMessage({sfDebug:b.getConfig().sfDebug,stackDepthLocals:b.getConfig().stackDepthLocals,nodeModulesToCollectLocalVariablesOn:b.getConfig().nodeModulesToCollectLocalVariablesOn}),c.type==="exception"){const{frames:i}=c,o=C;if(!o)return;const s=(function(m){return m?m.split(`
|
|
3
|
-
`).slice(1).map(a=>{const f=/at (.+?) \((.+):(\d+):(\d+)\)/.exec(a)||/at (.+):(\d+):(\d+)/.exec(a);if(f){const[,W,B,A,Z]=f;return new K({function:W||"<anonymous>",locals:{},file:B||"<unknown>",line:parseInt(A,10)||0,code:"<not captured>",column:parseInt(Z)||0})}return new K({function:"<unknown>",locals:{},file:"<unknown>",line:0,code:"<not captured>",column:0})}):[]})(E(o.stack)),V=(function(m,a){const f=[];let W=-1,B=-1;for(let A=0;A<m.length;A++){const Z=wn(m[A].file);if(B=A,Z!=="<unknown>"){for(let u=0;u<a.length;u++){const y=a[u];if(sn(y,Z)||typeof y.file=="string"&&y.file.includes(Z)){W=u,X=0,b.getConfig().sfDebug&&G(`✅ Matched Frame Found: ${Z} @ Debugger Frame ${u}`);break}}if(W!==-1)break}}if(W===-1)return X===10?(X=0,m):(++X,b.getConfig().sfDebug&&G(`"❌ No matching frame found. Checking once again, Attempt N ${X}"`),[]);b.getConfig().sfDebug&&G(`🔄 Merging from matched index ${W} onward...`);for(let A=0;A<a.length;A++){const Z=m[B+A],u=a[W+A];f.push(new K({function:u?.function||Z?.function||"<anonymous>",locals:u?.locals||Z?.locals||{},file:Z?.file||u?.file||"<unknown>",line:u?.line||Z?.line||0,code:u?.code||Z?.code||"<not captured>"}))}return f})(s,i||[]);if(V.length!==0){C=null;const m=b.getConfig().stackDepthCodeTraceDepth,a=m===-1?V:V.slice(0,m+1),f=Math.min(a.length,s.length);await Promise.all(Array.from({length:f},async(Z,u)=>{const y=await(async function(un,bn,an){const h=(function(r){r.startsWith("at ")&&(r=r.slice(3).trim());const N=r.match(/^(.*?)(:\d+)+(\.map)?$/);return N?N[1]:r})(un);if(!h||h==="<unknown>")return null;const w=h+".map";try{let r=v.get(w);if(r===void 0){const R=await Yn.readFile(w,"utf-8");r=R?JSON.parse(R):null,en(w,r)}if(!r)return null;let N=new pn.sourceMapExports.SourceMapConsumer(r).originalPositionFor({line:bn,column:an});if(h&&N.source){const R=gn(h),U=r.sources.findIndex(F=>gn(F)===R);if(U===-1)b.getConfig().sfDebug&&G(`Source file "${h}" not found in the source map.`);else{const F=r.sourcesContent[U],dn=r.names.join(",");if(F)return{content:F.split(`
|
|
4
|
-
`).slice(N.line-1,N.line+20).join(`
|
|
5
|
-
`),name:dn,file:N.source};b.getConfig().sfDebug&&G(`No source content available for file "${h}".`)}}return{content:r.sourcesContent[0],name:r.names[0],file:r.file}}catch(r){b.getConfig().sfDebug&&G(`Cant read/parse "${w}: Error - ".`,r),en(w,null)}return null})(a[u].file,s[u].line,s[u].column);y&&(y.content!=null&&(a[u].code=y.content),y.file!=null&&(a[u].file=y.file))})),n.setOperationName("CollectExceptions");const W=o.message?`${o.name}: ${o.message}`:o.name;b.getConfig().sfDebug&&G("error message is : ",W);const B=b.ContextManager.getInstance(),A=e.get(o);A?(B.setTraceIdFor(A,A),B.runWithSession(A,()=>{B.setTraceId(A),n.doSend(W,a)})):n.doSend(W,a)}}}),g.on("error",c=>{T("[Worker Error]",c)}),g.on("exit",c=>{T(`[Worker] Exited with code ${c}`)}),g.unref();const I=Error,l=new Set;function t(...c){const i=Reflect.construct(I,c);Reflect.setPrototypeOf(i,t.prototype);try{const s=b.ContextManager.getInstance().getTraceId();e.set(i,s)}catch{}I.captureStackTrace&&I.captureStackTrace(i,t);const o=`${i.message}:${E(i.stack).split(`
|
|
6
|
-
`)[1]?.trim()}`;if(!l.has(o)){if(l.add(o),l.size>1e3){const s=l.values().next().value;l.delete(s)}C=i,g.postMessage({type:"processException",error:i.message})}return i}t.prototype=Object.create(I.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),Object.setPrototypeOf(t,I),globalThis.Error=t},exports.initializeLogInterceptor=function(n){function g(t,c,i,o){const s=b.getGlobalConfigUnsafe();if(s?.logIgnoreRegex&&s.logIgnoreRegex.test(c))return;const[V,m]=on(2,i,o);n.setOperationName("CollectLogs"),n.doSend([c,t,V,m])}const C=console.log=(...t)=>{if(d)D(...p(t));else{d=!0;try{const c=p(t);g("INFO",S(c),C,t),D(...c)}finally{d=!1}}},e=console.error=(...t)=>{if(d)Q(...p(t));else{d=!0;try{const c=p(t);g("ERROR",S(c),e,t),Q(...c)}finally{d=!1}}},I=console.warn=(...t)=>{if(d)$(...p(t));else{d=!0;try{const c=p(t);g("WARN",S(c),I,t),$(...c)}finally{d=!1}}},l=console.info=(...t)=>{if(d)q(...p(t));else{d=!0;try{const c=p(t);g("INFO",S(c),l,t),q(...c)}finally{d=!1}}};if(b.getConfig().logLevel==="DEBUG"){const t=console.debug=(...c)=>{if(d)nn(...p(c));else{d=!0;try{const i=p(c);g("DEBUG",S(i),t,c),nn(...i)}finally{d=!1}}}}},exports.internalError=T,exports.internalLog=G,exports.isProductionEnvironment=cn,exports.isRuntimeModeEnabled=In,exports.serializeJsonWithExclusions=function(n){const g={},C=[];if(n)for(const[e,I]of Object.entries(n))Vn(I)?g[e]=I:C.push(e);return{traitsJson:JSON.stringify(g),excludedFields:C}},exports.shouldEnableRuntimeHooks=function(){return!!In()&&(!cn()||(console.warn("[FuncSpan Runtime] DISABLED in production environment"),!1))},exports.stackToString=E;
|