@sailfish-ai/sf-veritas 0.2.4 → 0.2.5

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.
Files changed (35) hide show
  1. package/README.md +120 -0
  2. package/dist/funcSpanTransformer-TjdooSrw.cjs +1 -0
  3. package/dist/funcSpanTransformer-sqmZLAcs.js +750 -0
  4. package/dist/plugins/funcspanEsbuildPlugin.cjs +1 -1
  5. package/dist/plugins/funcspanEsbuildPlugin.mjs +1 -1
  6. package/dist/plugins/funcspanRollupPlugin.cjs +1 -1
  7. package/dist/plugins/funcspanRollupPlugin.mjs +1 -1
  8. package/dist/plugins/funcspanTscPlugin.cjs +1 -1
  9. package/dist/plugins/funcspanTscPlugin.mjs +1 -1
  10. package/dist/plugins/funcspanVitePlugin.cjs +1 -1
  11. package/dist/plugins/funcspanVitePlugin.mjs +1 -1
  12. package/dist/plugins/funcspanWebpackLoader.cjs +1 -1
  13. package/dist/plugins/funcspanWebpackLoader.mjs +1 -1
  14. package/dist/runtime/register.cjs +1 -0
  15. package/dist/runtime/register.mjs +27 -0
  16. package/dist/sf-veritas.cjs +61 -15
  17. package/dist/sf-veritas.mjs +1065 -628
  18. package/dist/types/functionSpanTransmitter.d.ts +15 -1
  19. package/dist/types/index.d.ts +2 -0
  20. package/dist/types/patches/workerPool/argumentCapture.d.ts +47 -0
  21. package/dist/types/patches/workerPool/index.d.ts +19 -0
  22. package/dist/types/patches/workerPool/patchCrypto.d.ts +9 -0
  23. package/dist/types/patches/workerPool/patchDns.d.ts +10 -0
  24. package/dist/types/patches/workerPool/patchFs.d.ts +9 -0
  25. package/dist/types/patches/workerPool/patchZlib.d.ts +9 -0
  26. package/dist/types/patches/workerPool/workerPoolTypes.d.ts +70 -0
  27. package/dist/types/requestUtils.d.ts +1 -0
  28. package/dist/types/runtime/register.d.ts +56 -0
  29. package/dist/types/workerPoolConfig.d.ts +22 -0
  30. package/dist/types/workerPoolSpanCapture.d.ts +36 -0
  31. package/package.json +12 -1
  32. package/dist/funcSpanTransformer-CTddGtUV.cjs +0 -1
  33. package/dist/funcSpanTransformer-coYDqcrs.js +0 -136
  34. package/dist/source-map-Cr6YkjTd.js +0 -631
  35. package/dist/source-map-rHHEdpre.cjs +0 -1
@@ -1,4 +1,9 @@
1
1
  import { BaseTransmitter } from "./baseTransmitter";
2
+ import type { WorkerPoolSpanData } from "./patches/workerPool/workerPoolTypes";
3
+ /**
4
+ * Union type for all span types
5
+ */
6
+ export type SpanData = FunctionSpanData | WorkerPoolSpanData;
2
7
  /**
3
8
  * FunctionSpanTransmitter - Transmits function span data to the backend
4
9
  */
@@ -9,7 +14,15 @@ export declare class FunctionSpanTransmitter extends BaseTransmitter {
9
14
  * Sends each span individually as the backend expects single spans, not arrays
10
15
  * This is TRULY non-blocking - fire and forget
11
16
  */
12
- send(functionSpans: FunctionSpanData[]): void;
17
+ send(functionSpans: SpanData[]): void;
18
+ /**
19
+ * Send worker pool span to backend using dedicated collectWorkerPoolSpans mutation
20
+ */
21
+ private sendWorkerPoolSpan;
22
+ /**
23
+ * GraphQL mutation query for collecting worker pool spans
24
+ */
25
+ private getWorkerPoolQuery;
13
26
  /**
14
27
  * GraphQL mutation query for collecting function spans
15
28
  */
@@ -27,6 +40,7 @@ export interface FunctionSpanData {
27
40
  result: any;
28
41
  error: string | null;
29
42
  duration: number;
43
+ durationNs: number;
30
44
  async: boolean;
31
45
  spanId: string;
32
46
  parentSpanId: string | null;
@@ -3,3 +3,5 @@ export { addOrUpdateMetadata, identify, setupInterceptors } from "./unifiedInter
3
3
  export { captureFunctionSpan, type FunctionSpanMetadata } from "./funcSpanCapture";
4
4
  export { type FuncspanConfig, type FuncspanHeaderOverride, setFuncspanOverride, getFuncspanOverride, clearFuncspanOverride, parseHeaderOverride, getEnvConfig, getDefaultConfig, } from "./funcSpanConfig";
5
5
  export { initializeConfigLoader, getGlobalConfig, isConfigLoaderInitialized, } from "./funcSpanConfigLoader";
6
+ export { transformFunctionSpans, type TransformOptions, type TransformResult } from "./plugins/funcSpanTransformer";
7
+ export { initializeWorkerPoolPatching, isInitialized as isWorkerPoolInitialized } from "./patches/workerPool/index";
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Argument Capture and Sanitization
3
+ *
4
+ * Module-specific logic for capturing and sanitizing arguments and results
5
+ * from worker pool operations. Ensures sensitive data is not captured.
6
+ */
7
+ import type { FsMethod, DnsMethod, CryptoMethod, ZlibMethod } from "./workerPoolTypes";
8
+ /**
9
+ * Capture and sanitize fs module arguments
10
+ */
11
+ export declare function captureFsArgs(methodName: FsMethod, args: any[]): Record<string, any>;
12
+ /**
13
+ * Capture and sanitize fs module results
14
+ */
15
+ export declare function captureFsResult(methodName: FsMethod, result: any): any;
16
+ /**
17
+ * Capture and sanitize dns module arguments
18
+ */
19
+ export declare function captureDnsArgs(methodName: DnsMethod, args: any[]): Record<string, any>;
20
+ /**
21
+ * Capture and sanitize dns module results
22
+ */
23
+ export declare function captureDnsResult(methodName: DnsMethod, result: any): any;
24
+ /**
25
+ * Capture and sanitize crypto module arguments
26
+ */
27
+ export declare function captureCryptoArgs(methodName: CryptoMethod, args: any[]): Record<string, any>;
28
+ /**
29
+ * Capture and sanitize crypto module results
30
+ */
31
+ export declare function captureCryptoResult(methodName: CryptoMethod, result: any): any;
32
+ /**
33
+ * Capture and sanitize zlib module arguments
34
+ */
35
+ export declare function captureZlibArgs(methodName: ZlibMethod, args: any[]): Record<string, any>;
36
+ /**
37
+ * Capture and sanitize zlib module results
38
+ */
39
+ export declare function captureZlibResult(methodName: ZlibMethod, result: any): any;
40
+ /**
41
+ * Main argument capture function that delegates to module-specific handlers
42
+ */
43
+ export declare function captureArguments(moduleName: string, methodName: string, args: any[], limitMb: number): Record<string, any> | null;
44
+ /**
45
+ * Main result capture function that delegates to module-specific handlers
46
+ */
47
+ export declare function captureResult(moduleName: string, methodName: string, result: any, limitMb: number): any;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Worker Pool Patching Initialization
3
+ *
4
+ * Central initialization point for all worker pool module patches.
5
+ */
6
+ /**
7
+ * Initialize worker pool patching based on configuration.
8
+ * This should be called early in the application lifecycle,
9
+ * before any user code requires these modules.
10
+ */
11
+ export declare function initializeWorkerPoolPatching(): void;
12
+ /**
13
+ * Check if worker pool patching has been initialized
14
+ */
15
+ export declare function isInitialized(): boolean;
16
+ export { patchFsModule } from "./patchFs";
17
+ export { patchDnsModule } from "./patchDns";
18
+ export { patchCryptoModule } from "./patchCrypto";
19
+ export { patchZlibModule } from "./patchZlib";
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Crypto Module Patching
3
+ *
4
+ * Patches the Node.js 'crypto' module to capture worker pool operations.
5
+ */
6
+ /**
7
+ * Patch the crypto module to capture worker pool operations
8
+ */
9
+ export declare function patchCryptoModule(): void;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * DNS Module Patching
3
+ *
4
+ * Patches the Node.js 'dns' module to capture worker pool operations.
5
+ * Handles both callback-style and Promise-based DNS APIs.
6
+ */
7
+ /**
8
+ * Patch the dns module to capture worker pool operations
9
+ */
10
+ export declare function patchDnsModule(): void;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * File System Module Patching
3
+ *
4
+ * Patches the Node.js 'fs' module to capture worker pool operations.
5
+ */
6
+ /**
7
+ * Patch the fs module to capture worker pool operations
8
+ */
9
+ export declare function patchFsModule(): void;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Zlib Module Patching
3
+ *
4
+ * Patches the Node.js 'zlib' module to capture worker pool operations.
5
+ */
6
+ /**
7
+ * Patch the zlib module to capture worker pool operations
8
+ */
9
+ export declare function patchZlibModule(): void;
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Worker Pool Span Types
3
+ *
4
+ * Type definitions for tracking Node.js libuv worker pool operations
5
+ * (file system, DNS, crypto, compression)
6
+ */
7
+ /**
8
+ * Metadata about a worker pool operation
9
+ */
10
+ export interface WorkerPoolSpanMetadata {
11
+ moduleName: string;
12
+ methodName: string;
13
+ operationName: string;
14
+ }
15
+ /**
16
+ * Complete data captured for a worker pool operation
17
+ */
18
+ export interface WorkerPoolSpanData {
19
+ operationType: 'worker_pool';
20
+ operationName: string;
21
+ moduleName: string;
22
+ methodName: string;
23
+ duration: number;
24
+ durationNs: string;
25
+ startTimeNs: string;
26
+ args: Record<string, any> | null;
27
+ result: any;
28
+ error: string | null;
29
+ spanId: string;
30
+ parentSpanId: string | null;
31
+ pid: number;
32
+ threadId: number;
33
+ }
34
+ /**
35
+ * Internal span data structure used during capture
36
+ */
37
+ export interface WorkerPoolSpan {
38
+ metadata: WorkerPoolSpanMetadata;
39
+ args: Record<string, any> | null;
40
+ result: any;
41
+ error: string | null;
42
+ duration: number;
43
+ spanId: string;
44
+ parentSpanId: string | null;
45
+ }
46
+ /**
47
+ * Configuration for worker pool tracking
48
+ */
49
+ export interface WorkerPoolConfig {
50
+ enabled: boolean;
51
+ trackFs: boolean;
52
+ trackDns: boolean;
53
+ trackCrypto: boolean;
54
+ trackZlib: boolean;
55
+ captureArguments: boolean;
56
+ captureReturnValue: boolean;
57
+ argLimitMb: number;
58
+ returnLimitMb: number;
59
+ }
60
+ /**
61
+ * Module-specific method lists
62
+ */
63
+ export declare const FS_METHODS: readonly ["readFile", "writeFile", "appendFile", "readdir", "stat", "lstat", "fstat", "access", "open", "close", "read", "write", "chmod", "mkdir", "rmdir", "unlink", "rename"];
64
+ export declare const DNS_METHODS: readonly ["lookup", "resolve", "resolve4", "resolve6", "resolveAny", "resolveMx", "resolveNs", "resolveTxt", "reverse"];
65
+ export declare const CRYPTO_METHODS: readonly ["pbkdf2", "randomBytes", "scrypt", "generateKeyPair"];
66
+ export declare const ZLIB_METHODS: readonly ["gzip", "gunzip", "deflate", "inflate", "deflateRaw", "inflateRaw", "brotliCompress", "brotliDecompress"];
67
+ export type FsMethod = typeof FS_METHODS[number];
68
+ export type DnsMethod = typeof DNS_METHODS[number];
69
+ export type CryptoMethod = typeof CRYPTO_METHODS[number];
70
+ export type ZlibMethod = typeof ZLIB_METHODS[number];
@@ -1,3 +1,4 @@
1
+ export declare function isSendingInternalTelemetry(): boolean;
1
2
  /**
2
3
  * Sends a non-blocking POST request to a GraphQL endpoint.
3
4
  * The request is sent asynchronously, and any response errors or issues are logged.
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Programmatic Runtime Hook Registration
3
+ *
4
+ * Provides a TypeScript-friendly API for enabling function span runtime hooks
5
+ * from within your application code.
6
+ *
7
+ * Usage:
8
+ * import { registerFuncspanRuntime } from '@sailfish-ai/sf-veritas/runtime/register';
9
+ *
10
+ * registerFuncspanRuntime({ debug: true, sampleRate: 1.0 });
11
+ *
12
+ * Note: This must be called before importing any modules you want to instrument.
13
+ */
14
+ export interface RuntimeHookOptions {
15
+ /**
16
+ * Enable debug logging
17
+ * @default false
18
+ */
19
+ debug?: boolean;
20
+ /**
21
+ * List of node_modules packages to instrument (e.g., ['express', 'axios'])
22
+ * @default []
23
+ */
24
+ includeNodeModules?: string[];
25
+ /**
26
+ * Override sample rate (0.0 to 1.0)
27
+ * @default undefined (uses .sailfish config or env vars)
28
+ */
29
+ sampleRate?: number;
30
+ /**
31
+ * Project root directory for resolving relative paths
32
+ * @default process.cwd()
33
+ */
34
+ projectRoot?: string;
35
+ }
36
+ /**
37
+ * Register runtime hooks programmatically
38
+ *
39
+ * This function enables function span collection by hooking into the module system.
40
+ * It must be called before importing any modules you want to instrument.
41
+ *
42
+ * @param options Configuration options
43
+ * @returns Cleanup function to unregister hooks (if supported)
44
+ */
45
+ export declare function registerFuncspanRuntime(options?: RuntimeHookOptions): () => void;
46
+ /**
47
+ * Check if runtime hooks are currently registered
48
+ *
49
+ * Note: This only checks for CommonJS hooks. ESM hooks registered via --import
50
+ * cannot be detected programmatically.
51
+ */
52
+ export declare function isRuntimeRegistered(): boolean;
53
+ /**
54
+ * Get current runtime hook configuration from environment
55
+ */
56
+ export declare function getRuntimeConfig(): RuntimeHookOptions;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Worker Pool Configuration
3
+ *
4
+ * Configuration system for controlling worker pool operation tracking.
5
+ * Supports environment variables for runtime configuration.
6
+ */
7
+ import type { WorkerPoolConfig } from "./patches/workerPool/workerPoolTypes";
8
+ /**
9
+ * Get worker pool configuration from environment variables
10
+ *
11
+ * By default, only DNS tracking is enabled to reduce noise.
12
+ * Enable other modules (fs, crypto, zlib) via environment variables if needed.
13
+ */
14
+ export declare function getWorkerPoolConfig(): WorkerPoolConfig;
15
+ /**
16
+ * Check if worker pool tracking is enabled for a specific module
17
+ */
18
+ export declare function isModuleTrackingEnabled(moduleName: string): boolean;
19
+ /**
20
+ * Check if worker pool tracking is enabled at all
21
+ */
22
+ export declare function isWorkerPoolTrackingEnabled(): boolean;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Worker Pool Span Capture
3
+ *
4
+ * Core logic for capturing libuv worker pool operations (fs, dns, crypto, zlib).
5
+ * Uses AsyncResource to preserve AsyncLocalStorage context across callback boundaries.
6
+ */
7
+ import type { WorkerPoolSpanData } from "./patches/workerPool/workerPoolTypes";
8
+ /**
9
+ * Captures a worker pool operation by wrapping the original function
10
+ * and its callback to track execution details.
11
+ *
12
+ * @param moduleName - The module name (fs, dns, crypto, zlib)
13
+ * @param methodName - The method name (readFile, lookup, etc.)
14
+ * @param originalFn - The original function to wrap
15
+ * @param args - The arguments passed to the function
16
+ * @param thisContext - The 'this' context to preserve
17
+ * @returns The result of calling the original function
18
+ */
19
+ export declare function captureWorkerPoolOperation(moduleName: string, methodName: string, originalFn: Function, args: any[], thisContext: any): any;
20
+ /**
21
+ * Captures a Promise-based worker pool operation by wrapping the promise
22
+ * to track execution details.
23
+ *
24
+ * @param moduleName - The module name (fs, dns, crypto, zlib)
25
+ * @param methodName - The method name (readFile, lookup, etc.)
26
+ * @param originalFn - The original function to wrap
27
+ * @param args - The arguments passed to the function
28
+ * @param thisContext - The 'this' context to preserve
29
+ * @returns A promise that wraps the original function's promise
30
+ */
31
+ export declare function captureWorkerPoolPromiseOperation(moduleName: string, methodName: string, originalFn: Function, args: any[], thisContext: any): Promise<any>;
32
+ /**
33
+ * Internal function to capture and send worker pool span data
34
+ * Also exported for use by patchDns.ts for Promise-based operations
35
+ */
36
+ export declare function sendWorkerPoolSpanData(span: WorkerPoolSpanData): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sailfish-ai/sf-veritas",
3
- "version": "0.2.4",
3
+ "version": "0.2.5",
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,17 @@
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"
40
51
  }
41
52
  },
42
53
  "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
- };