@sailfish-ai/sf-veritas 0.2.4 → 0.2.6
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 +120 -0
- package/dist/funcSpanTransformer-TjdooSrw.cjs +1 -0
- package/dist/funcSpanTransformer-sqmZLAcs.js +750 -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/funcspanWebpackLoader.cjs +1 -1
- package/dist/plugins/funcspanWebpackLoader.mjs +65 -8
- package/dist/plugins/funcspanWebpackPlugin.cjs +1 -1
- package/dist/plugins/funcspanWebpackPlugin.mjs +24 -24
- package/dist/runtime/register.cjs +1 -0
- package/dist/runtime/register.mjs +27 -0
- package/dist/sf-veritas.cjs +16 -52
- package/dist/sf-veritas.mjs +573 -811
- package/dist/types/functionSpanTransmitter.d.ts +15 -1
- package/dist/types/index.d.ts +2 -0
- package/dist/types/patches/workerPool/argumentCapture.d.ts +47 -0
- package/dist/types/patches/workerPool/index.d.ts +19 -0
- package/dist/types/patches/workerPool/patchCrypto.d.ts +9 -0
- package/dist/types/patches/workerPool/patchDns.d.ts +10 -0
- package/dist/types/patches/workerPool/patchFs.d.ts +9 -0
- package/dist/types/patches/workerPool/patchZlib.d.ts +9 -0
- package/dist/types/patches/workerPool/workerPoolTypes.d.ts +70 -0
- package/dist/types/plugins/funcspanWebpackPlugin.d.ts +20 -0
- package/dist/types/plugins/workerPoolTransformer.d.ts +42 -0
- package/dist/types/requestUtils.d.ts +1 -0
- package/dist/types/runtime/register.d.ts +56 -0
- package/dist/types/worker-pool-capture.d.ts +9 -0
- package/dist/types/workerPoolConfig.d.ts +22 -0
- package/dist/types/workerPoolSpanCapture.d.ts +36 -0
- package/dist/worker-pool-capture.cjs +1 -0
- package/dist/worker-pool-capture.mjs +4 -0
- package/dist/workerPoolSpanCapture-BOnYC4s3.js +705 -0
- package/dist/workerPoolSpanCapture-CNEouInA.cjs +83 -0
- package/package.json +17 -1
- package/dist/funcSpanTransformer-CTddGtUV.cjs +0 -1
- package/dist/funcSpanTransformer-coYDqcrs.js +0 -136
- package/dist/source-map-Cr6YkjTd.js +0 -631
- package/dist/source-map-rHHEdpre.cjs +0 -1
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"use strict";var ne=Object.defineProperty;var oe=(t,e,n)=>e in t?ne(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var c=(t,e,n)=>oe(t,typeof e!="symbol"?e+"":e,n);const P=require("async_hooks"),se=require("fs"),k=require("worker_threads"),l=[];for(let t=0;t<256;++t)l.push((t+256).toString(16).slice(1));let L;const ae=new Uint8Array(16),z={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function v(t,e,n){if(z.randomUUID&&!t)return z.randomUUID();const a=(t=t||{}).random??t.rng?.()??(function(){if(!L){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");L=crypto.getRandomValues.bind(crypto)}return L(ae)})();if(a.length<16)throw new Error("Random bytes length must be >= 16");return a[6]=15&a[6]|64,a[8]=63&a[8]|128,(function(s,i=0){return(l[s[i+0]]+l[s[i+1]]+l[s[i+2]]+l[s[i+3]]+"-"+l[s[i+4]]+l[s[i+5]]+"-"+l[s[i+6]]+l[s[i+7]]+"-"+l[s[i+8]]+l[s[i+9]]+"-"+l[s[i+10]]+l[s[i+11]]+l[s[i+12]]+l[s[i+13]]+l[s[i+14]]+l[s[i+15]]).toLowerCase()})(a)}class ie{constructor(e){c(this,"apiKey");c(this,"apiGraphqlEndpoint");c(this,"sfDebug");c(this,"serviceIdentifier");c(this,"serviceVersion");c(this,"serviceUUID");c(this,"serviceAdditionalMetadata");c(this,"profilingModeEnabled");c(this,"profilingMaxDepth");c(this,"profilingMaxVariableSizeKb");c(this,"domainsToNotPropagateHeadersTo");c(this,"nodeModulesToCollectLocalVariablesOn");c(this,"printConfigurationStatuses");c(this,"logLevel");c(this,"stackDepthLocals");c(this,"stackDepthCodeTraceDepth");c(this,"packageLibraryType");c(this,"version");c(this,"gitSha");c(this,"_serviceIdentificationReceived",!1);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=v(),this.serviceVersion=e?.serviceVersion||process.env.SERVICE_VERSION,this.gitSha=e?.gitSha||process.env.GIT_SHA||process.env.VERCEL_GIT_COMMIT_SHA,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()}getPackageVersion(){return"0.1.15"}get serviceIdentificationReceived(){return this._serviceIdentificationReceived}setServiceIdentificationReceived(e){this._serviceIdentificationReceived=e}}const Z=Symbol.for("sailfish.sf_config");function T(){return globalThis[Z]}function f(){const t=T();if(!t)throw new Error("Configuration has not been initialized. Call getOrCreateConfig(options) first.");return t}const J=Symbol.for("sf.ctx.storeAls"),h=globalThis,R=h[J]??(h[J]=new P.AsyncLocalStorage),ee=["identitytoolkit.googleapis.com","t.co","*.twitter.com","*.gravatar.com","*.googleapis.com","*.amazonaws.com","*.smooch.io","*.zendesk.com"],q=Symbol.for("sf.ctx.als"),A=h[q]??(h[q]=new P.AsyncLocalStorage),j=Symbol.for("sf.ctx.sessionRegistry"),E=h[j]??(h[j]=new Map),D={handledExceptions:new Set,reentrancyGuardLoggingActive:!1,reentrancyGuardLoggingPreActive:!1,reentrancyGuardPrintActive:!1,reentrancyGuardPrintPreActive:!1,reentrancyGuardExceptionActive:!1,reentrancyGuardExceptionPreActive:!1,excludedDomains:new Set(ee),supportedDomains:new Set},I=class I{constructor(){}current(){return R.getStore()}ensureStore(){const e=this.current();if(e)return e;const n=new Map;return R.enterWith(n),n}runWith(e,n){const a=this.current()??new Map,s=new Map(a);for(const[i,r]of Object.entries(e))s.set(i,r);return R.run(s,n)}static getInstance(){return h[I.GLOBAL_MANAGER_SYMBOL]||(h[I.GLOBAL_MANAGER_SYMBOL]=new I),h[I.GLOBAL_MANAGER_SYMBOL]}getCurrentContext(){return A.getStore()||D}setCurrentContext(e){const n=A.getStore()||D;A.enterWith({...n,...e})}ensureSession(e){let n=E.get(e);return n||(n={...D},E.set(e,n)),n}getContextFor(e){return E.get(e)??D}updateContextFor(e,n){const a=this.ensureSession(e);E.set(e,{...a,...n})}runWithSession(e,n){const a={...this.ensureSession(e)};return A.run(a,n)}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,n=!1){let a=this.getTraceId();return a||(a=e||(n?v():`nonsession-applogs-v3/${f().apiKey}/${v()}`),this.setTraceId(a),f().sfDebug&&console.log(" Created new trace ID:",a),a)}getOrSetPageVisitUUID(){let e=this.getPageVisitUUID();return e||(e=v(),this.setPageVisitUUID(e),f().sfDebug&&console.log(" Created new page visit UUID:",e),e)}getHandledExceptions(){return this.getCurrentContext().handledExceptions}markExceptionHandled(e){const n=this.getHandledExceptions();n.add(e),this.setCurrentContext({handledExceptions:n})}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,n){this.updateContextFor(e,{traceId:n})}setPageVisitUUIDFor(e,n){this.updateContextFor(e,{pageVisitUUID:n})}};c(I,"GLOBAL_MANAGER_SYMBOL",Symbol.for("sf.ctx.manager"));let y=I;class re{constructor(){c(this,"apiKey");c(this,"endpoint");c(this,"queryType","mutation");c(this,"operationName","");c(this,"serviceUUID",f().serviceUUID);c(this,"contextManager");this.apiKey=f().apiKey,this.endpoint=f().apiGraphqlEndpoint,this.contextManager=y.getInstance()}get queryName(){return this.operationName?this.operationName.charAt(0).toLowerCase()+this.operationName.slice(1):""}getDefaultVariables(){const e=Date.now().toString(),n=this.contextManager.getOrSetSfTraceId(),a=this.contextManager.getCurrentFunctionSpanId();return{apiKey:this.apiKey,serviceUuid:this.serviceUUID,sessionId:n,timestampMs:e,parentSpanId:a}}getVariables(e={}){return{...this.getDefaultVariables(),...e}}setOperationName(e){this.operationName=e}setEndpoint(e){this.endpoint=e}setServiceUUID(e){this.serviceUUID=e}}const ce=fetch;let F=!1;async function K(t,e,n,a){try{const s=f();let i;try{i=JSON.stringify({query:n,variables:a,operationName:e})}catch{i=JSON.stringify({query:n,operationName:e})}F=!0,ce(t,{method:"POST",headers:{"Content-Type":"application/json"},body:i}).then(async r=>{if(F=!1,!r.ok)return void(s.sfDebug&&console.error(`GraphQL request failed with status ${r.status} for ${e}`));const o=await r.json();o.errors?.length?(function(u,m,p){const g=u&&typeof u=="object"&&!Array.isArray(u)?Object.keys(u)[0]:void 0;console.error(g==="identifyServiceDetails"?`IdentifyServiceDetails NOT sent successfully for service: UUID=${p.serviceUUID}`:`GraphQL request failed with errors: ${JSON.stringify(m)} for operation key ${g}`)})(o.data,o.errors,s):s.sfDebug&&(function(u,m,p){const g=u&&typeof u=="object"&&!Array.isArray(u)?Object.keys(u)[0]:void 0,d=u[g]||!1;g==="identifyServiceDetails"&&(p.setServiceIdentificationReceived(d),f().sfDebug&&console.log(`IdentifyServiceDetails sent successfully for service: UUID=${p.serviceUUID}; serviceIdentificationReceived=${g==="identifyServiceDetails"?d:"N/A"}`))})(o.data,0,s)}).catch(r=>{F=!1,s.sfDebug&&(console.error(`[RequestUtils] Fetch error for ${e} to ${t}:`,r),r.cause&&console.error("[RequestUtils] Error cause:",r.cause))})}catch(s){F=!1,f().sfDebug&&console.error("Error sending data to GraphQL server:",s)}}function C(t,e){if(!t)return e;const n=t.toLowerCase();return n==="true"||n==="1"||n==="yes"}const M=new P.AsyncLocalStorage;function B(t,e){try{const n=JSON.stringify(t).length/1048576;return n<=e?t:{_truncated:!0,_originalSizeMB:n.toFixed(2),_limitMB:e,_preview:JSON.stringify(t).substring(0,500)+"..."}}catch{return{_error:"Failed to serialize data",_type:typeof t}}}function _(t,e){const n=process.env[t];return n===void 0?e:n==="true"||n==="1"}function Q(t,e){const n=process.env[t];if(n===void 0)return e;const a=parseFloat(n);return isNaN(a)?e:a}function x(){return{enabled:_("SF_WORKER_POOL_ENABLED",!0),trackFs:_("SF_WORKER_POOL_TRACK_FS",!1),trackDns:_("SF_WORKER_POOL_TRACK_DNS",!0),trackCrypto:_("SF_WORKER_POOL_TRACK_CRYPTO",!1),trackZlib:_("SF_WORKER_POOL_TRACK_ZLIB",!1),captureArguments:_("SF_WORKER_POOL_CAPTURE_ARGUMENTS",!0),captureReturnValue:_("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(t,e,n,a){let s;try{switch(t){case"fs":s=(function(i,r){const o={};switch(i){case"readFile":case"writeFile":case"appendFile":o.path=String(r[0]||""),r[1]&&typeof r[1]=="object"?(o.encoding=r[1].encoding||null,o.flag=r[1].flag||null):typeof r[1]=="string"&&(o.encoding=r[1]),i!=="writeFile"&&i!=="appendFile"||(Buffer.isBuffer(r[1])?(o.dataType="Buffer",o.dataSize=r[1].length):typeof r[1]=="string"&&(o.dataType="string",o.dataSize=r[1].length));break;case"readdir":case"stat":case"lstat":case"access":case"chmod":case"mkdir":case"rmdir":case"unlink":o.path=String(r[0]||""),r[1]&&typeof r[1]=="object"&&(o.options={...r[1]},delete o.options.callback);break;case"rename":o.oldPath=String(r[0]||""),o.newPath=String(r[1]||"");break;case"open":o.path=String(r[0]||""),o.flags=r[1],o.mode=r[2];break;case"close":case"fstat":o.fd=r[0];break;case"read":case"write":o.fd=r[0],Buffer.isBuffer(r[1])&&(o.bufferSize=r[1].length),o.offset=r[2],o.length=r[3],o.position=r[4];break;default:o.argsCount=r.length-1}return o})(e,n);break;case"dns":s=(function(i,r){const o={};switch(i){case"lookup":o.hostname=String(r[0]||""),typeof r[1]=="object"?(o.family=r[1].family,o.all=r[1].all):typeof r[1]=="number"&&(o.family=r[1]);break;case"resolve":case"resolve4":case"resolve6":case"resolveAny":case"resolveMx":case"resolveNs":case"resolveTxt":o.hostname=String(r[0]||"");break;case"reverse":o.ip=String(r[0]||"");break;default:o.argsCount=r.length-1}return o})(e,n);break;case"crypto":s=(function(i,r){const o={};switch(i){case"pbkdf2":o.passwordType=typeof r[0],o.saltType=typeof r[1],o.iterations=r[2],o.keylen=r[3],o.digest=r[4];break;case"scrypt":o.passwordType=typeof r[0],o.saltType=typeof r[1],o.keylen=r[2],typeof r[3]=="object"&&(o.N=r[3].N,o.r=r[3].r,o.p=r[3].p);break;case"randomBytes":o.size=r[0];break;case"generateKeyPair":o.type=r[0],typeof r[1]=="object"&&(o.modulusLength=r[1].modulusLength,o.namedCurve=r[1].namedCurve);break;default:o.argsCount=r.length-1}return o})(e,n);break;case"zlib":s=(function(i,r){const o={};return Buffer.isBuffer(r[0])?(o.inputType="Buffer",o.inputSize=r[0].length):typeof r[0]=="string"?(o.inputType="string",o.inputSize=r[0].length):o.inputType=typeof r[0],r[1]&&typeof r[1]=="object"&&typeof r[1]!="function"&&(o.options={...r[1]}),o})(0,n);break;default:return null}return a>0?B(s,a):s}catch{return{error:"Failed to capture arguments",argsCount:n.length-1}}}function Y(t,e,n,a){let s;try{switch(t){case"fs":s=(function(i,r){if(!r)return null;switch(i){case"readFile":return Buffer.isBuffer(r)?{type:"Buffer",size:r.length}:typeof r=="string"?{type:"string",size:r.length}:{type:typeof r};case"readdir":return{count:Array.isArray(r)?r.length:0,items:r};case"stat":case"lstat":case"fstat":return{size:r.size,mode:r.mode,isFile:r.isFile(),isDirectory:r.isDirectory()};case"open":return{fd:r};case"read":return{bytesRead:r};case"write":return{bytesWritten:r};default:return r}})(e,n);break;case"dns":s=(function(i,r){if(!r)return null;switch(i){case"lookup":return Array.isArray(r)?{count:r.length,addresses:r}:r;case"resolve":case"resolve4":case"resolve6":case"resolveAny":case"resolveMx":case"resolveNs":case"resolveTxt":return{count:Array.isArray(r)?r.length:0,records:r};case"reverse":return{hostnames:r};default:return r}})(e,n);break;case"crypto":s=(function(i,r){if(!r)return null;switch(i){case"pbkdf2":case"scrypt":case"randomBytes":return Buffer.isBuffer(r)?{type:"Buffer",size:r.length}:{type:typeof r};case"generateKeyPair":return{hasPublicKey:!!r?.publicKey,hasPrivateKey:!!r?.privateKey};default:return r}})(e,n);break;case"zlib":s=(function(i,r){return r?Buffer.isBuffer(r)?{type:"Buffer",size:r.length}:typeof r=="string"?{type:"string",size:r.length}:{type:typeof r}:null})(0,n);break;default:return null}return a>0?B(s,a):s}catch{return{error:"Failed to capture result",type:typeof n}}}function ue(t){return t.operationType==="worker_pool"}class te extends re{constructor(){super(),this.operationName="CollectFunctionSpans"}send(e){const n=f().sfDebug;n&&console.log(`[FunctionSpanTransmitter] Preparing to send ${e.length} function span(s)`);for(const a of e)try{if(ue(a)){this.sendWorkerPoolSpan(a,n);continue}const s=a;let i;if(s.result!==void 0&&s.result!==null){const o=typeof s.result;i=JSON.stringify({type:o,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 r=this.getVariables({library:"JS/TS BACKEND",version:f().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()});n&&(console.log(`[FunctionSpanTransmitter] Sending GraphQL mutation to ${this.endpoint}`),console.log("[FunctionSpanTransmitter] Variables:",JSON.stringify(r,null,2))),K(this.endpoint,this.operationName,this.getQuery(),r),n&&console.log(`[FunctionSpanTransmitter] Queued function span for ${s.functionName}`)}catch(s){console.error(`[FunctionSpanTransmitter] Error preparing function span for ${a.functionName}:`,s)}}sendWorkerPoolSpan(e,n){try{let a;if(e.result!==void 0&&e.result!==null){const i=typeof e.result;a=JSON.stringify({type:i,has_value:!0,value:e.result})}else a=e.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:f().version,spanId:e.spanId,operationName:e.operationName,moduleName:e.moduleName,methodName:e.methodName,startTimeNs:e.startTimeNs,durationNs:e.durationNs,arguments:JSON.stringify(e.args||{}),returnValue:a,error:e.error,pid:e.pid,threadId:e.threadId});n&&(console.log(`[FunctionSpanTransmitter] Sending worker pool span: ${e.operationName}`),console.log("[FunctionSpanTransmitter] Variables:",JSON.stringify(s,null,2))),K(this.endpoint,"CollectWorkerPoolSpans",this.getWorkerPoolQuery(),s),n&&console.log(`[FunctionSpanTransmitter] Queued worker pool span for ${e.operationName}`)}catch(a){console.error(`[FunctionSpanTransmitter] Error preparing worker pool span for ${e.operationName}:`,a)}}getWorkerPoolQuery(){return`
|
|
2
|
+
mutation CollectWorkerPoolSpans(
|
|
3
|
+
$apiKey: String!,
|
|
4
|
+
$serviceUuid: String!,
|
|
5
|
+
$sessionId: String!,
|
|
6
|
+
$timestampMs: String!,
|
|
7
|
+
$library: String!,
|
|
8
|
+
$version: String!,
|
|
9
|
+
$spanId: String!,
|
|
10
|
+
$operationName: String!,
|
|
11
|
+
$moduleName: String!,
|
|
12
|
+
$methodName: String!,
|
|
13
|
+
$startTimeNs: String!,
|
|
14
|
+
$durationNs: String!,
|
|
15
|
+
$parentSpanId: String,
|
|
16
|
+
$arguments: String,
|
|
17
|
+
$returnValue: String,
|
|
18
|
+
$error: String,
|
|
19
|
+
$pid: Int,
|
|
20
|
+
$threadId: Int
|
|
21
|
+
) {
|
|
22
|
+
collectWorkerPoolSpans(
|
|
23
|
+
apiKey: $apiKey,
|
|
24
|
+
serviceUuid: $serviceUuid,
|
|
25
|
+
sessionId: $sessionId,
|
|
26
|
+
timestampMs: $timestampMs,
|
|
27
|
+
library: $library,
|
|
28
|
+
version: $version,
|
|
29
|
+
spanId: $spanId,
|
|
30
|
+
operationName: $operationName,
|
|
31
|
+
moduleName: $moduleName,
|
|
32
|
+
methodName: $methodName,
|
|
33
|
+
startTimeNs: $startTimeNs,
|
|
34
|
+
durationNs: $durationNs,
|
|
35
|
+
parentSpanId: $parentSpanId,
|
|
36
|
+
arguments: $arguments,
|
|
37
|
+
returnValue: $returnValue,
|
|
38
|
+
error: $error,
|
|
39
|
+
pid: $pid,
|
|
40
|
+
threadId: $threadId
|
|
41
|
+
)
|
|
42
|
+
}
|
|
43
|
+
`}getQuery(){return`
|
|
44
|
+
${this.queryType} ${this.operationName}(
|
|
45
|
+
$apiKey: String!,
|
|
46
|
+
$serviceUuid: String!,
|
|
47
|
+
$sessionId: String!,
|
|
48
|
+
$timestampMs: String!,
|
|
49
|
+
$parentSpanId: String,
|
|
50
|
+
$library: String!,
|
|
51
|
+
$version: String!,
|
|
52
|
+
$spanId: String!,
|
|
53
|
+
$filePath: String!,
|
|
54
|
+
$lineNumber: Int!,
|
|
55
|
+
$columnNumber: Int!,
|
|
56
|
+
$functionName: String!,
|
|
57
|
+
$arguments: String!,
|
|
58
|
+
$returnValue: String,
|
|
59
|
+
$startTimeNs: String!,
|
|
60
|
+
$durationNs: String!
|
|
61
|
+
) {
|
|
62
|
+
${this.queryName}(
|
|
63
|
+
apiKey: $apiKey,
|
|
64
|
+
serviceUuid: $serviceUuid,
|
|
65
|
+
sessionId: $sessionId,
|
|
66
|
+
timestampMs: $timestampMs,
|
|
67
|
+
parentSpanId: $parentSpanId,
|
|
68
|
+
library: $library,
|
|
69
|
+
version: $version,
|
|
70
|
+
spanId: $spanId,
|
|
71
|
+
filePath: $filePath,
|
|
72
|
+
lineNumber: $lineNumber,
|
|
73
|
+
columnNumber: $columnNumber,
|
|
74
|
+
functionName: $functionName,
|
|
75
|
+
arguments: $arguments,
|
|
76
|
+
returnValue: $returnValue,
|
|
77
|
+
startTimeNs: $startTimeNs,
|
|
78
|
+
durationNs: $durationNs
|
|
79
|
+
)
|
|
80
|
+
}
|
|
81
|
+
`}}let w=null;function V(t){const e=T(),n=e?.sfDebug||!1;n&&console.log("[WorkerPool] Capturing span:",{operation:t.operationName,duration:`${t.duration}ms`,error:t.error,spanId:t.spanId,parentSpanId:t.parentSpanId}),process.env.SF_FUNCSPAN_CONSOLE_OUTPUT==="true"&&console.log(`
|
|
82
|
+
⚙️ Worker Pool Operation:`,{operation:t.operationName,duration:`${t.duration.toFixed(2)}ms`,arguments:t.args,result:t.error?`Error: ${t.error}`:t.result,spanId:t.spanId,parentSpanId:t.parentSpanId||"none"});const a=process.env.SF_FUNCSPAN_JSONL_FILE;if(a)try{const s=a==="true"||a==="1"?"funcspans.jsonl":a,i=Date.now(),r=process.hrtime.bigint(),o=BigInt(t.startTimeNs),u=Number(r-o)/1e6,m=new Date(i-u).toISOString(),p=JSON.stringify({timestamp:m,operationType:t.operationType,operationName:t.operationName,moduleName:t.moduleName,methodName:t.methodName,duration:t.duration,durationNs:t.durationNs,startTimeNs:t.startTimeNs,arguments:t.args,returnValue:t.error?{error:String(t.error)}:t.result,spanId:t.spanId,parentSpanId:t.parentSpanId,pid:t.pid,threadId:t.threadId})+`
|
|
83
|
+
`;se.appendFileSync(s,p,"utf-8")}catch(s){console.error("[WorkerPool] Error writing to JSONL file:",s)}if(n&&console.log("[WorkerPool] Sending span to transmitter"),process.env.SF_FUNCSPAN_SKIP_BACKEND!=="true")try{(w||(w=new te),w).send([t]),n&&console.log("[WorkerPool] Span sent successfully")}catch(s){n&&console.error("[WorkerPool] Error sending span:",s)}}exports.BaseTransmitter=re,exports.ContextManager=y,exports.DEFAULT_DOMAINS_TO_EXCLUDE=ee,exports.FunctionSpanTransmitter=te,exports.captureWorkerPoolOperation=function(t,e,n,a,s){const i=T(),r=i?.sfDebug||!1;r&&console.log(`[WorkerPool] Capturing ${t}.${e}`);const o=x(),u=y.getInstance().getCurrentFunctionSpanId(),m=v();r&&console.log(`[WorkerPool] Span ID: ${m}, Parent: ${u||"none"}`);const p=new P.AsyncResource("WorkerPoolOperation"),g=process.hrtime.bigint();let d=null;o.captureArguments&&(d=X(t,e,a,o.argLimitMb));const S=a.findIndex(b=>typeof b=="function");if(S===-1)return r&&console.log(`[WorkerPool] No callback found for ${t}.${e}`),n.apply(s,a);const N=a[S],$=[...a];return $[S]=function(b,...O){const U=process.hrtime.bigint()-g,W=Number(U)/1e6;N(b,...O),p.runInAsyncScope(()=>{r&&console.log(`[WorkerPool] ${t}.${e} completed in ${W.toFixed(3)}ms (${U}ns)`);let G=null,H=null;b?H=b?.message||String(b):o.captureReturnValue&&O.length>0&&(G=Y(t,e,O[0],o.returnLimitMb)),V({operationType:"worker_pool",operationName:`${t}.${e}`,moduleName:t,methodName:e,duration:W,durationNs:U.toString(),startTimeNs:g.toString(),args:d,result:G,error:H,spanId:m,parentSpanId:u,pid:process.pid,threadId:k.threadId})}),p.emitDestroy()},n.apply(s,$)},exports.captureWorkerPoolPromiseOperation=function(t,e,n,a,s){const i=T(),r=i?.sfDebug||!1;r&&console.log(`[WorkerPool] Capturing ${t}.${e} (Promise)`);const o=x(),u=y.getInstance().getCurrentFunctionSpanId(),m=v();r&&console.log(`[WorkerPool] Span ID: ${m}, Parent: ${u||"none"}`);const p=process.hrtime.bigint();let g=null;return o.captureArguments&&(g=X(t,e,a,o.argLimitMb)),n.apply(s,a).then(d=>{const S=process.hrtime.bigint()-p,N=Number(S)/1e6;r&&console.log(`[WorkerPool] ${t}.${e} completed in ${N.toFixed(3)}ms (${S}ns)`);let $=null;return o.captureReturnValue&&($=Y(t,e,d,o.returnLimitMb)),V({operationType:"worker_pool",operationName:`${t}.${e}`,moduleName:t,methodName:e,duration:N,durationNs:S.toString(),startTimeNs:p.toString(),args:g,result:$,error:null,spanId:m,parentSpanId:u,pid:process.pid,threadId:k.threadId}),d},d=>{const S=process.hrtime.bigint()-p,N=Number(S)/1e6;throw r&&console.log(`[WorkerPool] ${t}.${e} failed in ${N.toFixed(3)}ms: ${d?.message||d}`),V({operationType:"worker_pool",operationName:`${t}.${e}`,moduleName:t,methodName:e,duration:N,durationNs:S.toString(),startTimeNs:p.toString(),args:g,result:null,error:d?.message||String(d),spanId:m,parentSpanId:u,pid:process.pid,threadId:k.threadId}),d})},exports.clearFuncspanOverride=function(){M.enterWith(void 0)},exports.getConfig=f,exports.getCurrentFunctionSpanId=function(){return y.getInstance().getCurrentFunctionSpanId()},exports.getDefaultConfig=function(){return{capture_arguments:!1,capture_return_value:!1,arg_limit_mb:1,return_limit_mb:1,autocapture_all_child_functions:!1,sample_rate:0,enable_sampling:!1,capture_sf_veritas:!1,parse_json_strings:!1}},exports.getEnvConfig=function(){return{capture_arguments:C(process.env.SF_FUNCSPAN_CAPTURE_ARGUMENTS,!0),capture_return_value:C(process.env.SF_FUNCSPAN_CAPTURE_RETURN_VALUE,!0),arg_limit_mb:parseInt(process.env.SF_FUNCSPAN_ARG_LIMIT_MB||"1",10),return_limit_mb:parseInt(process.env.SF_FUNCSPAN_RETURN_LIMIT_MB||"1",10),autocapture_all_child_functions:C(process.env.SF_FUNCSPAN_AUTOCAPTURE_ALL_CHILD_FUNCTIONS,!1),sample_rate:parseFloat(process.env.SF_FUNCSPAN_SAMPLE_RATE||"1.0"),enable_sampling:C(process.env.SF_FUNCSPAN_ENABLE_SAMPLING,!1),capture_sf_veritas:C(process.env.SF_FUNCSPAN_CAPTURE_SF_VERITAS,!1),parse_json_strings:C(process.env.SF_FUNCSPAN_PARSE_JSON_STRINGS,!1)}},exports.getFuncspanOverride=function(){return M.getStore()},exports.getGlobalConfigUnsafe=T,exports.getOrCreateConfig=function(t){const e=T();if(e)return{config:e};const n=new ie(t);return(function(a){globalThis[Z]=a})(n),n.sfDebug&&console.log("[[getOrCreateConfig]] Created global config:",n),{config:n}},exports.isModuleTrackingEnabled=function(t){const e=x();if(!e.enabled)return!1;switch(t){case"fs":return e.trackFs;case"dns":return e.trackDns;case"crypto":return e.trackCrypto;case"zlib":return e.trackZlib;default:return!1}},exports.mergeConfigs=function(...t){const e={};for(const n of t)for(const a in n)n[a]!==void 0&&(e[a]=n[a]);return e},exports.nonBlockingPost=K,exports.parseHeaderOverride=function(t){try{const e=t.split("-");return e.length!==9?(console.error(`[FuncSpan] Invalid header format: expected 9 parts, got ${e.length}`),null):{capture_arguments:e[0]==="1",capture_return_value:e[1]==="1",arg_limit_mb:parseInt(e[2],10),return_limit_mb:parseInt(e[3],10),autocapture_all_child_functions:e[4]==="1",sample_rate:parseFloat(e[5]),enable_sampling:e[6]==="1",capture_sf_veritas:e[7]==="1",parse_json_strings:e[8]==="1"}}catch(e){return console.error(`[FuncSpan] Failed to parse header override "${t}":`,e),null}},exports.runWithContext=function(t){const e={...y.getInstance().getCurrentContext()};A.run(e,()=>{t()})},exports.setFuncspanOverride=function(t){M.enterWith(t)},exports.truncateToLimit=B,exports.v4=v;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sailfish-ai/sf-veritas",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.6",
|
|
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",
|
|
@@ -37,6 +37,22 @@
|
|
|
37
37
|
"import": "./dist/plugins/funcspanTscPlugin.mjs",
|
|
38
38
|
"require": "./dist/plugins/funcspanTscPlugin.cjs",
|
|
39
39
|
"types": "./dist/types/plugins/funcspanTscPlugin.d.ts"
|
|
40
|
+
},
|
|
41
|
+
"./runtime/esm-loader": {
|
|
42
|
+
"import": "./dist/runtime/funcspanEsmLoader.mjs"
|
|
43
|
+
},
|
|
44
|
+
"./runtime/commonjs-hook": {
|
|
45
|
+
"require": "./dist/runtime/funcspanRegister.cjs"
|
|
46
|
+
},
|
|
47
|
+
"./runtime/register": {
|
|
48
|
+
"import": "./dist/runtime/register.mjs",
|
|
49
|
+
"require": "./dist/runtime/register.cjs",
|
|
50
|
+
"types": "./dist/types/runtime/register.d.ts"
|
|
51
|
+
},
|
|
52
|
+
"./worker-pool-capture": {
|
|
53
|
+
"import": "./dist/worker-pool-capture.mjs",
|
|
54
|
+
"require": "./dist/worker-pool-capture.cjs",
|
|
55
|
+
"types": "./dist/types/worker-pool-capture.d.ts"
|
|
40
56
|
}
|
|
41
57
|
},
|
|
42
58
|
"scripts": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";const q=require("@babel/parser"),O=require("@babel/traverse"),W=require("@babel/generator"),M=require("@babel/types"),u=require("path"),C=require("fs"),D=require("./source-map-rHHEdpre.cjs");function w(l){const o=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(l){for(const s in l)if(s!=="default"){const E=Object.getOwnPropertyDescriptor(l,s);Object.defineProperty(o,s,E.get?E:{enumerable:!0,get:()=>l[s]})}}return o.default=l,Object.freeze(o)}const e=w(M),I=O.default||O,N=W.default||W;function v(l){const o=[];for(const s of l)e.isIdentifier(s)?o.push(s.name):e.isRestElement(s)&&e.isIdentifier(s.argument)?o.push(`...${s.argument.name}`):e.isAssignmentPattern(s)&&e.isIdentifier(s.left)?o.push(s.left.name):e.isObjectPattern(s)?o.push("{}"):e.isArrayPattern(s)?o.push("[]"):o.push("_");return o}exports.transformFunctionSpans=async function(l,o,s={}){const{projectRoot:E=process.cwd(),includeNodeModules:_=[],debug:g=!1}=s;if(o.includes("node_modules")&&!_.some(n=>o.includes(`node_modules/${n}`)))return{code:l,modified:!1,functionsWrapped:0};const F=u.relative(E,o).replace(/\\/g,"/");let x;g&&console.log(`[FuncSpan Transform] Processing: ${F}`);try{x=q.parse(l,{sourceType:"module",plugins:["typescript","jsx","decorators-legacy","classProperties","objectRestSpread","asyncGenerators","dynamicImport","optionalCatchBinding","optionalChaining","nullishCoalescingOperator"]})}catch(n){return g&&console.error(`[FuncSpan Transform] Parse error in ${F}:`,n),{code:l,modified:!1,functionsWrapped:0}}let k=null,T=null;try{const n=C.readFileSync(`${o}.map`,"utf-8");k=await new D.sourceMapExports.SourceMapConsumer(JSON.parse(n))}catch{}const P=(n,i)=>{if(k){const r=k.originalPositionFor({line:n,column:i});if(r.line!==null&&r.column!==null)return!T&&r.source&&(T=r.source),{line:r.line,column:r.column,source:r.source||void 0}}return{line:n,column:i}};let L=!1,h=0;const y=new Set;if(I(x,{FunctionDeclaration(n){const i=n.node.id?.name;if(!i)return;const r=`decl_${i}`;if(y.has(r))return;g&&console.log(`[FuncSpan Transform] Wrapping function declaration: ${i}`);const t=n.node.loc?.start.line??0,a=n.node.loc?.start.column??0,c=P(t,a),{line:d,column:p}=c;let m=F;if(c.source){const j=u.resolve(u.dirname(o),c.source);m=u.relative(E,j).replace(/\\/g,"/")}!g||d===t&&p===a||console.log(`[FuncSpan Transform] Mapped ${t}:${a} → ${d}:${p} in ${m}`);const S=v(n.node.params),b=e.callExpression(e.identifier("captureFunctionSpan"),[e.identifier(i),e.stringLiteral(i),e.stringLiteral(m),e.objectExpression([e.objectProperty(e.identifier("line"),e.numericLiteral(d)),e.objectProperty(e.identifier("column"),e.numericLiteral(p)),e.objectProperty(e.identifier("paramNames"),e.arrayExpression(S.map(j=>e.stringLiteral(j))))])]),$=e.expressionStatement(e.assignmentExpression("=",e.identifier(i),b));n.insertAfter($),L=!0,h++,y.add(r)},VariableDeclarator(n){const i=n.node.id,r=n.node.init;if(!e.isIdentifier(i)||!r||!e.isFunctionExpression(r)&&!e.isArrowFunctionExpression(r))return;const t=i.name,a=`var_${t}`;if(y.has(a))return;g&&console.log(`[FuncSpan Transform] Wrapping variable function: ${t}`);const c=r.loc?.start.line??0,d=r.loc?.start.column??0,p=P(c,d),{line:m,column:S}=p;let b=F;if(p.source){const f=u.resolve(u.dirname(o),p.source);b=u.relative(E,f).replace(/\\/g,"/")}!g||m===c&&S===d||console.log(`[FuncSpan Transform] Mapped ${c}:${d} → ${m}:${S} in ${b}`);const $=v(r.params),j=e.callExpression(e.identifier("captureFunctionSpan"),[r,e.stringLiteral(t),e.stringLiteral(b),e.objectExpression([e.objectProperty(e.identifier("line"),e.numericLiteral(m)),e.objectProperty(e.identifier("column"),e.numericLiteral(S)),e.objectProperty(e.identifier("paramNames"),e.arrayExpression($.map(f=>e.stringLiteral(f))))])]);n.node.init=j,L=!0,h++,y.add(a)},ClassMethod(n){if(n.node.kind==="constructor"||n.node.kind==="get"||n.node.kind==="set")return;const i=e.isIdentifier(n.node.key)?n.node.key.name:"anonymous",r=`method_${i}_${n.node.start}`;if(y.has(r))return;g&&console.log(`[FuncSpan Transform] Wrapping class method: ${i}`);const t=n.node.body,a=e.functionExpression(null,n.node.params,t,n.node.generator,n.node.async),c=e.callExpression(e.identifier("captureFunctionSpan"),[a,e.stringLiteral(i),e.stringLiteral(F)]),d=e.blockStatement([e.returnStatement(e.callExpression(e.memberExpression(c,e.identifier("call")),[e.thisExpression(),e.spreadElement(e.identifier("arguments"))]))]);n.node.body=d,L=!0,h++,y.add(r)},ObjectMethod(n){if(n.node.kind==="get"||n.node.kind==="set")return;const i=e.isIdentifier(n.node.key)?n.node.key.name:e.isStringLiteral(n.node.key)?n.node.key.value:"anonymous",r=`objmethod_${i}_${n.node.start}`;if(y.has(r))return;g&&console.log(`[FuncSpan Transform] Wrapping object method: ${i}`);const t=n.node.loc?.start.line??0,a=n.node.loc?.start.column??0,c=P(t,a),{line:d,column:p}=c;let m=F;if(c.source){const f=u.resolve(u.dirname(o),c.source);m=u.relative(E,f).replace(/\\/g,"/")}const S=v(n.node.params),b=e.functionExpression(e.identifier(i),n.node.params,n.node.body,n.node.generator,n.node.async),$=e.callExpression(e.identifier("captureFunctionSpan"),[b,e.stringLiteral(i),e.stringLiteral(m),e.objectExpression([e.objectProperty(e.identifier("line"),e.numericLiteral(d)),e.objectProperty(e.identifier("column"),e.numericLiteral(p)),e.objectProperty(e.identifier("paramNames"),e.arrayExpression(S.map(f=>e.stringLiteral(f))))])]),j=e.objectProperty(n.node.key,$,n.node.computed,!1);n.replaceWith(j),L=!0,h++,y.add(r)},ClassProperty(n){const i=n.node.key,r=n.node.value;if(!e.isIdentifier(i)||!r||!e.isFunctionExpression(r)&&!e.isArrowFunctionExpression(r))return;const t=i.name,a=`classprop_${t}_${n.node.start}`;if(y.has(a))return;g&&console.log(`[FuncSpan Transform] Wrapping class property function: ${t}`);const c=r.loc?.start.line??0,d=r.loc?.start.column??0,p=P(c,d),{line:m,column:S}=p;let b=F;if(p.source){const f=u.resolve(u.dirname(o),p.source);b=u.relative(E,f).replace(/\\/g,"/")}const $=v(r.params),j=e.callExpression(e.identifier("captureFunctionSpan"),[r,e.stringLiteral(t),e.stringLiteral(b),e.objectExpression([e.objectProperty(e.identifier("line"),e.numericLiteral(m)),e.objectProperty(e.identifier("column"),e.numericLiteral(S)),e.objectProperty(e.identifier("paramNames"),e.arrayExpression($.map(f=>e.stringLiteral(f))))])]);n.node.value=j,L=!0,h++,y.add(a)}}),L&&!(function(n){let i=!1;return I(n,{ImportDeclaration(r){e.isStringLiteral(r.node.source)&&r.node.source.value==="@sailfish-ai/sf-veritas"&&r.node.specifiers.some(t=>e.isImportSpecifier(t)&&e.isIdentifier(t.imported)&&t.imported.name==="captureFunctionSpan")&&(i=!0,r.stop())},VariableDeclarator(r){if(e.isObjectPattern(r.node.id)&&e.isCallExpression(r.node.init)&&e.isIdentifier(r.node.init.callee)&&r.node.init.callee.name==="require"){const t=r.node.init.arguments;t.length>0&&e.isStringLiteral(t[0])&&t[0].value==="@sailfish-ai/sf-veritas"&&r.node.id.properties.some(a=>e.isObjectProperty(a)&&e.isIdentifier(a.key)&&a.key.name==="captureFunctionSpan")&&(i=!0,r.stop())}}}),i})(x))if((function(n){let i=!1;return I(n,{CallExpression(r){e.isIdentifier(r.node.callee)&&r.node.callee.name==="require"&&(i=!0,r.stop())},MemberExpression(r){!e.isIdentifier(r.node.object)||r.node.object.name!=="module"&&r.node.object.name!=="exports"||(i=!0,r.stop())}}),i})(x)){const n=e.variableDeclaration("const",[e.variableDeclarator(e.objectPattern([e.objectProperty(e.identifier("captureFunctionSpan"),e.identifier("captureFunctionSpan"),!1,!0)]),e.callExpression(e.identifier("require"),[e.stringLiteral("@sailfish-ai/sf-veritas")]))]);x.program.body.unshift(n)}else{const n=e.importDeclaration([e.importSpecifier(e.identifier("captureFunctionSpan"),e.identifier("captureFunctionSpan"))],e.stringLiteral("@sailfish-ai/sf-veritas"));x.program.body.unshift(n)}if(h>0){const n=N(x,{retainLines:!0,compact:!1,sourceMaps:!0,sourceFileName:o},l);return g&&console.log(`[FuncSpan Transform] ✅ Wrapped ${h} functions in ${F}`),{code:n.code,map:n.map,modified:!0,functionsWrapped:h}}return{code:l,modified:!1,functionsWrapped:0}};
|
|
@@ -1,136 +0,0 @@
|
|
|
1
|
-
import { parse as N } from "@babel/parser";
|
|
2
|
-
import C from "@babel/traverse";
|
|
3
|
-
import M from "@babel/generator";
|
|
4
|
-
import * as e from "@babel/types";
|
|
5
|
-
import { relative as E, resolve as k, dirname as v } from "path";
|
|
6
|
-
import { readFileSync as w } from "fs";
|
|
7
|
-
import { s as O } from "./source-map-Cr6YkjTd.js";
|
|
8
|
-
const W = C.default || C, A = M.default || M;
|
|
9
|
-
async function z(F, t, p = {}) {
|
|
10
|
-
const { projectRoot: $ = process.cwd(), includeNodeModules: D = [], debug: m = !1 } = p;
|
|
11
|
-
if (t.includes("node_modules") && !D.some((n) => t.includes(`node_modules/${n}`))) return { code: F, modified: !1, functionsWrapped: 0 };
|
|
12
|
-
const S = E($, t).replace(/\\/g, "/");
|
|
13
|
-
let j;
|
|
14
|
-
m && console.log(`[FuncSpan Transform] Processing: ${S}`);
|
|
15
|
-
try {
|
|
16
|
-
j = N(F, { sourceType: "module", plugins: ["typescript", "jsx", "decorators-legacy", "classProperties", "objectRestSpread", "asyncGenerators", "dynamicImport", "optionalCatchBinding", "optionalChaining", "nullishCoalescingOperator"] });
|
|
17
|
-
} catch (n) {
|
|
18
|
-
return m && console.error(`[FuncSpan Transform] Parse error in ${S}:`, n), { code: F, modified: !1, functionsWrapped: 0 };
|
|
19
|
-
}
|
|
20
|
-
let T = null, _ = null;
|
|
21
|
-
try {
|
|
22
|
-
const n = w(`${t}.map`, "utf-8");
|
|
23
|
-
T = await new O.SourceMapConsumer(JSON.parse(n));
|
|
24
|
-
} catch {
|
|
25
|
-
}
|
|
26
|
-
const P = (n, i) => {
|
|
27
|
-
if (T) {
|
|
28
|
-
const r = T.originalPositionFor({ line: n, column: i });
|
|
29
|
-
if (r.line !== null && r.column !== null) return !_ && r.source && (_ = r.source), { line: r.line, column: r.column, source: r.source || void 0 };
|
|
30
|
-
}
|
|
31
|
-
return { line: n, column: i };
|
|
32
|
-
};
|
|
33
|
-
let L = !1, h = 0;
|
|
34
|
-
const f = /* @__PURE__ */ new Set();
|
|
35
|
-
if (W(j, { FunctionDeclaration(n) {
|
|
36
|
-
const i = n.node.id?.name;
|
|
37
|
-
if (!i) return;
|
|
38
|
-
const r = `decl_${i}`;
|
|
39
|
-
if (f.has(r)) return;
|
|
40
|
-
m && console.log(`[FuncSpan Transform] Wrapping function declaration: ${i}`);
|
|
41
|
-
const o = n.node.loc?.start.line ?? 0, s = n.node.loc?.start.column ?? 0, a = P(o, s), { line: c, column: l } = a;
|
|
42
|
-
let d = S;
|
|
43
|
-
if (a.source) {
|
|
44
|
-
const b = k(v(t), a.source);
|
|
45
|
-
d = E($, b).replace(/\\/g, "/");
|
|
46
|
-
}
|
|
47
|
-
!m || c === o && l === s || console.log(`[FuncSpan Transform] Mapped ${o}:${s} → ${c}:${l} in ${d}`);
|
|
48
|
-
const y = I(n.node.params), g = e.callExpression(e.identifier("captureFunctionSpan"), [e.identifier(i), e.stringLiteral(i), e.stringLiteral(d), e.objectExpression([e.objectProperty(e.identifier("line"), e.numericLiteral(c)), e.objectProperty(e.identifier("column"), e.numericLiteral(l)), e.objectProperty(e.identifier("paramNames"), e.arrayExpression(y.map((b) => e.stringLiteral(b))))])]), x = e.expressionStatement(e.assignmentExpression("=", e.identifier(i), g));
|
|
49
|
-
n.insertAfter(x), L = !0, h++, f.add(r);
|
|
50
|
-
}, VariableDeclarator(n) {
|
|
51
|
-
const i = n.node.id, r = n.node.init;
|
|
52
|
-
if (!e.isIdentifier(i) || !r || !e.isFunctionExpression(r) && !e.isArrowFunctionExpression(r)) return;
|
|
53
|
-
const o = i.name, s = `var_${o}`;
|
|
54
|
-
if (f.has(s)) return;
|
|
55
|
-
m && console.log(`[FuncSpan Transform] Wrapping variable function: ${o}`);
|
|
56
|
-
const a = r.loc?.start.line ?? 0, c = r.loc?.start.column ?? 0, l = P(a, c), { line: d, column: y } = l;
|
|
57
|
-
let g = S;
|
|
58
|
-
if (l.source) {
|
|
59
|
-
const u = k(v(t), l.source);
|
|
60
|
-
g = E($, u).replace(/\\/g, "/");
|
|
61
|
-
}
|
|
62
|
-
!m || d === a && y === c || console.log(`[FuncSpan Transform] Mapped ${a}:${c} → ${d}:${y} in ${g}`);
|
|
63
|
-
const x = I(r.params), b = e.callExpression(e.identifier("captureFunctionSpan"), [r, e.stringLiteral(o), e.stringLiteral(g), e.objectExpression([e.objectProperty(e.identifier("line"), e.numericLiteral(d)), e.objectProperty(e.identifier("column"), e.numericLiteral(y)), e.objectProperty(e.identifier("paramNames"), e.arrayExpression(x.map((u) => e.stringLiteral(u))))])]);
|
|
64
|
-
n.node.init = b, L = !0, h++, f.add(s);
|
|
65
|
-
}, ClassMethod(n) {
|
|
66
|
-
if (n.node.kind === "constructor" || n.node.kind === "get" || n.node.kind === "set") return;
|
|
67
|
-
const i = e.isIdentifier(n.node.key) ? n.node.key.name : "anonymous", r = `method_${i}_${n.node.start}`;
|
|
68
|
-
if (f.has(r)) return;
|
|
69
|
-
m && console.log(`[FuncSpan Transform] Wrapping class method: ${i}`);
|
|
70
|
-
const o = n.node.body, s = e.functionExpression(null, n.node.params, o, n.node.generator, n.node.async), a = e.callExpression(e.identifier("captureFunctionSpan"), [s, e.stringLiteral(i), e.stringLiteral(S)]), c = e.blockStatement([e.returnStatement(e.callExpression(e.memberExpression(a, e.identifier("call")), [e.thisExpression(), e.spreadElement(e.identifier("arguments"))]))]);
|
|
71
|
-
n.node.body = c, L = !0, h++, f.add(r);
|
|
72
|
-
}, ObjectMethod(n) {
|
|
73
|
-
if (n.node.kind === "get" || n.node.kind === "set") return;
|
|
74
|
-
const i = e.isIdentifier(n.node.key) ? n.node.key.name : e.isStringLiteral(n.node.key) ? n.node.key.value : "anonymous", r = `objmethod_${i}_${n.node.start}`;
|
|
75
|
-
if (f.has(r)) return;
|
|
76
|
-
m && console.log(`[FuncSpan Transform] Wrapping object method: ${i}`);
|
|
77
|
-
const o = n.node.loc?.start.line ?? 0, s = n.node.loc?.start.column ?? 0, a = P(o, s), { line: c, column: l } = a;
|
|
78
|
-
let d = S;
|
|
79
|
-
if (a.source) {
|
|
80
|
-
const u = k(v(t), a.source);
|
|
81
|
-
d = E($, u).replace(/\\/g, "/");
|
|
82
|
-
}
|
|
83
|
-
const y = I(n.node.params), g = e.functionExpression(e.identifier(i), n.node.params, n.node.body, n.node.generator, n.node.async), x = e.callExpression(e.identifier("captureFunctionSpan"), [g, e.stringLiteral(i), e.stringLiteral(d), e.objectExpression([e.objectProperty(e.identifier("line"), e.numericLiteral(c)), e.objectProperty(e.identifier("column"), e.numericLiteral(l)), e.objectProperty(e.identifier("paramNames"), e.arrayExpression(y.map((u) => e.stringLiteral(u))))])]), b = e.objectProperty(n.node.key, x, n.node.computed, !1);
|
|
84
|
-
n.replaceWith(b), L = !0, h++, f.add(r);
|
|
85
|
-
}, ClassProperty(n) {
|
|
86
|
-
const i = n.node.key, r = n.node.value;
|
|
87
|
-
if (!e.isIdentifier(i) || !r || !e.isFunctionExpression(r) && !e.isArrowFunctionExpression(r)) return;
|
|
88
|
-
const o = i.name, s = `classprop_${o}_${n.node.start}`;
|
|
89
|
-
if (f.has(s)) return;
|
|
90
|
-
m && console.log(`[FuncSpan Transform] Wrapping class property function: ${o}`);
|
|
91
|
-
const a = r.loc?.start.line ?? 0, c = r.loc?.start.column ?? 0, l = P(a, c), { line: d, column: y } = l;
|
|
92
|
-
let g = S;
|
|
93
|
-
if (l.source) {
|
|
94
|
-
const u = k(v(t), l.source);
|
|
95
|
-
g = E($, u).replace(/\\/g, "/");
|
|
96
|
-
}
|
|
97
|
-
const x = I(r.params), b = e.callExpression(e.identifier("captureFunctionSpan"), [r, e.stringLiteral(o), e.stringLiteral(g), e.objectExpression([e.objectProperty(e.identifier("line"), e.numericLiteral(d)), e.objectProperty(e.identifier("column"), e.numericLiteral(y)), e.objectProperty(e.identifier("paramNames"), e.arrayExpression(x.map((u) => e.stringLiteral(u))))])]);
|
|
98
|
-
n.node.value = b, L = !0, h++, f.add(s);
|
|
99
|
-
} }), L && !(function(n) {
|
|
100
|
-
let i = !1;
|
|
101
|
-
return W(n, { ImportDeclaration(r) {
|
|
102
|
-
e.isStringLiteral(r.node.source) && r.node.source.value === "@sailfish-ai/sf-veritas" && r.node.specifiers.some((o) => e.isImportSpecifier(o) && e.isIdentifier(o.imported) && o.imported.name === "captureFunctionSpan") && (i = !0, r.stop());
|
|
103
|
-
}, VariableDeclarator(r) {
|
|
104
|
-
if (e.isObjectPattern(r.node.id) && e.isCallExpression(r.node.init) && e.isIdentifier(r.node.init.callee) && r.node.init.callee.name === "require") {
|
|
105
|
-
const o = r.node.init.arguments;
|
|
106
|
-
o.length > 0 && e.isStringLiteral(o[0]) && o[0].value === "@sailfish-ai/sf-veritas" && r.node.id.properties.some((s) => e.isObjectProperty(s) && e.isIdentifier(s.key) && s.key.name === "captureFunctionSpan") && (i = !0, r.stop());
|
|
107
|
-
}
|
|
108
|
-
} }), i;
|
|
109
|
-
})(j)) if ((function(n) {
|
|
110
|
-
let i = !1;
|
|
111
|
-
return W(n, { CallExpression(r) {
|
|
112
|
-
e.isIdentifier(r.node.callee) && r.node.callee.name === "require" && (i = !0, r.stop());
|
|
113
|
-
}, MemberExpression(r) {
|
|
114
|
-
!e.isIdentifier(r.node.object) || r.node.object.name !== "module" && r.node.object.name !== "exports" || (i = !0, r.stop());
|
|
115
|
-
} }), i;
|
|
116
|
-
})(j)) {
|
|
117
|
-
const n = e.variableDeclaration("const", [e.variableDeclarator(e.objectPattern([e.objectProperty(e.identifier("captureFunctionSpan"), e.identifier("captureFunctionSpan"), !1, !0)]), e.callExpression(e.identifier("require"), [e.stringLiteral("@sailfish-ai/sf-veritas")]))]);
|
|
118
|
-
j.program.body.unshift(n);
|
|
119
|
-
} else {
|
|
120
|
-
const n = e.importDeclaration([e.importSpecifier(e.identifier("captureFunctionSpan"), e.identifier("captureFunctionSpan"))], e.stringLiteral("@sailfish-ai/sf-veritas"));
|
|
121
|
-
j.program.body.unshift(n);
|
|
122
|
-
}
|
|
123
|
-
if (h > 0) {
|
|
124
|
-
const n = A(j, { retainLines: !0, compact: !1, sourceMaps: !0, sourceFileName: t }, F);
|
|
125
|
-
return m && console.log(`[FuncSpan Transform] ✅ Wrapped ${h} functions in ${S}`), { code: n.code, map: n.map, modified: !0, functionsWrapped: h };
|
|
126
|
-
}
|
|
127
|
-
return { code: F, modified: !1, functionsWrapped: 0 };
|
|
128
|
-
}
|
|
129
|
-
function I(F) {
|
|
130
|
-
const t = [];
|
|
131
|
-
for (const p of F) e.isIdentifier(p) ? t.push(p.name) : e.isRestElement(p) && e.isIdentifier(p.argument) ? t.push(`...${p.argument.name}`) : e.isAssignmentPattern(p) && e.isIdentifier(p.left) ? t.push(p.left.name) : e.isObjectPattern(p) ? t.push("{}") : e.isArrayPattern(p) ? t.push("[]") : t.push("_");
|
|
132
|
-
return t;
|
|
133
|
-
}
|
|
134
|
-
export {
|
|
135
|
-
z as t
|
|
136
|
-
};
|