tjs-lang 0.2.8 → 0.3.0
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/demo/docs.json +20 -14
- package/demo/src/examples.ts +23 -83
- package/demo/src/playground-shared.ts +666 -0
- package/demo/src/tjs-playground.ts +52 -528
- package/demo/src/ts-examples.ts +5 -4
- package/demo/src/ts-playground.ts +50 -414
- package/dist/index.js +58 -23
- package/dist/index.js.map +9 -9
- package/dist/src/lang/types.d.ts +1 -1
- package/dist/src/types/Type.d.ts +3 -1
- package/dist/tjs-full.js +58 -23
- package/dist/tjs-full.js.map +9 -9
- package/dist/tjs-transpiler.js +55 -20
- package/dist/tjs-transpiler.js.map +7 -7
- package/dist/tjs-vm.js +14 -14
- package/dist/tjs-vm.js.map +5 -5
- package/docs/index.js +740 -1010
- package/docs/index.js.map +9 -8
- package/editors/codemirror/ajs-language.ts +27 -1
- package/editors/codemirror/autocomplete.test.ts +3 -3
- package/package.json +1 -1
- package/src/lang/codegen.test.ts +11 -11
- package/src/lang/emitters/from-ts.ts +1 -1
- package/src/lang/emitters/js.ts +74 -0
- package/src/lang/inference.ts +40 -8
- package/src/lang/lang.test.ts +154 -16
- package/src/lang/runtime.ts +7 -0
- package/src/lang/types.ts +2 -0
- package/src/lang/typescript-syntax.test.ts +6 -4
- package/src/types/Type.test.ts +64 -0
- package/src/types/Type.ts +22 -1
- package/src/use-cases/transpiler-integration.test.ts +10 -10
- package/src/vm/atoms/batteries.ts +2 -0
package/dist/tjs-full.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
var F7=Object.defineProperty;var w7=(Z,$)=>()=>($||Z(($={exports:{}}).exports,$),$.exports);var P7=(Z,$)=>{for(var X in $)F7(Z,X,{get:$[X],enumerable:!0,configurable:!0,set:(K)=>$[X]=()=>K})};var C7=(Z,$)=>()=>(Z&&($=Z(Z=0)),$);var r0=((Z)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(Z,{get:($,X)=>(typeof require<"u"?require:$)[X]}):Z)(function(Z){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+Z+'" is not supported')});var J6=w7((n$,KZ)=>{KZ.exports={name:"tjs-lang",version:"0.
|
|
1
|
+
var F7=Object.defineProperty;var w7=(Z,$)=>()=>($||Z(($={exports:{}}).exports,$),$.exports);var P7=(Z,$)=>{for(var X in $)F7(Z,X,{get:$[X],enumerable:!0,configurable:!0,set:(K)=>$[X]=()=>K})};var C7=(Z,$)=>()=>(Z&&($=Z(Z=0)),$);var r0=((Z)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(Z,{get:($,X)=>(typeof require<"u"?require:$)[X]}):Z)(function(Z){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+Z+'" is not supported')});var J6=w7((n$,KZ)=>{KZ.exports={name:"tjs-lang",version:"0.3.0",description:"Type-safe JavaScript dialect with runtime validation, sandboxed VM execution, and AI agent orchestration. Transpiles TypeScript to validated JS with fuel-metered execution for untrusted code.",keywords:["typescript","transpiler","runtime-validation","type-safety","sandbox","virtual-machine","wasm-alternative","ai-agents","llm","orchestration","security","fuel-metering","capability-based","json-ast","untrusted-code"],license:"Apache-2.0",main:"./dist/index.js",exports:{".":{bun:"./src/index.ts",default:"./dist/index.js"},"./eval":{bun:"./src/lang/eval.ts",default:"./dist/lang/eval.js"},"./lang":{bun:"./src/lang/index.ts",default:"./dist/lang/index.js"},"./lang/eval":{bun:"./src/lang/eval.ts",default:"./dist/lang/eval.js"},"./lang/from-ts":{bun:"./src/lang/emitters/from-ts.ts",default:"./dist/lang/emitters/from-ts.js"},"./src":"./src/index.ts","./editors/monaco":"./editors/monaco/ajs-monarch.js","./editors/codemirror":"./editors/codemirror/ajs-language.js","./editors/ace":"./editors/ace/ajs-mode.js"},bin:{tjs:"./src/cli/tjs.ts",tjsx:"./src/cli/tjsx.ts","tjs-playground":"./src/cli/playground.ts","create-tjs-app":"./src/cli/create-app.ts","ajs-install-vscode":"./bin/install-vscode.sh","ajs-install-cursor":"./bin/install-cursor.sh"},type:"module",files:["dist","src","docs","editors","bin","demo","tjs-lang.svg","CONTEXT.md"],sideEffects:!1,repository:{type:"git",url:"https://github.com/tonioloewald/tjs-lang.git"},devDependencies:{"@codemirror/lang-javascript":"^6.2.4","@codemirror/state":"^6.5.3","@codemirror/view":"^6.39.9","@happy-dom/global-registrator":"^20.1.0","@types/bun":"latest","@types/jsdom":"^21.1.7","@typescript-eslint/eslint-plugin":"^5.62.0","@typescript-eslint/parser":"^5.62.0","acorn-walk":"^8.3.4",chokidar:"^4.0.3",codemirror:"^6.0.2",eslint:"^8.57.1","firebase-admin":"^13.6.0","firebase-functions":"^7.0.5",marked:"^9.1.6",prettier:"^2.8.8",tosijs:"^1.2.0","tosijs-ui":"^1.2.0",typescript:"^5.6.2",valibot:"^0.36.0",vitest:"^2.0.5"},scripts:{format:"bun eslint src --fix && bun prettier --write .",lint:"eslint src","build:grammars":"bun editors/build-grammars.ts","test:fast":"SKIP_LLM_TESTS=1 SKIP_BENCHMARKS=1 bun test","test:llm":"bun test src/batteries/models.integration.test.ts",bench:"bun bin/benchmarks.ts",make:"rm -rf dist && bun format && bun run build:grammars && tsc -p tsconfig.build.json && bun scripts/build.ts","build:bundles":"bun scripts/build.ts",typecheck:"tsc --noEmit",latest:"rm -rf node_modules && bun install",docs:"node bin/docs.js",dev:"bun run bin/dev.ts","build:demo":"bun scripts/build-demo.ts","build:cli":"bun build src/cli/tjs.ts --compile --outfile=dist/tjs && bun build src/cli/tjsx.ts --compile --outfile=dist/tjsx","functions:build":"cd functions && npm run build","functions:deploy":"cd functions && npm run deploy","functions:serve":"cd functions && npm run serve","deploy:hosting":"firebase deploy --only hosting",deploy:"npm run functions:deploy && firebase deploy --only hosting",start:"bun run build:demo && bun run dev"},dependencies:{"@codemirror/lang-css":"^6.3.1","@codemirror/lang-html":"^6.4.11","@codemirror/lang-markdown":"^6.5.0","@codemirror/theme-one-dark":"^6.1.3",acorn:"^8.15.0",firebase:"^10.12.0","tosijs-schema":"^1.2.0"}}});var g4={};P7(g4,{sep:()=>Q7,resolve:()=>n0,relative:()=>r6,posix:()=>Y7,parse:()=>K7,normalize:()=>k4,join:()=>a6,isAbsolute:()=>s6,format:()=>$7,extname:()=>X7,dirname:()=>e6,delimiter:()=>H7,default:()=>KX,basename:()=>Z7,_makeLong:()=>t6});function G1(Z){if(typeof Z!=="string")throw TypeError("Path must be a string. Received "+JSON.stringify(Z))}function o6(Z,$){var X="",K=0,Q=-1,H=0,Y;for(var z=0;z<=Z.length;++z){if(z<Z.length)Y=Z.charCodeAt(z);else if(Y===47)break;else Y=47;if(Y===47){if(Q===z-1||H===1);else if(Q!==z-1&&H===2){if(X.length<2||K!==2||X.charCodeAt(X.length-1)!==46||X.charCodeAt(X.length-2)!==46){if(X.length>2){var W=X.lastIndexOf("/");if(W!==X.length-1){if(W===-1)X="",K=0;else X=X.slice(0,W),K=X.length-1-X.lastIndexOf("/");Q=z,H=0;continue}}else if(X.length===2||X.length===1){X="",K=0,Q=z,H=0;continue}}if($){if(X.length>0)X+="/..";else X="..";K=2}}else{if(X.length>0)X+="/"+Z.slice(Q+1,z);else X=Z.slice(Q+1,z);K=z-Q-1}Q=z,H=0}else if(Y===46&&H!==-1)++H;else H=-1}return X}function $X(Z,$){var X=$.dir||$.root,K=$.base||($.name||"")+($.ext||"");if(!X)return K;if(X===$.root)return X+K;return X+Z+K}function n0(){var Z="",$=!1,X;for(var K=arguments.length-1;K>=-1&&!$;K--){var Q;if(K>=0)Q=arguments[K];else{if(X===void 0)X=process.cwd();Q=X}if(G1(Q),Q.length===0)continue;Z=Q+"/"+Z,$=Q.charCodeAt(0)===47}if(Z=o6(Z,!$),$)if(Z.length>0)return"/"+Z;else return"/";else if(Z.length>0)return Z;else return"."}function k4(Z){if(G1(Z),Z.length===0)return".";var $=Z.charCodeAt(0)===47,X=Z.charCodeAt(Z.length-1)===47;if(Z=o6(Z,!$),Z.length===0&&!$)Z=".";if(Z.length>0&&X)Z+="/";if($)return"/"+Z;return Z}function s6(Z){return G1(Z),Z.length>0&&Z.charCodeAt(0)===47}function a6(){if(arguments.length===0)return".";var Z;for(var $=0;$<arguments.length;++$){var X=arguments[$];if(G1(X),X.length>0)if(Z===void 0)Z=X;else Z+="/"+X}if(Z===void 0)return".";return k4(Z)}function r6(Z,$){if(G1(Z),G1($),Z===$)return"";if(Z=n0(Z),$=n0($),Z===$)return"";var X=1;for(;X<Z.length;++X)if(Z.charCodeAt(X)!==47)break;var K=Z.length,Q=K-X,H=1;for(;H<$.length;++H)if($.charCodeAt(H)!==47)break;var Y=$.length,z=Y-H,W=Q<z?Q:z,G=-1,J=0;for(;J<=W;++J){if(J===W){if(z>W){if($.charCodeAt(H+J)===47)return $.slice(H+J+1);else if(J===0)return $.slice(H+J)}else if(Q>W){if(Z.charCodeAt(X+J)===47)G=J;else if(J===0)G=0}break}var U=Z.charCodeAt(X+J),_=$.charCodeAt(H+J);if(U!==_)break;else if(U===47)G=J}var D="";for(J=X+G+1;J<=K;++J)if(J===K||Z.charCodeAt(J)===47)if(D.length===0)D+="..";else D+="/..";if(D.length>0)return D+$.slice(H+G);else{if(H+=G,$.charCodeAt(H)===47)++H;return $.slice(H)}}function t6(Z){return Z}function e6(Z){if(G1(Z),Z.length===0)return".";var $=Z.charCodeAt(0),X=$===47,K=-1,Q=!0;for(var H=Z.length-1;H>=1;--H)if($=Z.charCodeAt(H),$===47){if(!Q){K=H;break}}else Q=!1;if(K===-1)return X?"/":".";if(X&&K===1)return"//";return Z.slice(0,K)}function Z7(Z,$){if($!==void 0&&typeof $!=="string")throw TypeError('"ext" argument must be a string');G1(Z);var X=0,K=-1,Q=!0,H;if($!==void 0&&$.length>0&&$.length<=Z.length){if($.length===Z.length&&$===Z)return"";var Y=$.length-1,z=-1;for(H=Z.length-1;H>=0;--H){var W=Z.charCodeAt(H);if(W===47){if(!Q){X=H+1;break}}else{if(z===-1)Q=!1,z=H+1;if(Y>=0)if(W===$.charCodeAt(Y)){if(--Y===-1)K=H}else Y=-1,K=z}}if(X===K)K=z;else if(K===-1)K=Z.length;return Z.slice(X,K)}else{for(H=Z.length-1;H>=0;--H)if(Z.charCodeAt(H)===47){if(!Q){X=H+1;break}}else if(K===-1)Q=!1,K=H+1;if(K===-1)return"";return Z.slice(X,K)}}function X7(Z){G1(Z);var $=-1,X=0,K=-1,Q=!0,H=0;for(var Y=Z.length-1;Y>=0;--Y){var z=Z.charCodeAt(Y);if(z===47){if(!Q){X=Y+1;break}continue}if(K===-1)Q=!1,K=Y+1;if(z===46){if($===-1)$=Y;else if(H!==1)H=1}else if($!==-1)H=-1}if($===-1||K===-1||H===0||H===1&&$===K-1&&$===X+1)return"";return Z.slice($,K)}function $7(Z){if(Z===null||typeof Z!=="object")throw TypeError('The "pathObject" argument must be of type Object. Received type '+typeof Z);return $X("/",Z)}function K7(Z){G1(Z);var $={root:"",dir:"",base:"",ext:"",name:""};if(Z.length===0)return $;var X=Z.charCodeAt(0),K=X===47,Q;if(K)$.root="/",Q=1;else Q=0;var H=-1,Y=0,z=-1,W=!0,G=Z.length-1,J=0;for(;G>=Q;--G){if(X=Z.charCodeAt(G),X===47){if(!W){Y=G+1;break}continue}if(z===-1)W=!1,z=G+1;if(X===46){if(H===-1)H=G;else if(J!==1)J=1}else if(H!==-1)J=-1}if(H===-1||z===-1||J===0||J===1&&H===z-1&&H===Y+1){if(z!==-1)if(Y===0&&K)$.base=$.name=Z.slice(1,z);else $.base=$.name=Z.slice(Y,z)}else{if(Y===0&&K)$.name=Z.slice(1,H),$.base=Z.slice(1,z);else $.name=Z.slice(Y,H),$.base=Z.slice(Y,z);$.ext=Z.slice(H,z)}if(Y>0)$.dir=Z.slice(0,Y-1);else if(K)$.dir="/";return $}var Q7="/",H7=":",Y7,KX;var b4=C7(()=>{Y7=((Z)=>(Z.posix=Z,Z))({resolve:n0,normalize:k4,isAbsolute:s6,join:a6,relative:r6,_makeLong:t6,dirname:e6,basename:Z7,extname:X7,format:$7,parse:K7,sep:Q7,delimiter:H7,win32:null,posix:null}),KX=Y7});import*as s4 from"acorn";class y extends Error{line;column;source;filename;constructor(Z,$,X,K){let Q=`${K||"<source>"}:${$.line}:${$.column}`;super(`${Z} at ${Q}`);this.name="TranspileError",this.line=$.line,this.column=$.column,this.source=X,this.filename=K}}class D1 extends y{constructor(Z,$,X,K){super(Z,$,X,K);this.name="SyntaxError"}formatWithContext(Z=2){if(!this.source)return this.message;let $=this.source.split(`
|
|
2
2
|
`),X=this.line-1,K=Math.max(0,X-Z),Q=Math.min($.length-1,X+Z),H=[],Y=String(Q+1).length;for(let z=K;z<=Q;z++){let W=String(z+1).padStart(Y),G=z===X?">":" ";if(H.push(`${G} ${W} | ${$[z]}`),z===X){let J=" ".repeat(Y+4+this.column);H.push(`${J}^ ${this.message.split(" at ")[0]}`)}}return H.join(`
|
|
3
3
|
`)}}class V7 extends y{expected;received;suggestion;constructor(Z,$,X){super(Z,$,X?.source,X?.filename);this.name="TypeError",this.expected=X?.expected,this.received=X?.received,this.suggestion=X?.suggestion}}function Z1(Z){return{depth:Z.depth+1,locals:new Map,parent:Z,parameters:Z.parameters,atoms:Z.atoms,warnings:Z.warnings,source:Z.source,filename:Z.filename,options:Z.options}}function O7(Z,$){if($.locals.has(Z))return $.locals.get(Z);if($.parameters.has(Z))return $.parameters.get(Z)?.type;if($.parent)return O7(Z,$.parent);return}function h(Z){if(Z.loc)return{line:Z.loc.start.line,column:Z.loc.start.column};return{line:1,column:0}}function e0(Z,$){let X="",K=0,Q,H,Y="normal",z=[],W=[{type:"top-level",braceDepth:0}],G=0,J=()=>W[W.length-1]?.type||"top-level",U=()=>{let _=W[W.length-1];return _?.type==="class-body"&&G===_.braceDepth+1};while(K<Z.length){let _=Z[K],D=Z[K+1];switch(Y){case"single-string":if(X+=_,_==="\\"&&K+1<Z.length){X+=D,K+=2;continue}if(_==="'")Y="normal";K++;continue;case"double-string":if(X+=_,_==="\\"&&K+1<Z.length){X+=D,K+=2;continue}if(_==='"')Y="normal";K++;continue;case"template-string":if(X+=_,_==="\\"&&K+1<Z.length){X+=D,K+=2;continue}if(_==="$"&&D==="{"){X+=D,K+=2,z.push(1),Y="normal";continue}if(_==="`")Y="normal";K++;continue;case"line-comment":if(X+=_,_===`
|
|
4
|
-
`)Y="normal";K++;continue;case"block-comment":if(X+=_,_==="*"&&D==="/"){X+=D,K+=2,Y="normal";continue}K++;continue;case"regex":if(X+=_,_==="\\"&&K+1<Z.length){X+=D,K+=2;continue}if(_==="["){K++;while(K<Z.length&&Z[K]!=="]")if(X+=Z[K],Z[K]==="\\"&&K+1<Z.length)X+=Z[K+1],K+=2;else K++;if(K<Z.length)X+=Z[K],K++;continue}if(_==="/"){K++;while(K<Z.length&&/[gimsuy]/.test(Z[K]))X+=Z[K],K++;Y="normal";continue}K++;continue;case"normal":if(z.length>0){if(_==="{")z[z.length-1]++;else if(_==="}"){if(z[z.length-1]--,z[z.length-1]===0){z.pop(),X+=_,K++,Y="template-string";continue}}}if(_==="'"){X+=_,K++,Y="single-string";continue}if(_==='"'){X+=_,K++,Y="double-string";continue}if(_==="`"){X+=_,K++,Y="template-string";continue}if(_==="/"&&D==="/"){X+=_+D,K+=2,Y="line-comment";continue}if(_==="/"&&D==="*"){X+=_+D,K+=2,Y="block-comment";continue}if(_==="/"){let j=X.trimEnd();if(!j[j.length-1]||/[=(!,;:{[&|?+\-*%<>~^]$/.test(j)||/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)\s*$/.test(j)){X+=_,K++,Y="regex";continue}}break}if(_==="{"){G++,X+=_,K++;continue}if(_==="}"){G--;let j=W[W.length-1];if(j&&G===j.braceDepth)W.pop();X+=_,K++;continue}let I=Z.slice(K).match(/^class\s+\w+(?:\s+extends\s+\w+)?\s*\{/);if(I){let j=I[0].slice(0,-1);X+=j,K+=j.length,W.push({type:"class-body",braceDepth:G});continue}let B=Z.slice(K).match(/^function\s+(\w+)\s*\(/);if(B){let j=B[1],P=B[0].length,N=Z[K+P],M=null,w=K+P;if(N==="?"||N==="!")if(M=N,w++,M==="!")$.unsafeFunctions.add(j);else $.safeFunctions.add(j);X+=`function ${j}(`,K=w;let V=Y0(Z,K,"(",")");if(!V){X+=Z[K],K++;continue}let{content:O,endPos:S}=V;K=S;let k=t0(O,$,!0);X+=k+")";let g=K;while(g<Z.length&&/\s/.test(Z[g]))g++;let o=Z.slice(g,g+2);if(o==="->"||o==="-?"||o==="-!"){g+=2;while(g<Z.length&&/\s/.test(Z[g]))g++;let f=H0(Z,g);if(f){let{type:m,endPos:j1}=f;if(Q===void 0){if(Q=m,o==="-?")H="safe";else if(o==="-!")H="unsafe"}K=j1}}continue}let A=Z.slice(K).match(/^(constructor|(?:get|set)\s+\w+|async\s+\w+|\w+)\s*\(/);if(A&&U()){let j=A[1],P=A[0].length,N=K+P;X+=j+"(",K=N;let M=Y0(Z,K,"(",")");if(!M){X+=Z[K],K++;continue}let{content:w,endPos:V}=M;K=V;let O=t0(w,$,!0);X+=O+")";let S=K;while(S<Z.length&&/\s/.test(Z[S]))S++;if(Z.slice(S,S+2)==="->"){S+=2;while(S<Z.length&&/\s/.test(Z[S]))S++;let g=H0(Z,S);if(g)K=g.endPos}else if(Z[S]===":"){S++;while(S<Z.length&&/\s/.test(Z[S]))S++;let g=H0(Z,S);if(g)K=g.endPos}continue}if(Z[K]==="("){let j=Y0(Z,K+1,"(",")");if(!j){X+=Z[K],K++;continue}let{content:P,endPos:N}=j,M=N;while(M<Z.length&&/\s/.test(Z[M]))M++;let w,V=Z.slice(M,M+2);if(V==="->"||V==="-?"||V==="-!"){M+=2;while(M<Z.length&&/\s/.test(Z[M]))M++;let O=H0(Z,M);if(O){w=O.type,M=O.endPos;while(M<Z.length&&/\s/.test(Z[M]))M++}}if(Z.slice(M,M+2)==="=>"){let O=null,S=P,k=P.trimStart();if(k.startsWith("?")&&(k.length===1||/\s/.test(k[1])))O="?",S=k.slice(1);else if(k.startsWith("!")&&(k.length===1||/\s/.test(k[1])))O="!",S=k.slice(1);let g=t0(S,$,!1);X+=`(${O==="?"?"/* safe */ ":O==="!"?"/* unsafe */ ":""}${g})`,K=N;while(K<M&&/\s/.test(Z[K]))X+=Z[K],K++;if(w)K=M}else{let O=e0(P,$);X+=`(${O.source})`,K=N}continue}X+=Z[K],K++}return{source:X,returnType:Q,returnSafety:H}}function Y0(Z,$,X,K){let Q=1,H=$,Y=!1,z="";while(H<Z.length&&Q>0){let W=Z[H];if(!Y&&(W==="'"||W==='"'||W==="`"))Y=!0,z=W;else if(Y&&W===z&&Z[H-1]!=="\\")Y=!1;else if(!Y){if(W===X)Q++;else if(W===K)Q--}H++}if(Q!==0)return null;return{content:Z.slice($,H-1),endPos:H}}function N7(Z,$){let X=$;while(X<Z.length&&/\s/.test(Z[X]))X++;if(X>=Z.length)return null;let K=X,Q=Z[X];if(Q==="{"||Q==="["){let Y=Q==="{"?"}":"]",z=Y0(Z,X+1,Q,Y);if(!z)return null;return{value:Z.slice(K,z.endPos),endPos:z.endPos}}if(Q==="'"||Q==='"'||Q==="`"){X++;while(X<Z.length){if(Z[X]===Q&&Z[X-1]!=="\\")return X++,{value:Z.slice(K,X),endPos:X};X++}return null}if(/[-+\d]/.test(Q)){while(X<Z.length&&/[\d.eE+-]/.test(Z[X]))X++;return{value:Z.slice(K,X),endPos:X}}let H=Z.slice(X).match(/^(true|false|null|undefined)\b/);if(H)return{value:H[1],endPos:X+H[1].length};return null}function x1(Z){return Z.replace(/(?<!\|)\|(?!\|)/g," || ")}function H0(Z,$){let X=$,K=0,Q=!1,H="",Y=!1,z=(W)=>({type:x1(Z.slice($,W).trim()),endPos:W});while(X<Z.length){let W=Z[X];if(!Q&&(W==="'"||W==='"'||W==="`")){Q=!0,H=W,Y=!0,X++;continue}if(Q){if(W===H&&Z[X-1]!=="\\"){if(Q=!1,X++,K===0){let G=X;while(G<Z.length&&/\s/.test(Z[G]))G++;if(Z[G]==="{"){if(!Z.slice(G+1).match(/^\s*(\w+)\s*:/))return z(X)}if(Z[G]!=="|"&&Z[G]!=="&")return z(X)}continue}X++;continue}if(W==="{"||W==="["||W==="("){K++,Y=!0,X++;continue}if(W==="}"||W==="]"||W===")"){if(K--,K===0){X++;let G=X;while(G<Z.length&&/\s/.test(Z[G]))G++;if(Z[G]==="|"||Z[G]==="&")continue;return z(X)}X++;continue}if(K===0&&W==="{"){if(Y)return z(X);if(Z.slice(X+1).match(/^\s*(\w+)\s*:/)){K++,Y=!0,X++;continue}return z(X)}if(K===0&&(W==="|"||W==="&")){if(X++,X<Z.length&&Z[X]==="|")X++;while(X<Z.length&&/\s/.test(Z[X]))X++;continue}if(K===0&&(/\d/.test(W)||W==="-"&&/\d/.test(Z[X+1]))){let G=X;if(Z[G]==="-")G++;while(G<Z.length&&/\d/.test(Z[G]))G++;if(G<Z.length&&Z[G]==="."&&/\d/.test(Z[G+1])){G++;while(G<Z.length&&/\d/.test(Z[G]))G++}if(G<Z.length&&(Z[G]==="e"||Z[G]==="E")){if(G++,G<Z.length&&(Z[G]==="+"||Z[G]==="-"))G++;while(G<Z.length&&/\d/.test(Z[G]))G++}Y=!0,X=G;while(X<Z.length&&/\s/.test(Z[X]))X++;if(X<Z.length&&Z[X]==="{")return{type:x1(Z.slice($,G).trim()),endPos:G};if(Z[X]!=="|"&&Z[X]!=="&")return{type:x1(Z.slice($,G).trim()),endPos:G};continue}if(K===0&&/[a-zA-Z_]/.test(W)){let G=X;while(G<Z.length&&/\w/.test(Z[G]))G++;Y=!0,X=G;while(X<Z.length&&/\s/.test(Z[X]))X++;if(X<Z.length&&Z[X]==="{"){if(!Z.slice(X+1).match(/^\s*(\w+)\s*:/)){let U=G;while(U>$&&/\s/.test(Z[U-1]))U--;return{type:x1(Z.slice($,U).trim()),endPos:G}}}if(Z[X]!=="|"&&Z[X]!=="&")return{type:x1(Z.slice($,G).trim()),endPos:G};continue}X++}if(Y)return z(X);return null}function t0(Z,$,X){let K=e0(Z,{originalSource:Z,requiredParams:$.requiredParams,unsafeFunctions:$.unsafeFunctions,safeFunctions:$.safeFunctions}).source,Q=J0(K),H=!1,Y=new Set,z=(G)=>{if(X&&/^\w+$/.test(G)){if(Y.has(G))throw Error(`Duplicate parameter name '${G}'`);Y.add(G)}};return Q.map((G)=>{let J=G.trim();if(!J)return G;if(X&&J.startsWith("{")&&J.endsWith("}")){let D=J.slice(1,-1);return`{ ${n4(D,$)} }`}if(X&&J.startsWith("[")&&J.endsWith("]")){let D=J.slice(1,-1);return`[ ${n4(D,$)} ]`}let U=J.match(/^(\w+)\s*\?\s*:\s*(.+)$/);if(U){let[,D,I]=U;return z(D),H=!0,`${D} = ${I}`}if(!E7(J)){let D=J.match(/^(\w+)\s*=/);if(D)z(D[1]);return H=!0,G}let _=S7(J);if(_!==-1){let D=J.slice(0,_).trim(),I=J.slice(_+1).trim();if(z(D),H&&X&&/^\w+$/.test(D))throw Error(`Required parameter '${D}' cannot follow optional parameter`);if(X&&/^\w+$/.test(D))$.requiredParams.add(D);return`${D} = ${I}`}return G}).join(",")}function n4(Z,$){return J0(Z).map((Q)=>{let H=Q.trim();if(!H)return Q;let Y=H.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if(Y){let[,G,J]=Y;$.requiredParams.add(G);let U=z0(J);return`${G} = ${U}`}let z=H.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(z){let[,G,J]=z;$.requiredParams.add(G);let U=G0(J);return`${G} = ${U}`}let W=H.match(/^(\w+)\s*:\s*([\s\S]+)$/);if(W){let[,G,J]=W;return $.requiredParams.add(G),`${G} = ${J}`}return Q}).join(", ")}function z0(Z){let $=Z.slice(1,-1).trim();return`{ ${J0($).map((Q)=>{let H=Q.trim();if(!H)return Q;let Y=H.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if(Y){let[,U,_]=Y;return`${U}: ${z0(_)}`}let z=H.match(/^(\w+)\s*=\s*(\{[\s\S]*\})$/);if(z){let[,U,_]=z;return`${U}: ${z0(_)}`}let W=H.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(W){let[,U,_]=W;return`${U}: ${G0(_)}`}let G=H.match(/^(\w+)\s*=\s*(\[[\s\S]*\])$/);if(G){let[,U,_]=G;return`${U}: ${G0(_)}`}let J=H.match(/^(\w+)\s*=\s*([\s\S]+)$/);if(J){let[,U,_]=J;return`${U}: ${_}`}return Q}).join(", ")} }`}function G0(Z){let $=Z.slice(1,-1).trim();return`[ ${J0($).map((Q)=>{let H=Q.trim();if(!H)return Q;if(H.startsWith("{")&&H.endsWith("}"))return z0(H);if(H.startsWith("[")&&H.endsWith("]"))return G0(H);return Q}).join(", ")} ]`}function E7(Z){let $=0,X=!1,K=!1,Q=!1,H="";for(let Y=0;Y<Z.length;Y++){let z=Z[Y];if(!Q&&(z==="'"||z==='"'||z==="`")){Q=!0,H=z;continue}if(Q){if(z===H&&Z[Y-1]!=="\\")Q=!1;continue}if(z==="("||z==="{"||z==="[")$++;else if(z===")"||z==="}"||z==="]")$--;else if($===0){if(z===":")X=!0;if(z==="="&&Z[Y+1]!==">")K=!0}}return X&&!K}function S7(Z){let $=0,X=!1,K="";for(let Q=0;Q<Z.length;Q++){let H=Z[Q];if(!X&&(H==="'"||H==='"'||H==="`")){X=!0,K=H;continue}if(X){if(H===K&&Z[Q-1]!=="\\")X=!1;continue}if(H==="("||H==="{"||H==="[")$++;else if(H===")"||H==="}"||H==="]")$--;else if($===0&&H===":")return Q}return-1}function W0(Z,$={}){let X=Z,K,Q=new Set,H=new Set,Y=new Set,z={tjsEquals:!1,tjsClass:!1,tjsDate:!1,tjsNoeval:!1,tjsStandard:!1,tjsSafeEval:!1},W=Z.match(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\b/);if(W)K=W[2],Z=Z.replace(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\s*/,"$1");let G=/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*(TjsStrict|TjsEquals|TjsClass|TjsDate|TjsNoeval|TjsStandard|TjsSafeEval)\b/,J;while(J=Z.match(G)){let A=J[2];if(A==="TjsStrict")z.tjsEquals=!0,z.tjsClass=!0,z.tjsDate=!0,z.tjsNoeval=!0,z.tjsStandard=!0;else if(A==="TjsEquals")z.tjsEquals=!0;else if(A==="TjsClass")z.tjsClass=!0;else if(A==="TjsDate")z.tjsDate=!0;else if(A==="TjsNoeval")z.tjsNoeval=!0;else if(A==="TjsStandard")z.tjsStandard=!0;else if(A==="TjsSafeEval")z.tjsSafeEval=!0;Z=Z.replace(new RegExp(`^(\\s*(?:\\/\\/[^\\n]*\\n|\\/\\*[\\s\\S]*?\\*\\/\\s*)*)\\s*${A}\\s*`),"$1")}if(z.tjsStandard)Z=f7(Z);if(Z=v7(Z),z.tjsEquals&&!$.vmTarget)Z=y7(Z);Z=u7(Z),Z=d7(Z),Z=m7(Z),Z=l7(Z),Z=p7(Z);let{source:U,returnType:_,returnSafety:D}=e0(Z,{originalSource:X,requiredParams:Q,unsafeFunctions:H,safeFunctions:Y});Z=U,Z=T7(Z);let I=k7(Z);Z=I.source;let B=n7(Z,$.dangerouslySkipTests);if(Z=B.source,z.tjsClass)Z=c7(Z);if(z.tjsDate)Z=o7(Z);if(z.tjsNoeval)Z=s7(Z);return{source:Z,returnType:_,returnSafety:D,moduleSafety:K,tjsModes:z,originalSource:X,requiredParams:Q,unsafeFunctions:H,safeFunctions:Y,wasmBlocks:I.blocks,tests:B.tests,testErrors:B.errors}}function T7(Z){let $="",X=0;while(X<Z.length){let K=Z.slice(X).match(/^\btry\s*\{/);if(K){let H=X+K[0].length-1+1,Y=1,z=H;while(z<Z.length&&Y>0){let G=Z[z];if(G==="{")Y++;else if(G==="}")Y--;z++}if(Y!==0){$+=Z[X],X++;continue}if(Z.slice(z).match(/^\s*(catch|finally)\b/))$+=Z.slice(X,z),X=z;else{let G=Z.slice(H,z-1);$+=`try {${G}} catch (__try_err) { return { $error: true, message: __try_err?.message || String(__try_err), op: 'try', cause: __try_err, stack: globalThis.__tjs?.getStack?.() } }`,X=z}}else $+=Z[X],X++}return $}function k7(Z){let $=[],X="",K=0,Q=0;while(K<Z.length){let H=Z.slice(K).match(/^\bwasm\s*\{/);if(H){let Y=K,z=K+H[0].length,W=1,G=z;while(G<Z.length&&W>0){let V=Z[G];if(V==="{")W++;else if(V==="}")W--;G++}if(W!==0){X+=Z[K],K++;continue}let J=Z.slice(z,G-1),U,_=G,D=Z.slice(G).match(/^\s*fallback\s*\{/);if(D){let V=G+D[0].length;W=1;let O=V;while(O<Z.length&&W>0){let S=Z[O];if(S==="{")W++;else if(S==="}")W--;O++}if(W===0)U=Z.slice(V,O-1),_=O}let B=g7(J).map((V)=>{let O=b7(Z,Y,V);return O?`${V}: ${O}`:V}),A={id:`__tjs_wasm_${Q}`,body:J,fallback:U,captures:B,start:Y,end:_};$.push(A);let j=U??J,P=B.map((V)=>V.split(":")[0].trim()),N=P.length>0?P.join(", "):"",M=P.length>0?`globalThis.${A.id}(${N})`:`globalThis.${A.id}()`,w=`(globalThis.${A.id} ? ${M} : (() => {${j}})())`;X+=w,K=_,Q++}else X+=Z[K],K++}return{source:X,blocks:$}}function g7(Z){let $=Z.replace(/\/\/[^\n]*/g,"").replace(/\/\*[\s\S]*?\*\//g,""),X=/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,K=new Set,Q;while((Q=X.exec($))!==null)K.add(Q[1]);let H=new Set,Y=/\b(?:let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;while((Q=Y.exec($))!==null)H.add(Q[1]);let z=/\bfor\s*\(\s*(?:let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;while((Q=z.exec($))!==null)H.add(Q[1]);let W=new Set(["if","else","for","while","do","switch","case","break","continue","return","function","let","const","var","new","this","true","false","null","undefined","typeof","instanceof","in","of","try","catch","finally","throw","async","await","class","extends","super","import","export","default","from","as","static","get","set","yield","console","Math","Array","Object","String","Number","Boolean","Date","JSON","Promise","Map","Set","WeakMap","WeakSet","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","ArrayBuffer","DataView","Error","TypeError","RangeError","length","push","pop","shift","unshift","slice","splice","map","filter","reduce","forEach","find","findIndex","indexOf","includes","globalThis","window","document","Infinity","NaN","isNaN","isFinite","parseInt","parseFloat","encodeURI","decodeURI","eval"]),G=[];for(let J of K)if(!H.has(J)&&!W.has(J))G.push(J);return G.sort()}function b7(Z,$,X){let K=Z.slice(0,$),Q=/function\s+\w+\s*\(([^)]*)\)\s*(?:->.*?)?\s*\{[^}]*$/,H=K.match(Q);if(!H){let Y=/(?:const|let|var)?\s*\w+\s*=\s*(?:async\s*)?\(([^)]*)\)\s*(?:=>|->)?\s*\{[^}]*$/,z=K.match(Y);if(!z)return;return c4(z[1],X)}return c4(H[1],X)}function c4(Z,$){let X=Z.split(",").map((K)=>K.trim());for(let K of X){let Q=K.match(new RegExp(`^${$}\\s*:\\s*([A-Za-z][A-Za-z0-9]*)`));if(Q)return Q[1];let H=K.match(new RegExp(`^${$}\\s*=\\s*(Float32Array|Float64Array|Int32Array|Uint8Array|Int8Array|Int16Array|Uint16Array|Uint32Array)`));if(H)return H[1]}return}function J0(Z){let $=[],X="",K=0,Q=!1,H=!1,Y=0;while(Y<Z.length){let z=Z[Y],W=Z[Y+1];if(!H&&z==="/"&&W==="/"){Q=!0,X+="//",Y+=2;continue}if(!Q&&z==="/"&&W==="*"){H=!0,X+="/*",Y+=2;continue}if(Q&&z===`
|
|
5
|
-
`){Q=!1,X+=z,Y++;continue}if(H&&z==="*"&&W==="/"){H=!1,X+="*/",Y+=2;continue}if(Q||H){X+=z,Y++;continue}if(z==="("||z==="{"||z==="[")K++,X+=z;else if(z===")"||z==="}"||z==="]")K--,X+=z;else if(z===","&&K===0)$.push(X),X="";else X+=z;Y++}if(X.trim())$.push(X);return $}function
|
|
4
|
+
`)Y="normal";K++;continue;case"block-comment":if(X+=_,_==="*"&&D==="/"){X+=D,K+=2,Y="normal";continue}K++;continue;case"regex":if(X+=_,_==="\\"&&K+1<Z.length){X+=D,K+=2;continue}if(_==="["){K++;while(K<Z.length&&Z[K]!=="]")if(X+=Z[K],Z[K]==="\\"&&K+1<Z.length)X+=Z[K+1],K+=2;else K++;if(K<Z.length)X+=Z[K],K++;continue}if(_==="/"){K++;while(K<Z.length&&/[gimsuy]/.test(Z[K]))X+=Z[K],K++;Y="normal";continue}K++;continue;case"normal":if(z.length>0){if(_==="{")z[z.length-1]++;else if(_==="}"){if(z[z.length-1]--,z[z.length-1]===0){z.pop(),X+=_,K++,Y="template-string";continue}}}if(_==="'"){X+=_,K++,Y="single-string";continue}if(_==='"'){X+=_,K++,Y="double-string";continue}if(_==="`"){X+=_,K++,Y="template-string";continue}if(_==="/"&&D==="/"){X+=_+D,K+=2,Y="line-comment";continue}if(_==="/"&&D==="*"){X+=_+D,K+=2,Y="block-comment";continue}if(_==="/"){let j=X.trimEnd();if(!j[j.length-1]||/[=(!,;:{[&|?+\-*%<>~^]$/.test(j)||/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)\s*$/.test(j)){X+=_,K++,Y="regex";continue}}break}if(_==="{"){G++,X+=_,K++;continue}if(_==="}"){G--;let j=W[W.length-1];if(j&&G===j.braceDepth)W.pop();X+=_,K++;continue}let I=Z.slice(K).match(/^class\s+\w+(?:\s+extends\s+\w+)?\s*\{/);if(I){let j=I[0].slice(0,-1);X+=j,K+=j.length,W.push({type:"class-body",braceDepth:G});continue}let B=Z.slice(K).match(/^function\s+(\w+)\s*\(/);if(B){let j=B[1],P=B[0].length,N=Z[K+P],M=null,w=K+P;if(N==="?"||N==="!")if(M=N,w++,M==="!")$.unsafeFunctions.add(j);else $.safeFunctions.add(j);X+=`function ${j}(`,K=w;let V=Y0(Z,K,"(",")");if(!V){X+=Z[K],K++;continue}let{content:O,endPos:S}=V;K=S;let k=t0(O,$,!0);X+=k+")";let g=K;while(g<Z.length&&/\s/.test(Z[g]))g++;let o=Z.slice(g,g+2);if(o==="->"||o==="-?"||o==="-!"){g+=2;while(g<Z.length&&/\s/.test(Z[g]))g++;let v=H0(Z,g);if(v){let{type:m,endPos:j1}=v;if(Q===void 0){if(Q=m,o==="-?")H="safe";else if(o==="-!")H="unsafe"}K=j1}}continue}let A=Z.slice(K).match(/^(constructor|(?:get|set)\s+\w+|async\s+\w+|\w+)\s*\(/);if(A&&U()){let j=A[1],P=A[0].length,N=K+P;X+=j+"(",K=N;let M=Y0(Z,K,"(",")");if(!M){X+=Z[K],K++;continue}let{content:w,endPos:V}=M;K=V;let O=t0(w,$,!0);X+=O+")";let S=K;while(S<Z.length&&/\s/.test(Z[S]))S++;if(Z.slice(S,S+2)==="->"){S+=2;while(S<Z.length&&/\s/.test(Z[S]))S++;let g=H0(Z,S);if(g)K=g.endPos}else if(Z[S]===":"){S++;while(S<Z.length&&/\s/.test(Z[S]))S++;let g=H0(Z,S);if(g)K=g.endPos}continue}if(Z[K]==="("){let j=Y0(Z,K+1,"(",")");if(!j){X+=Z[K],K++;continue}let{content:P,endPos:N}=j,M=N;while(M<Z.length&&/\s/.test(Z[M]))M++;let w,V=Z.slice(M,M+2);if(V==="->"||V==="-?"||V==="-!"){M+=2;while(M<Z.length&&/\s/.test(Z[M]))M++;let O=H0(Z,M);if(O){w=O.type,M=O.endPos;while(M<Z.length&&/\s/.test(Z[M]))M++}}if(Z.slice(M,M+2)==="=>"){let O=null,S=P,k=P.trimStart();if(k.startsWith("?")&&(k.length===1||/\s/.test(k[1])))O="?",S=k.slice(1);else if(k.startsWith("!")&&(k.length===1||/\s/.test(k[1])))O="!",S=k.slice(1);let g=t0(S,$,!1);X+=`(${O==="?"?"/* safe */ ":O==="!"?"/* unsafe */ ":""}${g})`,K=N;while(K<M&&/\s/.test(Z[K]))X+=Z[K],K++;if(w)K=M}else{let O=e0(P,$);X+=`(${O.source})`,K=N}continue}X+=Z[K],K++}return{source:X,returnType:Q,returnSafety:H}}function Y0(Z,$,X,K){let Q=1,H=$,Y=!1,z="";while(H<Z.length&&Q>0){let W=Z[H];if(!Y&&(W==="'"||W==='"'||W==="`"))Y=!0,z=W;else if(Y&&W===z&&Z[H-1]!=="\\")Y=!1;else if(!Y){if(W===X)Q++;else if(W===K)Q--}H++}if(Q!==0)return null;return{content:Z.slice($,H-1),endPos:H}}function N7(Z,$){let X=$;while(X<Z.length&&/\s/.test(Z[X]))X++;if(X>=Z.length)return null;let K=X,Q=Z[X];if(Q==="{"||Q==="["){let Y=Q==="{"?"}":"]",z=Y0(Z,X+1,Q,Y);if(!z)return null;return{value:Z.slice(K,z.endPos),endPos:z.endPos}}if(Q==="'"||Q==='"'||Q==="`"){X++;while(X<Z.length){if(Z[X]===Q&&Z[X-1]!=="\\")return X++,{value:Z.slice(K,X),endPos:X};X++}return null}if(/[-+\d]/.test(Q)){while(X<Z.length&&/[\d.eE+-]/.test(Z[X]))X++;return{value:Z.slice(K,X),endPos:X}}let H=Z.slice(X).match(/^(true|false|null|undefined)\b/);if(H)return{value:H[1],endPos:X+H[1].length};return null}function x1(Z){return Z.replace(/(?<!\|)\|(?!\|)/g," || ")}function H0(Z,$){let X=$,K=0,Q=!1,H="",Y=!1,z=(W)=>({type:x1(Z.slice($,W).trim()),endPos:W});while(X<Z.length){let W=Z[X];if(!Q&&(W==="'"||W==='"'||W==="`")){Q=!0,H=W,Y=!0,X++;continue}if(Q){if(W===H&&Z[X-1]!=="\\"){if(Q=!1,X++,K===0){let G=X;while(G<Z.length&&/\s/.test(Z[G]))G++;if(Z[G]==="{"){if(!Z.slice(G+1).match(/^\s*(\w+)\s*:/))return z(X)}if(Z[G]!=="|"&&Z[G]!=="&")return z(X)}continue}X++;continue}if(W==="{"||W==="["||W==="("){K++,Y=!0,X++;continue}if(W==="}"||W==="]"||W===")"){if(K--,K===0){X++;let G=X;while(G<Z.length&&/\s/.test(Z[G]))G++;if(Z[G]==="|"||Z[G]==="&")continue;return z(X)}X++;continue}if(K===0&&W==="{"){if(Y)return z(X);if(Z.slice(X+1).match(/^\s*(\w+)\s*:/)){K++,Y=!0,X++;continue}return z(X)}if(K===0&&(W==="|"||W==="&")){if(X++,X<Z.length&&Z[X]==="|")X++;while(X<Z.length&&/\s/.test(Z[X]))X++;continue}if(K===0&&(/\d/.test(W)||W==="-"&&/\d/.test(Z[X+1]))){let G=X;if(Z[G]==="-")G++;while(G<Z.length&&/\d/.test(Z[G]))G++;if(G<Z.length&&Z[G]==="."&&/\d/.test(Z[G+1])){G++;while(G<Z.length&&/\d/.test(Z[G]))G++}if(G<Z.length&&(Z[G]==="e"||Z[G]==="E")){if(G++,G<Z.length&&(Z[G]==="+"||Z[G]==="-"))G++;while(G<Z.length&&/\d/.test(Z[G]))G++}Y=!0,X=G;while(X<Z.length&&/\s/.test(Z[X]))X++;if(X<Z.length&&Z[X]==="{")return{type:x1(Z.slice($,G).trim()),endPos:G};if(Z[X]!=="|"&&Z[X]!=="&")return{type:x1(Z.slice($,G).trim()),endPos:G};continue}if(K===0&&/[a-zA-Z_]/.test(W)){let G=X;while(G<Z.length&&/\w/.test(Z[G]))G++;Y=!0,X=G;while(X<Z.length&&/\s/.test(Z[X]))X++;if(X<Z.length&&Z[X]==="{"){if(!Z.slice(X+1).match(/^\s*(\w+)\s*:/)){let U=G;while(U>$&&/\s/.test(Z[U-1]))U--;return{type:x1(Z.slice($,U).trim()),endPos:G}}}if(Z[X]!=="|"&&Z[X]!=="&")return{type:x1(Z.slice($,G).trim()),endPos:G};continue}X++}if(Y)return z(X);return null}function t0(Z,$,X){let K=e0(Z,{originalSource:Z,requiredParams:$.requiredParams,unsafeFunctions:$.unsafeFunctions,safeFunctions:$.safeFunctions}).source,Q=J0(K),H=!1,Y=new Set,z=(G)=>{if(X&&/^\w+$/.test(G)){if(Y.has(G))throw Error(`Duplicate parameter name '${G}'`);Y.add(G)}};return Q.map((G)=>{let J=G.trim();if(!J)return G;if(X&&J.startsWith("{")&&J.endsWith("}")){let D=J.slice(1,-1);return`{ ${n4(D,$)} }`}if(X&&J.startsWith("[")&&J.endsWith("]")){let D=J.slice(1,-1);return`[ ${n4(D,$)} ]`}let U=J.match(/^(\w+)\s*\?\s*:\s*(.+)$/);if(U){let[,D,I]=U;return z(D),H=!0,`${D} = ${I}`}if(!E7(J)){let D=J.match(/^(\w+)\s*=/);if(D)z(D[1]);return H=!0,G}let _=S7(J);if(_!==-1){let D=J.slice(0,_).trim(),I=J.slice(_+1).trim();if(z(D),H&&X&&/^\w+$/.test(D))throw Error(`Required parameter '${D}' cannot follow optional parameter`);if(X&&/^\w+$/.test(D))$.requiredParams.add(D);return`${D} = ${I}`}return G}).join(",")}function n4(Z,$){return J0(Z).map((Q)=>{let H=Q.trim();if(!H)return Q;let Y=H.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if(Y){let[,G,J]=Y;$.requiredParams.add(G);let U=z0(J);return`${G} = ${U}`}let z=H.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(z){let[,G,J]=z;$.requiredParams.add(G);let U=G0(J);return`${G} = ${U}`}let W=H.match(/^(\w+)\s*:\s*([\s\S]+)$/);if(W){let[,G,J]=W;return $.requiredParams.add(G),`${G} = ${J}`}return Q}).join(", ")}function z0(Z){let $=Z.slice(1,-1).trim();return`{ ${J0($).map((Q)=>{let H=Q.trim();if(!H)return Q;let Y=H.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if(Y){let[,U,_]=Y;return`${U}: ${z0(_)}`}let z=H.match(/^(\w+)\s*=\s*(\{[\s\S]*\})$/);if(z){let[,U,_]=z;return`${U}: ${z0(_)}`}let W=H.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(W){let[,U,_]=W;return`${U}: ${G0(_)}`}let G=H.match(/^(\w+)\s*=\s*(\[[\s\S]*\])$/);if(G){let[,U,_]=G;return`${U}: ${G0(_)}`}let J=H.match(/^(\w+)\s*=\s*([\s\S]+)$/);if(J){let[,U,_]=J;return`${U}: ${_}`}return Q}).join(", ")} }`}function G0(Z){let $=Z.slice(1,-1).trim();return`[ ${J0($).map((Q)=>{let H=Q.trim();if(!H)return Q;if(H.startsWith("{")&&H.endsWith("}"))return z0(H);if(H.startsWith("[")&&H.endsWith("]"))return G0(H);return Q}).join(", ")} ]`}function E7(Z){let $=0,X=!1,K=!1,Q=!1,H="";for(let Y=0;Y<Z.length;Y++){let z=Z[Y];if(!Q&&(z==="'"||z==='"'||z==="`")){Q=!0,H=z;continue}if(Q){if(z===H&&Z[Y-1]!=="\\")Q=!1;continue}if(z==="("||z==="{"||z==="[")$++;else if(z===")"||z==="}"||z==="]")$--;else if($===0){if(z===":")X=!0;if(z==="="&&Z[Y+1]!==">")K=!0}}return X&&!K}function S7(Z){let $=0,X=!1,K="";for(let Q=0;Q<Z.length;Q++){let H=Z[Q];if(!X&&(H==="'"||H==='"'||H==="`")){X=!0,K=H;continue}if(X){if(H===K&&Z[Q-1]!=="\\")X=!1;continue}if(H==="("||H==="{"||H==="[")$++;else if(H===")"||H==="}"||H==="]")$--;else if($===0&&H===":")return Q}return-1}function W0(Z,$={}){let X=Z,K,Q=new Set,H=new Set,Y=new Set,z={tjsEquals:!1,tjsClass:!1,tjsDate:!1,tjsNoeval:!1,tjsStandard:!1,tjsSafeEval:!1},W=Z.match(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\b/);if(W)K=W[2],Z=Z.replace(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\s*/,"$1");let G=/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*(TjsStrict|TjsEquals|TjsClass|TjsDate|TjsNoeval|TjsStandard|TjsSafeEval)\b/,J;while(J=Z.match(G)){let A=J[2];if(A==="TjsStrict")z.tjsEquals=!0,z.tjsClass=!0,z.tjsDate=!0,z.tjsNoeval=!0,z.tjsStandard=!0;else if(A==="TjsEquals")z.tjsEquals=!0;else if(A==="TjsClass")z.tjsClass=!0;else if(A==="TjsDate")z.tjsDate=!0;else if(A==="TjsNoeval")z.tjsNoeval=!0;else if(A==="TjsStandard")z.tjsStandard=!0;else if(A==="TjsSafeEval")z.tjsSafeEval=!0;Z=Z.replace(new RegExp(`^(\\s*(?:\\/\\/[^\\n]*\\n|\\/\\*[\\s\\S]*?\\*\\/\\s*)*)\\s*${A}\\s*`),"$1")}if(z.tjsStandard)Z=v7(Z);if(Z=f7(Z),z.tjsEquals&&!$.vmTarget)Z=y7(Z);Z=u7(Z),Z=d7(Z),Z=m7(Z),Z=l7(Z),Z=p7(Z);let{source:U,returnType:_,returnSafety:D}=e0(Z,{originalSource:X,requiredParams:Q,unsafeFunctions:H,safeFunctions:Y});Z=U,Z=T7(Z);let I=k7(Z);Z=I.source;let B=n7(Z,$.dangerouslySkipTests);if(Z=B.source,z.tjsClass)Z=c7(Z);if(z.tjsDate)Z=o7(Z);if(z.tjsNoeval)Z=s7(Z);return{source:Z,returnType:_,returnSafety:D,moduleSafety:K,tjsModes:z,originalSource:X,requiredParams:Q,unsafeFunctions:H,safeFunctions:Y,wasmBlocks:I.blocks,tests:B.tests,testErrors:B.errors}}function T7(Z){let $="",X=0;while(X<Z.length){let K=Z.slice(X).match(/^\btry\s*\{/);if(K){let H=X+K[0].length-1+1,Y=1,z=H;while(z<Z.length&&Y>0){let G=Z[z];if(G==="{")Y++;else if(G==="}")Y--;z++}if(Y!==0){$+=Z[X],X++;continue}if(Z.slice(z).match(/^\s*(catch|finally)\b/))$+=Z.slice(X,z),X=z;else{let G=Z.slice(H,z-1);$+=`try {${G}} catch (__try_err) { return { $error: true, message: __try_err?.message || String(__try_err), op: 'try', cause: __try_err, stack: globalThis.__tjs?.getStack?.() } }`,X=z}}else $+=Z[X],X++}return $}function k7(Z){let $=[],X="",K=0,Q=0;while(K<Z.length){let H=Z.slice(K).match(/^\bwasm\s*\{/);if(H){let Y=K,z=K+H[0].length,W=1,G=z;while(G<Z.length&&W>0){let V=Z[G];if(V==="{")W++;else if(V==="}")W--;G++}if(W!==0){X+=Z[K],K++;continue}let J=Z.slice(z,G-1),U,_=G,D=Z.slice(G).match(/^\s*fallback\s*\{/);if(D){let V=G+D[0].length;W=1;let O=V;while(O<Z.length&&W>0){let S=Z[O];if(S==="{")W++;else if(S==="}")W--;O++}if(W===0)U=Z.slice(V,O-1),_=O}let B=g7(J).map((V)=>{let O=b7(Z,Y,V);return O?`${V}: ${O}`:V}),A={id:`__tjs_wasm_${Q}`,body:J,fallback:U,captures:B,start:Y,end:_};$.push(A);let j=U??J,P=B.map((V)=>V.split(":")[0].trim()),N=P.length>0?P.join(", "):"",M=P.length>0?`globalThis.${A.id}(${N})`:`globalThis.${A.id}()`,w=`(globalThis.${A.id} ? ${M} : (() => {${j}})())`;X+=w,K=_,Q++}else X+=Z[K],K++}return{source:X,blocks:$}}function g7(Z){let $=Z.replace(/\/\/[^\n]*/g,"").replace(/\/\*[\s\S]*?\*\//g,""),X=/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,K=new Set,Q;while((Q=X.exec($))!==null)K.add(Q[1]);let H=new Set,Y=/\b(?:let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;while((Q=Y.exec($))!==null)H.add(Q[1]);let z=/\bfor\s*\(\s*(?:let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;while((Q=z.exec($))!==null)H.add(Q[1]);let W=new Set(["if","else","for","while","do","switch","case","break","continue","return","function","let","const","var","new","this","true","false","null","undefined","typeof","instanceof","in","of","try","catch","finally","throw","async","await","class","extends","super","import","export","default","from","as","static","get","set","yield","console","Math","Array","Object","String","Number","Boolean","Date","JSON","Promise","Map","Set","WeakMap","WeakSet","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","ArrayBuffer","DataView","Error","TypeError","RangeError","length","push","pop","shift","unshift","slice","splice","map","filter","reduce","forEach","find","findIndex","indexOf","includes","globalThis","window","document","Infinity","NaN","isNaN","isFinite","parseInt","parseFloat","encodeURI","decodeURI","eval"]),G=[];for(let J of K)if(!H.has(J)&&!W.has(J))G.push(J);return G.sort()}function b7(Z,$,X){let K=Z.slice(0,$),Q=/function\s+\w+\s*\(([^)]*)\)\s*(?:->.*?)?\s*\{[^}]*$/,H=K.match(Q);if(!H){let Y=/(?:const|let|var)?\s*\w+\s*=\s*(?:async\s*)?\(([^)]*)\)\s*(?:=>|->)?\s*\{[^}]*$/,z=K.match(Y);if(!z)return;return c4(z[1],X)}return c4(H[1],X)}function c4(Z,$){let X=Z.split(",").map((K)=>K.trim());for(let K of X){let Q=K.match(new RegExp(`^${$}\\s*:\\s*([A-Za-z][A-Za-z0-9]*)`));if(Q)return Q[1];let H=K.match(new RegExp(`^${$}\\s*=\\s*(Float32Array|Float64Array|Int32Array|Uint8Array|Int8Array|Int16Array|Uint16Array|Uint32Array)`));if(H)return H[1]}return}function J0(Z){let $=[],X="",K=0,Q=!1,H=!1,Y=0;while(Y<Z.length){let z=Z[Y],W=Z[Y+1];if(!H&&z==="/"&&W==="/"){Q=!0,X+="//",Y+=2;continue}if(!Q&&z==="/"&&W==="*"){H=!0,X+="/*",Y+=2;continue}if(Q&&z===`
|
|
5
|
+
`){Q=!1,X+=z,Y++;continue}if(H&&z==="*"&&W==="/"){H=!1,X+="*/",Y+=2;continue}if(Q||H){X+=z,Y++;continue}if(z==="("||z==="{"||z==="[")K++,X+=z;else if(z===")"||z==="}"||z==="]")K--,X+=z;else if(z===","&&K===0)$.push(X),X="";else X+=z;Y++}if(X.trim())$.push(X);return $}function f7(Z){let X=new RegExp(`([\\w][\\w.\\[\\]()]*|null|undefined|true|false|\\d+(?:\\.\\d+)?|'[^']*'|"[^"]*")\\s+IsNot\\s+([\\w][\\w.\\[\\]()]*|null|undefined|true|false|\\d+(?:\\.\\d+)?|'[^']*'|"[^"]*")`,"g");Z=Z.replace(X,"IsNot($1, $2)");let K=new RegExp(`([\\w][\\w.\\[\\]()]*|null|undefined|true|false|\\d+(?:\\.\\d+)?|'[^']*'|"[^"]*")\\s+Is\\s+([\\w][\\w.\\[\\]()]*|null|undefined|true|false|\\d+(?:\\.\\d+)?|'[^']*'|"[^"]*")`,"g");return Z=Z.replace(K,"Is($1, $2)"),Z}function v7(Z){let $=/^[\s]*[([/+\-`]/,X=/[{([,;:+\-*/%=&|?<>!~^]\s*$|^\s*$/,K=/\b(return|throw|yield|await|case|default|extends|new|typeof|void|delete|in|of|instanceof)\s*$/,Q=Z.split(`
|
|
6
6
|
`),H=[];for(let Y=0;Y<Q.length;Y++){let z=Q[Y],W=Y>0?Q[Y-1]:"";if(Y>0&&$.test(z)){let G=W.replace(/\/\/.*$/,"").replace(/\/\*.*\*\/\s*$/,"");if(!X.test(G)&&!K.test(G)){let J=z.match(/^(\s*)/),U=J?J[1]:"",_=z.slice(U.length);H.push(U+";"+_);continue}}H.push(z)}return H.join(`
|
|
7
7
|
`)}function y7(Z){let $=[],X=0,K="normal",Q=[];while(X<Z.length){let Y=Z[X],z=Z[X+1];switch(K){case"single-string":if(Y==="\\"&&X+1<Z.length){X+=2;continue}if(Y==="'")K="normal";X++;continue;case"double-string":if(Y==="\\"&&X+1<Z.length){X+=2;continue}if(Y==='"')K="normal";X++;continue;case"template-string":if(Y==="\\"&&X+1<Z.length){X+=2;continue}if(Y==="$"&&z==="{"){X+=2,Q.push(1),K="normal";continue}if(Y==="`")K="normal";X++;continue;case"line-comment":if(Y===`
|
|
8
8
|
`)K="normal";X++;continue;case"block-comment":if(Y==="*"&&z==="/"){X+=2,K="normal";continue}X++;continue;case"regex":if(Y==="\\"&&X+1<Z.length){X+=2;continue}if(Y==="["){X++;while(X<Z.length&&Z[X]!=="]")if(Z[X]==="\\"&&X+1<Z.length)X+=2;else X++;if(X<Z.length)X++;continue}if(Y==="/"){X++;while(X<Z.length&&/[gimsuy]/.test(Z[X]))X++;K="normal";continue}X++;continue;case"normal":if(Q.length>0){if(Y==="{")Q[Q.length-1]++;else if(Y==="}"){if(Q[Q.length-1]--,Q[Q.length-1]===0){Q.pop(),X++,K="template-string";continue}}}if(Y==="'"){X++,K="single-string";continue}if(Y==='"'){X++,K="double-string";continue}if(Y==="`"){X++,K="template-string";continue}if(Y==="/"&&z==="/"){X+=2,K="line-comment";continue}if(Y==="/"&&z==="*"){X+=2,K="block-comment";continue}if(Y==="/"){let W=X-1;while(W>=0&&/\s/.test(Z[W]))W--;let G=W>=0?Z[W]:"";if(!G||/[=(!,;:{[&|?+\-*%<>~^]/.test(G)||W>=5&&/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)$/.test(Z.slice(Math.max(0,W-10),W+1))){X++,K="regex";continue}}if(Y==="="&&z==="="&&Z[X+2]!=="="&&Z[X-1]!=="!"){$.push({pos:X,op:"=="}),X+=2;continue}if(Y==="!"&&z==="="&&Z[X+2]!=="="){$.push({pos:X,op:"!="}),X+=2;continue}break}X++}if($.length===0)return Z;let H=Z;for(let Y=$.length-1;Y>=0;Y--){let{pos:z,op:W}=$[Y],G=W==="=="?"Is":"IsNot",J=h7(H,z),U=x7(H,z+2),_=H.slice(J,z).trim(),D=H.slice(z+2,U).trim();if(_&&D){let I=H.slice(0,J),B=H.slice(U),j=/[a-zA-Z0-9_$]$/.test(I)?" ":"";H=`${I}${j}${G}(${_}, ${D})${B}`}}return H}function h7(Z,$){let X=$-1;while(X>=0&&/\s/.test(Z[X]))X--;if(X<0)return 0;let K=0,Q=!1,H="";while(X>=0){let Y=Z[X],z=X>0?Z[X-1]:"";if(Q){if(Y===H&&z!=="\\")Q=!1;X--;continue}if((Y==='"'||Y==="'"||Y==="`")&&z!=="\\"){Q=!0,H=Y,X--;continue}if(Y===")"||Y==="]"){K++,X--;continue}if(Y==="("||Y==="["){if(K>0){K--,X--;continue}return X+1}if(K>0){X--;continue}if(Y===";"||Y==="{"||Y==="}")return X+1;if(/[a-z]/.test(Y)){let W=X+1,G=X;while(G>0&&/[a-z]/i.test(Z[G-1]))G--;let J=Z.slice(G,W),U=G>0?Z[G-1]:"";if(!/[a-zA-Z0-9_$]/.test(U)){if(["return","throw","case","typeof","void","delete","await","yield","new"].includes(J))return W}}if(Y===">"&&z==="=")return X+1;if(Y==="="&&z!=="="&&z!=="!"&&z!=="<"&&z!==">")return X+1;if(Y==="&"&&z==="&")return X+1;if(Y==="|"&&z==="|")return X+1;if(Y==="?"||Y===":")return X+1;if(Y===",")return X+1;X--}return 0}function x7(Z,$){let X=$;while(X<Z.length&&/\s/.test(Z[X]))X++;if(X>=Z.length)return Z.length;let K=0,Q=!1,H="";while(X<Z.length){let Y=Z[X],z=X+1<Z.length?Z[X+1]:"";if(Q){if(Y===H&&Z[X-1]!=="\\")Q=!1;X++;continue}if((Y==='"'||Y==="'"||Y==="`")&&Z[X-1]!=="\\"){Q=!0,H=Y,X++;continue}if(Y==="("||Y==="["||Y==="{"){K++,X++;continue}if(Y===")"||Y==="]"||Y==="}"){if(K>0){K--,X++;continue}return X}if(K>0){X++;continue}if(Y===";")return X;if(Y==="&"&&z==="&")return X;if(Y==="|"&&z==="|")return X;if(Y==="?")return X;if(Y===":")return X;if(Y===",")return X;if((Y==="="||Y==="!")&&z==="="&&Z[X+2]!=="=")return X;X++}return Z.length}function u7(Z){let $="",X=0;while(X<Z.length){let K=Z.slice(X).match(/^\bType\s+([A-Z][a-zA-Z0-9_]*)\s*/);if(K){let Q=K[1],H=X+K[0].length,Y=Q,z=!1,W=Z.slice(H).match(/^(['"`])([^]*?)\1\s*/);if(W){let _=H+W[0].length,D=Z[_],I=D===void 0||_>=Z.length||D!=="="&&D!=="{";if(D==="="||D==="{")Y=W[2],z=!0,H=_;else if(I){let B=W[0].trim(),A=W[0].slice(B.length);$+=`const ${Q} = Type('${Q}', ${B})${A}`,X=_;continue}}let G,J=H,U=Z.slice(H).match(/^=\s*/);if(U){H+=U[0].length;let _=Z.slice(H).match(/^(\+?\d+(?:\.\d+)?|['"`][^'"`]*['"`]|\{[^}]*\}|\[[^\]]*\]|true|false|null)/);if(_){G=_[0],H+=_[0].length,J=H;let D=Z.slice(H).match(/^\s*/);if(D)H+=D[0].length}}if(Z[H]==="{"){let _=H+1,D=1,I=_;while(I<Z.length&&D>0){let w=Z[I];if(w==="{")D++;else if(w==="}")D--;I++}if(D!==0){$+=Z[X],X++;continue}let B=Z.slice(_,I-1).trim(),A=I,j=B.match(/description\s*:\s*(['"`])([^]*?)\1/);if(j&&!z)Y=j[2];let P,N=B.match(/example\s*:\s*/);if(N){let w=N.index+N[0].length,V=N7(B,w);if(V)P=V.value.trim()}let M=B.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/);if(M&&P){let w=M[1].trim(),V=M[2].trim(),O=G?`, ${G}`:"";$+=`const ${Q} = Type('${Y}', (${w}) => { if (!globalThis.__tjs?.validate(${w}, globalThis.__tjs?.infer(${P}))) return false; ${V} }, ${P}${O})`}else if(M){let w=M[1].trim(),V=M[2].trim(),O=G?`, undefined, ${G}`:"";$+=`const ${Q} = Type('${Y}', (${w}) => { ${V} }${O})`}else if(P){let w=G?`, ${G}`:"";$+=`const ${Q} = Type('${Y}', undefined, ${P}${w})`}else if(G)$+=`const ${Q} = Type('${Y}', ${G})`;else $+=`const ${Q} = Type('${Y}')`;X=A;continue}else if(G){$+=`const ${Q} = Type('${Y}', ${G})`,X=J;continue}else if(!W){let _=Z.slice(H).match(/^(['"`][^]*?['"`]|\+?\d+(?:\.\d+)?|true|false|null|\{[^]*?\}|\[[^]*?\])/);if(_){let D=_[0];$+=`const ${Q} = Type('${Q}', ${D})`,X=H+_[0].length;continue}}}$+=Z[X],X++}return $}function d7(Z){let $="",X=0;while(X<Z.length){let K=Z.slice(X).match(/^\bGeneric\s+([A-Z][a-zA-Z0-9_]*)\s*<([^>]+)>\s*\{/);if(K){let Q=K[1],H=K[2],z=X+K[0].length-1+1,W=1,G=z;while(G<Z.length&&W>0){let A=Z[G];if(A==="{")W++;else if(A==="}")W--;G++}if(W!==0){$+=Z[X],X++;continue}let J=Z.slice(z,G-1).trim(),U=G,_=H.split(",").map((A)=>{let j=A.trim().split("=").map((P)=>P.trim());if(j.length===2)return`['${j[0]}', ${j[1]}]`;return`'${j[0]}'`}),D=J.match(/description\s*:\s*(['"`])([^]*?)\1/),I=J.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/),B=D?D[2]:Q;if(I){let A=I[1].trim().split(",").map((w)=>w.trim()),j=I[2].trim(),P=A[0]||"x",N=A.slice(1),M=N.map((w)=>`check${w}`);N.forEach((w,V)=>{j=j.replace(new RegExp(`\\b${w}\\s*\\(`,"g"),`${M[V]}(`)}),$+=`const ${Q} = Generic([${_.join(", ")}], (${P}, ${M.join(", ")}) => { ${j} }, '${B}')`}else $+=`const ${Q} = Generic([${_.join(", ")}], () => true, '${B}')`;X=U;continue}$+=Z[X],X++}return $}function m7(Z){let $="",X=0;while(X<Z.length){let K=Z.slice(X).match(/^\bUnion\s+([A-Z][a-zA-Z0-9_]*)\s+(['"`])([^]*?)\2\s*/);if(K){let Q=K[1],H=K[3],Y=X+K[0].length;if(Z[Y]==="{"){let z=Y+1,W=1,G=z;while(G<Z.length&&W>0){let D=Z[G];if(D==="{")W++;else if(D==="}")W--;G++}if(W!==0){$+=Z[X],X++;continue}let J=Z.slice(z,G-1).trim(),U=G,_=o4(J);$+=`const ${Q} = Union('${H}', [${_.join(", ")}])`,X=U;continue}else{let z=Z.indexOf(`
|
|
9
|
-
`,Y);if(z===-1)z=Z.length;let W=Z.slice(Y,z).trim();if(W){let G=o4(W);$+=`const ${Q} = Union('${H}', [${G.join(", ")}])`,X=z;continue}}}$+=Z[X],X++}return $}function o4(Z){let $=[],X=Z.split("|").map((K)=>K.trim());for(let K of X){if(!K)continue;$.push(K)}return $}function l7(Z){let $="",X=0;while(X<Z.length){let K=Z.slice(X).match(/^\bEnum\s+([A-Z][a-zA-Z0-9_]*)\s+(['"`])([^]*?)\2\s*\{/);if(K){let Q=K[1],H=K[3],z=X+K[0].length-1+1,W=1,G=z;while(G<Z.length&&W>0){let I=Z[G];if(I==="{")W++;else if(I==="}")W--;G++}if(W!==0){$+=Z[X],X++;continue}let J=Z.slice(z,G-1).trim(),U=G,D=i7(J).map(([I,B])=>`${I}: ${B}`).join(", ");$+=`const ${Q} = Enum('${H}', { ${D} })`,X=U;continue}$+=Z[X],X++}return $}function i7(Z){let $=[],X=0,K=Z.split(/[\n,]/).map((Q)=>Q.trim()).filter((Q)=>Q&&!Q.startsWith("//"));for(let Q of K){let H=Q.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:=\s*(.+))?$/);if(H){let Y=H[1],z=H[2]?.trim();if(z!==void 0){$.push([Y,z]);let W=Number(z);if(!isNaN(W))X=W+1}else $.push([Y,String(X)]),X++}}return $}function p7(Z){return Z.replace(/(?<=^|[;\n{])\s*([A-Z][a-zA-Z0-9_]*)\s*=(?!=)/gm,($,X)=>{return $.replace(X,`const ${X}`)})}function W1(Z,$={}){let{filename:X="<source>",colonShorthand:K=!0,vmTarget:Q=!1}=$,{source:H,returnType:Y,returnSafety:z,moduleSafety:W,originalSource:G,requiredParams:J,unsafeFunctions:U,safeFunctions:_,wasmBlocks:D,tests:I,testErrors:B}=K?W0(Z,{vmTarget:Q}):{source:Z,returnType:void 0,returnSafety:void 0,moduleSafety:void 0,originalSource:Z,requiredParams:new Set,unsafeFunctions:new Set,safeFunctions:new Set,wasmBlocks:[],tests:[],testErrors:[]};try{return{ast:s4.parse(H,{ecmaVersion:2022,sourceType:"module",locations:!0,allowReturnOutsideFunction:!1}),returnType:Y,returnSafety:z,moduleSafety:W,originalSource:G,requiredParams:J,unsafeFunctions:U,safeFunctions:_,wasmBlocks:D,tests:I,testErrors:B}}catch(A){let j=A.loc||{line:1,column:0};throw new
|
|
9
|
+
`,Y);if(z===-1)z=Z.length;let W=Z.slice(Y,z).trim();if(W){let G=o4(W);$+=`const ${Q} = Union('${H}', [${G.join(", ")}])`,X=z;continue}}}$+=Z[X],X++}return $}function o4(Z){let $=[],X=Z.split("|").map((K)=>K.trim());for(let K of X){if(!K)continue;$.push(K)}return $}function l7(Z){let $="",X=0;while(X<Z.length){let K=Z.slice(X).match(/^\bEnum\s+([A-Z][a-zA-Z0-9_]*)\s+(['"`])([^]*?)\2\s*\{/);if(K){let Q=K[1],H=K[3],z=X+K[0].length-1+1,W=1,G=z;while(G<Z.length&&W>0){let I=Z[G];if(I==="{")W++;else if(I==="}")W--;G++}if(W!==0){$+=Z[X],X++;continue}let J=Z.slice(z,G-1).trim(),U=G,D=i7(J).map(([I,B])=>`${I}: ${B}`).join(", ");$+=`const ${Q} = Enum('${H}', { ${D} })`,X=U;continue}$+=Z[X],X++}return $}function i7(Z){let $=[],X=0,K=Z.split(/[\n,]/).map((Q)=>Q.trim()).filter((Q)=>Q&&!Q.startsWith("//"));for(let Q of K){let H=Q.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:=\s*(.+))?$/);if(H){let Y=H[1],z=H[2]?.trim();if(z!==void 0){$.push([Y,z]);let W=Number(z);if(!isNaN(W))X=W+1}else $.push([Y,String(X)]),X++}}return $}function p7(Z){return Z.replace(/(?<=^|[;\n{])\s*([A-Z][a-zA-Z0-9_]*)\s*=(?!=)/gm,($,X)=>{return $.replace(X,`const ${X}`)})}function W1(Z,$={}){let{filename:X="<source>",colonShorthand:K=!0,vmTarget:Q=!1}=$,{source:H,returnType:Y,returnSafety:z,moduleSafety:W,originalSource:G,requiredParams:J,unsafeFunctions:U,safeFunctions:_,wasmBlocks:D,tests:I,testErrors:B}=K?W0(Z,{vmTarget:Q}):{source:Z,returnType:void 0,returnSafety:void 0,moduleSafety:void 0,originalSource:Z,requiredParams:new Set,unsafeFunctions:new Set,safeFunctions:new Set,wasmBlocks:[],tests:[],testErrors:[]};try{return{ast:s4.parse(H,{ecmaVersion:2022,sourceType:"module",locations:!0,allowReturnOutsideFunction:!1}),returnType:Y,returnSafety:z,moduleSafety:W,originalSource:G,requiredParams:J,unsafeFunctions:U,safeFunctions:_,wasmBlocks:D,tests:I,testErrors:B}}catch(A){let j=A.loc||{line:1,column:0};throw new D1(A.message.replace(/\s*\(\d+:\d+\)$/,""),j,G,X)}}function _0(Z,$){for(let K of Z.body){if(K.type==="ImportDeclaration")throw new D1("Imports are not supported. All atoms must be registered with the VM.",K.loc?.start||{line:1,column:0},void 0,$);if(K.type==="ExportNamedDeclaration"||K.type==="ExportDefaultDeclaration")throw new D1("Exports are not supported. The function is automatically exported.",K.loc?.start||{line:1,column:0},void 0,$);if(K.type==="ClassDeclaration")throw new D1("Classes are not supported. Agent99 uses functional composition.",K.loc?.start||{line:1,column:0},void 0,$)}let X=Z.body.filter((K)=>K.type==="FunctionDeclaration");if(X.length===0)throw new D1("Source must contain a function declaration",{line:1,column:0},void 0,$);if(X.length>1){let K=X[1];throw new D1("Only a single function per agent is allowed",K.loc?.start||{line:1,column:0},void 0,$)}return X[0]}function u1(Z,$){let X={params:{}};if(!$.loc)return X;let K=Z.substring(0,$.start),Q=[...K.matchAll(/\/\*#([\s\S]*?)\*\//g)];if(Q.length>0){let J=Q[Q.length-1],U=K.substring(J.index+J[0].length);if(/^(?:\s|\/\/[^\n]*)*$/.test(U)){let _=J[1],D=_.split(`
|
|
10
10
|
`),I=D.filter((B)=>B.trim().length>0).reduce((B,A)=>{let j=A.match(/^(\s*)/)?.[1].length||0;return Math.min(B,j)},1/0);if(I>0&&I<1/0)_=D.map((B)=>B.slice(I)).join(`
|
|
11
11
|
`);return X.description=_.trim(),X}}let H=K.match(/\/\*\*[\s\S]*?\*\/\s*$/);if(!H)return X;let Y=H[0],z=Y.match(/\/\*\*\s*\n?\s*\*?\s*([^@\n][^\n]*)/m);if(z)X.description=z[1].trim();let W=/@param\s+(?:\{[^}]+\}\s+)?(\w+)\s*-?\s*(.*)/g,G;while((G=W.exec(Y))!==null)X.params[G[1]]=G[2].trim();return X}function n7(Z,$=!1){let X=[],K=[],Q="",H=0;while(H<Z.length){let Y=Z.slice(H).match(/^\btest\s+/);if(Y){let z=H,W=H+Y[0].length,G,J=Z.slice(W).match(/^(['"`])([^]*?)\1\s*/);if(J)G=J[2],W+=J[0].length;if(Z[W]==="{"){let U=W+1,_=1,D=U;while(D<Z.length&&_>0){let I=Z[D];if(I==="{")_++;else if(I==="}")_--;D++}if(_===0){let I=Z.slice(U,D-1).trim(),B=D;if(X.push({description:G,body:I,start:z,end:B}),!$)try{Function(I)()}catch(P){let N=G||`test at position ${z}`;K.push(`Test failed: ${N}
|
|
12
12
|
${P.message||P}`)}let j=(Z.slice(z,B).match(/\n/g)||[]).length;Q+=`
|
|
13
|
-
`.repeat(j),H=B;continue}}}Q+=Z[H],H++}return{source:Q,tests:X,errors:K}}function c7(Z){let $=/\bclass\s+(\w+)(\s+extends\s+\w+)?\s*\{/g,X="",K=0,Q;while((Q=$.exec(Z))!==null){let H=Q[1],Y=Q[2]||"",z=Q.index,W=z+Q[0].length-1,G=1,J=W+1;while(J<Z.length&&G>0){let U=Z[J];if(U==="{")G++;else if(U==="}")G--;J++}if(G===0){let U=J,_=Z.slice(W,U);X+=Z.slice(K,z),X+=`let ${H} = class ${H}${Y} ${_}; `,X+=`${H} = new Proxy(${H}, { apply(t, _, a) { return Reflect.construct(t, a) } });`,K=U}}return X+=Z.slice(K),X}function o7(Z){let $=[{pattern:/\bnew\s+Date\b/,message:"new Date() is not allowed in TjsDate mode. Use Timestamp.now() or Timestamp.from()"},{pattern:/\bDate\.now\b/,message:"Date.now() is not allowed in TjsDate mode. Use Timestamp.now()"},{pattern:/\bDate\.parse\b/,message:"Date.parse() is not allowed in TjsDate mode. Use Timestamp.parse()"},{pattern:/\bDate\.UTC\b/,message:"Date.UTC() is not allowed in TjsDate mode. Use Timestamp.from()"}];for(let{pattern:X,message:K}of $)if(X.test(Z))throw Error(K);return Z}function s7(Z){if(/(?<![A-Za-z_$])\beval\s*\(/.test(Z))throw Error("eval() is not allowed in TjsNoeval mode. Use Eval() from TJS runtime for safe evaluation.");if(/\bnew\s+Function\s*\(/.test(Z))throw Error("new Function() is not allowed in TjsNoeval mode. Use SafeFunction() from TJS runtime.");return Z}import{parseExpressionAt as a7}from"acorn";function X1(Z){switch(Z.type){case"Literal":{let $=Z.value;if($===null)return{kind:"null"};if(typeof $==="string")return{kind:"string"};if(typeof $==="number")return{kind:"number"};if(typeof $==="boolean")return{kind:"boolean"};return{kind:"any"}}case"ArrayExpression":{let $=Z.elements;if($.length===0)return{kind:"array",items:{kind:"any"}};return{kind:"array",items:X1($[0])}}case"ObjectExpression":{let $=Z.properties,X={};for(let K of $)if(K.type==="Property"&&K.key.type==="Identifier"){let Q=K.key.name;X[Q]=X1(K.value)}return{kind:"object",shape:X}}case"LogicalExpression":{let{operator:$,left:X,right:K}=Z;if($==="||"){let Q=X1(X),H=X1(K);if(H.kind==="null")return{...Q,nullable:!0};if(Q.kind==="null")return{...H,nullable:!0};return{kind:"union",members:[Q,H]}}if($==="&&")return X1(K);if($==="??")return X1(K);return{kind:"any"}}case"Identifier":{if(Z.name==="undefined")return{kind:"undefined"};return{kind:"any"}}case"UnaryExpression":{if(Z.operator==="-"&&Z.argument.type==="Literal"){if(typeof Z.argument.value==="number")return{kind:"number"}}return{kind:"any"}}default:return{kind:"any"}}}function I1(Z,$){if(Z.type==="Identifier")return{name:Z.name,type:{kind:"any"},required:!0};if(Z.type==="AssignmentPattern"){let{left:X,right:K}=Z;if(X.type!=="Identifier")throw new y("Only simple parameter names are supported",h(Z));let Q=X.name,H=$?.has(Q)??!1,Y=X1(K),z=D1(K);return{name:Q,type:Y,required:H,default:H?null:z,example:z,loc:{start:Z.start,end:Z.end}}}if(Z.type==="ObjectPattern"){let X=Z.properties,K={},Q={};for(let H of X)if(H.type==="Property"){let Y=H.key.type==="Identifier"?H.key.name:String(H.key.value);if(H.value.type==="Identifier")K[Y]={kind:"any"},Q[Y]={name:Y,type:{kind:"any"},required:!0};else if(H.value.type==="AssignmentPattern"){let z=I1(H.value,$),W=$?.has(Y)??!1;K[Y]=z.type,Q[Y]={name:Y,type:z.type,required:W,default:W?null:z.example,example:z.example}}}return{name:"__destructured__",type:{kind:"object",shape:K,destructuredParams:Q},required:!0}}throw new y(`Unsupported parameter pattern: ${Z.type}`,h(Z))}function D1(Z){switch(Z.type){case"Literal":return Z.value;case"ArrayExpression":return Z.elements.map(($)=>$?D1($):null);case"ObjectExpression":{let $={};for(let X of Z.properties)if(X.type==="Property"&&X.key.type==="Identifier")$[X.key.name]=D1(X.value);return $}case"UnaryExpression":if(Z.operator==="-"){let $=D1(Z.argument);return typeof $==="number"?-$:void 0}return;case"LogicalExpression":{let{operator:$,left:X,right:K}=Z;if($==="&&"){if(X.type==="Literal"&&X.value===null)return null}if($==="||")return D1(X)??D1(K);if($==="??")return D1(X)??D1(K);return}default:return}}function a4(Z){try{let $=a7(Z,0,{ecmaVersion:2022});return X1($)}catch{return{kind:"any"}}}function Z4(Z){switch(Z.kind){case"string":return Z.nullable?"string | null":"string";case"number":return Z.nullable?"number | null":"number";case"boolean":return Z.nullable?"boolean | null":"boolean";case"null":return"null";case"any":return"any";case"array":{let $=Z.items?Z4(Z.items):"any";return Z.nullable?`${$}[] | null`:`${$}[]`}case"object":{if(!Z.shape||Object.keys(Z.shape).length===0)return Z.nullable?"object | null":"object";let $=Object.entries(Z.shape).map(([X,K])=>`${X}: ${Z4(K)}`).join(", ");return Z.nullable?`{ ${$} } | null`:`{ ${$} }`}case"union":return Z.members?.map(Z4).join(" | ")||"any";default:return"any"}}function L0(Z){switch(Z.kind){case"string":return{type:"string"};case"number":return{type:"number"};case"boolean":return{type:"boolean"};case"null":return{};case"undefined":return{};case"any":return{};case"array":return{type:"array",items:Z.items?L0(Z.items):{}};case"object":if(Z.shape){let $={};for(let[X,K]of Object.entries(Z.shape))$[X]=L0(K);return{type:"object",properties:$,additionalProperties:!1}}return{type:"object"};case"union":if(Z.members)return{oneOf:Z.members.map(L0)};return{};default:return{}}}function r7(Z){let $={},X=[];for(let[K,Q]of Object.entries(Z))if($[K]=L0(Q.type),Q.required)X.push(K);return{type:"object",properties:$,required:X.length>0?X:void 0,additionalProperties:!1}}function l1(Z,$,X,K={},Q){let H=u1($,Z),Y=new Map;for(let A of Z.params){let j=I1(A,Q);if(j.name==="__destructured__"&&j.type.kind==="object"&&j.type.destructuredParams)for(let[P,N]of Object.entries(j.type.destructuredParams))Y.set(P,{...N,description:H.params[P]});else j.description=H.params[j.name],Y.set(j.name,j)}let z;if(X)z=a4(X);let W={depth:0,locals:new Map,parameters:Y,atoms:new Set(Object.keys(K.atoms||{})),warnings:[],source:$,filename:K.filename||"<source>",options:K},G=Y1(Z.body,W),J=[],U=[],_=[];for(let[A,j]of Y.entries())if(j.required)U.push(A);else if(j.default!==void 0)_.push({name:A,defaultValue:j.default});else U.push(A);if(U.length>0)J.push({op:"varsImport",keys:U});for(let{name:A,defaultValue:j}of _)J.push({op:"varsImport",keys:[A]}),J.push({op:"if",condition:{$expr:"binary",op:"==",left:{$expr:"ident",name:A},right:{$expr:"literal",value:null}},then:[{op:"varSet",key:A,value:j}]});J.push(...G);let D=Object.fromEntries(Y),I={name:Z.id?.name||"anonymous",description:H.description,parameters:D,returns:z},B=r7(D);return{ast:{op:"seq",steps:J,inputSchema:B},signature:I,warnings:W.warnings}}function Y1(Z,$){let X=[];for(let K of Z.body){let Q=d1(K,$);if(Q)if(Array.isArray(Q))X.push(...Q);else X.push(Q)}return X}function d1(Z,$){switch(Z.type){case"VariableDeclaration":return t7(Z,$);case"ExpressionStatement":return e7(Z,$);case"IfStatement":return X8(Z,$);case"WhileStatement":return $8(Z,$);case"ForOfStatement":return K8(Z,$);case"TryStatement":return Q8(Z,$);case"ReturnStatement":return H8(Z,$);case"ThrowStatement":throw new y("'throw' is not supported in AsyncJS. Use Error('message') to trigger error flow",h(Z),$.source,$.filename);case"BlockStatement":return{op:"scope",steps:Y1(Z,Z1($))};case"EmptyStatement":return null;default:throw new y(`Unsupported statement type: ${Z.type}`,h(Z),$.source,$.filename)}}function t7(Z,$){let X=[],K=Z.kind==="const",Q=K?"constSet":"varSet";for(let H of Z.declarations){if(H.id.type!=="Identifier")throw new y("Only simple variable names are supported",h(H),$.source,$.filename);let Y=H.id.name;if(H.init){let{step:z,resultVar:W}=F1(H.init,$,Y,K);if(z)X.push(z);else if(W!==Y)X.push({op:Q,key:Y,value:W});let G=X1(H.init);$.locals.set(Y,G)}else{if(K)throw new y("const declarations must be initialized",h(H),$.source,$.filename);X.push({op:"varSet",key:Y,value:null}),$.locals.set(Y,{kind:"any",nullable:!0})}}return X}function e7(Z,$){let X=Z.expression;if(X.type==="AssignmentExpression")return Z8(X,$);if(X.type==="CallExpression"){let{step:K,resultVar:Q}=F1(X,$);if(K)return K;if(Q)return{op:"varSet",key:"_",value:Q};return null}return $.warnings.push({message:"Expression statement has no effect",line:h(Z).line,column:h(Z).column}),null}function Z8(Z,$){if(Z.left.type!=="Identifier")throw new y("Only simple variable assignment is supported",h(Z),$.source,$.filename);let X=Z.left.name,{step:K,resultVar:Q}=F1(Z.right,$,X);if(K)return K;return{op:"varSet",key:X,value:Q}}function X8(Z,$){let X=v(Z.test,$),K=Z.consequent.type==="BlockStatement"?Y1(Z.consequent,Z1($)):[d1(Z.consequent,$)].filter(Boolean),Q;if(Z.alternate)Q=Z.alternate.type==="BlockStatement"?Y1(Z.alternate,Z1($)):[d1(Z.alternate,$)].filter(Boolean);return{op:"if",condition:X,then:K,...Q&&{else:Q}}}function $8(Z,$){let X=v(Z.test,$),K=Z.body.type==="BlockStatement"?Y1(Z.body,Z1($)):[d1(Z.body,$)].filter(Boolean);return{op:"while",condition:X,body:K}}function K8(Z,$){let X;if(Z.left.type==="VariableDeclaration"){let Y=Z.left.declarations[0];if(Y.id.type!=="Identifier")throw new y("Only simple variable names are supported in for...of",h(Z.left),$.source,$.filename);X=Y.id.name}else if(Z.left.type==="Identifier")X=Z.left.name;else throw new y("Unsupported for...of left-hand side",h(Z.left),$.source,$.filename);let K=n(Z.right,$),Q=Z1($);Q.locals.set(X,{kind:"any"});let H=Z.body.type==="BlockStatement"?Y1(Z.body,Q):[d1(Z.body,Q)].filter(Boolean);return{op:"map",items:K,as:X,steps:H}}function Q8(Z,$){let X=Y1(Z.block,Z1($)),K,Q;if(Z.handler){let H=Z1($);if(Z.handler.param?.type==="Identifier")Q=Z.handler.param.name,H.locals.set(Q,{kind:"any"});K=Y1(Z.handler.body,H)}return{op:"try",try:X,...K&&{catch:K},...Q&&{catchParam:Q}}}function H8(Z,$){if(!Z.argument)return{op:"return",value:{}};let{step:X,resultVar:K}=F1(Z.argument,$,"__returnVal__");if(X)return[X,{op:"return",value:K}];return{op:"return",value:n(Z.argument,$)}}var t4=new Set(["Math","JSON","Array","Object","String","Number","console","Date","Schema"]),Y8=new Set(["parseInt","parseFloat","isNaN","isFinite","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent","Set","Date","filter"]),m1=new Set(["RegExp","Promise","Map","WeakSet","WeakMap","Symbol","Proxy","Reflect","Function","eval","setTimeout","setInterval","fetch","require","import","process","window","document","global","globalThis"]),z8=new Set(["toUpperCase","toLowerCase","trim","trimStart","trimEnd","charAt","charCodeAt","codePointAt","concat","includes","indexOf","lastIndexOf","startsWith","endsWith","slice","substring","substr","replace","replaceAll","match","search","padStart","padEnd","repeat","normalize","localeCompare","toString","valueOf","at","reverse","sort","fill","copyWithin","flat","flatMap","every","some","forEach","add","remove","has","clear","toArray","union","intersection","diff","format","isBefore","isAfter"]);function G8(Z){if(Z.callee.type==="Identifier"){let $=Z.callee.name;return Y8.has($)||m1.has($)}if(Z.callee.type==="MemberExpression"){let $=Z.callee;if($.object.type==="Identifier"){let X=$.object.name;if(t4.has(X)||m1.has(X))return!0}if($.property.type==="Identifier"){let X=$.property.name;if(z8.has(X))return!0}}return!1}function W8(Z){if(Z.object.type==="Identifier"){let $=Z.object.name;return t4.has($)||m1.has($)}return!1}var r4={RegExp:"RegExp is not available. Use string methods or the regexMatch atom.",Promise:"Promise is not needed. All operations are implicitly async.",Map:"Map is not available. Use plain objects instead.",WeakSet:"WeakSet is not available.",WeakMap:"WeakMap is not available.",Symbol:"Symbol is not available.",Proxy:"Proxy is not available.",Reflect:"Reflect is not available.",Function:"Function constructor is not available. Define functions normally.",eval:"eval is not available. Code is compiled, not evaluated.",setTimeout:"setTimeout is not available. Use the delay atom.",setInterval:"setInterval is not available. Use while loops with delay.",fetch:"fetch is not available. Use the httpFetch atom.",require:"require is not available. Atoms must be registered with the VM.",import:"import is not available. Atoms must be registered with the VM.",process:"process is not available. AsyncJS runs in a sandboxed environment.",window:"window is not available. AsyncJS runs in a sandboxed environment.",document:"document is not available. AsyncJS runs in a sandboxed environment.",global:"global is not available. AsyncJS runs in a sandboxed environment.",globalThis:"globalThis is not available. Use builtins directly."};function J8(Z){if(Z.callee.type==="Identifier"){let $=Z.callee.name;if(m1.has($))return r4[$]||`${$} is not available in AsyncJS.`}if(Z.callee.type==="MemberExpression"){let $=Z.callee;if($.object.type==="Identifier"){let X=$.object.name;if(m1.has(X))return r4[X]||`${X} is not available in AsyncJS.`}}return null}function e4(Z){return{Date:" Use Date() or Date('2024-01-15') instead - no 'new' needed.",Set:" Use Set([items]) instead - no 'new' needed.",Map:" Use plain objects instead of Map.",Array:" Use array literals like [1, 2, 3] instead.",Object:" Use object literals like { key: value } instead.",Error:" Return an error object like { error: 'message' } instead.",RegExp:" Use string methods or the regexMatch atom.",Promise:" Not needed - all operations are implicitly async.",WeakSet:" WeakSet is not available.",WeakMap:" WeakMap is not available."}[Z]||" Use factory functions or object literals instead."}function F1(Z,$,X,K){let Q=K?"constSet":"varSet";if(Z.type==="ChainExpression")return F1(Z.expression,$,X,K);if(Z.type==="NewExpression"){let Y=Z,z="constructor";if(Y.callee.type==="Identifier")z=Y.callee.name;let W=e4(z);throw new y(`The 'new' keyword is not supported in AsyncJS.${W}`,h(Z),$.source,$.filename)}if(Z.type==="CallExpression"){let Y=J8(Z);if(Y)throw new y(Y,h(Z),$.source,$.filename)}if(Z.type==="CallExpression"&&G8(Z)){let Y=v(Z,$);if(X)return{step:{op:Q,key:X,value:Y},resultVar:X};return{step:null,resultVar:Y}}if(Z.type==="MemberExpression"&&W8(Z)){let Y=v(Z,$);if(X)return{step:{op:Q,key:X,value:Y},resultVar:X};return{step:null,resultVar:Y}}if(Z.type==="CallExpression")return _8(Z,$,X,K);if(Z.type==="TemplateLiteral")return q8(Z,$,X,K);if(Z.type==="BinaryExpression"||Z.type==="LogicalExpression"||Z.type==="UnaryExpression"){let Y=v(Z,$);if(X)return{step:{op:Q,key:X,value:Y},resultVar:X};return{step:null,resultVar:Y}}return{step:null,resultVar:n(Z,$)}}function _8(Z,$,X,K){let Q,H=!1,Y;if(Z.callee.type==="Identifier")Q=Z.callee.name;else if(Z.callee.type==="MemberExpression"){let W=Z.callee;if(W.property.type==="Identifier")Q=W.property.name,H=!0,Y=n(W.object,$);else throw new y("Computed method names are not supported",h(Z),$.source,$.filename)}else throw new y("Only named function calls are supported",h(Z),$.source,$.filename);if(H)return L8(Q,Y,Z.arguments,$,X,K);if(Q==="console"&&Z.callee.type==="MemberExpression");let z=U8(Z,$);return{step:{op:Q,...z,...X&&{result:X},...X&&K&&{resultConst:!0}},resultVar:X}}function L8(Z,$,X,K,Q,H){switch(Z){case"map":if(X.length>0&&(X[0].type==="ArrowFunctionExpression"||X[0].type==="FunctionExpression")){let Y=X[0],z=Y.params[0],W=z?.type==="Identifier"?z.name:"item",G=Z1(K);G.locals.set(W,{kind:"any"});let J;if(Y.body.type==="BlockStatement")J=Y1(Y.body,G);else{let{step:U,resultVar:_}=F1(Y.body,G,"result");J=U?[U]:[{op:"varSet",key:"result",value:_}]}return{step:{op:"map",items:$,as:W,steps:J,...Q&&{result:Q},...Q&&H&&{resultConst:!0}},resultVar:Q}}break;case"filter":if(X.length>0&&(X[0].type==="ArrowFunctionExpression"||X[0].type==="FunctionExpression")){let Y=X[0],z=Y.params[0],W=z?.type==="Identifier"?z.name:"item",G=Z1(K);G.locals.set(W,{kind:"any"});let J;if(Y.body.type==="BlockStatement")throw new y("filter callback must be an expression, not a block",h(X[0]),K.source,K.filename);else J=v(Y.body,G);return{step:{op:"filter",items:$,as:W,condition:J,...Q&&{result:Q},...Q&&H&&{resultConst:!0}},resultVar:Q}}break;case"find":if(X.length>0&&(X[0].type==="ArrowFunctionExpression"||X[0].type==="FunctionExpression")){let Y=X[0],z=Y.params[0],W=z?.type==="Identifier"?z.name:"item",G=Z1(K);G.locals.set(W,{kind:"any"});let J;if(Y.body.type==="BlockStatement")throw new y("find callback must be an expression, not a block",h(X[0]),K.source,K.filename);else J=v(Y.body,G);return{step:{op:"find",items:$,as:W,condition:J,...Q&&{result:Q},...Q&&H&&{resultConst:!0}},resultVar:Q}}break;case"reduce":if(X.length>=2&&(X[0].type==="ArrowFunctionExpression"||X[0].type==="FunctionExpression")){let Y=X[0],z=Y.params[0],W=Y.params[1],G=z?.type==="Identifier"?z.name:"acc",J=W?.type==="Identifier"?W.name:"item",U=Z1(K);U.locals.set(G,{kind:"any"}),U.locals.set(J,{kind:"any"});let _;if(Y.body.type==="BlockStatement")_=Y1(Y.body,U);else{let{step:I,resultVar:B}=F1(Y.body,U,"result");_=I?[I]:[{op:"varSet",key:"result",value:B}]}let D=n(X[1],K);return{step:{op:"reduce",items:$,as:J,accumulator:G,initial:D,steps:_,...Q&&{result:Q},...Q&&H&&{resultConst:!0}},resultVar:Q}}break;case"slice":break;case"push":return{step:{op:"push",list:$,item:n(X[0],K),...Q&&{result:Q},...Q&&H&&{resultConst:!0}},resultVar:Q};case"join":return{step:{op:"join",list:$,sep:X.length>0?n(X[0],K):"",...Q&&{result:Q},...Q&&H&&{resultConst:!0}},resultVar:Q};case"split":return{step:{op:"split",str:$,sep:X.length>0?n(X[0],K):"",...Q&&{result:Q},...Q&&H&&{resultConst:!0}},resultVar:Q}}return K.warnings.push({message:`Unknown method '${Z}' - treating as atom call`,line:0,column:0}),{step:{op:Z,receiver:$,args:X.map((Y)=>n(Y,K)),...Q&&{result:Q},...Q&&H&&{resultConst:!0}},resultVar:Q}}function q8(Z,$,X,K){let Q="",H={};for(let Y=0;Y<Z.quasis.length;Y++)if(Q+=Z.quasis[Y].value.cooked||Z.quasis[Y].value.raw,Y<Z.expressions.length){let z=Z.expressions[Y],W=`_${Y}`;H[W]=n(z,$),Q+=`{{${W}}}`}return{step:{op:"template",tmpl:Q,vars:H,...X&&{result:X},...X&&K&&{resultConst:!0}},resultVar:X}}function v(Z,$){switch(Z.type){case"Literal":return{$expr:"literal",value:Z.value};case"Identifier":return{$expr:"ident",name:Z.name};case"MemberExpression":{let X=Z,K=v(X.object,$),Q=X.optional===!0;if(X.computed){let Y=X.property;if(Y.type==="Literal")return{$expr:"member",object:K,property:String(Y.value),computed:!0,...Q&&{optional:!0}};throw new y("Computed member access with variables not yet supported",h(Z),$.source,$.filename)}let H=X.property.name;return{$expr:"member",object:K,property:H,...Q&&{optional:!0}}}case"ChainExpression":return v(Z.expression,$);case"BinaryExpression":{let X=Z;return{$expr:"binary",op:X.operator,left:v(X.left,$),right:v(X.right,$)}}case"LogicalExpression":{let X=Z;return{$expr:"logical",op:X.operator,left:v(X.left,$),right:v(X.right,$)}}case"UnaryExpression":{let X=Z;return{$expr:"unary",op:X.operator,argument:v(X.argument,$)}}case"ConditionalExpression":{let X=Z;return{$expr:"conditional",test:v(X.test,$),consequent:v(X.consequent,$),alternate:v(X.alternate,$)}}case"ArrayExpression":return{$expr:"array",elements:Z.elements.filter((K)=>K!==null).map((K)=>v(K,$))};case"ObjectExpression":{let X=Z,K=[];for(let Q of X.properties)if(Q.type==="Property"){let H=Q.key.type==="Identifier"?Q.key.name:String(Q.key.value);K.push({key:H,value:v(Q.value,$)})}return{$expr:"object",properties:K}}case"CallExpression":{let X=Z;if(X.callee.type==="MemberExpression"){let K=X.callee,Q=K.property.type==="Identifier"?K.property.name:String(K.property.value),H=K.optional===!0||X.optional===!0;return{$expr:"methodCall",object:v(K.object,$),method:Q,arguments:X.arguments.map((Y)=>v(Y,$)),...H&&{optional:!0}}}if(X.callee.type==="Identifier")return{$expr:"call",callee:X.callee.name,arguments:X.arguments.map((Q)=>v(Q,$))};throw new y("Complex function calls in expressions should be lifted to statements",h(Z),$.source,$.filename)}case"NewExpression":{let X=Z,K="constructor";if(X.callee.type==="Identifier")K=X.callee.name;let Q=e4(K);throw new y(`The 'new' keyword is not supported in AsyncJS.${Q}`,h(Z),$.source,$.filename)}case"TemplateLiteral":throw new y("Template literals inside expressions are not supported. Assign to a variable first: const msg = `hello ${name}`; then use msg",h(Z),$.source,$.filename);default:throw new y(`Unsupported expression type in condition: ${Z.type}`,h(Z),$.source,$.filename)}}function n(Z,$){switch(Z.type){case"Literal":return Z.value;case"Identifier":return Z.name;case"MemberExpression":{let X=Z;if(X.optional===!0)return v(Z,$);let Q=n(X.object,$);if(Q&&typeof Q==="object"&&Q.$expr){let Y=X.computed?String(X.property.value):X.property.name;return{$expr:"member",object:Q,property:Y,...X.computed&&{computed:!0}}}if(X.computed)return`${Q}[${n(X.property,$)}]`;let H=X.property.name;if(typeof Q==="string")return`${Q}.${H}`;if(Q&&Q.$kind==="arg")return{$kind:"arg",path:`${Q.path}.${H}`};return`${Q}.${H}`}case"ChainExpression":return n(Z.expression,$);case"ArrayExpression":return Z.elements.map((X)=>X?n(X,$):null);case"ObjectExpression":{let X={};for(let K of Z.properties)if(K.type==="Property"){let Q=K.key.type==="Identifier"?K.key.name:String(K.key.value);X[Q]=n(K.value,$)}return X}case"TemplateLiteral":return v(Z,$);case"CallExpression":return v(Z,$);case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"ConditionalExpression":return v(Z,$);default:return null}}function U8(Z,$){if(Z.arguments.length===1&&Z.arguments[0].type==="ObjectExpression"){let X=Z.arguments[0],K={};for(let Q of X.properties)if(Q.type==="Property"){let H=Q.key.type==="Identifier"?Q.key.name:String(Q.key.value);K[H]=n(Q.value,$)}return K}return{args:Z.arguments.map((X)=>n(X,$))}}import{parseExpressionAt as y8}from"acorn";function D8(Z,$){let X=$;while(X>0&&Z[X-1]!==`
|
|
13
|
+
`.repeat(j),H=B;continue}}}Q+=Z[H],H++}return{source:Q,tests:X,errors:K}}function c7(Z){let $=/\bclass\s+(\w+)(\s+extends\s+\w+)?\s*\{/g,X="",K=0,Q;while((Q=$.exec(Z))!==null){let H=Q[1],Y=Q[2]||"",z=Q.index,W=z+Q[0].length-1,G=1,J=W+1;while(J<Z.length&&G>0){let U=Z[J];if(U==="{")G++;else if(U==="}")G--;J++}if(G===0){let U=J,_=Z.slice(W,U);X+=Z.slice(K,z),X+=`let ${H} = class ${H}${Y} ${_}; `,X+=`${H} = new Proxy(${H}, { apply(t, _, a) { return Reflect.construct(t, a) } });`,K=U}}return X+=Z.slice(K),X}function o7(Z){let $=[{pattern:/\bnew\s+Date\b/,message:"new Date() is not allowed in TjsDate mode. Use Timestamp.now() or Timestamp.from()"},{pattern:/\bDate\.now\b/,message:"Date.now() is not allowed in TjsDate mode. Use Timestamp.now()"},{pattern:/\bDate\.parse\b/,message:"Date.parse() is not allowed in TjsDate mode. Use Timestamp.parse()"},{pattern:/\bDate\.UTC\b/,message:"Date.UTC() is not allowed in TjsDate mode. Use Timestamp.from()"}];for(let{pattern:X,message:K}of $)if(X.test(Z))throw Error(K);return Z}function s7(Z){if(/(?<![A-Za-z_$])\beval\s*\(/.test(Z))throw Error("eval() is not allowed in TjsNoeval mode. Use Eval() from TJS runtime for safe evaluation.");if(/\bnew\s+Function\s*\(/.test(Z))throw Error("new Function() is not allowed in TjsNoeval mode. Use SafeFunction() from TJS runtime.");return Z}import{parseExpressionAt as a7}from"acorn";function X1(Z){switch(Z.type){case"Literal":{let $=Z.value;if($===null)return{kind:"null"};if(typeof $==="string")return{kind:"string"};if(typeof $==="number"){let X=Z.raw;if(X&&X.includes("."))return{kind:"number"};return{kind:"integer"}}if(typeof $==="boolean")return{kind:"boolean"};return{kind:"any"}}case"ArrayExpression":{let $=Z.elements;if($.length===0)return{kind:"array",items:{kind:"any"}};return{kind:"array",items:X1($[0])}}case"ObjectExpression":{let $=Z.properties,X={};for(let K of $)if(K.type==="Property"&&K.key.type==="Identifier"){let Q=K.key.name;X[Q]=X1(K.value)}return{kind:"object",shape:X}}case"LogicalExpression":{let{operator:$,left:X,right:K}=Z;if($==="||"){let Q=X1(X),H=X1(K);if(H.kind==="null")return{...Q,nullable:!0};if(Q.kind==="null")return{...H,nullable:!0};return{kind:"union",members:[Q,H]}}if($==="&&")return X1(K);if($==="??")return X1(K);return{kind:"any"}}case"Identifier":{if(Z.name==="undefined")return{kind:"undefined"};return{kind:"any"}}case"UnaryExpression":{let{operator:$,argument:X}=Z;if($==="+"&&X.type==="Literal"){if(typeof X.value==="number")return{kind:"non-negative-integer"}}if($==="-"&&X.type==="Literal"){if(typeof X.value==="number"){let Q=X.raw;if(Q&&Q.includes("."))return{kind:"number"};return{kind:"integer"}}}return{kind:"any"}}default:return{kind:"any"}}}function I1(Z,$){if(Z.type==="Identifier")return{name:Z.name,type:{kind:"any"},required:!0};if(Z.type==="AssignmentPattern"){let{left:X,right:K}=Z;if(X.type!=="Identifier")throw new y("Only simple parameter names are supported",h(Z));let Q=X.name,H=$?.has(Q)??!1,Y=X1(K),z=J1(K);return{name:Q,type:Y,required:H,default:H?null:z,example:z,loc:{start:Z.start,end:Z.end}}}if(Z.type==="ObjectPattern"){let X=Z.properties,K={},Q={};for(let H of X)if(H.type==="Property"){let Y=H.key.type==="Identifier"?H.key.name:String(H.key.value);if(H.value.type==="Identifier")K[Y]={kind:"any"},Q[Y]={name:Y,type:{kind:"any"},required:!0};else if(H.value.type==="AssignmentPattern"){let z=I1(H.value,$),W=$?.has(Y)??!1;K[Y]=z.type,Q[Y]={name:Y,type:z.type,required:W,default:W?null:z.example,example:z.example}}}return{name:"__destructured__",type:{kind:"object",shape:K,destructuredParams:Q},required:!0}}throw new y(`Unsupported parameter pattern: ${Z.type}`,h(Z))}function J1(Z){switch(Z.type){case"Literal":return Z.value;case"ArrayExpression":return Z.elements.map(($)=>$?J1($):null);case"ObjectExpression":{let $={};for(let X of Z.properties)if(X.type==="Property"&&X.key.type==="Identifier")$[X.key.name]=J1(X.value);return $}case"UnaryExpression":if(Z.operator==="-"){let $=J1(Z.argument);return typeof $==="number"?-$:void 0}if(Z.operator==="+"){let $=J1(Z.argument);return typeof $==="number"?+$:void 0}return;case"LogicalExpression":{let{operator:$,left:X,right:K}=Z;if($==="&&"){if(X.type==="Literal"&&X.value===null)return null}if($==="||")return J1(X)??J1(K);if($==="??")return J1(X)??J1(K);return}default:return}}function a4(Z){try{let $=a7(Z,0,{ecmaVersion:2022});return X1($)}catch{return{kind:"any"}}}function Z4(Z){switch(Z.kind){case"string":return Z.nullable?"string | null":"string";case"number":return Z.nullable?"number | null":"number";case"integer":return Z.nullable?"integer | null":"integer";case"non-negative-integer":return Z.nullable?"non-negative integer | null":"non-negative integer";case"boolean":return Z.nullable?"boolean | null":"boolean";case"null":return"null";case"any":return"any";case"array":{let $=Z.items?Z4(Z.items):"any";return Z.nullable?`${$}[] | null`:`${$}[]`}case"object":{if(!Z.shape||Object.keys(Z.shape).length===0)return Z.nullable?"object | null":"object";let $=Object.entries(Z.shape).map(([X,K])=>`${X}: ${Z4(K)}`).join(", ");return Z.nullable?`{ ${$} } | null`:`{ ${$} }`}case"union":return Z.members?.map(Z4).join(" | ")||"any";default:return"any"}}function L0(Z){switch(Z.kind){case"string":return{type:"string"};case"number":return{type:"number"};case"boolean":return{type:"boolean"};case"null":return{};case"undefined":return{};case"any":return{};case"array":return{type:"array",items:Z.items?L0(Z.items):{}};case"object":if(Z.shape){let $={};for(let[X,K]of Object.entries(Z.shape))$[X]=L0(K);return{type:"object",properties:$,additionalProperties:!1}}return{type:"object"};case"union":if(Z.members)return{oneOf:Z.members.map(L0)};return{};default:return{}}}function r7(Z){let $={},X=[];for(let[K,Q]of Object.entries(Z))if($[K]=L0(Q.type),Q.required)X.push(K);return{type:"object",properties:$,required:X.length>0?X:void 0,additionalProperties:!1}}function l1(Z,$,X,K={},Q){let H=u1($,Z),Y=new Map;for(let A of Z.params){let j=I1(A,Q);if(j.name==="__destructured__"&&j.type.kind==="object"&&j.type.destructuredParams)for(let[P,N]of Object.entries(j.type.destructuredParams))Y.set(P,{...N,description:H.params[P]});else j.description=H.params[j.name],Y.set(j.name,j)}let z;if(X)z=a4(X);let W={depth:0,locals:new Map,parameters:Y,atoms:new Set(Object.keys(K.atoms||{})),warnings:[],source:$,filename:K.filename||"<source>",options:K},G=Y1(Z.body,W),J=[],U=[],_=[];for(let[A,j]of Y.entries())if(j.required)U.push(A);else if(j.default!==void 0)_.push({name:A,defaultValue:j.default});else U.push(A);if(U.length>0)J.push({op:"varsImport",keys:U});for(let{name:A,defaultValue:j}of _)J.push({op:"varsImport",keys:[A]}),J.push({op:"if",condition:{$expr:"binary",op:"==",left:{$expr:"ident",name:A},right:{$expr:"literal",value:null}},then:[{op:"varSet",key:A,value:j}]});J.push(...G);let D=Object.fromEntries(Y),I={name:Z.id?.name||"anonymous",description:H.description,parameters:D,returns:z},B=r7(D);return{ast:{op:"seq",steps:J,inputSchema:B},signature:I,warnings:W.warnings}}function Y1(Z,$){let X=[];for(let K of Z.body){let Q=d1(K,$);if(Q)if(Array.isArray(Q))X.push(...Q);else X.push(Q)}return X}function d1(Z,$){switch(Z.type){case"VariableDeclaration":return t7(Z,$);case"ExpressionStatement":return e7(Z,$);case"IfStatement":return X8(Z,$);case"WhileStatement":return $8(Z,$);case"ForOfStatement":return K8(Z,$);case"TryStatement":return Q8(Z,$);case"ReturnStatement":return H8(Z,$);case"ThrowStatement":throw new y("'throw' is not supported in AsyncJS. Use Error('message') to trigger error flow",h(Z),$.source,$.filename);case"BlockStatement":return{op:"scope",steps:Y1(Z,Z1($))};case"EmptyStatement":return null;default:throw new y(`Unsupported statement type: ${Z.type}`,h(Z),$.source,$.filename)}}function t7(Z,$){let X=[],K=Z.kind==="const",Q=K?"constSet":"varSet";for(let H of Z.declarations){if(H.id.type!=="Identifier")throw new y("Only simple variable names are supported",h(H),$.source,$.filename);let Y=H.id.name;if(H.init){let{step:z,resultVar:W}=F1(H.init,$,Y,K);if(z)X.push(z);else if(W!==Y)X.push({op:Q,key:Y,value:W});let G=X1(H.init);$.locals.set(Y,G)}else{if(K)throw new y("const declarations must be initialized",h(H),$.source,$.filename);X.push({op:"varSet",key:Y,value:null}),$.locals.set(Y,{kind:"any",nullable:!0})}}return X}function e7(Z,$){let X=Z.expression;if(X.type==="AssignmentExpression")return Z8(X,$);if(X.type==="CallExpression"){let{step:K,resultVar:Q}=F1(X,$);if(K)return K;if(Q)return{op:"varSet",key:"_",value:Q};return null}return $.warnings.push({message:"Expression statement has no effect",line:h(Z).line,column:h(Z).column}),null}function Z8(Z,$){if(Z.left.type!=="Identifier")throw new y("Only simple variable assignment is supported",h(Z),$.source,$.filename);let X=Z.left.name,{step:K,resultVar:Q}=F1(Z.right,$,X);if(K)return K;return{op:"varSet",key:X,value:Q}}function X8(Z,$){let X=f(Z.test,$),K=Z.consequent.type==="BlockStatement"?Y1(Z.consequent,Z1($)):[d1(Z.consequent,$)].filter(Boolean),Q;if(Z.alternate)Q=Z.alternate.type==="BlockStatement"?Y1(Z.alternate,Z1($)):[d1(Z.alternate,$)].filter(Boolean);return{op:"if",condition:X,then:K,...Q&&{else:Q}}}function $8(Z,$){let X=f(Z.test,$),K=Z.body.type==="BlockStatement"?Y1(Z.body,Z1($)):[d1(Z.body,$)].filter(Boolean);return{op:"while",condition:X,body:K}}function K8(Z,$){let X;if(Z.left.type==="VariableDeclaration"){let Y=Z.left.declarations[0];if(Y.id.type!=="Identifier")throw new y("Only simple variable names are supported in for...of",h(Z.left),$.source,$.filename);X=Y.id.name}else if(Z.left.type==="Identifier")X=Z.left.name;else throw new y("Unsupported for...of left-hand side",h(Z.left),$.source,$.filename);let K=n(Z.right,$),Q=Z1($);Q.locals.set(X,{kind:"any"});let H=Z.body.type==="BlockStatement"?Y1(Z.body,Q):[d1(Z.body,Q)].filter(Boolean);return{op:"map",items:K,as:X,steps:H}}function Q8(Z,$){let X=Y1(Z.block,Z1($)),K,Q;if(Z.handler){let H=Z1($);if(Z.handler.param?.type==="Identifier")Q=Z.handler.param.name,H.locals.set(Q,{kind:"any"});K=Y1(Z.handler.body,H)}return{op:"try",try:X,...K&&{catch:K},...Q&&{catchParam:Q}}}function H8(Z,$){if(!Z.argument)return{op:"return",value:{}};let{step:X,resultVar:K}=F1(Z.argument,$,"__returnVal__");if(X)return[X,{op:"return",value:K}];return{op:"return",value:n(Z.argument,$)}}var t4=new Set(["Math","JSON","Array","Object","String","Number","console","Date","Schema"]),Y8=new Set(["parseInt","parseFloat","isNaN","isFinite","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent","Set","Date","filter"]),m1=new Set(["RegExp","Promise","Map","WeakSet","WeakMap","Symbol","Proxy","Reflect","Function","eval","setTimeout","setInterval","fetch","require","import","process","window","document","global","globalThis"]),z8=new Set(["toUpperCase","toLowerCase","trim","trimStart","trimEnd","charAt","charCodeAt","codePointAt","concat","includes","indexOf","lastIndexOf","startsWith","endsWith","slice","substring","substr","replace","replaceAll","match","search","padStart","padEnd","repeat","normalize","localeCompare","toString","valueOf","at","reverse","sort","fill","copyWithin","flat","flatMap","every","some","forEach","add","remove","has","clear","toArray","union","intersection","diff","format","isBefore","isAfter"]);function G8(Z){if(Z.callee.type==="Identifier"){let $=Z.callee.name;return Y8.has($)||m1.has($)}if(Z.callee.type==="MemberExpression"){let $=Z.callee;if($.object.type==="Identifier"){let X=$.object.name;if(t4.has(X)||m1.has(X))return!0}if($.property.type==="Identifier"){let X=$.property.name;if(z8.has(X))return!0}}return!1}function W8(Z){if(Z.object.type==="Identifier"){let $=Z.object.name;return t4.has($)||m1.has($)}return!1}var r4={RegExp:"RegExp is not available. Use string methods or the regexMatch atom.",Promise:"Promise is not needed. All operations are implicitly async.",Map:"Map is not available. Use plain objects instead.",WeakSet:"WeakSet is not available.",WeakMap:"WeakMap is not available.",Symbol:"Symbol is not available.",Proxy:"Proxy is not available.",Reflect:"Reflect is not available.",Function:"Function constructor is not available. Define functions normally.",eval:"eval is not available. Code is compiled, not evaluated.",setTimeout:"setTimeout is not available. Use the delay atom.",setInterval:"setInterval is not available. Use while loops with delay.",fetch:"fetch is not available. Use the httpFetch atom.",require:"require is not available. Atoms must be registered with the VM.",import:"import is not available. Atoms must be registered with the VM.",process:"process is not available. AsyncJS runs in a sandboxed environment.",window:"window is not available. AsyncJS runs in a sandboxed environment.",document:"document is not available. AsyncJS runs in a sandboxed environment.",global:"global is not available. AsyncJS runs in a sandboxed environment.",globalThis:"globalThis is not available. Use builtins directly."};function J8(Z){if(Z.callee.type==="Identifier"){let $=Z.callee.name;if(m1.has($))return r4[$]||`${$} is not available in AsyncJS.`}if(Z.callee.type==="MemberExpression"){let $=Z.callee;if($.object.type==="Identifier"){let X=$.object.name;if(m1.has(X))return r4[X]||`${X} is not available in AsyncJS.`}}return null}function e4(Z){return{Date:" Use Date() or Date('2024-01-15') instead - no 'new' needed.",Set:" Use Set([items]) instead - no 'new' needed.",Map:" Use plain objects instead of Map.",Array:" Use array literals like [1, 2, 3] instead.",Object:" Use object literals like { key: value } instead.",Error:" Return an error object like { error: 'message' } instead.",RegExp:" Use string methods or the regexMatch atom.",Promise:" Not needed - all operations are implicitly async.",WeakSet:" WeakSet is not available.",WeakMap:" WeakMap is not available."}[Z]||" Use factory functions or object literals instead."}function F1(Z,$,X,K){let Q=K?"constSet":"varSet";if(Z.type==="ChainExpression")return F1(Z.expression,$,X,K);if(Z.type==="NewExpression"){let Y=Z,z="constructor";if(Y.callee.type==="Identifier")z=Y.callee.name;let W=e4(z);throw new y(`The 'new' keyword is not supported in AsyncJS.${W}`,h(Z),$.source,$.filename)}if(Z.type==="CallExpression"){let Y=J8(Z);if(Y)throw new y(Y,h(Z),$.source,$.filename)}if(Z.type==="CallExpression"&&G8(Z)){let Y=f(Z,$);if(X)return{step:{op:Q,key:X,value:Y},resultVar:X};return{step:null,resultVar:Y}}if(Z.type==="MemberExpression"&&W8(Z)){let Y=f(Z,$);if(X)return{step:{op:Q,key:X,value:Y},resultVar:X};return{step:null,resultVar:Y}}if(Z.type==="CallExpression")return _8(Z,$,X,K);if(Z.type==="TemplateLiteral")return q8(Z,$,X,K);if(Z.type==="BinaryExpression"||Z.type==="LogicalExpression"||Z.type==="UnaryExpression"){let Y=f(Z,$);if(X)return{step:{op:Q,key:X,value:Y},resultVar:X};return{step:null,resultVar:Y}}return{step:null,resultVar:n(Z,$)}}function _8(Z,$,X,K){let Q,H=!1,Y;if(Z.callee.type==="Identifier")Q=Z.callee.name;else if(Z.callee.type==="MemberExpression"){let W=Z.callee;if(W.property.type==="Identifier")Q=W.property.name,H=!0,Y=n(W.object,$);else throw new y("Computed method names are not supported",h(Z),$.source,$.filename)}else throw new y("Only named function calls are supported",h(Z),$.source,$.filename);if(H)return L8(Q,Y,Z.arguments,$,X,K);if(Q==="console"&&Z.callee.type==="MemberExpression");let z=U8(Z,$);return{step:{op:Q,...z,...X&&{result:X},...X&&K&&{resultConst:!0}},resultVar:X}}function L8(Z,$,X,K,Q,H){switch(Z){case"map":if(X.length>0&&(X[0].type==="ArrowFunctionExpression"||X[0].type==="FunctionExpression")){let Y=X[0],z=Y.params[0],W=z?.type==="Identifier"?z.name:"item",G=Z1(K);G.locals.set(W,{kind:"any"});let J;if(Y.body.type==="BlockStatement")J=Y1(Y.body,G);else{let{step:U,resultVar:_}=F1(Y.body,G,"result");J=U?[U]:[{op:"varSet",key:"result",value:_}]}return{step:{op:"map",items:$,as:W,steps:J,...Q&&{result:Q},...Q&&H&&{resultConst:!0}},resultVar:Q}}break;case"filter":if(X.length>0&&(X[0].type==="ArrowFunctionExpression"||X[0].type==="FunctionExpression")){let Y=X[0],z=Y.params[0],W=z?.type==="Identifier"?z.name:"item",G=Z1(K);G.locals.set(W,{kind:"any"});let J;if(Y.body.type==="BlockStatement")throw new y("filter callback must be an expression, not a block",h(X[0]),K.source,K.filename);else J=f(Y.body,G);return{step:{op:"filter",items:$,as:W,condition:J,...Q&&{result:Q},...Q&&H&&{resultConst:!0}},resultVar:Q}}break;case"find":if(X.length>0&&(X[0].type==="ArrowFunctionExpression"||X[0].type==="FunctionExpression")){let Y=X[0],z=Y.params[0],W=z?.type==="Identifier"?z.name:"item",G=Z1(K);G.locals.set(W,{kind:"any"});let J;if(Y.body.type==="BlockStatement")throw new y("find callback must be an expression, not a block",h(X[0]),K.source,K.filename);else J=f(Y.body,G);return{step:{op:"find",items:$,as:W,condition:J,...Q&&{result:Q},...Q&&H&&{resultConst:!0}},resultVar:Q}}break;case"reduce":if(X.length>=2&&(X[0].type==="ArrowFunctionExpression"||X[0].type==="FunctionExpression")){let Y=X[0],z=Y.params[0],W=Y.params[1],G=z?.type==="Identifier"?z.name:"acc",J=W?.type==="Identifier"?W.name:"item",U=Z1(K);U.locals.set(G,{kind:"any"}),U.locals.set(J,{kind:"any"});let _;if(Y.body.type==="BlockStatement")_=Y1(Y.body,U);else{let{step:I,resultVar:B}=F1(Y.body,U,"result");_=I?[I]:[{op:"varSet",key:"result",value:B}]}let D=n(X[1],K);return{step:{op:"reduce",items:$,as:J,accumulator:G,initial:D,steps:_,...Q&&{result:Q},...Q&&H&&{resultConst:!0}},resultVar:Q}}break;case"slice":break;case"push":return{step:{op:"push",list:$,item:n(X[0],K),...Q&&{result:Q},...Q&&H&&{resultConst:!0}},resultVar:Q};case"join":return{step:{op:"join",list:$,sep:X.length>0?n(X[0],K):"",...Q&&{result:Q},...Q&&H&&{resultConst:!0}},resultVar:Q};case"split":return{step:{op:"split",str:$,sep:X.length>0?n(X[0],K):"",...Q&&{result:Q},...Q&&H&&{resultConst:!0}},resultVar:Q}}return K.warnings.push({message:`Unknown method '${Z}' - treating as atom call`,line:0,column:0}),{step:{op:Z,receiver:$,args:X.map((Y)=>n(Y,K)),...Q&&{result:Q},...Q&&H&&{resultConst:!0}},resultVar:Q}}function q8(Z,$,X,K){let Q="",H={};for(let Y=0;Y<Z.quasis.length;Y++)if(Q+=Z.quasis[Y].value.cooked||Z.quasis[Y].value.raw,Y<Z.expressions.length){let z=Z.expressions[Y],W=`_${Y}`;H[W]=n(z,$),Q+=`{{${W}}}`}return{step:{op:"template",tmpl:Q,vars:H,...X&&{result:X},...X&&K&&{resultConst:!0}},resultVar:X}}function f(Z,$){switch(Z.type){case"Literal":return{$expr:"literal",value:Z.value};case"Identifier":return{$expr:"ident",name:Z.name};case"MemberExpression":{let X=Z,K=f(X.object,$),Q=X.optional===!0;if(X.computed){let Y=X.property;if(Y.type==="Literal")return{$expr:"member",object:K,property:String(Y.value),computed:!0,...Q&&{optional:!0}};throw new y("Computed member access with variables not yet supported",h(Z),$.source,$.filename)}let H=X.property.name;return{$expr:"member",object:K,property:H,...Q&&{optional:!0}}}case"ChainExpression":return f(Z.expression,$);case"BinaryExpression":{let X=Z;return{$expr:"binary",op:X.operator,left:f(X.left,$),right:f(X.right,$)}}case"LogicalExpression":{let X=Z;return{$expr:"logical",op:X.operator,left:f(X.left,$),right:f(X.right,$)}}case"UnaryExpression":{let X=Z;return{$expr:"unary",op:X.operator,argument:f(X.argument,$)}}case"ConditionalExpression":{let X=Z;return{$expr:"conditional",test:f(X.test,$),consequent:f(X.consequent,$),alternate:f(X.alternate,$)}}case"ArrayExpression":return{$expr:"array",elements:Z.elements.filter((K)=>K!==null).map((K)=>f(K,$))};case"ObjectExpression":{let X=Z,K=[];for(let Q of X.properties)if(Q.type==="Property"){let H=Q.key.type==="Identifier"?Q.key.name:String(Q.key.value);K.push({key:H,value:f(Q.value,$)})}return{$expr:"object",properties:K}}case"CallExpression":{let X=Z;if(X.callee.type==="MemberExpression"){let K=X.callee,Q=K.property.type==="Identifier"?K.property.name:String(K.property.value),H=K.optional===!0||X.optional===!0;return{$expr:"methodCall",object:f(K.object,$),method:Q,arguments:X.arguments.map((Y)=>f(Y,$)),...H&&{optional:!0}}}if(X.callee.type==="Identifier")return{$expr:"call",callee:X.callee.name,arguments:X.arguments.map((Q)=>f(Q,$))};throw new y("Complex function calls in expressions should be lifted to statements",h(Z),$.source,$.filename)}case"NewExpression":{let X=Z,K="constructor";if(X.callee.type==="Identifier")K=X.callee.name;let Q=e4(K);throw new y(`The 'new' keyword is not supported in AsyncJS.${Q}`,h(Z),$.source,$.filename)}case"TemplateLiteral":throw new y("Template literals inside expressions are not supported. Assign to a variable first: const msg = `hello ${name}`; then use msg",h(Z),$.source,$.filename);default:throw new y(`Unsupported expression type in condition: ${Z.type}`,h(Z),$.source,$.filename)}}function n(Z,$){switch(Z.type){case"Literal":return Z.value;case"Identifier":return Z.name;case"MemberExpression":{let X=Z;if(X.optional===!0)return f(Z,$);let Q=n(X.object,$);if(Q&&typeof Q==="object"&&Q.$expr){let Y=X.computed?String(X.property.value):X.property.name;return{$expr:"member",object:Q,property:Y,...X.computed&&{computed:!0}}}if(X.computed)return`${Q}[${n(X.property,$)}]`;let H=X.property.name;if(typeof Q==="string")return`${Q}.${H}`;if(Q&&Q.$kind==="arg")return{$kind:"arg",path:`${Q.path}.${H}`};return`${Q}.${H}`}case"ChainExpression":return n(Z.expression,$);case"ArrayExpression":return Z.elements.map((X)=>X?n(X,$):null);case"ObjectExpression":{let X={};for(let K of Z.properties)if(K.type==="Property"){let Q=K.key.type==="Identifier"?K.key.name:String(K.key.value);X[Q]=n(K.value,$)}return X}case"TemplateLiteral":return f(Z,$);case"CallExpression":return f(Z,$);case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"ConditionalExpression":return f(Z,$);default:return null}}function U8(Z,$){if(Z.arguments.length===1&&Z.arguments[0].type==="ObjectExpression"){let X=Z.arguments[0],K={};for(let Q of X.properties)if(Q.type==="Property"){let H=Q.key.type==="Identifier"?Q.key.name:String(Q.key.value);K[H]=n(Q.value,$)}return K}return{args:Z.arguments.map((X)=>n(X,$))}}import{parseExpressionAt as y8}from"acorn";function D8(Z,$){let X=$;while(X>0&&Z[X-1]!==`
|
|
14
14
|
`)X--;if(Z.slice(X,$).includes("//"))return!0;let Q=0,H=!1;while(Q<$)if(!H&&Z.slice(Q,Q+2)==="/*")H=!0,Q+=2;else if(H&&Z.slice(Q,Q+2)==="*/")H=!1,Q+=2;else Q++;return H}function I8(Z){let $=[],X=/\/\*test\s+(['"`])([^'"`]*)\1\s*\{([\s\S]*?)\}\s*\*\/|\/\*test\s*\{([\s\S]*?)\}\s*\*\//g,K;while((K=X.exec(Z))!==null){let Q=K[2]||`embedded test ${$.length+1}`,H=(K[3]||K[4]||"").trim();$.push({description:Q,body:H,line:X4(Z,K.index)})}return $}function $4(Z){let $=[],X=[],K=I8(Z);$.push(...K);let Q=/test\s+(['"`])([^'"`]*)\1\s*\{|test\s*\(\s*(['"`])([^'"`]*)\3\s*\)\s*\{|test\s*\{/g,H=/mock\s*\{/g,Y=Z,z,W=[];while((z=Q.exec(Z))!==null){let _=z.index;if(D8(Z,_))continue;let D=z[2]||z[4]||`test ${$.length+1}`,I=z.index+z[0].length,B=Z6(Z,I-1);if(B===-1)continue;let A=Z.slice(I,B).trim();$.push({description:D,body:A,line:X4(Z,_)}),W.push({start:_,end:B+1,desc:D})}let G=[];while((z=H.exec(Z))!==null){let _=z.index,D=z.index+z[0].length,I=Z6(Z,D-1);if(I===-1)continue;let B=Z.slice(D,I).trim();X.push({body:B,line:X4(Z,_)}),G.push({start:_,end:I+1})}let J=[...W,...G].sort((_,D)=>D.start-_.start);for(let _ of J)Y=Y.slice(0,_.start)+Y.slice(_.end);Y=Y.replace(/\n\s*\n\s*\n/g,`
|
|
15
15
|
|
|
16
16
|
`).trim();let U=B8($,X);return{code:Y,tests:$,mocks:X,testRunner:U}}function Z6(Z,$){let X=0,K=null,Q=!1;for(let H=$;H<Z.length;H++){let Y=Z[H];if(Q){Q=!1;continue}if(Y==="\\"){Q=!0;continue}if(!K&&(Y==='"'||Y==="'"||Y==="`")){K=Y;continue}if(K===Y){K=null;continue}if(K)continue;if(Y==="{")X++;if(Y==="}"){if(X--,X===0)return H}}return-1}function X4(Z,$){return Z.slice(0,$).split(`
|
|
@@ -136,20 +136,20 @@ function expect(actual) {
|
|
|
136
136
|
}
|
|
137
137
|
`,R8=X6+`
|
|
138
138
|
`+$6;import*as K6 from"acorn";var Q1={i32:127,i64:126,f32:125,f64:124,v128:123,funcref:112,externref:111,void:64},i1={custom:0,type:1,import:2,function:3,table:4,memory:5,global:6,export:7,start:8,element:9,code:10,data:11},q={unreachable:0,nop:1,block:2,loop:3,if:4,else:5,end:11,br:12,br_if:13,br_table:14,return:15,call:16,call_indirect:17,drop:26,select:27,local_get:32,local_set:33,local_tee:34,global_get:35,global_set:36,i32_load:40,i64_load:41,f32_load:42,f64_load:43,i32_load8_s:44,i32_load8_u:45,i32_load16_s:46,i32_load16_u:47,i32_store:54,i64_store:55,f32_store:56,f64_store:57,i32_store8:58,i32_store16:59,memory_size:63,memory_grow:64,i32_const:65,i64_const:66,f32_const:67,f64_const:68,i32_eqz:69,i32_eq:70,i32_ne:71,i32_lt_s:72,i32_lt_u:73,i32_gt_s:74,i32_gt_u:75,i32_le_s:76,i32_le_u:77,i32_ge_s:78,i32_ge_u:79,i64_eqz:80,i64_eq:81,i64_ne:82,i64_lt_s:83,i64_lt_u:84,i64_gt_s:85,i64_gt_u:86,i64_le_s:87,i64_le_u:88,i64_ge_s:89,i64_ge_u:90,f32_eq:91,f32_ne:92,f32_lt:93,f32_gt:94,f32_le:95,f32_ge:96,f64_eq:97,f64_ne:98,f64_lt:99,f64_gt:100,f64_le:101,f64_ge:102,i32_clz:103,i32_ctz:104,i32_popcnt:105,i32_add:106,i32_sub:107,i32_mul:108,i32_div_s:109,i32_div_u:110,i32_rem_s:111,i32_rem_u:112,i32_and:113,i32_or:114,i32_xor:115,i32_shl:116,i32_shr_s:117,i32_shr_u:118,i32_rotl:119,i32_rotr:120,i64_add:124,i64_sub:125,i64_mul:126,i64_div_s:127,f32_abs:139,f32_neg:140,f32_ceil:141,f32_floor:142,f32_trunc:143,f32_nearest:144,f32_sqrt:145,f32_add:146,f32_sub:147,f32_mul:148,f32_div:149,f32_min:150,f32_max:151,f32_copysign:152,f64_abs:153,f64_neg:154,f64_ceil:155,f64_floor:156,f64_trunc:157,f64_nearest:158,f64_sqrt:159,f64_add:160,f64_sub:161,f64_mul:162,f64_div:163,f64_min:164,f64_max:165,f64_copysign:166,i32_wrap_i64:167,i32_trunc_f32_s:168,i32_trunc_f32_u:169,i32_trunc_f64_s:170,i32_trunc_f64_u:171,i64_extend_i32_s:172,i64_extend_i32_u:173,f32_convert_i32_s:178,f32_convert_i32_u:179,f32_convert_i64_s:180,f32_demote_f64:182,f64_convert_i32_s:183,f64_convert_i32_u:184,f64_convert_i64_s:185,f64_promote_f32:187,i32_reinterpret_f32:188,f32_reinterpret_i32:190,f64_reinterpret_i64:191,i32_extend8_s:192,i32_extend16_s:193},M8=Object.fromEntries(Object.entries(q).map(([Z,$])=>[$,Z.replace(/_/g,".")]));function b(Z){let $=[];do{let X=Z&127;if(Z>>>=7,Z!==0)X|=128;$.push(X)}while(Z!==0);return $}function c1(Z){let $=[],X=!0;while(X){let K=Z&127;if(Z>>=7,Z===0&&(K&64)===0||Z===-1&&(K&64)!==0)X=!1;else K|=128;$.push(K)}return $}function A8(Z){let $=new ArrayBuffer(4);return new Float32Array($)[0]=Z,[...new Uint8Array($)]}function H1(Z){let $=new ArrayBuffer(8);return new Float64Array($)[0]=Z,[...new Uint8Array($)]}function K4(Z){let $=new TextEncoder().encode(Z);return[...b($.length),...$]}function p1(Z,$){return[Z,...b($.length),...$]}function n1(Z,$){let X=0,K=0,Q=$;while(Q<Z.length){let H=Z[Q];if(X|=(H&127)<<K,Q++,(H&128)===0)break;K+=7}return[X,Q-$]}function j8(Z,$){let X=new ArrayBuffer(8),K=new Uint8Array(X);for(let Q=0;Q<8;Q++)K[Q]=Z[$+Q];return new Float64Array(X)[0]}function F8(Z,$,X){let K=[],Q=1,H=()=>" ".repeat(Q),Y=$.map((G,J)=>`(param $${G.name} ${G.type})`).join(" "),z=X.map((G,J)=>`(local $L${$.length+J} ${G})`).join(" ");if(K.push(`(func (export "compute") ${Y} (result f64)`),z)K.push(` ${z}`);let W=0;while(W<Z.length){let G=Z[W],J=M8[G]||`unknown(0x${G.toString(16)})`;if(W++,G===q.local_get||G===q.local_set||G===q.local_tee){let[U,_]=n1(Z,W);W+=_;let D=U<$.length?`$${$[U].name}`:`$L${U}`;K.push(`${H()}${J} ${D}`)}else if(G===q.br||G===q.br_if){let[U,_]=n1(Z,W);W+=_,K.push(`${H()}${J} ${U}`)}else if(G===q.i32_const){let[U,_]=n1(Z,W);W+=_,K.push(`${H()}i32.const ${U}`)}else if(G===q.f64_const){let U=j8(Z,W);W+=8,K.push(`${H()}f64.const ${U}`)}else if(G===q.block||G===q.loop){let U=Z[W];W++,K.push(`${H()}${J}${U===Q1.void?"":` (result ${U===Q1.f64?"f64":"i32"})`}`),Q++}else if(G===q.if){let U=Z[W];W++,K.push(`${H()}if${U===Q1.void?"":` (result ${U===Q1.f64?"f64":"i32"})`}`),Q++}else if(G===q.else)Q--,K.push(`${H()}else`),Q++;else if(G===q.end)Q=Math.max(1,Q-1),K.push(`${H()}end`);else if(G===q.f64_load||G===q.f64_store||G===q.f32_load||G===q.f32_store||G===q.i32_load||G===q.i32_store){let[U,_]=n1(Z,W);W+=_;let[D,I]=n1(Z,W);W+=I,K.push(`${H()}${J}${D?` offset=${D}`:""}`)}else K.push(`${H()}${J}`)}return K.push(")"),K.join(`
|
|
139
|
-
`)}var U0={Int8Array:{elementType:"i32",bytesPerElement:1,loadOp:q.i32_load8_s,storeOp:q.i32_store8},Uint8Array:{elementType:"i32",bytesPerElement:1,loadOp:q.i32_load8_u,storeOp:q.i32_store8},Uint8ClampedArray:{elementType:"i32",bytesPerElement:1,loadOp:q.i32_load8_u,storeOp:q.i32_store8},Int16Array:{elementType:"i32",bytesPerElement:2,loadOp:q.i32_load16_s,storeOp:q.i32_store16},Uint16Array:{elementType:"i32",bytesPerElement:2,loadOp:q.i32_load16_u,storeOp:q.i32_store16},Int32Array:{elementType:"i32",bytesPerElement:4,loadOp:q.i32_load,storeOp:q.i32_store},Uint32Array:{elementType:"i32",bytesPerElement:4,loadOp:q.i32_load,storeOp:q.i32_store},Float32Array:{elementType:"f32",bytesPerElement:4,loadOp:q.f32_load,storeOp:q.f32_store},Float64Array:{elementType:"f64",bytesPerElement:8,loadOp:q.f64_load,storeOp:q.f64_store}};function w8(Z){let $={params:Z,locals:new Map,nextLocalIndex:Z.length,localTypes:[],warnings:[],errors:[],loopDepth:0,needsMathImports:new Set,needsMemory:!1,hasReturn:!1,wat:[],watIndent:1};return Z.forEach((X,K)=>{$.locals.set(X.name,{index:K,type:X.type})}),$}function q0(Z,$,X){if(Z.locals.has($))return Z.errors.push(`Duplicate local declaration: ${$}`),Z.locals.get($).index;let K=Z.nextLocalIndex++;return Z.locals.set($,{index:K,type:X}),Z.localTypes.push(X),K}function w1(Z,$){return Z.locals.get($)}function S1(Z,$){switch(Z.type){case"ExpressionStatement":{let X=Z.expression;return[...i(X,$),q.drop]}case"ReturnStatement":{let X=Z;if($.hasReturn=!0,!X.argument)return[q.return];let K=i(X.argument,$),Q=c(X.argument,$);if(Q==="i32")K.push(q.f64_convert_i32_s);else if(Q==="f32")K.push(q.f64_promote_f32);return K.push(q.return),K}case"VariableDeclaration":{let X=Z,K=[];for(let Q of X.declarations){if(Q.id.type!=="Identifier"){$.errors.push("Destructuring not supported in WASM blocks");continue}let H=Q.id.name,Y="f64";if(Q.init)Y=c(Q.init,$);let z=q0($,H,Y);if(Q.init)K.push(...i(Q.init,$)),K.push(q.local_set,...b(z))}return K}case"ForStatement":return P8(Z,$);case"IfStatement":return C8(Z,$);case"BlockStatement":{let X=Z,K=[];for(let Q of X.body)K.push(...S1(Q,$));return K}default:return $.errors.push(`Unsupported statement type: ${Z.type}`),[]}}function P8(Z,$){let X=[];if(Z.init)if(Z.init.type==="VariableDeclaration")X.push(...S1(Z.init,$));else X.push(...i(Z.init,$));if(X.push(q.block,Q1.void),X.push(q.loop,Q1.void),Z.test)X.push(...i(Z.test,$)),X.push(q.i32_eqz),X.push(q.br_if,1);if($.loopDepth++,Z.body)X.push(...S1(Z.body,$));if($.loopDepth--,Z.update)X.push(...i(Z.update,$)),X.push(q.drop);return X.push(q.br,0),X.push(q.end),X.push(q.end),X}function C8(Z,$){let X=[];if(X.push(...i(Z.test,$)),X.push(q.if,Q1.void),X.push(...S1(Z.consequent,$)),Z.alternate)X.push(q.else),X.push(...S1(Z.alternate,$));return X.push(q.end),X}function c(Z,$){switch(Z.type){case"Literal":{let X=Z;if(typeof X.value==="number"){if(X.raw&&(X.raw.includes(".")||X.raw.includes("e")))return"f64";if(Number.isInteger(X.value)&&X.value>=-2147483648&&X.value<=2147483647)return"i32";return"f64"}return"f64"}case"Identifier":return w1($,Z.name)?.type??"f64";case"BinaryExpression":case"AssignmentExpression":{let X=Z;if(["<",">","<=",">=","==","!=","===","!=="].includes(X.operator))return"i32";if(["|","&","^","<<",">>",">>>"].includes(X.operator))return"i32";let K=c(X.left,$),Q=c(X.right,$);if(K==="f64"||Q==="f64")return"f64";if(K==="f32"||Q==="f32")return"f32";return"i32"}case"UnaryExpression":{let X=Z;if(X.operator==="!")return"i32";return c(X.argument,$)}case"MemberExpression":{let X=Z;if(X.object.type==="Identifier"){if(w1($,X.object.name)){let Q=$.params.find((H)=>H.name===X.object.name);if(Q?.arrayType){let H=U0[Q.arrayType];if(H)return H.elementType}}}return"f64"}case"CallExpression":{let X=Z;if(X.callee.type==="MemberExpression"){let K=X.callee;if(K.object.type==="Identifier"&&K.object.name==="Math")return"f64"}return"f64"}default:return"f64"}}function i(Z,$){switch(Z.type){case"Literal":{let X=Z;if(typeof X.value==="number"){let K=c(Z,$);if(K==="i32")return[q.i32_const,...c1(X.value|0)];else if(K==="f32")return[q.f32_const,...A8(X.value)];else return[q.f64_const,...H1(X.value)]}return $.errors.push(`Unsupported literal type: ${typeof X.value}`),[q.f64_const,...H1(0)]}case"Identifier":{let X=Z.name,K=w1($,X);if(K)return[q.local_get,...b(K.index)];return $.errors.push(`Unknown identifier: ${X}`),[q.f64_const,...H1(0)]}case"BinaryExpression":return V8(Z,$);case"UnaryExpression":return O8(Z,$);case"AssignmentExpression":return N8(Z,$);case"UpdateExpression":return E8(Z,$);case"MemberExpression":return S8(Z,$);case"CallExpression":return k8(Z,$);case"SequenceExpression":{let X=Z,K=[];for(let Q=0;Q<X.expressions.length;Q++)if(K.push(...i(X.expressions[Q],$)),Q<X.expressions.length-1)K.push(q.drop);return K}default:return $.errors.push(`Unsupported expression type: ${Z.type}`),[q.f64_const,...H1(0)]}}function V8(Z,$){let X=i(Z.left,$),K=i(Z.right,$),Q=c(Z,$),H=c(Z.left,$),Y=c(Z.right,$),z=["<",">","<=",">=","==","===","!=","!=="].includes(Z.operator),W;if(H==="f64"||Y==="f64")W="f64";else if(H==="f32"||Y==="f32")W="f32";else W="i32";if(!z&&Q==="f64")W="f64";let G=X,J=K;if(W==="f64"){if(H==="i32")G=[...X,q.f64_convert_i32_s];else if(H==="f32")G=[...X,q.f64_promote_f32];if(Y==="i32")J=[...K,q.f64_convert_i32_s];else if(Y==="f32")J=[...K,q.f64_promote_f32]}else if(W==="f32"){if(H==="i32")G=[...X,q.f32_convert_i32_s];if(Y==="i32")J=[...K,q.f32_convert_i32_s]}let _={"+":{i32:q.i32_add,f32:q.f32_add,f64:q.f64_add},"-":{i32:q.i32_sub,f32:q.f32_sub,f64:q.f64_sub},"*":{i32:q.i32_mul,f32:q.f32_mul,f64:q.f64_mul},"/":{i32:q.i32_div_s,f32:q.f32_div,f64:q.f64_div},"%":{i32:q.i32_rem_s},"<":{i32:q.i32_lt_s,f32:q.f32_lt,f64:q.f64_lt},">":{i32:q.i32_gt_s,f32:q.f32_gt,f64:q.f64_gt},"<=":{i32:q.i32_le_s,f32:q.f32_le,f64:q.f64_le},">=":{i32:q.i32_ge_s,f32:q.f32_ge,f64:q.f64_ge},"==":{i32:q.i32_eq,f32:q.f32_eq,f64:q.f64_eq},"===":{i32:q.i32_eq,f32:q.f32_eq,f64:q.f64_eq},"!=":{i32:q.i32_ne,f32:q.f32_ne,f64:q.f64_ne},"!==":{i32:q.i32_ne,f32:q.f32_ne,f64:q.f64_ne},"|":{i32:q.i32_or},"&":{i32:q.i32_and},"^":{i32:q.i32_xor},"<<":{i32:q.i32_shl},">>":{i32:q.i32_shr_s},">>>":{i32:q.i32_shr_u}}[Z.operator];if(!_)return $.errors.push(`Unsupported operator: ${Z.operator}`),[q.f64_const,...H1(0)];let D=_[W]??_.f64??_.i32;if(D===void 0)return $.errors.push(`Operator ${Z.operator} not supported for type ${W}`),[q.f64_const,...H1(0)];return[...G,...J,D]}function O8(Z,$){let X=i(Z.argument,$),K=c(Z.argument,$);switch(Z.operator){case"-":if(K==="i32")return[q.i32_const,0,...X,q.i32_sub];else if(K==="f32")return[...X,q.f32_neg];else return[...X,q.f64_neg];case"!":return[...X,q.i32_eqz];case"~":return[...X,q.i32_const,...c1(-1),q.i32_xor];default:return $.errors.push(`Unsupported unary operator: ${Z.operator}`),X}}function N8(Z,$){if(Z.left.type==="MemberExpression")return T8(Z.left,Z.right,Z.operator,$);if(Z.left.type!=="Identifier")return $.errors.push("Assignment target must be identifier or array element"),[];let X=Z.left.name,K=w1($,X);if(!K)return $.errors.push(`Unknown variable: ${X}`),[];let Q=[];if(Z.operator==="="){Q.push(...i(Z.right,$));let H=c(Z.right,$);if(K.type==="f64"&&H==="i32")Q.push(q.f64_convert_i32_s);else if(K.type==="f64"&&H==="f32")Q.push(q.f64_promote_f32);else if(K.type==="i32"&&H==="f64")Q.push(q.i32_trunc_f64_s);else if(K.type==="i32"&&H==="f32")Q.push(q.i32_trunc_f32_s);else if(K.type==="f32"&&H==="i32")Q.push(q.f32_convert_i32_s);else if(K.type==="f32"&&H==="f64")Q.push(q.f32_demote_f64)}else{let H=c(Z.right,$),Y=K.type;if(H==="f64"||K.type==="f64")Y="f64";else if(H==="f32"||K.type==="f32")Y="f32";if(Q.push(q.local_get,...b(K.index)),Y==="f64"&&K.type==="i32")Q.push(q.f64_convert_i32_s);else if(Y==="f64"&&K.type==="f32")Q.push(q.f64_promote_f32);else if(Y==="f32"&&K.type==="i32")Q.push(q.f32_convert_i32_s);if(Q.push(...i(Z.right,$)),Y==="f64"&&H==="i32")Q.push(q.f64_convert_i32_s);else if(Y==="f64"&&H==="f32")Q.push(q.f64_promote_f32);else if(Y==="f32"&&H==="i32")Q.push(q.f32_convert_i32_s);let z=Z.operator.slice(0,-1),G={"+":{i32:q.i32_add,f32:q.f32_add,f64:q.f64_add},"-":{i32:q.i32_sub,f32:q.f32_sub,f64:q.f64_sub},"*":{i32:q.i32_mul,f32:q.f32_mul,f64:q.f64_mul},"/":{i32:q.i32_div_s,f32:q.f32_div,f64:q.f64_div}}[z]?.[Y];if(!G)return $.errors.push(`Unsupported compound assignment: ${Z.operator}`),[];if(Q.push(G),K.type==="i32"&&Y==="f64")Q.push(q.i32_trunc_f64_s);else if(K.type==="i32"&&Y==="f32")Q.push(q.i32_trunc_f32_s);else if(K.type==="f32"&&Y==="f64")Q.push(q.f32_demote_f64)}return Q.push(q.local_tee,...b(K.index)),Q}function E8(Z,$){if(Z.argument.type!=="Identifier")return $.errors.push("Update expression argument must be identifier"),[];let X=Z.argument.name,K=w1($,X);if(!K)return $.errors.push(`Unknown variable: ${X}`),[];let Q=[],H=K.type==="i32";if(Z.prefix){if(Q.push(q.local_get,...b(K.index)),H)Q.push(q.i32_const,1),Q.push(Z.operator==="++"?q.i32_add:q.i32_sub);else Q.push(q.f64_const,...H1(1)),Q.push(Z.operator==="++"?q.f64_add:q.f64_sub);Q.push(q.local_tee,...b(K.index))}else{if(Q.push(q.local_get,...b(K.index)),Q.push(q.local_get,...b(K.index)),H)Q.push(q.i32_const,1),Q.push(Z.operator==="++"?q.i32_add:q.i32_sub);else Q.push(q.f64_const,...H1(1)),Q.push(Z.operator==="++"?q.f64_add:q.f64_sub);Q.push(q.local_set,...b(K.index))}return Q}function S8(Z,$){if(Z.object.type!=="Identifier")return $.errors.push("Array access requires identifier"),[];let X=Z.object.name,K=$.params.find((G)=>G.name===X);if(!K?.isArray||!K.arrayType)return $.errors.push(`${X} is not a typed array parameter`),[];let Q=U0[K.arrayType];if(!Q)return $.errors.push(`Unknown array type: ${K.arrayType}`),[];$.needsMemory=!0;let H=[],Y=w1($,X);if(!Y)return $.errors.push(`Unknown array: ${X}`),[];if(H.push(q.local_get,...b(Y.index)),!Z.computed||!Z.property)return $.errors.push("Array access requires computed index"),[];let z=i(Z.property,$),W=c(Z.property,$);if(H.push(...z),W==="f64")H.push(q.i32_trunc_f64_s);if(Q.bytesPerElement>1)H.push(q.i32_const,...c1(Q.bytesPerElement)),H.push(q.i32_mul);return H.push(q.i32_add),H.push(Q.loadOp,0,0),H}function T8(Z,$,X,K){if(Z.object.type!=="Identifier")return K.errors.push("Array store requires identifier"),[];let Q=Z.object.name,H=K.params.find((I)=>I.name===Q);if(!H?.isArray||!H.arrayType)return K.errors.push(`${Q} is not a typed array parameter`),[];let Y=U0[H.arrayType];if(!Y)return K.errors.push(`Unknown array type: ${H.arrayType}`),[];K.needsMemory=!0;let z=[],W=w1(K,Q);if(!W)return[];if(!Z.computed||!Z.property)return K.errors.push("Array store requires computed index"),[];let G=i(Z.property,K),J=c(Z.property,K),U=()=>{let I=[];if(I.push(q.local_get,...b(W.index)),I.push(...G),J==="f64")I.push(q.i32_trunc_f64_s);if(Y.bytesPerElement>1)I.push(q.i32_const,...c1(Y.bytesPerElement)),I.push(q.i32_mul);return I.push(q.i32_add),I};if(X==="=")z.push(...i($,K));else{let I=q0(K,`__addr_${K.nextLocalIndex}`,"i32");z.push(...U()),z.push(q.local_tee,...b(I)),z.push(Y.loadOp,0,0),z.push(...i($,K));let B=c($,K);if(Y.elementType==="f32"&&B==="f64")z.push(q.f32_demote_f64);else if(Y.elementType==="f64"&&B==="f32")z.push(q.f64_promote_f32);else if(Y.elementType==="f32"&&B==="i32")z.push(q.f32_convert_i32_s);else if(Y.elementType==="f64"&&B==="i32")z.push(q.f64_convert_i32_s);else if(Y.elementType==="i32"&&B==="f64")z.push(q.i32_trunc_f64_s);else if(Y.elementType==="i32"&&B==="f32")z.push(q.i32_trunc_f32_s);let A=X.slice(0,-1),j={"+":Y.elementType==="i32"?q.i32_add:Y.elementType==="f32"?q.f32_add:q.f64_add,"-":Y.elementType==="i32"?q.i32_sub:Y.elementType==="f32"?q.f32_sub:q.f64_sub,"*":Y.elementType==="i32"?q.i32_mul:Y.elementType==="f32"?q.f32_mul:q.f64_mul};z.push(j[A]??q.f64_add);let P=q0(K,`__val_${K.nextLocalIndex}`,Y.elementType);return z.push(q.local_set,...b(P)),z.push(q.local_get,...b(I)),z.push(q.local_get,...b(P)),z.push(Y.storeOp,0,0),z.push(q.local_get,...b(P)),z}let _=c($,K);if(Y.elementType==="f32"&&_==="f64")z.push(q.f32_demote_f64);else if(Y.elementType==="f64"&&_==="f32")z.push(q.f64_promote_f32);else if(Y.elementType==="i32"&&_==="f64")z.push(q.i32_trunc_f64_s);let D=q0(K,`__tmp_${K.nextLocalIndex}`,Y.elementType);if(z.push(q.local_set,...b(D)),z.push(q.local_get,...b(W.index)),z.push(...G),J==="f64")z.push(q.i32_trunc_f64_s);if(Y.bytesPerElement>1)z.push(q.i32_const,...c1(Y.bytesPerElement)),z.push(q.i32_mul);return z.push(q.i32_add),z.push(q.local_get,...b(D)),z.push(Y.storeOp,0,0),z.push(q.local_get,...b(D)),z}function k8(Z,$){if(Z.callee.type==="MemberExpression"){let X=Z.callee;if(X.object.type==="Identifier"&&X.object.name==="Math"&&X.property.type==="Identifier"){let K=X.property.name;return g8(K,Z.arguments,$)}}return $.errors.push(`Unsupported function call: ${Z.callee.type}`),[q.f64_const,...H1(0)]}function g8(Z,$,X){let K=[];for(let z of $){K.push(...i(z,X));let W=c(z,X);if(W==="i32")K.push(q.f64_convert_i32_s);else if(W==="f32")K.push(q.f64_promote_f32)}let H={abs:q.f64_abs,ceil:q.f64_ceil,floor:q.f64_floor,trunc:q.f64_trunc,sqrt:q.f64_sqrt,min:q.f64_min,max:q.f64_max}[Z];if(H!==void 0)return K.push(H),K;if(["sin","cos","tan","asin","acos","atan","atan2","exp","log","pow"].includes(Z))return X.needsMathImports.add(Z),X.errors.push(`Math.${Z} requires JS import (not yet implemented)`),[q.f64_const,...H1(0)];return X.errors.push(`Unknown Math method: ${Z}`),[q.f64_const,...H1(0)]}function Q6(Z){let $=Z.split(":").map((H)=>H.trim()),X=$[0];if($.length===1)return{name:X,type:"f64"};let K=$[1];if(U0[K])return{name:X,type:"i32",isArray:!0,arrayType:K};return{name:X,type:{i32:"i32",i64:"i64",f32:"f32",f64:"f64",number:"f64",int:"i32"}[K]??"f64"}}function b8(Z,$,X,K,Q){let H=[0,97,115,109,1,0,0,0],Y=Z.map((P)=>Q1[P.type]),z=Q?[1,Q1.f64]:[0],W=p1(i1.type,[1,96,...b(Z.length),...Y,...z]),G=[],J=[];if(K)J=p1(i1.import,[1,...K4("env"),...K4("memory"),2,0,1]);let U=p1(i1.function,[1,0]),_=p1(i1.export,[1,...K4("compute"),0,0]),D=[];if(X.length>0){let P=X[0],N=1;for(let M=1;M<X.length;M++)if(X[M]===P)N++;else D.push([...b(N),Q1[P]]),P=X[M],N=1;D.push([...b(N),Q1[P]])}let B=[...[...b(D.length),...D.flat()],...$,q.end],A=p1(i1.code,[1,...b(B.length),...B]),j=[...H,...W];if(J.length>0)j.push(...J);return j.push(...U,..._,...A),j}function D0(Z){try{let $=Z.captures.map(Q6),X;try{let G=`function __wasm__(${$.map((J)=>J.name).join(", ")}) { ${Z.body} }`;X=K6.parse(G,{ecmaVersion:2022})}catch(G){return{bytes:new Uint8Array,warnings:[],success:!1,error:`Parse error: ${G.message}`}}let Q=X.body[0].body.body,H=w8($),Y=[];for(let G of Q)Y.push(...S1(G,H));if(H.errors.length>0)return{bytes:new Uint8Array,warnings:H.warnings,success:!1,error:H.errors.join("; ")};let z=b8($,Y,H.localTypes,H.needsMemory,H.hasReturn),W=F8(Y,$,H.localTypes);return{bytes:new Uint8Array(z),warnings:H.warnings,success:!0,needsMemory:H.needsMemory,wat:W}}catch($){return{bytes:new Uint8Array,warnings:[],success:!1,error:$.message}}}async function H6(Z,$){let X={};if($)X.env={memory:$};let K=await WebAssembly.compile(Z);return WebAssembly.instantiate(K,X)}async function v8(Z){let $=D0(Z);if(!$.success)return{fn:()=>0,success:!1,error:$.error};try{let X;if($.needsMemory)X=new WebAssembly.Memory({initial:256});let Q=(await H6($.bytes,X)).exports.compute,H=Z.captures.map(Q6);if(!H.some((W)=>W.isArray))return{fn:Q,memory:X,success:!0};return{fn:(...W)=>{if(!X)throw Error("Memory not initialized");let G=new Uint8Array(X.buffer),J=0,U=[];for(let D=0;D<H.length;D++){let I=H[D],B=W[D];if(I.isArray&&B instanceof Object&&"buffer"in B){let A=B,j=new Uint8Array(A.buffer,A.byteOffset,A.byteLength);G.set(j,J),U.push(J),J+=j.length,J=J+7&-8}else U.push(B)}let _=Q(...U);J=0;for(let D=0;D<H.length;D++){let I=H[D],B=W[D];if(I.isArray&&B instanceof Object&&"buffer"in B){let A=B,j=new Uint8Array(A.buffer,A.byteOffset,A.byteLength);j.set(G.slice(J,J+j.length)),J+=j.length,J=J+7&-8}}return _},memory:X,success:!0}}catch(X){return{fn:()=>0,success:!1,error:X.message}}}async function Y6(Z){let $=await v8(Z);if(!$.success)return console.warn(`WASM compilation failed for ${Z.id}:`,$.error),!1;return globalThis[Z.id]=$.fn,!0}async function f8(Z){let $=0,X=0,K=[];for(let Q of Z)if(await Y6(Q))$++;else X++,K.push(`Failed to compile ${Q.id}`);return{compiled:$,failed:X,errors:K}}function h8(Z,$,X,K){let Q=[],H=u1($,Z),Y={},z=!1,W,G;if(Z.params.length===1&&(Z.params[0].type==="ObjectPattern"||Z.params[0].type==="AssignmentPattern"&&Z.params[0].left.type==="ObjectPattern")){z=!0;let _=Z.params[0],D=_.type==="ObjectPattern"?_:_.left,I=I1(D,X);if(I.type.kind==="object"&&I.type.destructuredParams){W={},G=new Set;for(let[B,A]of Object.entries(I.type.destructuredParams))if(Y[B]={...A,description:H.params[B]},W[B]=A.type,A.required)G.add(B)}}else for(let _ of Z.params)if(_.type==="Identifier"){let D=I1(_,X);Y[_.name]={...D,required:X.has(_.name),description:H.params[_.name]}}else if(_.type==="AssignmentPattern"&&_.left.type==="Identifier"){let D=I1(_,X);Y[_.left.name]={...D,required:X.has(_.left.name),description:H.params[_.left.name]}}else if(_.type==="ObjectPattern"){let D=I1(_,X);if(D.type.kind==="object"&&D.type.destructuredParams)for(let[I,B]of Object.entries(D.type.destructuredParams))Y[I]={...B,description:H.params[I]}}let J;if(K)try{let _=y8(K,0,{ecmaVersion:2022});J=X1(_)}catch{J={kind:"any"},Q.push(`Could not parse return type: ${K}`)}return{types:{name:Z.id?.name||"anonymous",params:Y,returns:J,description:H.description,isDestructuredParam:z,destructuredShape:W,destructuredRequired:G},warnings:Q}}function x8(Z,$,X){let K=[],Q=X?`${X}:`:"",H=X?`${X}:${Z}`:Z;if(K.push(`__tjs.pushStack('${H}');`),$.isDestructuredParam&&$.destructuredShape){let z=$.destructuredShape,W=$.destructuredRequired||new Set,G=Object.keys(z);if(G.length===0)return null;for(let J of G)K.push(`if (${J} instanceof Error) return ${J};`);for(let[J,U]of Object.entries(z)){let _=W.has(J),D=`${Q}${Z}.${J}`,I=z6(J,U);if(I){let B=U.kind;if(_)K.push(`if (${I}) return __tjs.typeError('${D}', '${B}', ${J});`);else K.push(`if (${J} !== undefined && ${I}) return __tjs.typeError('${D}', '${B}', ${J});`)}}return K.length>0?K.join(`
|
|
139
|
+
`)}var U0={Int8Array:{elementType:"i32",bytesPerElement:1,loadOp:q.i32_load8_s,storeOp:q.i32_store8},Uint8Array:{elementType:"i32",bytesPerElement:1,loadOp:q.i32_load8_u,storeOp:q.i32_store8},Uint8ClampedArray:{elementType:"i32",bytesPerElement:1,loadOp:q.i32_load8_u,storeOp:q.i32_store8},Int16Array:{elementType:"i32",bytesPerElement:2,loadOp:q.i32_load16_s,storeOp:q.i32_store16},Uint16Array:{elementType:"i32",bytesPerElement:2,loadOp:q.i32_load16_u,storeOp:q.i32_store16},Int32Array:{elementType:"i32",bytesPerElement:4,loadOp:q.i32_load,storeOp:q.i32_store},Uint32Array:{elementType:"i32",bytesPerElement:4,loadOp:q.i32_load,storeOp:q.i32_store},Float32Array:{elementType:"f32",bytesPerElement:4,loadOp:q.f32_load,storeOp:q.f32_store},Float64Array:{elementType:"f64",bytesPerElement:8,loadOp:q.f64_load,storeOp:q.f64_store}};function w8(Z){let $={params:Z,locals:new Map,nextLocalIndex:Z.length,localTypes:[],warnings:[],errors:[],loopDepth:0,needsMathImports:new Set,needsMemory:!1,hasReturn:!1,wat:[],watIndent:1};return Z.forEach((X,K)=>{$.locals.set(X.name,{index:K,type:X.type})}),$}function q0(Z,$,X){if(Z.locals.has($))return Z.errors.push(`Duplicate local declaration: ${$}`),Z.locals.get($).index;let K=Z.nextLocalIndex++;return Z.locals.set($,{index:K,type:X}),Z.localTypes.push(X),K}function w1(Z,$){return Z.locals.get($)}function S1(Z,$){switch(Z.type){case"ExpressionStatement":{let X=Z.expression;return[...i(X,$),q.drop]}case"ReturnStatement":{let X=Z;if($.hasReturn=!0,!X.argument)return[q.return];let K=i(X.argument,$),Q=c(X.argument,$);if(Q==="i32")K.push(q.f64_convert_i32_s);else if(Q==="f32")K.push(q.f64_promote_f32);return K.push(q.return),K}case"VariableDeclaration":{let X=Z,K=[];for(let Q of X.declarations){if(Q.id.type!=="Identifier"){$.errors.push("Destructuring not supported in WASM blocks");continue}let H=Q.id.name,Y="f64";if(Q.init)Y=c(Q.init,$);let z=q0($,H,Y);if(Q.init)K.push(...i(Q.init,$)),K.push(q.local_set,...b(z))}return K}case"ForStatement":return P8(Z,$);case"IfStatement":return C8(Z,$);case"BlockStatement":{let X=Z,K=[];for(let Q of X.body)K.push(...S1(Q,$));return K}default:return $.errors.push(`Unsupported statement type: ${Z.type}`),[]}}function P8(Z,$){let X=[];if(Z.init)if(Z.init.type==="VariableDeclaration")X.push(...S1(Z.init,$));else X.push(...i(Z.init,$));if(X.push(q.block,Q1.void),X.push(q.loop,Q1.void),Z.test)X.push(...i(Z.test,$)),X.push(q.i32_eqz),X.push(q.br_if,1);if($.loopDepth++,Z.body)X.push(...S1(Z.body,$));if($.loopDepth--,Z.update)X.push(...i(Z.update,$)),X.push(q.drop);return X.push(q.br,0),X.push(q.end),X.push(q.end),X}function C8(Z,$){let X=[];if(X.push(...i(Z.test,$)),X.push(q.if,Q1.void),X.push(...S1(Z.consequent,$)),Z.alternate)X.push(q.else),X.push(...S1(Z.alternate,$));return X.push(q.end),X}function c(Z,$){switch(Z.type){case"Literal":{let X=Z;if(typeof X.value==="number"){if(X.raw&&(X.raw.includes(".")||X.raw.includes("e")))return"f64";if(Number.isInteger(X.value)&&X.value>=-2147483648&&X.value<=2147483647)return"i32";return"f64"}return"f64"}case"Identifier":return w1($,Z.name)?.type??"f64";case"BinaryExpression":case"AssignmentExpression":{let X=Z;if(["<",">","<=",">=","==","!=","===","!=="].includes(X.operator))return"i32";if(["|","&","^","<<",">>",">>>"].includes(X.operator))return"i32";let K=c(X.left,$),Q=c(X.right,$);if(K==="f64"||Q==="f64")return"f64";if(K==="f32"||Q==="f32")return"f32";return"i32"}case"UnaryExpression":{let X=Z;if(X.operator==="!")return"i32";return c(X.argument,$)}case"MemberExpression":{let X=Z;if(X.object.type==="Identifier"){if(w1($,X.object.name)){let Q=$.params.find((H)=>H.name===X.object.name);if(Q?.arrayType){let H=U0[Q.arrayType];if(H)return H.elementType}}}return"f64"}case"CallExpression":{let X=Z;if(X.callee.type==="MemberExpression"){let K=X.callee;if(K.object.type==="Identifier"&&K.object.name==="Math")return"f64"}return"f64"}default:return"f64"}}function i(Z,$){switch(Z.type){case"Literal":{let X=Z;if(typeof X.value==="number"){let K=c(Z,$);if(K==="i32")return[q.i32_const,...c1(X.value|0)];else if(K==="f32")return[q.f32_const,...A8(X.value)];else return[q.f64_const,...H1(X.value)]}return $.errors.push(`Unsupported literal type: ${typeof X.value}`),[q.f64_const,...H1(0)]}case"Identifier":{let X=Z.name,K=w1($,X);if(K)return[q.local_get,...b(K.index)];return $.errors.push(`Unknown identifier: ${X}`),[q.f64_const,...H1(0)]}case"BinaryExpression":return V8(Z,$);case"UnaryExpression":return O8(Z,$);case"AssignmentExpression":return N8(Z,$);case"UpdateExpression":return E8(Z,$);case"MemberExpression":return S8(Z,$);case"CallExpression":return k8(Z,$);case"SequenceExpression":{let X=Z,K=[];for(let Q=0;Q<X.expressions.length;Q++)if(K.push(...i(X.expressions[Q],$)),Q<X.expressions.length-1)K.push(q.drop);return K}default:return $.errors.push(`Unsupported expression type: ${Z.type}`),[q.f64_const,...H1(0)]}}function V8(Z,$){let X=i(Z.left,$),K=i(Z.right,$),Q=c(Z,$),H=c(Z.left,$),Y=c(Z.right,$),z=["<",">","<=",">=","==","===","!=","!=="].includes(Z.operator),W;if(H==="f64"||Y==="f64")W="f64";else if(H==="f32"||Y==="f32")W="f32";else W="i32";if(!z&&Q==="f64")W="f64";let G=X,J=K;if(W==="f64"){if(H==="i32")G=[...X,q.f64_convert_i32_s];else if(H==="f32")G=[...X,q.f64_promote_f32];if(Y==="i32")J=[...K,q.f64_convert_i32_s];else if(Y==="f32")J=[...K,q.f64_promote_f32]}else if(W==="f32"){if(H==="i32")G=[...X,q.f32_convert_i32_s];if(Y==="i32")J=[...K,q.f32_convert_i32_s]}let _={"+":{i32:q.i32_add,f32:q.f32_add,f64:q.f64_add},"-":{i32:q.i32_sub,f32:q.f32_sub,f64:q.f64_sub},"*":{i32:q.i32_mul,f32:q.f32_mul,f64:q.f64_mul},"/":{i32:q.i32_div_s,f32:q.f32_div,f64:q.f64_div},"%":{i32:q.i32_rem_s},"<":{i32:q.i32_lt_s,f32:q.f32_lt,f64:q.f64_lt},">":{i32:q.i32_gt_s,f32:q.f32_gt,f64:q.f64_gt},"<=":{i32:q.i32_le_s,f32:q.f32_le,f64:q.f64_le},">=":{i32:q.i32_ge_s,f32:q.f32_ge,f64:q.f64_ge},"==":{i32:q.i32_eq,f32:q.f32_eq,f64:q.f64_eq},"===":{i32:q.i32_eq,f32:q.f32_eq,f64:q.f64_eq},"!=":{i32:q.i32_ne,f32:q.f32_ne,f64:q.f64_ne},"!==":{i32:q.i32_ne,f32:q.f32_ne,f64:q.f64_ne},"|":{i32:q.i32_or},"&":{i32:q.i32_and},"^":{i32:q.i32_xor},"<<":{i32:q.i32_shl},">>":{i32:q.i32_shr_s},">>>":{i32:q.i32_shr_u}}[Z.operator];if(!_)return $.errors.push(`Unsupported operator: ${Z.operator}`),[q.f64_const,...H1(0)];let D=_[W]??_.f64??_.i32;if(D===void 0)return $.errors.push(`Operator ${Z.operator} not supported for type ${W}`),[q.f64_const,...H1(0)];return[...G,...J,D]}function O8(Z,$){let X=i(Z.argument,$),K=c(Z.argument,$);switch(Z.operator){case"-":if(K==="i32")return[q.i32_const,0,...X,q.i32_sub];else if(K==="f32")return[...X,q.f32_neg];else return[...X,q.f64_neg];case"!":return[...X,q.i32_eqz];case"~":return[...X,q.i32_const,...c1(-1),q.i32_xor];default:return $.errors.push(`Unsupported unary operator: ${Z.operator}`),X}}function N8(Z,$){if(Z.left.type==="MemberExpression")return T8(Z.left,Z.right,Z.operator,$);if(Z.left.type!=="Identifier")return $.errors.push("Assignment target must be identifier or array element"),[];let X=Z.left.name,K=w1($,X);if(!K)return $.errors.push(`Unknown variable: ${X}`),[];let Q=[];if(Z.operator==="="){Q.push(...i(Z.right,$));let H=c(Z.right,$);if(K.type==="f64"&&H==="i32")Q.push(q.f64_convert_i32_s);else if(K.type==="f64"&&H==="f32")Q.push(q.f64_promote_f32);else if(K.type==="i32"&&H==="f64")Q.push(q.i32_trunc_f64_s);else if(K.type==="i32"&&H==="f32")Q.push(q.i32_trunc_f32_s);else if(K.type==="f32"&&H==="i32")Q.push(q.f32_convert_i32_s);else if(K.type==="f32"&&H==="f64")Q.push(q.f32_demote_f64)}else{let H=c(Z.right,$),Y=K.type;if(H==="f64"||K.type==="f64")Y="f64";else if(H==="f32"||K.type==="f32")Y="f32";if(Q.push(q.local_get,...b(K.index)),Y==="f64"&&K.type==="i32")Q.push(q.f64_convert_i32_s);else if(Y==="f64"&&K.type==="f32")Q.push(q.f64_promote_f32);else if(Y==="f32"&&K.type==="i32")Q.push(q.f32_convert_i32_s);if(Q.push(...i(Z.right,$)),Y==="f64"&&H==="i32")Q.push(q.f64_convert_i32_s);else if(Y==="f64"&&H==="f32")Q.push(q.f64_promote_f32);else if(Y==="f32"&&H==="i32")Q.push(q.f32_convert_i32_s);let z=Z.operator.slice(0,-1),G={"+":{i32:q.i32_add,f32:q.f32_add,f64:q.f64_add},"-":{i32:q.i32_sub,f32:q.f32_sub,f64:q.f64_sub},"*":{i32:q.i32_mul,f32:q.f32_mul,f64:q.f64_mul},"/":{i32:q.i32_div_s,f32:q.f32_div,f64:q.f64_div}}[z]?.[Y];if(!G)return $.errors.push(`Unsupported compound assignment: ${Z.operator}`),[];if(Q.push(G),K.type==="i32"&&Y==="f64")Q.push(q.i32_trunc_f64_s);else if(K.type==="i32"&&Y==="f32")Q.push(q.i32_trunc_f32_s);else if(K.type==="f32"&&Y==="f64")Q.push(q.f32_demote_f64)}return Q.push(q.local_tee,...b(K.index)),Q}function E8(Z,$){if(Z.argument.type!=="Identifier")return $.errors.push("Update expression argument must be identifier"),[];let X=Z.argument.name,K=w1($,X);if(!K)return $.errors.push(`Unknown variable: ${X}`),[];let Q=[],H=K.type==="i32";if(Z.prefix){if(Q.push(q.local_get,...b(K.index)),H)Q.push(q.i32_const,1),Q.push(Z.operator==="++"?q.i32_add:q.i32_sub);else Q.push(q.f64_const,...H1(1)),Q.push(Z.operator==="++"?q.f64_add:q.f64_sub);Q.push(q.local_tee,...b(K.index))}else{if(Q.push(q.local_get,...b(K.index)),Q.push(q.local_get,...b(K.index)),H)Q.push(q.i32_const,1),Q.push(Z.operator==="++"?q.i32_add:q.i32_sub);else Q.push(q.f64_const,...H1(1)),Q.push(Z.operator==="++"?q.f64_add:q.f64_sub);Q.push(q.local_set,...b(K.index))}return Q}function S8(Z,$){if(Z.object.type!=="Identifier")return $.errors.push("Array access requires identifier"),[];let X=Z.object.name,K=$.params.find((G)=>G.name===X);if(!K?.isArray||!K.arrayType)return $.errors.push(`${X} is not a typed array parameter`),[];let Q=U0[K.arrayType];if(!Q)return $.errors.push(`Unknown array type: ${K.arrayType}`),[];$.needsMemory=!0;let H=[],Y=w1($,X);if(!Y)return $.errors.push(`Unknown array: ${X}`),[];if(H.push(q.local_get,...b(Y.index)),!Z.computed||!Z.property)return $.errors.push("Array access requires computed index"),[];let z=i(Z.property,$),W=c(Z.property,$);if(H.push(...z),W==="f64")H.push(q.i32_trunc_f64_s);if(Q.bytesPerElement>1)H.push(q.i32_const,...c1(Q.bytesPerElement)),H.push(q.i32_mul);return H.push(q.i32_add),H.push(Q.loadOp,0,0),H}function T8(Z,$,X,K){if(Z.object.type!=="Identifier")return K.errors.push("Array store requires identifier"),[];let Q=Z.object.name,H=K.params.find((I)=>I.name===Q);if(!H?.isArray||!H.arrayType)return K.errors.push(`${Q} is not a typed array parameter`),[];let Y=U0[H.arrayType];if(!Y)return K.errors.push(`Unknown array type: ${H.arrayType}`),[];K.needsMemory=!0;let z=[],W=w1(K,Q);if(!W)return[];if(!Z.computed||!Z.property)return K.errors.push("Array store requires computed index"),[];let G=i(Z.property,K),J=c(Z.property,K),U=()=>{let I=[];if(I.push(q.local_get,...b(W.index)),I.push(...G),J==="f64")I.push(q.i32_trunc_f64_s);if(Y.bytesPerElement>1)I.push(q.i32_const,...c1(Y.bytesPerElement)),I.push(q.i32_mul);return I.push(q.i32_add),I};if(X==="=")z.push(...i($,K));else{let I=q0(K,`__addr_${K.nextLocalIndex}`,"i32");z.push(...U()),z.push(q.local_tee,...b(I)),z.push(Y.loadOp,0,0),z.push(...i($,K));let B=c($,K);if(Y.elementType==="f32"&&B==="f64")z.push(q.f32_demote_f64);else if(Y.elementType==="f64"&&B==="f32")z.push(q.f64_promote_f32);else if(Y.elementType==="f32"&&B==="i32")z.push(q.f32_convert_i32_s);else if(Y.elementType==="f64"&&B==="i32")z.push(q.f64_convert_i32_s);else if(Y.elementType==="i32"&&B==="f64")z.push(q.i32_trunc_f64_s);else if(Y.elementType==="i32"&&B==="f32")z.push(q.i32_trunc_f32_s);let A=X.slice(0,-1),j={"+":Y.elementType==="i32"?q.i32_add:Y.elementType==="f32"?q.f32_add:q.f64_add,"-":Y.elementType==="i32"?q.i32_sub:Y.elementType==="f32"?q.f32_sub:q.f64_sub,"*":Y.elementType==="i32"?q.i32_mul:Y.elementType==="f32"?q.f32_mul:q.f64_mul};z.push(j[A]??q.f64_add);let P=q0(K,`__val_${K.nextLocalIndex}`,Y.elementType);return z.push(q.local_set,...b(P)),z.push(q.local_get,...b(I)),z.push(q.local_get,...b(P)),z.push(Y.storeOp,0,0),z.push(q.local_get,...b(P)),z}let _=c($,K);if(Y.elementType==="f32"&&_==="f64")z.push(q.f32_demote_f64);else if(Y.elementType==="f64"&&_==="f32")z.push(q.f64_promote_f32);else if(Y.elementType==="i32"&&_==="f64")z.push(q.i32_trunc_f64_s);let D=q0(K,`__tmp_${K.nextLocalIndex}`,Y.elementType);if(z.push(q.local_set,...b(D)),z.push(q.local_get,...b(W.index)),z.push(...G),J==="f64")z.push(q.i32_trunc_f64_s);if(Y.bytesPerElement>1)z.push(q.i32_const,...c1(Y.bytesPerElement)),z.push(q.i32_mul);return z.push(q.i32_add),z.push(q.local_get,...b(D)),z.push(Y.storeOp,0,0),z.push(q.local_get,...b(D)),z}function k8(Z,$){if(Z.callee.type==="MemberExpression"){let X=Z.callee;if(X.object.type==="Identifier"&&X.object.name==="Math"&&X.property.type==="Identifier"){let K=X.property.name;return g8(K,Z.arguments,$)}}return $.errors.push(`Unsupported function call: ${Z.callee.type}`),[q.f64_const,...H1(0)]}function g8(Z,$,X){let K=[];for(let z of $){K.push(...i(z,X));let W=c(z,X);if(W==="i32")K.push(q.f64_convert_i32_s);else if(W==="f32")K.push(q.f64_promote_f32)}let H={abs:q.f64_abs,ceil:q.f64_ceil,floor:q.f64_floor,trunc:q.f64_trunc,sqrt:q.f64_sqrt,min:q.f64_min,max:q.f64_max}[Z];if(H!==void 0)return K.push(H),K;if(["sin","cos","tan","asin","acos","atan","atan2","exp","log","pow"].includes(Z))return X.needsMathImports.add(Z),X.errors.push(`Math.${Z} requires JS import (not yet implemented)`),[q.f64_const,...H1(0)];return X.errors.push(`Unknown Math method: ${Z}`),[q.f64_const,...H1(0)]}function Q6(Z){let $=Z.split(":").map((H)=>H.trim()),X=$[0];if($.length===1)return{name:X,type:"f64"};let K=$[1];if(U0[K])return{name:X,type:"i32",isArray:!0,arrayType:K};return{name:X,type:{i32:"i32",i64:"i64",f32:"f32",f64:"f64",number:"f64",int:"i32"}[K]??"f64"}}function b8(Z,$,X,K,Q){let H=[0,97,115,109,1,0,0,0],Y=Z.map((P)=>Q1[P.type]),z=Q?[1,Q1.f64]:[0],W=p1(i1.type,[1,96,...b(Z.length),...Y,...z]),G=[],J=[];if(K)J=p1(i1.import,[1,...K4("env"),...K4("memory"),2,0,1]);let U=p1(i1.function,[1,0]),_=p1(i1.export,[1,...K4("compute"),0,0]),D=[];if(X.length>0){let P=X[0],N=1;for(let M=1;M<X.length;M++)if(X[M]===P)N++;else D.push([...b(N),Q1[P]]),P=X[M],N=1;D.push([...b(N),Q1[P]])}let B=[...[...b(D.length),...D.flat()],...$,q.end],A=p1(i1.code,[1,...b(B.length),...B]),j=[...H,...W];if(J.length>0)j.push(...J);return j.push(...U,..._,...A),j}function D0(Z){try{let $=Z.captures.map(Q6),X;try{let G=`function __wasm__(${$.map((J)=>J.name).join(", ")}) { ${Z.body} }`;X=K6.parse(G,{ecmaVersion:2022})}catch(G){return{bytes:new Uint8Array,warnings:[],success:!1,error:`Parse error: ${G.message}`}}let Q=X.body[0].body.body,H=w8($),Y=[];for(let G of Q)Y.push(...S1(G,H));if(H.errors.length>0)return{bytes:new Uint8Array,warnings:H.warnings,success:!1,error:H.errors.join("; ")};let z=b8($,Y,H.localTypes,H.needsMemory,H.hasReturn),W=F8(Y,$,H.localTypes);return{bytes:new Uint8Array(z),warnings:H.warnings,success:!0,needsMemory:H.needsMemory,wat:W}}catch($){return{bytes:new Uint8Array,warnings:[],success:!1,error:$.message}}}async function H6(Z,$){let X={};if($)X.env={memory:$};let K=await WebAssembly.compile(Z);return WebAssembly.instantiate(K,X)}async function f8(Z){let $=D0(Z);if(!$.success)return{fn:()=>0,success:!1,error:$.error};try{let X;if($.needsMemory)X=new WebAssembly.Memory({initial:256});let Q=(await H6($.bytes,X)).exports.compute,H=Z.captures.map(Q6);if(!H.some((W)=>W.isArray))return{fn:Q,memory:X,success:!0};return{fn:(...W)=>{if(!X)throw Error("Memory not initialized");let G=new Uint8Array(X.buffer),J=0,U=[];for(let D=0;D<H.length;D++){let I=H[D],B=W[D];if(I.isArray&&B instanceof Object&&"buffer"in B){let A=B,j=new Uint8Array(A.buffer,A.byteOffset,A.byteLength);G.set(j,J),U.push(J),J+=j.length,J=J+7&-8}else U.push(B)}let _=Q(...U);J=0;for(let D=0;D<H.length;D++){let I=H[D],B=W[D];if(I.isArray&&B instanceof Object&&"buffer"in B){let A=B,j=new Uint8Array(A.buffer,A.byteOffset,A.byteLength);j.set(G.slice(J,J+j.length)),J+=j.length,J=J+7&-8}}return _},memory:X,success:!0}}catch(X){return{fn:()=>0,success:!1,error:X.message}}}async function Y6(Z){let $=await f8(Z);if(!$.success)return console.warn(`WASM compilation failed for ${Z.id}:`,$.error),!1;return globalThis[Z.id]=$.fn,!0}async function v8(Z){let $=0,X=0,K=[];for(let Q of Z)if(await Y6(Q))$++;else X++,K.push(`Failed to compile ${Q.id}`);return{compiled:$,failed:X,errors:K}}function h8(Z,$,X,K){let Q=[],H=u1($,Z),Y={},z=!1,W,G;if(Z.params.length===1&&(Z.params[0].type==="ObjectPattern"||Z.params[0].type==="AssignmentPattern"&&Z.params[0].left.type==="ObjectPattern")){z=!0;let _=Z.params[0],D=_.type==="ObjectPattern"?_:_.left,I=I1(D,X);if(I.type.kind==="object"&&I.type.destructuredParams){W={},G=new Set;for(let[B,A]of Object.entries(I.type.destructuredParams))if(Y[B]={...A,description:H.params[B]},W[B]=A.type,A.required)G.add(B)}}else for(let _ of Z.params)if(_.type==="Identifier"){let D=I1(_,X);Y[_.name]={...D,required:X.has(_.name),description:H.params[_.name]}}else if(_.type==="AssignmentPattern"&&_.left.type==="Identifier"){let D=I1(_,X);Y[_.left.name]={...D,required:X.has(_.left.name),description:H.params[_.left.name]}}else if(_.type==="ObjectPattern"){let D=I1(_,X);if(D.type.kind==="object"&&D.type.destructuredParams)for(let[I,B]of Object.entries(D.type.destructuredParams))Y[I]={...B,description:H.params[I]}}let J;if(K)try{let _=y8(K,0,{ecmaVersion:2022});J=X1(_)}catch{J={kind:"any"},Q.push(`Could not parse return type: ${K}`)}return{types:{name:Z.id?.name||"anonymous",params:Y,returns:J,description:H.description,isDestructuredParam:z,destructuredShape:W,destructuredRequired:G},warnings:Q}}function x8(Z,$,X){let K=[],Q=X?`${X}:`:"",H=X?`${X}:${Z}`:Z;if(K.push(`__tjs.pushStack('${H}');`),$.isDestructuredParam&&$.destructuredShape){let z=$.destructuredShape,W=$.destructuredRequired||new Set,G=Object.keys(z);if(G.length===0)return null;for(let J of G)K.push(`if (${J} instanceof Error) return ${J};`);for(let[J,U]of Object.entries(z)){let _=W.has(J),D=`${Q}${Z}.${J}`,I=z6(J,U);if(I){let B=U.kind;if(_)K.push(`if (${I}) return __tjs.typeError('${D}', '${B}', ${J});`);else K.push(`if (${J} !== undefined && ${I}) return __tjs.typeError('${D}', '${B}', ${J});`)}}return K.length>0?K.join(`
|
|
140
140
|
`):null}let Y=Object.entries($.params);if(Y.length===0)return null;for(let[z]of Y)K.push(`if (${z} instanceof Error) return ${z};`);for(let[z,W]of Y){let G=`${Q}${Z}.${z}`,J=z6(z,W.type);if(J){let U=W.type.kind;if(W.required)K.push(`if (${J}) return __tjs.typeError('${G}', '${U}', ${z});`);else K.push(`if (${z} !== undefined && ${J}) return __tjs.typeError('${G}', '${U}', ${z});`)}}return K.length>0?K.join(`
|
|
141
|
-
`):null}function u8(Z,$){let K=new RegExp(`function\\s+${$}\\s*\\([^)]*\\)\\s*(-[>?!])\\s*`,"g").exec(Z);if(!K)return null;let Q=Z.slice(K.index+K[0].length);return G6(Q)}function d8(Z,$){let K=new RegExp(`function\\s+${$}\\s*\\([^)]*\\)\\s*-([>?!])`,"g").exec(Z);if(!K)return;let Q=K[1];if(Q==="?")return"safe";if(Q==="!")return"unsafe";return}function m8(Z){let $=Z.match(/^\/\*\s*tjs\s*<-\s*([^*]+?)\s*\*\//);return $?$[1].trim():void 0}function l8(Z,$){let X=new RegExp(`\\/\\*\\s*line\\s+(\\d+)\\s*\\*\\/\\s*(?:async\\s+)?function\\s+${$}\\s*\\(`,"m"),K=Z.match(X);return K?parseInt(K[1],10):void 0}function a1(Z,$={}){let{filename:X="<source>",runTests:K=!0,debug:Q=!1,resolvedImports:H={}}=$,Y=[],W=m8(Z)||X,{code:G,tests:J,mocks:U,testRunner:_}=$4(Z),{ast:D,originalSource:I,requiredParams:B,unsafeFunctions:A}=W1(G,{filename:X,colonShorthand:!0}),j=i8(D),P=W0(G),N={},M=[];for(let
|
|
142
|
-
${A7}`}),!i4){let j7=`${a0.file}:${a0.line}`,p4=x8(m,
|
|
141
|
+
`):null}function u8(Z,$){let K=new RegExp(`function\\s+${$}\\s*\\([^)]*\\)\\s*(-[>?!])\\s*`,"g").exec(Z);if(!K)return null;let Q=Z.slice(K.index+K[0].length);return G6(Q)}function d8(Z,$){let K=new RegExp(`function\\s+${$}\\s*\\([^)]*\\)\\s*-([>?!])`,"g").exec(Z);if(!K)return;let Q=K[1];if(Q==="?")return"safe";if(Q==="!")return"unsafe";return}function m8(Z){let $=Z.match(/^\/\*\s*tjs\s*<-\s*([^*]+?)\s*\*\//);return $?$[1].trim():void 0}function l8(Z,$){let X=new RegExp(`\\/\\*\\s*line\\s+(\\d+)\\s*\\*\\/\\s*(?:async\\s+)?function\\s+${$}\\s*\\(`,"m"),K=Z.match(X);return K?parseInt(K[1],10):void 0}function a1(Z,$={}){let{filename:X="<source>",runTests:K=!0,debug:Q=!1,resolvedImports:H={}}=$,Y=[],W=m8(Z)||X,{code:G,tests:J,mocks:U,testRunner:_}=$4(Z),{ast:D,originalSource:I,requiredParams:B,unsafeFunctions:A}=W1(G,{filename:X,colonShorthand:!0}),j=i8(D),P=W0(G),N={},M=[];for(let v of j){let m=v.id?.name||"anonymous",j1=u8(G,m),{types:U1,warnings:I7}=h8(v,I,B,j1);Y.push(...I7),N[m]=U1;let i4=P.moduleSafety==="none"||A.has(m),B7=P.safeFunctions.has(m),R7=d8(G,m),M7=l8(Z,m),a0={file:W,line:M7??v.loc?.start.line??0,column:v.loc?.start.column??0},A7=p8(m,U1,{unsafe:i4,safe:B7,returnSafety:R7},{debug:Q,source:a0});if(M.push({position:v.end,text:`
|
|
142
|
+
${A7}`}),!i4){let j7=`${a0.file}:${a0.line}`,p4=x8(m,U1,j7);if(p4&&v.body&&v.body.start!==void 0)M.push({position:v.body.start+1,text:`
|
|
143
143
|
${p4}
|
|
144
|
-
`})}}M.sort((
|
|
145
|
-
`;if(O||S){let m=[O&&"Is",S&&"IsNot"].filter(Boolean).join(", ");
|
|
146
|
-
`}w=
|
|
147
|
-
`+w;let g;if(K){let
|
|
148
|
-
${
|
|
149
|
-
${
|
|
144
|
+
`})}}M.sort((v,m)=>m.position-v.position);let w=P.source;for(let{position:v,text:m}of M)w=w.slice(0,v)+m+w.slice(v);let V=w.includes("__tjs.typeError("),O=w.includes("Is("),S=w.includes("IsNot("),k=P.tjsModes.tjsSafeEval;if(V||O||S||k){let v=`const __tjs = globalThis.__tjs?.createRuntime?.() ?? globalThis.__tjs;
|
|
145
|
+
`;if(O||S){let m=[O&&"Is",S&&"IsNot"].filter(Boolean).join(", ");v+=`const { ${m} } = __tjs ?? {};
|
|
146
|
+
`}w=v+w}if(k)w=`import { Eval, SafeFunction } from 'tjs-lang';
|
|
147
|
+
`+w;let g;if(K){let v=s8(Z);g=a8(J,U,v,w,H);let m=g.filter((j1)=>!j1.passed);if(m.length>0&&K===!0){let j1=m.map((U1)=>{if(U1.isSignatureTest)return` Function signature example is inconsistent:
|
|
148
|
+
${U1.error}`;return` Test '${U1.description}' failed:
|
|
149
|
+
${U1.error}`});throw Error(`Transpile-time test failures:
|
|
150
150
|
${j1.join(`
|
|
151
|
-
`)}`)}}if(K==="only")return{code:"",types:N,metadata:N,testResults:g,testCount:g?.length};let o;if(P.wasmBlocks.length>0){o=[];let
|
|
152
|
-
`+w;o=
|
|
151
|
+
`)}`)}}if(K==="only")return{code:"",types:N,metadata:N,testResults:g,testCount:g?.length};let o;if(P.wasmBlocks.length>0){o=[];let v=e8(P.wasmBlocks);if(v.code)w=v.code+`
|
|
152
|
+
`+w;o=v.results}return{code:w,types:N,metadata:N,warnings:Y.length>0?Y:void 0,testRunner:J.length>0?_:void 0,testCount:J.length>0?J.length:void 0,testResults:g,wasmCompiled:o}}function i8(Z){let $=[];for(let X of Z.body)if(X.type==="FunctionDeclaration")$.push(X);else if(X.type==="ExportNamedDeclaration"&&X.declaration?.type==="FunctionDeclaration")$.push(X.declaration);else if(X.type==="ExportDefaultDeclaration"&&X.declaration?.type==="FunctionDeclaration")$.push(X.declaration);return $}function s1(Z){let $={kind:Z.kind};if(Z.nullable)$.nullable=!0;if(Z.items)$.items=s1(Z.items);if(Z.shape)$.shape=Object.fromEntries(Object.entries(Z.shape).map(([X,K])=>[X,s1(K)]));if(Z.members)$.members=Z.members.map(s1);return $}function p8(Z,$,X={},K={}){let Q={};for(let[Y,z]of Object.entries($.params)){if(Q[Y]={type:s1(z.type),required:z.required},z.default!==void 0)Q[Y].default=z.default;if(z.description)Q[Y].description=z.description}let H={params:Q};if($.returns){if(H.returns={type:s1($.returns)},X.returnSafety==="safe")H.safeReturn=!0;else if(X.returnSafety==="unsafe")H.unsafeReturn=!0}if($.description)H.description=$.description;if(X.unsafe)H.unsafe=!0;if(X.safe)H.safe=!0;if(K.source){let{file:Y,line:z}=K.source;H.source=`${Y}:${z}`}return`${Z}.__tjs = ${JSON.stringify(H,null,2)}`}function z6(Z,$){switch($.kind){case"string":return`typeof ${Z} !== 'string'`;case"number":return`typeof ${Z} !== 'number'`;case"integer":return`(typeof ${Z} !== 'number' || !Number.isInteger(${Z}))`;case"non-negative-integer":return`(typeof ${Z} !== 'number' || !Number.isInteger(${Z}) || ${Z} < 0)`;case"boolean":return`typeof ${Z} !== 'boolean'`;case"null":return`${Z} !== null`;case"undefined":return`${Z} !== undefined`;case"array":return`!Array.isArray(${Z})`;case"object":return`(typeof ${Z} !== 'object' || ${Z} === null || Array.isArray(${Z}))`;case"any":return null;default:return null}}function n8(Z,$,X=0.000000001){if(Z===$)return!0;if(typeof Z==="number"&&typeof $==="number"){if(!Number.isInteger(Z)||!Number.isInteger($)){let K=Math.abs(Z-$),Q=Math.max(Math.abs(Z),Math.abs($),1);return K/Q<X}}return!1}function Q4(Z,$){if(Z===$)return!0;if(n8(Z,$))return!0;if(Z===null||$===null)return Z===$;if(Z===void 0||$===void 0)return Z===$;if(typeof Z!==typeof $)return!1;if(typeof Z!=="object")return!1;if(Array.isArray(Z)&&Array.isArray($)){if(Z.length!==$.length)return!1;return Z.every((Q,H)=>Q4(Q,$[H]))}if(Array.isArray(Z)!==Array.isArray($))return!1;let X=Object.keys(Z),K=Object.keys($);if(X.length!==K.length)return!1;return X.every((Q)=>Q4(Z[Q],$[Q]))}function H4(Z,$,X=""){if($===null){if(Z===null)return{matches:!0};return{matches:!1,error:`Expected null at '${X}', got ${P1(Z)}`}}if($===void 0){if(Z===void 0)return{matches:!0};return{matches:!1,error:`Expected undefined at '${X}', got ${P1(Z)}`}}if(typeof $==="number"){if(typeof Z==="number")return{matches:!0};return{matches:!1,error:`Expected number at '${X}', got ${P1(Z)}`}}if(typeof $==="string"){if(typeof Z==="string")return{matches:!0};return{matches:!1,error:`Expected string at '${X}', got ${P1(Z)}`}}if(typeof $==="boolean"){if(typeof Z==="boolean")return{matches:!0};return{matches:!1,error:`Expected boolean at '${X}', got ${P1(Z)}`}}if(Array.isArray($)){if(!Array.isArray(Z))return{matches:!1,error:`Expected array at '${X}', got ${P1(Z)}`};if($.length===0)return{matches:!0};let K=$[0];for(let Q=0;Q<Z.length;Q++){let H=H4(Z[Q],K,`${X}[${Q}]`);if(!H.matches)return H}return{matches:!0}}if(typeof $==="object"&&$!==null){if(typeof Z!=="object"||Z===null||Array.isArray(Z))return{matches:!1,error:`Expected object at '${X}', got ${P1(Z)}`};for(let K of Object.keys($)){let Q=X?`${X}.${K}`:K;if(!(K in Z))return{matches:!1,error:`Missing property '${Q}'`};let H=H4(Z[K],$[K],Q);if(!H.matches)return H}return{matches:!0}}if(Z===$)return{matches:!0};return{matches:!1,error:`Type mismatch at '${X}'`}}function P1(Z){if(Z===null)return"null";if(Z===void 0)return"undefined";if(Array.isArray(Z))return"array";return typeof Z}function o1(Z,$=0){if(Z===null)return"null";if(Z===void 0)return"undefined";if(typeof Z==="string")return JSON.stringify(Z);if(typeof Z==="number")return String(Z);if(typeof Z==="boolean")return String(Z);if(Array.isArray(Z)){if(Z.length===0)return"[]";if(Z.length<=3)return`[${Z.map((X)=>o1(X,$)).join(", ")}]`;return`[${Z.slice(0,3).map((X)=>o1(X,$)).join(", ")}, ...]`}if(typeof Z==="object"){let X=Object.entries(Z);if(X.length===0)return"{}";let K=(W)=>/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(W)?W:JSON.stringify(W);if(X.length<=2)return`{${X.map(([G,J])=>`${K(G)}: ${o1(J,$)}`).join(", ")}}`;let Q=" ".repeat($+1),H=" ".repeat($),Y=X.slice(0,8).map(([W,G])=>`${Q}${K(W)}: ${o1(G,$+1)}`).join(`,
|
|
153
153
|
`),z=X.length>8?`,
|
|
154
154
|
${Q}...`:"";return`{
|
|
155
155
|
${Y}${z}
|
|
@@ -203,6 +203,41 @@ ${H}}`}return String(Z)}function c8(Z){let $=Z.replace(/\/\*[\s\S]*?\*\//g,(X)=>
|
|
|
203
203
|
if (!__deepEqual(actual, expected)) {
|
|
204
204
|
throw new Error('Expected ' + __format(expected) + ' but got ' + __format(actual))
|
|
205
205
|
}
|
|
206
|
+
},
|
|
207
|
+
toContain(item) {
|
|
208
|
+
if (!Array.isArray(actual) || !actual.some(function(v) { return __deepEqual(v, item) })) {
|
|
209
|
+
throw new Error('Expected ' + __format(actual) + ' to contain ' + __format(item))
|
|
210
|
+
}
|
|
211
|
+
},
|
|
212
|
+
toBeTruthy() {
|
|
213
|
+
if (!actual) {
|
|
214
|
+
throw new Error('Expected ' + __format(actual) + ' to be truthy')
|
|
215
|
+
}
|
|
216
|
+
},
|
|
217
|
+
toBeFalsy() {
|
|
218
|
+
if (actual) {
|
|
219
|
+
throw new Error('Expected ' + __format(actual) + ' to be falsy')
|
|
220
|
+
}
|
|
221
|
+
},
|
|
222
|
+
toBeNull() {
|
|
223
|
+
if (actual !== null) {
|
|
224
|
+
throw new Error('Expected null but got ' + __format(actual))
|
|
225
|
+
}
|
|
226
|
+
},
|
|
227
|
+
toBeUndefined() {
|
|
228
|
+
if (actual !== undefined) {
|
|
229
|
+
throw new Error('Expected undefined but got ' + __format(actual))
|
|
230
|
+
}
|
|
231
|
+
},
|
|
232
|
+
toBeGreaterThan(n) {
|
|
233
|
+
if (!(actual > n)) {
|
|
234
|
+
throw new Error('Expected ' + __format(actual) + ' to be greater than ' + n)
|
|
235
|
+
}
|
|
236
|
+
},
|
|
237
|
+
toBeLessThan(n) {
|
|
238
|
+
if (!(actual < n)) {
|
|
239
|
+
throw new Error('Expected ' + __format(actual) + ' to be less than ' + n)
|
|
240
|
+
}
|
|
206
241
|
}
|
|
207
242
|
}
|
|
208
243
|
}
|
|
@@ -254,7 +289,7 @@ for(const{id,b64,c,m}of __wasmBlocks){
|
|
|
254
289
|
if(p.a&&a?.buffer){const ab=new Uint8Array(a.buffer,a.byteOffset,a.byteLength);ab.set(mv.slice(off,off+ab.length));off+=ab.length;off=(off+7)&~7}}
|
|
255
290
|
return r};
|
|
256
291
|
}})();
|
|
257
|
-
`.trim(),results:$}}import R from"typescript";import{validate as _6,s as b0}from"tosijs-schema";import{validate as G4,s as I0}from"tosijs-schema";function B1(Z){return Z!==null&&typeof Z==="object"&&"__runtimeType"in Z&&Z.__runtimeType===!0}function W6(Z){return Z!==null&&typeof Z==="object"&&"schema"in Z&&typeof Z.schema==="object"}function ZZ(Z){return Z!==null&&typeof Z==="object"&&"type"in Z&&typeof Z.type==="string"}function d(Z,$,X,K){let Q,H,Y,z=X,W=K;if(typeof Z==="string")if(Q=Z,typeof $==="function"){if(H=$,z!==void 0)Y=I0.infer(z)}else if($===void 0&&z!==void 0)Y=I0.infer(z);else if(W6($))Y=$;else if(ZZ($))Y=$;else if($!==void 0)z=$,W=z,Y=I0.infer(z);else throw Error("Type(description) requires a predicate, schema, or example");else{if(W6(Z))Y=Z;else Y=Z;Q=XZ(Y)}return{description:Q,check:(J)=>{if(H)return H(J);if(Y)return G4(J,Y);return!1},schema:Y,predicate:H,example:z,default:W,__runtimeType:!0}}function XZ(Z){let $=Z?.schema??Z;if($&&typeof $==="object"&&"type"in $){let X=$;switch(X.type){case"string":if(X.format)return`string (${X.format})`;if(X.pattern)return`string matching ${X.pattern}`;if(X.minLength!==void 0&&X.maxLength!==void 0)return`string (${X.minLength}-${X.maxLength} chars)`;return"string";case"number":case"integer":if(X.minimum!==void 0&&X.maximum!==void 0)return`${X.type} (${X.minimum}-${X.maximum})`;if(X.minimum!==void 0)return`${X.type} >= ${X.minimum}`;if(X.maximum!==void 0)return`${X.type} <= ${X.maximum}`;return X.type;case"boolean":return"boolean";case"array":return"array";case"object":return"object";case"null":return"null"}}return"value"}var B0=d("string",(Z)=>typeof Z==="string"),R0=d("number",(Z)=>typeof Z==="number"),M0=d("boolean",(Z)=>typeof Z==="boolean"),A0=d("integer",(Z)=>typeof Z==="number"&&Number.isInteger(Z)),j0=d("positive integer",(Z)=>typeof Z==="number"&&Number.isInteger(Z)&&Z>0),F0=d("non-empty string",(Z)=>typeof Z==="string"&&Z.length>0),w0=d("email address",(Z)=>typeof Z==="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Z)),W4=(Z)=>{try{return new URL(Z),!0}catch{return!1}},P0=d("URL",(Z)=>typeof Z==="string"&&W4(Z)),C0=d("UUID",(Z)=>typeof Z==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(Z)),J4=(Z)=>{let $=new Date(Z);return!isNaN($.getTime())&&Z.includes("T")},_4=(Z)=>{if(!/^\d{4}-\d{2}-\d{2}$/.test(Z))return!1;let $=new Date(Z+"T00:00:00Z");return!isNaN($.getTime())},L4=d("ISO 8601 timestamp",(Z)=>typeof Z==="string"&&J4(Z)),q4=d("date (YYYY-MM-DD)",(Z)=>typeof Z==="string"&&_4(Z));function V0(Z){return d(`${Z.description} or null`,($)=>$===null||Z.check($))}function O0(Z){return d(`${Z.description} (optional)`,($)=>$===null||$===void 0||Z.check($))}function N0(Z,$,...X){if(typeof Z==="string"&&Array.isArray($)){let H=Z,Y=$,z=new Set(Y);return{description:H,check:(G)=>z.has(G),__runtimeType:!0,values:Y}}let K=[];if(B1(Z))K.push(Z);if(B1($))K.push($);K.push(...X);let Q=K.map((H)=>H.description).join(" | ");return d(Q,(H)=>K.some((Y)=>Y.check(H)))}function E0(Z){return d(`array of ${Z.description}`,($)=>Array.isArray($)&&$.every((X)=>Z.check(X)))}function $Z(Z){if(B1(Z))return(X)=>Z.check(X);if(Z&&typeof Z==="object"&&"schema"in Z)return(X)=>G4(X,Z);let $=I0.infer(Z);return(X)=>G4(X,$)}function T1(Z,$,X){let K=[],Q=[];for(let Y of Z)if(typeof Y==="string")K.push(Y),Q.push(void 0);else K.push(Y[0]),Q.push(Y[1]);let H=(...Y)=>{let z=K.map((G,J)=>{let U=J<Y.length?Y[J]:Q[J];if(U===void 0)return()=>!0;return $Z(U)}),W=X;return K.forEach((G,J)=>{let U=J<Y.length?Y[J]:Q[J],_="any";if(B1(U))_=U.description;else if(U!==void 0)_=typeof U==="string"?"string":JSON.stringify(U);W=W.replace(new RegExp(`\\b${G}\\b`,"g"),_)}),d(W,(G)=>$(G,...z))};return H.params=K,H.description=X,H}var S0=T1(["T","U"],(Z,$,X)=>Array.isArray(Z)&&Z.length===2&&$(Z[0])&&X(Z[1]),"Pair<T, U>"),T0=T1(["V"],(Z,$)=>typeof Z==="object"&&Z!==null&&!Array.isArray(Z)&&Object.values(Z).every($),"Record<string, V>");function k0(Z,$){let X=Object.values($),K=new Set(X),Q=Object.keys($),H={};for(let[z,W]of Object.entries($))H[W]=z;return{description:Z,check:(z)=>K.has(z),__runtimeType:!0,members:$,names:H,values:X,keys:Q}}var QZ=J6(),a=QZ.version;function v0(Z){let[$=0,X=0,K=0]=Z.split(".").map(Number);return{major:$,minor:X,patch:K}}function U4(Z,$){let X=v0(Z),K=v0($);if(X.major!==K.major)return X.major<K.major?-1:1;if(X.minor!==K.minor)return X.minor<K.minor?-1:1;if(X.patch!==K.patch)return X.patch<K.patch?-1:1;return 0}function D4(Z,$){let X=v0(Z),K=v0($);return X.major===K.major}class O1 extends Error{path;expected;actual;callStack;constructor(Z,$,X,K,Q){super(Z);if(this.name="MonadicError",this.path=$,this.expected=X,this.actual=K,this.callStack=Q,Error.captureStackTrace)Error.captureStackTrace(this,O1)}}function HZ(Z,$,X){let K=X===null?"null":typeof X,Q=t.debug?U6():void 0;return new O1(`Expected ${$} for '${Z}', got ${K}`,Z,$,K,Q)}function L6(Z){return Z instanceof O1}var I4={debug:!1,safety:"inputs",requireReturnTypes:!1,maxStackSize:100},t={...I4},_1=[],g1=0;function YZ(){g1++}function zZ(){if(g1>0)g1--}function GZ(){return g1>0}function WZ(Z){t={...t,...Z}}function JZ(){return{...t}}function q6(Z){if(t.debug&&Z){_1.push(Z);let $=t.maxStackSize??100;while(_1.length>$)_1.shift()}}function g0(){if(t.debug)_1.pop()}function U6(){return[..._1]}function _Z(){t={...I4},_1.length=0,g1=0}function r1(Z,$){if(Z!==null&&typeof Z==="object"&&typeof Z.Equals==="function")return Z.Equals($);if($!==null&&typeof $==="object"&&typeof $.Equals==="function")return $.Equals(Z);if(Z===$)return!0;if((Z===null||Z===void 0)&&($===null||$===void 0))return!0;if(Z===null||Z===void 0||$===null||$===void 0)return!1;if(typeof Z!==typeof $)return!1;if(typeof Z!=="object")return!1;if(Array.isArray(Z)&&Array.isArray($)){if(Z.length!==$.length)return!1;return Z.every((Q,H)=>r1(Q,$[H]))}if(Array.isArray(Z)!==Array.isArray($))return!1;let X=Object.keys(Z),K=Object.keys($);if(X.length!==K.length)return!1;return X.every((Q)=>r1(Z[Q],$[Q]))}function D6(Z,$){return!r1(Z,$)}function J1(Z){return Z!==null&&typeof Z==="object"&&Z.$error===!0}function z1(Z,$){let X={$error:!0,message:Z,...$};if(t.debug&&_1.length>0){let K=$?.path?[..._1,$.path]:[..._1];X.stack=K}return X}function B4(Z,$){if(Z.length===0)return z1("Unknown error");if(Z.length===1)return Z[0];let X=Z.map((Q)=>{if(Q.path){let H=Q.path.split(".");return H[H.length-1]}return"unknown"}).join(", "),K=`Multiple parameter errors in ${$||"function"}: ${X}`;return z1(K,{path:$,errors:Z})}function k1(Z){if(Z===null)return"null";if(Z===void 0)return"undefined";if(Array.isArray(Z))return"array";let $=typeof Z;if($!=="object")return $;let X=Z.constructor?.name;if(X&&X!=="Object")return X;return"object"}function I6(Z,$){if(Z===null||Z===void 0)return!1;if(typeof Z!=="object"&&typeof Z!=="function")return!1;let X=Z;while(X!==null){if(X.constructor?.name===$)return!0;X=Object.getPrototypeOf(X)}return!1}function V1(Z,$,X){if(J1(Z))return Z;if(typeof $==="object"&&$!==null&&"check"in $){if($.check(Z))return null;return z1(`Expected ${$.description} but got ${k1(Z)}`,{path:X,expected:$.description,actual:k1(Z)})}let K=k1(Z);if($==="any")return null;if($===K)return null;if($==="number"&&K==="number")return null;if($==="integer"&&K==="number"&&Number.isInteger(Z))return null;if($==="object"&&K==="object")return null;return z1(`Expected ${$} but got ${K}`,{path:X,expected:$,actual:K})}function R4(Z,$,X){for(let[K,Q]of Object.entries($.params)){let H=Z[K];if(J1(H))return H;if(Q.required&&H===void 0){let z=typeof Q.type==="string"?Q.type:Q.type.description;return z1(`Missing required parameter '${K}'`,{path:X?`${X}.${K}`:K,expected:z,actual:"undefined",loc:Q.loc})}if(H===void 0)continue;let Y=V1(H,Q.type,X?`${X}.${K}`:K);if(Y){if(Q.loc)Y.loc=Q.loc;return Y}}return null}function M4(Z,$){if(Z.__tjs=$,!($.safe||$.safeReturn||t.safety!=="none"&&!$.unsafe||$.returns&&t.safety==="all"&&!$.unsafeReturn))return Z;let K=!!$.returns,Q=!!$.unsafe,H=!!$.safe,Y=!!$.unsafeReturn,z=!!$.safeReturn,W=Object.entries($.params),G=W.length,J=Z.name||$.name||"anonymous",U=function(..._){if(g1>0)return Z.apply(this,_);let D=H||!Q&&t.safety!=="none",I=K&&(z||!Y&&t.safety==="all");if(!D&&!I)return Z.apply(this,_);if(_.length>0&&J1(_[0]))return _[0];if(D){let B=_.length===1&&typeof _[0]==="object"&&_[0]!==null&&!Array.isArray(_[0]),A=[];if(!B)for(let j=0;j<G;j++){let[P,N]=W[j],M=_[j];if(J1(M)){A.push(M);continue}if(N.required&&M===void 0){A.push(z1(`Missing required parameter '${P}'`,{path:`${J}.${P}`,expected:typeof N.type==="string"?N.type:N.type?.description||"value",actual:"undefined",loc:N.loc}));continue}if(M!==void 0){let w=V1(M,N.type,`${J}.${P}`);if(w){if(N.loc)w.loc=N.loc;A.push(w)}}}else{let j=_[0];for(let P=0;P<G;P++){let[N,M]=W[P],w=j[N];if(J1(w)){A.push(w);continue}if(M.required&&w===void 0){A.push(z1(`Missing required parameter '${N}'`,{path:`${J}.${N}`,expected:typeof M.type==="string"?M.type:M.type?.description||"value",actual:"undefined",loc:M.loc}));continue}if(w!==void 0){let V=V1(w,M.type,`${J}.${N}`);if(V){if(M.loc)V.loc=M.loc;A.push(V)}}}}if(A.length>0)return B4(A,J)}q6(J);try{let B=Z.apply(this,_);if(I&&$.returns&&!J1(B)){let A=V1(B,$.returns.type,`${J}()`);if(A)return g0(),A}return g0(),B}catch(B){return g0(),z1(B.message||String(B),{path:J,cause:B})}};return Object.defineProperty(U,"name",{value:Z.name}),U.__tjs=$,U}function B6(Z){let $=new Proxy(Z,{construct(X,K,Q){return Reflect.construct(X,K,Q)},apply(X,K,Q){return Reflect.construct(X,Q)}});Object.defineProperty($,"name",{value:Z.name});for(let X of Object.getOwnPropertyNames(Z))if(X!=="length"&&X!=="name"&&X!=="prototype")Object.defineProperty($,X,Object.getOwnPropertyDescriptor(Z,X));return $}function LZ(){let Z={...t},$=[],X=0;function K(I){Z={...Z,...I}}function Q(){return{...Z}}function H(I){if(Z.debug&&I){$.push(I);let B=Z.maxStackSize??100;while($.length>B)$.shift()}}function Y(){if(Z.debug)$.pop()}function z(){return[...$]}function W(){Z={...I4},$.length=0,X=0}function G(){X++}function J(){if(X>0)X--}function U(){return X>0}function _(I,B,A){let j=A===null?"null":typeof A,P=Z.debug?z():void 0;return new O1(`Expected ${B} for '${I}', got ${j}`,I,B,j,P)}function D(I,B){let A={$error:!0,message:I,...B};if(Z.debug&&$.length>0){let j=B?.path?[...$,B.path]:[...$];A.stack=j}return A}return{version:a,MonadicError:O1,typeError:_,isMonadicError:L6,isError:J1,error:D,composeErrors:B4,typeOf:k1,isNativeType:I6,checkType:V1,validateArgs:R4,wrap:M4,wrapClass:B6,compareVersions:U4,versionsCompatible:D4,configure:K,getConfig:Q,pushStack:H,popStack:Y,getStack:z,resetRuntime:W,enterUnsafe:G,exitUnsafe:J,isUnsafeMode:U,validate:_6,infer:b0.infer.bind(b0),Type:d,isRuntimeType:B1,Union:N0,Generic:T1,Enum:k0,Nullable:V0,Optional:O0,TArray:E0,TString:B0,TNumber:R0,TBoolean:M0,TInteger:A0,TPositiveInt:j0,TNonEmptyString:F0,TEmail:w0,TUrl:P0,TUuid:C0,TPair:S0,TRecord:T0,Is:r1,IsNot:D6}}var C1={version:a,MonadicError:O1,typeError:HZ,isMonadicError:L6,isError:J1,error:z1,composeErrors:B4,typeOf:k1,isNativeType:I6,checkType:V1,validateArgs:R4,wrap:M4,wrapClass:B6,compareVersions:U4,versionsCompatible:D4,configure:WZ,getConfig:JZ,pushStack:q6,popStack:g0,getStack:U6,resetRuntime:_Z,enterUnsafe:YZ,exitUnsafe:zZ,isUnsafeMode:GZ,createRuntime:LZ,validate:_6,infer:b0.infer.bind(b0),Type:d,isRuntimeType:B1,Union:N0,Generic:T1,Enum:k0,Nullable:V0,Optional:O0,TArray:E0,TString:B0,TNumber:R0,TBoolean:M0,TInteger:A0,TPositiveInt:j0,TNonEmptyString:F0,TEmail:w0,TUrl:P0,TUuid:C0,Timestamp:L4,LegalDate:q4,TPair:S0,TRecord:T0,Is:r1,IsNot:D6};function qZ(){let Z=globalThis;if(Z.__tjs){let $=Z.__tjs.version;if(typeof $!=="string")return Z.__tjs=C1,C1;let X=U4(a,$);if(X===0)return Z.__tjs;if(D4(a,$))if(X>0)console.info(`TJS runtime: upgrading ${$} → ${a}`),Z.__tjs=C1;else console.info(`TJS runtime: keeping ${$} (newer than ${a})`);else if(console.warn(`TJS runtime version conflict: ${$} vs ${a} (major version mismatch)`),X>0)console.warn(`Upgrading to ${a} - check for breaking changes`),Z.__tjs=C1;return Z.__tjs}return Z.__tjs=C1,C1}function UZ(Z){return`
|
|
292
|
+
`.trim(),results:$}}import R from"typescript";import{validate as _6,s as b0}from"tosijs-schema";import{validate as G4,s as I0}from"tosijs-schema";function B1(Z){return Z!==null&&typeof Z==="object"&&"__runtimeType"in Z&&Z.__runtimeType===!0}function W6(Z){return Z!==null&&typeof Z==="object"&&"schema"in Z&&typeof Z.schema==="object"}function ZZ(Z){return Z!==null&&typeof Z==="object"&&"type"in Z&&typeof Z.type==="string"}function d(Z,$,X,K){let Q,H,Y,z=X,W=K;if(typeof Z==="string")if(Q=Z,typeof $==="function"){if(H=$,z!==void 0)Y=I0.infer(z)}else if($===void 0&&z!==void 0)Y=I0.infer(z);else if(W6($))Y=$;else if(ZZ($))Y=$;else if($!==void 0)z=$,W=z,Y=I0.infer(z);else throw Error("Type(description) requires a predicate, schema, or example");else{if(W6(Z))Y=Z;else Y=Z;Q=XZ(Y)}let G;if(Y){let U=Y?.schema??Y;if(U&&typeof U==="object"&&Array.isArray(U.examples))G=U.examples}if(z===void 0&&G&&G.length>0)z=G[0];return{description:Q,check:(U)=>{if(H)return H(U);if(Y)return G4(U,Y);return!1},schema:Y,predicate:H,example:z,examples:G,default:W,__runtimeType:!0}}function XZ(Z){let $=Z?.schema??Z;if($&&typeof $==="object"&&"type"in $){let X=$;switch(X.type){case"string":if(X.format)return`string (${X.format})`;if(X.pattern)return`string matching ${X.pattern}`;if(X.minLength!==void 0&&X.maxLength!==void 0)return`string (${X.minLength}-${X.maxLength} chars)`;return"string";case"number":case"integer":if(X.minimum!==void 0&&X.maximum!==void 0)return`${X.type} (${X.minimum}-${X.maximum})`;if(X.minimum!==void 0)return`${X.type} >= ${X.minimum}`;if(X.maximum!==void 0)return`${X.type} <= ${X.maximum}`;return X.type;case"boolean":return"boolean";case"array":return"array";case"object":return"object";case"null":return"null"}}return"value"}var B0=d("string",(Z)=>typeof Z==="string"),R0=d("number",(Z)=>typeof Z==="number"),M0=d("boolean",(Z)=>typeof Z==="boolean"),A0=d("integer",(Z)=>typeof Z==="number"&&Number.isInteger(Z)),j0=d("positive integer",(Z)=>typeof Z==="number"&&Number.isInteger(Z)&&Z>0),F0=d("non-empty string",(Z)=>typeof Z==="string"&&Z.length>0),w0=d("email address",(Z)=>typeof Z==="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Z)),W4=(Z)=>{try{return new URL(Z),!0}catch{return!1}},P0=d("URL",(Z)=>typeof Z==="string"&&W4(Z)),C0=d("UUID",(Z)=>typeof Z==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(Z)),J4=(Z)=>{let $=new Date(Z);return!isNaN($.getTime())&&Z.includes("T")},_4=(Z)=>{if(!/^\d{4}-\d{2}-\d{2}$/.test(Z))return!1;let $=new Date(Z+"T00:00:00Z");return!isNaN($.getTime())},L4=d("ISO 8601 timestamp",(Z)=>typeof Z==="string"&&J4(Z)),q4=d("date (YYYY-MM-DD)",(Z)=>typeof Z==="string"&&_4(Z));function V0(Z){return d(`${Z.description} or null`,($)=>$===null||Z.check($))}function O0(Z){return d(`${Z.description} (optional)`,($)=>$===null||$===void 0||Z.check($))}function N0(Z,$,...X){if(typeof Z==="string"&&Array.isArray($)){let H=Z,Y=$,z=new Set(Y);return{description:H,check:(G)=>z.has(G),__runtimeType:!0,values:Y}}let K=[];if(B1(Z))K.push(Z);if(B1($))K.push($);K.push(...X);let Q=K.map((H)=>H.description).join(" | ");return d(Q,(H)=>K.some((Y)=>Y.check(H)))}function E0(Z){return d(`array of ${Z.description}`,($)=>Array.isArray($)&&$.every((X)=>Z.check(X)))}function $Z(Z){if(B1(Z))return(X)=>Z.check(X);if(Z&&typeof Z==="object"&&"schema"in Z)return(X)=>G4(X,Z);let $=I0.infer(Z);return(X)=>G4(X,$)}function T1(Z,$,X){let K=[],Q=[];for(let Y of Z)if(typeof Y==="string")K.push(Y),Q.push(void 0);else K.push(Y[0]),Q.push(Y[1]);let H=(...Y)=>{let z=K.map((G,J)=>{let U=J<Y.length?Y[J]:Q[J];if(U===void 0)return()=>!0;return $Z(U)}),W=X;return K.forEach((G,J)=>{let U=J<Y.length?Y[J]:Q[J],_="any";if(B1(U))_=U.description;else if(U!==void 0)_=typeof U==="string"?"string":JSON.stringify(U);W=W.replace(new RegExp(`\\b${G}\\b`,"g"),_)}),d(W,(G)=>$(G,...z))};return H.params=K,H.description=X,H}var S0=T1(["T","U"],(Z,$,X)=>Array.isArray(Z)&&Z.length===2&&$(Z[0])&&X(Z[1]),"Pair<T, U>"),T0=T1(["V"],(Z,$)=>typeof Z==="object"&&Z!==null&&!Array.isArray(Z)&&Object.values(Z).every($),"Record<string, V>");function k0(Z,$){let X=Object.values($),K=new Set(X),Q=Object.keys($),H={};for(let[z,W]of Object.entries($))H[W]=z;return{description:Z,check:(z)=>K.has(z),__runtimeType:!0,members:$,names:H,values:X,keys:Q}}var QZ=J6(),a=QZ.version;function f0(Z){let[$=0,X=0,K=0]=Z.split(".").map(Number);return{major:$,minor:X,patch:K}}function U4(Z,$){let X=f0(Z),K=f0($);if(X.major!==K.major)return X.major<K.major?-1:1;if(X.minor!==K.minor)return X.minor<K.minor?-1:1;if(X.patch!==K.patch)return X.patch<K.patch?-1:1;return 0}function D4(Z,$){let X=f0(Z),K=f0($);return X.major===K.major}class O1 extends Error{path;expected;actual;callStack;constructor(Z,$,X,K,Q){super(Z);if(this.name="MonadicError",this.path=$,this.expected=X,this.actual=K,this.callStack=Q,Error.captureStackTrace)Error.captureStackTrace(this,O1)}}function HZ(Z,$,X){let K=X===null?"null":typeof X,Q=t.debug?U6():void 0;return new O1(`Expected ${$} for '${Z}', got ${K}`,Z,$,K,Q)}function L6(Z){return Z instanceof O1}var I4={debug:!1,safety:"inputs",requireReturnTypes:!1,maxStackSize:100},t={...I4},L1=[],g1=0;function YZ(){g1++}function zZ(){if(g1>0)g1--}function GZ(){return g1>0}function WZ(Z){t={...t,...Z}}function JZ(){return{...t}}function q6(Z){if(t.debug&&Z){L1.push(Z);let $=t.maxStackSize??100;while(L1.length>$)L1.shift()}}function g0(){if(t.debug)L1.pop()}function U6(){return[...L1]}function _Z(){t={...I4},L1.length=0,g1=0}function r1(Z,$){if(Z!==null&&typeof Z==="object"&&typeof Z.Equals==="function")return Z.Equals($);if($!==null&&typeof $==="object"&&typeof $.Equals==="function")return $.Equals(Z);if(Z===$)return!0;if((Z===null||Z===void 0)&&($===null||$===void 0))return!0;if(Z===null||Z===void 0||$===null||$===void 0)return!1;if(typeof Z!==typeof $)return!1;if(typeof Z!=="object")return!1;if(Array.isArray(Z)&&Array.isArray($)){if(Z.length!==$.length)return!1;return Z.every((Q,H)=>r1(Q,$[H]))}if(Array.isArray(Z)!==Array.isArray($))return!1;let X=Object.keys(Z),K=Object.keys($);if(X.length!==K.length)return!1;return X.every((Q)=>r1(Z[Q],$[Q]))}function D6(Z,$){return!r1(Z,$)}function _1(Z){return Z!==null&&typeof Z==="object"&&Z.$error===!0}function z1(Z,$){let X={$error:!0,message:Z,...$};if(t.debug&&L1.length>0){let K=$?.path?[...L1,$.path]:[...L1];X.stack=K}return X}function B4(Z,$){if(Z.length===0)return z1("Unknown error");if(Z.length===1)return Z[0];let X=Z.map((Q)=>{if(Q.path){let H=Q.path.split(".");return H[H.length-1]}return"unknown"}).join(", "),K=`Multiple parameter errors in ${$||"function"}: ${X}`;return z1(K,{path:$,errors:Z})}function k1(Z){if(Z===null)return"null";if(Z===void 0)return"undefined";if(Array.isArray(Z))return"array";let $=typeof Z;if($!=="object")return $;let X=Z.constructor?.name;if(X&&X!=="Object")return X;return"object"}function I6(Z,$){if(Z===null||Z===void 0)return!1;if(typeof Z!=="object"&&typeof Z!=="function")return!1;let X=Z;while(X!==null){if(X.constructor?.name===$)return!0;X=Object.getPrototypeOf(X)}return!1}function V1(Z,$,X){if(_1(Z))return Z;if(typeof $==="object"&&$!==null&&"check"in $){if($.check(Z))return null;return z1(`Expected ${$.description} but got ${k1(Z)}`,{path:X,expected:$.description,actual:k1(Z)})}let K=k1(Z);if($==="any")return null;if($===K)return null;if($==="number"&&K==="number")return null;if($==="integer"&&K==="number"&&Number.isInteger(Z))return null;if($==="non-negative-integer"&&K==="number"&&Number.isInteger(Z)&&Z>=0)return null;if($==="object"&&K==="object")return null;return z1(`Expected ${$} but got ${K}`,{path:X,expected:$,actual:K})}function R4(Z,$,X){for(let[K,Q]of Object.entries($.params)){let H=Z[K];if(_1(H))return H;if(Q.required&&H===void 0){let z=typeof Q.type==="string"?Q.type:Q.type.description;return z1(`Missing required parameter '${K}'`,{path:X?`${X}.${K}`:K,expected:z,actual:"undefined",loc:Q.loc})}if(H===void 0)continue;let Y=V1(H,Q.type,X?`${X}.${K}`:K);if(Y){if(Q.loc)Y.loc=Q.loc;return Y}}return null}function M4(Z,$){if(Z.__tjs=$,!($.safe||$.safeReturn||t.safety!=="none"&&!$.unsafe||$.returns&&t.safety==="all"&&!$.unsafeReturn))return Z;let K=!!$.returns,Q=!!$.unsafe,H=!!$.safe,Y=!!$.unsafeReturn,z=!!$.safeReturn,W=Object.entries($.params),G=W.length,J=Z.name||$.name||"anonymous",U=function(..._){if(g1>0)return Z.apply(this,_);let D=H||!Q&&t.safety!=="none",I=K&&(z||!Y&&t.safety==="all");if(!D&&!I)return Z.apply(this,_);if(_.length>0&&_1(_[0]))return _[0];if(D){let B=_.length===1&&typeof _[0]==="object"&&_[0]!==null&&!Array.isArray(_[0]),A=[];if(!B)for(let j=0;j<G;j++){let[P,N]=W[j],M=_[j];if(_1(M)){A.push(M);continue}if(N.required&&M===void 0){A.push(z1(`Missing required parameter '${P}'`,{path:`${J}.${P}`,expected:typeof N.type==="string"?N.type:N.type?.description||"value",actual:"undefined",loc:N.loc}));continue}if(M!==void 0){let w=V1(M,N.type,`${J}.${P}`);if(w){if(N.loc)w.loc=N.loc;A.push(w)}}}else{let j=_[0];for(let P=0;P<G;P++){let[N,M]=W[P],w=j[N];if(_1(w)){A.push(w);continue}if(M.required&&w===void 0){A.push(z1(`Missing required parameter '${N}'`,{path:`${J}.${N}`,expected:typeof M.type==="string"?M.type:M.type?.description||"value",actual:"undefined",loc:M.loc}));continue}if(w!==void 0){let V=V1(w,M.type,`${J}.${N}`);if(V){if(M.loc)V.loc=M.loc;A.push(V)}}}}if(A.length>0)return B4(A,J)}q6(J);try{let B=Z.apply(this,_);if(I&&$.returns&&!_1(B)){let A=V1(B,$.returns.type,`${J}()`);if(A)return g0(),A}return g0(),B}catch(B){return g0(),z1(B.message||String(B),{path:J,cause:B})}};return Object.defineProperty(U,"name",{value:Z.name}),U.__tjs=$,U}function B6(Z){let $=new Proxy(Z,{construct(X,K,Q){return Reflect.construct(X,K,Q)},apply(X,K,Q){return Reflect.construct(X,Q)}});Object.defineProperty($,"name",{value:Z.name});for(let X of Object.getOwnPropertyNames(Z))if(X!=="length"&&X!=="name"&&X!=="prototype")Object.defineProperty($,X,Object.getOwnPropertyDescriptor(Z,X));return $}function LZ(){let Z={...t},$=[],X=0;function K(I){Z={...Z,...I}}function Q(){return{...Z}}function H(I){if(Z.debug&&I){$.push(I);let B=Z.maxStackSize??100;while($.length>B)$.shift()}}function Y(){if(Z.debug)$.pop()}function z(){return[...$]}function W(){Z={...I4},$.length=0,X=0}function G(){X++}function J(){if(X>0)X--}function U(){return X>0}function _(I,B,A){let j=A===null?"null":typeof A,P=Z.debug?z():void 0;return new O1(`Expected ${B} for '${I}', got ${j}`,I,B,j,P)}function D(I,B){let A={$error:!0,message:I,...B};if(Z.debug&&$.length>0){let j=B?.path?[...$,B.path]:[...$];A.stack=j}return A}return{version:a,MonadicError:O1,typeError:_,isMonadicError:L6,isError:_1,error:D,composeErrors:B4,typeOf:k1,isNativeType:I6,checkType:V1,validateArgs:R4,wrap:M4,wrapClass:B6,compareVersions:U4,versionsCompatible:D4,configure:K,getConfig:Q,pushStack:H,popStack:Y,getStack:z,resetRuntime:W,enterUnsafe:G,exitUnsafe:J,isUnsafeMode:U,validate:_6,infer:b0.infer.bind(b0),Type:d,isRuntimeType:B1,Union:N0,Generic:T1,Enum:k0,Nullable:V0,Optional:O0,TArray:E0,TString:B0,TNumber:R0,TBoolean:M0,TInteger:A0,TPositiveInt:j0,TNonEmptyString:F0,TEmail:w0,TUrl:P0,TUuid:C0,TPair:S0,TRecord:T0,Is:r1,IsNot:D6}}var C1={version:a,MonadicError:O1,typeError:HZ,isMonadicError:L6,isError:_1,error:z1,composeErrors:B4,typeOf:k1,isNativeType:I6,checkType:V1,validateArgs:R4,wrap:M4,wrapClass:B6,compareVersions:U4,versionsCompatible:D4,configure:WZ,getConfig:JZ,pushStack:q6,popStack:g0,getStack:U6,resetRuntime:_Z,enterUnsafe:YZ,exitUnsafe:zZ,isUnsafeMode:GZ,createRuntime:LZ,validate:_6,infer:b0.infer.bind(b0),Type:d,isRuntimeType:B1,Union:N0,Generic:T1,Enum:k0,Nullable:V0,Optional:O0,TArray:E0,TString:B0,TNumber:R0,TBoolean:M0,TInteger:A0,TPositiveInt:j0,TNonEmptyString:F0,TEmail:w0,TUrl:P0,TUuid:C0,Timestamp:L4,LegalDate:q4,TPair:S0,TRecord:T0,Is:r1,IsNot:D6};function qZ(){let Z=globalThis;if(Z.__tjs){let $=Z.__tjs.version;if(typeof $!=="string")return Z.__tjs=C1,C1;let X=U4(a,$);if(X===0)return Z.__tjs;if(D4(a,$))if(X>0)console.info(`TJS runtime: upgrading ${$} → ${a}`),Z.__tjs=C1;else console.info(`TJS runtime: keeping ${$} (newer than ${a})`);else if(console.warn(`TJS runtime version conflict: ${$} vs ${a} (major version mismatch)`),X>0)console.warn(`Upgrading to ${a} - check for breaking changes`),Z.__tjs=C1;return Z.__tjs}return Z.__tjs=C1,C1}function UZ(Z){return`
|
|
258
293
|
// TJS runtime wrapper (skips unsafe functions)
|
|
259
294
|
if (typeof ${Z}.__tjs === 'object' && !${Z}.__tjs.unsafe && typeof globalThis.__tjs?.wrap === 'function') {
|
|
260
295
|
${Z} = globalThis.__tjs.wrap(${Z}, ${Z}.__tjs)
|
|
@@ -262,7 +297,7 @@ if (typeof ${Z}.__tjs === 'object' && !${Z}.__tjs.unsafe && typeof globalThis.__
|
|
|
262
297
|
`.trim()}function R6(Z){return`
|
|
263
298
|
// TJS: callable without new
|
|
264
299
|
${Z} = new Proxy(${Z}, { apply(t, _, a) { return Reflect.construct(t, a) } });
|
|
265
|
-
`.trim()}function x(Z,$,X,K){if(!Z)return"undefined";switch(Z.kind){case R.SyntaxKind.StringKeyword:return"''";case R.SyntaxKind.NumberKeyword:return"0";case R.SyntaxKind.BooleanKeyword:return"true";case R.SyntaxKind.NullKeyword:return"null";case R.SyntaxKind.UndefinedKeyword:return"undefined";case R.SyntaxKind.VoidKeyword:return"undefined";case R.SyntaxKind.AnyKeyword:return"any";case R.SyntaxKind.UnknownKeyword:return"any";case R.SyntaxKind.NeverKeyword:return"null";case R.SyntaxKind.ArrayType:{let H=x(Z.elementType,$);if(H==="any")H="null";return`[${H}]`}case R.SyntaxKind.TypeReference:{let Q=Z,H=Q.typeName.getText();if(H==="Array"&&Q.typeArguments?.length)return`[${x(Q.typeArguments[0],$,X,K)}]`;if(H==="Promise"){if(Q.typeArguments?.length)return x(Q.typeArguments[0],$,X,K);return"undefined"}if(H==="Record")return"{}";if(H==="Map")return"new Map()";if(H==="Set")return"new Set()";if(K?.typeAliases?.has(H)){let Y=K.visited??new Set;if(Y.has(H))return X?.push(`Circular type reference '${H}' - using 'any'`),"any";Y.add(H);let z=K.typeAliases.get(H);return x(z,$,X,{...K,visited:Y})}if(K?.interfaces?.has(H)){let Y=K.visited??new Set;if(Y.has(H))return X?.push(`Circular type reference '${H}' - using 'any'`),"any";Y.add(H);let z=K.interfaces.get(H),W=[];for(let G of z.members)if(R.isPropertySignature(G)&&G.name){let J=G.name.getText(K.sourceFile),U=x(G.type,$,X,{...K,visited:Y});if(!!G.questionToken)W.push(`${J} = ${U}`);else W.push(`${J}: ${U}`)}return`{ ${W.join(", ")} }`}if(/^[A-Z]$/.test(H)||["T","K","V","U","TKey","TValue","TItem","TResult"].includes(H))return X?.push(`Generic type parameter '${H}' converted to 'any' - consider specializing`),"any";return X?.push(`Unknown type '${H}' converted to 'any' - may need manual review`),"any"}case R.SyntaxKind.TypeLiteral:{let Q=Z,H=[];for(let Y of Q.members)if(R.isPropertySignature(Y)&&Y.name){let z=Y.name.getText(),W=x(Y.type,$);if(W==="any")W="null";H.push(`${z}: ${W}`)}return`{ ${H.join(", ")} }`}case R.SyntaxKind.UnionType:{let Q=Z,H=(J)=>J.kind===R.SyntaxKind.NullKeyword||R.isLiteralTypeNode(J)&&J.literal.kind===R.SyntaxKind.NullKeyword,Y=(J)=>J.kind===R.SyntaxKind.UndefinedKeyword||R.isLiteralTypeNode(J)&&J.literal.kind===R.SyntaxKind.UndefinedKeyword,z=Q.types.filter((J)=>!H(J)&&!Y(J)),W=Q.types.some(H),G=Q.types.some(Y);if(z.length===1&&(W||G)){let J=x(z[0],$);if(W)return`${J} || null`;if(G)return`${J} || undefined`}if(Q.types.length>0)return x(Q.types[0],$);return"undefined"}case R.SyntaxKind.LiteralType:{let Q=Z;if(R.isStringLiteral(Q.literal))return`'${Q.literal.text}'`;if(R.isNumericLiteral(Q.literal))return Q.literal.text;if(Q.literal.kind===R.SyntaxKind.TrueKeyword)return"true";if(Q.literal.kind===R.SyntaxKind.FalseKeyword)return"false";if(Q.literal.kind===R.SyntaxKind.NullKeyword)return"null";return"undefined"}case R.SyntaxKind.ParenthesizedType:return x(Z.type,$);case R.SyntaxKind.FunctionType:return"undefined";case R.SyntaxKind.TupleType:return`[${Z.elements.map((Y)=>{if(R.isNamedTupleMember(Y))return x(Y.type,$);return x(Y,$)}).join(", ")}]`;default:return"undefined"}}function l(Z,$){if(!Z)return{kind:"any"};switch(Z.kind){case R.SyntaxKind.StringKeyword:return{kind:"string"};case R.SyntaxKind.NumberKeyword:return{kind:"number"};case R.SyntaxKind.BooleanKeyword:return{kind:"boolean"};case R.SyntaxKind.NullKeyword:return{kind:"null"};case R.SyntaxKind.UndefinedKeyword:case R.SyntaxKind.VoidKeyword:return{kind:"undefined"};case R.SyntaxKind.ArrayType:return{kind:"array",items:l(Z.elementType,$)};case R.SyntaxKind.TypeLiteral:{let X=Z,K={};for(let Q of X.members)if(R.isPropertySignature(Q)&&Q.name){let H=Q.name.getText();K[H]=l(Q.type,$)}return{kind:"object",shape:K}}case R.SyntaxKind.UnionType:{let X=Z,K=X.types.filter((H)=>H.kind!==R.SyntaxKind.NullKeyword&&H.kind!==R.SyntaxKind.UndefinedKeyword),Q=X.types.some((H)=>H.kind===R.SyntaxKind.NullKeyword);if(K.length===1&&Q)return{...l(K[0],$),nullable:!0};return{kind:"union",members:X.types.map((H)=>l(H,$))}}case R.SyntaxKind.IntersectionType:{let X=Z,K={};for(let Q of X.types){let H=l(Q,$);if(H.kind==="object"&&H.shape)Object.assign(K,H.shape)}if(Object.keys(K).length>0)return{kind:"object",shape:K};return{kind:"any"}}case R.SyntaxKind.TupleType:{let X=Z,K=[];for(let Q of X.elements)if(R.isNamedTupleMember(Q))K.push(l(Q.type,$));else K.push(l(Q,$));return{kind:"tuple",elements:K}}case R.SyntaxKind.TypeReference:{let X=Z,K=X.typeName.getText();if(K==="Array"&&X.typeArguments?.length)return{kind:"array",items:l(X.typeArguments[0],$)};if(K==="Promise"&&X.typeArguments?.length)return l(X.typeArguments[0],$);if(X.typeArguments?.length){let Q=l(X.typeArguments[0],$);if(K==="Partial")return Q;if(K==="Required")return Q;if(K==="Readonly")return Q;if(K==="Record"&&X.typeArguments.length>=2)return{kind:"object",shape:{"[key]":l(X.typeArguments[1],$)}};if(K==="Pick"||K==="Omit")return Q;if(K==="NonNullable"){if(Q.nullable)return{...Q,nullable:!1};return Q}if(["ReturnType","Parameters","ConstructorParameters"].includes(K))return{kind:"any"}}if($?.typeAliases?.has(K)){let Q=$.visited??new Set;if(Q.has(K))return{kind:"any"};Q.add(K);let H=$.typeAliases.get(K);return l(H,{...$,visited:Q})}if($?.interfaces?.has(K)){let Q=$.visited??new Set;if(Q.has(K))return{kind:"any"};Q.add(K);let H=$.interfaces.get(K),Y={};if(H.heritageClauses){for(let z of H.heritageClauses)if(z.token===R.SyntaxKind.ExtendsKeyword)for(let W of z.types){let G=W.expression.getText($.sourceFile);if($.interfaces?.has(G)&&!Q.has(G)){let J={kind:R.SyntaxKind.TypeReference,typeName:{getText:()=>G}},U=l(J,{...$,visited:Q});if(U.kind==="object"&&U.shape)Object.assign(Y,U.shape)}}}for(let z of H.members)if(R.isPropertySignature(z)&&z.name){let W=z.name.getText($.sourceFile);Y[W]=l(z.type,{...$,visited:Q})}return{kind:"object",shape:Y}}return{kind:"any"}}default:return{kind:"any"}}}function DZ(Z,$){if(!Z.typeParameters||Z.typeParameters.length===0)return;let X={};for(let K of Z.typeParameters){let Q=K.name.getText(),H={};if(K.constraint){let Y=x(K.constraint,void 0,$);if(Y.startsWith("{"))try{H.constraint=Y}catch{H.constraint=Y}else H.constraint=Y}if(K.default){let Y=x(K.default,void 0,$);H.default=Y}X[Q]=H}return Object.keys(X).length>0?X:void 0}function IZ(Z,$,X){let K=Z.name.getText($);if(Z.typeParameters&&Z.typeParameters.length>0)return BZ(Z,$,X);let Q=[];for(let H of Z.members)if(R.isPropertySignature(H)&&H.name){let Y=H.name.getText($),z=x(H.type,void 0,X);if(z==="any")z="null";Q.push(`${Y}: ${z}`)}if(Q.length===0)return`Type ${K} {}`;return`Type ${K} {
|
|
300
|
+
`.trim()}function x(Z,$,X,K){if(!Z)return"undefined";switch(Z.kind){case R.SyntaxKind.StringKeyword:return"''";case R.SyntaxKind.NumberKeyword:return"0.0";case R.SyntaxKind.BooleanKeyword:return"true";case R.SyntaxKind.NullKeyword:return"null";case R.SyntaxKind.UndefinedKeyword:return"undefined";case R.SyntaxKind.VoidKeyword:return"undefined";case R.SyntaxKind.AnyKeyword:return"any";case R.SyntaxKind.UnknownKeyword:return"any";case R.SyntaxKind.NeverKeyword:return"null";case R.SyntaxKind.ArrayType:{let H=x(Z.elementType,$);if(H==="any")H="null";return`[${H}]`}case R.SyntaxKind.TypeReference:{let Q=Z,H=Q.typeName.getText();if(H==="Array"&&Q.typeArguments?.length)return`[${x(Q.typeArguments[0],$,X,K)}]`;if(H==="Promise"){if(Q.typeArguments?.length)return x(Q.typeArguments[0],$,X,K);return"undefined"}if(H==="Record")return"{}";if(H==="Map")return"new Map()";if(H==="Set")return"new Set()";if(K?.typeAliases?.has(H)){let Y=K.visited??new Set;if(Y.has(H))return X?.push(`Circular type reference '${H}' - using 'any'`),"any";Y.add(H);let z=K.typeAliases.get(H);return x(z,$,X,{...K,visited:Y})}if(K?.interfaces?.has(H)){let Y=K.visited??new Set;if(Y.has(H))return X?.push(`Circular type reference '${H}' - using 'any'`),"any";Y.add(H);let z=K.interfaces.get(H),W=[];for(let G of z.members)if(R.isPropertySignature(G)&&G.name){let J=G.name.getText(K.sourceFile),U=x(G.type,$,X,{...K,visited:Y});if(!!G.questionToken)W.push(`${J} = ${U}`);else W.push(`${J}: ${U}`)}return`{ ${W.join(", ")} }`}if(/^[A-Z]$/.test(H)||["T","K","V","U","TKey","TValue","TItem","TResult"].includes(H))return X?.push(`Generic type parameter '${H}' converted to 'any' - consider specializing`),"any";return X?.push(`Unknown type '${H}' converted to 'any' - may need manual review`),"any"}case R.SyntaxKind.TypeLiteral:{let Q=Z,H=[];for(let Y of Q.members)if(R.isPropertySignature(Y)&&Y.name){let z=Y.name.getText(),W=x(Y.type,$);if(W==="any")W="null";H.push(`${z}: ${W}`)}return`{ ${H.join(", ")} }`}case R.SyntaxKind.UnionType:{let Q=Z,H=(J)=>J.kind===R.SyntaxKind.NullKeyword||R.isLiteralTypeNode(J)&&J.literal.kind===R.SyntaxKind.NullKeyword,Y=(J)=>J.kind===R.SyntaxKind.UndefinedKeyword||R.isLiteralTypeNode(J)&&J.literal.kind===R.SyntaxKind.UndefinedKeyword,z=Q.types.filter((J)=>!H(J)&&!Y(J)),W=Q.types.some(H),G=Q.types.some(Y);if(z.length===1&&(W||G)){let J=x(z[0],$);if(W)return`${J} || null`;if(G)return`${J} || undefined`}if(Q.types.length>0)return x(Q.types[0],$);return"undefined"}case R.SyntaxKind.LiteralType:{let Q=Z;if(R.isStringLiteral(Q.literal))return`'${Q.literal.text}'`;if(R.isNumericLiteral(Q.literal))return Q.literal.text;if(Q.literal.kind===R.SyntaxKind.TrueKeyword)return"true";if(Q.literal.kind===R.SyntaxKind.FalseKeyword)return"false";if(Q.literal.kind===R.SyntaxKind.NullKeyword)return"null";return"undefined"}case R.SyntaxKind.ParenthesizedType:return x(Z.type,$);case R.SyntaxKind.FunctionType:return"undefined";case R.SyntaxKind.TupleType:return`[${Z.elements.map((Y)=>{if(R.isNamedTupleMember(Y))return x(Y.type,$);return x(Y,$)}).join(", ")}]`;default:return"undefined"}}function l(Z,$){if(!Z)return{kind:"any"};switch(Z.kind){case R.SyntaxKind.StringKeyword:return{kind:"string"};case R.SyntaxKind.NumberKeyword:return{kind:"number"};case R.SyntaxKind.BooleanKeyword:return{kind:"boolean"};case R.SyntaxKind.NullKeyword:return{kind:"null"};case R.SyntaxKind.UndefinedKeyword:case R.SyntaxKind.VoidKeyword:return{kind:"undefined"};case R.SyntaxKind.ArrayType:return{kind:"array",items:l(Z.elementType,$)};case R.SyntaxKind.TypeLiteral:{let X=Z,K={};for(let Q of X.members)if(R.isPropertySignature(Q)&&Q.name){let H=Q.name.getText();K[H]=l(Q.type,$)}return{kind:"object",shape:K}}case R.SyntaxKind.UnionType:{let X=Z,K=X.types.filter((H)=>H.kind!==R.SyntaxKind.NullKeyword&&H.kind!==R.SyntaxKind.UndefinedKeyword),Q=X.types.some((H)=>H.kind===R.SyntaxKind.NullKeyword);if(K.length===1&&Q)return{...l(K[0],$),nullable:!0};return{kind:"union",members:X.types.map((H)=>l(H,$))}}case R.SyntaxKind.IntersectionType:{let X=Z,K={};for(let Q of X.types){let H=l(Q,$);if(H.kind==="object"&&H.shape)Object.assign(K,H.shape)}if(Object.keys(K).length>0)return{kind:"object",shape:K};return{kind:"any"}}case R.SyntaxKind.TupleType:{let X=Z,K=[];for(let Q of X.elements)if(R.isNamedTupleMember(Q))K.push(l(Q.type,$));else K.push(l(Q,$));return{kind:"tuple",elements:K}}case R.SyntaxKind.TypeReference:{let X=Z,K=X.typeName.getText();if(K==="Array"&&X.typeArguments?.length)return{kind:"array",items:l(X.typeArguments[0],$)};if(K==="Promise"&&X.typeArguments?.length)return l(X.typeArguments[0],$);if(X.typeArguments?.length){let Q=l(X.typeArguments[0],$);if(K==="Partial")return Q;if(K==="Required")return Q;if(K==="Readonly")return Q;if(K==="Record"&&X.typeArguments.length>=2)return{kind:"object",shape:{"[key]":l(X.typeArguments[1],$)}};if(K==="Pick"||K==="Omit")return Q;if(K==="NonNullable"){if(Q.nullable)return{...Q,nullable:!1};return Q}if(["ReturnType","Parameters","ConstructorParameters"].includes(K))return{kind:"any"}}if($?.typeAliases?.has(K)){let Q=$.visited??new Set;if(Q.has(K))return{kind:"any"};Q.add(K);let H=$.typeAliases.get(K);return l(H,{...$,visited:Q})}if($?.interfaces?.has(K)){let Q=$.visited??new Set;if(Q.has(K))return{kind:"any"};Q.add(K);let H=$.interfaces.get(K),Y={};if(H.heritageClauses){for(let z of H.heritageClauses)if(z.token===R.SyntaxKind.ExtendsKeyword)for(let W of z.types){let G=W.expression.getText($.sourceFile);if($.interfaces?.has(G)&&!Q.has(G)){let J={kind:R.SyntaxKind.TypeReference,typeName:{getText:()=>G}},U=l(J,{...$,visited:Q});if(U.kind==="object"&&U.shape)Object.assign(Y,U.shape)}}}for(let z of H.members)if(R.isPropertySignature(z)&&z.name){let W=z.name.getText($.sourceFile);Y[W]=l(z.type,{...$,visited:Q})}return{kind:"object",shape:Y}}return{kind:"any"}}default:return{kind:"any"}}}function DZ(Z,$){if(!Z.typeParameters||Z.typeParameters.length===0)return;let X={};for(let K of Z.typeParameters){let Q=K.name.getText(),H={};if(K.constraint){let Y=x(K.constraint,void 0,$);if(Y.startsWith("{"))try{H.constraint=Y}catch{H.constraint=Y}else H.constraint=Y}if(K.default){let Y=x(K.default,void 0,$);H.default=Y}X[Q]=H}return Object.keys(X).length>0?X:void 0}function IZ(Z,$,X){let K=Z.name.getText($);if(Z.typeParameters&&Z.typeParameters.length>0)return BZ(Z,$,X);let Q=[];for(let H of Z.members)if(R.isPropertySignature(H)&&H.name){let Y=H.name.getText($),z=x(H.type,void 0,X);if(z==="any")z="null";Q.push(`${Y}: ${z}`)}if(Q.length===0)return`Type ${K} {}`;return`Type ${K} {
|
|
266
301
|
example: { ${Q.join(", ")} }
|
|
267
302
|
}`}function BZ(Z,$,X){let K=Z.name.getText($),Q=[];for(let W of Z.typeParameters||[]){let G=W.name.getText($);if(W.default){let J=x(W.default,void 0,X);Q.push(`${G} = ${J}`)}else Q.push(G)}let H=(Z.typeParameters||[]).map((W)=>W.name.getText($)),Y=["typeof x === 'object'","x !== null"];for(let W of Z.members)if(R.isPropertySignature(W)&&W.name){let G=W.name.getText($);if(Y.push(`'${G}' in x`),W.type&&R.isTypeReferenceNode(W.type)){let J=W.type.typeName.getText($);if(H.includes(J))Y.push(`${J}(x.${G})`)}}let z=["x",...H].join(", ");return`Generic ${K}<${Q.join(", ")}> {
|
|
268
303
|
description: '${K}'
|
|
@@ -293,7 +328,7 @@ ${M}.__tjs = ${O};
|
|
|
293
328
|
${M}.__tjs = ${O};
|
|
294
329
|
`,N+=`
|
|
295
330
|
${R6(M)}
|
|
296
|
-
`}return{code:N,types:J,classes:Object.keys(U).length>0?U:void 0,warnings:Q.length>0?Q:void 0}}import{s as j6}from"tosijs-schema";function F6(Z){if(Z===null)return"null";if(Z===void 0)return"undefined";if(Array.isArray(Z))return"array";return typeof Z}function f0(Z){return j6.infer(Z)}function j4(Z){return f0(Z)}j4.type=F6;j4.infer=f0;var OZ=new Proxy(j4,{get(Z,$){if($==="type")return F6;if($==="infer")return f0;return j6[$]},apply(Z,$,X){return f0(X[0])}});async function y0(Z){let $=`${a}:${Z}`;if(typeof crypto<"u"&&crypto.subtle){let Q=new TextEncoder().encode($),H=await crypto.subtle.digest("SHA-256",Q);return Array.from(new Uint8Array(H)).map((z)=>z.toString(16).padStart(2,"0")).join("")}let X=5381;for(let K=0;K<$.length;K++)X=(X<<5)+X+$.charCodeAt(K)>>>0;return X.toString(16)}function NZ(Z){let $=`${a}:${Z}`,X=5381;for(let K=0;K<$.length;K++)X=(X<<5)+X+$.charCodeAt(K)>>>0;return X.toString(16)}var EZ="tjs-metadata-cache",SZ=1,p="modules";class F4{db=null;stats={hits:0,misses:0};pendingOpen=null;async open(){if(this.db)return;if(this.pendingOpen)return this.pendingOpen;this.pendingOpen=this._open(),await this.pendingOpen,this.pendingOpen=null}async _open(){return new Promise((Z,$)=>{if(typeof indexedDB>"u"){Z();return}let X=indexedDB.open(EZ,SZ);X.onerror=()=>{console.warn("MetadataCache: Failed to open IndexedDB",X.error),Z()},X.onsuccess=()=>{this.db=X.result,Z()},X.onupgradeneeded=(K)=>{let Q=K.target.result;if(!Q.objectStoreNames.contains(p)){let H=Q.createObjectStore(p,{keyPath:"hash"});H.createIndex("timestamp","timestamp"),H.createIndex("version","version")}}})}async get(Z){if(!this.db){this.stats.misses++;return}let $=await y0(Z);return new Promise((X)=>{let H=this.db.transaction(p,"readonly").objectStore(p).get($);H.onerror=()=>{this.stats.misses++,X(void 0)},H.onsuccess=()=>{let Y=H.result;if(Y&&Y.version!==a){this.stats.misses++,X(void 0);return}if(Y)this.stats.hits++;else this.stats.misses++;X(Y)}})}async getTranspile(Z){return(await this.get(Z))?.transpile}async getTJS(Z){return(await this.get(Z))?.tjs}async setTranspile(Z,$){await this._set(Z,{transpile:$})}async setTJS(Z,$){await this._set(Z,{tjs:$})}async _set(Z,$){if(!this.db)return;let X=await y0(Z);return new Promise((K,Q)=>{let Y=this.db.transaction(p,"readwrite").objectStore(p),z=Y.get(X);z.onsuccess=()=>{let W=z.result,G={hash:X,version:a,timestamp:Date.now(),transpile:$.transpile??W?.transpile,tjs:$.tjs??W?.tjs},J=Y.put(G);J.onerror=()=>Q(J.error),J.onsuccess=()=>K()},z.onerror=()=>Q(z.error)})}async delete(Z){if(!this.db)return;let $=await y0(Z);return new Promise((X,K)=>{let Y=this.db.transaction(p,"readwrite").objectStore(p).delete($);Y.onerror=()=>K(Y.error),Y.onsuccess=()=>X()})}async clear(){if(!this.db)return;return new Promise((Z,$)=>{let Q=this.db.transaction(p,"readwrite").objectStore(p).clear();Q.onerror=()=>$(Q.error),Q.onsuccess=()=>{this.stats={hits:0,misses:0},Z()}})}async prune(Z){if(!this.db)return 0;let $=Date.now()-Z;return new Promise((X,K)=>{let Y=this.db.transaction(p,"readwrite").objectStore(p).index("timestamp"),z=IDBKeyRange.upperBound($),W=0,G=Y.openCursor(z);G.onsuccess=(J)=>{let U=J.target.result;if(U)U.delete(),W++,U.continue();else X(W)},G.onerror=()=>K(G.error)})}async pruneOldVersions(){if(!this.db)return 0;return new Promise((Z,$)=>{let K=this.db.transaction(p,"readwrite").objectStore(p),Q=0,H=K.openCursor();H.onsuccess=(Y)=>{let z=Y.target.result;if(z){if(z.value.version!==a)z.delete(),Q++;z.continue()}else Z(Q)},H.onerror=()=>$(H.error)})}async getStats(){let Z=await this.count(),$=await this.estimateSize(),X=this.stats.hits+this.stats.misses,K=X>0?this.stats.hits/X:0;return{entries:Z,bytes:$,hits:this.stats.hits,misses:this.stats.misses,hitRate:K}}async count(){if(!this.db)return 0;return new Promise((Z,$)=>{let Q=this.db.transaction(p,"readonly").objectStore(p).count();Q.onerror=()=>$(Q.error),Q.onsuccess=()=>Z(Q.result)})}async estimateSize(){if(!this.db)return 0;if(typeof navigator<"u"&&navigator.storage?.estimate)try{return(await navigator.storage.estimate()).usage??0}catch{}return new Promise((Z,$)=>{let K=this.db.transaction(p,"readonly").objectStore(p),Q=0,H=K.openCursor();H.onsuccess=(Y)=>{let z=Y.target.result;if(z)Q+=JSON.stringify(z.value).length*2,z.continue();else Z(Q)},H.onerror=()=>$(H.error)})}close(){if(this.db)this.db.close(),this.db=null}isAvailable(){return this.db!==null}resetStats(){this.stats={hits:0,misses:0}}}var t1=null;async function h0(){if(!t1)t1=new F4,await t1.open();return t1}function TZ(Z){t1=Z}function x0(Z,$,X,K,Q){if(!X)X=C;(function H(Y,z,W){var G=W||Y.type;if(X[G](Y,z,H),$[G])$[G](Y,z)})(Z,K,Q)}function w6(Z,$,X,K,Q){var H=[];if(!X)X=C;(function Y(z,W,G){var J=G||z.type,U=z!==H[H.length-1];if(U)H.push(z);if(X[J](z,W,Y),$[J])$[J](z,W||H,H);if(U)H.pop()})(Z,K,Q)}function w4(Z,$,X){X(Z,$)}function N1(Z,$,X){}var C={};C.Program=C.BlockStatement=C.StaticBlock=function(Z,$,X){for(var K=0,Q=Z.body;K<Q.length;K+=1){var H=Q[K];X(H,$,"Statement")}};C.Statement=w4;C.EmptyStatement=N1;C.ExpressionStatement=C.ParenthesizedExpression=C.ChainExpression=function(Z,$,X){return X(Z.expression,$,"Expression")};C.IfStatement=function(Z,$,X){if(X(Z.test,$,"Expression"),X(Z.consequent,$,"Statement"),Z.alternate)X(Z.alternate,$,"Statement")};C.LabeledStatement=function(Z,$,X){return X(Z.body,$,"Statement")};C.BreakStatement=C.ContinueStatement=N1;C.WithStatement=function(Z,$,X){X(Z.object,$,"Expression"),X(Z.body,$,"Statement")};C.SwitchStatement=function(Z,$,X){X(Z.discriminant,$,"Expression");for(var K=0,Q=Z.cases;K<Q.length;K+=1){var H=Q[K];X(H,$)}};C.SwitchCase=function(Z,$,X){if(Z.test)X(Z.test,$,"Expression");for(var K=0,Q=Z.consequent;K<Q.length;K+=1){var H=Q[K];X(H,$,"Statement")}};C.ReturnStatement=C.YieldExpression=C.AwaitExpression=function(Z,$,X){if(Z.argument)X(Z.argument,$,"Expression")};C.ThrowStatement=C.SpreadElement=function(Z,$,X){return X(Z.argument,$,"Expression")};C.TryStatement=function(Z,$,X){if(X(Z.block,$,"Statement"),Z.handler)X(Z.handler,$);if(Z.finalizer)X(Z.finalizer,$,"Statement")};C.CatchClause=function(Z,$,X){if(Z.param)X(Z.param,$,"Pattern");X(Z.body,$,"Statement")};C.WhileStatement=C.DoWhileStatement=function(Z,$,X){X(Z.test,$,"Expression"),X(Z.body,$,"Statement")};C.ForStatement=function(Z,$,X){if(Z.init)X(Z.init,$,"ForInit");if(Z.test)X(Z.test,$,"Expression");if(Z.update)X(Z.update,$,"Expression");X(Z.body,$,"Statement")};C.ForInStatement=C.ForOfStatement=function(Z,$,X){X(Z.left,$,"ForInit"),X(Z.right,$,"Expression"),X(Z.body,$,"Statement")};C.ForInit=function(Z,$,X){if(Z.type==="VariableDeclaration")X(Z,$);else X(Z,$,"Expression")};C.DebuggerStatement=N1;C.FunctionDeclaration=function(Z,$,X){return X(Z,$,"Function")};C.VariableDeclaration=function(Z,$,X){for(var K=0,Q=Z.declarations;K<Q.length;K+=1){var H=Q[K];X(H,$)}};C.VariableDeclarator=function(Z,$,X){if(X(Z.id,$,"Pattern"),Z.init)X(Z.init,$,"Expression")};C.Function=function(Z,$,X){if(Z.id)X(Z.id,$,"Pattern");for(var K=0,Q=Z.params;K<Q.length;K+=1){var H=Q[K];X(H,$,"Pattern")}X(Z.body,$,Z.expression?"Expression":"Statement")};C.Pattern=function(Z,$,X){if(Z.type==="Identifier")X(Z,$,"VariablePattern");else if(Z.type==="MemberExpression")X(Z,$,"MemberPattern");else X(Z,$)};C.VariablePattern=N1;C.MemberPattern=w4;C.RestElement=function(Z,$,X){return X(Z.argument,$,"Pattern")};C.ArrayPattern=function(Z,$,X){for(var K=0,Q=Z.elements;K<Q.length;K+=1){var H=Q[K];if(H)X(H,$,"Pattern")}};C.ObjectPattern=function(Z,$,X){for(var K=0,Q=Z.properties;K<Q.length;K+=1){var H=Q[K];if(H.type==="Property"){if(H.computed)X(H.key,$,"Expression");X(H.value,$,"Pattern")}else if(H.type==="RestElement")X(H.argument,$,"Pattern")}};C.Expression=w4;C.ThisExpression=C.Super=C.MetaProperty=N1;C.ArrayExpression=function(Z,$,X){for(var K=0,Q=Z.elements;K<Q.length;K+=1){var H=Q[K];if(H)X(H,$,"Expression")}};C.ObjectExpression=function(Z,$,X){for(var K=0,Q=Z.properties;K<Q.length;K+=1){var H=Q[K];X(H,$)}};C.FunctionExpression=C.ArrowFunctionExpression=C.FunctionDeclaration;C.SequenceExpression=function(Z,$,X){for(var K=0,Q=Z.expressions;K<Q.length;K+=1){var H=Q[K];X(H,$,"Expression")}};C.TemplateLiteral=function(Z,$,X){for(var K=0,Q=Z.quasis;K<Q.length;K+=1){var H=Q[K];X(H,$)}for(var Y=0,z=Z.expressions;Y<z.length;Y+=1){var W=z[Y];X(W,$,"Expression")}};C.TemplateElement=N1;C.UnaryExpression=C.UpdateExpression=function(Z,$,X){X(Z.argument,$,"Expression")};C.BinaryExpression=C.LogicalExpression=function(Z,$,X){X(Z.left,$,"Expression"),X(Z.right,$,"Expression")};C.AssignmentExpression=C.AssignmentPattern=function(Z,$,X){X(Z.left,$,"Pattern"),X(Z.right,$,"Expression")};C.ConditionalExpression=function(Z,$,X){X(Z.test,$,"Expression"),X(Z.consequent,$,"Expression"),X(Z.alternate,$,"Expression")};C.NewExpression=C.CallExpression=function(Z,$,X){if(X(Z.callee,$,"Expression"),Z.arguments)for(var K=0,Q=Z.arguments;K<Q.length;K+=1){var H=Q[K];X(H,$,"Expression")}};C.MemberExpression=function(Z,$,X){if(X(Z.object,$,"Expression"),Z.computed)X(Z.property,$,"Expression")};C.ExportNamedDeclaration=C.ExportDefaultDeclaration=function(Z,$,X){if(Z.declaration)X(Z.declaration,$,Z.type==="ExportNamedDeclaration"||Z.declaration.id?"Statement":"Expression");if(Z.source)X(Z.source,$,"Expression")};C.ExportAllDeclaration=function(Z,$,X){if(Z.exported)X(Z.exported,$);X(Z.source,$,"Expression")};C.ImportDeclaration=function(Z,$,X){for(var K=0,Q=Z.specifiers;K<Q.length;K+=1){var H=Q[K];X(H,$)}X(Z.source,$,"Expression")};C.ImportExpression=function(Z,$,X){X(Z.source,$,"Expression")};C.ImportSpecifier=C.ImportDefaultSpecifier=C.ImportNamespaceSpecifier=C.Identifier=C.PrivateIdentifier=C.Literal=N1;C.TaggedTemplateExpression=function(Z,$,X){X(Z.tag,$,"Expression"),X(Z.quasi,$,"Expression")};C.ClassDeclaration=C.ClassExpression=function(Z,$,X){return X(Z,$,"Class")};C.Class=function(Z,$,X){if(Z.id)X(Z.id,$,"Pattern");if(Z.superClass)X(Z.superClass,$,"Expression");X(Z.body,$)};C.ClassBody=function(Z,$,X){for(var K=0,Q=Z.body;K<Q.length;K+=1){var H=Q[K];X(H,$)}};C.MethodDefinition=C.PropertyDefinition=C.Property=function(Z,$,X){if(Z.computed)X(Z.key,$,"Expression");if(Z.value)X(Z.value,$,"Expression")};var gZ={unusedVariables:!0,undefinedVariables:!0,unreachableCode:!0,noExplicitNew:!0};function bZ(Z,$={}){let X={...gZ,...$},K=[],Q;try{Q=W1(Z,{filename:X.filename,colonShorthand:!0}).ast}catch(Y){return{diagnostics:[{severity:"error",message:Y.message,line:Y.loc?.line,column:Y.loc?.column,rule:"parse-error"}],valid:!1}}let H=[P6()];if(w6(Q,{FunctionDeclaration(Y,z,W){let G=P6();H.push(G);for(let J of Y.params)vZ(G,J,"parameter");if(Y.id)(H[H.length-2]||H[0]).declarations.set(Y.id.name,{node:Y.id,kind:"function",used:!1})},VariableDeclaration(Y){let z=H[H.length-1];for(let W of Y.declarations)if(W.id.type==="Identifier")z.declarations.set(W.id.name,{node:W.id,kind:Y.kind,used:!1})}}),x0(Q,{Identifier(Y){for(let z=H.length-1;z>=0;z--){let W=H[z].declarations.get(Y.name);if(W){W.used=!0;break}}}}),X.unusedVariables)for(let Y of H)for(let[z,W]of Y.declarations){if(z.startsWith("_"))continue;if(!W.used&&W.kind!=="function")K.push({severity:"warning",message:`'${z}' is declared but never used`,line:W.node.loc?.start?.line,column:W.node.loc?.start?.column,rule:"no-unused-vars"})}if(X.unreachableCode)x0(Q,{BlockStatement(Y){let z=!1;for(let W of Y.body){if(z){K.push({severity:"warning",message:"Unreachable code after return statement",line:W.loc?.start?.line,column:W.loc?.start?.column,rule:"no-unreachable"});break}if(W.type==="ReturnStatement")z=!0}}});if(X.noExplicitNew)x0(Q,{NewExpression(Y){let z="class";if(Y.callee.type==="Identifier")z=Y.callee.name;else if(Y.callee.type==="MemberExpression"){if(Y.callee.property.type==="Identifier")z=Y.callee.property.name}K.push({severity:"warning",message:`Unnecessary 'new' keyword. In TJS, classes are callable without 'new': ${z}(...) instead of new ${z}(...)`,line:Y.loc?.start?.line,column:Y.loc?.start?.column,rule:"no-explicit-new"})}});return{diagnostics:K,valid:K.filter((Y)=>Y.severity==="error").length===0}}function P6(){return{declarations:new Map}}function vZ(Z,$,X){if($.type==="Identifier")Z.declarations.set($.name,{node:$,kind:X,used:!1});else if($.type==="AssignmentPattern"&&$.left.type==="Identifier")Z.declarations.set($.left.name,{node:$.left,kind:X,used:!1})}function fZ(Z){let $=[],X=0,K=null;for(let Q=0;Q<Z.length;Q++){let H=Z[Q],Y=Q>0?Z[Q-1]:"";if(!K&&(H==='"'||H==="'"||H==="`"))K=H;else if(K&&H===K&&Y!=="\\")K=null;if(!K){if(H==="{")X++;if(H==="}")X--}$[Q]=X}return $}function C6(Z){let $=[],X=fZ(Z),K=/\/\*#([\s\S]*?)\*\//g,Q=/function\s+(\w+)\s*\(([^)]*)\)\s*(?:(-[>?!])\s*('[^']*'|"[^"]*"|[^\s{]+)|:\s*(\w+))?\s*\{/g,H=[],Y;while((Y=K.exec(Z))!==null){if(X[Y.index]!==0)continue;let W=Y[1],G=W.split(`
|
|
331
|
+
`}return{code:N,types:J,classes:Object.keys(U).length>0?U:void 0,warnings:Q.length>0?Q:void 0}}import{s as j6}from"tosijs-schema";function F6(Z){if(Z===null)return"null";if(Z===void 0)return"undefined";if(Array.isArray(Z))return"array";return typeof Z}function v0(Z){return j6.infer(Z)}function j4(Z){return v0(Z)}j4.type=F6;j4.infer=v0;var OZ=new Proxy(j4,{get(Z,$){if($==="type")return F6;if($==="infer")return v0;return j6[$]},apply(Z,$,X){return v0(X[0])}});async function y0(Z){let $=`${a}:${Z}`;if(typeof crypto<"u"&&crypto.subtle){let Q=new TextEncoder().encode($),H=await crypto.subtle.digest("SHA-256",Q);return Array.from(new Uint8Array(H)).map((z)=>z.toString(16).padStart(2,"0")).join("")}let X=5381;for(let K=0;K<$.length;K++)X=(X<<5)+X+$.charCodeAt(K)>>>0;return X.toString(16)}function NZ(Z){let $=`${a}:${Z}`,X=5381;for(let K=0;K<$.length;K++)X=(X<<5)+X+$.charCodeAt(K)>>>0;return X.toString(16)}var EZ="tjs-metadata-cache",SZ=1,p="modules";class F4{db=null;stats={hits:0,misses:0};pendingOpen=null;async open(){if(this.db)return;if(this.pendingOpen)return this.pendingOpen;this.pendingOpen=this._open(),await this.pendingOpen,this.pendingOpen=null}async _open(){return new Promise((Z,$)=>{if(typeof indexedDB>"u"){Z();return}let X=indexedDB.open(EZ,SZ);X.onerror=()=>{console.warn("MetadataCache: Failed to open IndexedDB",X.error),Z()},X.onsuccess=()=>{this.db=X.result,Z()},X.onupgradeneeded=(K)=>{let Q=K.target.result;if(!Q.objectStoreNames.contains(p)){let H=Q.createObjectStore(p,{keyPath:"hash"});H.createIndex("timestamp","timestamp"),H.createIndex("version","version")}}})}async get(Z){if(!this.db){this.stats.misses++;return}let $=await y0(Z);return new Promise((X)=>{let H=this.db.transaction(p,"readonly").objectStore(p).get($);H.onerror=()=>{this.stats.misses++,X(void 0)},H.onsuccess=()=>{let Y=H.result;if(Y&&Y.version!==a){this.stats.misses++,X(void 0);return}if(Y)this.stats.hits++;else this.stats.misses++;X(Y)}})}async getTranspile(Z){return(await this.get(Z))?.transpile}async getTJS(Z){return(await this.get(Z))?.tjs}async setTranspile(Z,$){await this._set(Z,{transpile:$})}async setTJS(Z,$){await this._set(Z,{tjs:$})}async _set(Z,$){if(!this.db)return;let X=await y0(Z);return new Promise((K,Q)=>{let Y=this.db.transaction(p,"readwrite").objectStore(p),z=Y.get(X);z.onsuccess=()=>{let W=z.result,G={hash:X,version:a,timestamp:Date.now(),transpile:$.transpile??W?.transpile,tjs:$.tjs??W?.tjs},J=Y.put(G);J.onerror=()=>Q(J.error),J.onsuccess=()=>K()},z.onerror=()=>Q(z.error)})}async delete(Z){if(!this.db)return;let $=await y0(Z);return new Promise((X,K)=>{let Y=this.db.transaction(p,"readwrite").objectStore(p).delete($);Y.onerror=()=>K(Y.error),Y.onsuccess=()=>X()})}async clear(){if(!this.db)return;return new Promise((Z,$)=>{let Q=this.db.transaction(p,"readwrite").objectStore(p).clear();Q.onerror=()=>$(Q.error),Q.onsuccess=()=>{this.stats={hits:0,misses:0},Z()}})}async prune(Z){if(!this.db)return 0;let $=Date.now()-Z;return new Promise((X,K)=>{let Y=this.db.transaction(p,"readwrite").objectStore(p).index("timestamp"),z=IDBKeyRange.upperBound($),W=0,G=Y.openCursor(z);G.onsuccess=(J)=>{let U=J.target.result;if(U)U.delete(),W++,U.continue();else X(W)},G.onerror=()=>K(G.error)})}async pruneOldVersions(){if(!this.db)return 0;return new Promise((Z,$)=>{let K=this.db.transaction(p,"readwrite").objectStore(p),Q=0,H=K.openCursor();H.onsuccess=(Y)=>{let z=Y.target.result;if(z){if(z.value.version!==a)z.delete(),Q++;z.continue()}else Z(Q)},H.onerror=()=>$(H.error)})}async getStats(){let Z=await this.count(),$=await this.estimateSize(),X=this.stats.hits+this.stats.misses,K=X>0?this.stats.hits/X:0;return{entries:Z,bytes:$,hits:this.stats.hits,misses:this.stats.misses,hitRate:K}}async count(){if(!this.db)return 0;return new Promise((Z,$)=>{let Q=this.db.transaction(p,"readonly").objectStore(p).count();Q.onerror=()=>$(Q.error),Q.onsuccess=()=>Z(Q.result)})}async estimateSize(){if(!this.db)return 0;if(typeof navigator<"u"&&navigator.storage?.estimate)try{return(await navigator.storage.estimate()).usage??0}catch{}return new Promise((Z,$)=>{let K=this.db.transaction(p,"readonly").objectStore(p),Q=0,H=K.openCursor();H.onsuccess=(Y)=>{let z=Y.target.result;if(z)Q+=JSON.stringify(z.value).length*2,z.continue();else Z(Q)},H.onerror=()=>$(H.error)})}close(){if(this.db)this.db.close(),this.db=null}isAvailable(){return this.db!==null}resetStats(){this.stats={hits:0,misses:0}}}var t1=null;async function h0(){if(!t1)t1=new F4,await t1.open();return t1}function TZ(Z){t1=Z}function x0(Z,$,X,K,Q){if(!X)X=C;(function H(Y,z,W){var G=W||Y.type;if(X[G](Y,z,H),$[G])$[G](Y,z)})(Z,K,Q)}function w6(Z,$,X,K,Q){var H=[];if(!X)X=C;(function Y(z,W,G){var J=G||z.type,U=z!==H[H.length-1];if(U)H.push(z);if(X[J](z,W,Y),$[J])$[J](z,W||H,H);if(U)H.pop()})(Z,K,Q)}function w4(Z,$,X){X(Z,$)}function N1(Z,$,X){}var C={};C.Program=C.BlockStatement=C.StaticBlock=function(Z,$,X){for(var K=0,Q=Z.body;K<Q.length;K+=1){var H=Q[K];X(H,$,"Statement")}};C.Statement=w4;C.EmptyStatement=N1;C.ExpressionStatement=C.ParenthesizedExpression=C.ChainExpression=function(Z,$,X){return X(Z.expression,$,"Expression")};C.IfStatement=function(Z,$,X){if(X(Z.test,$,"Expression"),X(Z.consequent,$,"Statement"),Z.alternate)X(Z.alternate,$,"Statement")};C.LabeledStatement=function(Z,$,X){return X(Z.body,$,"Statement")};C.BreakStatement=C.ContinueStatement=N1;C.WithStatement=function(Z,$,X){X(Z.object,$,"Expression"),X(Z.body,$,"Statement")};C.SwitchStatement=function(Z,$,X){X(Z.discriminant,$,"Expression");for(var K=0,Q=Z.cases;K<Q.length;K+=1){var H=Q[K];X(H,$)}};C.SwitchCase=function(Z,$,X){if(Z.test)X(Z.test,$,"Expression");for(var K=0,Q=Z.consequent;K<Q.length;K+=1){var H=Q[K];X(H,$,"Statement")}};C.ReturnStatement=C.YieldExpression=C.AwaitExpression=function(Z,$,X){if(Z.argument)X(Z.argument,$,"Expression")};C.ThrowStatement=C.SpreadElement=function(Z,$,X){return X(Z.argument,$,"Expression")};C.TryStatement=function(Z,$,X){if(X(Z.block,$,"Statement"),Z.handler)X(Z.handler,$);if(Z.finalizer)X(Z.finalizer,$,"Statement")};C.CatchClause=function(Z,$,X){if(Z.param)X(Z.param,$,"Pattern");X(Z.body,$,"Statement")};C.WhileStatement=C.DoWhileStatement=function(Z,$,X){X(Z.test,$,"Expression"),X(Z.body,$,"Statement")};C.ForStatement=function(Z,$,X){if(Z.init)X(Z.init,$,"ForInit");if(Z.test)X(Z.test,$,"Expression");if(Z.update)X(Z.update,$,"Expression");X(Z.body,$,"Statement")};C.ForInStatement=C.ForOfStatement=function(Z,$,X){X(Z.left,$,"ForInit"),X(Z.right,$,"Expression"),X(Z.body,$,"Statement")};C.ForInit=function(Z,$,X){if(Z.type==="VariableDeclaration")X(Z,$);else X(Z,$,"Expression")};C.DebuggerStatement=N1;C.FunctionDeclaration=function(Z,$,X){return X(Z,$,"Function")};C.VariableDeclaration=function(Z,$,X){for(var K=0,Q=Z.declarations;K<Q.length;K+=1){var H=Q[K];X(H,$)}};C.VariableDeclarator=function(Z,$,X){if(X(Z.id,$,"Pattern"),Z.init)X(Z.init,$,"Expression")};C.Function=function(Z,$,X){if(Z.id)X(Z.id,$,"Pattern");for(var K=0,Q=Z.params;K<Q.length;K+=1){var H=Q[K];X(H,$,"Pattern")}X(Z.body,$,Z.expression?"Expression":"Statement")};C.Pattern=function(Z,$,X){if(Z.type==="Identifier")X(Z,$,"VariablePattern");else if(Z.type==="MemberExpression")X(Z,$,"MemberPattern");else X(Z,$)};C.VariablePattern=N1;C.MemberPattern=w4;C.RestElement=function(Z,$,X){return X(Z.argument,$,"Pattern")};C.ArrayPattern=function(Z,$,X){for(var K=0,Q=Z.elements;K<Q.length;K+=1){var H=Q[K];if(H)X(H,$,"Pattern")}};C.ObjectPattern=function(Z,$,X){for(var K=0,Q=Z.properties;K<Q.length;K+=1){var H=Q[K];if(H.type==="Property"){if(H.computed)X(H.key,$,"Expression");X(H.value,$,"Pattern")}else if(H.type==="RestElement")X(H.argument,$,"Pattern")}};C.Expression=w4;C.ThisExpression=C.Super=C.MetaProperty=N1;C.ArrayExpression=function(Z,$,X){for(var K=0,Q=Z.elements;K<Q.length;K+=1){var H=Q[K];if(H)X(H,$,"Expression")}};C.ObjectExpression=function(Z,$,X){for(var K=0,Q=Z.properties;K<Q.length;K+=1){var H=Q[K];X(H,$)}};C.FunctionExpression=C.ArrowFunctionExpression=C.FunctionDeclaration;C.SequenceExpression=function(Z,$,X){for(var K=0,Q=Z.expressions;K<Q.length;K+=1){var H=Q[K];X(H,$,"Expression")}};C.TemplateLiteral=function(Z,$,X){for(var K=0,Q=Z.quasis;K<Q.length;K+=1){var H=Q[K];X(H,$)}for(var Y=0,z=Z.expressions;Y<z.length;Y+=1){var W=z[Y];X(W,$,"Expression")}};C.TemplateElement=N1;C.UnaryExpression=C.UpdateExpression=function(Z,$,X){X(Z.argument,$,"Expression")};C.BinaryExpression=C.LogicalExpression=function(Z,$,X){X(Z.left,$,"Expression"),X(Z.right,$,"Expression")};C.AssignmentExpression=C.AssignmentPattern=function(Z,$,X){X(Z.left,$,"Pattern"),X(Z.right,$,"Expression")};C.ConditionalExpression=function(Z,$,X){X(Z.test,$,"Expression"),X(Z.consequent,$,"Expression"),X(Z.alternate,$,"Expression")};C.NewExpression=C.CallExpression=function(Z,$,X){if(X(Z.callee,$,"Expression"),Z.arguments)for(var K=0,Q=Z.arguments;K<Q.length;K+=1){var H=Q[K];X(H,$,"Expression")}};C.MemberExpression=function(Z,$,X){if(X(Z.object,$,"Expression"),Z.computed)X(Z.property,$,"Expression")};C.ExportNamedDeclaration=C.ExportDefaultDeclaration=function(Z,$,X){if(Z.declaration)X(Z.declaration,$,Z.type==="ExportNamedDeclaration"||Z.declaration.id?"Statement":"Expression");if(Z.source)X(Z.source,$,"Expression")};C.ExportAllDeclaration=function(Z,$,X){if(Z.exported)X(Z.exported,$);X(Z.source,$,"Expression")};C.ImportDeclaration=function(Z,$,X){for(var K=0,Q=Z.specifiers;K<Q.length;K+=1){var H=Q[K];X(H,$)}X(Z.source,$,"Expression")};C.ImportExpression=function(Z,$,X){X(Z.source,$,"Expression")};C.ImportSpecifier=C.ImportDefaultSpecifier=C.ImportNamespaceSpecifier=C.Identifier=C.PrivateIdentifier=C.Literal=N1;C.TaggedTemplateExpression=function(Z,$,X){X(Z.tag,$,"Expression"),X(Z.quasi,$,"Expression")};C.ClassDeclaration=C.ClassExpression=function(Z,$,X){return X(Z,$,"Class")};C.Class=function(Z,$,X){if(Z.id)X(Z.id,$,"Pattern");if(Z.superClass)X(Z.superClass,$,"Expression");X(Z.body,$)};C.ClassBody=function(Z,$,X){for(var K=0,Q=Z.body;K<Q.length;K+=1){var H=Q[K];X(H,$)}};C.MethodDefinition=C.PropertyDefinition=C.Property=function(Z,$,X){if(Z.computed)X(Z.key,$,"Expression");if(Z.value)X(Z.value,$,"Expression")};var gZ={unusedVariables:!0,undefinedVariables:!0,unreachableCode:!0,noExplicitNew:!0};function bZ(Z,$={}){let X={...gZ,...$},K=[],Q;try{Q=W1(Z,{filename:X.filename,colonShorthand:!0}).ast}catch(Y){return{diagnostics:[{severity:"error",message:Y.message,line:Y.loc?.line,column:Y.loc?.column,rule:"parse-error"}],valid:!1}}let H=[P6()];if(w6(Q,{FunctionDeclaration(Y,z,W){let G=P6();H.push(G);for(let J of Y.params)fZ(G,J,"parameter");if(Y.id)(H[H.length-2]||H[0]).declarations.set(Y.id.name,{node:Y.id,kind:"function",used:!1})},VariableDeclaration(Y){let z=H[H.length-1];for(let W of Y.declarations)if(W.id.type==="Identifier")z.declarations.set(W.id.name,{node:W.id,kind:Y.kind,used:!1})}}),x0(Q,{Identifier(Y){for(let z=H.length-1;z>=0;z--){let W=H[z].declarations.get(Y.name);if(W){W.used=!0;break}}}}),X.unusedVariables)for(let Y of H)for(let[z,W]of Y.declarations){if(z.startsWith("_"))continue;if(!W.used&&W.kind!=="function")K.push({severity:"warning",message:`'${z}' is declared but never used`,line:W.node.loc?.start?.line,column:W.node.loc?.start?.column,rule:"no-unused-vars"})}if(X.unreachableCode)x0(Q,{BlockStatement(Y){let z=!1;for(let W of Y.body){if(z){K.push({severity:"warning",message:"Unreachable code after return statement",line:W.loc?.start?.line,column:W.loc?.start?.column,rule:"no-unreachable"});break}if(W.type==="ReturnStatement")z=!0}}});if(X.noExplicitNew)x0(Q,{NewExpression(Y){let z="class";if(Y.callee.type==="Identifier")z=Y.callee.name;else if(Y.callee.type==="MemberExpression"){if(Y.callee.property.type==="Identifier")z=Y.callee.property.name}K.push({severity:"warning",message:`Unnecessary 'new' keyword. In TJS, classes are callable without 'new': ${z}(...) instead of new ${z}(...)`,line:Y.loc?.start?.line,column:Y.loc?.start?.column,rule:"no-explicit-new"})}});return{diagnostics:K,valid:K.filter((Y)=>Y.severity==="error").length===0}}function P6(){return{declarations:new Map}}function fZ(Z,$,X){if($.type==="Identifier")Z.declarations.set($.name,{node:$,kind:X,used:!1});else if($.type==="AssignmentPattern"&&$.left.type==="Identifier")Z.declarations.set($.left.name,{node:$.left,kind:X,used:!1})}function vZ(Z){let $=[],X=0,K=null;for(let Q=0;Q<Z.length;Q++){let H=Z[Q],Y=Q>0?Z[Q-1]:"";if(!K&&(H==='"'||H==="'"||H==="`"))K=H;else if(K&&H===K&&Y!=="\\")K=null;if(!K){if(H==="{")X++;if(H==="}")X--}$[Q]=X}return $}function C6(Z){let $=[],X=vZ(Z),K=/\/\*#([\s\S]*?)\*\//g,Q=/function\s+(\w+)\s*\(([^)]*)\)\s*(?:(-[>?!])\s*('[^']*'|"[^"]*"|[^\s{]+)|:\s*(\w+))?\s*\{/g,H=[],Y;while((Y=K.exec(Z))!==null){if(X[Y.index]!==0)continue;let W=Y[1],G=W.split(`
|
|
297
332
|
`),J=G.filter((U)=>U.trim().length>0).reduce((U,_)=>{let D=_.match(/^(\s*)/)?.[1].length||0;return Math.min(U,D)},1/0);if(J>0&&J<1/0)W=G.map((U)=>U.slice(J)).join(`
|
|
298
333
|
`);H.push({type:"doc",index:Y.index,data:W.trim()})}while((Y=Q.exec(Z))!==null){let W=Y[1],G=Y[2],J=Y[3]||"",U=Y[4]||"",_=Y[5]||"",D=`function ${W}(${G})`;if(J)D+=` ${J} ${U}`;else if(_)D+=`: ${_}`;H.push({type:"function",index:Y.index,data:{name:W,signature:D}})}H.sort((W,G)=>W.index-G.index);for(let W of H)if(W.type==="doc")$.push({type:"doc",content:W.data});else $.push({type:"function",name:W.data.name,signature:W.data.signature});let z=$.map((W)=>{if(W.type==="doc")return W.content;else return`\`\`\`tjs
|
|
299
334
|
${W.signature}
|
|
@@ -312,8 +347,8 @@ ${Q.signature}
|
|
|
312
347
|
`}K+=`
|
|
313
348
|
`}if(H?.returns)K+=`**Returns:** ${H.returns.kind||"void"}
|
|
314
349
|
|
|
315
|
-
`}return K.trim()||"*No documentation available*"}import{s as L,validate as P4,filter as k6}from"tosijs-schema";class e{$error=!0;message;op;cause;constructor(Z,$,X){this.message=Z,this.op=$,this.cause=X}toString(){return`AgentError[${this.op}]: ${this.message}`}toJSON(){return{$error:!0,message:this.message,op:this.op}}}function zK(Z){return Z instanceof e||Z&&Z.$error===!0}var v1=new Map,hZ=3600000,xZ=102400,C4="proc_";function V4(Z){return typeof Z==="string"&&Z.startsWith(C4)}function O4(Z){let $=v1.get(Z);if(!$)throw Error(`Procedure not found: ${Z}`);if(Date.now()>$.expiresAt)throw v1.delete(Z),Error(`Procedure expired: ${Z}`);return $.ast}function uZ(){if(typeof crypto<"u"&&crypto.randomUUID)return C4+crypto.randomUUID();return C4+Math.random().toString(36).slice(2)+Date.now().toString(36)}var g6=new Set(["__proto__","constructor","prototype"]);function V6(Z){if(g6.has(Z))throw Error(`Security Error: Access to '${Z}' is forbidden`)}var dZ=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","metadata.google.internal"]);function mZ(Z){try{let $=new URL(Z);if($.protocol!=="http:"&&$.protocol!=="https:")return!0;let X=$.hostname.toLowerCase();if(dZ.has(X))return!0;if(X.endsWith(".internal")||X.endsWith(".local"))return!0;if(X==="169.254.169.254")return!0;if(/^10\./.test(X)||/^192\.168\./.test(X)||/^172\.(1[6-9]|2\d|3[01])\./.test(X))return!0;return!1}catch{return!0}}function lZ(Z){if(/\([^)]*[+*][^)]*\)[+*]/.test(Z))return!0;if(/\(([^|)]+)\|\1\)[+*]/.test(Z))return!0;if(/\(\.\*\)\+/.test(Z))return!0;if(/\(\.\+\)\+/.test(Z))return!0;if(/\(\[.*\]\+\)\+/.test(Z))return!0;return!1}function R1(Z){return{...Z,state:Object.create(Z.state)}}function iZ(Z,$){let X={},K=new Set([...Object.keys(Z),...Object.keys($)]);for(let Q of K){let H=Z[Q],Y=$[Q];if(Y!==H)X[Q]=Y}return X}function F(Z,$){if(Z&&typeof Z==="object"&&Z.$kind==="arg")return $.args[Z.path];if(Z&&typeof Z==="object"&&Z.$expr)return u(Z,$);if(typeof Z==="string"){if(Z.startsWith("args.")&&!("args"in $.state))return $.args[Z.replace("args.","")];if(Z.includes(".")){let X=Z.split(".");for(let Q of X)if(g6.has(Q))throw Error(`Security Error: Access to '${Q}' is forbidden`);let K=$.state[X[0]];if(K!==void 0){for(let Q=1;Q<X.length;Q++)K=K?.[X[Q]];return K}}if(Z in $.state)return $.state[Z];return Z}if(Z&&typeof Z==="object"&&!Array.isArray(Z)&&Z.constructor===Object){let X={};for(let K of Object.keys(Z))X[K]=F(Z[K],$);return X}if(Array.isArray(Z))return Z.map((X)=>F(X,$));return Z}function E1(Z,$,X){return new Proxy($,{get(K,Q){if(Q in K)return K[Q];let H=X?.[Q];if(H)throw Error(`${Z}.${Q} is not available. ${H}`);throw Error(`${Z}.${Q} is not supported in AsyncJS. Check docs for available ${Z} methods.`)}})}function b1(Z){if(Z===null)return{type:"null"};if(Z===void 0)return{};if(typeof Z==="object"&&Z!==null&&"type"in Z&&typeof Z.type==="string")return Z;if(typeof Z==="object"&&Z!==null&&"schema"in Z&&typeof Z.schema==="object")return Z.schema;let $=typeof Z;if($==="string")return{type:"string"};if($==="number")return Number.isInteger(Z)?{type:"integer"}:{type:"number"};if($==="boolean")return{type:"boolean"};if(Array.isArray(Z)){if(Z.length===0)return{type:"array"};return{type:"array",items:b1(Z[0])}}if($==="object"){let X={},K=[];for(let[Q,H]of Object.entries(Z))X[Q]=b1(H),K.push(Q);return{type:"object",properties:X,required:K}}return{}}var L1={Math:E1("Math",{PI:Math.PI,E:Math.E,LN2:Math.LN2,LN10:Math.LN10,LOG2E:Math.LOG2E,LOG10E:Math.LOG10E,SQRT2:Math.SQRT2,SQRT1_2:Math.SQRT1_2,abs:Math.abs,ceil:Math.ceil,floor:Math.floor,round:Math.round,trunc:Math.trunc,sign:Math.sign,sqrt:Math.sqrt,cbrt:Math.cbrt,pow:Math.pow,exp:Math.exp,expm1:Math.expm1,log:Math.log,log2:Math.log2,log10:Math.log10,log1p:Math.log1p,sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,atan2:Math.atan2,sinh:Math.sinh,cosh:Math.cosh,tanh:Math.tanh,asinh:Math.asinh,acosh:Math.acosh,atanh:Math.atanh,hypot:Math.hypot,min:Math.min,max:Math.max,clz32:Math.clz32,imul:Math.imul,fround:Math.fround,random:()=>{if(typeof crypto<"u"&&crypto.getRandomValues){let Z=new Uint32Array(1);return crypto.getRandomValues(Z),Z[0]/4294967296}return Math.random()}}),JSON:E1("JSON",{parse:(Z)=>JSON.parse(Z),stringify:(Z,$,X)=>JSON.stringify(Z,$,X)}),console:E1("console",{log:(...Z)=>{return},warn:(...Z)=>{return},error:(...Z)=>{return},info:(...Z)=>{return}},{table:"Use console.log with JSON.stringify for structured data.",dir:"Use console.log instead.",trace:"Stack traces are not available in AsyncJS."}),Array:E1("Array",{isArray:(Z)=>Array.isArray(Z),from:(Z,$,X)=>Array.from(Z,$,X),of:(...Z)=>Array.of(...Z)},{prototype:"Prototype access is not allowed."}),Object:E1("Object",{keys:(Z)=>Object.keys(Z),values:(Z)=>Object.values(Z),entries:(Z)=>Object.entries(Z),fromEntries:(Z)=>Object.fromEntries(Z),assign:(Z,...$)=>Object.assign({},Z,...$),hasOwn:(Z,$)=>Object.hasOwn(Z,$)},{prototype:"Prototype access is not allowed.",create:"Use object literals instead.",defineProperty:"Property descriptors are not supported.",getPrototypeOf:"Prototype access is not allowed.",setPrototypeOf:"Prototype modification is not allowed."}),String:E1("String",{fromCharCode:(...Z)=>String.fromCharCode(...Z),fromCodePoint:(...Z)=>String.fromCodePoint(...Z)}),Number:E1("Number",{isNaN:Number.isNaN,isFinite:Number.isFinite,isInteger:Number.isInteger,isSafeInteger:Number.isSafeInteger,parseFloat,parseInt,MAX_VALUE:Number.MAX_VALUE,MIN_VALUE:Number.MIN_VALUE,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,MIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,POSITIVE_INFINITY:Number.POSITIVE_INFINITY,NEGATIVE_INFINITY:Number.NEGATIVE_INFINITY,NaN:Number.NaN,EPSILON:Number.EPSILON}),parseInt,parseFloat,isNaN,isFinite,encodeURI,decodeURI,encodeURIComponent,decodeURIComponent,undefined:void 0,null:null,NaN:NaN,Infinity:1/0,filter:(Z,$)=>{let X=b1($),K=k6(Z,X);if(K instanceof Error)throw K;return K},Schema:{...L,response:(Z,$)=>{let X=$?.schema!=null?$.schema:b1($);return{type:"json_schema",json_schema:{name:Z,strict:!0,schema:X}}},fromExample:(Z)=>b1(Z),isValid:(Z,$)=>{if($?.schema!=null)return P4(Z,$);return P4(Z,b1($))}},Set:(Z=[])=>{let $=[...new globalThis.Set(Z)];return{add(X){if(!$.includes(X))$.push(X);return this},remove(X){let K=$.indexOf(X);if(K!==-1)$.splice(K,1);return this},clear(){return $.length=0,this},has(X){return $.includes(X)},get size(){return $.length},toArray(){return[...$]},union(X){let K=X?.toArray?.()??X??[];return L1.Set([...$,...K])},intersection(X){let K=X?.toArray?.()??X??[];return L1.Set($.filter((Q)=>K.includes(Q)))},diff(X){let K=X?.toArray?.()??X??[];return L1.Set($.filter((Q)=>!K.includes(Q)))},forEach(X){$.forEach(X)},map(X){return L1.Set($.map(X))},filter(X){return L1.Set($.filter(X))},toJSON(){return[...$]}}},Date:(()=>{let Z=(X)=>({get value(){return X.toISOString()},get timestamp(){return X.getTime()},get year(){return X.getFullYear()},get month(){return X.getMonth()+1},get day(){return X.getDate()},get hours(){return X.getHours()},get minutes(){return X.getMinutes()},get seconds(){return X.getSeconds()},get dayOfWeek(){return X.getDay()},add({years:K=0,months:Q=0,days:H=0,hours:Y=0,minutes:z=0,seconds:W=0,ms:G=0}={}){let J=new globalThis.Date(X.getTime());if(K)J.setFullYear(J.getFullYear()+K);if(Q)J.setMonth(J.getMonth()+Q);if(H)J.setDate(J.getDate()+H);if(Y)J.setHours(J.getHours()+Y);if(z)J.setMinutes(J.getMinutes()+z);if(W)J.setSeconds(J.getSeconds()+W);if(G)J.setMilliseconds(J.getMilliseconds()+G);return Z(J)},diff(K,Q="ms"){let H=typeof K==="object"&&K.timestamp?K.timestamp:new globalThis.Date(K).getTime(),Y=X.getTime()-H;switch(Q){case"seconds":return Y/1000;case"minutes":return Y/60000;case"hours":return Y/3600000;case"days":return Y/86400000;default:return Y}},format(K="ISO"){if(K==="ISO")return X.toISOString();if(K==="date")return X.toISOString().split("T")[0];if(K==="time")return X.toISOString().split("T")[1].split(".")[0];return K.replace("YYYY",String(X.getFullYear())).replace("MM",String(X.getMonth()+1).padStart(2,"0")).replace("DD",String(X.getDate()).padStart(2,"0")).replace("HH",String(X.getHours()).padStart(2,"0")).replace("mm",String(X.getMinutes()).padStart(2,"0")).replace("ss",String(X.getSeconds()).padStart(2,"0"))},isBefore(K){let Q=typeof K==="object"&&K.timestamp?K.timestamp:new globalThis.Date(K).getTime();return X.getTime()<Q},isAfter(K){let Q=typeof K==="object"&&K.timestamp?K.timestamp:new globalThis.Date(K).getTime();return X.getTime()>Q},toString(){return X.toISOString()},toJSON(){return X.toISOString()}}),$=(X)=>{let K=X!==void 0?new globalThis.Date(X):new globalThis.Date;if(isNaN(K.getTime()))throw Error(`Invalid date: ${X}`);return Z(K)};return $.now=()=>globalThis.Date.now(),$.parse=(X)=>Z(new globalThis.Date(X)),$})()},u0={RegExp:"RegExp is not available. Use string methods or the regexMatch atom.",Promise:"Promise is not needed. All operations are implicitly async.",Map:"Map is not available. Use plain objects instead.",WeakSet:"WeakSet is not available.",WeakMap:"WeakMap is not available.",Symbol:"Symbol is not available.",Proxy:"Proxy is not available.",Reflect:"Reflect is not available.",Function:"Function constructor is not available. Define functions normally.",eval:"eval is not available. Code is compiled, not evaluated.",setTimeout:"setTimeout is not available. Use the delay atom.",setInterval:"setInterval is not available. Use while loops with delay.",fetch:"fetch is not available. Use the httpFetch atom.",require:"require is not available. Atoms must be registered with the VM.",import:"import is not available. Atoms must be registered with the VM.",process:"process is not available. AsyncJS runs in a sandboxed environment.",window:"window is not available. AsyncJS runs in a sandboxed environment.",document:"document is not available. AsyncJS runs in a sandboxed environment.",global:"global is not available. AsyncJS runs in a sandboxed environment.",globalThis:"globalThis is not available. Use builtins directly."},pZ=0.01,O6=0.0001,N6=0.001,nZ=new Set(["concat","slice","map","filter","flatMap","flat","toReversed","toSorted","toSpliced","repeat","padStart","padEnd","split","join","replace","replaceAll","substring","substr","trim","trimStart","trimEnd","toLowerCase","toUpperCase","match","matchAll","parse","stringify"]);function u(Z,$){if(Z===null||Z===void 0)return Z;if(typeof Z!=="object"||!("$expr"in Z))return Z;if($.fuel){if($.fuel.current-=pZ,$.fuel.current<=0)throw Error("Out of Fuel")}switch(Z.$expr){case"literal":return Z.value;case"ident":{if(Z.name in $.state)return $.state[Z.name];if(Z.name in $.args)return $.args[Z.name];if(Z.name in L1)return L1[Z.name];if(Z.name in u0)throw Error(u0[Z.name]);return}case"member":{let X=u(Z.object,$);if(Z.optional&&(X===null||X===void 0))return;let K=Z.property;return V6(K),X?.[K]}case"binary":{let X=u(Z.left,$),K=u(Z.right,$);switch(Z.op){case"+":{let Q=X+K;if(typeof Q==="string"&&$.fuel){if($.fuel.current-=Q.length*O6,$.fuel.current<=0){$.error=new e("Out of Fuel","expr.concat");return}}return Q}case"-":return X-K;case"*":return X*K;case"/":return X/K;case"%":return X%K;case"**":return X**K;case">":return X>K;case"<":return X<K;case">=":return X>=K;case"<=":return X<=K;case"==":return X==K;case"!=":return X!=K;case"===":return X===K;case"!==":return X!==K;default:throw Error(`Unknown binary operator: ${Z.op}`)}}case"unary":{let X=u(Z.argument,$);switch(Z.op){case"!":return!X;case"-":return-X;case"+":return+X;case"typeof":return typeof X;default:throw Error(`Unknown unary operator: ${Z.op}`)}}case"logical":{let X=u(Z.left,$);if(Z.op==="&&")return X?u(Z.right,$):X;else if(Z.op==="??")return X??u(Z.right,$);else return X?X:u(Z.right,$)}case"conditional":return u(Z.test,$)?u(Z.consequent,$):u(Z.alternate,$);case"array":return Z.elements.map((X)=>u(X,$));case"object":{let X={};for(let K of Z.properties)X[K.key]=u(K.value,$);return X}case"call":{if(Z.callee==="Error"){let K=Z.arguments.map((H)=>u(H,$)),Q=typeof K[0]==="string"?K[0]:"Error";$.error=new e(Q,"Error");return}if(Z.callee in L1){let K=L1[Z.callee];if(typeof K==="function"){let Q=Z.arguments.map((H)=>u(H,$));return K(...Q)}}if(!$.resolver(Z.callee)){if(Z.callee in u0)throw Error(u0[Z.callee]);throw Error(`Unknown function: ${Z.callee}`)}throw Error(`Atom calls in expressions not yet supported: ${Z.callee}`)}case"methodCall":{let X=u(Z.object,$);if(Z.optional&&(X===null||X===void 0))return;let K=Z.method;if(V6(K),X===null||X===void 0)throw Error(`Cannot call method '${K}' on ${X}`);let Q=X[K];if(typeof Q!=="function")throw Error(`'${K}' is not a function`);let H=Z.arguments.map((z)=>u(z,$)),Y=Q.apply(X,H);if($.fuel&&nZ.has(K)){let z=0;if(typeof Y==="string")z=Y.length*O6;else if(Array.isArray(Y))z=Y.length*N6;else if(typeof Y==="object"&&Y!==null)z=Object.keys(Y).length*N6;if($.fuel.current-=z,$.fuel.current<=0){$.error=new e("Out of Fuel",`expr.${K}`);return}}return Y}default:throw Error(`Unknown expression type: ${Z.$expr}`)}}function E(Z,$,X,K,Q={}){let{docs:H="",timeoutMs:Y=1000,cost:z=1}=typeof Q==="string"?{docs:Q}:Q;return{op:Z,inputSchema:$,outputSchema:X,exec:async(G,J)=>{let{op:U,result:_,...D}=G;if(J.error)return;let I=J.trace?{...J.state}:null,B=J.fuel.current,A,j;try{let P=J.costOverrides?.[Z],N=P!==void 0?P:z,M=typeof N==="function"?N(D,J):N;if((J.fuel.current-=M)<=0){J.error=new e("Out of Fuel",Z);return}let w,V=async()=>K(G,J);if(A=Y>0?await Promise.race([V(),new Promise((O,S)=>{w=setTimeout(()=>S(Error(`Atom '${Z}' timed out`)),Y)})]).finally(()=>clearTimeout(w)):await V(),G.result){if(J.consts.has(G.result))throw Error(`Cannot reassign const variable '${G.result}'`);if(A!==void 0&&X&&!P4(A,X)){J.error=new e(`Output validation failed for '${Z}'`,Z);return}if(J.state[G.result]=A,G.resultConst)J.consts.add(G.result)}}catch(P){j=P.message||String(P),J.error=new e(j,Z,P)}finally{if(J.trace&&I){let P=iZ(I,J.state);J.trace.push({op:Z,input:D,stateDiff:P,result:A,error:j,fuelBefore:B,fuelAfter:J.fuel.current,timestamp:new Date().toISOString()})}}},docs:H,timeoutMs:Y,cost:z,create:(G)=>({op:Z,...G})}}var $1=E("seq",L.object({steps:L.array(L.any)}),void 0,async({steps:Z},$)=>{for(let X of Z){if($.output!==void 0)return;if($.error)return;let K=$.resolver(X.op);if(!K)throw Error(`Unknown Atom: ${X.op}`);await K.exec(X,$)}},{docs:"Sequence",timeoutMs:0,cost:0.1}),cZ=E("if",L.object({condition:L.any,then:L.array(L.any),else:L.array(L.any).optional}),void 0,async(Z,$)=>{if(u(Z.condition,$))await $1.exec({op:"seq",steps:Z.then},$);else if(Z.else)await $1.exec({op:"seq",steps:Z.else},$)},{docs:"If/Else",timeoutMs:0,cost:0.1}),oZ=E("while",L.object({condition:L.any,body:L.array(L.any)}),void 0,async(Z,$)=>{while(u(Z.condition,$)){if($.signal?.aborted)throw Error("Execution aborted");if(($.fuel.current-=0.1)<=0)throw Error("Out of Fuel");if(await $1.exec({op:"seq",steps:Z.body},$),$.output!==void 0)return}},{docs:"While Loop",timeoutMs:0,cost:0.1}),sZ=E("return",void 0,L.any,async(Z,$)=>{if($.error)return $.output=$.error,$.error;if("value"in Z){let K=F(Z.value,$);return $.output=K,K}let X={};if(Z.schema?.properties){for(let K of Object.keys(Z.schema.properties))X[K]=$.state[K];if(Z.filter!==!1){let K=k6(X,Z.schema);if(!(K instanceof Error))X=K}}return $.output=X,X},{docs:"Return",cost:0.1}),aZ=E("try",L.object({try:L.array(L.any),catch:L.array(L.any).optional,catchParam:L.string.optional}),void 0,async(Z,$)=>{if(await $1.exec({op:"seq",steps:Z.try},$),$.error&&Z.catch){let X=Z.catchParam||"error";$.state[X]=$.error.message,$.state.errorOp=$.error.op,$.error=void 0,await $1.exec({op:"seq",steps:Z.catch},$)}},{docs:"Try/Catch",timeoutMs:0,cost:0.1}),rZ=E("Error",L.object({args:L.array(L.any).optional}),void 0,async(Z,$)=>{let X=Z.args?.[0]??"Error";$.error=new e(String(X),"Error")},{docs:"Trigger error flow",cost:0.1}),tZ=E("varSet",L.object({key:L.string,value:L.any}),void 0,async({key:Z,value:$},X)=>{if(X.consts.has(Z))throw Error(`Cannot reassign const variable '${Z}'`);X.state[Z]=F($,X)},{docs:"Set Variable",cost:0.1}),eZ=E("constSet",L.object({key:L.string,value:L.any}),void 0,async({key:Z,value:$},X)=>{if(X.consts.has(Z))throw Error(`Cannot reassign const variable '${Z}'`);if(Z in X.state)throw Error(`Cannot redeclare variable '${Z}' as const`);X.state[Z]=F($,X),X.consts.add(Z)},{docs:"Set Const Variable (immutable)",cost:0.1}),Z5=E("varGet",L.object({key:L.string}),L.any,async({key:Z},$)=>{return F(Z,$)},{docs:"Get Variable",cost:0.1}),X5=E("varsImport",L.object({keys:L.union([L.array(L.string),L.record(L.string)])}),void 0,async({keys:Z},$)=>{if(Array.isArray(Z))for(let X of Z)$.state[X]=F({$kind:"arg",path:X},$);else for(let[X,K]of Object.entries(Z))$.state[X]=F({$kind:"arg",path:K},$)},{docs:"Import variables from args into the current scope, with optional renaming.",cost:0.2}),$5=E("varsLet",L.record(L.any),void 0,async(Z,$)=>{for(let X of Object.keys(Z)){if(X==="op"||X==="result")continue;$.state[X]=F(Z[X],$)}},{docs:"Initialize a set of variables in the current scope from the step object properties.",cost:0.1}),K5=E("varsExport",L.object({keys:L.union([L.array(L.string),L.record(L.string)])}),L.record(L.any),async({keys:Z},$)=>{let X={};if(Array.isArray(Z))for(let K of Z)X[K]=F(K,$);else for(let[K,Q]of Object.entries(Z))X[K]=F(Q,$);return X},{docs:"Export variables from the current scope, with optional renaming.",cost:0.2}),Q5=E("scope",L.object({steps:L.array(L.any)}),void 0,async({steps:Z},$)=>{let X=R1($);if(await $1.exec({op:"seq",steps:Z},X),X.output!==void 0)$.output=X.output},{docs:"Create new scope",timeoutMs:0,cost:0.1}),H5=E("map",L.object({items:L.array(L.any),as:L.string,steps:L.array(L.any)}),L.array(L.any),async({items:Z,as:$,steps:X},K)=>{let Q=[],H=F(Z,K);if(!Array.isArray(H))throw Error("map: items is not an array");for(let Y of H){if(K.signal?.aborted)throw Error("Execution aborted");let z=R1(K);z.state[$]=Y,await $1.exec({op:"seq",steps:X},z),Q.push(z.state.result??null)}return Q},{docs:"Map Array",timeoutMs:0,cost:1}),Y5=E("filter",L.object({items:L.array(L.any),as:L.string,condition:L.any}),L.array(L.any),async({items:Z,as:$,condition:X},K)=>{let Q=[],H=F(Z,K);if(!Array.isArray(H))throw Error("filter: items is not an array");for(let Y of H){if(K.signal?.aborted)throw Error("Execution aborted");let z=R1(K);if(z.state[$]=Y,u(X,z))Q.push(Y)}return Q},{docs:"Filter Array",timeoutMs:0,cost:1}),z5=E("reduce",L.object({items:L.array(L.any),as:L.string,accumulator:L.string,initial:L.any,steps:L.array(L.any)}),L.any,async({items:Z,as:$,accumulator:X,initial:K,steps:Q},H)=>{let Y=F(Z,H),z=F(K,H);if(!Array.isArray(Y))throw Error("reduce: items is not an array");let W=z;for(let G of Y){if(H.signal?.aborted)throw Error("Execution aborted");let J=R1(H);J.state[$]=G,J.state[X]=W,await $1.exec({op:"seq",steps:Q},J),W=J.state.result??W}return W},{docs:"Reduce Array",timeoutMs:0,cost:1}),G5=E("find",L.object({items:L.array(L.any),as:L.string,condition:L.any}),L.any,async({items:Z,as:$,condition:X},K)=>{let Q=F(Z,K);if(!Array.isArray(Q))throw Error("find: items is not an array");for(let H of Q){if(K.signal?.aborted)throw Error("Execution aborted");let Y=R1(K);if(Y.state[$]=H,u(X,Y))return H}return null},{docs:"Find in Array",timeoutMs:0,cost:1}),W5=E("push",L.object({list:L.array(L.any),item:L.any}),L.array(L.any),async({list:Z,item:$},X)=>{let K=F(Z,X),Q=F($,X);if(Array.isArray(K))K.push(Q);return K},{docs:"Push to Array",cost:1}),J5=E("len",L.object({list:L.any}),L.number,async({list:Z},$)=>{let X=F(Z,$);return Array.isArray(X)||typeof X==="string"?X.length:0},{docs:"Length",cost:1}),_5=E("split",L.object({str:L.string,sep:L.string}),L.array(L.string),async({str:Z,sep:$},X)=>F(Z,X).split(F($,X)),{docs:"Split String",cost:1}),L5=E("join",L.object({list:L.array(L.string),sep:L.string}),L.string,async({list:Z,sep:$},X)=>F(Z,X).join(F($,X)),{docs:"Join String",cost:1}),q5=E("template",L.object({tmpl:L.string,vars:L.record(L.any)}),L.string,async({tmpl:Z,vars:$},X)=>{return F(Z,X).replace(/\{\{(\w+)\}\}/g,(Q,H)=>String(F($[H],X)??""))},{docs:"String Template",cost:1}),U5=E("regexMatch",L.object({pattern:L.string,value:L.any}),L.boolean,async({pattern:Z,value:$},X)=>{if(lZ(Z))throw Error(`Suspicious regex pattern rejected (potential ReDoS): ${Z}`);let K=F($,X);return new RegExp(Z).test(K)},{docs:"Returns true if the value matches the regex pattern.",cost:2}),D5=E("pick",L.object({obj:L.record(L.any),keys:L.array(L.string)}),L.record(L.any),async({obj:Z,keys:$},X)=>{let K=F(Z,X),Q=F($,X),H={};if(K&&Array.isArray(Q))Q.forEach((Y)=>H[Y]=K[Y]);return H},{docs:"Pick Keys",cost:1}),I5=E("omit",L.object({obj:L.record(L.any),keys:L.array(L.string)}),L.record(L.any),async({obj:Z,keys:$},X)=>{let K=F(Z,X),Q=new Set(F($,X)),H={};if(K)Object.keys(K).forEach((Y)=>{if(!Q.has(Y))H[Y]=K[Y]});return H},{docs:"Omit Keys",cost:1}),B5=E("merge",L.object({a:L.record(L.any),b:L.record(L.any)}),L.record(L.any),async({a:Z,b:$},X)=>({...F(Z,X),...F($,X)}),{docs:"Merge Objects",cost:1}),R5=E("keys",L.object({obj:L.record(L.any)}),L.array(L.string),async({obj:Z},$)=>Object.keys(F(Z,$)??{}),{docs:"Object Keys",cost:1}),E6=10,S6="X-Agent-Depth";function M5(Z,$){try{let K=new URL(Z).hostname.toLowerCase();for(let Q of $){let H=Q.toLowerCase();if(H.startsWith("*.")){let Y=H.slice(1);if(K.endsWith(Y)||K===H.slice(2))return!0}else if(K===H)return!0}return!1}catch{return!1}}var A5=E("httpFetch",L.object({url:L.string,method:L.string.optional,headers:L.record(L.string).optional,body:L.any.optional,responseType:L.string.optional}),L.any,async(Z,$)=>{let X=F(Z.url,$),K=F(Z.method,$),Q=F(Z.headers,$)||{},H=F(Z.body,$),Y=F(Z.responseType,$),z=$.context?.requestDepth??0;if(z>=E6)throw Error(`Agent request depth exceeded (max ${E6}). This prevents recursive agent loops.`);if($.capabilities.fetch)return $.capabilities.fetch(X,{method:K,headers:{...Q,[S6]:String(z+1)},body:H,signal:$.signal,responseType:Y});let W=$.context?.allowedFetchDomains;if(W){if(!M5(X,W))throw Error(`Fetch blocked: domain not in allowlist. Allowed: ${W.join(", ")}`)}else{if(mZ(X))throw Error("Blocked URL: private/internal addresses not allowed in default fetch");try{let J=new URL(X).hostname.toLowerCase();if(J!=="localhost"&&J!=="127.0.0.1"&&J!=="[::1]")throw Error("Fetch blocked: no allowedFetchDomains configured. Set ctx.context.allowedFetchDomains or provide a custom fetch capability.")}catch(G){if(G.message.includes("allowedFetchDomains"))throw G;throw Error(`Invalid URL: ${X}`)}}if(typeof globalThis.fetch==="function"){let G=await globalThis.fetch(X,{method:K,headers:{...Q,[S6]:String(z+1)},body:H?JSON.stringify(H):void 0,signal:$.signal});if(Y==="dataUrl"){let U=await G.arrayBuffer(),_=new Uint8Array(U),D="";for(let A=0;A<_.length;A++)D+=String.fromCharCode(_[A]);let I=btoa(D);return`data:${G.headers.get("content-type")||"application/octet-stream"};base64,${I}`}let J=G.headers.get("content-type");if(Y==="json"||J&&J.includes("application/json"))return G.json();return G.text()}throw Error("Capability 'fetch' missing and no global fetch available")},{docs:"HTTP Fetch",timeoutMs:30000,cost:5}),j5=E("storeGet",L.object({key:L.string}),L.any,async({key:Z},$)=>{let X=F(Z,$);return $.capabilities.store?.get(X)},{docs:"Store Get",cost:5}),F5=E("storeSet",L.object({key:L.string,value:L.any}),void 0,async({key:Z,value:$},X)=>{let K=F(Z,X),Q=F($,X);return X.capabilities.store?.set(K,Q)},{docs:"Store Set",cost:5}),w5=E("storeQuery",L.object({query:L.any}),L.array(L.any),async({query:Z},$)=>$.capabilities.store?.query?.(F(Z,$))??[],{docs:"Store Query",cost:5}),P5=E("storeVectorSearch",L.object({collection:L.string.optional,vector:L.array(L.number),k:L.number.optional}),L.array(L.any),async({collection:Z,vector:$,k:X},K)=>K.capabilities.store?.vectorSearch?.(F(Z,K),F($,K),F(X,K))??[],{docs:"Vector Search",cost:(Z,$)=>5+(F(Z.k,$)??5)}),C5=E("llmPredict",L.object({prompt:L.string,options:L.any.optional}),L.string,async({prompt:Z,options:$},X)=>{if(!X.capabilities.llm?.predict)throw Error("Capability 'llm.predict' missing");return X.capabilities.llm.predict(F(Z,X),F($,X))},{docs:"LLM Predict",timeoutMs:120000,cost:100}),V5=E("agentRun",L.object({agentId:L.any,input:L.any}),L.any,async({agentId:Z,input:$},X)=>{let K=F(Z,X),Q=F($,X),H=Q;if(Q&&typeof Q==="object"&&!Array.isArray(Q)){H={};for(let z in Q)H[z]=F(Q[z],X)}if(V4(K)){let z=O4(K),W={...X,args:H,state:{},consts:new Set,output:void 0,error:void 0},G=X.resolver("seq");if(!G)throw Error("seq atom not found");if(await G.exec(z,W),W.error)throw Error(W.error.message||"Sub-agent failed");return W.output}if(K&&typeof K==="object"&&"op"in K){let z={...X,args:H,state:{},consts:new Set,output:void 0,error:void 0},W=X.resolver("seq");if(!W)throw Error("seq atom not found");if(await W.exec(K,z),z.error)throw Error(z.error.message||"Sub-agent failed");return z.output}if(!X.capabilities.agent?.run)throw Error("Capability 'agent.run' missing");let Y=await X.capabilities.agent.run(K,H);if(Y&&typeof Y==="object"&&"fuelUsed"in Y&&typeof Y.fuelUsed==="number"){if(Y.error)throw Error(Y.error.message||"Sub-agent failed");return Y.result}return Y},{docs:"Run Sub-Agent (accepts procedure token, AST, or agent ID)",cost:1}),O5=E("transpileCode",L.object({code:L.string}),L.any,async({code:Z},$)=>{if(!$.capabilities.code?.transpile)throw Error("Capability 'code.transpile' missing. Enable code transpilation by providing the code capability.");let X=F(Z,$);try{return $.capabilities.code.transpile(X)}catch(K){throw Error(`Code transpilation failed: ${K.message}`)}},{docs:"Transpile AsyncJS code to AST",cost:1}),T6=10,N5=E("runCode",L.object({code:L.string,args:L.record(L.any).optional}),L.any,async({code:Z,args:$},X)=>{let K=X.runCodeDepth??0;if(K>=T6)throw Error(`runCode recursion limit exceeded (max ${T6}). This prevents infinite loops from dynamically generated code calling runCode.`);if(!X.capabilities.code?.transpile)throw Error("Capability 'code.transpile' missing. Enable dynamic code execution by providing the code capability.");let Q=F(Z,X),H=$?F($,X):{},Y;try{Y=X.capabilities.code.transpile(Q)}catch(W){throw Error(`Code transpilation failed: ${W.message}`)}if(Y.op!=="seq")throw Error("Transpiled code must be a seq node");let z=R1(X);if(z.args=H,z.output=void 0,z.runCodeDepth=K+1,await $1.exec(Y,z),z.error){X.error=z.error;return}return z.output},{docs:"Run dynamically generated AsyncJS code",cost:1}),E5=E("jsonParse",L.object({str:L.string}),L.any,async({str:Z},$)=>JSON.parse(F(Z,$)),{docs:"Parse JSON",cost:1}),S5=E("jsonStringify",L.object({value:L.any}),L.string,async({value:Z},$)=>JSON.stringify(F(Z,$)),{docs:"Stringify JSON",cost:1}),T5=E("xmlParse",L.object({str:L.string}),L.any,async({str:Z},$)=>{if(!$.capabilities.xml?.parse)throw Error("Capability 'xml.parse' missing");return $.capabilities.xml.parse(F(Z,$))},{docs:"Parse XML",cost:1}),k5=E("memoize",L.object({key:L.string.optional,steps:L.array(L.any)}),L.any,async({key:Z,steps:$},X)=>{if(!X.memo)X.memo=new Map;let K=F(Z,X)??await N4.exec({value:$,algorithm:"SHA-256"},X);if(X.memo.has(K))return X.memo.get(K);let Q=R1(X);await $1.exec({op:"seq",steps:$},Q);let H=Q.output??Q.state.result;return X.memo.set(K,H),H},{docs:"Memoize steps result in memory",cost:1}),g5=E("cache",L.object({key:L.string.optional,steps:L.array(L.any),ttlMs:L.number.optional}),L.any,async({key:Z,steps:$,ttlMs:X},K)=>{if(!K.capabilities.store)throw Error("Capability 'store' missing for caching");let H=`cache:${F(Z,K)??await N4.exec({value:$,algorithm:"SHA-256"},K)}`,Y=await K.capabilities.store.get(H);if(Y)if(typeof Y==="object"&&Y._exp){if(Date.now()<Y._exp)return Y.val}else return Y;let z=R1(K);await $1.exec({op:"seq",steps:$},z);let W=z.output??z.state.result,G=Date.now()+(X??86400000);if((K.fuel.current-=5)<=0)throw Error("Out of Fuel");return await K.capabilities.store.set(H,{val:W,_exp:G}),W},{docs:"Cache steps result in store with TTL",cost:5}),b5=E("random",L.object({min:L.number.optional,max:L.number.optional,format:L.string.optional,length:L.number.optional}),L.any,async({min:Z,max:$,format:X,length:K},Q)=>{let H=F(X,Q)??"float",Y=F(K,Q)??10,z=F(Z,Q)??0,W=F($,Q)??1;if(H==="base36"){let D="";if(typeof crypto<"u"&&crypto.getRandomValues){let I=new Uint8Array(Y);crypto.getRandomValues(I);for(let B=0;B<Y;B++)D+="0123456789abcdefghijklmnopqrstuvwxyz"[I[B]%36]}else for(let I=0;I<Y;I++)D+="0123456789abcdefghijklmnopqrstuvwxyz".charAt(Math.floor(Math.random()*36));return D}let G;if(typeof crypto<"u"&&crypto.getRandomValues){let _=new Uint32Array(1);crypto.getRandomValues(_),G=_[0]/4294967296}else G=Math.random();let J=W-z,U=G*J+z;if(H==="integer")return Math.floor(U);return U},{docs:"Generate Random",cost:1}),v5=E("uuid",void 0,L.string,async()=>{if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();if(typeof crypto<"u"&&crypto.getRandomValues){let Z=new Uint8Array(16);crypto.getRandomValues(Z),Z[6]=Z[6]&15|64,Z[8]=Z[8]&63|128;let $=Array.from(Z,(X)=>X.toString(16).padStart(2,"0")).join("");return`${$.slice(0,8)}-${$.slice(8,12)}-${$.slice(12,16)}-${$.slice(16,20)}-${$.slice(20)}`}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(Z)=>{let $=Math.random()*16|0;return(Z==="x"?$:$&3|8).toString(16)})},{docs:"Generate UUID",cost:1}),N4=E("hash",L.object({value:L.any,algorithm:L.string.optional}),L.string,async({value:Z,algorithm:$},X)=>{let K=typeof Z==="string"?Z:JSON.stringify(F(Z,X)),Q=F($,X)||"SHA-256";if(typeof crypto<"u"&&crypto.subtle){let z=new TextEncoder().encode(K),W=await crypto.subtle.digest(Q,z);return Array.from(new Uint8Array(W)).map((J)=>J.toString(16).padStart(2,"0")).join("")}let H=0;for(let Y=0;Y<K.length;Y++){let z=K.charCodeAt(Y);H=(H<<5)-H+z,H|=0}return String(H)},{docs:"Hash a value",cost:1}),f5=E("consoleLog",L.object({message:L.any}),void 0,async({message:Z},$)=>{let X=F(Z,$);if($.trace)$.trace.push({op:"console.log",input:{message:X},stateDiff:{},result:X,fuelBefore:$.fuel.current,fuelAfter:$.fuel.current,timestamp:new Date().toISOString()})},{docs:"Log to trace",cost:0.1}),y5=E("consoleWarn",L.object({message:L.any}),void 0,async({message:Z},$)=>{let X=F(Z,$),K=typeof X==="string"?X:JSON.stringify(X);if(!$.warnings)$.warnings=[];if($.warnings.push(K),$.trace)$.trace.push({op:"console.warn",input:{message:X},stateDiff:{},result:X,fuelBefore:$.fuel.current,fuelAfter:$.fuel.current,timestamp:new Date().toISOString()})},{docs:"Add warning",cost:0.1}),h5=E("consoleError",L.object({message:L.any}),void 0,async({message:Z},$)=>{let X=F(Z,$),K=typeof X==="string"?X:JSON.stringify(X);$.error=new e(K,"console.error")},{docs:"Emit error and stop",cost:0.1}),x5=E("storeProcedure",L.object({ast:L.any,ttl:L.number.optional,maxSize:L.number.optional}),L.string,async({ast:Z,ttl:$,maxSize:X},K)=>{let Q=F(Z,K),H=$?F($,K):hZ,Y=X?F(X,K):xZ;if(!Q||typeof Q!=="object"||!Q.op)throw Error('Invalid AST: must be an object with an "op" property');let z=JSON.stringify(Q);if(z.length>Y)throw Error(`AST too large: ${z.length} bytes exceeds limit of ${Y} bytes. Consider reducing AST size or using a shorter TTL.`);let W=uZ(),G=Date.now();return v1.set(W,{ast:Q,createdAt:G,expiresAt:G+H}),W},{docs:"Store an AST and return a token for later execution",cost:1}),u5=E("releaseProcedure",L.object({token:L.string}),L.boolean,async({token:Z},$)=>{let X=F(Z,$);return v1.delete(X)},{docs:"Release a stored procedure by token",cost:0.1}),d5=E("clearExpiredProcedures",void 0,L.number,async()=>{let Z=Date.now(),$=0;for(let[X,K]of v1)if(Z>K.expiresAt)v1.delete(X),$++;return $},{docs:"Clear all expired procedures and return count",cost:0.5}),d0={seq:$1,if:cZ,while:oZ,return:sZ,try:aZ,Error:rZ,varSet:tZ,constSet:eZ,varGet:Z5,varsImport:X5,varsLet:$5,varsExport:K5,scope:Q5,map:H5,filter:Y5,reduce:z5,find:G5,push:W5,len:J5,split:_5,join:L5,template:q5,regexMatch:U5,pick:D5,omit:I5,merge:B5,keys:R5,httpFetch:A5,storeGet:j5,storeSet:F5,storeQuery:w5,storeVectorSearch:P5,llmPredict:C5,agentRun:V5,transpileCode:O5,runCode:N5,jsonParse:E5,jsonStringify:S5,xmlParse:T5,memoize:k5,cache:g5,random:b5,uuid:v5,hash:N4,consoleLog:f5,consoleWarn:y5,consoleError:h5,storeProcedure:x5,releaseProcedure:u5,clearExpiredProcedures:d5};var m5=new Set(["true","false","null","undefined","and","or","not"]);function l5(Z,$){let X=Z.replace(/"[^"]*"/g,'""').replace(/'[^']*'/g,"''"),K=[],Q=/(?<![.])\b([a-zA-Z_][a-zA-Z0-9_]*)\b/g,H;while((H=Q.exec(X))!==null)K.push(H[1]);let z=[...new Set(K)].filter((W)=>!m5.has(W)&&!(W in $)&&!new RegExp(`\\b${W}\\s*\\(`).test(X));if(z.length>0)console.warn(`[Agent99 Builder] Condition "${Z}" references variables not in vars mapping: ${z.join(", ")}. Add them to vars or use AsyncJS syntax (ajs\`...\`) which handles this automatically.`)}function m0(Z,$){l5(Z,$);let X=i5(Z),K=h6(X,0,$);if(K.pos<X.length){let Q=X.slice(K.pos).join(" ");throw Error(`Unsupported condition syntax near '${Q}' in: ${Z}
|
|
316
|
-
Supported: comparisons, &&, ||, !, arithmetic, member access (a.b), literals`)}return K.node}function i5(Z){let $=[],X=0;while(X<Z.length){while(X<Z.length&&/\s/.test(Z[X]))X++;if(X>=Z.length)break;if(Z[X]==='"'||Z[X]==="'"){let K=Z[X++],Q="";while(X<Z.length&&Z[X]!==K)if(Z[X]==="\\"&&X+1<Z.length)X++,Q+=Z[X++];else Q+=Z[X++];X++,$.push(JSON.stringify(Q));continue}if(Z.slice(X,X+2).match(/^(&&|\|\||==|!=|>=|<=)$/)){$.push(Z.slice(X,X+2)),X+=2;continue}if("+-*/%><!().?:[]".includes(Z[X])){$.push(Z[X]),X++;continue}if(/\d/.test(Z[X])){let K="";while(X<Z.length&&/[\d.]/.test(Z[X]))K+=Z[X++];$.push(K);continue}if(/[a-zA-Z_]/.test(Z[X])){let K="";while(X<Z.length&&/[a-zA-Z0-9_]/.test(Z[X]))K+=Z[X++];$.push(K);continue}X++}return $}function h6(Z,$,X){return p5(Z,$,X)}function p5(Z,$,X){let{node:K,pos:Q}=b6(Z,$,X);while(Z[Q]==="||"){Q++;let{node:H,pos:Y}=b6(Z,Q,X);K={$expr:"logical",op:"||",left:K,right:H},Q=Y}return{node:K,pos:Q}}function b6(Z,$,X){let{node:K,pos:Q}=v6(Z,$,X);while(Z[Q]==="&&"){Q++;let{node:H,pos:Y}=v6(Z,Q,X);K={$expr:"logical",op:"&&",left:K,right:H},Q=Y}return{node:K,pos:Q}}function v6(Z,$,X){let{node:K,pos:Q}=f6(Z,$,X),H=["==","!=",">","<",">=","<="];while(H.includes(Z[Q])){let Y=Z[Q++],{node:z,pos:W}=f6(Z,Q,X);K={$expr:"binary",op:Y,left:K,right:z},Q=W}return{node:K,pos:Q}}function f6(Z,$,X){let{node:K,pos:Q}=y6(Z,$,X);while(Z[Q]==="+"||Z[Q]==="-"){let H=Z[Q++],{node:Y,pos:z}=y6(Z,Q,X);K={$expr:"binary",op:H,left:K,right:Y},Q=z}return{node:K,pos:Q}}function y6(Z,$,X){let{node:K,pos:Q}=E4(Z,$,X);while(Z[Q]==="*"||Z[Q]==="/"||Z[Q]==="%"){let H=Z[Q++],{node:Y,pos:z}=E4(Z,Q,X);K={$expr:"binary",op:H,left:K,right:Y},Q=z}return{node:K,pos:Q}}function E4(Z,$,X){if(Z[$]==="!"||Z[$]==="-"){let K=Z[$++],{node:Q,pos:H}=E4(Z,$,X);return{node:{$expr:"unary",op:K,argument:Q},pos:H}}return n5(Z,$,X)}function n5(Z,$,X){let K=Z[$];if(K==="("){let{node:Q,pos:H}=h6(Z,$+1,X);return{node:Q,pos:H+1}}if(K&&K.startsWith('"'))return{node:{$expr:"literal",value:JSON.parse(K)},pos:$+1};if(K&&/^\d/.test(K))return{node:{$expr:"literal",value:parseFloat(K)},pos:$+1};if(K==="true")return{node:{$expr:"literal",value:!0},pos:$+1};if(K==="false")return{node:{$expr:"literal",value:!1},pos:$+1};if(K==="null")return{node:{$expr:"literal",value:null},pos:$+1};if(K&&/^[a-zA-Z_]/.test(K)){let Q={$expr:"ident",name:K},H=$+1;while(Z[H]==="."){H++;let Y=Z[H++];Q={$expr:"member",object:Q,property:Y}}return{node:Q,pos:H}}return{node:{$expr:"literal",value:null},pos:$+1}}class s{steps=[];atoms;proxy;constructor(Z){return this.atoms=Z,this.proxy=new Proxy(this,{get:($,X,K)=>{if(X in $)return $[X];if(typeof X==="string"&&X in $.atoms)return(Q)=>{let H=$.atoms[X];return $.add(H.create(Q)),K};return}}),this.proxy}add(Z){return this.steps.push(Z),this.proxy}as(Z){if(this.steps.length===0)throw Error("No step to capture");let $=this.steps[this.steps.length-1];return $.result=Z,this.proxy}step(Z){return this.add(Z)}return(Z){let $=this.atoms.return;if(!$)throw Error("Atom 'return' not found");let X=Z.schema??Z;return this.add($.create({schema:X}))}toJSON(){return{op:"seq",steps:[...this.steps]}}varsImport(Z){return this.add(this.atoms.varsImport.create({keys:Z}))}varsExport(Z){return this.add(this.atoms.varsExport.create({keys:Z}))}if(Z,$,X,K){let Q=new s(this.atoms);X(Q);let H;if(K){let W=new s(this.atoms);K(W),H=W.steps}let Y=m0(Z,$),z=this.atoms.if;return this.add(z.create({condition:Y,then:Q.steps,else:H}))}while(Z,$,X){let K=new s(this.atoms);X(K);let Q=m0(Z,$),H=this.atoms.while;return this.add(H.create({condition:Q,body:K.steps}))}scope(Z){let $=new s(this.atoms);Z($);let X=this.atoms.scope;return this.add(X.create({steps:$.steps}))}map(Z,$,X){let K=new s(this.atoms);X(K);let Q=this.atoms.map;return this.add(Q.create({items:Z,as:$,steps:K.steps}))}filter(Z,$,X,K={}){let Q=m0(X,K),H=this.atoms.filter;return this.add(H.create({items:Z,as:$,condition:Q}))}find(Z,$,X,K={}){let Q=m0(X,K),H=this.atoms.find;return this.add(H.create({items:Z,as:$,condition:Q}))}reduce(Z,$,X,K,Q){let H=new s(this.atoms);Q(H);let Y=this.atoms.reduce;return this.add(Y.create({items:Z,as:$,accumulator:X,initial:K,steps:H.steps}))}memoize(Z,$){let X=new s(this.atoms);Z(X);let K=this.atoms.memoize;return this.add(K.create({key:$,steps:X.steps}))}cache(Z,$,X){let K=new s(this.atoms);Z(K);let Q=this.atoms.cache;return this.add(Q.create({key:$,steps:K.steps,ttlMs:X}))}try(Z){let $=new s(this.atoms);Z.try($);let X;if(Z.catch){let Q=new s(this.atoms);Z.catch(Q),X=Q.steps}let K=this.atoms.try;return this.add(K.create({try:$.steps,catch:X}))}}var c5={take(Z){return new s(d0)},custom(Z){return new s(Z)},args(Z){return{$kind:"arg",path:Z}},val(Z){return Z}},JK=c5;import{validate as o5}from"tosijs-schema";function e1(Z,$={}){let{ast:X,returnType:K,originalSource:Q,requiredParams:H}=W1(Z,{filename:$.filename,colonShorthand:!0,vmTarget:!0}),Y=_0(X,$.filename),{ast:z,signature:W,warnings:G}=l1(Y,Q,K,$,H);return{ast:z,signature:W,warnings:G}}var s5=10;class S4{atoms;constructor(Z={}){this.atoms={...d0,...Z}}get builder(){return new s(this.atoms)}get Agent(){return new s(this.atoms)}get A99(){return this.Agent}resolve(Z){return this.atoms[Z]}getTools(Z="all"){let $=Object.values(this.atoms);if(Array.isArray(Z))$=$.filter((X)=>Z.includes(X.op));else if(Z==="flow"){let X=["seq","if","while","return","try","varSet","varGet","scope"];$=$.filter((K)=>X.includes(K.op))}return $.map((X)=>({type:"function",function:{name:X.op,description:X.docs,parameters:X.inputSchema?.schema??{}}}))}async run(Z,$={},X={}){let K;if(typeof Z==="string")if(V4(Z))K=O4(Z);else try{K=e1(Z).ast}catch(D){throw Error(`AJS transpilation failed: ${D.message}`)}else K=Z;let Q=X.fuel??1000,H=X.timeoutMs??Q*s5,Y=X.capabilities??{},z=[];if(!Y.store){let D=new Map,I=!1;Y.store={get:async(B)=>{if(!I)I=!0,z.push("Using default in-memory store (not suitable for production)");return D.get(B)},set:async(B,A)=>{if(!I)I=!0,z.push("Using default in-memory store (not suitable for production)");D.set(B,A)}}}let W=new AbortController,G=setTimeout(()=>W.abort(),H);if(X.signal)X.signal.addEventListener("abort",()=>W.abort());let J={fuel:{current:Q},args:$,state:{},consts:new Set,capabilities:Y,resolver:(D)=>this.resolve(D),output:void 0,signal:W.signal,costOverrides:X.costOverrides,context:X.context,warnings:z};if(X.trace)J.trace=[];if(K.op!=="seq")throw Error("Root AST must be 'seq'. Ensure you're passing a transpiled agent (use ajs`...` or transpile()).");let U=K.inputSchema;if(U&&!o5($,U)){let D=new e("Input validation failed: args do not match expected schema","vm.run");return{result:D,error:D,fuelUsed:0,trace:J.trace,warnings:z.length>0?z:void 0}}try{await Promise.race([this.resolve("seq")?.exec(K,J),new Promise((D,I)=>{if(W.signal.addEventListener("abort",()=>{I(Error(`Execution timeout after ${H}ms (fuel: ${Q}). Consider increasing fuel or optimizing your agent.`))}),W.signal.aborted)I(Error(`Execution timeout after ${H}ms (fuel: ${Q}). Consider increasing fuel or optimizing your agent.`))})])}catch(D){if(D.message?.includes("timeout")||D.message?.includes("aborted")||W.signal.aborted)J.error=new e(`Execution timeout after ${H}ms (fuel: ${Q}). Consider increasing fuel or optimizing your agent.`,"vm.run");else throw D}finally{clearTimeout(G)}if(J.error&&J.output===void 0)J.output=J.error;let _=[...z,...J.warnings??[]];return{result:J.output,error:J.error,fuelUsed:Q-J.fuel.current,trace:J.trace,warnings:_.length>0?_:void 0}}}var a5=null,x6=()=>a5??=new S4;async function r5(Z){let{code:$,context:X={},fuel:K=1000,timeoutMs:Q,capabilities:H={}}=Z,Y=x6(),W=/\breturn\b/.test($)?`function __eval() { ${$} }`:`function __eval() { return (${$}) }`;try{let{ast:G}=e1(W),J=await Y.run(G,X,{fuel:K,timeoutMs:Q,capabilities:H});return{result:J.result,fuelUsed:J.fuelUsed,error:J.error?{message:J.error.message||String(J.error)}:void 0}}catch(G){return{result:void 0,fuelUsed:K,error:{message:G.message||String(G)}}}}async function t5(Z){let{body:$,params:X=[],fuel:K=1000,timeoutMs:Q,capabilities:H={}}=Z,Y=x6(),W=`function __safeFn(${X.join(", ")}) { ${$} }`,{ast:G}=e1(W);return async(...J)=>{let U={};for(let _=0;_<X.length;_++)U[X[_]]=J[_];try{let _=await Y.run(G,U,{fuel:K,timeoutMs:Q,capabilities:H});return{result:_.result,fuelUsed:_.fuelUsed,error:_.error?{message:_.error.message||String(_.error)}:void 0}}catch(_){return{result:void 0,fuelUsed:K,error:{message:_.message||String(_)}}}}}function i0(Z,$={}){let{ast:X,returnType:K,originalSource:Q,requiredParams:H}=W1(Z,{filename:$.filename,colonShorthand:!0,vmTarget:!0}),Y=_0(X,$.filename),{ast:z,signature:W,warnings:G}=l1(Y,Q,K,$,H);return{ast:z,signature:W,warnings:G}}function NK(Z,...$){if(typeof Z==="string")return i0(Z).ast;let X=Z.reduce((K,Q,H)=>K+Q+($[H]!==void 0?String($[H]):""),"");return i0(X).ast}function SK(Z,$,...X){if(typeof Z==="string")return a1(Z,$);let K=$!==void 0?[$,...X]:X,Q=Z.reduce((H,Y,z)=>H+Y+(K[z]!==void 0?String(K[z]):""),"");return a1(Q)}async function TK(Z,$={},X){let K=X??await h0(),Q=await K.getTranspile(Z);if(Q)return{ast:Q.ast,signature:Q.signature,warnings:Q.warnings};let H=i0(Z,$);return K.setTranspile(Z,{ast:H.ast,signature:H.signature,warnings:H.warnings}),H}async function kK(Z,$={},X){let K=X??await h0(),Q=await K.getTJS(Z);if(Q)return{code:Q.code,types:Q.types,metadata:Q.types,testRunner:Q.testRunner,testCount:Q.testCount,warnings:Q.warnings};let H=a1(Z,$);return K.setTJS(Z,{code:H.code,types:H.types,testRunner:H.testRunner,testCount:H.testCount,warnings:H.warnings}),H}function gK(Z,$,X){let{ast:K,signature:Q}=i0(Z),H=async(Y)=>{return(await $.run(K,Y,X)).result};return H.signature=Q,H.ast=K,H}function bK(Z){return Object.entries(Z).map(([$,X])=>{let K=X.signature,Q={},H=[];for(let[Y,z]of Object.entries(K.parameters)){if(Q[Y]=l0(z.type),z.description)Q[Y].description=z.description;if(z.required)H.push(Y)}return{type:"function",function:{name:K.name||$,description:K.description,parameters:{type:"object",properties:Q,required:H}}}})}function l0(Z){switch(Z.kind){case"string":return{type:"string"};case"number":return{type:"number"};case"boolean":return{type:"boolean"};case"null":return{type:"null"};case"array":return{type:"array",items:Z.items?l0(Z.items):{}};case"object":if(!Z.shape)return{type:"object"};return{type:"object",properties:Object.fromEntries(Object.entries(Z.shape).map(([$,X])=>[$,l0(X)]))};case"union":if(!Z.members)return{};return{anyOf:Z.members.map(l0)};case"any":default:return{}}}import{s as T}from"tosijs-schema";var u6=E("storeVectorize",T.object({text:T.string,model:T.string.optional}),T.array(T.number),async({text:Z},$)=>{let X=$.capabilities.vector;if(!X)throw Error("Capability 'vector' missing. Ensure vector battery is loaded.");let K=F(Z,$);return X.embed(K)},{docs:"Generate embeddings using vector battery",cost:20}),d6=E("storeCreateCollection",T.object({collection:T.string,dimension:T.number.optional}),void 0,async({collection:Z,dimension:$},X)=>{let K=X.capabilities.store;if(!K?.createCollection)throw Error("Capability 'store' missing or does not support createCollection.");let Q=F(Z,X),H=F($,X);return K.createCollection(Q,void 0,H)},{docs:"Create a vector store collection",cost:5}),m6=E("storeVectorAdd",T.object({collection:T.string,doc:T.any}),void 0,async({collection:Z,doc:$},X)=>{let K=X.capabilities.store;if(!K?.vectorAdd)throw Error("Capability 'store' missing or does not support vectorAdd.");let Q=F(Z,X),H=F($,X);return K.vectorAdd(Q,H)},{docs:"Add a document to a vector store collection",cost:5}),l6=E("storeSearch",T.object({collection:T.string,queryVector:T.array(T.number),k:T.number.optional,filter:T.record(T.any).optional}),T.array(T.any),async({collection:Z,queryVector:$,k:X,filter:K},Q)=>{let H=Q.capabilities.store;if(!H?.vectorSearch)throw Error("Capability 'store' missing or does not support vectorSearch.");let Y=F(Z,Q),z=F($,Q),W=F(X,Q)??5,G=F(K,Q);return H.vectorSearch(Y,z,W,G)},{docs:"Search vector store",cost:(Z,$)=>5+(F(Z.k,$)??5)}),i6=E("llmPredictBattery",T.object({system:T.string.optional,user:T.string,tools:T.array(T.any).optional,responseFormat:T.any.optional}),T.object({content:T.string.optional,tool_calls:T.array(T.any).optional}),async({system:Z,user:$,tools:X,responseFormat:K},Q)=>{let H=Q.capabilities.llmBattery;if(!H?.predict)throw Error("Capability 'llmBattery' missing or invalid.");let Y=F(Z,Q)??"You are a helpful agent.",z=F($,Q),W=F(X,Q),G=F(K,Q);return H.predict(Y,z,W,G)},{docs:"Generate completion using LLM battery",cost:100}),p6=E("llmVision",T.object({system:T.string.optional,prompt:T.string,images:T.array(T.string),responseFormat:T.any.optional}),T.object({content:T.string.optional,tool_calls:T.array(T.any).optional}),async({system:Z,prompt:$,images:X,responseFormat:K},Q)=>{let H=Q.capabilities.llmBattery;if(!H?.predict)throw Error("Capability 'llmBattery' missing or invalid.");let Y=F(Z,Q)??"You analyze images accurately and concisely.",z=F($,Q),W=F(X,Q)??[],G=F(K,Q);return H.predict(Y,{text:z,images:W},void 0,G)},{docs:"Analyze images using a vision model",timeoutMs:120000,cost:150});var XQ={storeCreateCollection:d6,storeSearch:l6,storeVectorAdd:m6,storeVectorize:u6,llmPredictBattery:i6,llmVision:p6};var n6=new Map,p0=new Map;function e5(Z,$){if(Z.length!==$.length)throw Error("Vectors must have the same length for cosine similarity.");let X=0,K=0,Q=0;for(let H=0;H<Z.length;H++)X+=Z[H]*$[H],K+=Z[H]*Z[H],Q+=$[H]*$[H];if(K=Math.sqrt(K),Q=Math.sqrt(Q),K===0||Q===0)return 0;return X/(K*Q)}function T4(){return{async get(Z){return n6.get(Z)},async set(Z,$){n6.set(Z,$)},async createCollection(Z,$,X){if(p0.has(Z))console.warn(`Collection '${Z}' already exists. Overwriting.`);p0.set(Z,[])},async vectorAdd(Z,$){let X=p0.get(Z);if(!X)throw Error(`Collection '${Z}' not found. Create it first.`);if(!$.embedding||!Array.isArray($.embedding))throw Error("Document must have an 'embedding' property that is an array of numbers.");X.push($)},async vectorSearch(Z,$,X=5){let K=p0.get(Z);if(!K)throw Error(`Collection '${Z}' not found. Create it first.`);let Q=K.map((H)=>({doc:H,score:e5($,H.embedding)}));return Q.sort((H,Y)=>Y.score-H.score),Q.slice(0,X).map((H)=>H.doc)}}}function ZX(Z){if(typeof Z==="string")return{role:"user",content:Z};let $=[{type:"text",text:Z.text}];for(let X of Z.images||[])$.push({type:"image_url",image_url:{url:X}});return{role:"user",content:$}}var XX="http://localhost:1234/v1";function c6(Z,$=XX){return{async predict(X,K,Q,H){try{let Y=H?Z.getStructuredLLM():Z.getLLM(),z=[{role:"system",content:X},ZX(K)],W=await fetch(`${$}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:Y.id,messages:z,temperature:0.7,tools:Q,response_format:H})});if(!W.ok)throw Error(`LLM Error: ${W.status} ${W.statusText}`);return(await W.json()).choices[0]?.message??{content:""}}catch(Y){if(Y.cause?.code==="ECONNREFUSED")throw Error("No LLM provider configured. Please start LM Studio or provide an API key.");throw Y}},async embed(X){try{let K=Z.getEmbedding(),Q=await fetch(`${$}/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:K.id,input:X})});if(!Q.ok)throw Error(`Embedding Error: ${Q.status}`);return(await Q.json()).data[0]?.embedding??[]}catch(K){if(K.cause?.code==="ECONNREFUSED")throw Error("No LLM provider configured. Please start LM Studio or provide an API key.");throw K}}}}var Z0=typeof window<"u"&&typeof window.localStorage<"u";async function QX(Z){try{if(Z0){let $=window.localStorage.getItem(".models.cache.json");if(!$)return null;let X=JSON.parse($);if(X.baseUrl!==Z)return null;if(Date.now()-X.timestamp>86400000)return null;return X.models}else{let $=await import("node:fs/promises"),K=(await Promise.resolve().then(() => (b4(),g4))).join(process.cwd(),".models.cache.json");try{let Q=await $.readFile(K,"utf-8"),H=JSON.parse(Q);if(H.baseUrl!==Z)return null;if(Date.now()-H.timestamp>86400000)return null;return H.models}catch{return null}}}catch($){return console.warn("⚠️ Error reading model cache:",$),null}}async function HX(Z,$){let X={timestamp:Date.now(),baseUrl:Z,models:$};try{if(Z0)window.localStorage.setItem(".models.cache.json",JSON.stringify(X));else{let K=await import("node:fs/promises"),H=(await Promise.resolve().then(() => (b4(),g4))).join(process.cwd(),".models.cache.json");await K.writeFile(H,JSON.stringify(X,null,2))}}catch(K){console.error("❌ Error writing model cache:",K)}}var X0=async(Z,$)=>{let X=new AbortController,K=setTimeout(()=>X.abort(),60000);try{let Q=await fetch(Z,{...$,signal:X.signal});return clearTimeout(K),Q}catch(Q){throw clearTimeout(K),Q}};async function YX(Z,$){try{let X={type:"json_schema",json_schema:{name:"test",strict:!1,schema:{type:"object",properties:{status:{type:"string"}}}}},K=await X0(`${Z}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:$,messages:[{role:"system",content:"You respond in JSON."},{role:"user",content:'Return JSON: {"status": "ok"}'}],response_format:X,max_tokens:20})});if(!K.ok){if(K.status===400)return zX(Z,$);return{ok:!1,msg:`HTTP ${K.status}`}}let Q=await K.json();return JSON.parse(Q.choices[0].message.content),{ok:!0,msg:"OK (Schema)"}}catch(X){return{ok:!1,msg:X.message||"Error"}}}async function zX(Z,$){try{if((await X0(`${Z}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:$,messages:[{role:"user",content:'JSON: {"a":1}'}],response_format:{type:"json_object"},max_tokens:10})})).ok)return{ok:!0,msg:"OK (Legacy Mode)"};return{ok:!1,msg:"Not Supported"}}catch{return{ok:!1,msg:"Legacy Fail"}}}async function GX(Z,$){try{return(await X0(`${Z}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:$,messages:[{role:"user",content:"hi"}],max_tokens:1})})).ok}catch{return!1}}async function WX(Z,$){try{let X=await X0(`${Z}/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:$,input:"test"})});if(!X.ok)return null;return(await X.json()).data[0]?.embedding?.length??null}catch{return null}}var JX="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==";async function _X(Z,$){try{return(await X0(`${Z}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:$,messages:[{role:"user",content:[{type:"text",text:"What color is this?"},{type:"image_url",image_url:{url:JX}}]}],max_tokens:10})})).ok}catch{return!1}}async function z7(Z){let $=await QX(Z),X=[];try{let Y=await fetch(`${Z}/models`);if(!Y.ok)throw Error("Could not connect");X=(await Y.json()).data.map((W)=>W.id).sort()}catch(Y){if($)return console.log("⚠️ LM Studio unavailable, using cached model audit."),$;return console.error("❌ Failed to connect to LM Studio."),[]}if($){let Y=$.map((z)=>z.id).sort();if(JSON.stringify(X)===JSON.stringify(Y))return console.log("✅ Using cached model audit."),$;console.log("\uD83D\uDD0D Model list changed. Re-running audit...")}console.log("\uD83D\uDD0D Scanning models (this may take a moment)...");let K=[],Q=X.map((Y)=>({id:Y})),H;if(!Z0)H=await import("node:readline");for(let Y of Q){if(!Z0&&H)H.cursorTo(process.stdout,0),process.stdout.write(`\uD83D\uDC49 Testing: ${Y.id}...`),H.clearLine(process.stdout,1);let z="Unknown",W=!1,G=!1,J="",U=void 0,_=await GX(Z,Y.id),D=await WX(Z,Y.id);if(D)U=D;if(_){z="LLM";let I=await YX(Z,Y.id);if(W=I.ok,G=await _X(Z,Y.id),J=W?I.msg:`Fail: ${I.msg}`,G)J+=" +Vision"}else if(D)z="Embedding",J=`OK (Dim: ${D})`;else J="LLM Fail";K.push({id:Y.id,type:z,structuredOutput:W,vision:G,dimension:U,status:J})}if(!Z0&&H)H.cursorTo(process.stdout,0),H.clearLine(process.stdout,0);return console.log(`
|
|
317
|
-
`),console.table(K),await HX(Z,K),console.log("\uD83D\uDCDD Audit results saved to cache."),K}var LX="http://localhost:1234/v1";class v4{baseUrl;models=[];defaultLLM=null;defaultEmbedding=null;defaultStructuredLLM=null;constructor(Z=LX){this.baseUrl=Z}async audit(){this.models=await z7(this.baseUrl),this.selectDefaults()}selectDefaults(){if(this.defaultEmbedding=this.models.find((Z)=>Z.type==="Embedding")||null,this.defaultLLM=this.models.find((Z)=>Z.type==="LLM")||null,this.defaultStructuredLLM=this.models.find((Z)=>Z.type==="LLM"&&Z.structuredOutput)||null,!this.defaultEmbedding)console.warn("⚠️ No embedding model found.");if(!this.defaultLLM)console.warn("⚠️ No LLM found.");if(!this.defaultStructuredLLM)console.warn("⚠️ No LLM with structured output support found.")}getModels(){return this.models}_setDefaultModel(Z,$,X,K){let Q=this.models.find((H)=>H.id===Z&&X(H));if(!Q)throw Error(`Model '${Z}' not found or is not ${K}.`);this[$]=Q}setDefaultLLM(Z){this._setDefaultModel(Z,"defaultLLM",($)=>$.type==="LLM","an LLM")}setDefaultEmbedding(Z){this._setDefaultModel(Z,"defaultEmbedding",($)=>$.dimension!==void 0,"an embedding model")}setDefaultStructuredLLM(Z){this._setDefaultModel(Z,"defaultStructuredLLM",($)=>$.type==="LLM"&&$.structuredOutput,"a structured-output LLM")}getLLM(){if(!this.defaultLLM)throw Error("No LLM available.");return this.defaultLLM}getEmbedding(){if(!this.defaultEmbedding)throw Error("No embedding model available.");return this.defaultEmbedding}getStructuredLLM(){if(!this.defaultStructuredLLM)throw Error("No structured-output LLM available.");return this.defaultStructuredLLM}}var qX=typeof window<"u",UX=qX&&window.location.protocol==="https:",$0=null,f4=null,G7=!1;async function DX(){if(G7)return{localModels:$0,llm:f4};if(G7=!0,UX)return console.log("\uD83D\uDCE1 HTTPS detected - local LLM endpoints disabled. Use HTTP for local LLM support."),{localModels:null,llm:null};try{$0=new v4,await $0.audit(),f4=c6($0)}catch(Z){console.warn("⚠️ Could not connect to local LLM:",Z)}return{localModels:$0,llm:f4}}async function IX(){let{localModels:Z,llm:$}=await DX();return{vector:$?{embed:$.embed}:void 0,store:T4(),llmBattery:$,models:Z}}async function _Q(){return IX()}var LQ={store:T4(),llmBattery:null,vector:void 0,models:null};function BX(Z){if(typeof Z!=="string")return!1;let $=new Date(Z);return!isNaN($.getTime())&&Z.includes("T")}function RX(){return new Date().toISOString()}function f1(Z,$,X,K=0,Q=0,H=0,Y=0){return new Date(Date.UTC(Z,$-1,X,K,Q,H,Y)).toISOString()}function W7(Z){let $=new Date(Z);if(isNaN($.getTime()))throw Error(`Invalid date string: ${Z}`);return $.toISOString()}function MX(Z){try{return W7(Z)}catch{return null}}function K0(Z,$){let X=new Date(Z);return X.setTime(X.getTime()+$),X.toISOString()}function AX(Z,$){return K0(Z,$*1000)}function jX(Z,$){return K0(Z,$*60*1000)}function FX(Z,$){return K0(Z,$*60*60*1000)}function J7(Z,$){return K0(Z,$*24*60*60*1000)}function wX(Z,$){return J7(Z,$*7)}function PX(Z,$){let X=new Date(Z),K=X.getUTCMonth()+$;if(X.setUTCMonth(K),X.getUTCMonth()!==(K%12+12)%12)X.setUTCDate(0);return X.toISOString()}function CX(Z,$){let X=new Date(Z),K=X.getUTCDate();if(X.setUTCFullYear(X.getUTCFullYear()+$),X.getUTCDate()!==K)X.setUTCDate(0);return X.toISOString()}function M1(Z,$){return new Date(Z).getTime()-new Date($).getTime()}function VX(Z,$){return Math.floor(M1(Z,$)/1000)}function OX(Z,$){return Math.floor(M1(Z,$)/60000)}function NX(Z,$){return Math.floor(M1(Z,$)/3600000)}function EX(Z,$){return Math.floor(M1(Z,$)/86400000)}function y1(Z){return new Date(Z).getUTCFullYear()}function c0(Z){return new Date(Z).getUTCMonth()+1}function y4(Z){return new Date(Z).getUTCDate()}function SX(Z){return new Date(Z).getUTCHours()}function TX(Z){return new Date(Z).getUTCMinutes()}function kX(Z){return new Date(Z).getUTCSeconds()}function gX(Z){return new Date(Z).getUTCMilliseconds()}function bX(Z){let $=new Date(Z).getUTCDay();return $===0?7:$}function o0(Z,$,X){let K=new Date(Z),Q={timeZone:$,...X};return new Intl.DateTimeFormat(void 0,Q).format(K)}function vX(Z,$){return o0(Z,$,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"})}function fX(Z,$){return o0(Z,$,{year:"numeric",month:"short",day:"numeric"})}function yX(Z,$){return o0(Z,$,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}function hX(Z){return Z.slice(0,10)}function _7(Z,$){return M1(Z,$)<0}function L7(Z,$){return M1(Z,$)>0}function xX(Z,$){return M1(Z,$)===0}function uX(Z,$){return _7(Z,$)?Z:$}function dX(Z,$){return L7(Z,$)?Z:$}function mX(Z){return f1(y1(Z),c0(Z),y4(Z))}function lX(Z){return f1(y1(Z),c0(Z),y4(Z),23,59,59,999)}function iX(Z){return f1(y1(Z),c0(Z),1)}function pX(Z){let $=new Date(Z);return $.setUTCMonth($.getUTCMonth()+1,0),$.setUTCHours(23,59,59,999),$.toISOString()}function nX(Z){return f1(y1(Z),1,1)}function cX(Z){return f1(y1(Z),12,31,23,59,59,999)}var h1={isValid:BX,now:RX,from:f1,parse:W7,tryParse:MX,addMilliseconds:K0,addSeconds:AX,addMinutes:jX,addHours:FX,addDays:J7,addWeeks:wX,addMonths:PX,addYears:CX,diff:M1,diffSeconds:VX,diffMinutes:OX,diffHours:NX,diffDays:EX,year:y1,month:c0,day:y4,hour:SX,minute:TX,second:kX,millisecond:gX,dayOfWeek:bX,toLocal:o0,format:vX,formatDate:fX,formatTime:yX,toDate:hX,isBefore:_7,isAfter:L7,isEqual:xX,min:uX,max:dX,startOfDay:mX,endOfDay:lX,startOfMonth:iX,endOfMonth:pX,startOfYear:nX,endOfYear:cX};function h4(Z){if(typeof Z!=="string")return!1;if(!/^\d{4}-\d{2}-\d{2}$/.test(Z))return!1;let $=parseInt(Z.slice(0,4),10),X=parseInt(Z.slice(5,7),10),K=parseInt(Z.slice(8,10),10);if(X<1||X>12)return!1;if(K<1)return!1;let Q=[31,28,31,30,31,30,31,31,30,31,30,31],H=X===2&&($%4===0&&$%100!==0||$%400===0)?29:Q[X-1];return K<=H}function oX(){return h1.toDate(h1.now())}function sX(Z){let $=new Date;return new Intl.DateTimeFormat("en-CA",{timeZone:Z,year:"numeric",month:"2-digit",day:"2-digit"}).format($)}function K1(Z,$,X){let K=String(Z).padStart(4,"0"),Q=String($).padStart(2,"0"),H=String(X).padStart(2,"0"),Y=`${K}-${Q}-${H}`;if(!h4(Y))throw Error(`Invalid date: ${Z}-${$}-${X}`);return Y}function q7(Z){if(/^\d{4}-\d{2}-\d{2}$/.test(Z)){if(!h4(Z))throw Error(`Invalid date: ${Z}`);return Z}let $=new Date(Z);if(isNaN($.getTime()))throw Error(`Invalid date string: ${Z}`);let X=$.getUTCFullYear(),K=$.getUTCMonth()+1,Q=$.getUTCDate();return K1(X,K,Q)}function aX(Z){try{return q7(Z)}catch{return null}}function s0(Z,$){let X=D7(Z);return h1.toDate(h1.addDays(X,$))}function rX(Z,$){return s0(Z,$*7)}function tX(Z,$){let X=r(Z),K=A1(Z),Q=x4(Z),H=X*12+(K-1)+$,Y=Math.floor(H/12),z=H%12+1,W=Q0(Y,z),G=Math.min(Q,W);return K1(Y,z,G)}function eX(Z,$){let X=r(Z),K=A1(Z),Q=x4(Z),H=X+$,Y=Q0(H,K),z=Math.min(Q,Y);return K1(H,K,z)}function U7(Z,$){let K=new Date(Z+"T00:00:00Z").getTime(),Q=new Date($+"T00:00:00Z").getTime();return Math.round((K-Q)/86400000)}function Z$(Z,$){let X=r(Z),K=A1(Z),Q=r($),H=A1($);return(X-Q)*12+(K-H)}function X$(Z,$){return r(Z)-r($)}function r(Z){return parseInt(Z.slice(0,4),10)}function A1(Z){return parseInt(Z.slice(5,7),10)}function x4(Z){return parseInt(Z.slice(8,10),10)}function u4(Z){let $=new Date(Z+"T00:00:00Z").getUTCDay();return $===0?7:$}function $$(Z){let $=new Date(Z+"T00:00:00Z"),X=$.getUTCDay()||7;$.setUTCDate($.getUTCDate()+4-X);let K=new Date(Date.UTC($.getUTCFullYear(),0,1));return Math.ceil((($.getTime()-K.getTime())/86400000+1)/7)}function K$(Z){let $=K1(r(Z),1,1);return U7(Z,$)+1}function d4(Z){return Math.ceil(A1(Z)/3)}function m4(Z){return Z%4===0&&Z%100!==0||Z%400===0}function Q0(Z,$){let X=[31,28,31,30,31,30,31,31,30,31,30,31];if($===2&&m4(Z))return 29;return X[$-1]}function Q$(Z){return m4(Z)?366:365}function D7(Z){return Z+"T00:00:00.000Z"}function H$(Z){return Math.floor(new Date(Z+"T00:00:00Z").getTime()/1000)}function Y$(Z){let $=new Date(Z*1000);return K1($.getUTCFullYear(),$.getUTCMonth()+1,$.getUTCDate())}function l4(Z,$){let X=new Date(Z+"T00:00:00Z"),K={timeZone:"UTC",...$};return new Intl.DateTimeFormat(void 0,K).format(X)}function z$(Z){return l4(Z,{year:"numeric",month:"long",day:"numeric"})}function G$(Z){return l4(Z,{year:"numeric",month:"short",day:"numeric"})}function W$(Z,$){return Z<$}function J$(Z,$){return Z>$}function _$(Z,$){return Z===$}function L$(Z,$){return Z<$?Z:$}function q$(Z,$){return Z>$?Z:$}function U$(Z,$,X){return Z>=$&&Z<=X}function D$(Z){return K1(r(Z),A1(Z),1)}function I$(Z){let $=r(Z),X=A1(Z);return K1($,X,Q0($,X))}function B$(Z){let X=(d4(Z)-1)*3+1;return K1(r(Z),X,1)}function R$(Z){let X=d4(Z)*3;return K1(r(Z),X,Q0(r(Z),X))}function M$(Z){return K1(r(Z),1,1)}function A$(Z){return K1(r(Z),12,31)}function j$(Z){let $=u4(Z);return s0(Z,-($-1))}function F$(Z){let $=u4(Z);return s0(Z,7-$)}var w$={isValid:h4,today:oX,todayIn:sX,from:K1,parse:q7,tryParse:aX,addDays:s0,addWeeks:rX,addMonths:tX,addYears:eX,diff:U7,diffMonths:Z$,diffYears:X$,year:r,month:A1,day:x4,dayOfWeek:u4,weekOfYear:$$,dayOfYear:K$,quarter:d4,isLeapYear:m4,daysInMonth:Q0,daysInYear:Q$,toTimestamp:D7,toUnix:H$,fromUnix:Y$,format:l4,formatLong:z$,formatShort:G$,isBefore:W$,isAfter:J$,isEqual:_$,min:L$,max:q$,isBetween:U$,startOfMonth:D$,endOfMonth:I$,startOfQuarter:B$,endOfQuarter:R$,startOfYear:M$,endOfYear:A$,startOfWeek:j$,endOfWeek:F$};export{T5 as xmlParse,M4 as wrap,oZ as whileLoop,P5 as vectorSearch,$5 as varsLet,X5 as varsImport,K5 as varsExport,tZ as varSet,Z5 as varGet,R4 as validateArgs,v5 as uuid,Z4 as typeToString,k1 as typeOf,aZ as tryCatch,TK as transpileWithCache,a1 as transpileToJS,O5 as transpileCode,i0 as transpile,l1 as transformFunction,kK as tjsWithCache,SK as tjs,R8 as testUtils,q5 as template,z4 as stripTjsPreamble,Y4 as stripModuleSyntax,F5 as storeSet,w5 as storeQuery,x5 as storeProcedure,j5 as storeGet,_5 as split,TZ as setGlobalCache,$1 as seq,Q5 as scope,C1 as runtime,N5 as runCode,sZ as ret,F as resolveValue,O4 as resolveProcedureToken,u5 as releaseProcedure,Y6 as registerWasmBlock,U5 as regexMatch,z5 as reduce,b5 as random,W5 as push,v1 as procedureStore,W0 as preprocess,D5 as pick,a4 as parseReturnType,I1 as parseParameter,W1 as parse,I5 as omit,B5 as merge,k5 as memoize,H5 as map,O7 as lookupVariable,C5 as llmPredict,bZ as lint,J5 as len,R5 as keys,S5 as jsonStringify,E5 as jsonParse,L5 as join,W4 as isValidUrl,J4 as isValidTimestamp,_4 as isValidLegalDate,B1 as isRuntimeType,V4 as isProcedureToken,J1 as isError,zK as isAgentError,H6 as instantiateWasm,qZ as installRuntime,X1 as inferTypeFromValue,cZ as iff,NZ as hashSourceSync,y0 as hashSource,N4 as hash,bK as getToolDefinitions,T4 as getStoreCapabilityDefault,_Q as getStandardCapabilities,h as getLocation,c6 as getLLMCapability,h0 as getGlobalCache,IX as getBatteries,yZ as generateDocsMarkdown,C6 as generateDocs,VZ as fromTS,G5 as find,Y5 as filter,A5 as fetch,$4 as extractTests,u1 as extractTDoc,D1 as extractLiteralValue,$6 as expectFunction,u as evaluateExpr,rZ as errorAtom,z1 as error,UZ as emitRuntimeWrapper,E as defineAtom,R1 as createChildScope,Z1 as createChildContext,gK as createAgent,d0 as coreAtoms,eZ as constSet,y5 as consoleWarn,f5 as consoleLog,h5 as consoleError,f8 as compileWasmBlocks,D0 as compileToWasm,d5 as clearExpiredProcedures,V1 as checkType,g5 as cache,L1 as builtins,XQ as batteryAtoms,LQ as batteries,X6 as assertFunction,NK as ajs,V5 as agentRun,N0 as Union,s as TypedBuilder,V7 as TypeError,d as Type,y as TranspileError,L4 as TimestampType,h1 as Timestamp,C0 as TUuid,P0 as TUrl,B0 as TString,T0 as TRecord,j0 as TPositiveInt,S0 as TPair,R0 as TNumber,F0 as TNonEmptyString,a as TJS_VERSION,A0 as TInteger,w0 as TEmail,M0 as TBoolean,E0 as TArray,U1 as SyntaxError,OZ as Schema,t5 as SafeFunction,C4 as PROCEDURE_TOKEN_PREFIX,O0 as Optional,V0 as Nullable,F4 as MetadataCache,v4 as LocalModels,q4 as LegalDateType,w$ as LegalDate,T1 as Generic,r5 as Eval,k0 as Enum,hZ as DEFAULT_PROCEDURE_TTL,xZ as DEFAULT_MAX_AST_SIZE,S4 as AgentVM,e as AgentError,c5 as Agent,JK as A99};
|
|
350
|
+
`}return K.trim()||"*No documentation available*"}import{s as L,validate as P4,filter as k6}from"tosijs-schema";class e{$error=!0;message;op;cause;constructor(Z,$,X){this.message=Z,this.op=$,this.cause=X}toString(){return`AgentError[${this.op}]: ${this.message}`}toJSON(){return{$error:!0,message:this.message,op:this.op}}}function zK(Z){return Z instanceof e||Z&&Z.$error===!0}var f1=new Map,hZ=3600000,xZ=102400,C4="proc_";function V4(Z){return typeof Z==="string"&&Z.startsWith(C4)}function O4(Z){let $=f1.get(Z);if(!$)throw Error(`Procedure not found: ${Z}`);if(Date.now()>$.expiresAt)throw f1.delete(Z),Error(`Procedure expired: ${Z}`);return $.ast}function uZ(){if(typeof crypto<"u"&&crypto.randomUUID)return C4+crypto.randomUUID();return C4+Math.random().toString(36).slice(2)+Date.now().toString(36)}var g6=new Set(["__proto__","constructor","prototype"]);function V6(Z){if(g6.has(Z))throw Error(`Security Error: Access to '${Z}' is forbidden`)}var dZ=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","metadata.google.internal"]);function mZ(Z){try{let $=new URL(Z);if($.protocol!=="http:"&&$.protocol!=="https:")return!0;let X=$.hostname.toLowerCase();if(dZ.has(X))return!0;if(X.endsWith(".internal")||X.endsWith(".local"))return!0;if(X==="169.254.169.254")return!0;if(/^10\./.test(X)||/^192\.168\./.test(X)||/^172\.(1[6-9]|2\d|3[01])\./.test(X))return!0;return!1}catch{return!0}}function lZ(Z){if(/\([^)]*[+*][^)]*\)[+*]/.test(Z))return!0;if(/\(([^|)]+)\|\1\)[+*]/.test(Z))return!0;if(/\(\.\*\)\+/.test(Z))return!0;if(/\(\.\+\)\+/.test(Z))return!0;if(/\(\[.*\]\+\)\+/.test(Z))return!0;return!1}function R1(Z){return{...Z,state:Object.create(Z.state)}}function iZ(Z,$){let X={},K=new Set([...Object.keys(Z),...Object.keys($)]);for(let Q of K){let H=Z[Q],Y=$[Q];if(Y!==H)X[Q]=Y}return X}function F(Z,$){if(Z&&typeof Z==="object"&&Z.$kind==="arg")return $.args[Z.path];if(Z&&typeof Z==="object"&&Z.$expr)return u(Z,$);if(typeof Z==="string"){if(Z.startsWith("args.")&&!("args"in $.state))return $.args[Z.replace("args.","")];if(Z.includes(".")){let X=Z.split(".");for(let Q of X)if(g6.has(Q))throw Error(`Security Error: Access to '${Q}' is forbidden`);let K=$.state[X[0]];if(K!==void 0){for(let Q=1;Q<X.length;Q++)K=K?.[X[Q]];return K}}if(Z in $.state)return $.state[Z];return Z}if(Z&&typeof Z==="object"&&!Array.isArray(Z)&&Z.constructor===Object){let X={};for(let K of Object.keys(Z))X[K]=F(Z[K],$);return X}if(Array.isArray(Z))return Z.map((X)=>F(X,$));return Z}function E1(Z,$,X){return new Proxy($,{get(K,Q){if(Q in K)return K[Q];let H=X?.[Q];if(H)throw Error(`${Z}.${Q} is not available. ${H}`);throw Error(`${Z}.${Q} is not supported in AsyncJS. Check docs for available ${Z} methods.`)}})}function b1(Z){if(Z===null)return{type:"null"};if(Z===void 0)return{};if(typeof Z==="object"&&Z!==null&&"type"in Z&&typeof Z.type==="string")return Z;if(typeof Z==="object"&&Z!==null&&"schema"in Z&&typeof Z.schema==="object")return Z.schema;let $=typeof Z;if($==="string")return{type:"string"};if($==="number")return Number.isInteger(Z)?{type:"integer"}:{type:"number"};if($==="boolean")return{type:"boolean"};if(Array.isArray(Z)){if(Z.length===0)return{type:"array"};return{type:"array",items:b1(Z[0])}}if($==="object"){let X={},K=[];for(let[Q,H]of Object.entries(Z))X[Q]=b1(H),K.push(Q);return{type:"object",properties:X,required:K}}return{}}var q1={Math:E1("Math",{PI:Math.PI,E:Math.E,LN2:Math.LN2,LN10:Math.LN10,LOG2E:Math.LOG2E,LOG10E:Math.LOG10E,SQRT2:Math.SQRT2,SQRT1_2:Math.SQRT1_2,abs:Math.abs,ceil:Math.ceil,floor:Math.floor,round:Math.round,trunc:Math.trunc,sign:Math.sign,sqrt:Math.sqrt,cbrt:Math.cbrt,pow:Math.pow,exp:Math.exp,expm1:Math.expm1,log:Math.log,log2:Math.log2,log10:Math.log10,log1p:Math.log1p,sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,atan2:Math.atan2,sinh:Math.sinh,cosh:Math.cosh,tanh:Math.tanh,asinh:Math.asinh,acosh:Math.acosh,atanh:Math.atanh,hypot:Math.hypot,min:Math.min,max:Math.max,clz32:Math.clz32,imul:Math.imul,fround:Math.fround,random:()=>{if(typeof crypto<"u"&&crypto.getRandomValues){let Z=new Uint32Array(1);return crypto.getRandomValues(Z),Z[0]/4294967296}return Math.random()}}),JSON:E1("JSON",{parse:(Z)=>JSON.parse(Z),stringify:(Z,$,X)=>JSON.stringify(Z,$,X)}),console:E1("console",{log:(...Z)=>{return},warn:(...Z)=>{return},error:(...Z)=>{return},info:(...Z)=>{return}},{table:"Use console.log with JSON.stringify for structured data.",dir:"Use console.log instead.",trace:"Stack traces are not available in AsyncJS."}),Array:E1("Array",{isArray:(Z)=>Array.isArray(Z),from:(Z,$,X)=>Array.from(Z,$,X),of:(...Z)=>Array.of(...Z)},{prototype:"Prototype access is not allowed."}),Object:E1("Object",{keys:(Z)=>Object.keys(Z),values:(Z)=>Object.values(Z),entries:(Z)=>Object.entries(Z),fromEntries:(Z)=>Object.fromEntries(Z),assign:(Z,...$)=>Object.assign({},Z,...$),hasOwn:(Z,$)=>Object.hasOwn(Z,$)},{prototype:"Prototype access is not allowed.",create:"Use object literals instead.",defineProperty:"Property descriptors are not supported.",getPrototypeOf:"Prototype access is not allowed.",setPrototypeOf:"Prototype modification is not allowed."}),String:E1("String",{fromCharCode:(...Z)=>String.fromCharCode(...Z),fromCodePoint:(...Z)=>String.fromCodePoint(...Z)}),Number:E1("Number",{isNaN:Number.isNaN,isFinite:Number.isFinite,isInteger:Number.isInteger,isSafeInteger:Number.isSafeInteger,parseFloat,parseInt,MAX_VALUE:Number.MAX_VALUE,MIN_VALUE:Number.MIN_VALUE,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,MIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,POSITIVE_INFINITY:Number.POSITIVE_INFINITY,NEGATIVE_INFINITY:Number.NEGATIVE_INFINITY,NaN:Number.NaN,EPSILON:Number.EPSILON}),parseInt,parseFloat,isNaN,isFinite,encodeURI,decodeURI,encodeURIComponent,decodeURIComponent,undefined:void 0,null:null,NaN:NaN,Infinity:1/0,filter:(Z,$)=>{let X=b1($),K=k6(Z,X);if(K instanceof Error)throw K;return K},Schema:{...L,response:(Z,$)=>{let X=$?.schema!=null?$.schema:b1($);return{type:"json_schema",json_schema:{name:Z,strict:!0,schema:X}}},fromExample:(Z)=>b1(Z),isValid:(Z,$)=>{if($?.schema!=null)return P4(Z,$);return P4(Z,b1($))}},Set:(Z=[])=>{let $=[...new globalThis.Set(Z)];return{add(X){if(!$.includes(X))$.push(X);return this},remove(X){let K=$.indexOf(X);if(K!==-1)$.splice(K,1);return this},clear(){return $.length=0,this},has(X){return $.includes(X)},get size(){return $.length},toArray(){return[...$]},union(X){let K=X?.toArray?.()??X??[];return q1.Set([...$,...K])},intersection(X){let K=X?.toArray?.()??X??[];return q1.Set($.filter((Q)=>K.includes(Q)))},diff(X){let K=X?.toArray?.()??X??[];return q1.Set($.filter((Q)=>!K.includes(Q)))},forEach(X){$.forEach(X)},map(X){return q1.Set($.map(X))},filter(X){return q1.Set($.filter(X))},toJSON(){return[...$]}}},Date:(()=>{let Z=(X)=>({get value(){return X.toISOString()},get timestamp(){return X.getTime()},get year(){return X.getFullYear()},get month(){return X.getMonth()+1},get day(){return X.getDate()},get hours(){return X.getHours()},get minutes(){return X.getMinutes()},get seconds(){return X.getSeconds()},get dayOfWeek(){return X.getDay()},add({years:K=0,months:Q=0,days:H=0,hours:Y=0,minutes:z=0,seconds:W=0,ms:G=0}={}){let J=new globalThis.Date(X.getTime());if(K)J.setFullYear(J.getFullYear()+K);if(Q)J.setMonth(J.getMonth()+Q);if(H)J.setDate(J.getDate()+H);if(Y)J.setHours(J.getHours()+Y);if(z)J.setMinutes(J.getMinutes()+z);if(W)J.setSeconds(J.getSeconds()+W);if(G)J.setMilliseconds(J.getMilliseconds()+G);return Z(J)},diff(K,Q="ms"){let H=typeof K==="object"&&K.timestamp?K.timestamp:new globalThis.Date(K).getTime(),Y=X.getTime()-H;switch(Q){case"seconds":return Y/1000;case"minutes":return Y/60000;case"hours":return Y/3600000;case"days":return Y/86400000;default:return Y}},format(K="ISO"){if(K==="ISO")return X.toISOString();if(K==="date")return X.toISOString().split("T")[0];if(K==="time")return X.toISOString().split("T")[1].split(".")[0];return K.replace("YYYY",String(X.getFullYear())).replace("MM",String(X.getMonth()+1).padStart(2,"0")).replace("DD",String(X.getDate()).padStart(2,"0")).replace("HH",String(X.getHours()).padStart(2,"0")).replace("mm",String(X.getMinutes()).padStart(2,"0")).replace("ss",String(X.getSeconds()).padStart(2,"0"))},isBefore(K){let Q=typeof K==="object"&&K.timestamp?K.timestamp:new globalThis.Date(K).getTime();return X.getTime()<Q},isAfter(K){let Q=typeof K==="object"&&K.timestamp?K.timestamp:new globalThis.Date(K).getTime();return X.getTime()>Q},toString(){return X.toISOString()},toJSON(){return X.toISOString()}}),$=(X)=>{let K=X!==void 0?new globalThis.Date(X):new globalThis.Date;if(isNaN(K.getTime()))throw Error(`Invalid date: ${X}`);return Z(K)};return $.now=()=>globalThis.Date.now(),$.parse=(X)=>Z(new globalThis.Date(X)),$})()},u0={RegExp:"RegExp is not available. Use string methods or the regexMatch atom.",Promise:"Promise is not needed. All operations are implicitly async.",Map:"Map is not available. Use plain objects instead.",WeakSet:"WeakSet is not available.",WeakMap:"WeakMap is not available.",Symbol:"Symbol is not available.",Proxy:"Proxy is not available.",Reflect:"Reflect is not available.",Function:"Function constructor is not available. Define functions normally.",eval:"eval is not available. Code is compiled, not evaluated.",setTimeout:"setTimeout is not available. Use the delay atom.",setInterval:"setInterval is not available. Use while loops with delay.",fetch:"fetch is not available. Use the httpFetch atom.",require:"require is not available. Atoms must be registered with the VM.",import:"import is not available. Atoms must be registered with the VM.",process:"process is not available. AsyncJS runs in a sandboxed environment.",window:"window is not available. AsyncJS runs in a sandboxed environment.",document:"document is not available. AsyncJS runs in a sandboxed environment.",global:"global is not available. AsyncJS runs in a sandboxed environment.",globalThis:"globalThis is not available. Use builtins directly."},pZ=0.01,O6=0.0001,N6=0.001,nZ=new Set(["concat","slice","map","filter","flatMap","flat","toReversed","toSorted","toSpliced","repeat","padStart","padEnd","split","join","replace","replaceAll","substring","substr","trim","trimStart","trimEnd","toLowerCase","toUpperCase","match","matchAll","parse","stringify"]);function u(Z,$){if(Z===null||Z===void 0)return Z;if(typeof Z!=="object"||!("$expr"in Z))return Z;if($.fuel){if($.fuel.current-=pZ,$.fuel.current<=0)throw Error("Out of Fuel")}switch(Z.$expr){case"literal":return Z.value;case"ident":{if(Z.name in $.state)return $.state[Z.name];if(Z.name in $.args)return $.args[Z.name];if(Z.name in q1)return q1[Z.name];if(Z.name in u0)throw Error(u0[Z.name]);return}case"member":{let X=u(Z.object,$);if(Z.optional&&(X===null||X===void 0))return;let K=Z.property;return V6(K),X?.[K]}case"binary":{let X=u(Z.left,$),K=u(Z.right,$);switch(Z.op){case"+":{let Q=X+K;if(typeof Q==="string"&&$.fuel){if($.fuel.current-=Q.length*O6,$.fuel.current<=0){$.error=new e("Out of Fuel","expr.concat");return}}return Q}case"-":return X-K;case"*":return X*K;case"/":return X/K;case"%":return X%K;case"**":return X**K;case">":return X>K;case"<":return X<K;case">=":return X>=K;case"<=":return X<=K;case"==":return X==K;case"!=":return X!=K;case"===":return X===K;case"!==":return X!==K;default:throw Error(`Unknown binary operator: ${Z.op}`)}}case"unary":{let X=u(Z.argument,$);switch(Z.op){case"!":return!X;case"-":return-X;case"+":return+X;case"typeof":return typeof X;default:throw Error(`Unknown unary operator: ${Z.op}`)}}case"logical":{let X=u(Z.left,$);if(Z.op==="&&")return X?u(Z.right,$):X;else if(Z.op==="??")return X??u(Z.right,$);else return X?X:u(Z.right,$)}case"conditional":return u(Z.test,$)?u(Z.consequent,$):u(Z.alternate,$);case"array":return Z.elements.map((X)=>u(X,$));case"object":{let X={};for(let K of Z.properties)X[K.key]=u(K.value,$);return X}case"call":{if(Z.callee==="Error"){let K=Z.arguments.map((H)=>u(H,$)),Q=typeof K[0]==="string"?K[0]:"Error";$.error=new e(Q,"Error");return}if(Z.callee in q1){let K=q1[Z.callee];if(typeof K==="function"){let Q=Z.arguments.map((H)=>u(H,$));return K(...Q)}}if(!$.resolver(Z.callee)){if(Z.callee in u0)throw Error(u0[Z.callee]);throw Error(`Unknown function: ${Z.callee}`)}throw Error(`Atom calls in expressions not yet supported: ${Z.callee}`)}case"methodCall":{let X=u(Z.object,$);if(Z.optional&&(X===null||X===void 0))return;let K=Z.method;if(V6(K),X===null||X===void 0)throw Error(`Cannot call method '${K}' on ${X}`);let Q=X[K];if(typeof Q!=="function")throw Error(`'${K}' is not a function`);let H=Z.arguments.map((z)=>u(z,$)),Y=Q.apply(X,H);if($.fuel&&nZ.has(K)){let z=0;if(typeof Y==="string")z=Y.length*O6;else if(Array.isArray(Y))z=Y.length*N6;else if(typeof Y==="object"&&Y!==null)z=Object.keys(Y).length*N6;if($.fuel.current-=z,$.fuel.current<=0){$.error=new e("Out of Fuel",`expr.${K}`);return}}return Y}default:throw Error(`Unknown expression type: ${Z.$expr}`)}}function E(Z,$,X,K,Q={}){let{docs:H="",timeoutMs:Y=1000,cost:z=1}=typeof Q==="string"?{docs:Q}:Q;return{op:Z,inputSchema:$,outputSchema:X,exec:async(G,J)=>{let{op:U,result:_,...D}=G;if(J.error)return;let I=J.trace?{...J.state}:null,B=J.fuel.current,A,j;try{let P=J.costOverrides?.[Z],N=P!==void 0?P:z,M=typeof N==="function"?N(D,J):N;if((J.fuel.current-=M)<=0){J.error=new e("Out of Fuel",Z);return}let w,V=async()=>K(G,J);if(A=Y>0?await Promise.race([V(),new Promise((O,S)=>{w=setTimeout(()=>S(Error(`Atom '${Z}' timed out`)),Y)})]).finally(()=>clearTimeout(w)):await V(),G.result){if(J.consts.has(G.result))throw Error(`Cannot reassign const variable '${G.result}'`);if(A!==void 0&&X&&!P4(A,X)){J.error=new e(`Output validation failed for '${Z}'`,Z);return}if(J.state[G.result]=A,G.resultConst)J.consts.add(G.result)}}catch(P){j=P.message||String(P),J.error=new e(j,Z,P)}finally{if(J.trace&&I){let P=iZ(I,J.state);J.trace.push({op:Z,input:D,stateDiff:P,result:A,error:j,fuelBefore:B,fuelAfter:J.fuel.current,timestamp:new Date().toISOString()})}}},docs:H,timeoutMs:Y,cost:z,create:(G)=>({op:Z,...G})}}var $1=E("seq",L.object({steps:L.array(L.any)}),void 0,async({steps:Z},$)=>{for(let X of Z){if($.output!==void 0)return;if($.error)return;let K=$.resolver(X.op);if(!K)throw Error(`Unknown Atom: ${X.op}`);await K.exec(X,$)}},{docs:"Sequence",timeoutMs:0,cost:0.1}),cZ=E("if",L.object({condition:L.any,then:L.array(L.any),else:L.array(L.any).optional}),void 0,async(Z,$)=>{if(u(Z.condition,$))await $1.exec({op:"seq",steps:Z.then},$);else if(Z.else)await $1.exec({op:"seq",steps:Z.else},$)},{docs:"If/Else",timeoutMs:0,cost:0.1}),oZ=E("while",L.object({condition:L.any,body:L.array(L.any)}),void 0,async(Z,$)=>{while(u(Z.condition,$)){if($.signal?.aborted)throw Error("Execution aborted");if(($.fuel.current-=0.1)<=0)throw Error("Out of Fuel");if(await $1.exec({op:"seq",steps:Z.body},$),$.output!==void 0)return}},{docs:"While Loop",timeoutMs:0,cost:0.1}),sZ=E("return",void 0,L.any,async(Z,$)=>{if($.error)return $.output=$.error,$.error;if("value"in Z){let K=F(Z.value,$);return $.output=K,K}let X={};if(Z.schema?.properties){for(let K of Object.keys(Z.schema.properties))X[K]=$.state[K];if(Z.filter!==!1){let K=k6(X,Z.schema);if(!(K instanceof Error))X=K}}return $.output=X,X},{docs:"Return",cost:0.1}),aZ=E("try",L.object({try:L.array(L.any),catch:L.array(L.any).optional,catchParam:L.string.optional}),void 0,async(Z,$)=>{if(await $1.exec({op:"seq",steps:Z.try},$),$.error&&Z.catch){let X=Z.catchParam||"error";$.state[X]=$.error.message,$.state.errorOp=$.error.op,$.error=void 0,await $1.exec({op:"seq",steps:Z.catch},$)}},{docs:"Try/Catch",timeoutMs:0,cost:0.1}),rZ=E("Error",L.object({args:L.array(L.any).optional}),void 0,async(Z,$)=>{let X=Z.args?.[0]??"Error";$.error=new e(String(X),"Error")},{docs:"Trigger error flow",cost:0.1}),tZ=E("varSet",L.object({key:L.string,value:L.any}),void 0,async({key:Z,value:$},X)=>{if(X.consts.has(Z))throw Error(`Cannot reassign const variable '${Z}'`);X.state[Z]=F($,X)},{docs:"Set Variable",cost:0.1}),eZ=E("constSet",L.object({key:L.string,value:L.any}),void 0,async({key:Z,value:$},X)=>{if(X.consts.has(Z))throw Error(`Cannot reassign const variable '${Z}'`);if(Z in X.state)throw Error(`Cannot redeclare variable '${Z}' as const`);X.state[Z]=F($,X),X.consts.add(Z)},{docs:"Set Const Variable (immutable)",cost:0.1}),Z5=E("varGet",L.object({key:L.string}),L.any,async({key:Z},$)=>{return F(Z,$)},{docs:"Get Variable",cost:0.1}),X5=E("varsImport",L.object({keys:L.union([L.array(L.string),L.record(L.string)])}),void 0,async({keys:Z},$)=>{if(Array.isArray(Z))for(let X of Z)$.state[X]=F({$kind:"arg",path:X},$);else for(let[X,K]of Object.entries(Z))$.state[X]=F({$kind:"arg",path:K},$)},{docs:"Import variables from args into the current scope, with optional renaming.",cost:0.2}),$5=E("varsLet",L.record(L.any),void 0,async(Z,$)=>{for(let X of Object.keys(Z)){if(X==="op"||X==="result")continue;$.state[X]=F(Z[X],$)}},{docs:"Initialize a set of variables in the current scope from the step object properties.",cost:0.1}),K5=E("varsExport",L.object({keys:L.union([L.array(L.string),L.record(L.string)])}),L.record(L.any),async({keys:Z},$)=>{let X={};if(Array.isArray(Z))for(let K of Z)X[K]=F(K,$);else for(let[K,Q]of Object.entries(Z))X[K]=F(Q,$);return X},{docs:"Export variables from the current scope, with optional renaming.",cost:0.2}),Q5=E("scope",L.object({steps:L.array(L.any)}),void 0,async({steps:Z},$)=>{let X=R1($);if(await $1.exec({op:"seq",steps:Z},X),X.output!==void 0)$.output=X.output},{docs:"Create new scope",timeoutMs:0,cost:0.1}),H5=E("map",L.object({items:L.array(L.any),as:L.string,steps:L.array(L.any)}),L.array(L.any),async({items:Z,as:$,steps:X},K)=>{let Q=[],H=F(Z,K);if(!Array.isArray(H))throw Error("map: items is not an array");for(let Y of H){if(K.signal?.aborted)throw Error("Execution aborted");let z=R1(K);z.state[$]=Y,await $1.exec({op:"seq",steps:X},z),Q.push(z.state.result??null)}return Q},{docs:"Map Array",timeoutMs:0,cost:1}),Y5=E("filter",L.object({items:L.array(L.any),as:L.string,condition:L.any}),L.array(L.any),async({items:Z,as:$,condition:X},K)=>{let Q=[],H=F(Z,K);if(!Array.isArray(H))throw Error("filter: items is not an array");for(let Y of H){if(K.signal?.aborted)throw Error("Execution aborted");let z=R1(K);if(z.state[$]=Y,u(X,z))Q.push(Y)}return Q},{docs:"Filter Array",timeoutMs:0,cost:1}),z5=E("reduce",L.object({items:L.array(L.any),as:L.string,accumulator:L.string,initial:L.any,steps:L.array(L.any)}),L.any,async({items:Z,as:$,accumulator:X,initial:K,steps:Q},H)=>{let Y=F(Z,H),z=F(K,H);if(!Array.isArray(Y))throw Error("reduce: items is not an array");let W=z;for(let G of Y){if(H.signal?.aborted)throw Error("Execution aborted");let J=R1(H);J.state[$]=G,J.state[X]=W,await $1.exec({op:"seq",steps:Q},J),W=J.state.result??W}return W},{docs:"Reduce Array",timeoutMs:0,cost:1}),G5=E("find",L.object({items:L.array(L.any),as:L.string,condition:L.any}),L.any,async({items:Z,as:$,condition:X},K)=>{let Q=F(Z,K);if(!Array.isArray(Q))throw Error("find: items is not an array");for(let H of Q){if(K.signal?.aborted)throw Error("Execution aborted");let Y=R1(K);if(Y.state[$]=H,u(X,Y))return H}return null},{docs:"Find in Array",timeoutMs:0,cost:1}),W5=E("push",L.object({list:L.array(L.any),item:L.any}),L.array(L.any),async({list:Z,item:$},X)=>{let K=F(Z,X),Q=F($,X);if(Array.isArray(K))K.push(Q);return K},{docs:"Push to Array",cost:1}),J5=E("len",L.object({list:L.any}),L.number,async({list:Z},$)=>{let X=F(Z,$);return Array.isArray(X)||typeof X==="string"?X.length:0},{docs:"Length",cost:1}),_5=E("split",L.object({str:L.string,sep:L.string}),L.array(L.string),async({str:Z,sep:$},X)=>F(Z,X).split(F($,X)),{docs:"Split String",cost:1}),L5=E("join",L.object({list:L.array(L.string),sep:L.string}),L.string,async({list:Z,sep:$},X)=>F(Z,X).join(F($,X)),{docs:"Join String",cost:1}),q5=E("template",L.object({tmpl:L.string,vars:L.record(L.any)}),L.string,async({tmpl:Z,vars:$},X)=>{return F(Z,X).replace(/\{\{(\w+)\}\}/g,(Q,H)=>String(F($[H],X)??""))},{docs:"String Template",cost:1}),U5=E("regexMatch",L.object({pattern:L.string,value:L.any}),L.boolean,async({pattern:Z,value:$},X)=>{if(lZ(Z))throw Error(`Suspicious regex pattern rejected (potential ReDoS): ${Z}`);let K=F($,X);return new RegExp(Z).test(K)},{docs:"Returns true if the value matches the regex pattern.",cost:2}),D5=E("pick",L.object({obj:L.record(L.any),keys:L.array(L.string)}),L.record(L.any),async({obj:Z,keys:$},X)=>{let K=F(Z,X),Q=F($,X),H={};if(K&&Array.isArray(Q))Q.forEach((Y)=>H[Y]=K[Y]);return H},{docs:"Pick Keys",cost:1}),I5=E("omit",L.object({obj:L.record(L.any),keys:L.array(L.string)}),L.record(L.any),async({obj:Z,keys:$},X)=>{let K=F(Z,X),Q=new Set(F($,X)),H={};if(K)Object.keys(K).forEach((Y)=>{if(!Q.has(Y))H[Y]=K[Y]});return H},{docs:"Omit Keys",cost:1}),B5=E("merge",L.object({a:L.record(L.any),b:L.record(L.any)}),L.record(L.any),async({a:Z,b:$},X)=>({...F(Z,X),...F($,X)}),{docs:"Merge Objects",cost:1}),R5=E("keys",L.object({obj:L.record(L.any)}),L.array(L.string),async({obj:Z},$)=>Object.keys(F(Z,$)??{}),{docs:"Object Keys",cost:1}),E6=10,S6="X-Agent-Depth";function M5(Z,$){try{let K=new URL(Z).hostname.toLowerCase();for(let Q of $){let H=Q.toLowerCase();if(H.startsWith("*.")){let Y=H.slice(1);if(K.endsWith(Y)||K===H.slice(2))return!0}else if(K===H)return!0}return!1}catch{return!1}}var A5=E("httpFetch",L.object({url:L.string,method:L.string.optional,headers:L.record(L.string).optional,body:L.any.optional,responseType:L.string.optional}),L.any,async(Z,$)=>{let X=F(Z.url,$),K=F(Z.method,$),Q=F(Z.headers,$)||{},H=F(Z.body,$),Y=F(Z.responseType,$),z=$.context?.requestDepth??0;if(z>=E6)throw Error(`Agent request depth exceeded (max ${E6}). This prevents recursive agent loops.`);if($.capabilities.fetch)return $.capabilities.fetch(X,{method:K,headers:{...Q,[S6]:String(z+1)},body:H,signal:$.signal,responseType:Y});let W=$.context?.allowedFetchDomains;if(W){if(!M5(X,W))throw Error(`Fetch blocked: domain not in allowlist. Allowed: ${W.join(", ")}`)}else{if(mZ(X))throw Error("Blocked URL: private/internal addresses not allowed in default fetch");try{let J=new URL(X).hostname.toLowerCase();if(J!=="localhost"&&J!=="127.0.0.1"&&J!=="[::1]")throw Error("Fetch blocked: no allowedFetchDomains configured. Set ctx.context.allowedFetchDomains or provide a custom fetch capability.")}catch(G){if(G.message.includes("allowedFetchDomains"))throw G;throw Error(`Invalid URL: ${X}`)}}if(typeof globalThis.fetch==="function"){let G=await globalThis.fetch(X,{method:K,headers:{...Q,[S6]:String(z+1)},body:H?JSON.stringify(H):void 0,signal:$.signal});if(Y==="dataUrl"){let U=await G.arrayBuffer(),_=new Uint8Array(U),D="";for(let A=0;A<_.length;A++)D+=String.fromCharCode(_[A]);let I=btoa(D);return`data:${G.headers.get("content-type")||"application/octet-stream"};base64,${I}`}let J=G.headers.get("content-type");if(Y==="json"||J&&J.includes("application/json"))return G.json();return G.text()}throw Error("Capability 'fetch' missing and no global fetch available")},{docs:"HTTP Fetch",timeoutMs:30000,cost:5}),j5=E("storeGet",L.object({key:L.string}),L.any,async({key:Z},$)=>{let X=F(Z,$);return $.capabilities.store?.get(X)},{docs:"Store Get",cost:5}),F5=E("storeSet",L.object({key:L.string,value:L.any}),void 0,async({key:Z,value:$},X)=>{let K=F(Z,X),Q=F($,X);return X.capabilities.store?.set(K,Q)},{docs:"Store Set",cost:5}),w5=E("storeQuery",L.object({query:L.any}),L.array(L.any),async({query:Z},$)=>$.capabilities.store?.query?.(F(Z,$))??[],{docs:"Store Query",cost:5}),P5=E("storeVectorSearch",L.object({collection:L.string.optional,vector:L.array(L.number),k:L.number.optional}),L.array(L.any),async({collection:Z,vector:$,k:X},K)=>K.capabilities.store?.vectorSearch?.(F(Z,K),F($,K),F(X,K))??[],{docs:"Vector Search",cost:(Z,$)=>5+(F(Z.k,$)??5)}),C5=E("llmPredict",L.object({prompt:L.string,options:L.any.optional}),L.string,async({prompt:Z,options:$},X)=>{if(!X.capabilities.llm?.predict)throw Error("Capability 'llm.predict' missing");return X.capabilities.llm.predict(F(Z,X),F($,X))},{docs:"LLM Predict",timeoutMs:120000,cost:100}),V5=E("agentRun",L.object({agentId:L.any,input:L.any}),L.any,async({agentId:Z,input:$},X)=>{let K=F(Z,X),Q=F($,X),H=Q;if(Q&&typeof Q==="object"&&!Array.isArray(Q)){H={};for(let z in Q)H[z]=F(Q[z],X)}if(V4(K)){let z=O4(K),W={...X,args:H,state:{},consts:new Set,output:void 0,error:void 0},G=X.resolver("seq");if(!G)throw Error("seq atom not found");if(await G.exec(z,W),W.error)throw Error(W.error.message||"Sub-agent failed");return W.output}if(K&&typeof K==="object"&&"op"in K){let z={...X,args:H,state:{},consts:new Set,output:void 0,error:void 0},W=X.resolver("seq");if(!W)throw Error("seq atom not found");if(await W.exec(K,z),z.error)throw Error(z.error.message||"Sub-agent failed");return z.output}if(!X.capabilities.agent?.run)throw Error("Capability 'agent.run' missing");let Y=await X.capabilities.agent.run(K,H);if(Y&&typeof Y==="object"&&"fuelUsed"in Y&&typeof Y.fuelUsed==="number"){if(Y.error)throw Error(Y.error.message||"Sub-agent failed");return Y.result}return Y},{docs:"Run Sub-Agent (accepts procedure token, AST, or agent ID)",cost:1}),O5=E("transpileCode",L.object({code:L.string}),L.any,async({code:Z},$)=>{if(!$.capabilities.code?.transpile)throw Error("Capability 'code.transpile' missing. Enable code transpilation by providing the code capability.");let X=F(Z,$);try{return $.capabilities.code.transpile(X)}catch(K){throw Error(`Code transpilation failed: ${K.message}`)}},{docs:"Transpile AsyncJS code to AST",cost:1}),T6=10,N5=E("runCode",L.object({code:L.string,args:L.record(L.any).optional}),L.any,async({code:Z,args:$},X)=>{let K=X.runCodeDepth??0;if(K>=T6)throw Error(`runCode recursion limit exceeded (max ${T6}). This prevents infinite loops from dynamically generated code calling runCode.`);if(!X.capabilities.code?.transpile)throw Error("Capability 'code.transpile' missing. Enable dynamic code execution by providing the code capability.");let Q=F(Z,X),H=$?F($,X):{},Y;try{Y=X.capabilities.code.transpile(Q)}catch(W){throw Error(`Code transpilation failed: ${W.message}`)}if(Y.op!=="seq")throw Error("Transpiled code must be a seq node");let z=R1(X);if(z.args=H,z.output=void 0,z.runCodeDepth=K+1,await $1.exec(Y,z),z.error){X.error=z.error;return}return z.output},{docs:"Run dynamically generated AsyncJS code",cost:1}),E5=E("jsonParse",L.object({str:L.string}),L.any,async({str:Z},$)=>JSON.parse(F(Z,$)),{docs:"Parse JSON",cost:1}),S5=E("jsonStringify",L.object({value:L.any}),L.string,async({value:Z},$)=>JSON.stringify(F(Z,$)),{docs:"Stringify JSON",cost:1}),T5=E("xmlParse",L.object({str:L.string}),L.any,async({str:Z},$)=>{if(!$.capabilities.xml?.parse)throw Error("Capability 'xml.parse' missing");return $.capabilities.xml.parse(F(Z,$))},{docs:"Parse XML",cost:1}),k5=E("memoize",L.object({key:L.string.optional,steps:L.array(L.any)}),L.any,async({key:Z,steps:$},X)=>{if(!X.memo)X.memo=new Map;let K=F(Z,X)??await N4.exec({value:$,algorithm:"SHA-256"},X);if(X.memo.has(K))return X.memo.get(K);let Q=R1(X);await $1.exec({op:"seq",steps:$},Q);let H=Q.output??Q.state.result;return X.memo.set(K,H),H},{docs:"Memoize steps result in memory",cost:1}),g5=E("cache",L.object({key:L.string.optional,steps:L.array(L.any),ttlMs:L.number.optional}),L.any,async({key:Z,steps:$,ttlMs:X},K)=>{if(!K.capabilities.store)throw Error("Capability 'store' missing for caching");let H=`cache:${F(Z,K)??await N4.exec({value:$,algorithm:"SHA-256"},K)}`,Y=await K.capabilities.store.get(H);if(Y)if(typeof Y==="object"&&Y._exp){if(Date.now()<Y._exp)return Y.val}else return Y;let z=R1(K);await $1.exec({op:"seq",steps:$},z);let W=z.output??z.state.result,G=Date.now()+(X??86400000);if((K.fuel.current-=5)<=0)throw Error("Out of Fuel");return await K.capabilities.store.set(H,{val:W,_exp:G}),W},{docs:"Cache steps result in store with TTL",cost:5}),b5=E("random",L.object({min:L.number.optional,max:L.number.optional,format:L.string.optional,length:L.number.optional}),L.any,async({min:Z,max:$,format:X,length:K},Q)=>{let H=F(X,Q)??"float",Y=F(K,Q)??10,z=F(Z,Q)??0,W=F($,Q)??1;if(H==="base36"){let D="";if(typeof crypto<"u"&&crypto.getRandomValues){let I=new Uint8Array(Y);crypto.getRandomValues(I);for(let B=0;B<Y;B++)D+="0123456789abcdefghijklmnopqrstuvwxyz"[I[B]%36]}else for(let I=0;I<Y;I++)D+="0123456789abcdefghijklmnopqrstuvwxyz".charAt(Math.floor(Math.random()*36));return D}let G;if(typeof crypto<"u"&&crypto.getRandomValues){let _=new Uint32Array(1);crypto.getRandomValues(_),G=_[0]/4294967296}else G=Math.random();let J=W-z,U=G*J+z;if(H==="integer")return Math.floor(U);return U},{docs:"Generate Random",cost:1}),f5=E("uuid",void 0,L.string,async()=>{if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();if(typeof crypto<"u"&&crypto.getRandomValues){let Z=new Uint8Array(16);crypto.getRandomValues(Z),Z[6]=Z[6]&15|64,Z[8]=Z[8]&63|128;let $=Array.from(Z,(X)=>X.toString(16).padStart(2,"0")).join("");return`${$.slice(0,8)}-${$.slice(8,12)}-${$.slice(12,16)}-${$.slice(16,20)}-${$.slice(20)}`}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(Z)=>{let $=Math.random()*16|0;return(Z==="x"?$:$&3|8).toString(16)})},{docs:"Generate UUID",cost:1}),N4=E("hash",L.object({value:L.any,algorithm:L.string.optional}),L.string,async({value:Z,algorithm:$},X)=>{let K=typeof Z==="string"?Z:JSON.stringify(F(Z,X)),Q=F($,X)||"SHA-256";if(typeof crypto<"u"&&crypto.subtle){let z=new TextEncoder().encode(K),W=await crypto.subtle.digest(Q,z);return Array.from(new Uint8Array(W)).map((J)=>J.toString(16).padStart(2,"0")).join("")}let H=0;for(let Y=0;Y<K.length;Y++){let z=K.charCodeAt(Y);H=(H<<5)-H+z,H|=0}return String(H)},{docs:"Hash a value",cost:1}),v5=E("consoleLog",L.object({message:L.any}),void 0,async({message:Z},$)=>{let X=F(Z,$);if($.trace)$.trace.push({op:"console.log",input:{message:X},stateDiff:{},result:X,fuelBefore:$.fuel.current,fuelAfter:$.fuel.current,timestamp:new Date().toISOString()})},{docs:"Log to trace",cost:0.1}),y5=E("consoleWarn",L.object({message:L.any}),void 0,async({message:Z},$)=>{let X=F(Z,$),K=typeof X==="string"?X:JSON.stringify(X);if(!$.warnings)$.warnings=[];if($.warnings.push(K),$.trace)$.trace.push({op:"console.warn",input:{message:X},stateDiff:{},result:X,fuelBefore:$.fuel.current,fuelAfter:$.fuel.current,timestamp:new Date().toISOString()})},{docs:"Add warning",cost:0.1}),h5=E("consoleError",L.object({message:L.any}),void 0,async({message:Z},$)=>{let X=F(Z,$),K=typeof X==="string"?X:JSON.stringify(X);$.error=new e(K,"console.error")},{docs:"Emit error and stop",cost:0.1}),x5=E("storeProcedure",L.object({ast:L.any,ttl:L.number.optional,maxSize:L.number.optional}),L.string,async({ast:Z,ttl:$,maxSize:X},K)=>{let Q=F(Z,K),H=$?F($,K):hZ,Y=X?F(X,K):xZ;if(!Q||typeof Q!=="object"||!Q.op)throw Error('Invalid AST: must be an object with an "op" property');let z=JSON.stringify(Q);if(z.length>Y)throw Error(`AST too large: ${z.length} bytes exceeds limit of ${Y} bytes. Consider reducing AST size or using a shorter TTL.`);let W=uZ(),G=Date.now();return f1.set(W,{ast:Q,createdAt:G,expiresAt:G+H}),W},{docs:"Store an AST and return a token for later execution",cost:1}),u5=E("releaseProcedure",L.object({token:L.string}),L.boolean,async({token:Z},$)=>{let X=F(Z,$);return f1.delete(X)},{docs:"Release a stored procedure by token",cost:0.1}),d5=E("clearExpiredProcedures",void 0,L.number,async()=>{let Z=Date.now(),$=0;for(let[X,K]of f1)if(Z>K.expiresAt)f1.delete(X),$++;return $},{docs:"Clear all expired procedures and return count",cost:0.5}),d0={seq:$1,if:cZ,while:oZ,return:sZ,try:aZ,Error:rZ,varSet:tZ,constSet:eZ,varGet:Z5,varsImport:X5,varsLet:$5,varsExport:K5,scope:Q5,map:H5,filter:Y5,reduce:z5,find:G5,push:W5,len:J5,split:_5,join:L5,template:q5,regexMatch:U5,pick:D5,omit:I5,merge:B5,keys:R5,httpFetch:A5,storeGet:j5,storeSet:F5,storeQuery:w5,storeVectorSearch:P5,llmPredict:C5,agentRun:V5,transpileCode:O5,runCode:N5,jsonParse:E5,jsonStringify:S5,xmlParse:T5,memoize:k5,cache:g5,random:b5,uuid:f5,hash:N4,consoleLog:v5,consoleWarn:y5,consoleError:h5,storeProcedure:x5,releaseProcedure:u5,clearExpiredProcedures:d5};var m5=new Set(["true","false","null","undefined","and","or","not"]);function l5(Z,$){let X=Z.replace(/"[^"]*"/g,'""').replace(/'[^']*'/g,"''"),K=[],Q=/(?<![.])\b([a-zA-Z_][a-zA-Z0-9_]*)\b/g,H;while((H=Q.exec(X))!==null)K.push(H[1]);let z=[...new Set(K)].filter((W)=>!m5.has(W)&&!(W in $)&&!new RegExp(`\\b${W}\\s*\\(`).test(X));if(z.length>0)console.warn(`[Agent99 Builder] Condition "${Z}" references variables not in vars mapping: ${z.join(", ")}. Add them to vars or use AsyncJS syntax (ajs\`...\`) which handles this automatically.`)}function m0(Z,$){l5(Z,$);let X=i5(Z),K=h6(X,0,$);if(K.pos<X.length){let Q=X.slice(K.pos).join(" ");throw Error(`Unsupported condition syntax near '${Q}' in: ${Z}
|
|
351
|
+
Supported: comparisons, &&, ||, !, arithmetic, member access (a.b), literals`)}return K.node}function i5(Z){let $=[],X=0;while(X<Z.length){while(X<Z.length&&/\s/.test(Z[X]))X++;if(X>=Z.length)break;if(Z[X]==='"'||Z[X]==="'"){let K=Z[X++],Q="";while(X<Z.length&&Z[X]!==K)if(Z[X]==="\\"&&X+1<Z.length)X++,Q+=Z[X++];else Q+=Z[X++];X++,$.push(JSON.stringify(Q));continue}if(Z.slice(X,X+2).match(/^(&&|\|\||==|!=|>=|<=)$/)){$.push(Z.slice(X,X+2)),X+=2;continue}if("+-*/%><!().?:[]".includes(Z[X])){$.push(Z[X]),X++;continue}if(/\d/.test(Z[X])){let K="";while(X<Z.length&&/[\d.]/.test(Z[X]))K+=Z[X++];$.push(K);continue}if(/[a-zA-Z_]/.test(Z[X])){let K="";while(X<Z.length&&/[a-zA-Z0-9_]/.test(Z[X]))K+=Z[X++];$.push(K);continue}X++}return $}function h6(Z,$,X){return p5(Z,$,X)}function p5(Z,$,X){let{node:K,pos:Q}=b6(Z,$,X);while(Z[Q]==="||"){Q++;let{node:H,pos:Y}=b6(Z,Q,X);K={$expr:"logical",op:"||",left:K,right:H},Q=Y}return{node:K,pos:Q}}function b6(Z,$,X){let{node:K,pos:Q}=f6(Z,$,X);while(Z[Q]==="&&"){Q++;let{node:H,pos:Y}=f6(Z,Q,X);K={$expr:"logical",op:"&&",left:K,right:H},Q=Y}return{node:K,pos:Q}}function f6(Z,$,X){let{node:K,pos:Q}=v6(Z,$,X),H=["==","!=",">","<",">=","<="];while(H.includes(Z[Q])){let Y=Z[Q++],{node:z,pos:W}=v6(Z,Q,X);K={$expr:"binary",op:Y,left:K,right:z},Q=W}return{node:K,pos:Q}}function v6(Z,$,X){let{node:K,pos:Q}=y6(Z,$,X);while(Z[Q]==="+"||Z[Q]==="-"){let H=Z[Q++],{node:Y,pos:z}=y6(Z,Q,X);K={$expr:"binary",op:H,left:K,right:Y},Q=z}return{node:K,pos:Q}}function y6(Z,$,X){let{node:K,pos:Q}=E4(Z,$,X);while(Z[Q]==="*"||Z[Q]==="/"||Z[Q]==="%"){let H=Z[Q++],{node:Y,pos:z}=E4(Z,Q,X);K={$expr:"binary",op:H,left:K,right:Y},Q=z}return{node:K,pos:Q}}function E4(Z,$,X){if(Z[$]==="!"||Z[$]==="-"){let K=Z[$++],{node:Q,pos:H}=E4(Z,$,X);return{node:{$expr:"unary",op:K,argument:Q},pos:H}}return n5(Z,$,X)}function n5(Z,$,X){let K=Z[$];if(K==="("){let{node:Q,pos:H}=h6(Z,$+1,X);return{node:Q,pos:H+1}}if(K&&K.startsWith('"'))return{node:{$expr:"literal",value:JSON.parse(K)},pos:$+1};if(K&&/^\d/.test(K))return{node:{$expr:"literal",value:parseFloat(K)},pos:$+1};if(K==="true")return{node:{$expr:"literal",value:!0},pos:$+1};if(K==="false")return{node:{$expr:"literal",value:!1},pos:$+1};if(K==="null")return{node:{$expr:"literal",value:null},pos:$+1};if(K&&/^[a-zA-Z_]/.test(K)){let Q={$expr:"ident",name:K},H=$+1;while(Z[H]==="."){H++;let Y=Z[H++];Q={$expr:"member",object:Q,property:Y}}return{node:Q,pos:H}}return{node:{$expr:"literal",value:null},pos:$+1}}class s{steps=[];atoms;proxy;constructor(Z){return this.atoms=Z,this.proxy=new Proxy(this,{get:($,X,K)=>{if(X in $)return $[X];if(typeof X==="string"&&X in $.atoms)return(Q)=>{let H=$.atoms[X];return $.add(H.create(Q)),K};return}}),this.proxy}add(Z){return this.steps.push(Z),this.proxy}as(Z){if(this.steps.length===0)throw Error("No step to capture");let $=this.steps[this.steps.length-1];return $.result=Z,this.proxy}step(Z){return this.add(Z)}return(Z){let $=this.atoms.return;if(!$)throw Error("Atom 'return' not found");let X=Z.schema??Z;return this.add($.create({schema:X}))}toJSON(){return{op:"seq",steps:[...this.steps]}}varsImport(Z){return this.add(this.atoms.varsImport.create({keys:Z}))}varsExport(Z){return this.add(this.atoms.varsExport.create({keys:Z}))}if(Z,$,X,K){let Q=new s(this.atoms);X(Q);let H;if(K){let W=new s(this.atoms);K(W),H=W.steps}let Y=m0(Z,$),z=this.atoms.if;return this.add(z.create({condition:Y,then:Q.steps,else:H}))}while(Z,$,X){let K=new s(this.atoms);X(K);let Q=m0(Z,$),H=this.atoms.while;return this.add(H.create({condition:Q,body:K.steps}))}scope(Z){let $=new s(this.atoms);Z($);let X=this.atoms.scope;return this.add(X.create({steps:$.steps}))}map(Z,$,X){let K=new s(this.atoms);X(K);let Q=this.atoms.map;return this.add(Q.create({items:Z,as:$,steps:K.steps}))}filter(Z,$,X,K={}){let Q=m0(X,K),H=this.atoms.filter;return this.add(H.create({items:Z,as:$,condition:Q}))}find(Z,$,X,K={}){let Q=m0(X,K),H=this.atoms.find;return this.add(H.create({items:Z,as:$,condition:Q}))}reduce(Z,$,X,K,Q){let H=new s(this.atoms);Q(H);let Y=this.atoms.reduce;return this.add(Y.create({items:Z,as:$,accumulator:X,initial:K,steps:H.steps}))}memoize(Z,$){let X=new s(this.atoms);Z(X);let K=this.atoms.memoize;return this.add(K.create({key:$,steps:X.steps}))}cache(Z,$,X){let K=new s(this.atoms);Z(K);let Q=this.atoms.cache;return this.add(Q.create({key:$,steps:K.steps,ttlMs:X}))}try(Z){let $=new s(this.atoms);Z.try($);let X;if(Z.catch){let Q=new s(this.atoms);Z.catch(Q),X=Q.steps}let K=this.atoms.try;return this.add(K.create({try:$.steps,catch:X}))}}var c5={take(Z){return new s(d0)},custom(Z){return new s(Z)},args(Z){return{$kind:"arg",path:Z}},val(Z){return Z}},JK=c5;import{validate as o5}from"tosijs-schema";function e1(Z,$={}){let{ast:X,returnType:K,originalSource:Q,requiredParams:H}=W1(Z,{filename:$.filename,colonShorthand:!0,vmTarget:!0}),Y=_0(X,$.filename),{ast:z,signature:W,warnings:G}=l1(Y,Q,K,$,H);return{ast:z,signature:W,warnings:G}}var s5=10;class S4{atoms;constructor(Z={}){this.atoms={...d0,...Z}}get builder(){return new s(this.atoms)}get Agent(){return new s(this.atoms)}get A99(){return this.Agent}resolve(Z){return this.atoms[Z]}getTools(Z="all"){let $=Object.values(this.atoms);if(Array.isArray(Z))$=$.filter((X)=>Z.includes(X.op));else if(Z==="flow"){let X=["seq","if","while","return","try","varSet","varGet","scope"];$=$.filter((K)=>X.includes(K.op))}return $.map((X)=>({type:"function",function:{name:X.op,description:X.docs,parameters:X.inputSchema?.schema??{}}}))}async run(Z,$={},X={}){let K;if(typeof Z==="string")if(V4(Z))K=O4(Z);else try{K=e1(Z).ast}catch(D){throw Error(`AJS transpilation failed: ${D.message}`)}else K=Z;let Q=X.fuel??1000,H=X.timeoutMs??Q*s5,Y=X.capabilities??{},z=[];if(!Y.store){let D=new Map,I=!1;Y.store={get:async(B)=>{if(!I)I=!0,z.push("Using default in-memory store (not suitable for production)");return D.get(B)},set:async(B,A)=>{if(!I)I=!0,z.push("Using default in-memory store (not suitable for production)");D.set(B,A)}}}let W=new AbortController,G=setTimeout(()=>W.abort(),H);if(X.signal)X.signal.addEventListener("abort",()=>W.abort());let J={fuel:{current:Q},args:$,state:{},consts:new Set,capabilities:Y,resolver:(D)=>this.resolve(D),output:void 0,signal:W.signal,costOverrides:X.costOverrides,context:X.context,warnings:z};if(X.trace)J.trace=[];if(K.op!=="seq")throw Error("Root AST must be 'seq'. Ensure you're passing a transpiled agent (use ajs`...` or transpile()).");let U=K.inputSchema;if(U&&!o5($,U)){let D=new e("Input validation failed: args do not match expected schema","vm.run");return{result:D,error:D,fuelUsed:0,trace:J.trace,warnings:z.length>0?z:void 0}}try{await Promise.race([this.resolve("seq")?.exec(K,J),new Promise((D,I)=>{if(W.signal.addEventListener("abort",()=>{I(Error(`Execution timeout after ${H}ms (fuel: ${Q}). Consider increasing fuel or optimizing your agent.`))}),W.signal.aborted)I(Error(`Execution timeout after ${H}ms (fuel: ${Q}). Consider increasing fuel or optimizing your agent.`))})])}catch(D){if(D.message?.includes("timeout")||D.message?.includes("aborted")||W.signal.aborted)J.error=new e(`Execution timeout after ${H}ms (fuel: ${Q}). Consider increasing fuel or optimizing your agent.`,"vm.run");else throw D}finally{clearTimeout(G)}if(J.error&&J.output===void 0)J.output=J.error;let _=[...z,...J.warnings??[]];return{result:J.output,error:J.error,fuelUsed:Q-J.fuel.current,trace:J.trace,warnings:_.length>0?_:void 0}}}var a5=null,x6=()=>a5??=new S4;async function r5(Z){let{code:$,context:X={},fuel:K=1000,timeoutMs:Q,capabilities:H={}}=Z,Y=x6(),W=/\breturn\b/.test($)?`function __eval() { ${$} }`:`function __eval() { return (${$}) }`;try{let{ast:G}=e1(W),J=await Y.run(G,X,{fuel:K,timeoutMs:Q,capabilities:H});return{result:J.result,fuelUsed:J.fuelUsed,error:J.error?{message:J.error.message||String(J.error)}:void 0}}catch(G){return{result:void 0,fuelUsed:K,error:{message:G.message||String(G)}}}}async function t5(Z){let{body:$,params:X=[],fuel:K=1000,timeoutMs:Q,capabilities:H={}}=Z,Y=x6(),W=`function __safeFn(${X.join(", ")}) { ${$} }`,{ast:G}=e1(W);return async(...J)=>{let U={};for(let _=0;_<X.length;_++)U[X[_]]=J[_];try{let _=await Y.run(G,U,{fuel:K,timeoutMs:Q,capabilities:H});return{result:_.result,fuelUsed:_.fuelUsed,error:_.error?{message:_.error.message||String(_.error)}:void 0}}catch(_){return{result:void 0,fuelUsed:K,error:{message:_.message||String(_)}}}}}function i0(Z,$={}){let{ast:X,returnType:K,originalSource:Q,requiredParams:H}=W1(Z,{filename:$.filename,colonShorthand:!0,vmTarget:!0}),Y=_0(X,$.filename),{ast:z,signature:W,warnings:G}=l1(Y,Q,K,$,H);return{ast:z,signature:W,warnings:G}}function NK(Z,...$){if(typeof Z==="string")return i0(Z).ast;let X=Z.reduce((K,Q,H)=>K+Q+($[H]!==void 0?String($[H]):""),"");return i0(X).ast}function SK(Z,$,...X){if(typeof Z==="string")return a1(Z,$);let K=$!==void 0?[$,...X]:X,Q=Z.reduce((H,Y,z)=>H+Y+(K[z]!==void 0?String(K[z]):""),"");return a1(Q)}async function TK(Z,$={},X){let K=X??await h0(),Q=await K.getTranspile(Z);if(Q)return{ast:Q.ast,signature:Q.signature,warnings:Q.warnings};let H=i0(Z,$);return K.setTranspile(Z,{ast:H.ast,signature:H.signature,warnings:H.warnings}),H}async function kK(Z,$={},X){let K=X??await h0(),Q=await K.getTJS(Z);if(Q)return{code:Q.code,types:Q.types,metadata:Q.types,testRunner:Q.testRunner,testCount:Q.testCount,warnings:Q.warnings};let H=a1(Z,$);return K.setTJS(Z,{code:H.code,types:H.types,testRunner:H.testRunner,testCount:H.testCount,warnings:H.warnings}),H}function gK(Z,$,X){let{ast:K,signature:Q}=i0(Z),H=async(Y)=>{return(await $.run(K,Y,X)).result};return H.signature=Q,H.ast=K,H}function bK(Z){return Object.entries(Z).map(([$,X])=>{let K=X.signature,Q={},H=[];for(let[Y,z]of Object.entries(K.parameters)){if(Q[Y]=l0(z.type),z.description)Q[Y].description=z.description;if(z.required)H.push(Y)}return{type:"function",function:{name:K.name||$,description:K.description,parameters:{type:"object",properties:Q,required:H}}}})}function l0(Z){switch(Z.kind){case"string":return{type:"string"};case"number":return{type:"number"};case"boolean":return{type:"boolean"};case"null":return{type:"null"};case"array":return{type:"array",items:Z.items?l0(Z.items):{}};case"object":if(!Z.shape)return{type:"object"};return{type:"object",properties:Object.fromEntries(Object.entries(Z.shape).map(([$,X])=>[$,l0(X)]))};case"union":if(!Z.members)return{};return{anyOf:Z.members.map(l0)};case"any":default:return{}}}import{s as T}from"tosijs-schema";var u6=E("storeVectorize",T.object({text:T.string,model:T.string.optional}),T.array(T.number),async({text:Z},$)=>{let X=$.capabilities.vector;if(!X)throw Error("Capability 'vector' missing. Ensure vector battery is loaded.");let K=F(Z,$);return X.embed(K)},{docs:"Generate embeddings using vector battery",cost:20}),d6=E("storeCreateCollection",T.object({collection:T.string,dimension:T.number.optional}),void 0,async({collection:Z,dimension:$},X)=>{let K=X.capabilities.store;if(!K?.createCollection)throw Error("Capability 'store' missing or does not support createCollection.");let Q=F(Z,X),H=F($,X);return K.createCollection(Q,void 0,H)},{docs:"Create a vector store collection",cost:5}),m6=E("storeVectorAdd",T.object({collection:T.string,doc:T.any}),void 0,async({collection:Z,doc:$},X)=>{let K=X.capabilities.store;if(!K?.vectorAdd)throw Error("Capability 'store' missing or does not support vectorAdd.");let Q=F(Z,X),H=F($,X);return K.vectorAdd(Q,H)},{docs:"Add a document to a vector store collection",cost:5}),l6=E("storeSearch",T.object({collection:T.string,queryVector:T.array(T.number),k:T.number.optional,filter:T.record(T.any).optional}),T.array(T.any),async({collection:Z,queryVector:$,k:X,filter:K},Q)=>{let H=Q.capabilities.store;if(!H?.vectorSearch)throw Error("Capability 'store' missing or does not support vectorSearch.");let Y=F(Z,Q),z=F($,Q),W=F(X,Q)??5,G=F(K,Q);return H.vectorSearch(Y,z,W,G)},{docs:"Search vector store",cost:(Z,$)=>5+(F(Z.k,$)??5)}),i6=E("llmPredictBattery",T.object({system:T.string.optional,user:T.string,tools:T.array(T.any).optional,responseFormat:T.any.optional}),T.object({role:T.string.optional,content:T.string.optional,tool_calls:T.array(T.any).optional}),async({system:Z,user:$,tools:X,responseFormat:K},Q)=>{let H=Q.capabilities.llmBattery;if(!H?.predict)throw Error("Capability 'llmBattery' missing or invalid.");let Y=F(Z,Q)??"You are a helpful agent.",z=F($,Q),W=F(X,Q),G=F(K,Q);return H.predict(Y,z,W,G)},{docs:"Generate completion using LLM battery",cost:100}),p6=E("llmVision",T.object({system:T.string.optional,prompt:T.string,images:T.array(T.string),responseFormat:T.any.optional}),T.object({role:T.string.optional,content:T.string.optional,tool_calls:T.array(T.any).optional}),async({system:Z,prompt:$,images:X,responseFormat:K},Q)=>{let H=Q.capabilities.llmBattery;if(!H?.predict)throw Error("Capability 'llmBattery' missing or invalid.");let Y=F(Z,Q)??"You analyze images accurately and concisely.",z=F($,Q),W=F(X,Q)??[],G=F(K,Q);return H.predict(Y,{text:z,images:W},void 0,G)},{docs:"Analyze images using a vision model",timeoutMs:120000,cost:150});var XQ={storeCreateCollection:d6,storeSearch:l6,storeVectorAdd:m6,storeVectorize:u6,llmPredictBattery:i6,llmVision:p6};var n6=new Map,p0=new Map;function e5(Z,$){if(Z.length!==$.length)throw Error("Vectors must have the same length for cosine similarity.");let X=0,K=0,Q=0;for(let H=0;H<Z.length;H++)X+=Z[H]*$[H],K+=Z[H]*Z[H],Q+=$[H]*$[H];if(K=Math.sqrt(K),Q=Math.sqrt(Q),K===0||Q===0)return 0;return X/(K*Q)}function T4(){return{async get(Z){return n6.get(Z)},async set(Z,$){n6.set(Z,$)},async createCollection(Z,$,X){if(p0.has(Z))console.warn(`Collection '${Z}' already exists. Overwriting.`);p0.set(Z,[])},async vectorAdd(Z,$){let X=p0.get(Z);if(!X)throw Error(`Collection '${Z}' not found. Create it first.`);if(!$.embedding||!Array.isArray($.embedding))throw Error("Document must have an 'embedding' property that is an array of numbers.");X.push($)},async vectorSearch(Z,$,X=5){let K=p0.get(Z);if(!K)throw Error(`Collection '${Z}' not found. Create it first.`);let Q=K.map((H)=>({doc:H,score:e5($,H.embedding)}));return Q.sort((H,Y)=>Y.score-H.score),Q.slice(0,X).map((H)=>H.doc)}}}function ZX(Z){if(typeof Z==="string")return{role:"user",content:Z};let $=[{type:"text",text:Z.text}];for(let X of Z.images||[])$.push({type:"image_url",image_url:{url:X}});return{role:"user",content:$}}var XX="http://localhost:1234/v1";function c6(Z,$=XX){return{async predict(X,K,Q,H){try{let Y=H?Z.getStructuredLLM():Z.getLLM(),z=[{role:"system",content:X},ZX(K)],W=await fetch(`${$}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:Y.id,messages:z,temperature:0.7,tools:Q,response_format:H})});if(!W.ok)throw Error(`LLM Error: ${W.status} ${W.statusText}`);return(await W.json()).choices[0]?.message??{content:""}}catch(Y){if(Y.cause?.code==="ECONNREFUSED")throw Error("No LLM provider configured. Please start LM Studio or provide an API key.");throw Y}},async embed(X){try{let K=Z.getEmbedding(),Q=await fetch(`${$}/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:K.id,input:X})});if(!Q.ok)throw Error(`Embedding Error: ${Q.status}`);return(await Q.json()).data[0]?.embedding??[]}catch(K){if(K.cause?.code==="ECONNREFUSED")throw Error("No LLM provider configured. Please start LM Studio or provide an API key.");throw K}}}}var Z0=typeof window<"u"&&typeof window.localStorage<"u";async function QX(Z){try{if(Z0){let $=window.localStorage.getItem(".models.cache.json");if(!$)return null;let X=JSON.parse($);if(X.baseUrl!==Z)return null;if(Date.now()-X.timestamp>86400000)return null;return X.models}else{let $=await import("node:fs/promises"),K=(await Promise.resolve().then(() => (b4(),g4))).join(process.cwd(),".models.cache.json");try{let Q=await $.readFile(K,"utf-8"),H=JSON.parse(Q);if(H.baseUrl!==Z)return null;if(Date.now()-H.timestamp>86400000)return null;return H.models}catch{return null}}}catch($){return console.warn("⚠️ Error reading model cache:",$),null}}async function HX(Z,$){let X={timestamp:Date.now(),baseUrl:Z,models:$};try{if(Z0)window.localStorage.setItem(".models.cache.json",JSON.stringify(X));else{let K=await import("node:fs/promises"),H=(await Promise.resolve().then(() => (b4(),g4))).join(process.cwd(),".models.cache.json");await K.writeFile(H,JSON.stringify(X,null,2))}}catch(K){console.error("❌ Error writing model cache:",K)}}var X0=async(Z,$)=>{let X=new AbortController,K=setTimeout(()=>X.abort(),60000);try{let Q=await fetch(Z,{...$,signal:X.signal});return clearTimeout(K),Q}catch(Q){throw clearTimeout(K),Q}};async function YX(Z,$){try{let X={type:"json_schema",json_schema:{name:"test",strict:!1,schema:{type:"object",properties:{status:{type:"string"}}}}},K=await X0(`${Z}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:$,messages:[{role:"system",content:"You respond in JSON."},{role:"user",content:'Return JSON: {"status": "ok"}'}],response_format:X,max_tokens:20})});if(!K.ok){if(K.status===400)return zX(Z,$);return{ok:!1,msg:`HTTP ${K.status}`}}let Q=await K.json();return JSON.parse(Q.choices[0].message.content),{ok:!0,msg:"OK (Schema)"}}catch(X){return{ok:!1,msg:X.message||"Error"}}}async function zX(Z,$){try{if((await X0(`${Z}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:$,messages:[{role:"user",content:'JSON: {"a":1}'}],response_format:{type:"json_object"},max_tokens:10})})).ok)return{ok:!0,msg:"OK (Legacy Mode)"};return{ok:!1,msg:"Not Supported"}}catch{return{ok:!1,msg:"Legacy Fail"}}}async function GX(Z,$){try{return(await X0(`${Z}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:$,messages:[{role:"user",content:"hi"}],max_tokens:1})})).ok}catch{return!1}}async function WX(Z,$){try{let X=await X0(`${Z}/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:$,input:"test"})});if(!X.ok)return null;return(await X.json()).data[0]?.embedding?.length??null}catch{return null}}var JX="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==";async function _X(Z,$){try{return(await X0(`${Z}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:$,messages:[{role:"user",content:[{type:"text",text:"What color is this?"},{type:"image_url",image_url:{url:JX}}]}],max_tokens:10})})).ok}catch{return!1}}async function z7(Z){let $=await QX(Z),X=[];try{let Y=await fetch(`${Z}/models`);if(!Y.ok)throw Error("Could not connect");X=(await Y.json()).data.map((W)=>W.id).sort()}catch(Y){if($)return console.log("⚠️ LM Studio unavailable, using cached model audit."),$;return console.error("❌ Failed to connect to LM Studio."),[]}if($){let Y=$.map((z)=>z.id).sort();if(JSON.stringify(X)===JSON.stringify(Y))return console.log("✅ Using cached model audit."),$;console.log("\uD83D\uDD0D Model list changed. Re-running audit...")}console.log("\uD83D\uDD0D Scanning models (this may take a moment)...");let K=[],Q=X.map((Y)=>({id:Y})),H;if(!Z0)H=await import("node:readline");for(let Y of Q){if(!Z0&&H)H.cursorTo(process.stdout,0),process.stdout.write(`\uD83D\uDC49 Testing: ${Y.id}...`),H.clearLine(process.stdout,1);let z="Unknown",W=!1,G=!1,J="",U=void 0,_=await GX(Z,Y.id),D=await WX(Z,Y.id);if(D)U=D;if(_){z="LLM";let I=await YX(Z,Y.id);if(W=I.ok,G=await _X(Z,Y.id),J=W?I.msg:`Fail: ${I.msg}`,G)J+=" +Vision"}else if(D)z="Embedding",J=`OK (Dim: ${D})`;else J="LLM Fail";K.push({id:Y.id,type:z,structuredOutput:W,vision:G,dimension:U,status:J})}if(!Z0&&H)H.cursorTo(process.stdout,0),H.clearLine(process.stdout,0);return console.log(`
|
|
352
|
+
`),console.table(K),await HX(Z,K),console.log("\uD83D\uDCDD Audit results saved to cache."),K}var LX="http://localhost:1234/v1";class f4{baseUrl;models=[];defaultLLM=null;defaultEmbedding=null;defaultStructuredLLM=null;constructor(Z=LX){this.baseUrl=Z}async audit(){this.models=await z7(this.baseUrl),this.selectDefaults()}selectDefaults(){if(this.defaultEmbedding=this.models.find((Z)=>Z.type==="Embedding")||null,this.defaultLLM=this.models.find((Z)=>Z.type==="LLM")||null,this.defaultStructuredLLM=this.models.find((Z)=>Z.type==="LLM"&&Z.structuredOutput)||null,!this.defaultEmbedding)console.warn("⚠️ No embedding model found.");if(!this.defaultLLM)console.warn("⚠️ No LLM found.");if(!this.defaultStructuredLLM)console.warn("⚠️ No LLM with structured output support found.")}getModels(){return this.models}_setDefaultModel(Z,$,X,K){let Q=this.models.find((H)=>H.id===Z&&X(H));if(!Q)throw Error(`Model '${Z}' not found or is not ${K}.`);this[$]=Q}setDefaultLLM(Z){this._setDefaultModel(Z,"defaultLLM",($)=>$.type==="LLM","an LLM")}setDefaultEmbedding(Z){this._setDefaultModel(Z,"defaultEmbedding",($)=>$.dimension!==void 0,"an embedding model")}setDefaultStructuredLLM(Z){this._setDefaultModel(Z,"defaultStructuredLLM",($)=>$.type==="LLM"&&$.structuredOutput,"a structured-output LLM")}getLLM(){if(!this.defaultLLM)throw Error("No LLM available.");return this.defaultLLM}getEmbedding(){if(!this.defaultEmbedding)throw Error("No embedding model available.");return this.defaultEmbedding}getStructuredLLM(){if(!this.defaultStructuredLLM)throw Error("No structured-output LLM available.");return this.defaultStructuredLLM}}var qX=typeof window<"u",UX=qX&&window.location.protocol==="https:",$0=null,v4=null,G7=!1;async function DX(){if(G7)return{localModels:$0,llm:v4};if(G7=!0,UX)return console.log("\uD83D\uDCE1 HTTPS detected - local LLM endpoints disabled. Use HTTP for local LLM support."),{localModels:null,llm:null};try{$0=new f4,await $0.audit(),v4=c6($0)}catch(Z){console.warn("⚠️ Could not connect to local LLM:",Z)}return{localModels:$0,llm:v4}}async function IX(){let{localModels:Z,llm:$}=await DX();return{vector:$?{embed:$.embed}:void 0,store:T4(),llmBattery:$,models:Z}}async function _Q(){return IX()}var LQ={store:T4(),llmBattery:null,vector:void 0,models:null};function BX(Z){if(typeof Z!=="string")return!1;let $=new Date(Z);return!isNaN($.getTime())&&Z.includes("T")}function RX(){return new Date().toISOString()}function v1(Z,$,X,K=0,Q=0,H=0,Y=0){return new Date(Date.UTC(Z,$-1,X,K,Q,H,Y)).toISOString()}function W7(Z){let $=new Date(Z);if(isNaN($.getTime()))throw Error(`Invalid date string: ${Z}`);return $.toISOString()}function MX(Z){try{return W7(Z)}catch{return null}}function K0(Z,$){let X=new Date(Z);return X.setTime(X.getTime()+$),X.toISOString()}function AX(Z,$){return K0(Z,$*1000)}function jX(Z,$){return K0(Z,$*60*1000)}function FX(Z,$){return K0(Z,$*60*60*1000)}function J7(Z,$){return K0(Z,$*24*60*60*1000)}function wX(Z,$){return J7(Z,$*7)}function PX(Z,$){let X=new Date(Z),K=X.getUTCMonth()+$;if(X.setUTCMonth(K),X.getUTCMonth()!==(K%12+12)%12)X.setUTCDate(0);return X.toISOString()}function CX(Z,$){let X=new Date(Z),K=X.getUTCDate();if(X.setUTCFullYear(X.getUTCFullYear()+$),X.getUTCDate()!==K)X.setUTCDate(0);return X.toISOString()}function M1(Z,$){return new Date(Z).getTime()-new Date($).getTime()}function VX(Z,$){return Math.floor(M1(Z,$)/1000)}function OX(Z,$){return Math.floor(M1(Z,$)/60000)}function NX(Z,$){return Math.floor(M1(Z,$)/3600000)}function EX(Z,$){return Math.floor(M1(Z,$)/86400000)}function y1(Z){return new Date(Z).getUTCFullYear()}function c0(Z){return new Date(Z).getUTCMonth()+1}function y4(Z){return new Date(Z).getUTCDate()}function SX(Z){return new Date(Z).getUTCHours()}function TX(Z){return new Date(Z).getUTCMinutes()}function kX(Z){return new Date(Z).getUTCSeconds()}function gX(Z){return new Date(Z).getUTCMilliseconds()}function bX(Z){let $=new Date(Z).getUTCDay();return $===0?7:$}function o0(Z,$,X){let K=new Date(Z),Q={timeZone:$,...X};return new Intl.DateTimeFormat(void 0,Q).format(K)}function fX(Z,$){return o0(Z,$,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"})}function vX(Z,$){return o0(Z,$,{year:"numeric",month:"short",day:"numeric"})}function yX(Z,$){return o0(Z,$,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}function hX(Z){return Z.slice(0,10)}function _7(Z,$){return M1(Z,$)<0}function L7(Z,$){return M1(Z,$)>0}function xX(Z,$){return M1(Z,$)===0}function uX(Z,$){return _7(Z,$)?Z:$}function dX(Z,$){return L7(Z,$)?Z:$}function mX(Z){return v1(y1(Z),c0(Z),y4(Z))}function lX(Z){return v1(y1(Z),c0(Z),y4(Z),23,59,59,999)}function iX(Z){return v1(y1(Z),c0(Z),1)}function pX(Z){let $=new Date(Z);return $.setUTCMonth($.getUTCMonth()+1,0),$.setUTCHours(23,59,59,999),$.toISOString()}function nX(Z){return v1(y1(Z),1,1)}function cX(Z){return v1(y1(Z),12,31,23,59,59,999)}var h1={isValid:BX,now:RX,from:v1,parse:W7,tryParse:MX,addMilliseconds:K0,addSeconds:AX,addMinutes:jX,addHours:FX,addDays:J7,addWeeks:wX,addMonths:PX,addYears:CX,diff:M1,diffSeconds:VX,diffMinutes:OX,diffHours:NX,diffDays:EX,year:y1,month:c0,day:y4,hour:SX,minute:TX,second:kX,millisecond:gX,dayOfWeek:bX,toLocal:o0,format:fX,formatDate:vX,formatTime:yX,toDate:hX,isBefore:_7,isAfter:L7,isEqual:xX,min:uX,max:dX,startOfDay:mX,endOfDay:lX,startOfMonth:iX,endOfMonth:pX,startOfYear:nX,endOfYear:cX};function h4(Z){if(typeof Z!=="string")return!1;if(!/^\d{4}-\d{2}-\d{2}$/.test(Z))return!1;let $=parseInt(Z.slice(0,4),10),X=parseInt(Z.slice(5,7),10),K=parseInt(Z.slice(8,10),10);if(X<1||X>12)return!1;if(K<1)return!1;let Q=[31,28,31,30,31,30,31,31,30,31,30,31],H=X===2&&($%4===0&&$%100!==0||$%400===0)?29:Q[X-1];return K<=H}function oX(){return h1.toDate(h1.now())}function sX(Z){let $=new Date;return new Intl.DateTimeFormat("en-CA",{timeZone:Z,year:"numeric",month:"2-digit",day:"2-digit"}).format($)}function K1(Z,$,X){let K=String(Z).padStart(4,"0"),Q=String($).padStart(2,"0"),H=String(X).padStart(2,"0"),Y=`${K}-${Q}-${H}`;if(!h4(Y))throw Error(`Invalid date: ${Z}-${$}-${X}`);return Y}function q7(Z){if(/^\d{4}-\d{2}-\d{2}$/.test(Z)){if(!h4(Z))throw Error(`Invalid date: ${Z}`);return Z}let $=new Date(Z);if(isNaN($.getTime()))throw Error(`Invalid date string: ${Z}`);let X=$.getUTCFullYear(),K=$.getUTCMonth()+1,Q=$.getUTCDate();return K1(X,K,Q)}function aX(Z){try{return q7(Z)}catch{return null}}function s0(Z,$){let X=D7(Z);return h1.toDate(h1.addDays(X,$))}function rX(Z,$){return s0(Z,$*7)}function tX(Z,$){let X=r(Z),K=A1(Z),Q=x4(Z),H=X*12+(K-1)+$,Y=Math.floor(H/12),z=H%12+1,W=Q0(Y,z),G=Math.min(Q,W);return K1(Y,z,G)}function eX(Z,$){let X=r(Z),K=A1(Z),Q=x4(Z),H=X+$,Y=Q0(H,K),z=Math.min(Q,Y);return K1(H,K,z)}function U7(Z,$){let K=new Date(Z+"T00:00:00Z").getTime(),Q=new Date($+"T00:00:00Z").getTime();return Math.round((K-Q)/86400000)}function Z$(Z,$){let X=r(Z),K=A1(Z),Q=r($),H=A1($);return(X-Q)*12+(K-H)}function X$(Z,$){return r(Z)-r($)}function r(Z){return parseInt(Z.slice(0,4),10)}function A1(Z){return parseInt(Z.slice(5,7),10)}function x4(Z){return parseInt(Z.slice(8,10),10)}function u4(Z){let $=new Date(Z+"T00:00:00Z").getUTCDay();return $===0?7:$}function $$(Z){let $=new Date(Z+"T00:00:00Z"),X=$.getUTCDay()||7;$.setUTCDate($.getUTCDate()+4-X);let K=new Date(Date.UTC($.getUTCFullYear(),0,1));return Math.ceil((($.getTime()-K.getTime())/86400000+1)/7)}function K$(Z){let $=K1(r(Z),1,1);return U7(Z,$)+1}function d4(Z){return Math.ceil(A1(Z)/3)}function m4(Z){return Z%4===0&&Z%100!==0||Z%400===0}function Q0(Z,$){let X=[31,28,31,30,31,30,31,31,30,31,30,31];if($===2&&m4(Z))return 29;return X[$-1]}function Q$(Z){return m4(Z)?366:365}function D7(Z){return Z+"T00:00:00.000Z"}function H$(Z){return Math.floor(new Date(Z+"T00:00:00Z").getTime()/1000)}function Y$(Z){let $=new Date(Z*1000);return K1($.getUTCFullYear(),$.getUTCMonth()+1,$.getUTCDate())}function l4(Z,$){let X=new Date(Z+"T00:00:00Z"),K={timeZone:"UTC",...$};return new Intl.DateTimeFormat(void 0,K).format(X)}function z$(Z){return l4(Z,{year:"numeric",month:"long",day:"numeric"})}function G$(Z){return l4(Z,{year:"numeric",month:"short",day:"numeric"})}function W$(Z,$){return Z<$}function J$(Z,$){return Z>$}function _$(Z,$){return Z===$}function L$(Z,$){return Z<$?Z:$}function q$(Z,$){return Z>$?Z:$}function U$(Z,$,X){return Z>=$&&Z<=X}function D$(Z){return K1(r(Z),A1(Z),1)}function I$(Z){let $=r(Z),X=A1(Z);return K1($,X,Q0($,X))}function B$(Z){let X=(d4(Z)-1)*3+1;return K1(r(Z),X,1)}function R$(Z){let X=d4(Z)*3;return K1(r(Z),X,Q0(r(Z),X))}function M$(Z){return K1(r(Z),1,1)}function A$(Z){return K1(r(Z),12,31)}function j$(Z){let $=u4(Z);return s0(Z,-($-1))}function F$(Z){let $=u4(Z);return s0(Z,7-$)}var w$={isValid:h4,today:oX,todayIn:sX,from:K1,parse:q7,tryParse:aX,addDays:s0,addWeeks:rX,addMonths:tX,addYears:eX,diff:U7,diffMonths:Z$,diffYears:X$,year:r,month:A1,day:x4,dayOfWeek:u4,weekOfYear:$$,dayOfYear:K$,quarter:d4,isLeapYear:m4,daysInMonth:Q0,daysInYear:Q$,toTimestamp:D7,toUnix:H$,fromUnix:Y$,format:l4,formatLong:z$,formatShort:G$,isBefore:W$,isAfter:J$,isEqual:_$,min:L$,max:q$,isBetween:U$,startOfMonth:D$,endOfMonth:I$,startOfQuarter:B$,endOfQuarter:R$,startOfYear:M$,endOfYear:A$,startOfWeek:j$,endOfWeek:F$};export{T5 as xmlParse,M4 as wrap,oZ as whileLoop,P5 as vectorSearch,$5 as varsLet,X5 as varsImport,K5 as varsExport,tZ as varSet,Z5 as varGet,R4 as validateArgs,f5 as uuid,Z4 as typeToString,k1 as typeOf,aZ as tryCatch,TK as transpileWithCache,a1 as transpileToJS,O5 as transpileCode,i0 as transpile,l1 as transformFunction,kK as tjsWithCache,SK as tjs,R8 as testUtils,q5 as template,z4 as stripTjsPreamble,Y4 as stripModuleSyntax,F5 as storeSet,w5 as storeQuery,x5 as storeProcedure,j5 as storeGet,_5 as split,TZ as setGlobalCache,$1 as seq,Q5 as scope,C1 as runtime,N5 as runCode,sZ as ret,F as resolveValue,O4 as resolveProcedureToken,u5 as releaseProcedure,Y6 as registerWasmBlock,U5 as regexMatch,z5 as reduce,b5 as random,W5 as push,f1 as procedureStore,W0 as preprocess,D5 as pick,a4 as parseReturnType,I1 as parseParameter,W1 as parse,I5 as omit,B5 as merge,k5 as memoize,H5 as map,O7 as lookupVariable,C5 as llmPredict,bZ as lint,J5 as len,R5 as keys,S5 as jsonStringify,E5 as jsonParse,L5 as join,W4 as isValidUrl,J4 as isValidTimestamp,_4 as isValidLegalDate,B1 as isRuntimeType,V4 as isProcedureToken,_1 as isError,zK as isAgentError,H6 as instantiateWasm,qZ as installRuntime,X1 as inferTypeFromValue,cZ as iff,NZ as hashSourceSync,y0 as hashSource,N4 as hash,bK as getToolDefinitions,T4 as getStoreCapabilityDefault,_Q as getStandardCapabilities,h as getLocation,c6 as getLLMCapability,h0 as getGlobalCache,IX as getBatteries,yZ as generateDocsMarkdown,C6 as generateDocs,VZ as fromTS,G5 as find,Y5 as filter,A5 as fetch,$4 as extractTests,u1 as extractTDoc,J1 as extractLiteralValue,$6 as expectFunction,u as evaluateExpr,rZ as errorAtom,z1 as error,UZ as emitRuntimeWrapper,E as defineAtom,R1 as createChildScope,Z1 as createChildContext,gK as createAgent,d0 as coreAtoms,eZ as constSet,y5 as consoleWarn,v5 as consoleLog,h5 as consoleError,v8 as compileWasmBlocks,D0 as compileToWasm,d5 as clearExpiredProcedures,V1 as checkType,g5 as cache,q1 as builtins,XQ as batteryAtoms,LQ as batteries,X6 as assertFunction,NK as ajs,V5 as agentRun,N0 as Union,s as TypedBuilder,V7 as TypeError,d as Type,y as TranspileError,L4 as TimestampType,h1 as Timestamp,C0 as TUuid,P0 as TUrl,B0 as TString,T0 as TRecord,j0 as TPositiveInt,S0 as TPair,R0 as TNumber,F0 as TNonEmptyString,a as TJS_VERSION,A0 as TInteger,w0 as TEmail,M0 as TBoolean,E0 as TArray,D1 as SyntaxError,OZ as Schema,t5 as SafeFunction,C4 as PROCEDURE_TOKEN_PREFIX,O0 as Optional,V0 as Nullable,F4 as MetadataCache,f4 as LocalModels,q4 as LegalDateType,w$ as LegalDate,T1 as Generic,r5 as Eval,k0 as Enum,hZ as DEFAULT_PROCEDURE_TTL,xZ as DEFAULT_MAX_AST_SIZE,S4 as AgentVM,e as AgentError,c5 as Agent,JK as A99};
|
|
318
353
|
|
|
319
|
-
//# debugId=
|
|
354
|
+
//# debugId=44B09E4D4ECF6A3F64756E2164756E21
|