tjs-lang 0.8.2 → 0.8.4
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/CLAUDE.md +5 -2
- package/demo/autocomplete.test.ts +37 -0
- package/demo/docs.json +701 -11
- package/demo/src/autocomplete.ts +40 -2
- package/demo/src/introspection-bridge.ts +140 -0
- package/demo/src/introspection-doc.test.ts +63 -0
- package/demo/src/playground-shared.ts +53 -0
- package/demo/src/tjs-playground.ts +21 -0
- package/dist/experiments/predicates/css.predicates.d.ts +13 -0
- package/dist/experiments/predicates/verify.d.ts +39 -0
- package/dist/index.js +101 -97
- package/dist/index.js.map +4 -4
- package/dist/src/lang/index.d.ts +2 -0
- package/dist/src/lang/predicate-schema.d.ts +39 -0
- package/dist/src/lang/predicate.d.ts +103 -0
- package/dist/src/lang/transpiler.d.ts +2 -0
- package/dist/src/vm/runtime.d.ts +22 -0
- package/dist/tjs-eval.js +29 -29
- package/dist/tjs-eval.js.map +3 -3
- package/dist/tjs-from-ts.js +1 -1
- package/dist/tjs-from-ts.js.map +2 -2
- package/dist/tjs-lang.js +86 -82
- package/dist/tjs-lang.js.map +4 -4
- package/dist/tjs-vm.js +45 -45
- package/dist/tjs-vm.js.map +3 -3
- package/editors/codemirror/ajs-language.ts +130 -44
- package/editors/codemirror/completion-source.test.ts +114 -0
- package/editors/introspect-value.test.ts +61 -0
- package/editors/introspect-value.ts +86 -0
- package/editors/scope-symbols.test.ts +113 -0
- package/editors/scope-symbols.ts +173 -0
- package/package.json +2 -1
- package/src/lang/index.ts +22 -0
- package/src/lang/predicate-schema.test.ts +97 -0
- package/src/lang/predicate-schema.ts +168 -0
- package/src/lang/predicate.test.ts +184 -0
- package/src/lang/predicate.ts +550 -0
- package/src/lang/runtime.test.ts +46 -0
- package/src/lang/suggest.test.ts +84 -0
- package/src/lang/transpiler.ts +26 -0
- package/src/runtime.test.ts +6 -6
- package/src/vm/atom-effects.test.ts +72 -0
- package/src/vm/atoms/batteries.ts +12 -0
- package/src/vm/equality.test.ts +59 -0
- package/src/vm/runtime.ts +77 -59
package/dist/tjs-eval.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import{s as f,validate as Ee,filter as Fe}from"tosijs-schema";var ce=Symbol.for("tjs.equals");function fe(e,n){if(e!==null&&typeof e=="object"&&typeof e[ce]=="function")return e[ce](n);if(n!==null&&typeof n=="object"&&typeof n[ce]=="function")return n[ce](e);if(e!==null&&typeof e=="object"&&typeof e.Equals=="function")return e.Equals(n);if(n!==null&&typeof n=="object"&&typeof n.Equals=="function")return n.Equals(e);if(e===n||e==null&&n==null)return!0;if(e==null||n===null||n===void 0||typeof e!=typeof n||typeof e!="object")return!1;if(Array.isArray(e)&&Array.isArray(n))return e.length!==n.length?!1:e.every((s,o)=>fe(s,n[o]));if(Array.isArray(e)!==Array.isArray(n))return!1;let t=Object.keys(e),r=Object.keys(n);return t.length!==r.length?!1:t.every(s=>fe(e[s],n[s]))}var O=class{$error=!0;message;op;cause;constructor(n,t,r){this.message=n,this.op=t,this.cause=r}toString(){return`AgentError[${this.op}]: ${this.message}`}toJSON(){return{$error:!0,message:this.message,op:this.op}}};function _t(e){return e instanceof O||e&&e.$error===!0}var Q=new Map,Ot=3600*1e3,Dt=100*1024,Te="proc_";function xe(e){return typeof e=="string"&&e.startsWith(Te)}function je(e){let n=Q.get(e);if(!n)throw new Error(`Procedure not found: ${e}`);if(Date.now()>n.expiresAt)throw Q.delete(e),new Error(`Procedure expired: ${e}`);return n.ast}function Ft(){return typeof crypto<"u"&&crypto.randomUUID?Te+crypto.randomUUID():Te+Math.random().toString(36).slice(2)+Date.now().toString(36)}var Ue=new Set(["__proto__","constructor","prototype"]);function Ne(e){if(Ue.has(e))throw new Error(`Security Error: Access to '${e}' is forbidden`)}var Ut=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","metadata.google.internal"]);function qt(e){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return!0;let t=n.hostname.toLowerCase();return!!(Ut.has(t)||t.endsWith(".internal")||t.endsWith(".local")||t==="169.254.169.254"||/^10\./.test(t)||/^192\.168\./.test(t)||/^172\.(1[6-9]|2\d|3[01])\./.test(t))}catch{return!0}}function Lt(e){return!!(/\([^)]*[+*][^)]*\)[+*]/.test(e)||/\(([^|)]+)\|\1\)[+*]/.test(e)||/\(\.\*\)\+/.test(e)||/\(\.\+\)\+/.test(e)||/\(\[.*\]\+\)\+/.test(e))}function G(e){return{...e,state:Object.create(e.state)}}function Wt(e,n){let t={},r=new Set([...Object.keys(e),...Object.keys(n)]);for(let s of r){let o=e[s],i=n[s];i!==o&&(t[s]=i)}return t}function x(e,n){if(e&&typeof e=="object"&&e.$kind==="arg")return n.args[e.path];if(e&&typeof e=="object"&&e.$expr)return B(e,n);if(typeof e=="string"){if(e.startsWith("args.")&&!("args"in n.state))return n.args[e.replace("args.","")];if(e.includes(".")){let t=e.split(".");for(let s of t)if(Ue.has(s))throw new Error(`Security Error: Access to '${s}' is forbidden`);let r=n.state[t[0]];if(r!==void 0){for(let s=1;s<t.length;s++)r=r?.[t[s]];return r}}return e in n.state?n.state[e]:e}if(e&&typeof e=="object"&&!Array.isArray(e)&&e.constructor===Object){let t={};for(let r of Object.keys(e))t[r]=x(e[r],n);return t}return Array.isArray(e)?e.map(t=>x(t,n)):e}function H(e,n,t){return new Proxy(n,{get(r,s){if(s in r)return r[s];let o=t?.[s];throw o?new Error(`${e}.${s} is not available. ${o}`):new Error(`${e}.${s} is not supported in AsyncJS. Check docs for available ${e} methods.`)}})}function X(e){if(e===null)return{type:"null"};if(e===void 0)return{};if(typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string")return e;if(typeof e=="object"&&e!==null&&"schema"in e&&typeof e.schema=="object")return e.schema;let n=typeof e;if(n==="string")return{type:"string"};if(n==="number")return Number.isInteger(e)?{type:"integer"}:{type:"number"};if(n==="boolean")return{type:"boolean"};if(Array.isArray(e))return e.length===0?{type:"array"}:{type:"array",items:X(e[0])};if(n==="object"){let t={},r=[];for(let[s,o]of Object.entries(e))t[s]=X(o),r.push(s);return{type:"object",properties:t,required:r}}return{}}var z={Math:H("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 e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]/4294967296}return Math.random()}}),JSON:H("JSON",{parse:e=>JSON.parse(e),stringify:(e,n,t)=>JSON.stringify(e,n,t)}),console:H("console",{log:(...e)=>{},warn:(...e)=>{},error:(...e)=>{},info:(...e)=>{}},{table:"Use console.log with JSON.stringify for structured data.",dir:"Use console.log instead.",trace:"Stack traces are not available in AsyncJS."}),Array:H("Array",{isArray:e=>Array.isArray(e),from:(e,n,t)=>Array.from(e,n,t),of:(...e)=>Array.of(...e)},{prototype:"Prototype access is not allowed."}),Object:H("Object",{keys:e=>Object.keys(e),values:e=>Object.values(e),entries:e=>Object.entries(e),fromEntries:e=>Object.fromEntries(e),assign:(e,...n)=>Object.assign({},e,...n),hasOwn:(e,n)=>Object.hasOwn(e,n)},{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:H("String",{fromCharCode:(...e)=>String.fromCharCode(...e),fromCodePoint:(...e)=>String.fromCodePoint(...e)}),Number:H("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:(e,n)=>{let t=X(n),r=Fe(e,t);if(r instanceof Error)throw r;return r},Schema:{...f,response:(e,n)=>{let t=n?.schema!=null?n.schema:X(n);return{type:"json_schema",json_schema:{name:e,strict:!0,schema:t}}},fromExample:e=>X(e),isValid:(e,n)=>n?.schema!=null?Ee(e,n):Ee(e,X(n))},Set:(e=[])=>{let n=[...new globalThis.Set(e)];return{add(t){return n.includes(t)||n.push(t),this},remove(t){let r=n.indexOf(t);return r!==-1&&n.splice(r,1),this},clear(){return n.length=0,this},has(t){return n.includes(t)},get size(){return n.length},toArray(){return[...n]},union(t){let r=t?.toArray?.()??t??[];return z.Set([...n,...r])},intersection(t){let r=t?.toArray?.()??t??[];return z.Set(n.filter(s=>r.includes(s)))},diff(t){let r=t?.toArray?.()??t??[];return z.Set(n.filter(s=>!r.includes(s)))},forEach(t){n.forEach(t)},map(t){return z.Set(n.map(t))},filter(t){return z.Set(n.filter(t))},toJSON(){return[...n]}}},Date:(()=>{let e=t=>({get value(){return t.toISOString()},get timestamp(){return t.getTime()},get year(){return t.getFullYear()},get month(){return t.getMonth()+1},get day(){return t.getDate()},get hours(){return t.getHours()},get minutes(){return t.getMinutes()},get seconds(){return t.getSeconds()},get dayOfWeek(){return t.getDay()},add({years:r=0,months:s=0,days:o=0,hours:i=0,minutes:a=0,seconds:l=0,ms:c=0}={}){let p=new globalThis.Date(t.getTime());return r&&p.setFullYear(p.getFullYear()+r),s&&p.setMonth(p.getMonth()+s),o&&p.setDate(p.getDate()+o),i&&p.setHours(p.getHours()+i),a&&p.setMinutes(p.getMinutes()+a),l&&p.setSeconds(p.getSeconds()+l),c&&p.setMilliseconds(p.getMilliseconds()+c),e(p)},diff(r,s="ms"){let o=typeof r=="object"&&r.timestamp?r.timestamp:new globalThis.Date(r).getTime(),i=t.getTime()-o;switch(s){case"seconds":return i/1e3;case"minutes":return i/6e4;case"hours":return i/36e5;case"days":return i/864e5;default:return i}},format(r="ISO"){return r==="ISO"?t.toISOString():r==="date"?t.toISOString().split("T")[0]:r==="time"?t.toISOString().split("T")[1].split(".")[0]:r.replace("YYYY",String(t.getFullYear())).replace("MM",String(t.getMonth()+1).padStart(2,"0")).replace("DD",String(t.getDate()).padStart(2,"0")).replace("HH",String(t.getHours()).padStart(2,"0")).replace("mm",String(t.getMinutes()).padStart(2,"0")).replace("ss",String(t.getSeconds()).padStart(2,"0"))},isBefore(r){let s=typeof r=="object"&&r.timestamp?r.timestamp:new globalThis.Date(r).getTime();return t.getTime()<s},isAfter(r){let s=typeof r=="object"&&r.timestamp?r.timestamp:new globalThis.Date(r).getTime();return t.getTime()>s},toString(){return t.toISOString()},toJSON(){return t.toISOString()}}),n=t=>{let r=t!==void 0?new globalThis.Date(t):new globalThis.Date;if(isNaN(r.getTime()))throw new Error(`Invalid date: ${t}`);return e(r)};return n.now=()=>globalThis.Date.now(),n.parse=t=>e(new globalThis.Date(t)),n})()},ue={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."},Vt=.01,Pe=1e-4,Ie=.001,zt=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 B(e,n){if(e==null||typeof e!="object"||!("$expr"in e))return e;if(n.fuel&&(n.fuel.current-=Vt,n.fuel.current<=0))throw new Error("Out of Fuel");switch(e.$expr){case"literal":return e.value;case"ident":{if(e.name in n.state)return n.state[e.name];if(e.name in n.args)return n.args[e.name];if(e.name in z)return z[e.name];if(e.name in ue)throw new Error(ue[e.name]);return}case"member":{let t=B(e.object,n);if(e.optional&&t==null)return;let r=typeof e.property=="object"&&e.property!==null?B(e.property,n):e.property;return Ne(String(r)),t?.[r]}case"binary":{let t=B(e.left,n),r=B(e.right,n);switch(e.op){case"+":{let s=t+r;if(typeof s=="string"&&n.fuel&&(n.fuel.current-=s.length*Pe,n.fuel.current<=0)){n.error=new O("Out of Fuel","expr.concat");return}return s}case"-":return t-r;case"*":return t*r;case"/":return t/r;case"%":return t%r;case"**":return t**r;case">":return t>r;case"<":return t<r;case">=":return t>=r;case"<=":return t<=r;case"==":return fe(t,r);case"!=":return!fe(t,r);case"===":return t===r;case"!==":return t!==r;default:throw new Error(`Unknown binary operator: ${e.op}`)}}case"unary":{let t=B(e.argument,n);switch(e.op){case"!":return!t;case"-":return-t;case"+":return+t;case"typeof":return typeof t;default:throw new Error(`Unknown unary operator: ${e.op}`)}}case"logical":{let t=B(e.left,n);return e.op==="&&"?t&&B(e.right,n):e.op==="??"?t??B(e.right,n):t||B(e.right,n)}case"conditional":{let t=B(e.test,n);return B(t?e.consequent:e.alternate,n)}case"array":return e.elements.map(t=>B(t,n));case"object":{let t={};for(let r of e.properties)t[r.key]=B(r.value,n);return t}case"call":{if(e.callee==="Error"){let r=e.arguments.map(o=>B(o,n)),s=typeof r[0]=="string"?r[0]:"Error";n.error=new O(s,"Error");return}if(e.callee in z){let r=z[e.callee];if(typeof r=="function"){let s=e.arguments.map(o=>B(o,n));return r(...s)}}throw n.resolver(e.callee)?new Error(`Atom calls in expressions not yet supported: ${e.callee}`):e.callee in ue?new Error(ue[e.callee]):new Error(`Unknown function: ${e.callee}`)}case"methodCall":{let t=B(e.object,n);if(e.optional&&t==null)return;let r=e.method;if(Ne(r),t==null)throw new Error(`Cannot call method '${r}' on ${t}`);let s=t[r];if(typeof s!="function")throw new Error(`'${r}' is not a function`);let o=e.arguments.map(a=>B(a,n)),i=s.apply(t,o);if(n.fuel&&zt.has(r)){let a=0;if(typeof i=="string"?a=i.length*Pe:Array.isArray(i)?a=i.length*Ie:typeof i=="object"&&i!==null&&(a=Object.keys(i).length*Ie),n.fuel.current-=a,n.fuel.current<=0){n.error=new O("Out of Fuel",`expr.${r}`);return}}return i}default:throw new Error(`Unknown expression type: ${e.$expr}`)}}function M(e,n,t,r,s={}){let{docs:o="",timeoutMs:i=1e3,cost:a=1}=typeof s=="string"?{docs:s}:s;return{op:e,inputSchema:n,outputSchema:t,exec:async(c,p)=>{let{op:m,result:u,...d}=c;if(p.error)return;let g=p.trace?{...p.state}:null,h=p.fuel.current,w,E;try{let S=p.costOverrides?.[e],y=S!==void 0?S:a,T=typeof y=="function"?y(d,p):y;if((p.fuel.current-=T)<=0){p.error=new O("Out of Fuel",e);return}let $=p.timeoutOverrides?.[e],b=$!==void 0?$:i,j=typeof b=="function"?b(d,p):b,v,A=async()=>r(c,p);if(w=j>0?await Promise.race([A(),new Promise((k,C)=>{v=setTimeout(()=>C(new Error(`Atom '${e}' timed out`)),j)})]).finally(()=>clearTimeout(v)):await A(),c.result){if(p.consts.has(c.result))throw new Error(`Cannot reassign const variable '${c.result}'`);if(w!==void 0&&t&&!Ee(w,t)){p.error=new O(`Output validation failed for '${e}'`,e);return}p.state[c.result]=w,c.resultConst&&p.consts.add(c.result)}}catch(S){E=S.message||String(S),p.error=new O(E,e,S)}finally{if(p.trace&&g){let S=Wt(g,p.state);p.trace.push({op:e,input:d,stateDiff:S,result:w,error:E,fuelBefore:h,fuelAfter:p.fuel.current,timestamp:new Date().toISOString()})}}},docs:o,timeoutMs:i,cost:a,create:c=>({op:e,...c})}}var F=M("seq",f.object({steps:f.array(f.any)}),void 0,async({steps:e},n)=>{for(let t of e){if(n.output!==void 0||n.error)return;let r=n.resolver(t.op);if(!r)throw new Error(`Unknown Atom: ${t.op}`);await r.exec(t,n)}},{docs:"Sequence",timeoutMs:0,cost:.1}),Jt=M("if",f.object({condition:f.any,then:f.array(f.any),else:f.array(f.any).optional}),void 0,async(e,n)=>{B(e.condition,n)?await F.exec({op:"seq",steps:e.then},n):e.else&&await F.exec({op:"seq",steps:e.else},n)},{docs:"If/Else",timeoutMs:0,cost:.1}),Zt=M("while",f.object({condition:f.any,body:f.array(f.any)}),void 0,async(e,n)=>{for(;B(e.condition,n);){if(n.signal?.aborted)throw new Error("Execution aborted");if((n.fuel.current-=.1)<=0)throw new Error("Out of Fuel");if(await F.exec({op:"seq",steps:e.body},n),n.output!==void 0||n.error)return}},{docs:"While Loop",timeoutMs:0,cost:.1}),Gt=M("return",void 0,f.any,async(e,n)=>{if(n.error)return n.output=n.error,n.error;if("value"in e){let r=x(e.value,n);if(!n.localCall&&r!==void 0&&r!==null&&!_t(r)&&(typeof r!="object"||Array.isArray(r))){let s=new O(`Agent must return an object, got ${Array.isArray(r)?"array":typeof r}`,"return");return n.error=s,n.output=s,s}return n.output=r,r}let t={};if(e.schema?.properties){for(let r of Object.keys(e.schema.properties))t[r]=n.state[r];if(e.filter!==!1){let r=Fe(t,e.schema);r instanceof Error||(t=r)}}return n.output=t,t},{docs:"Return",cost:.1}),Ht=M("try",f.object({try:f.array(f.any),catch:f.array(f.any).optional,catchParam:f.string.optional}),void 0,async(e,n)=>{if(await F.exec({op:"seq",steps:e.try},n),n.error&&e.catch){let t=e.catchParam||"error";n.state[t]=n.error.message,n.state.errorOp=n.error.op,n.error=void 0,await F.exec({op:"seq",steps:e.catch},n)}},{docs:"Try/Catch",timeoutMs:0,cost:.1}),Kt=M("Error",f.object({args:f.array(f.any).optional}),void 0,async(e,n)=>{let t=e.args?.[0]??"Error";n.error=new O(String(t),"Error")},{docs:"Trigger error flow",cost:.1}),Yt=M("varSet",f.object({key:f.string,value:f.any}),void 0,async({key:e,value:n},t)=>{if(t.consts.has(e))throw new Error(`Cannot reassign const variable '${e}'`);t.state[e]=x(n,t)},{docs:"Set Variable",cost:.1}),Xt=M("constSet",f.object({key:f.string,value:f.any}),void 0,async({key:e,value:n},t)=>{if(t.consts.has(e))throw new Error(`Cannot reassign const variable '${e}'`);if(e in t.state)throw new Error(`Cannot redeclare variable '${e}' as const`);t.state[e]=x(n,t),t.consts.add(e)},{docs:"Set Const Variable (immutable)",cost:.1}),Qt=M("varGet",f.object({key:f.string}),f.any,async({key:e},n)=>x(e,n),{docs:"Get Variable",cost:.1}),en=M("varsImport",f.object({keys:f.union([f.array(f.string),f.record(f.string)])}),void 0,async({keys:e},n)=>{if(Array.isArray(e))for(let t of e)n.state[t]=x({$kind:"arg",path:t},n);else for(let[t,r]of Object.entries(e))n.state[t]=x({$kind:"arg",path:r},n)},{docs:"Import variables from args into the current scope, with optional renaming.",cost:.2}),tn=M("varsLet",f.record(f.any),void 0,async(e,n)=>{for(let t of Object.keys(e))t==="op"||t==="result"||(n.state[t]=x(e[t],n))},{docs:"Initialize a set of variables in the current scope from the step object properties.",cost:.1}),nn=M("varsExport",f.object({keys:f.union([f.array(f.string),f.record(f.string)])}),f.record(f.any),async({keys:e},n)=>{let t={};if(Array.isArray(e))for(let r of e)t[r]=x(r,n);else for(let[r,s]of Object.entries(e))t[r]=x(s,n);return t},{docs:"Export variables from the current scope, with optional renaming.",cost:.2}),rn=M("scope",f.object({steps:f.array(f.any)}),void 0,async({steps:e},n)=>{let t=G(n);await F.exec({op:"seq",steps:e},t),t.output!==void 0&&(n.output=t.output)},{docs:"Create new scope",timeoutMs:0,cost:.1}),Be=256,sn=M("callLocal",f.object({name:f.string,args:f.array(f.any)}),void 0,async({name:e,args:n},t)=>{let r=t.helpers?.[e];if(!r)return t.error=new O(`Unknown helper: ${e}`,"callLocal"),t.error;let s=(t.callDepth??0)+1;if(s>Be)return t.error=new O(`Maximum helper call depth (${Be}) exceeded \u2014 likely infinite recursion in '${e}'`,"callLocal"),t.error;let o=n.map(a=>x(a,t)),i={...t,state:{},consts:new Set,output:void 0,error:void 0,localCall:!0,callDepth:s};for(let a=0;a<r.paramNames.length;a++)i.state[r.paramNames[a]]=o[a];return await F.exec({op:"seq",steps:r.steps},i),i.error&&(t.error=i.error),i.output},{docs:"Invoke a local helper function by name",timeoutMs:0,cost:.1}),on=M("map",f.object({items:f.array(f.any),as:f.string,steps:f.array(f.any)}),f.array(f.any),async({items:e,as:n,steps:t},r)=>{let s=[],o=x(e,r);if(!Array.isArray(o))throw new Error("map: items is not an array");for(let i of o){if(r.signal?.aborted)throw new Error("Execution aborted");let a=G(r);a.state[n]=i,await F.exec({op:"seq",steps:t},a),s.push(a.state.result??null)}return s},{docs:"Map Array",timeoutMs:0,cost:1}),an=M("filter",f.object({items:f.array(f.any),as:f.string,condition:f.any}),f.array(f.any),async({items:e,as:n,condition:t},r)=>{let s=[],o=x(e,r);if(!Array.isArray(o))throw new Error("filter: items is not an array");for(let i of o){if(r.signal?.aborted)throw new Error("Execution aborted");let a=G(r);a.state[n]=i,B(t,a)&&s.push(i)}return s},{docs:"Filter Array",timeoutMs:0,cost:1}),ln=M("reduce",f.object({items:f.array(f.any),as:f.string,accumulator:f.string,initial:f.any,steps:f.array(f.any)}),f.any,async({items:e,as:n,accumulator:t,initial:r,steps:s},o)=>{let i=x(e,o),a=x(r,o);if(!Array.isArray(i))throw new Error("reduce: items is not an array");let l=a;for(let c of i){if(o.signal?.aborted)throw new Error("Execution aborted");let p=G(o);p.state[n]=c,p.state[t]=l,await F.exec({op:"seq",steps:s},p),l=p.state.result??l}return l},{docs:"Reduce Array",timeoutMs:0,cost:1}),cn=M("find",f.object({items:f.array(f.any),as:f.string,condition:f.any}),f.any,async({items:e,as:n,condition:t},r)=>{let s=x(e,r);if(!Array.isArray(s))throw new Error("find: items is not an array");for(let o of s){if(r.signal?.aborted)throw new Error("Execution aborted");let i=G(r);if(i.state[n]=o,B(t,i))return o}return null},{docs:"Find in Array",timeoutMs:0,cost:1}),un=M("push",f.object({list:f.array(f.any),item:f.any}),f.array(f.any),async({list:e,item:n},t)=>{let r=x(e,t),s=x(n,t);return Array.isArray(r)&&r.push(s),r},{docs:"Push to Array",cost:1}),fn=M("len",f.object({list:f.any}),f.number,async({list:e},n)=>{let t=x(e,n);return Array.isArray(t)||typeof t=="string"?t.length:0},{docs:"Length",cost:1}),pn=M("split",f.object({str:f.string,sep:f.string}),f.array(f.string),async({str:e,sep:n},t)=>x(e,t).split(x(n,t)),{docs:"Split String",cost:1}),mn=M("join",f.object({list:f.array(f.string),sep:f.string}),f.string,async({list:e,sep:n},t)=>x(e,t).join(x(n,t)),{docs:"Join String",cost:1}),dn=M("template",f.object({tmpl:f.string,vars:f.record(f.any)}),f.string,async({tmpl:e,vars:n},t)=>x(e,t).replace(/\{\{(\w+)\}\}/g,(s,o)=>String(x(n[o],t)??"")),{docs:"String Template",cost:1}),gn=M("regexMatch",f.object({pattern:f.string,value:f.any}),f.boolean,async({pattern:e,value:n},t)=>{if(Lt(e))throw new Error(`Suspicious regex pattern rejected (potential ReDoS): ${e}`);let r=x(n,t);return new RegExp(e).test(r)},{docs:"Returns true if the value matches the regex pattern.",cost:2}),yn=M("pick",f.object({obj:f.record(f.any),keys:f.array(f.string)}),f.record(f.any),async({obj:e,keys:n},t)=>{let r=x(e,t),s=x(n,t),o={};return r&&Array.isArray(s)&&s.forEach(i=>o[i]=r[i]),o},{docs:"Pick Keys",cost:1}),hn=M("omit",f.object({obj:f.record(f.any),keys:f.array(f.string)}),f.record(f.any),async({obj:e,keys:n},t)=>{let r=x(e,t),s=new Set(x(n,t)),o={};return r&&Object.keys(r).forEach(i=>{s.has(i)||(o[i]=r[i])}),o},{docs:"Omit Keys",cost:1}),bn=M("merge",f.object({a:f.record(f.any),b:f.record(f.any)}),f.record(f.any),async({a:e,b:n},t)=>({...x(e,t),...x(n,t)}),{docs:"Merge Objects",cost:1}),wn=M("keys",f.object({obj:f.record(f.any)}),f.array(f.string),async({obj:e},n)=>Object.keys(x(e,n)??{}),{docs:"Object Keys",cost:1}),_e=10,Oe="X-Agent-Depth";function Sn(e,n){try{let r=new URL(e).hostname.toLowerCase();for(let s of n){let o=s.toLowerCase();if(o.startsWith("*.")){let i=o.slice(1);if(r.endsWith(i)||r===o.slice(2))return!0}else if(r===o)return!0}return!1}catch{return!1}}var $n=M("httpFetch",f.object({url:f.string,method:f.string.optional,headers:f.record(f.string).optional,body:f.any.optional,responseType:f.string.optional}),f.any,async(e,n)=>{let t=x(e.url,n),r=x(e.method,n),s=x(e.headers,n)||{},o=x(e.body,n),i=x(e.responseType,n),a=n.context?.requestDepth??0;if(a>=_e)throw new Error(`Agent request depth exceeded (max ${_e}). This prevents recursive agent loops.`);if(n.capabilities.fetch)return n.capabilities.fetch(t,{method:r,headers:{...s,[Oe]:String(a+1)},body:o,signal:n.signal,responseType:i});let l=n.context?.allowedFetchDomains;if(l){if(!Sn(t,l))throw new Error(`Fetch blocked: domain not in allowlist. Allowed: ${l.join(", ")}`)}else{if(qt(t))throw new Error("Blocked URL: private/internal addresses not allowed in default fetch");try{let p=new URL(t).hostname.toLowerCase();if(p!=="localhost"&&p!=="127.0.0.1"&&p!=="[::1]")throw new Error("Fetch blocked: no allowedFetchDomains configured. Set ctx.context.allowedFetchDomains or provide a custom fetch capability.")}catch(c){throw c.message.includes("allowedFetchDomains")?c:new Error(`Invalid URL: ${t}`,{cause:c})}}if(typeof globalThis.fetch=="function"){let c=await globalThis.fetch(t,{method:r,headers:{...s,[Oe]:String(a+1)},body:o?JSON.stringify(o):void 0,signal:n.signal});if(i==="dataUrl"){let m=await c.arrayBuffer(),u=new Uint8Array(m),d="";for(let w=0;w<u.length;w++)d+=String.fromCharCode(u[w]);let g=btoa(d);return`data:${c.headers.get("content-type")||"application/octet-stream"};base64,${g}`}let p=c.headers.get("content-type");return i==="json"||p&&p.includes("application/json")?c.json():c.text()}throw new Error("Capability 'fetch' missing and no global fetch available")},{docs:"HTTP Fetch",timeoutMs:3e4,cost:5}),En=M("storeGet",f.object({key:f.string}),f.any,async({key:e},n)=>{let t=x(e,n);return n.capabilities.store?.get(t)},{docs:"Store Get",cost:5}),Tn=M("storeSet",f.object({key:f.string,value:f.any}),void 0,async({key:e,value:n},t)=>{let r=x(e,t),s=x(n,t);return t.capabilities.store?.set(r,s)},{docs:"Store Set",cost:5}),xn=M("storeQuery",f.object({query:f.any}),f.array(f.any),async({query:e},n)=>n.capabilities.store?.query?.(x(e,n))??[],{docs:"Store Query",cost:5}),jn=M("storeVectorSearch",f.object({collection:f.string.optional,vector:f.array(f.number),k:f.number.optional}),f.array(f.any),async({collection:e,vector:n,k:t},r)=>r.capabilities.store?.vectorSearch?.(x(e,r),x(n,r),x(t,r))??[],{docs:"Vector Search",cost:(e,n)=>5+(x(e.k,n)??5)}),An=M("llmPredict",f.object({prompt:f.string,options:f.any.optional}),f.string,async({prompt:e,options:n},t)=>{if(!t.capabilities.llm?.predict)throw new Error("Capability 'llm.predict' missing");return t.capabilities.llm.predict(x(e,t),x(n,t))},{docs:"LLM Predict",timeoutMs:12e4,cost:100}),vn=M("agentRun",f.object({agentId:f.any,input:f.any}),f.any,async({agentId:e,input:n},t)=>{let r=x(e,t),s=x(n,t),o=s;if(s&&typeof s=="object"&&!Array.isArray(s)){o={};for(let a in s)o[a]=x(s[a],t)}if(xe(r)){let a=je(r),l={...t,args:o,state:{},consts:new Set,output:void 0,error:void 0},c=t.resolver("seq");if(!c)throw new Error("seq atom not found");if(await c.exec(a,l),l.error)throw new Error(l.error.message||"Sub-agent failed");return l.output}if(r&&typeof r=="object"&&"op"in r){let a={...t,args:o,state:{},consts:new Set,output:void 0,error:void 0},l=t.resolver("seq");if(!l)throw new Error("seq atom not found");if(await l.exec(r,a),a.error)throw new Error(a.error.message||"Sub-agent failed");return a.output}if(!t.capabilities.agent?.run)throw new Error("Capability 'agent.run' missing");let i=await t.capabilities.agent.run(r,o);if(i&&typeof i=="object"&&"fuelUsed"in i&&typeof i.fuelUsed=="number"){if(i.error)throw new Error(i.error.message||"Sub-agent failed");return i.result}return i},{docs:"Run Sub-Agent (accepts procedure token, AST, or agent ID)",cost:1}),Mn=M("transpileCode",f.object({code:f.string}),f.any,async({code:e},n)=>{if(!n.capabilities.code?.transpile)throw new Error("Capability 'code.transpile' missing. Enable code transpilation by providing the code capability.");let t=x(e,n);try{return n.capabilities.code.transpile(t)}catch(r){throw new Error(`Code transpilation failed: ${r.message}`,{cause:r})}},{docs:"Transpile AsyncJS code to AST",cost:1}),De=10,kn=M("runCode",f.object({code:f.string,args:f.record(f.any).optional}),f.any,async({code:e,args:n},t)=>{let r=t.runCodeDepth??0;if(r>=De)throw new Error(`runCode recursion limit exceeded (max ${De}). This prevents infinite loops from dynamically generated code calling runCode.`);if(!t.capabilities.code?.transpile)throw new Error("Capability 'code.transpile' missing. Enable dynamic code execution by providing the code capability.");let s=x(e,t),o=n?x(n,t):{},i;try{i=t.capabilities.code.transpile(s)}catch(l){throw new Error(`Code transpilation failed: ${l.message}`,{cause:l})}if(i.op!=="seq")throw new Error("Transpiled code must be a seq node");let a=G(t);if(a.args=o,a.output=void 0,a.runCodeDepth=r+1,await F.exec(i,a),a.error){t.error=a.error;return}return a.output},{docs:"Run dynamically generated AsyncJS code",cost:1}),Cn=M("jsonParse",f.object({str:f.string}),f.any,async({str:e},n)=>JSON.parse(x(e,n)),{docs:"Parse JSON",cost:1}),Rn=M("jsonStringify",f.object({value:f.any}),f.string,async({value:e},n)=>JSON.stringify(x(e,n)),{docs:"Stringify JSON",cost:1}),Nn=M("xmlParse",f.object({str:f.string}),f.any,async({str:e},n)=>{if(!n.capabilities.xml?.parse)throw new Error("Capability 'xml.parse' missing");return n.capabilities.xml.parse(x(e,n))},{docs:"Parse XML",cost:1}),Pn=M("memoize",f.object({key:f.string.optional,steps:f.array(f.any)}),f.any,async({key:e,steps:n},t)=>{t.memo||(t.memo=new Map);let r=x(e,t)??await Ae.exec({value:n,algorithm:"SHA-256"},t);if(t.memo.has(r))return t.memo.get(r);let s=G(t);await F.exec({op:"seq",steps:n},s);let o=s.output??s.state.result;return t.memo.set(r,o),o},{docs:"Memoize steps result in memory",cost:1}),In=M("cache",f.object({key:f.string.optional,steps:f.array(f.any),ttlMs:f.number.optional}),f.any,async({key:e,steps:n,ttlMs:t},r)=>{if(!r.capabilities.store)throw new Error("Capability 'store' missing for caching");let o=`cache:${x(e,r)??await Ae.exec({value:n,algorithm:"SHA-256"},r)}`,i=await r.capabilities.store.get(o);if(i)if(typeof i=="object"&&i._exp){if(Date.now()<i._exp)return i.val}else return i;let a=G(r);await F.exec({op:"seq",steps:n},a);let l=a.output??a.state.result,c=Date.now()+(t??24*3600*1e3);if((r.fuel.current-=5)<=0)throw new Error("Out of Fuel");return await r.capabilities.store.set(o,{val:l,_exp:c}),l},{docs:"Cache steps result in store with TTL",cost:5}),Bn=M("random",f.object({min:f.number.optional,max:f.number.optional,format:f.string.optional,length:f.number.optional}),f.any,async({min:e,max:n,format:t,length:r},s)=>{let o=x(t,s)??"float",i=x(r,s)??10,a=x(e,s)??0,l=x(n,s)??1;if(o==="base36"){let u="0123456789abcdefghijklmnopqrstuvwxyz",d="";if(typeof crypto<"u"&&crypto.getRandomValues){let g=new Uint8Array(i);crypto.getRandomValues(g);for(let h=0;h<i;h++)d+=u[g[h]%36]}else for(let g=0;g<i;g++)d+=u.charAt(Math.floor(Math.random()*36));return d}let c;if(typeof crypto<"u"&&crypto.getRandomValues){let u=new Uint32Array(1);crypto.getRandomValues(u),c=u[0]/4294967296}else c=Math.random();let p=l-a,m=c*p+a;return o==="integer"?Math.floor(m):m},{docs:"Generate Random",cost:1}),_n=M("uuid",void 0,f.string,async()=>{if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=Array.from(e,t=>t.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let n=Math.random()*16|0;return(e==="x"?n:n&3|8).toString(16)})},{docs:"Generate UUID",cost:1}),Ae=M("hash",f.object({value:f.any,algorithm:f.string.optional}),f.string,async({value:e,algorithm:n},t)=>{let r=typeof e=="string"?e:JSON.stringify(x(e,t)),s=x(n,t)||"SHA-256";if(typeof crypto<"u"&&crypto.subtle){let a=new TextEncoder().encode(r),l=await crypto.subtle.digest(s,a);return Array.from(new Uint8Array(l)).map(p=>p.toString(16).padStart(2,"0")).join("")}let o=0;for(let i=0;i<r.length;i++){let a=r.charCodeAt(i);o=(o<<5)-o+a,o|=0}return String(o)},{docs:"Hash a value",cost:1}),On=M("consoleLog",f.object({message:f.any}),void 0,async({message:e},n)=>{let t=x(e,n);n.trace&&n.trace.push({op:"console.log",input:{message:t},stateDiff:{},result:t,fuelBefore:n.fuel.current,fuelAfter:n.fuel.current,timestamp:new Date().toISOString()})},{docs:"Log to trace",cost:.1}),Dn=M("consoleWarn",f.object({message:f.any}),void 0,async({message:e},n)=>{let t=x(e,n),r=typeof t=="string"?t:JSON.stringify(t);n.warnings||(n.warnings=[]),n.warnings.push(r),n.trace&&n.trace.push({op:"console.warn",input:{message:t},stateDiff:{},result:t,fuelBefore:n.fuel.current,fuelAfter:n.fuel.current,timestamp:new Date().toISOString()})},{docs:"Add warning",cost:.1}),Fn=M("consoleError",f.object({message:f.any}),void 0,async({message:e},n)=>{let t=x(e,n),r=typeof t=="string"?t:JSON.stringify(t);n.error=new O(r,"console.error")},{docs:"Emit error and stop",cost:.1}),Un=M("storeProcedure",f.object({ast:f.any,ttl:f.number.optional,maxSize:f.number.optional}),f.string,async({ast:e,ttl:n,maxSize:t},r)=>{let s=x(e,r),o=n?x(n,r):Ot,i=t?x(t,r):Dt;if(!s||typeof s!="object"||!s.op)throw new Error('Invalid AST: must be an object with an "op" property');let a=JSON.stringify(s);if(a.length>i)throw new Error(`AST too large: ${a.length} bytes exceeds limit of ${i} bytes. Consider reducing AST size or using a shorter TTL.`);let l=Ft(),c=Date.now();return Q.set(l,{ast:s,createdAt:c,expiresAt:c+o}),l},{docs:"Store an AST and return a token for later execution",cost:1}),qn=M("releaseProcedure",f.object({token:f.string}),f.boolean,async({token:e},n)=>{let t=x(e,n);return Q.delete(t)},{docs:"Release a stored procedure by token",cost:.1}),Ln=M("clearExpiredProcedures",void 0,f.number,async()=>{let e=Date.now(),n=0;for(let[t,r]of Q)e>r.expiresAt&&(Q.delete(t),n++);return n},{docs:"Clear all expired procedures and return count",cost:.5}),qe={seq:F,if:Jt,while:Zt,return:Gt,try:Ht,Error:Kt,varSet:Yt,constSet:Xt,varGet:Qt,varsImport:en,varsLet:tn,varsExport:nn,scope:rn,callLocal:sn,map:on,filter:an,reduce:ln,find:cn,push:un,len:fn,split:pn,join:mn,template:dn,regexMatch:gn,pick:yn,omit:hn,merge:bn,keys:wn,httpFetch:$n,storeGet:En,storeSet:Tn,storeQuery:xn,storeVectorSearch:jn,llmPredict:An,agentRun:vn,transpileCode:Mn,runCode:kn,jsonParse:Cn,jsonStringify:Rn,xmlParse:Nn,memoize:Pn,cache:In,random:Bn,uuid:_n,hash:Ae,consoleLog:On,consoleWarn:Dn,consoleError:Fn,storeProcedure:Un,releaseProcedure:qn,clearExpiredProcedures:Ln};var Wn=new Set(["true","false","null","undefined","and","or","not"]);function Vn(e,n){let t=e.replace(/"[^"]*"/g,'""').replace(/'[^']*'/g,"''"),r=[],s=/(?<![.])\b([a-zA-Z_][a-zA-Z0-9_]*)\b/g,o;for(;(o=s.exec(t))!==null;)r.push(o[1]);let a=[...new Set(r)].filter(l=>!Wn.has(l)&&!(l in n)&&!new RegExp(`\\b${l}\\s*\\(`).test(t));a.length>0&&console.warn(`[Agent99 Builder] Condition "${e}" references variables not in vars mapping: ${a.join(", ")}. Add them to vars or use AsyncJS syntax (ajs\`...\`) which handles this automatically.`)}function pe(e,n){Vn(e,n);let t=zn(e),r=Je(t,0,n);if(r.pos<t.length){let s=t.slice(r.pos).join(" ");throw new Error(`Unsupported condition syntax near '${s}' in: ${e}
|
|
2
|
-
Supported: comparisons, &&, ||, !, arithmetic, member access (a.b), literals`)}return r.node}function zn(e){let n=[],t=0;for(;t<e.length;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(t>=e.length)break;if(e[t]==='"'||e[t]==="'"){let r=e[t++],s="";for(;t<e.length&&e[t]!==r;)e[t]==="\\"&&t+1<e.length&&t++,s+=e[t++];t++,n.push(JSON.stringify(s));continue}if(e.slice(t,t+2).match(/^(&&|\|\||==|!=|>=|<=)$/)){n.push(e.slice(t,t+2)),t+=2;continue}if("+-*/%><!().?:[]".includes(e[t])){n.push(e[t]),t++;continue}if(/\d/.test(e[t])){let r="";for(;t<e.length&&/[\d.]/.test(e[t]);)r+=e[t++];n.push(r);continue}if(/[a-zA-Z_]/.test(e[t])){let r="";for(;t<e.length&&/[a-zA-Z0-9_]/.test(e[t]);)r+=e[t++];n.push(r);continue}t++}return n}function
|
|
1
|
+
import{s as f,validate as Se,filter as Fe}from"tosijs-schema";function Ne(e,n){return(e instanceof String||e instanceof Number||e instanceof Boolean)&&(e=e.valueOf()),(n instanceof String||n instanceof Number||n instanceof Boolean)&&(n=n.valueOf()),!!(e===n||typeof e=="number"&&typeof n=="number"&&isNaN(e)&&isNaN(n)||e==null&&n==null)}var O=class{$error=!0;message;op;cause;constructor(n,t,r){this.message=n,this.op=t,this.cause=r}toString(){return`AgentError[${this.op}]: ${this.message}`}toJSON(){return{$error:!0,message:this.message,op:this.op}}};function Bt(e){return e instanceof O||e&&e.$error===!0}var Q=new Map,_t=3600*1e3,Ot=100*1024,$e="proc_";function Ee(e){return typeof e=="string"&&e.startsWith($e)}function Te(e){let n=Q.get(e);if(!n)throw new Error(`Procedure not found: ${e}`);if(Date.now()>n.expiresAt)throw Q.delete(e),new Error(`Procedure expired: ${e}`);return n.ast}function Dt(){return typeof crypto<"u"&&crypto.randomUUID?$e+crypto.randomUUID():$e+Math.random().toString(36).slice(2)+Date.now().toString(36)}var Ue=new Set(["__proto__","constructor","prototype"]);function Re(e){if(Ue.has(e))throw new Error(`Security Error: Access to '${e}' is forbidden`)}var Ft=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","metadata.google.internal"]);function Ut(e){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return!0;let t=n.hostname.toLowerCase();return!!(Ft.has(t)||t.endsWith(".internal")||t.endsWith(".local")||t==="169.254.169.254"||/^10\./.test(t)||/^192\.168\./.test(t)||/^172\.(1[6-9]|2\d|3[01])\./.test(t))}catch{return!0}}function Lt(e){return!!(/\([^)]*[+*][^)]*\)[+*]/.test(e)||/\(([^|)]+)\|\1\)[+*]/.test(e)||/\(\.\*\)\+/.test(e)||/\(\.\+\)\+/.test(e)||/\(\[.*\]\+\)\+/.test(e))}function G(e){return{...e,state:Object.create(e.state)}}function qt(e,n){let t={},r=new Set([...Object.keys(e),...Object.keys(n)]);for(let s of r){let o=e[s],i=n[s];i!==o&&(t[s]=i)}return t}function x(e,n){if(e&&typeof e=="object"&&e.$kind==="arg")return n.args[e.path];if(e&&typeof e=="object"&&e.$expr)return B(e,n);if(typeof e=="string"){if(e.startsWith("args.")&&!("args"in n.state))return n.args[e.replace("args.","")];if(e.includes(".")){let t=e.split(".");for(let s of t)if(Ue.has(s))throw new Error(`Security Error: Access to '${s}' is forbidden`);let r=n.state[t[0]];if(r!==void 0){for(let s=1;s<t.length;s++)r=r?.[t[s]];return r}}return e in n.state?n.state[e]:e}if(e&&typeof e=="object"&&!Array.isArray(e)&&e.constructor===Object){let t={};for(let r of Object.keys(e))t[r]=x(e[r],n);return t}return Array.isArray(e)?e.map(t=>x(t,n)):e}function H(e,n,t){return new Proxy(n,{get(r,s){if(s in r)return r[s];let o=t?.[s];throw o?new Error(`${e}.${s} is not available. ${o}`):new Error(`${e}.${s} is not supported in AsyncJS. Check docs for available ${e} methods.`)}})}function X(e){if(e===null)return{type:"null"};if(e===void 0)return{};if(typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string")return e;if(typeof e=="object"&&e!==null&&"schema"in e&&typeof e.schema=="object")return e.schema;let n=typeof e;if(n==="string")return{type:"string"};if(n==="number")return Number.isInteger(e)?{type:"integer"}:{type:"number"};if(n==="boolean")return{type:"boolean"};if(Array.isArray(e))return e.length===0?{type:"array"}:{type:"array",items:X(e[0])};if(n==="object"){let t={},r=[];for(let[s,o]of Object.entries(e))t[s]=X(o),r.push(s);return{type:"object",properties:t,required:r}}return{}}var z={Math:H("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 e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]/4294967296}return Math.random()}}),JSON:H("JSON",{parse:e=>JSON.parse(e),stringify:(e,n,t)=>JSON.stringify(e,n,t)}),console:H("console",{log:(...e)=>{},warn:(...e)=>{},error:(...e)=>{},info:(...e)=>{}},{table:"Use console.log with JSON.stringify for structured data.",dir:"Use console.log instead.",trace:"Stack traces are not available in AsyncJS."}),Array:H("Array",{isArray:e=>Array.isArray(e),from:(e,n,t)=>Array.from(e,n,t),of:(...e)=>Array.of(...e)},{prototype:"Prototype access is not allowed."}),Object:H("Object",{keys:e=>Object.keys(e),values:e=>Object.values(e),entries:e=>Object.entries(e),fromEntries:e=>Object.fromEntries(e),assign:(e,...n)=>Object.assign({},e,...n),hasOwn:(e,n)=>Object.hasOwn(e,n)},{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:H("String",{fromCharCode:(...e)=>String.fromCharCode(...e),fromCodePoint:(...e)=>String.fromCodePoint(...e)}),Number:H("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:(e,n)=>{let t=X(n),r=Fe(e,t);if(r instanceof Error)throw r;return r},Schema:{...f,response:(e,n)=>{let t=n?.schema!=null?n.schema:X(n);return{type:"json_schema",json_schema:{name:e,strict:!0,schema:t}}},fromExample:e=>X(e),isValid:(e,n)=>n?.schema!=null?Se(e,n):Se(e,X(n))},Set:(e=[])=>{let n=[...new globalThis.Set(e)];return{add(t){return n.includes(t)||n.push(t),this},remove(t){let r=n.indexOf(t);return r!==-1&&n.splice(r,1),this},clear(){return n.length=0,this},has(t){return n.includes(t)},get size(){return n.length},toArray(){return[...n]},union(t){let r=t?.toArray?.()??t??[];return z.Set([...n,...r])},intersection(t){let r=t?.toArray?.()??t??[];return z.Set(n.filter(s=>r.includes(s)))},diff(t){let r=t?.toArray?.()??t??[];return z.Set(n.filter(s=>!r.includes(s)))},forEach(t){n.forEach(t)},map(t){return z.Set(n.map(t))},filter(t){return z.Set(n.filter(t))},toJSON(){return[...n]}}},Date:(()=>{let e=t=>({get value(){return t.toISOString()},get timestamp(){return t.getTime()},get year(){return t.getFullYear()},get month(){return t.getMonth()+1},get day(){return t.getDate()},get hours(){return t.getHours()},get minutes(){return t.getMinutes()},get seconds(){return t.getSeconds()},get dayOfWeek(){return t.getDay()},add({years:r=0,months:s=0,days:o=0,hours:i=0,minutes:a=0,seconds:l=0,ms:c=0}={}){let p=new globalThis.Date(t.getTime());return r&&p.setFullYear(p.getFullYear()+r),s&&p.setMonth(p.getMonth()+s),o&&p.setDate(p.getDate()+o),i&&p.setHours(p.getHours()+i),a&&p.setMinutes(p.getMinutes()+a),l&&p.setSeconds(p.getSeconds()+l),c&&p.setMilliseconds(p.getMilliseconds()+c),e(p)},diff(r,s="ms"){let o=typeof r=="object"&&r.timestamp?r.timestamp:new globalThis.Date(r).getTime(),i=t.getTime()-o;switch(s){case"seconds":return i/1e3;case"minutes":return i/6e4;case"hours":return i/36e5;case"days":return i/864e5;default:return i}},format(r="ISO"){return r==="ISO"?t.toISOString():r==="date"?t.toISOString().split("T")[0]:r==="time"?t.toISOString().split("T")[1].split(".")[0]:r.replace("YYYY",String(t.getFullYear())).replace("MM",String(t.getMonth()+1).padStart(2,"0")).replace("DD",String(t.getDate()).padStart(2,"0")).replace("HH",String(t.getHours()).padStart(2,"0")).replace("mm",String(t.getMinutes()).padStart(2,"0")).replace("ss",String(t.getSeconds()).padStart(2,"0"))},isBefore(r){let s=typeof r=="object"&&r.timestamp?r.timestamp:new globalThis.Date(r).getTime();return t.getTime()<s},isAfter(r){let s=typeof r=="object"&&r.timestamp?r.timestamp:new globalThis.Date(r).getTime();return t.getTime()>s},toString(){return t.toISOString()},toJSON(){return t.toISOString()}}),n=t=>{let r=t!==void 0?new globalThis.Date(t):new globalThis.Date;if(isNaN(r.getTime()))throw new Error(`Invalid date: ${t}`);return e(r)};return n.now=()=>globalThis.Date.now(),n.parse=t=>e(new globalThis.Date(t)),n})()},ce={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."},Wt=.01,Pe=1e-4,Ie=.001,Vt=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 B(e,n){if(e==null||typeof e!="object"||!("$expr"in e))return e;if(n.fuel&&(n.fuel.current-=Wt,n.fuel.current<=0))throw new Error("Out of Fuel");switch(e.$expr){case"literal":return e.value;case"ident":{if(e.name in n.state)return n.state[e.name];if(e.name in n.args)return n.args[e.name];if(e.name in z)return z[e.name];if(e.name in ce)throw new Error(ce[e.name]);return}case"member":{let t=B(e.object,n);if(e.optional&&t==null)return;let r=typeof e.property=="object"&&e.property!==null?B(e.property,n):e.property;return Re(String(r)),t?.[r]}case"binary":{let t=B(e.left,n),r=B(e.right,n);switch(e.op){case"+":{let s=t+r;if(typeof s=="string"&&n.fuel&&(n.fuel.current-=s.length*Pe,n.fuel.current<=0)){n.error=new O("Out of Fuel","expr.concat");return}return s}case"-":return t-r;case"*":return t*r;case"/":return t/r;case"%":return t%r;case"**":return t**r;case">":return t>r;case"<":return t<r;case">=":return t>=r;case"<=":return t<=r;case"==":return Ne(t,r);case"!=":return!Ne(t,r);case"===":return t===r;case"!==":return t!==r;default:throw new Error(`Unknown binary operator: ${e.op}`)}}case"unary":{let t=B(e.argument,n);switch(e.op){case"!":return!t;case"-":return-t;case"+":return+t;case"typeof":return typeof t;default:throw new Error(`Unknown unary operator: ${e.op}`)}}case"logical":{let t=B(e.left,n);return e.op==="&&"?t&&B(e.right,n):e.op==="??"?t??B(e.right,n):t||B(e.right,n)}case"conditional":{let t=B(e.test,n);return B(t?e.consequent:e.alternate,n)}case"array":return e.elements.map(t=>B(t,n));case"object":{let t={};for(let r of e.properties)t[r.key]=B(r.value,n);return t}case"call":{if(e.callee==="Error"){let r=e.arguments.map(o=>B(o,n)),s=typeof r[0]=="string"?r[0]:"Error";n.error=new O(s,"Error");return}if(e.callee in z){let r=z[e.callee];if(typeof r=="function"){let s=e.arguments.map(o=>B(o,n));return r(...s)}}throw n.resolver(e.callee)?new Error(`Atom calls in expressions not yet supported: ${e.callee}`):e.callee in ce?new Error(ce[e.callee]):new Error(`Unknown function: ${e.callee}`)}case"methodCall":{let t=B(e.object,n);if(e.optional&&t==null)return;let r=e.method;if(Re(r),t==null)throw new Error(`Cannot call method '${r}' on ${t}`);let s=t[r];if(typeof s!="function")throw new Error(`'${r}' is not a function`);let o=e.arguments.map(a=>B(a,n)),i=s.apply(t,o);if(n.fuel&&Vt.has(r)){let a=0;if(typeof i=="string"?a=i.length*Pe:Array.isArray(i)?a=i.length*Ie:typeof i=="object"&&i!==null&&(a=Object.keys(i).length*Ie),n.fuel.current-=a,n.fuel.current<=0){n.error=new O("Out of Fuel",`expr.${r}`);return}}return i}default:throw new Error(`Unknown expression type: ${e.$expr}`)}}function k(e,n,t,r,s={}){let{docs:o="",timeoutMs:i=1e3,cost:a=1,effects:l="pure"}=typeof s=="string"?{docs:s}:s;return{op:e,inputSchema:n,outputSchema:t,exec:async(p,m)=>{let{op:u,result:d,...g}=p;if(m.error)return;let y=m.trace?{...m.state}:null,w=m.fuel.current,E,S;try{let h=m.costOverrides?.[e],T=h!==void 0?h:a,$=typeof T=="function"?T(g,m):T;if((m.fuel.current-=$)<=0){m.error=new O("Out of Fuel",e);return}let b=m.timeoutOverrides?.[e],v=b!==void 0?b:i,j=typeof v=="function"?v(g,m):v,A,M=async()=>r(p,m);if(E=j>0?await Promise.race([M(),new Promise((C,R)=>{A=setTimeout(()=>R(new Error(`Atom '${e}' timed out`)),j)})]).finally(()=>clearTimeout(A)):await M(),p.result){if(m.consts.has(p.result))throw new Error(`Cannot reassign const variable '${p.result}'`);if(E!==void 0&&t&&!Se(E,t)){m.error=new O(`Output validation failed for '${e}'`,e);return}m.state[p.result]=E,p.resultConst&&m.consts.add(p.result)}}catch(h){S=h.message||String(h),m.error=new O(S,e,h)}finally{if(m.trace&&y){let h=qt(y,m.state);m.trace.push({op:e,input:g,stateDiff:h,result:E,error:S,fuelBefore:w,fuelAfter:m.fuel.current,timestamp:new Date().toISOString()})}}},docs:o,timeoutMs:i,cost:a,effects:l,create:p=>({op:e,...p})}}var F=k("seq",f.object({steps:f.array(f.any)}),void 0,async({steps:e},n)=>{for(let t of e){if(n.output!==void 0||n.error)return;let r=n.resolver(t.op);if(!r)throw new Error(`Unknown Atom: ${t.op}`);await r.exec(t,n)}},{docs:"Sequence",timeoutMs:0,cost:.1}),zt=k("if",f.object({condition:f.any,then:f.array(f.any),else:f.array(f.any).optional}),void 0,async(e,n)=>{B(e.condition,n)?await F.exec({op:"seq",steps:e.then},n):e.else&&await F.exec({op:"seq",steps:e.else},n)},{docs:"If/Else",timeoutMs:0,cost:.1}),Jt=k("while",f.object({condition:f.any,body:f.array(f.any)}),void 0,async(e,n)=>{for(;B(e.condition,n);){if(n.signal?.aborted)throw new Error("Execution aborted");if((n.fuel.current-=.1)<=0)throw new Error("Out of Fuel");if(await F.exec({op:"seq",steps:e.body},n),n.output!==void 0||n.error)return}},{docs:"While Loop",timeoutMs:0,cost:.1}),Zt=k("return",void 0,f.any,async(e,n)=>{if(n.error)return n.output=n.error,n.error;if("value"in e){let r=x(e.value,n);if(!n.localCall&&r!==void 0&&r!==null&&!Bt(r)&&(typeof r!="object"||Array.isArray(r))){let s=new O(`Agent must return an object, got ${Array.isArray(r)?"array":typeof r}`,"return");return n.error=s,n.output=s,s}return n.output=r,r}let t={};if(e.schema?.properties){for(let r of Object.keys(e.schema.properties))t[r]=n.state[r];if(e.filter!==!1){let r=Fe(t,e.schema);r instanceof Error||(t=r)}}return n.output=t,t},{docs:"Return",cost:.1}),Gt=k("try",f.object({try:f.array(f.any),catch:f.array(f.any).optional,catchParam:f.string.optional}),void 0,async(e,n)=>{if(await F.exec({op:"seq",steps:e.try},n),n.error&&e.catch){let t=e.catchParam||"error";n.state[t]=n.error.message,n.state.errorOp=n.error.op,n.error=void 0,await F.exec({op:"seq",steps:e.catch},n)}},{docs:"Try/Catch",timeoutMs:0,cost:.1}),Ht=k("Error",f.object({args:f.array(f.any).optional}),void 0,async(e,n)=>{let t=e.args?.[0]??"Error";n.error=new O(String(t),"Error")},{docs:"Trigger error flow",cost:.1}),Kt=k("varSet",f.object({key:f.string,value:f.any}),void 0,async({key:e,value:n},t)=>{if(t.consts.has(e))throw new Error(`Cannot reassign const variable '${e}'`);t.state[e]=x(n,t)},{docs:"Set Variable",cost:.1}),Yt=k("constSet",f.object({key:f.string,value:f.any}),void 0,async({key:e,value:n},t)=>{if(t.consts.has(e))throw new Error(`Cannot reassign const variable '${e}'`);if(e in t.state)throw new Error(`Cannot redeclare variable '${e}' as const`);t.state[e]=x(n,t),t.consts.add(e)},{docs:"Set Const Variable (immutable)",cost:.1}),Xt=k("varGet",f.object({key:f.string}),f.any,async({key:e},n)=>x(e,n),{docs:"Get Variable",cost:.1}),Qt=k("varsImport",f.object({keys:f.union([f.array(f.string),f.record(f.string)])}),void 0,async({keys:e},n)=>{if(Array.isArray(e))for(let t of e)n.state[t]=x({$kind:"arg",path:t},n);else for(let[t,r]of Object.entries(e))n.state[t]=x({$kind:"arg",path:r},n)},{docs:"Import variables from args into the current scope, with optional renaming.",cost:.2}),en=k("varsLet",f.record(f.any),void 0,async(e,n)=>{for(let t of Object.keys(e))t==="op"||t==="result"||(n.state[t]=x(e[t],n))},{docs:"Initialize a set of variables in the current scope from the step object properties.",cost:.1}),tn=k("varsExport",f.object({keys:f.union([f.array(f.string),f.record(f.string)])}),f.record(f.any),async({keys:e},n)=>{let t={};if(Array.isArray(e))for(let r of e)t[r]=x(r,n);else for(let[r,s]of Object.entries(e))t[r]=x(s,n);return t},{docs:"Export variables from the current scope, with optional renaming.",cost:.2}),nn=k("scope",f.object({steps:f.array(f.any)}),void 0,async({steps:e},n)=>{let t=G(n);await F.exec({op:"seq",steps:e},t),t.output!==void 0&&(n.output=t.output)},{docs:"Create new scope",timeoutMs:0,cost:.1}),Be=256,rn=k("callLocal",f.object({name:f.string,args:f.array(f.any)}),void 0,async({name:e,args:n},t)=>{let r=t.helpers?.[e];if(!r)return t.error=new O(`Unknown helper: ${e}`,"callLocal"),t.error;let s=(t.callDepth??0)+1;if(s>Be)return t.error=new O(`Maximum helper call depth (${Be}) exceeded \u2014 likely infinite recursion in '${e}'`,"callLocal"),t.error;let o=n.map(a=>x(a,t)),i={...t,state:{},consts:new Set,output:void 0,error:void 0,localCall:!0,callDepth:s};for(let a=0;a<r.paramNames.length;a++)i.state[r.paramNames[a]]=o[a];return await F.exec({op:"seq",steps:r.steps},i),i.error&&(t.error=i.error),i.output},{docs:"Invoke a local helper function by name",timeoutMs:0,cost:.1}),sn=k("map",f.object({items:f.array(f.any),as:f.string,steps:f.array(f.any)}),f.array(f.any),async({items:e,as:n,steps:t},r)=>{let s=[],o=x(e,r);if(!Array.isArray(o))throw new Error("map: items is not an array");for(let i of o){if(r.signal?.aborted)throw new Error("Execution aborted");let a=G(r);a.state[n]=i,await F.exec({op:"seq",steps:t},a),s.push(a.state.result??null)}return s},{docs:"Map Array",timeoutMs:0,cost:1}),on=k("filter",f.object({items:f.array(f.any),as:f.string,condition:f.any}),f.array(f.any),async({items:e,as:n,condition:t},r)=>{let s=[],o=x(e,r);if(!Array.isArray(o))throw new Error("filter: items is not an array");for(let i of o){if(r.signal?.aborted)throw new Error("Execution aborted");let a=G(r);a.state[n]=i,B(t,a)&&s.push(i)}return s},{docs:"Filter Array",timeoutMs:0,cost:1}),an=k("reduce",f.object({items:f.array(f.any),as:f.string,accumulator:f.string,initial:f.any,steps:f.array(f.any)}),f.any,async({items:e,as:n,accumulator:t,initial:r,steps:s},o)=>{let i=x(e,o),a=x(r,o);if(!Array.isArray(i))throw new Error("reduce: items is not an array");let l=a;for(let c of i){if(o.signal?.aborted)throw new Error("Execution aborted");let p=G(o);p.state[n]=c,p.state[t]=l,await F.exec({op:"seq",steps:s},p),l=p.state.result??l}return l},{docs:"Reduce Array",timeoutMs:0,cost:1}),ln=k("find",f.object({items:f.array(f.any),as:f.string,condition:f.any}),f.any,async({items:e,as:n,condition:t},r)=>{let s=x(e,r);if(!Array.isArray(s))throw new Error("find: items is not an array");for(let o of s){if(r.signal?.aborted)throw new Error("Execution aborted");let i=G(r);if(i.state[n]=o,B(t,i))return o}return null},{docs:"Find in Array",timeoutMs:0,cost:1}),cn=k("push",f.object({list:f.array(f.any),item:f.any}),f.array(f.any),async({list:e,item:n},t)=>{let r=x(e,t),s=x(n,t);return Array.isArray(r)&&r.push(s),r},{docs:"Push to Array",cost:1}),un=k("len",f.object({list:f.any}),f.number,async({list:e},n)=>{let t=x(e,n);return Array.isArray(t)||typeof t=="string"?t.length:0},{docs:"Length",cost:1}),fn=k("split",f.object({str:f.string,sep:f.string}),f.array(f.string),async({str:e,sep:n},t)=>x(e,t).split(x(n,t)),{docs:"Split String",cost:1}),pn=k("join",f.object({list:f.array(f.string),sep:f.string}),f.string,async({list:e,sep:n},t)=>x(e,t).join(x(n,t)),{docs:"Join String",cost:1}),mn=k("template",f.object({tmpl:f.string,vars:f.record(f.any)}),f.string,async({tmpl:e,vars:n},t)=>x(e,t).replace(/\{\{(\w+)\}\}/g,(s,o)=>String(x(n[o],t)??"")),{docs:"String Template",cost:1}),dn=k("regexMatch",f.object({pattern:f.string,value:f.any}),f.boolean,async({pattern:e,value:n},t)=>{if(Lt(e))throw new Error(`Suspicious regex pattern rejected (potential ReDoS): ${e}`);let r=x(n,t);return new RegExp(e).test(r)},{docs:"Returns true if the value matches the regex pattern.",cost:2}),gn=k("pick",f.object({obj:f.record(f.any),keys:f.array(f.string)}),f.record(f.any),async({obj:e,keys:n},t)=>{let r=x(e,t),s=x(n,t),o={};return r&&Array.isArray(s)&&s.forEach(i=>o[i]=r[i]),o},{docs:"Pick Keys",cost:1}),hn=k("omit",f.object({obj:f.record(f.any),keys:f.array(f.string)}),f.record(f.any),async({obj:e,keys:n},t)=>{let r=x(e,t),s=new Set(x(n,t)),o={};return r&&Object.keys(r).forEach(i=>{s.has(i)||(o[i]=r[i])}),o},{docs:"Omit Keys",cost:1}),yn=k("merge",f.object({a:f.record(f.any),b:f.record(f.any)}),f.record(f.any),async({a:e,b:n},t)=>({...x(e,t),...x(n,t)}),{docs:"Merge Objects",cost:1}),bn=k("keys",f.object({obj:f.record(f.any)}),f.array(f.string),async({obj:e},n)=>Object.keys(x(e,n)??{}),{docs:"Object Keys",cost:1}),_e=10,Oe="X-Agent-Depth";function wn(e,n){try{let r=new URL(e).hostname.toLowerCase();for(let s of n){let o=s.toLowerCase();if(o.startsWith("*.")){let i=o.slice(1);if(r.endsWith(i)||r===o.slice(2))return!0}else if(r===o)return!0}return!1}catch{return!1}}var Sn=k("httpFetch",f.object({url:f.string,method:f.string.optional,headers:f.record(f.string).optional,body:f.any.optional,responseType:f.string.optional}),f.any,async(e,n)=>{let t=x(e.url,n),r=x(e.method,n),s=x(e.headers,n)||{},o=x(e.body,n),i=x(e.responseType,n),a=n.context?.requestDepth??0;if(a>=_e)throw new Error(`Agent request depth exceeded (max ${_e}). This prevents recursive agent loops.`);if(n.capabilities.fetch)return n.capabilities.fetch(t,{method:r,headers:{...s,[Oe]:String(a+1)},body:o,signal:n.signal,responseType:i});let l=n.context?.allowedFetchDomains;if(l){if(!wn(t,l))throw new Error(`Fetch blocked: domain not in allowlist. Allowed: ${l.join(", ")}`)}else{if(Ut(t))throw new Error("Blocked URL: private/internal addresses not allowed in default fetch");try{let p=new URL(t).hostname.toLowerCase();if(p!=="localhost"&&p!=="127.0.0.1"&&p!=="[::1]")throw new Error("Fetch blocked: no allowedFetchDomains configured. Set ctx.context.allowedFetchDomains or provide a custom fetch capability.")}catch(c){throw c.message.includes("allowedFetchDomains")?c:new Error(`Invalid URL: ${t}`,{cause:c})}}if(typeof globalThis.fetch=="function"){let c=await globalThis.fetch(t,{method:r,headers:{...s,[Oe]:String(a+1)},body:o?JSON.stringify(o):void 0,signal:n.signal});if(i==="dataUrl"){let m=await c.arrayBuffer(),u=new Uint8Array(m),d="";for(let w=0;w<u.length;w++)d+=String.fromCharCode(u[w]);let g=btoa(d);return`data:${c.headers.get("content-type")||"application/octet-stream"};base64,${g}`}let p=c.headers.get("content-type");return i==="json"||p&&p.includes("application/json")?c.json():c.text()}throw new Error("Capability 'fetch' missing and no global fetch available")},{docs:"HTTP Fetch",timeoutMs:3e4,cost:5}),$n=k("storeGet",f.object({key:f.string}),f.any,async({key:e},n)=>{let t=x(e,n);return n.capabilities.store?.get(t)},{docs:"Store Get",cost:5}),En=k("storeSet",f.object({key:f.string,value:f.any}),void 0,async({key:e,value:n},t)=>{let r=x(e,t),s=x(n,t);return t.capabilities.store?.set(r,s)},{docs:"Store Set",cost:5}),Tn=k("storeQuery",f.object({query:f.any}),f.array(f.any),async({query:e},n)=>n.capabilities.store?.query?.(x(e,n))??[],{docs:"Store Query",cost:5}),xn=k("storeVectorSearch",f.object({collection:f.string.optional,vector:f.array(f.number),k:f.number.optional}),f.array(f.any),async({collection:e,vector:n,k:t},r)=>r.capabilities.store?.vectorSearch?.(x(e,r),x(n,r),x(t,r))??[],{docs:"Vector Search",cost:(e,n)=>5+(x(e.k,n)??5)}),vn=k("llmPredict",f.object({prompt:f.string,options:f.any.optional}),f.string,async({prompt:e,options:n},t)=>{if(!t.capabilities.llm?.predict)throw new Error("Capability 'llm.predict' missing");return t.capabilities.llm.predict(x(e,t),x(n,t))},{docs:"LLM Predict",timeoutMs:12e4,cost:100}),An=k("agentRun",f.object({agentId:f.any,input:f.any}),f.any,async({agentId:e,input:n},t)=>{let r=x(e,t),s=x(n,t),o=s;if(s&&typeof s=="object"&&!Array.isArray(s)){o={};for(let a in s)o[a]=x(s[a],t)}if(Ee(r)){let a=Te(r),l={...t,args:o,state:{},consts:new Set,output:void 0,error:void 0},c=t.resolver("seq");if(!c)throw new Error("seq atom not found");if(await c.exec(a,l),l.error)throw new Error(l.error.message||"Sub-agent failed");return l.output}if(r&&typeof r=="object"&&"op"in r){let a={...t,args:o,state:{},consts:new Set,output:void 0,error:void 0},l=t.resolver("seq");if(!l)throw new Error("seq atom not found");if(await l.exec(r,a),a.error)throw new Error(a.error.message||"Sub-agent failed");return a.output}if(!t.capabilities.agent?.run)throw new Error("Capability 'agent.run' missing");let i=await t.capabilities.agent.run(r,o);if(i&&typeof i=="object"&&"fuelUsed"in i&&typeof i.fuelUsed=="number"){if(i.error)throw new Error(i.error.message||"Sub-agent failed");return i.result}return i},{docs:"Run Sub-Agent (accepts procedure token, AST, or agent ID)",cost:1}),jn=k("transpileCode",f.object({code:f.string}),f.any,async({code:e},n)=>{if(!n.capabilities.code?.transpile)throw new Error("Capability 'code.transpile' missing. Enable code transpilation by providing the code capability.");let t=x(e,n);try{return n.capabilities.code.transpile(t)}catch(r){throw new Error(`Code transpilation failed: ${r.message}`,{cause:r})}},{docs:"Transpile AsyncJS code to AST",cost:1}),De=10,Mn=k("runCode",f.object({code:f.string,args:f.record(f.any).optional}),f.any,async({code:e,args:n},t)=>{let r=t.runCodeDepth??0;if(r>=De)throw new Error(`runCode recursion limit exceeded (max ${De}). This prevents infinite loops from dynamically generated code calling runCode.`);if(!t.capabilities.code?.transpile)throw new Error("Capability 'code.transpile' missing. Enable dynamic code execution by providing the code capability.");let s=x(e,t),o=n?x(n,t):{},i;try{i=t.capabilities.code.transpile(s)}catch(l){throw new Error(`Code transpilation failed: ${l.message}`,{cause:l})}if(i.op!=="seq")throw new Error("Transpiled code must be a seq node");let a=G(t);if(a.args=o,a.output=void 0,a.runCodeDepth=r+1,await F.exec(i,a),a.error){t.error=a.error;return}return a.output},{docs:"Run dynamically generated AsyncJS code",cost:1}),kn=k("jsonParse",f.object({str:f.string}),f.any,async({str:e},n)=>JSON.parse(x(e,n)),{docs:"Parse JSON",cost:1}),Cn=k("jsonStringify",f.object({value:f.any}),f.string,async({value:e},n)=>JSON.stringify(x(e,n)),{docs:"Stringify JSON",cost:1}),Nn=k("xmlParse",f.object({str:f.string}),f.any,async({str:e},n)=>{if(!n.capabilities.xml?.parse)throw new Error("Capability 'xml.parse' missing");return n.capabilities.xml.parse(x(e,n))},{docs:"Parse XML",cost:1}),Rn=k("memoize",f.object({key:f.string.optional,steps:f.array(f.any)}),f.any,async({key:e,steps:n},t)=>{t.memo||(t.memo=new Map);let r=x(e,t)??await xe.exec({value:n,algorithm:"SHA-256"},t);if(t.memo.has(r))return t.memo.get(r);let s=G(t);await F.exec({op:"seq",steps:n},s);let o=s.output??s.state.result;return t.memo.set(r,o),o},{docs:"Memoize steps result in memory",cost:1}),Pn=k("cache",f.object({key:f.string.optional,steps:f.array(f.any),ttlMs:f.number.optional}),f.any,async({key:e,steps:n,ttlMs:t},r)=>{if(!r.capabilities.store)throw new Error("Capability 'store' missing for caching");let o=`cache:${x(e,r)??await xe.exec({value:n,algorithm:"SHA-256"},r)}`,i=await r.capabilities.store.get(o);if(i)if(typeof i=="object"&&i._exp){if(Date.now()<i._exp)return i.val}else return i;let a=G(r);await F.exec({op:"seq",steps:n},a);let l=a.output??a.state.result,c=Date.now()+(t??24*3600*1e3);if((r.fuel.current-=5)<=0)throw new Error("Out of Fuel");return await r.capabilities.store.set(o,{val:l,_exp:c}),l},{docs:"Cache steps result in store with TTL",cost:5}),In=k("random",f.object({min:f.number.optional,max:f.number.optional,format:f.string.optional,length:f.number.optional}),f.any,async({min:e,max:n,format:t,length:r},s)=>{let o=x(t,s)??"float",i=x(r,s)??10,a=x(e,s)??0,l=x(n,s)??1;if(o==="base36"){let u="0123456789abcdefghijklmnopqrstuvwxyz",d="";if(typeof crypto<"u"&&crypto.getRandomValues){let g=new Uint8Array(i);crypto.getRandomValues(g);for(let y=0;y<i;y++)d+=u[g[y]%36]}else for(let g=0;g<i;g++)d+=u.charAt(Math.floor(Math.random()*36));return d}let c;if(typeof crypto<"u"&&crypto.getRandomValues){let u=new Uint32Array(1);crypto.getRandomValues(u),c=u[0]/4294967296}else c=Math.random();let p=l-a,m=c*p+a;return o==="integer"?Math.floor(m):m},{docs:"Generate Random",cost:1}),Bn=k("uuid",void 0,f.string,async()=>{if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=Array.from(e,t=>t.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let n=Math.random()*16|0;return(e==="x"?n:n&3|8).toString(16)})},{docs:"Generate UUID",cost:1}),xe=k("hash",f.object({value:f.any,algorithm:f.string.optional}),f.string,async({value:e,algorithm:n},t)=>{let r=typeof e=="string"?e:JSON.stringify(x(e,t)),s=x(n,t)||"SHA-256";if(typeof crypto<"u"&&crypto.subtle){let a=new TextEncoder().encode(r),l=await crypto.subtle.digest(s,a);return Array.from(new Uint8Array(l)).map(p=>p.toString(16).padStart(2,"0")).join("")}let o=0;for(let i=0;i<r.length;i++){let a=r.charCodeAt(i);o=(o<<5)-o+a,o|=0}return String(o)},{docs:"Hash a value",cost:1}),_n=k("consoleLog",f.object({message:f.any}),void 0,async({message:e},n)=>{let t=x(e,n);n.trace&&n.trace.push({op:"console.log",input:{message:t},stateDiff:{},result:t,fuelBefore:n.fuel.current,fuelAfter:n.fuel.current,timestamp:new Date().toISOString()})},{docs:"Log to trace",cost:.1}),On=k("consoleWarn",f.object({message:f.any}),void 0,async({message:e},n)=>{let t=x(e,n),r=typeof t=="string"?t:JSON.stringify(t);n.warnings||(n.warnings=[]),n.warnings.push(r),n.trace&&n.trace.push({op:"console.warn",input:{message:t},stateDiff:{},result:t,fuelBefore:n.fuel.current,fuelAfter:n.fuel.current,timestamp:new Date().toISOString()})},{docs:"Add warning",cost:.1}),Dn=k("consoleError",f.object({message:f.any}),void 0,async({message:e},n)=>{let t=x(e,n),r=typeof t=="string"?t:JSON.stringify(t);n.error=new O(r,"console.error")},{docs:"Emit error and stop",cost:.1}),Fn=k("storeProcedure",f.object({ast:f.any,ttl:f.number.optional,maxSize:f.number.optional}),f.string,async({ast:e,ttl:n,maxSize:t},r)=>{let s=x(e,r),o=n?x(n,r):_t,i=t?x(t,r):Ot;if(!s||typeof s!="object"||!s.op)throw new Error('Invalid AST: must be an object with an "op" property');let a=JSON.stringify(s);if(a.length>i)throw new Error(`AST too large: ${a.length} bytes exceeds limit of ${i} bytes. Consider reducing AST size or using a shorter TTL.`);let l=Dt(),c=Date.now();return Q.set(l,{ast:s,createdAt:c,expiresAt:c+o}),l},{docs:"Store an AST and return a token for later execution",cost:1}),Un=k("releaseProcedure",f.object({token:f.string}),f.boolean,async({token:e},n)=>{let t=x(e,n);return Q.delete(t)},{docs:"Release a stored procedure by token",cost:.1}),Ln=k("clearExpiredProcedures",void 0,f.number,async()=>{let e=Date.now(),n=0;for(let[t,r]of Q)e>r.expiresAt&&(Q.delete(t),n++);return n},{docs:"Clear all expired procedures and return count",cost:.5}),ve={seq:F,if:zt,while:Jt,return:Zt,try:Gt,Error:Ht,varSet:Kt,constSet:Yt,varGet:Xt,varsImport:Qt,varsLet:en,varsExport:tn,scope:nn,callLocal:rn,map:sn,filter:on,reduce:an,find:ln,push:cn,len:un,split:fn,join:pn,template:mn,regexMatch:dn,pick:gn,omit:hn,merge:yn,keys:bn,httpFetch:Sn,storeGet:$n,storeSet:En,storeQuery:Tn,storeVectorSearch:xn,llmPredict:vn,agentRun:An,transpileCode:jn,runCode:Mn,jsonParse:kn,jsonStringify:Cn,xmlParse:Nn,memoize:Rn,cache:Pn,random:In,uuid:Bn,hash:xe,consoleLog:_n,consoleWarn:On,consoleError:Dn,storeProcedure:Fn,releaseProcedure:Un,clearExpiredProcedures:Ln},qn=["httpFetch","storeGet","storeSet","storeQuery","storeVectorSearch","llmPredict","agentRun","transpileCode","runCode","random","uuid","consoleLog","consoleWarn","consoleError","storeProcedure","releaseProcedure","clearExpiredProcedures","cache","memoize"];for(let e of qn){let n=ve[e];n&&(n.effects="io")}var Wn=new Set(["true","false","null","undefined","and","or","not"]);function Vn(e,n){let t=e.replace(/"[^"]*"/g,'""').replace(/'[^']*'/g,"''"),r=[],s=/(?<![.])\b([a-zA-Z_][a-zA-Z0-9_]*)\b/g,o;for(;(o=s.exec(t))!==null;)r.push(o[1]);let a=[...new Set(r)].filter(l=>!Wn.has(l)&&!(l in n)&&!new RegExp(`\\b${l}\\s*\\(`).test(t));a.length>0&&console.warn(`[Agent99 Builder] Condition "${e}" references variables not in vars mapping: ${a.join(", ")}. Add them to vars or use AsyncJS syntax (ajs\`...\`) which handles this automatically.`)}function ue(e,n){Vn(e,n);let t=zn(e),r=ze(t,0,n);if(r.pos<t.length){let s=t.slice(r.pos).join(" ");throw new Error(`Unsupported condition syntax near '${s}' in: ${e}
|
|
2
|
+
Supported: comparisons, &&, ||, !, arithmetic, member access (a.b), literals`)}return r.node}function zn(e){let n=[],t=0;for(;t<e.length;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(t>=e.length)break;if(e[t]==='"'||e[t]==="'"){let r=e[t++],s="";for(;t<e.length&&e[t]!==r;)e[t]==="\\"&&t+1<e.length&&t++,s+=e[t++];t++,n.push(JSON.stringify(s));continue}if(e.slice(t,t+2).match(/^(&&|\|\||==|!=|>=|<=)$/)){n.push(e.slice(t,t+2)),t+=2;continue}if("+-*/%><!().?:[]".includes(e[t])){n.push(e[t]),t++;continue}if(/\d/.test(e[t])){let r="";for(;t<e.length&&/[\d.]/.test(e[t]);)r+=e[t++];n.push(r);continue}if(/[a-zA-Z_]/.test(e[t])){let r="";for(;t<e.length&&/[a-zA-Z0-9_]/.test(e[t]);)r+=e[t++];n.push(r);continue}t++}return n}function ze(e,n,t){return Jn(e,n,t)}function Jn(e,n,t){let{node:r,pos:s}=Le(e,n,t);for(;e[s]==="||";){s++;let{node:o,pos:i}=Le(e,s,t);r={$expr:"logical",op:"||",left:r,right:o},s=i}return{node:r,pos:s}}function Le(e,n,t){let{node:r,pos:s}=qe(e,n,t);for(;e[s]==="&&";){s++;let{node:o,pos:i}=qe(e,s,t);r={$expr:"logical",op:"&&",left:r,right:o},s=i}return{node:r,pos:s}}function qe(e,n,t){let{node:r,pos:s}=We(e,n,t),o=["==","!=",">","<",">=","<="];for(;o.includes(e[s]);){let i=e[s++],{node:a,pos:l}=We(e,s,t);r={$expr:"binary",op:i,left:r,right:a},s=l}return{node:r,pos:s}}function We(e,n,t){let{node:r,pos:s}=Ve(e,n,t);for(;e[s]==="+"||e[s]==="-";){let o=e[s++],{node:i,pos:a}=Ve(e,s,t);r={$expr:"binary",op:o,left:r,right:i},s=a}return{node:r,pos:s}}function Ve(e,n,t){let{node:r,pos:s}=Ae(e,n,t);for(;e[s]==="*"||e[s]==="/"||e[s]==="%";){let o=e[s++],{node:i,pos:a}=Ae(e,s,t);r={$expr:"binary",op:o,left:r,right:i},s=a}return{node:r,pos:s}}function Ae(e,n,t){if(e[n]==="!"||e[n]==="-"){let r=e[n++],{node:s,pos:o}=Ae(e,n,t);return{node:{$expr:"unary",op:r,argument:s},pos:o}}return Zn(e,n,t)}function Zn(e,n,t){let r=e[n];if(r==="("){let{node:s,pos:o}=ze(e,n+1,t);return{node:s,pos:o+1}}if(r&&r.startsWith('"'))return{node:{$expr:"literal",value:JSON.parse(r)},pos:n+1};if(r&&/^\d/.test(r))return{node:{$expr:"literal",value:parseFloat(r)},pos:n+1};if(r==="true")return{node:{$expr:"literal",value:!0},pos:n+1};if(r==="false")return{node:{$expr:"literal",value:!1},pos:n+1};if(r==="null")return{node:{$expr:"literal",value:null},pos:n+1};if(r&&/^[a-zA-Z_]/.test(r)){let s={$expr:"ident",name:r},o=n+1;for(;e[o]===".";){o++;let i=e[o++];s={$expr:"member",object:s,property:i}}return{node:s,pos:o}}return{node:{$expr:"literal",value:null},pos:n+1}}var re=class e{steps=[];atoms;proxy;constructor(n){return this.atoms=n,this.proxy=new Proxy(this,{get:(t,r,s)=>{if(r in t)return t[r];if(typeof r=="string"&&r in t.atoms)return o=>{let i=t.atoms[r];return t.add(i.create(o)),s}}}),this.proxy}add(n){return this.steps.push(n),this.proxy}as(n){if(this.steps.length===0)throw new Error("No step to capture");let t=this.steps[this.steps.length-1];return t.result=n,this.proxy}step(n){return this.add(n)}return(n){let t=this.atoms.return;if(!t)throw new Error("Atom 'return' not found");let r=n.schema??n;return this.add(t.create({schema:r}))}toJSON(){return{op:"seq",steps:[...this.steps]}}varsImport(n){return this.add(this.atoms.varsImport.create({keys:n}))}varsExport(n){return this.add(this.atoms.varsExport.create({keys:n}))}if(n,t,r,s){let o=new e(this.atoms);r(o);let i;if(s){let c=new e(this.atoms);s(c),i=c.steps}let a=ue(n,t),l=this.atoms.if;return this.add(l.create({condition:a,then:o.steps,else:i}))}while(n,t,r){let s=new e(this.atoms);r(s);let o=ue(n,t),i=this.atoms.while;return this.add(i.create({condition:o,body:s.steps}))}scope(n){let t=new e(this.atoms);n(t);let r=this.atoms.scope;return this.add(r.create({steps:t.steps}))}map(n,t,r){let s=new e(this.atoms);r(s);let o=this.atoms.map;return this.add(o.create({items:n,as:t,steps:s.steps}))}filter(n,t,r,s={}){let o=ue(r,s),i=this.atoms.filter;return this.add(i.create({items:n,as:t,condition:o}))}find(n,t,r,s={}){let o=ue(r,s),i=this.atoms.find;return this.add(i.create({items:n,as:t,condition:o}))}reduce(n,t,r,s,o){let i=new e(this.atoms);o(i);let a=this.atoms.reduce;return this.add(a.create({items:n,as:t,accumulator:r,initial:s,steps:i.steps}))}memoize(n,t){let r=new e(this.atoms);n(r);let s=this.atoms.memoize;return this.add(s.create({key:t,steps:r.steps}))}cache(n,t,r){let s=new e(this.atoms);n(s);let o=this.atoms.cache;return this.add(o.create({key:t,steps:s.steps,ttlMs:r}))}try(n){let t=new e(this.atoms);n.try(t);let r;if(n.catch){let o=new e(this.atoms);n.catch(o),r=o.steps}let s=this.atoms.try;return this.add(s.create({try:t.steps,catch:r}))}};import{validate as kr}from"tosijs-schema";import*as vt from"acorn";var P=class extends Error{line;column;source;filename;constructor(n,t,r,s){let o=`${s||"<source>"}:${t.line}:${t.column}`;super(`${n} at ${o}`),this.name="TranspileError",this.line=t.line,this.column=t.column,this.source=r,this.filename=s}},_=class extends P{constructor(n,t,r,s){super(n,t,r,s),this.name="SyntaxError"}formatWithContext(n=2){if(!this.source)return this.message;let t=this.source.split(`
|
|
3
3
|
`),r=this.line-1,s=Math.max(0,r-n),o=Math.min(t.length-1,r+n),i=[],a=String(o+1).length;for(let l=s;l<=o;l++){let c=String(l+1).padStart(a),p=l===r?">":" ";if(i.push(`${p} ${c} | ${t[l]}`),l===r){let m=" ".repeat(a+4+this.column);i.push(`${m}^ ${this.message.split(" at ")[0]}`)}}return i.join(`
|
|
4
|
-
`)}};function
|
|
5
|
-
`);if(S.length===0)return
|
|
6
|
-
${p}${
|
|
7
|
-
`),o=[],i=!1;for(let a=0;a<s.length;a++){let l=s[a],c=a>0?s[a-1]:"";if(i){o.push(l),l.includes("*/")&&(i=!1);continue}let p=l.indexOf("/*"),m=l.indexOf("*/");if(p!==-1&&(m===-1||m<p)){i=!0,o.push(l);continue}if(a>0&&n.test(l)){let u=c.replace(/\/\/.*$/,"").replace(/\/\*.*\*\/\s*$/,"");if(!t.test(u)&&!r.test(u)){let d=l.match(/^(\s*)/),g=d?d[1]:"",
|
|
4
|
+
`)}};function q(e){return{depth:e.depth+1,locals:new Map,parent:e,parameters:e.parameters,atoms:e.atoms,warnings:e.warnings,source:e.source,filename:e.filename,options:e.options,helpers:e.helpers,helperSteps:e.helperSteps,helperTransforming:e.helperTransforming}}function I(e){return e.loc?{line:e.loc.start.line,column:e.loc.start.column}:{line:1,column:0}}function Gn(e,n){let t=e.match(n);if(!t)return null;let r=t.index+t[0].length-1,s=1,o=r+1;for(;o<e.length&&s>0;)e[o]==="{"?s++:e[o]==="}"&&s--,o++;if(s!==0)return null;let i=e.slice(r,o),a=[t[0].slice(0,-1)+i,i];return a.index=t.index,a}function Ke(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\btry\s*\{/);if(r){let o=t+r[0].length-1+1,i=1,a=o;for(;a<e.length&&i>0;){let c=e[a];c==="{"?i++:c==="}"&&i--,a++}if(i!==0){n+=e[t],t++;continue}if(e.slice(a).match(/^\s*(catch|finally)\b/))n+=e.slice(t,a),t=a;else{let c=e.slice(o,a-1);n+=`try {${c}} catch (__try_err) { return new (__tjs?.MonadicError ?? Error)(__try_err?.message || String(__try_err), 'try', undefined, undefined, __tjs?.getStack?.()) }`,t=a}}else n+=e[t],t++}return n}function Ye(e){let n=[],t="",r=0,s=0;for(;r<e.length;){let o=e.slice(r).match(/^\bwasm\s*\{/);if(o){let i=r,a=r+o[0].length,l=1,c=a;for(;c<e.length&&l>0;){let b=e[c];b==="{"?l++:b==="}"&&l--,c++}if(l!==0){t+=e[r],r++;continue}let p=e.slice(a,c-1),m,u=c,d=e.slice(c).match(/^\s*fallback\s*\{/);if(d){let b=c+d[0].length;l=1;let v=b;for(;v<e.length&&l>0;){let j=e[v];j==="{"?l++:j==="}"&&l--,v++}l===0&&(m=e.slice(b,v-1),u=v)}let y=Yn(p).map(b=>{let v=Xn(e,i,b);return v?`${b}: ${v}`:b}),w={id:`__tjs_wasm_${s}`,body:p,fallback:m,captures:y,start:i,end:u};n.push(w);let E=m??p,S=y.map(b=>b.split(":")[0].trim()),h=S.length>0?S.join(", "):"",T=S.length>0?`globalThis.${w.id}(${h})`:`globalThis.${w.id}()`,$=`(globalThis.${w.id} ? ${T} : (() => {${E}})())`;t+=$,r=u,s++}else t+=e[r],r++}return{source:t,blocks:n}}function Xe(e){let n=[],t="",r=0;for(;r<e.length;){let s=/^\b(export\s+)?wasm\s+function\s+(\w+)\s*\(/,o=e.slice(r).match(s);if(!o){t+=e[r],r++;continue}let i=!!o[1],a=o[2],l=r,c=r+o[0].length,p=1,m=c;for(;m<e.length&&p>0;)e[m]==="("?p++:e[m]===")"&&p--,m++;if(p!==0){t+=e[r],r++;continue}let u=e.slice(c,m-1);if(u.match(/^\s*!/))throw new _(`Unsafe wasm functions (with \`!\` marker) are reserved for a future phase. Remove the bang from \`wasm function ${a}\` to declare it as a regular (pure) wasm function, or wait until the unsafe variant is implemented.`,J(e,l));let g,y=m,w=e.slice(m).match(/^\s*:\s*(\w+)/);w&&(g=w[1],y=m+w[0].length);let E=e.slice(y).match(/^\s*\{/);if(!E){t+=e[r],r++;continue}let S=y+E[0].length,h=1,T=S;for(;T<e.length&&h>0;)e[T]==="{"?h++:e[T]==="}"&&h--,T++;if(h!==0){t+=e[r],r++;continue}let $=e.slice(S,T-1),b=Hn(u),v=`__tjs_wasm_${a}`,j={id:v,name:a,returnType:g,body:$,captures:b,start:l,end:T};n.push(j);let A=b.map(R=>R.split(":")[0].trim()),C=`${i?"export ":""}function ${a}(${A.join(", ")}) { return globalThis.${v}(${A.join(", ")}) }`;t+=C,r=T}return{source:t,blocks:n}}function Qe(e,n){let{loader:t,importerPath:r}=n;if(!t)return{source:e,blocks:[]};let s=[],o=new Set;function i(c,p){if(!o.has(c.id)){s.push(c),o.add(c.id);for(let[m,u]of p){if(m===c.name||o.has(u.id))continue;new RegExp(`\\b${m}\\s*\\(`).test(c.body)&&i(u,p)}}}let a=/^(\s*)import\s*\{([^}]*?)\}\s*from\s*(['"])([^'"]+)\3\s*;?\s*$/gm;return{source:e.replace(a,(c,p,m,u,d)=>{let g=t.load(d,r);if(!g)return c;let y=new Map;for(let $ of g.parseResult.wasmBlocks)$.name&&y.set($.name,$);if(y.size===0)return c;let w=m.split(",").map($=>$.trim()).filter($=>$.length>0),E=[],S=[];for(let $ of w){let b=$.match(/^(\w+)(?:\s+as\s+(\w+))?$/);if(!b){S.push($);continue}let v=b[1],j=b[2]??b[1],A=y.get(v);if(!A){S.push($);continue}i(A,y);let M=A.captures.map(C=>C.split(":")[0].trim());E.push(`function ${j}(${M.join(", ")}) { return globalThis.${A.id}(${M.join(", ")}) }`)}let h=E.join(`
|
|
5
|
+
`);if(S.length===0)return h?`${p}${h}`:`${p}`;let T=`${p}import { ${S.join(", ")} } from '${d}'`;return h?`${T}
|
|
6
|
+
${p}${h}`:T}),blocks:s}}function Hn(e){let n=e.trim();return n?n.split(",").map(t=>t.trim()).filter(t=>t.length>0):[]}function Kn(e){return e.startsWith("f32x4_")||e.startsWith("v128_")}function Yn(e){let n=e.replace(/\/\/[^\n]*/g,"").replace(/\/\*[\s\S]*?\*\//g,""),t=new Set,r=/\.([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,s;for(;(s=r.exec(n))!==null;)t.add(s[1]);let o=/(?<!\.)(\b[a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,i=new Set;for(;(s=o.exec(n))!==null;)i.add(s[1]);for(let u of t){if(!i.has(u))continue;let d=new RegExp(`(?<!\\.)\\b${u}\\b`,"g"),g=new RegExp(`\\.${u}\\b`,"g"),y=n.match(d)?.length||0,w=n.match(g)?.length||0;y<=w&&i.delete(u)}let a=new Set,l=/\b(?:let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;for(;(s=l.exec(n))!==null;)a.add(s[1]);let c=/\bfor\s*\(\s*(?:let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;for(;(s=c.exec(n))!==null;)a.add(s[1]);let p=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","wasmBuffer"]),m=[];for(let u of i)!a.has(u)&&!p.has(u)&&!Kn(u)&&m.push(u);return m.sort()}function Xn(e,n,t){let r=e.slice(0,n),s=/function\s+\w+\s*\(([^)]*)\)\s*(?:->.*?)?\s*\{[^}]*$/,o=r.match(s);if(!o){let i=/(?:const|let|var)?\s*\w+\s*=\s*(?:async\s*)?\(([^)]*)\)\s*(?:=>|->)?\s*\{[^}]*$/,a=r.match(i);return a?Je(a[1],t):void 0}return Je(o[1],t)}function Je(e,n){let t=e.split(",").map(r=>r.trim());for(let r of t){let s=r.match(new RegExp(`^${n}\\s*:\\s*([A-Za-z][A-Za-z0-9]*)`));if(s)return s[1];let o=r.match(new RegExp(`^${n}\\s*=\\s*(Float32Array|Float64Array|Int32Array|Uint8Array|Int8Array|Int16Array|Uint16Array|Uint32Array)`));if(o)return o[1]}}function et(e){let n=`([\\w][\\w.\\[\\]()]*|null|undefined|true|false|\\d+(?:\\.\\d+)?|'[^']*'|"[^"]*")`,t=new RegExp(n+"\\s+IsNot\\s+"+n,"g");e=e.replace(t,"IsNot($1, $2)");let r=new RegExp(n+"\\s+Is\\s+"+n,"g");return e=e.replace(r,"Is($1, $2)"),e}function tt(e){let n=/^[\s]*[([`]/,t=/[{([,;:+\-*/%=&|?<>!~^]\s*$|^\s*$/,r=/\b(return|throw|yield|await|case|default|extends|new|typeof|void|delete|in|of|instanceof)\s*$/,s=e.split(`
|
|
7
|
+
`),o=[],i=!1;for(let a=0;a<s.length;a++){let l=s[a],c=a>0?s[a-1]:"";if(i){o.push(l),l.includes("*/")&&(i=!1);continue}let p=l.indexOf("/*"),m=l.indexOf("*/");if(p!==-1&&(m===-1||m<p)){i=!0,o.push(l);continue}if(a>0&&n.test(l)){let u=c.replace(/\/\/.*$/,"").replace(/\/\*.*\*\/\s*$/,"");if(!t.test(u)&&!r.test(u)){let d=l.match(/^(\s*)/),g=d?d[1]:"",y=l.slice(g.length);o.push(g+";"+y);continue}}o.push(l)}return o.join(`
|
|
8
8
|
`)}function Qn(e){let n=[],t=0,r="normal",s=[];for(;t<e.length;){let i=e[t],a=e[t+1];switch(r){case"single-string":if(i==="\\"&&t+1<e.length){t+=2;continue}i==="'"&&(r="normal"),t++;continue;case"double-string":if(i==="\\"&&t+1<e.length){t+=2;continue}i==='"'&&(r="normal"),t++;continue;case"template-string":if(i==="\\"&&t+1<e.length){t+=2;continue}if(i==="$"&&a==="{"){t+=2,s.push(1),r="normal";continue}i==="`"&&(r="normal"),t++;continue;case"line-comment":i===`
|
|
9
|
-
`&&(r="normal"),t++;continue;case"block-comment":if(i==="*"&&a==="/"){t+=2,r="normal";continue}t++;continue;case"regex":if(i==="\\"&&t+1<e.length){t+=2;continue}if(i==="["){for(t++;t<e.length&&e[t]!=="]";)e[t]==="\\"&&t+1<e.length?t+=2:t++;t<e.length&&t++;continue}if(i==="/"){for(t++;t<e.length&&/[gimsuy]/.test(e[t]);)t++;r="normal";continue}t++;continue;case"normal":if(s.length>0){if(i==="{")s[s.length-1]++;else if(i==="}"&&(s[s.length-1]--,s[s.length-1]===0)){s.pop(),t++,r="template-string";continue}}if(i==="'"){t++,r="single-string";continue}if(i==='"'){t++,r="double-string";continue}if(i==="`"){t++,r="template-string";continue}if(i==="/"&&a==="/"){t+=2,r="line-comment";continue}if(i==="/"&&a==="*"){t+=2,r="block-comment";continue}if(i==="/"){let l=t-1;for(;l>=0&&/\s/.test(e[l]);)l--;let c=l>=0?e[l]:"";if(!c||/[=(!,;:{[&|?+\-*%<>~^]/.test(c)||l>=5&&/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)$/.test(e.slice(Math.max(0,l-10),l+1))){t++,r="regex";continue}}if(i==="t"&&e.slice(t,t+6)==="typeof"&&(t===0||!/[\w$]/.test(e[t-1]))&&/\s/.test(e[t+6]??"")){let l=t+6;for(;l<e.length&&/\s/.test(e[l]);)l++;if(l<e.length&&/[a-zA-Z_$]/.test(e[l])){let c=l;for(;l<e.length&&/[\w$]/.test(e[l]);)l++;for(;l<e.length;)if(e[l]==="."&&/[a-zA-Z_$]/.test(e[l+1]??""))for(l++;l<e.length&&/[\w$]/.test(e[l]);)l++;else if(e[l]==="?"&&e[l+1]==="."&&/[a-zA-Z_$]/.test(e[l+2]??""))for(l+=2;l<e.length&&/[\w$]/.test(e[l]);)l++;else break;n.push({keywordStart:t,operandEnd:l,operand:e.slice(c,l)}),t=l;continue}}break}t++}if(n.length===0)return e;let o=e;for(let i=n.length-1;i>=0;i--){let a=n[i];o=o.slice(0,a.keywordStart)+`TypeOf(${a.operand})`+o.slice(a.operandEnd)}return o}function
|
|
10
|
-
`&&(r="normal"),t++;continue;case"block-comment":if(i==="*"&&a==="/"){t+=2,r="normal";continue}t++;continue;case"regex":if(i==="\\"&&t+1<e.length){t+=2;continue}if(i==="["){for(t++;t<e.length&&e[t]!=="]";)e[t]==="\\"&&t+1<e.length?t+=2:t++;t<e.length&&t++;continue}if(i==="/"){for(t++;t<e.length&&/[gimsuy]/.test(e[t]);)t++;r="normal";continue}t++;continue;case"normal":if(s.length>0){if(i==="{")s[s.length-1]++;else if(i==="}"&&(s[s.length-1]--,s[s.length-1]===0)){s.pop(),t++,r="template-string";continue}}if(i==="'"){t++,r="single-string";continue}if(i==='"'){t++,r="double-string";continue}if(i==="`"){t++,r="template-string";continue}if(i==="/"&&a==="/"){t+=2,r="line-comment";continue}if(i==="/"&&a==="*"){t+=2,r="block-comment";continue}if(i==="/"){let l=t-1;for(;l>=0&&/\s/.test(e[l]);)l--;let c=l>=0?e[l]:"";if(!c||/[=(!,;:{[&|?+\-*%<>~^]/.test(c)||l>=5&&/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)$/.test(e.slice(Math.max(0,l-10),l+1))){t++,r="regex";continue}}if(i==="="&&a==="="&&e[t+2]!=="="&&e[t-1]!=="!"){n.push({pos:t,op:"=="}),t+=2;continue}if(i==="!"&&a==="="&&e[t+2]!=="="){n.push({pos:t,op:"!="}),t+=2;continue}break}t++}if(n.length===0)return e;let o=e;for(let i=n.length-1;i>=0;i--){let{pos:a,op:l}=n[i],c=l==="=="?"Eq":"NotEq",p=er(o,a),m=tr(o,a+2),u=o.slice(p,a).trim(),d=o.slice(a+2,m).trim();if(u&&d){let g=o.slice(0,p),
|
|
11
|
-
`,i);a===-1&&(a=e.length);let l=e.slice(i,a).trim();if(l){let c=
|
|
12
|
-
`||e[r-1]===";"||e[r-1]==="}"){let
|
|
9
|
+
`&&(r="normal"),t++;continue;case"block-comment":if(i==="*"&&a==="/"){t+=2,r="normal";continue}t++;continue;case"regex":if(i==="\\"&&t+1<e.length){t+=2;continue}if(i==="["){for(t++;t<e.length&&e[t]!=="]";)e[t]==="\\"&&t+1<e.length?t+=2:t++;t<e.length&&t++;continue}if(i==="/"){for(t++;t<e.length&&/[gimsuy]/.test(e[t]);)t++;r="normal";continue}t++;continue;case"normal":if(s.length>0){if(i==="{")s[s.length-1]++;else if(i==="}"&&(s[s.length-1]--,s[s.length-1]===0)){s.pop(),t++,r="template-string";continue}}if(i==="'"){t++,r="single-string";continue}if(i==='"'){t++,r="double-string";continue}if(i==="`"){t++,r="template-string";continue}if(i==="/"&&a==="/"){t+=2,r="line-comment";continue}if(i==="/"&&a==="*"){t+=2,r="block-comment";continue}if(i==="/"){let l=t-1;for(;l>=0&&/\s/.test(e[l]);)l--;let c=l>=0?e[l]:"";if(!c||/[=(!,;:{[&|?+\-*%<>~^]/.test(c)||l>=5&&/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)$/.test(e.slice(Math.max(0,l-10),l+1))){t++,r="regex";continue}}if(i==="t"&&e.slice(t,t+6)==="typeof"&&(t===0||!/[\w$]/.test(e[t-1]))&&/\s/.test(e[t+6]??"")){let l=t+6;for(;l<e.length&&/\s/.test(e[l]);)l++;if(l<e.length&&/[a-zA-Z_$]/.test(e[l])){let c=l;for(;l<e.length&&/[\w$]/.test(e[l]);)l++;for(;l<e.length;)if(e[l]==="."&&/[a-zA-Z_$]/.test(e[l+1]??""))for(l++;l<e.length&&/[\w$]/.test(e[l]);)l++;else if(e[l]==="?"&&e[l+1]==="."&&/[a-zA-Z_$]/.test(e[l+2]??""))for(l+=2;l<e.length&&/[\w$]/.test(e[l]);)l++;else break;n.push({keywordStart:t,operandEnd:l,operand:e.slice(c,l)}),t=l;continue}}break}t++}if(n.length===0)return e;let o=e;for(let i=n.length-1;i>=0;i--){let a=n[i];o=o.slice(0,a.keywordStart)+`TypeOf(${a.operand})`+o.slice(a.operandEnd)}return o}function nt(e){e=Qn(e);let n=[],t=0,r="normal",s=[];for(;t<e.length;){let i=e[t],a=e[t+1];switch(r){case"single-string":if(i==="\\"&&t+1<e.length){t+=2;continue}i==="'"&&(r="normal"),t++;continue;case"double-string":if(i==="\\"&&t+1<e.length){t+=2;continue}i==='"'&&(r="normal"),t++;continue;case"template-string":if(i==="\\"&&t+1<e.length){t+=2;continue}if(i==="$"&&a==="{"){t+=2,s.push(1),r="normal";continue}i==="`"&&(r="normal"),t++;continue;case"line-comment":i===`
|
|
10
|
+
`&&(r="normal"),t++;continue;case"block-comment":if(i==="*"&&a==="/"){t+=2,r="normal";continue}t++;continue;case"regex":if(i==="\\"&&t+1<e.length){t+=2;continue}if(i==="["){for(t++;t<e.length&&e[t]!=="]";)e[t]==="\\"&&t+1<e.length?t+=2:t++;t<e.length&&t++;continue}if(i==="/"){for(t++;t<e.length&&/[gimsuy]/.test(e[t]);)t++;r="normal";continue}t++;continue;case"normal":if(s.length>0){if(i==="{")s[s.length-1]++;else if(i==="}"&&(s[s.length-1]--,s[s.length-1]===0)){s.pop(),t++,r="template-string";continue}}if(i==="'"){t++,r="single-string";continue}if(i==='"'){t++,r="double-string";continue}if(i==="`"){t++,r="template-string";continue}if(i==="/"&&a==="/"){t+=2,r="line-comment";continue}if(i==="/"&&a==="*"){t+=2,r="block-comment";continue}if(i==="/"){let l=t-1;for(;l>=0&&/\s/.test(e[l]);)l--;let c=l>=0?e[l]:"";if(!c||/[=(!,;:{[&|?+\-*%<>~^]/.test(c)||l>=5&&/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)$/.test(e.slice(Math.max(0,l-10),l+1))){t++,r="regex";continue}}if(i==="="&&a==="="&&e[t+2]!=="="&&e[t-1]!=="!"){n.push({pos:t,op:"=="}),t+=2;continue}if(i==="!"&&a==="="&&e[t+2]!=="="){n.push({pos:t,op:"!="}),t+=2;continue}break}t++}if(n.length===0)return e;let o=e;for(let i=n.length-1;i>=0;i--){let{pos:a,op:l}=n[i],c=l==="=="?"Eq":"NotEq",p=er(o,a),m=tr(o,a+2),u=o.slice(p,a).trim(),d=o.slice(a+2,m).trim();if(u&&d){let g=o.slice(0,p),y=o.slice(m),E=/[a-zA-Z0-9_$]$/.test(g)?" ":"";o=`${g}${E}${c}(${u}, ${d})${y}`}}return o}function er(e,n){let t=n-1;for(;t>=0&&/\s/.test(e[t]);)t--;if(t<0)return 0;let r=0,s=!1,o="";for(;t>=0;){let i=e[t],a=t>0?e[t-1]:"";if(s){i===o&&a!=="\\"&&(s=!1),t--;continue}if((i==='"'||i==="'"||i==="`")&&a!=="\\"){s=!0,o=i,t--;continue}if(i===")"||i==="]"||i==="}"){r++,t--;continue}if(i==="("||i==="["){if(r>0){r--,t--;continue}return t+1}if(i==="{"){if(r>0){r--,t--;continue}return t+1}if(r>0){t--;continue}if(i===";")return t+1;if(/[a-z]/.test(i)){let l=t+1,c=t;for(;c>0&&/[a-z]/i.test(e[c-1]);)c--;let p=e.slice(c,l),m=c>0?e[c-1]:"";if(!/[a-zA-Z0-9_$]/.test(m)){if(["return","throw","case","typeof","void","delete","await","yield"].includes(p))return l;if(p==="new")return c}}if(i===">"&&a==="="||i==="="&&a!=="="&&a!=="!"&&a!=="<"&&a!==">"||i==="&"&&a==="&"||i==="|"&&a==="|"||i==="?"||i===":"||i===",")return t+1;t--}return 0}function tr(e,n){let t=n;for(;t<e.length&&/\s/.test(e[t]);)t++;if(t>=e.length)return e.length;let r=0,s=!1,o="";for(;t<e.length;){let i=e[t],a=t+1<e.length?e[t+1]:"";if(s){i===o&&e[t-1]!=="\\"&&(s=!1),t++;continue}if((i==='"'||i==="'"||i==="`")&&e[t-1]!=="\\"){s=!0,o=i,t++;continue}if(i==="("||i==="["||i==="{"){r++,t++;continue}if(i===")"||i==="]"||i==="}"){if(r>0){r--,t++;continue}return t}if(r>0){t++;continue}if(i===";"||i==="&"&&a==="&"||i==="|"&&a==="|"||i==="?"||i===":"||i===","||(i==="="||i==="!")&&a==="="&&e[t+2]!=="=")return t;t++}return e.length}function rt(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\bType\s+([A-Z_][a-zA-Z0-9_]*)\s*/);if(r){let s=r[1],o=t+r[0].length,i=s,a=!1,l=e.slice(o).match(/^(['"`])([^]*?)\1\s*/);if(l){let u=o+l[0].length,d=e[u],g=d===void 0||u>=e.length||d!=="="&&d!=="{";if(d==="="||d==="{")i=l[2],a=!0,o=u;else if(g){let y=l[0].trim(),w=l[0].slice(y.length);n+=`const ${s} = Type('${s}', ${y})${w}`,t=u;continue}}let c,p=o,m=e.slice(o).match(/^=\s*/);if(m){o+=m[0].length;let u=e.slice(o).match(/^(\+?\d+(?:\.\d+)?|['"`][^'"`]*['"`]|\{[^}]*\}|\[[^\]]*\]|true|false|null)/);if(u){c=u[0],o+=u[0].length,p=o;let d=e.slice(o).match(/^\s*/);d&&(o+=d[0].length)}}if(e[o]==="{"){let u=o+1,d=1,g=u;for(;g<e.length&&d>0;){let $=e[g];$==="{"?d++:$==="}"&&d--,g++}if(d!==0){n+=e[t],t++;continue}let y=e.slice(u,g-1).trim(),w=g,E=y.match(/description\s*:\s*(['"`])([^]*?)\1/);E&&!a&&(i=E[2]);let S,h=y.match(/example\s*:\s*/);if(h){let $=h.index+h[0].length,b=Et(y,$);b&&(S=b.value.trim())}let T=y.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/);if(T&&S){let $=T[1].trim(),b=T[2].trim(),v=c?`, ${c}`:"";n+=`const ${s} = Type('${i}', (${$}) => { if (!globalThis.__tjs?.validate(${$}, globalThis.__tjs?.infer(${S}))) return false; ${b} }, ${S}${v})`}else if(T){let $=T[1].trim(),b=T[2].trim(),v=c?`, undefined, ${c}`:"";n+=`const ${s} = Type('${i}', (${$}) => { ${b} }${v})`}else if(S){let $=c?`, ${c}`:"";n+=`const ${s} = Type('${i}', undefined, ${S}${$})`}else c?n+=`const ${s} = Type('${i}', ${c})`:n+=`const ${s} = Type('${i}')`;t=w;continue}else if(c){n+=`const ${s} = Type('${i}', ${c})`,t=p;continue}else if(!l){let u=e.slice(o).match(/^(['"`][^]*?['"`]|\+?\d+(?:\.\d+)?|true|false|null|\{[^]*?\}|\[[^]*?\])/);if(u){let d=u[0];n+=`const ${s} = Type('${s}', ${d})`,t=o+u[0].length;continue}}}n+=e[t],t++}return n}function st(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\bFunctionPredicate\s+([A-Z_][a-zA-Z0-9_]*)\s*(?:<([^>]+)>)?\s*/);if(r){let s=r[1],o=r[2],i=t+r[0].length;if(e[i]==="{"){let a=1,l=i+1;for(;l<e.length&&a>0;)e[l]==="{"?a++:e[l]==="}"&&a--,l++;if(a===0){let c=e.slice(i+1,l-1).trim(),p=Gn(c,/params\s*:\s*\{/),m=c.match(/returns\s*:\s*(.+?)(?:\n|$)/),u=c.match(/returnContract\s*:\s*['"](\w+)['"]/),d=c.match(/description\s*:\s*(['"])([^]*?)\1/),g=[];p&&g.push(`params: ${p[1]}`),m&&g.push(`returns: ${m[1].trim()}`),u&&g.push(`returnContract: '${u[1]}'`);let y=d?d[2]:s;if(o){let w=o.split(",").map(S=>{let h=S.trim().split("=").map(T=>T.trim());if(h.length===2){let T=h[1]==="any"||h[1]==="undefined"?"null":h[1];return`['${h[0]}', ${T}]`}return`'${h[0]}'`}),E=o.split(",").map(S=>S.trim().split("=")[0].trim());n+=`const ${s} = FunctionPredicate('${y}', [${w.join(", ")}], (${E.join(", ")}) => ({ ${g.join(", ")} }))`}else n+=`const ${s} = FunctionPredicate('${y}', { ${g.join(", ")} })`;t=l;continue}}if(e[i]==="("){let a=1,l=i+1;for(;l<e.length&&a>0;)e[l]==="("?a++:e[l]===")"&&a--,l++;if(a===0){let c=e.slice(i+1,l-1).trim(),p=c.indexOf(",");if(p!==-1){let m=c.slice(0,p).trim(),u=c.slice(p+1).trim();n+=`const ${s} = FunctionPredicate(${u}, ${m})`}else n+=`const ${s} = FunctionPredicate('${s}', ${c})`;t=l;continue}}}n+=e[t],t++}return n}function it(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\bGeneric\s+([A-Z][a-zA-Z0-9_]*)\s*<([^>]+)>\s*\{/);if(r){let s=r[1],o=r[2],a=t+r[0].length-1+1,l=1,c=a;for(;c<e.length&&l>0;){let S=e[c];S==="{"?l++:S==="}"&&l--,c++}if(l!==0){n+=e[t],t++;continue}let p=e.slice(a,c-1).trim(),m=c,u=o.split(",").map(S=>{let h=S.trim().split("=").map(T=>T.trim());if(h.length===2){let T=h[1]==="any"||h[1]==="undefined"?"null":h[1];return`['${h[0]}', ${T}]`}return`'${h[0]}'`}),d=p,g=d.search(/\bdeclaration\s*\{/);if(g!==-1){let S=d.indexOf("{",g),h=1,T=S+1;for(;T<d.length&&h>0;)d[T]==="{"?h++:d[T]==="}"&&h--,T++;d=d.slice(0,g)+d.slice(T)}let y=d.match(/description\s*:\s*(['"`])([^]*?)\1/),w=d.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/),E=y?y[2]:s;if(w){let S=w[1].trim().split(",").map(v=>v.trim()),h=w[2].trim(),T=S[0]||"x",$=S.slice(1),b=$.map(v=>`check${v}`);$.forEach((v,j)=>{h=h.replace(new RegExp(`\\b${v}\\s*\\(`,"g"),`${b[j]}(`)}),n+=`const ${s} = Generic([${u.join(", ")}], (${T}, ${b.join(", ")}) => { ${h} }, '${E}')`}else n+=`const ${s} = Generic([${u.join(", ")}], () => true, '${E}')`;t=m;continue}n+=e[t],t++}return n}function ot(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\bUnion\s+([A-Z][a-zA-Z0-9_]*)\s+(['"`])([^]*?)\2\s*/);if(r){let s=r[1],o=r[3],i=t+r[0].length;if(e[i]==="{"){let a=i+1,l=1,c=a;for(;c<e.length&&l>0;){let d=e[c];d==="{"?l++:d==="}"&&l--,c++}if(l!==0){n+=e[t],t++;continue}let p=e.slice(a,c-1).trim(),m=c,u=Ze(p);n+=`const ${s} = Union('${o}', [${u.join(", ")}])`,t=m;continue}else{let a=e.indexOf(`
|
|
11
|
+
`,i);a===-1&&(a=e.length);let l=e.slice(i,a).trim();if(l){let c=Ze(l);n+=`const ${s} = Union('${o}', [${c.join(", ")}])`,t=a;continue}}}n+=e[t],t++}return n}function Ze(e){let n=[],t=e.split("|").map(r=>r.trim());for(let r of t)r&&n.push(r);return n}function at(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\bEnum\s+([A-Z][a-zA-Z0-9_]*)\s+(['"`])([^]*?)\2\s*\{/);if(r){let s=r[1],o=r[3],a=t+r[0].length-1+1,l=1,c=a;for(;c<e.length&&l>0;){let g=e[c];g==="{"?l++:g==="}"&&l--,c++}if(l!==0){n+=e[t],t++;continue}let p=e.slice(a,c-1).trim(),m=c,d=nr(p).map(([g,y])=>`${g}: ${y}`).join(", ");n+=`const ${s} = Enum('${o}', { ${d} })`,t=m;continue}n+=e[t],t++}return n}function nr(e){let n=[],t=0,r=e.split(/[\n,]/).map(s=>s.trim()).filter(s=>s&&!s.startsWith("//"));for(let s of r){let o=s.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:=\s*(.+))?$/);if(o){let i=o[1],a=o[2]?.trim();if(a!==void 0){n.push([i,a]);let l=Number(a);isNaN(l)||(t=l+1)}else n.push([i,String(t)]),t++}}return n}function lt(e){let n=new Map,t="",r=0;for(;r<e.length;){let s=e.slice(r),o=s.match(/^(\s*)extend\s+([A-Z]\w*)\s*\{/);if(!o){if(r===0||e[r-1]===`
|
|
12
|
+
`||e[r-1]===";"||e[r-1]==="}"){let h=s.match(/^(\s*)extend\s+([A-Z]\w*)\s*\{/)}t+=e[r],r++;continue}let i=o[1],a=o[2],l=r+o[0].length-1,c=se(e,l),p=e.slice(l+1,c-1).trim(),m=[],u=0,d=e.slice(l+1,c-1);for(;u<d.length;){let h=d.slice(u).match(/^(\s*)(async\s+)?(\w+)\s*\(/);if(!h){u++;continue}let T=h[1],$=!!h[2],b=h[3],v=u+h[0].length-1,j=1,A=v+1;for(;A<d.length&&j>0;)d[A]==="("&&j++,d[A]===")"&&j--,A++;let M=d.slice(v+1,A-1),C=A;for(;C<d.length&&/\s/.test(d[C]);)C++;if(d[C]==="="&&d[C+1]===">"){let Z=J(e,l+1+u);throw new _(`Arrow functions are not allowed in extend blocks (method '${b}' in extend ${a}). Use regular function syntax instead, as extension methods need 'this' binding.`,Z)}if(d[C]!=="{"){u++;continue}let R=se(d,C),L=d.slice(u,R).trim(),ee=M.split(",").map(Z=>Z.trim()).filter(Z=>Z.length>0).map(Z=>{let we=Z.match(/^(\w+)\s*:\s*(.+)$/);return we?`${we[1]} = ${we[2]}`:Z}).join(", "),te=$?"async ":"",ne=d.slice(C+1,R-1);m.push({name:b,isAsync:$,fullText:`${b}: ${te}function(${ee}) {${ne}}`}),u=R}let g=!n.has(a);g&&n.set(a,new Set);let y=n.get(a);for(let S of m)y.add(S.name);let w=m.map(S=>` ${S.fullText}`).join(`,
|
|
13
13
|
`),E;g?E=`${i}const __ext_${a} = {
|
|
14
14
|
${w}
|
|
15
15
|
${i}}
|
|
@@ -17,38 +17,38 @@ ${i}}
|
|
|
17
17
|
${w}
|
|
18
18
|
${i}})
|
|
19
19
|
`;for(let S of m)E+=`${i}if (__tjs?.registerExtension) { __tjs.registerExtension('${a}', '${S.name}', __ext_${a}.${S.name}) }
|
|
20
|
-
`;t+=E,r=c}return r<=e.length&&t.length<e.length,{source:t,extensions:n}}function
|
|
21
|
-
`?(t++,r=0):r++;return{line:t,column:r}}function
|
|
22
|
-
`&&(o=!1),r++;continue}if(i){if(a==="*"&&l==="/"){i=!1,r+=2;continue}r++;continue}if(s){if(a==="\\"){r+=2;continue}a===s&&(s=!1),r++;continue}if(a==="/"&&l==="/"){o=!0,r+=2;continue}if(a==="/"&&l==="*"){i=!0,r+=2;continue}if(a==="'"||a==='"'||a==="`"){s=a,r++;continue}a==="{"&&t++,a==="}"&&t--,r++}return r}function
|
|
23
|
-
${w}${
|
|
20
|
+
`;t+=E,r=c}return r<=e.length&&t.length<e.length,{source:t,extensions:n}}function ct(e,n){if(n.size===0)return e;let t=new Map;for(let[s,o]of n)for(let i of o)t.has(i)||t.set(i,[]),t.get(i).push(s);let r=e;for(let[s,o]of t){if(!o.includes("String"))continue;let i=new RegExp(`('(?:[^'\\\\]|\\\\.)*')\\.(${s})\\((\\))?`,"g");r=r.replace(i,(c,p,m,u)=>u?`__ext_String.${m}.call(${p})`:`__ext_String.${m}.call(${p}, `);let a=new RegExp(`("(?:[^"\\\\]|\\\\.)*")\\.(${s})\\((\\))?`,"g");r=r.replace(a,(c,p,m,u)=>u?`__ext_String.${m}.call(${p})`:`__ext_String.${m}.call(${p}, `);let l=new RegExp("(`(?:[^`\\\\]|\\\\.)*`)\\."+s+"\\((\\))?","g");r=r.replace(l,(c,p,m)=>m?`__ext_String.${s}.call(${p})`:`__ext_String.${s}.call(${p}, `)}for(let[s,o]of t){if(!o.includes("Array"))continue;let i=`].${s}(`,a=0,l;for(;(l=r.indexOf(i,a))!==-1;){let c=1,p=l-1,m=!1;for(;p>=0&&c>0;){let u=r[p];m?u===m&&(p===0||r[p-1]!=="\\")&&(m=!1):(u==="]"&&c++,u==="["&&c--,(u==="'"||u==='"'||u==="`")&&(m=u)),p--}if(c===0){let u=r.slice(p+1,l+1),d=r.slice(0,p+1),g=r.slice(l+i.length);g[0]===")"?r=`${d}__ext_Array.${s}.call(${u})${g.slice(1)}`:r=`${d}__ext_Array.${s}.call(${u}, ${g}`}a=l+1}}for(let[s,o]of t){if(!o.includes("Number"))continue;let i=new RegExp(`(\\d+(?:\\.\\d+)?)\\.(${s})\\((\\))?`,"g");r=r.replace(i,(a,l,c,p)=>p?`__ext_Number.${c}.call(${l})`:`__ext_Number.${c}.call(${l}, `)}return r}function J(e,n){let t=1,r=0;for(let s=0;s<n&&s<e.length;s++)e[s]===`
|
|
21
|
+
`?(t++,r=0):r++;return{line:t,column:r}}function ut(e,n){let t=n.trim();return/^['"`]/.test(t)?`typeof ${e} === 'string'`:t==="true"||t==="false"?`typeof ${e} === 'boolean'`:t==="null"?`${e} === null`:t==="undefined"?`${e} === undefined`:t.startsWith("[")?`Array.isArray(${e})`:t.startsWith("{")?`(typeof ${e} === 'object' && ${e} !== null && !Array.isArray(${e}))`:/^\+\d+/.test(t)?`(typeof ${e} === 'number' && Number.isInteger(${e}) && ${e} >= 0)`:/^-?\d+\.\d+/.test(t)?`typeof ${e} === 'number'`:/^-?\d+$/.test(t)?`(typeof ${e} === 'number' && Number.isInteger(${e}))`:"true"}function fe(e){let n=e.trim();return/^['"`]/.test(n)?"string":n==="true"||n==="false"?"boolean":n==="null"?"null":n==="undefined"?"undefined":n.startsWith("[")?"array":n.startsWith("{")?"object":/^\+\d+/.test(n)?"non-negative-integer":/^-?\d+\.\d+/.test(n)?"number":/^-?\d+$/.test(n)?"integer":"any"}function je(e,n){let t=[],r=0,s="",o=!1;for(let a=0;a<e.length;a++){let l=e[a];if(!o&&(l==="'"||l==='"'||l==="`")){o=l,s+=l;continue}if(o){if(s+=l,l==="\\"){a++,a<e.length&&(s+=e[a]);continue}l===o&&(o=!1);continue}if(l==="("||l==="["||l==="{"){r++,s+=l;continue}if(l===")"||l==="]"||l==="}"){r--,s+=l;continue}if(l===","&&r===0){let c=Ge(s.trim(),n);c&&t.push(c),s="";continue}s+=l}let i=s.trim();if(i){let a=Ge(i,n);a&&t.push(a)}return t}function Ge(e,n){let t=e.replace(/^\/\*\s*unsafe\s*\*\/\s*/,"");if(t.startsWith("..."))return null;let r=t.indexOf("=");if(r===-1)return{name:t.trim(),defaultValue:"",required:!0};let s=t.slice(0,r).trim(),o=t.slice(r+1).trim();return{name:s,defaultValue:o,required:n.has(s)}}function se(e,n){let t=1,r=n+1,s=!1,o=!1,i=!1;for(;r<e.length&&t>0;){let a=e[r],l=r+1<e.length?e[r+1]:"";if(o){a===`
|
|
22
|
+
`&&(o=!1),r++;continue}if(i){if(a==="*"&&l==="/"){i=!1,r+=2;continue}r++;continue}if(s){if(a==="\\"){r+=2;continue}a===s&&(s=!1),r++;continue}if(a==="/"&&l==="/"){o=!0,r+=2;continue}if(a==="/"&&l==="*"){i=!0,r+=2;continue}if(a==="'"||a==='"'||a==="`"){s=a,r++;continue}a==="{"&&t++,a==="}"&&t--,r++}return r}function ft(e,n){let t=new Set,r=/(?:^|(?<=[\n;{}]))\s*(export\s+)?(async\s+)?function\s+(\w+)\s*\(/gm,s=new Map,o,i=[];for(;(o=r.exec(e))!==null;){let m=!!o[1],u=!!o[2],d=o[3],g=o.index,y=g,E=o[0].indexOf("function");E>=0&&(y=g+E),i.push({name:d,fullMatchStart:g,funcKeywordStart:y,exported:m,isAsync:u})}for(let m of i)s.has(m.name)||s.set(m.name,[]);let a=new Map;for(let m of i)a.set(m.name,(a.get(m.name)||0)+1);let l=new Set;for(let[m,u]of a)u>1&&l.add(m);if(l.size===0)return{source:e,polymorphicNames:t};for(let m of i){if(!l.has(m.name))continue;let u=e.indexOf("(",m.funcKeywordStart);if(u===-1)continue;let d=1,g=u+1;for(;g<e.length&&d>0;)e[g]==="("&&d++,e[g]===")"&&d--,g++;let y=g-1,w=e.slice(u+1,y),E=g;for(;E<e.length&&e[E]!=="{";)E++;if(E>=e.length)continue;let S=se(e,E),h=m.fullMatchStart;for(;h>0&&e[h-1]===" ";)h--;let T=s.get(m.name),$=je(w,n);if(w.includes("...")){let v=J(e,m.funcKeywordStart);throw new _(`Rest parameters are not supported in polymorphic function '${m.name}'. Use separate function names instead.`,v)}T.push({index:T.length+1,start:h,end:S,text:e.slice(h,S),exported:m.exported,isAsync:m.isAsync,params:$})}for(let[m,u]of s){if(u.length<2)continue;let d=u.filter(g=>g.isAsync).length;if(d>0&&d<u.length){let g=J(e,u[0].start);throw new _(`Polymorphic function '${m}': all variants must be either sync or async, not mixed.`,g)}for(let g=0;g<u.length;g++)for(let y=g+1;y<u.length;y++){let w=u[g],E=u[y];if(w.params.length!==E.params.length)continue;let S=!0;for(let h=0;h<w.params.length;h++){let T=w.params[h].defaultValue?fe(w.params[h].defaultValue):"any",$=E.params[h].defaultValue?fe(E.params[h].defaultValue):"any";if(T!==$){S=!1;break}}if(S){let h=J(e,E.start);throw new _(`Polymorphic function '${m}': variants ${g+1} and ${y+1} have ambiguous signatures (same parameter types at every position). Overloads must differ by arity or parameter types.`,h)}}}let c=[];for(let[m,u]of s)if(!(u.length<2))for(let d of u)c.push({name:m,variant:d});c.sort((m,u)=>u.variant.start-m.variant.start);let p=e;for(let{name:m,variant:u}of c){let d=u.isAsync?"async ":"",g=u.text.replace(new RegExp(`(?:export\\s+)?${d?d.replace(/\s+$/,"\\s+"):""}function\\s+${m}\\s*\\(`),`${d}function ${m}$$${u.index}(`);p=p.slice(0,u.start)+g+p.slice(u.end)}for(let[m,u]of s){if(u.length<2)continue;t.add(m);let d=u[0].isAsync,g=u.some(T=>T.exported),y=d?"async ":"",w=g?"export ":"",E=[...u].sort((T,$)=>{if(T.params.length!==$.params.length)return 0;let b=0,v=0;for(let j of T.params){let A=j.defaultValue?fe(j.defaultValue):"any";A==="non-negative-integer"?b+=3:A==="integer"?b+=2:A!=="any"&&(b+=1)}for(let j of $.params){let A=j.defaultValue?fe(j.defaultValue):"any";A==="non-negative-integer"?v+=3:A==="integer"?v+=2:A!=="any"&&(v+=1)}return v-b}),S=[];for(let T of E){let $=[`__args.length === ${T.params.length}`],b=[];for(let v=0;v<T.params.length;v++){let j=T.params[v];if(b.push(`__args[${v}]`),j.defaultValue){let A=ut(`__args[${v}]`,j.defaultValue);A!=="true"&&$.push(A)}}S.push(` if (${$.join(" && ")}) return ${m}$${T.index}(${b.join(", ")})`)}let h=`
|
|
23
|
+
${w}${y}function ${m}(...__args) {
|
|
24
24
|
${S.join(`
|
|
25
25
|
`)}
|
|
26
26
|
return __tjs.typeError('${m}', 'no matching overload', __args)
|
|
27
27
|
}
|
|
28
|
-
`;p+=
|
|
28
|
+
`;p+=h}return{source:p,polymorphicNames:t}}function pt(e){return e.replace(/(?<=^|[;\n{])\s*([A-Z][a-zA-Z0-9_]*)\s*=(?!=)/gm,(n,t)=>n.replace(t,`const ${t}`))}function mt(e,n=!1){let t=[],r=[],s="",o=0;for(;o<e.length;){let i=e.slice(o).match(/^\btest\s+/);if(i){let a=o,l=o+i[0].length,c,p=e.slice(l).match(/^(['"`])([^]*?)\1\s*/);if(p&&(c=p[2],l+=p[0].length),e[l]==="{"){let m=l+1,u=1,d=m,g=null,y=!1;for(;d<e.length&&u>0;){let w=e[d];if(y){y=!1,d++;continue}if(w==="\\"&&g){y=!0,d++;continue}if(g){w===g&&(g=null),d++;continue}if(w==="/"&&e[d+1]==="/"){let E=e.indexOf(`
|
|
29
29
|
`,d);d=E===-1?e.length:E+1;continue}if(w==="/"&&e[d+1]==="*"){let E=e.indexOf("*/",d+2);d=E===-1?e.length:E+2;continue}if(w==="'"||w==='"'||w==="`"){g=w,d++;continue}w==="{"?u++:w==="}"&&u--,d++}if(u===0){let w=e.slice(m,d-1).trim(),E=d,S=(e.slice(0,a).match(/\n/g)||[]).length+1;if(t.push({description:c,body:w,start:a,end:E,line:S}),!n)try{new Function(w)()}catch($){let b=c||`test at line ${S}`;r.push(`Test failed: ${b} (line ${S})
|
|
30
30
|
${$.message||$}`)}let T=(e.slice(a,E).match(/\n/g)||[]).length;s+=`
|
|
31
|
-
`.repeat(T),o=E;continue}}}s+=e[o],o++}return{source:s,tests:t,errors:r}}function
|
|
32
|
-
`&&
|
|
31
|
+
`.repeat(T),o=E;continue}}}s+=e[o],o++}return{source:s,tests:t,errors:r}}function dt(e,n){let t=new Set,r=/\bclass\s+(\w+)(\s+extends\s+\w+)?\s*\{/g,s,o=[];for(;(s=r.exec(e))!==null;){let a=s[1],l=s[2]?.trim()||"",c=s.index+s[0].length-1,p=se(e,c),m=e.slice(c,p);o.push({className:a,extendsClause:l,bodyStart:c,bodyEnd:p,body:m})}let i=e;for(let a=o.length-1;a>=0;a--){let{className:l,extendsClause:c,bodyStart:p,bodyEnd:m,body:u}=o[a],d=/\bconstructor\s*\(/g,g,y=[];for(;(g=d.exec(u))!==null;)y.push(g.index);if(y.length<2)continue;t.add(l);let w=[];for(let $=0;$<y.length;$++){let b=y[$],v=u.indexOf("(",b),j=1,A=v+1;for(;A<u.length&&j>0;)u[A]==="("&&j++,u[A]===")"&&j--,A++;let M=u.slice(v+1,A-1),C=A;for(;C<u.length&&u[C]!=="{";)C++;let R=se(u,C),L=u.slice(C+1,R-1);w.push({index:$+1,paramStr:M,bodyText:L,fullStart:b,fullEnd:R})}let E=u;for(let $=w.length-1;$>=1;$--){let b=w[$],v=b.fullStart;for(;v>0&&E[v-1]===" ";)v--;v>0&&E[v-1]===`
|
|
32
|
+
`&&v--,E=E.slice(0,v)+E.slice(b.fullEnd)}let S="";for(let $=1;$<w.length;$++){let b=w[$],v=je(b.paramStr,n);if(b.paramStr.includes("...")){let A=J(e,p+b.fullStart);throw new _(`Rest parameters are not supported in polymorphic constructors for '${l}'.`,A)}S+=`
|
|
33
33
|
function ${l}$ctor$${b.index}(${b.paramStr}) {`,S+=`
|
|
34
34
|
const __obj = Object.create(${l}.prototype)`,S+=`
|
|
35
35
|
;(function() {${b.bodyText}}).call(__obj)`,S+=`
|
|
36
36
|
return __obj`,S+=`
|
|
37
37
|
}
|
|
38
|
-
`}let
|
|
38
|
+
`}let h=[];for(let $=0;$<w.length;$++){let b=w[$],v=je(b.paramStr,n),j=[`a.length === ${v.length}`];for(let A=0;A<v.length;A++){let M=v[A];if(M.defaultValue){let C=ut(`a[${A}]`,M.defaultValue);C!=="true"&&j.push(C)}}if($===0)h.push(` if (${j.join(" && ")}) return Reflect.construct(t, a)`);else{let A=v.map((M,C)=>`a[${C}]`).join(", ");h.push(` if (${j.join(" && ")}) return ${l}$ctor$${b.index}(${A})`)}}S+=`
|
|
39
39
|
function ${l}$dispatch(t, a) {
|
|
40
|
-
`,S+=
|
|
40
|
+
`,S+=h.join(`
|
|
41
41
|
`)+`
|
|
42
42
|
`,S+=` return __tjs.typeError('${l}', 'no matching constructor', a)
|
|
43
43
|
`,S+=`}
|
|
44
|
-
`,i=i.slice(0,p)+E+i.slice(m);let T=p+E.length;i=i.slice(0,T)+S+i.slice(T)}return{source:i,polyCtorClasses:t}}function
|
|
45
|
-
`&&(r="normal"),t++):r==="block-comment"?(n+=o,o==="*"&&i==="/"?(n+=i,r="normal",t+=2):t++):r==="string-single"?(n+=o,o==="\\"?(n+=i||"",t+=2):(o==="'"&&(r="normal"),t++)):r==="string-double"?(n+=o,o==="\\"?(n+=i||"",t+=2):(o==='"'&&(r="normal"),t++)):r==="string-template"?(n+=o,o==="\\"?(n+=i||"",t+=2):o==="`"?(s--,r=s>0?"string-template":"normal",t++):o==="$"&&i==="{"?(n+=i,t+=2,r="normal"):t++):(n+=o,t++)}return n}function rr(e){let n=e.length-1;for(;n>=0&&/\s/.test(e[n]);)n--;if(n<0)return e.length;for(;n>=0;){let t=e[n];if(/[\w$]/.test(t)){for(;n>=0&&/[\w$]/.test(e[n]);)n--;if(n>=0&&e[n]==="."){n>=1&&e[n-1]==="?"?n-=2:n--;continue}return n+1}else if(t===")"){if(n=
|
|
46
|
-
`&&(s="normal"),r++;continue;case"block-comment":if(a==="*"&&l==="/"){r+=2,s="normal";continue}r++;continue;case"regex":if(a==="\\"&&r+1<e.length){r+=2;continue}if(a==="["){for(r++;r<e.length&&e[r]!=="]";)e[r]==="\\"&&r+1<e.length?r+=2:r++;r<e.length&&r++;continue}if(a==="/"){for(r++;r<e.length&&/[gimsuy]/.test(e[r]);)r++;s="normal";continue}r++;continue;case"normal":if(o.length>0){if(a==="{")o[o.length-1]++;else if(a==="}"&&(o[o.length-1]--,o[o.length-1]===0)){o.pop(),r++,s="template-string";continue}}if(a==="'"){r++,s="single-string";continue}if(a==='"'){r++,s="double-string";continue}if(a==="`"){r++,s="template-string";continue}if(a==="/"&&l==="/"){r+=2,s="line-comment";continue}if(a==="/"&&l==="*"){r+=2,s="block-comment";continue}if(a==="/"){let c=r-1;for(;c>=0&&/\s/.test(e[c]);)c--;let p=c>=0?e[c]:"";if(!p||/[=(!,;:{[&|?+\-*%<>~^]/.test(p)||c>=5&&/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)$/.test(e.slice(Math.max(0,c-10),c+1))){r++,s="regex";continue}}if(a==="l"&&e.slice(r,r+4)==="let "&&(r===0||!/[\w$]/.test(e[r-1]))){let c=r+4;for(;c<e.length&&/\s/.test(e[c]);)c++;if(c<e.length&&/[a-zA-Z_$]/.test(e[c])){let p=c;for(;c<e.length&&/[\w$]/.test(e[c]);)c++;let m=c,u=e.slice(p,m),d=c;for(;d<e.length&&/\s/.test(e[d]);)d++;if(d<e.length&&e[d]===":"&&e[d+1]!==":"){let
|
|
47
|
-
`))return t;t++}return t}function
|
|
48
|
-
`&&(i="normal"),r++;continue;case"block-comment":if(t+=u,u==="*"&&d==="/"){t+=d,r+=2,i="normal";continue}r++;continue;case"regex":if(t+=u,u==="\\"&&r+1<e.length){t+=d,r+=2;continue}if(u==="["){for(r++;r<e.length&&e[r]!=="]";)t+=e[r],e[r]==="\\"&&r+1<e.length?(t+=e[r+1],r+=2):r++;r<e.length&&(t+=e[r],r++);continue}if(u==="/"){for(r++;r<e.length&&/[gimsuy]/.test(e[r]);)t+=e[r],r++;i="normal";continue}r++;continue;case"normal":if(a.length>0){if(u==="{")a[a.length-1]++;else if(u==="}"&&(a[a.length-1]--,a[a.length-1]===0)){a.pop(),t+=u,r++,i="template-string";continue}}if(u==="'"){t+=u,r++,i="single-string";continue}if(u==='"'){t+=u,r++,i="double-string";continue}if(u==="`"){t+=u,r++,i="template-string";continue}if(u==="/"&&d==="/"){t+=u+d,r+=2,i="line-comment";continue}if(u==="/"&&d==="*"){t+=u+d,r+=2,i="block-comment";continue}if(u==="/"){let
|
|
49
|
-
`})(),S=E!=="="&&E!==","&&E!=="("&&E!=="["&&E!==">";if(w&&m()&&!S){let
|
|
50
|
-
`){s=!1,t+=a,i++;continue}if(o&&a==="*"&&l==="/"){o=!1,t+="*/",i+=2;continue}if(s||o){t+=a,i++;continue}a==="("||a==="{"||a==="["?(r++,t+=a):a===")"||a==="}"||a==="]"?(r--,t+=a):a===","&&r===0?(n.push(t),t=""):t+=a,i++}return t.trim()&&n.push(t),n}function
|
|
51
|
-
`,t),o=s===-1?e.length:s;n+=" ".repeat(o-t),t=o;continue}n+=r,t++}return n}function ar(e,n={}){let t=e,r,s=new Set,o=new Set,i=new Set,a=/\/\*\s*tjs\s*<-\s*\S+\s*\*\//.test(e),l=n.dialect==="js"?!0:n.dialect==="tjs"?!1:a||n.vmTarget,c=l?{tjsEquals:!1,tjsClass:!1,tjsDate:!1,tjsNoeval:!1,tjsStandard:!1,tjsSafeEval:!1,tjsNoVar:!1,tjsSafeAssign:!1}:{tjsEquals:!0,tjsClass:!0,tjsDate:!0,tjsNoeval:!0,tjsStandard:!0,tjsSafeEval:!1,tjsNoVar:!0,tjsSafeAssign:!0};l&&(r="none");let p=e.match(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\b/);p&&(r=p[2],e=e.replace(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\s*/,"$1"));let m=/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*(TjsStrict|TjsCompat|TjsEquals|TjsClass|TjsDate|TjsNoeval|TjsNoVar|TjsStandard|TjsSafeEval|TjsSafeAssign)\b/,u;for(;u=e.match(m);){let
|
|
52
|
-
`),g=d.filter(
|
|
53
|
-
`)),t.description=u.trim(),t}}let o=r.match(/\/\*\*[\s\S]*?\*\/\s*$/);if(!o)return t;let i=o[0],a=i.match(/\/\*\*\s*\n?\s*\*?\s*([^@\n][^\n]*)/m);a&&(t.description=a[1].trim());let l=/@param\s+(?:\{[^}]+\}\s+)?(\w+)\s*-?\s*(.*)/g,c;for(;(c=l.exec(i))!==null;)t.params[c[1]]=c[2].trim();return t}import{parseExpressionAt as lr}from"acorn";function U(e){switch(e.type){case"Literal":{let n=e.value;if(n===null)return{kind:"null"};if(typeof n=="string")return{kind:"string"};if(typeof n=="number"){let t=e.raw;return t&&t.includes(".")?{kind:"number"}:{kind:"integer"}}return typeof n=="boolean"?{kind:"boolean"}:{kind:"any"}}case"ArrayExpression":{let n=e.elements;if(n.length===0)return{kind:"array",items:{kind:"any"}};let t=n.filter(i=>i!=null).map(i=>U(i));if(t.length===0)return{kind:"array",items:{kind:"any"}};let r=new Map;for(let i of t){let a=JSON.stringify(i);r.has(a)||r.set(a,i)}let s=[...r.values()];return{kind:"array",items:s.length===1?s[0]:{kind:"union",members:s}}}case"ObjectExpression":{let n=e.properties,t={};for(let r of n)if(r.type==="Property"&&r.key.type==="Identifier"){let s=r.key.name;t[s]=U(r.value)}return{kind:"object",shape:t}}case"LogicalExpression":{let{operator:n,left:t,right:r}=e;return n==="||"?U(t):n==="&&"||n==="??"?U(r):{kind:"any"}}case"BinaryExpression":{let{operator:n,left:t,right:r}=e;if(n==="|"){let s=U(t),o=U(r);return o.kind==="null"?{...s,nullable:!0}:s.kind==="null"?{...o,nullable:!0}:{kind:"union",members:[s,o]}}return{kind:"any"}}case"Identifier":return e.name==="undefined"?{kind:"undefined"}:{kind:"any"};case"ArrowFunctionExpression":case"FunctionExpression":{let n=e,t=n.params.map(s=>cr(s)),r={kind:"any"};return n.type==="ArrowFunctionExpression"&&n.body&&n.body.type!=="BlockStatement"&&(r=U(n.body)),{kind:"function",params:t,returns:r}}case"UnaryExpression":{let n=e.operator,t=e.argument;if(n==="+"&&t.type==="Literal"&&typeof t.value=="number")return{kind:"non-negative-integer"};if(n==="-"&&t.type==="Literal"&&typeof t.value=="number"){let s=t.raw;return s&&s.includes(".")?{kind:"number"}:{kind:"integer"}}return{kind:"any"}}default:return{kind:"any"}}}function cr(e){return e.type==="Identifier"?{name:e.name,type:{kind:"any"}}:e.type==="AssignmentPattern"&&e.left?.type==="Identifier"?{name:e.left.name,type:U(e.right)}:e.type==="RestElement"&&e.argument?.type==="Identifier"?{name:`...${e.argument.name}`,type:{kind:"array",items:{kind:"any"}}}:{name:"?",type:{kind:"any"}}}function Re(e,n){if(e.type==="Identifier")return{name:e.name,type:{kind:"any"},required:!0};if(e.type==="AssignmentPattern"){let{left:t,right:r}=e;if(t.type!=="Identifier")throw new N("Only simple parameter names are supported",P(e));let s=t.name,o=n?.has(s)??!1,i=U(r),a=V(r);return{name:s,type:i,required:o,default:o?null:a,example:a,loc:{start:e.start,end:e.end}}}if(e.type==="ObjectPattern"){let t=e.properties,r={},s={};for(let o of t)if(o.type==="Property"){let i=o.key.type==="Identifier"?o.key.name:String(o.key.value);if(o.value.type==="Identifier")r[i]={kind:"any"},s[i]={name:i,type:{kind:"any"},required:!0};else if(o.value.type==="AssignmentPattern"){let a=Re(o.value,n),l=n?.has(i)??!1;r[i]=a.type,s[i]={name:i,type:a.type,required:l,default:l?null:a.example,example:a.example}}}return{name:"__destructured__",type:{kind:"object",shape:r,destructuredParams:s},required:!0}}throw new N(`Unsupported parameter pattern: ${e.type}`,P(e))}function V(e){switch(e.type){case"Literal":return e.value;case"ArrayExpression":return e.elements.map(n=>n?V(n):null);case"ObjectExpression":{let n={};for(let t of e.properties)t.type==="Property"&&t.key.type==="Identifier"&&(n[t.key.name]=V(t.value));return n}case"UnaryExpression":if(e.operator==="-"){let n=V(e.argument);return typeof n=="number"?-n:void 0}if(e.operator==="+"){let n=V(e.argument);return typeof n=="number"?+n:void 0}return;case"BinaryExpression":{let{operator:n,left:t}=e;return n==="|"?V(t):void 0}case"LogicalExpression":{let{operator:n,left:t,right:r}=e;return n==="&&"&&t.type==="Literal"&&t.value===null?null:n==="||"||n==="??"?V(t)??V(r):void 0}default:return}}function Ct(e){try{let n=lr(e,0,{ecmaVersion:2022});return U(n)}catch{return{kind:"any"}}}function we(e){switch(e.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:e.items?we(e.items):{}};case"object":if(e.shape){let n={};for(let[t,r]of Object.entries(e.shape))n[t]=we(r);return{type:"object",properties:n,additionalProperties:!1}}return{type:"object"};case"union":return e.members?{oneOf:e.members.map(we)}:{};default:return{}}}function ur(e){let n={},t=[];for(let[r,s]of Object.entries(e))n[r]=we(s.type),s.required&&t.push(r);return{type:"object",properties:n,required:t.length>0?t:void 0,additionalProperties:!1}}function Nt(e,n,t,r={},s,o){let i=kt(n,e),a=new Map;for(let S of e.params){let y=Re(S,s);if(y.name==="__destructured__"&&y.type.kind==="object"&&y.type.destructuredParams)for(let[T,$]of Object.entries(y.type.destructuredParams))a.set(T,{...$,description:i.params[T]});else y.description=i.params[y.name],a.set(y.name,y)}let l;t&&(l=Ct(t));let c={depth:0,locals:new Map,parameters:a,atoms:new Set(Object.keys(r.atoms||{})),warnings:[],source:n,filename:r.filename||"<source>",options:r,helpers:o,helperSteps:o?new Map:void 0,helperTransforming:o?new Set:void 0},p=W(e.body,c),m=[],u=[],d=[];for(let[S,y]of a.entries())y.required?u.push(S):y.default!==void 0?d.push({name:S,defaultValue:y.default}):u.push(S);u.length>0&&m.push({op:"varsImport",keys:u});for(let{name:S,defaultValue:y}of d)m.push({op:"varsImport",keys:[S]}),m.push({op:"if",condition:{$expr:"binary",op:"==",left:{$expr:"ident",name:S},right:{$expr:"literal",value:null}},then:[{op:"varSet",key:S,value:y}]});m.push(...p);let g=Object.fromEntries(a),h={name:e.id?.name||"anonymous",description:i.description,parameters:g,returns:l},w=ur(g),E=c.helperSteps&&c.helperSteps.size>0?Object.fromEntries(c.helperSteps):void 0;return{ast:{op:"seq",steps:m,inputSchema:w,...E&&{helpers:E}},signature:h,warnings:c.warnings}}function W(e,n){let t=[];for(let r of e.body){let s=oe(r,n);s&&(Array.isArray(s)?t.push(...s):t.push(s))}return t}function oe(e,n){switch(e.type){case"VariableDeclaration":return fr(e,n);case"ExpressionStatement":return pr(e,n);case"IfStatement":return dr(e,n);case"WhileStatement":return gr(e,n);case"ForOfStatement":return yr(e,n);case"TryStatement":return hr(e,n);case"ReturnStatement":return br(e,n);case"ThrowStatement":throw new N("'throw' is not supported in AsyncJS. Use Error('message') to trigger error flow",P(e),n.source,n.filename);case"BlockStatement":return{op:"scope",steps:W(e,L(n))};case"EmptyStatement":return null;default:throw new N(`Unsupported statement type: ${e.type}`,P(e),n.source,n.filename)}}function fr(e,n){let t=[],r=e.kind==="const",s=r?"constSet":"varSet";for(let o of e.declarations){if(o.id.type!=="Identifier")throw new N("Only simple variable names are supported",P(o),n.source,n.filename);let i=o.id.name;if(o.init){let{step:a,resultVar:l}=K(o.init,n,i,r);a?t.push(a):l!==i&&t.push({op:s,key:i,value:l});let c=U(o.init);n.locals.set(i,c)}else{if(r)throw new N("const declarations must be initialized",P(o),n.source,n.filename);t.push({op:"varSet",key:i,value:null}),n.locals.set(i,{kind:"any",nullable:!0})}}return t}function pr(e,n){let t=e.expression;if(t.type==="AssignmentExpression")return mr(t,n);if(t.type==="CallExpression"){let{step:r,resultVar:s}=K(t,n);return r||(s?{op:"varSet",key:"_",value:s}:null)}return n.warnings.push({message:"Expression statement has no effect",line:P(e).line,column:P(e).column}),null}function mr(e,n){if(e.left.type!=="Identifier")throw new N("Only simple variable assignment is supported",P(e),n.source,n.filename);let t=e.left.name,{step:r,resultVar:s}=K(e.right,n,t);return r||{op:"varSet",key:t,value:s}}function dr(e,n){let t=R(e.test,n),r=e.consequent.type==="BlockStatement"?W(e.consequent,L(n)):[oe(e.consequent,n)].filter(Boolean),s;return e.alternate&&(s=e.alternate.type==="BlockStatement"?W(e.alternate,L(n)):[oe(e.alternate,n)].filter(Boolean)),{op:"if",condition:t,then:r,...s&&{else:s}}}function gr(e,n){let t=R(e.test,n),r=e.body.type==="BlockStatement"?W(e.body,L(n)):[oe(e.body,n)].filter(Boolean);return{op:"while",condition:t,body:r}}function yr(e,n){let t;if(e.left.type==="VariableDeclaration"){let i=e.left.declarations[0];if(i.id.type!=="Identifier")throw new N("Only simple variable names are supported in for...of",P(e.left),n.source,n.filename);t=i.id.name}else if(e.left.type==="Identifier")t=e.left.name;else throw new N("Unsupported for...of left-hand side",P(e.left),n.source,n.filename);let r=D(e.right,n),s=L(n);s.locals.set(t,{kind:"any"});let o=e.body.type==="BlockStatement"?W(e.body,s):[oe(e.body,s)].filter(Boolean);return{op:"map",items:r,as:t,steps:o}}function hr(e,n){let t=W(e.block,L(n)),r,s;if(e.handler){let o=L(n);e.handler.param?.type==="Identifier"&&(s=e.handler.param.name,o.locals.set(s,{kind:"any"})),r=W(e.handler.body,o)}return{op:"try",try:t,...r&&{catch:r},...s&&{catchParam:s}}}function br(e,n){if(!e.argument)return{op:"return",value:{}};let{step:t,resultVar:r}=K(e.argument,n,"__returnVal__");return t?[t,{op:"return",value:r}]:{op:"return",value:D(e.argument,n)}}var Pt=new Set(["Math","JSON","Array","Object","String","Number","console","Date","Schema"]),wr=new Set(["parseInt","parseFloat","isNaN","isFinite","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent","Set","Date","filter"]),ae=new Set(["RegExp","Promise","Map","WeakSet","WeakMap","Symbol","Proxy","Reflect","Function","eval","setTimeout","setInterval","fetch","require","import","process","window","document","global","globalThis"]),Sr=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 $r(e){if(e.callee.type==="Identifier"){let n=e.callee.name;return wr.has(n)||ae.has(n)}if(e.callee.type==="MemberExpression"){let n=e.callee;if(n.object.type==="Identifier"){let t=n.object.name;if(Pt.has(t)||ae.has(t))return!0}if(n.property.type==="Identifier"){let t=n.property.name;if(Sr.has(t))return!0}}return!1}function Er(e){if(e.object.type==="Identifier"){let n=e.object.name;return Pt.has(n)||ae.has(n)}return!1}var Rt={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 Tr(e){if(e.callee.type==="Identifier"){let n=e.callee.name;if(ae.has(n))return Rt[n]||`${n} is not available in AsyncJS.`}if(e.callee.type==="MemberExpression"){let n=e.callee;if(n.object.type==="Identifier"){let t=n.object.name;if(ae.has(t))return Rt[t]||`${t} is not available in AsyncJS.`}}return null}function It(e){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."}[e]||" Use factory functions or object literals instead."}function K(e,n,t,r){let s=r?"constSet":"varSet";if(e.type==="ChainExpression")return K(e.expression,n,t,r);if(e.type==="NewExpression"){let i=e,a="constructor";i.callee.type==="Identifier"&&(a=i.callee.name);let l=It(a);throw new N(`The 'new' keyword is not supported in AsyncJS.${l}`,P(e),n.source,n.filename)}if(e.type==="CallExpression"){let i=Tr(e);if(i)throw new N(i,P(e),n.source,n.filename)}if(e.type==="CallExpression"&&$r(e)){let i=R(e,n);return t?{step:{op:s,key:t,value:i},resultVar:t}:{step:null,resultVar:i}}if(e.type==="MemberExpression"&&Er(e)){let i=R(e,n);return t?{step:{op:s,key:t,value:i},resultVar:t}:{step:null,resultVar:i}}if(e.type==="CallExpression")return xr(e,n,t,r);if(e.type==="TemplateLiteral")return vr(e,n,t,r);if(e.type==="BinaryExpression"||e.type==="LogicalExpression"||e.type==="UnaryExpression"){let i=R(e,n);return t?{step:{op:s,key:t,value:i},resultVar:t}:{step:null,resultVar:i}}return{step:null,resultVar:D(e,n)}}function xr(e,n,t,r){let s,o=!1,i;if(e.callee.type==="Identifier")s=e.callee.name;else if(e.callee.type==="MemberExpression"){let l=e.callee;if(l.property.type==="Identifier")s=l.property.name,o=!0,i=D(l.object,n);else throw new N("Computed method names are not supported",P(e),n.source,n.filename)}else throw new N("Only named function calls are supported",P(e),n.source,n.filename);if(o)return Ar(s,i,e.arguments,n,t,r);if(s==="console"&&e.callee.type,n.helpers?.has(s)){let l=jr(s,n,e),c=e.arguments.map(p=>D(p,n));if(c.length!==l.length)throw new N(`Helper '${s}' expects ${l.length} argument(s), got ${c.length}`,P(e),n.source,n.filename);return{step:{op:"callLocal",name:s,args:c,...t&&{result:t},...t&&r&&{resultConst:!0}},resultVar:t}}let a=Mr(e,n);return{step:{op:s,...a,...t&&{result:t},...t&&r&&{resultConst:!0}},resultVar:t}}function jr(e,n,t){let r=n.helpers.get(e),s=[];for(let o of r.params){let i;if(o.type==="Identifier"?i=o:o.type==="AssignmentPattern"&&o.left?.type==="Identifier"&&(i=o.left),!i)throw new N(`Helper '${e}' parameters must be plain identifiers (optionally with an example value); destructuring is not supported`,o.loc?.start??P(t),n.source,n.filename);s.push(i.name)}if(n.helperSteps.has(e)||n.helperTransforming.has(e))return s;n.helperTransforming.add(e);try{let o={depth:0,locals:new Map,parameters:new Map(s.map(a=>[a,{name:a,type:{kind:"any"},required:!0}])),atoms:n.atoms,warnings:n.warnings,source:n.source,filename:n.filename,options:n.options,helpers:n.helpers,helperSteps:n.helperSteps,helperTransforming:n.helperTransforming},i=W(r.body,o);n.helperSteps.set(e,{steps:i,paramNames:s})}finally{n.helperTransforming.delete(e)}return s}function Ar(e,n,t,r,s,o){switch(e){case"map":if(t.length>0&&(t[0].type==="ArrowFunctionExpression"||t[0].type==="FunctionExpression")){let i=t[0],a=i.params[0],l=a?.type==="Identifier"?a.name:"item",c=L(r);c.locals.set(l,{kind:"any"});let p;if(i.body.type==="BlockStatement")p=W(i.body,c);else{let{step:m,resultVar:u}=K(i.body,c,"result");p=m?[m]:[{op:"varSet",key:"result",value:u}]}return{step:{op:"map",items:n,as:l,steps:p,...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}break;case"filter":if(t.length>0&&(t[0].type==="ArrowFunctionExpression"||t[0].type==="FunctionExpression")){let i=t[0],a=i.params[0],l=a?.type==="Identifier"?a.name:"item",c=L(r);c.locals.set(l,{kind:"any"});let p;if(i.body.type==="BlockStatement")throw new N("filter callback must be an expression, not a block",P(t[0]),r.source,r.filename);return p=R(i.body,c),{step:{op:"filter",items:n,as:l,condition:p,...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}break;case"find":if(t.length>0&&(t[0].type==="ArrowFunctionExpression"||t[0].type==="FunctionExpression")){let i=t[0],a=i.params[0],l=a?.type==="Identifier"?a.name:"item",c=L(r);c.locals.set(l,{kind:"any"});let p;if(i.body.type==="BlockStatement")throw new N("find callback must be an expression, not a block",P(t[0]),r.source,r.filename);return p=R(i.body,c),{step:{op:"find",items:n,as:l,condition:p,...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}break;case"reduce":if(t.length>=2&&(t[0].type==="ArrowFunctionExpression"||t[0].type==="FunctionExpression")){let i=t[0],a=i.params[0],l=i.params[1],c=a?.type==="Identifier"?a.name:"acc",p=l?.type==="Identifier"?l.name:"item",m=L(r);m.locals.set(c,{kind:"any"}),m.locals.set(p,{kind:"any"});let u;if(i.body.type==="BlockStatement")u=W(i.body,m);else{let{step:g,resultVar:h}=K(i.body,m,"result");u=g?[g]:[{op:"varSet",key:"result",value:h}]}let d=D(t[1],r);return{step:{op:"reduce",items:n,as:p,accumulator:c,initial:d,steps:u,...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}break;case"slice":break;case"push":return{step:{op:"push",list:n,item:D(t[0],r),...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s};case"join":return{step:{op:"join",list:n,sep:t.length>0?D(t[0],r):"",...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s};case"split":return{step:{op:"split",str:n,sep:t.length>0?D(t[0],r):"",...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}return r.warnings.push({message:`Unknown method '${e}' - treating as atom call`,line:0,column:0}),{step:{op:e,receiver:n,args:t.map(i=>D(i,r)),...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}function vr(e,n,t,r){let s="",o={};for(let i=0;i<e.quasis.length;i++)if(s+=e.quasis[i].value.cooked||e.quasis[i].value.raw,i<e.expressions.length){let a=e.expressions[i],l=`_${i}`;o[l]=D(a,n),s+=`{{${l}}}`}return{step:{op:"template",tmpl:s,vars:o,...t&&{result:t},...t&&r&&{resultConst:!0}},resultVar:t}}function R(e,n){switch(e.type){case"Literal":return{$expr:"literal",value:e.value};case"Identifier":return{$expr:"ident",name:e.name};case"MemberExpression":{let t=e,r=R(t.object,n),s=t.optional===!0;if(t.computed){let i=t.property;return i.type==="Literal"?{$expr:"member",object:r,property:String(i.value),computed:!0,...s&&{optional:!0}}:{$expr:"member",object:r,property:R(i,n),computed:!0,...s&&{optional:!0}}}let o=t.property.name;return{$expr:"member",object:r,property:o,...s&&{optional:!0}}}case"ChainExpression":return R(e.expression,n);case"BinaryExpression":{let t=e;return{$expr:"binary",op:t.operator,left:R(t.left,n),right:R(t.right,n)}}case"LogicalExpression":{let t=e;return{$expr:"logical",op:t.operator,left:R(t.left,n),right:R(t.right,n)}}case"UnaryExpression":{let t=e;return{$expr:"unary",op:t.operator,argument:R(t.argument,n)}}case"ConditionalExpression":{let t=e;return{$expr:"conditional",test:R(t.test,n),consequent:R(t.consequent,n),alternate:R(t.alternate,n)}}case"ArrayExpression":return{$expr:"array",elements:e.elements.filter(r=>r!==null).map(r=>R(r,n))};case"ObjectExpression":{let t=e,r=[];for(let s of t.properties)if(s.type==="Property"){let o=s.key.type==="Identifier"?s.key.name:String(s.key.value);r.push({key:o,value:R(s.value,n)})}return{$expr:"object",properties:r}}case"CallExpression":{let t=e;if(t.callee.type==="MemberExpression"){let r=t.callee,s=r.property.type==="Identifier"?r.property.name:String(r.property.value),o=r.optional===!0||t.optional===!0;return{$expr:"methodCall",object:R(r.object,n),method:s,arguments:t.arguments.map(i=>R(i,n)),...o&&{optional:!0}}}if(t.callee.type==="Identifier"){let r=t.callee.name;if(n.helpers?.has(r))throw new N(`Helper '${r}' cannot be called inside an expression. Assign its result to a variable first: const result = ${r}(...); then use result.`,P(e),n.source,n.filename);return{$expr:"call",callee:r,arguments:t.arguments.map(s=>R(s,n))}}throw new N("Complex function calls in expressions should be lifted to statements",P(e),n.source,n.filename)}case"NewExpression":{let t=e,r="constructor";t.callee.type==="Identifier"&&(r=t.callee.name);let s=It(r);throw new N(`The 'new' keyword is not supported in AsyncJS.${s}`,P(e),n.source,n.filename)}case"TemplateLiteral":throw new N("Template literals inside expressions are not supported. Assign to a variable first: const msg = `hello ${name}`; then use msg",P(e),n.source,n.filename);default:throw new N(`Unsupported expression type in condition: ${e.type}`,P(e),n.source,n.filename)}}function D(e,n){switch(e.type){case"Literal":return e.value;case"Identifier":return e.name;case"MemberExpression":{let t=e;if(t.optional===!0)return R(e,n);let s=D(t.object,n);if(s&&typeof s=="object"&&s.$expr){let i=t.computed?String(t.property.value):t.property.name;return{$expr:"member",object:s,property:i,...t.computed&&{computed:!0}}}if(t.computed)return R(e,n);let o=t.property.name;return typeof s=="string"?`${s}.${o}`:s&&s.$kind==="arg"?{$kind:"arg",path:`${s.path}.${o}`}:`${s}.${o}`}case"ChainExpression":return D(e.expression,n);case"ArrayExpression":return e.elements.map(t=>t?D(t,n):null);case"ObjectExpression":{let t={};for(let r of e.properties)if(r.type==="Property"){let s=r.key.type==="Identifier"?r.key.name:String(r.key.value);t[s]=D(r.value,n)}return t}case"TemplateLiteral":return R(e,n);case"CallExpression":return R(e,n);case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"ConditionalExpression":return R(e,n);default:return null}}function Mr(e,n){if(e.arguments.length===1&&e.arguments[0].type==="ObjectExpression"){let t=e.arguments[0],r={};for(let s of t.properties)if(s.type==="Property"){let o=s.key.type==="Identifier"?s.key.name:String(s.key.value);r[o]=D(s.value,n)}return r}return{args:e.arguments.map(t=>D(t,n))}}function le(e,n={}){let{ast:t,returnType:r,originalSource:s,requiredParams:o}=vt(e,{filename:n.filename,colonShorthand:!0,vmTarget:!0}),{entry:i,helpers:a}=Mt(t,n.filename),{ast:l,signature:c,warnings:p}=Nt(i,s,r,n,o,a.size>0?a:void 0);return{ast:l,signature:c,warnings:p}}var Cr=6e4,Se=class{atoms;_defaultRunTimeout;constructor(n={}){this.atoms={...qe,...n}}get defaultRunTimeout(){if(this._defaultRunTimeout===void 0){let n=0;for(let t of Object.values(this.atoms)){let r=t.timeoutMs??1e3;r>0&&r>n&&(n=r)}this._defaultRunTimeout=Math.max(Cr,n*2)}return this._defaultRunTimeout}get builder(){return new re(this.atoms)}get Agent(){return new re(this.atoms)}get A99(){return this.Agent}resolve(n){return this.atoms[n]}getTools(n="all"){let t=Object.values(this.atoms);if(Array.isArray(n))t=t.filter(r=>n.includes(r.op));else if(n==="flow"){let r=["seq","if","while","return","try","varSet","varGet","scope"];t=t.filter(s=>r.includes(s.op))}return t.map(r=>({type:"function",function:{name:r.op,description:r.docs,parameters:r.inputSchema?.schema??{}}}))}async run(n,t={},r={}){let s;if(typeof n=="string")if(xe(n))s=je(n);else try{s=le(n).ast}catch(g){throw new Error(`AJS transpilation failed: ${g.message}`,{cause:g})}else s=n;let o=r.fuel??1e3,i=r.timeoutMs??this.defaultRunTimeout,a=r.capabilities??{},l=[];if(!a.store){let g=new Map,h=!1;a.store={get:async w=>(h||(h=!0,l.push("Using default in-memory store (not suitable for production)")),g.get(w)),set:async(w,E)=>{h||(h=!0,l.push("Using default in-memory store (not suitable for production)")),g.set(w,E)}}}let c=new AbortController,p=setTimeout(()=>c.abort(),i);r.signal&&r.signal.addEventListener("abort",()=>c.abort());let m={fuel:{current:o},args:t,state:{},consts:new Set,capabilities:a,resolver:g=>this.resolve(g),output:void 0,signal:c.signal,costOverrides:r.costOverrides,timeoutOverrides:r.timeoutOverrides,context:r.context,warnings:l,helpers:s.helpers};if(r.trace&&(m.trace=[]),s.op!=="seq")throw new Error("Root AST must be 'seq'. Ensure you're passing a transpiled agent (use ajs`...` or transpile()).");let u=s.inputSchema;if(u&&!kr(t,u)){let g=new O("Input validation failed: args do not match expected schema","vm.run");return{result:g,error:g,fuelUsed:0,trace:m.trace,warnings:l.length>0?l:void 0}}try{await Promise.race([this.resolve("seq")?.exec(s,m),new Promise((g,h)=>{c.signal.addEventListener("abort",()=>{h(new Error(`Execution timeout after ${i}ms. Pass a higher \`timeoutMs\` to vm.run() or set per-atom \`timeoutOverrides\` for slow IO atoms.`))}),c.signal.aborted&&h(new Error(`Execution timeout after ${i}ms. Pass a higher \`timeoutMs\` to vm.run() or set per-atom \`timeoutOverrides\` for slow IO atoms.`))})])}catch(g){if(g.message?.includes("timeout")||g.message?.includes("aborted")||c.signal.aborted)m.error=new O(`Execution timeout after ${i}ms. Pass a higher \`timeoutMs\` to vm.run() or set per-atom \`timeoutOverrides\` for slow IO atoms.`,"vm.run");else throw g}finally{clearTimeout(p)}m.error&&m.output===void 0&&(m.output=m.error);let d=[...l,...m.warnings??[]];return{result:m.output,error:m.error,fuelUsed:o-m.fuel.current,trace:m.trace,warnings:d.length>0?d:void 0}}};var Rr=null,Bt=()=>Rr??=new Se;function Y(e){if(!(!e||typeof e!="object")){if(Array.isArray(e)){for(let n of e)Y(n);return}e.op==="return"&&"value"in e&&(e.value={__result:e.value}),e.steps&&Y(e.steps),e.then&&Y(e.then),e.else&&Y(e.else),e.body&&Y(e.body)}}async function us(e){let{code:n,context:t={},fuel:r=1e3,timeoutMs:s,capabilities:o={}}=e,i=Bt(),l=/\breturn\b/.test(n)?`function __eval() { ${n} }`:`function __eval() { return (${n}) }`;try{let{ast:c}=le(l);Y(c);let p=await i.run(c,t,{fuel:r,timeoutMs:s,capabilities:o}),m=p.result;return{result:m&&typeof m=="object"&&"__result"in m?m.__result:m,fuelUsed:p.fuelUsed,error:p.error?{message:p.error.message||String(p.error)}:void 0}}catch(c){return{result:void 0,fuelUsed:r,error:{message:c.message||String(c)}}}}async function fs(e){let{body:n,params:t=[],fuel:r=1e3,timeoutMs:s,capabilities:o={}}=e,i=Bt(),l=`function __safeFn(${t.join(", ")}) { ${n} }`,{ast:c}=le(l);return Y(c),async(...p)=>{let m={};for(let u=0;u<t.length;u++)m[t[u]]=p[u];try{let u=await i.run(c,m,{fuel:r,timeoutMs:s,capabilities:o}),d=u.result;return{result:d&&typeof d=="object"&&"__result"in d?d.__result:d,fuelUsed:u.fuelUsed,error:u.error?{message:u.error.message||String(u.error)}:void 0}}catch(u){return{result:void 0,fuelUsed:r,error:{message:u.message||String(u)}}}}}export{us as Eval,fs as SafeFunction};
|
|
44
|
+
`,i=i.slice(0,p)+E+i.slice(m);let T=p+E.length;i=i.slice(0,T)+S+i.slice(T)}return{source:i,polyCtorClasses:t}}function gt(e,n=new Set){let t=/\bclass\s+(\w+)(\s+extends\s+\w+)?\s*\{/g,r="",s=0,o;for(;(o=t.exec(e))!==null;){let i=o[1],a=o[2]||"",l=o.index,c=l+o[0].length-1,p=1,m=c+1;for(;m<e.length&&p>0;){let u=e[m];u==="{"?p++:u==="}"&&p--,m++}if(p===0){let u=m,d=e.slice(c,u);r+=e.slice(s,l),r+=`let ${i} = class ${i}${a} ${d}; `,n.has(i)?r+=`${i} = new Proxy(${i}, { apply(t, _, a) { return ${i}$dispatch(t, a) }, construct(t, a) { return ${i}$dispatch(t, a) } });`:r+=`${i} = new Proxy(${i}, { apply(t, _, a) { return Reflect.construct(t, a) } });`,s=u}}return r+=e.slice(s),r}function ht(e){let n=[{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:t,message:r}of n)if(t.test(e))throw new Error(r);return e}function yt(e){let n=new Set,t=/\bconst!\s+(\w+)\b/g,r;for(;(r=t.exec(e))!==null;)n.add(r[1]);if(n.size===0)return e;e=e.replace(/\bconst!\s+/g,"const ");let s=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"");for(let o of n){if(new RegExp(`\\b${o}\\s*(?:\\.[\\w]+|\\[[^\\]]+\\])\\s*(?:=(?!=)|\\+\\+|--|\\+=|-=|\\*=|\\/=|%=|&&=|\\|\\|=|\\?\\?=|<<=|>>=|>>>=|\\^=|&=|\\|=)`,"g").test(s))throw new Error(`Cannot mutate immutable binding '${o}'. const! bindings are read-only at compile time.`);if(new RegExp(`(?:\\+\\+|--)\\s*${o}\\s*(?:\\.[\\w]+|\\[[^\\]]+\\])`,"g").test(s))throw new Error(`Cannot mutate immutable binding '${o}'. const! bindings are read-only at compile time.`);if(new RegExp(`\\bdelete\\s+${o}\\s*(?:\\.[\\w]+|\\[[^\\]]+\\])`,"g").test(s))throw new Error(`Cannot mutate immutable binding '${o}'. const! bindings are read-only at compile time.`);let c="push|pop|splice|shift|unshift|sort|reverse|fill|copyWithin|set";if(new RegExp(`\\b${o}\\s*\\.\\s*(?:${c})\\s*\\(`,"g").test(s))throw new Error(`Cannot call mutating method on immutable binding '${o}'. const! bindings are read-only at compile time.`)}return e}function bt(e){if(/(?<![a-zA-Z_$])\bvar\s+/.test(e))throw new Error("var is not allowed in TjsNoVar mode. Use const or let instead.");return e}function wt(e){if(/(?<![A-Za-z_$])\beval\s*\(/.test(e))throw new Error("eval() is not allowed in TjsNoeval mode. Use Eval() from TJS runtime for safe evaluation.");if(/\bnew\s+Function\s*\(/.test(e))throw new Error("new Function() is not allowed in TjsNoeval mode. Use SafeFunction() from TJS runtime.");return e}function St(e){if(!e.includes("!."))return e;let n="",t=0,r="normal",s=0;for(;t<e.length;){let o=e[t],i=e[t+1];if(r==="normal"){if(o==="/"&&i==="/"){r="line-comment",n+=o,t++;continue}if(o==="/"&&i==="*"){r="block-comment",n+=o,t++;continue}if(o==="'"){r="string-single",n+=o,t++;continue}if(o==='"'){r="string-double",n+=o,t++;continue}if(o==="`"){r="string-template",s++,n+=o,t++;continue}if(o==="!"&&i==="."&&t+2<e.length&&/[a-zA-Z_$]/.test(e[t+2])){let a=n.length,l=rr(n);if(l<a){let c=n.slice(l);n=n.slice(0,l);let p=t+2;for(;p<e.length&&/[\w$]/.test(e[p]);)p++;let m=e.slice(t+2,p);n+=`__tjs.bang(${c},'${m}')`,t=p;continue}}n+=o,t++}else r==="line-comment"?(n+=o,o===`
|
|
45
|
+
`&&(r="normal"),t++):r==="block-comment"?(n+=o,o==="*"&&i==="/"?(n+=i,r="normal",t+=2):t++):r==="string-single"?(n+=o,o==="\\"?(n+=i||"",t+=2):(o==="'"&&(r="normal"),t++)):r==="string-double"?(n+=o,o==="\\"?(n+=i||"",t+=2):(o==='"'&&(r="normal"),t++)):r==="string-template"?(n+=o,o==="\\"?(n+=i||"",t+=2):o==="`"?(s--,r=s>0?"string-template":"normal",t++):o==="$"&&i==="{"?(n+=i,t+=2,r="normal"):t++):(n+=o,t++)}return n}function rr(e){let n=e.length-1;for(;n>=0&&/\s/.test(e[n]);)n--;if(n<0)return e.length;for(;n>=0;){let t=e[n];if(/[\w$]/.test(t)){for(;n>=0&&/[\w$]/.test(e[n]);)n--;if(n>=0&&e[n]==="."){n>=1&&e[n-1]==="?"?n-=2:n--;continue}return n+1}else if(t===")"){if(n=He(e,n,"(",")"),n<0)return 0;if(n--,n>=0&&/[\w$]/.test(e[n]))continue;if(n>=0&&e[n]==="."){n>=1&&e[n-1]==="?"?n-=2:n--;continue}return n+1}else if(t==="]"){if(n=He(e,n,"[","]"),n<0)return 0;if(n--,n>=0&&/[\w$]/.test(e[n]))continue;if(n>=0&&e[n]==="."){n>=1&&e[n-1]==="?"?n-=2:n--;continue}return n+1}else return n+1}return 0}function He(e,n,t,r){let s=1;for(n--;n>=0&&s>0;)e[n]===r?s++:e[n]===t&&s--,s>0&&n--;return n}function $t(e){let n=new Map;if(!e.includes("let "))return{source:e,annotations:n};let t=[],r=0,s="normal",o=[];for(;r<e.length;){let a=e[r],l=e[r+1];switch(s){case"single-string":if(a==="\\"&&r+1<e.length){r+=2;continue}a==="'"&&(s="normal"),r++;continue;case"double-string":if(a==="\\"&&r+1<e.length){r+=2;continue}a==='"'&&(s="normal"),r++;continue;case"template-string":if(a==="\\"&&r+1<e.length){r+=2;continue}if(a==="$"&&l==="{"){r+=2,o.push(1),s="normal";continue}a==="`"&&(s="normal"),r++;continue;case"line-comment":a===`
|
|
46
|
+
`&&(s="normal"),r++;continue;case"block-comment":if(a==="*"&&l==="/"){r+=2,s="normal";continue}r++;continue;case"regex":if(a==="\\"&&r+1<e.length){r+=2;continue}if(a==="["){for(r++;r<e.length&&e[r]!=="]";)e[r]==="\\"&&r+1<e.length?r+=2:r++;r<e.length&&r++;continue}if(a==="/"){for(r++;r<e.length&&/[gimsuy]/.test(e[r]);)r++;s="normal";continue}r++;continue;case"normal":if(o.length>0){if(a==="{")o[o.length-1]++;else if(a==="}"&&(o[o.length-1]--,o[o.length-1]===0)){o.pop(),r++,s="template-string";continue}}if(a==="'"){r++,s="single-string";continue}if(a==='"'){r++,s="double-string";continue}if(a==="`"){r++,s="template-string";continue}if(a==="/"&&l==="/"){r+=2,s="line-comment";continue}if(a==="/"&&l==="*"){r+=2,s="block-comment";continue}if(a==="/"){let c=r-1;for(;c>=0&&/\s/.test(e[c]);)c--;let p=c>=0?e[c]:"";if(!p||/[=(!,;:{[&|?+\-*%<>~^]/.test(p)||c>=5&&/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)$/.test(e.slice(Math.max(0,c-10),c+1))){r++,s="regex";continue}}if(a==="l"&&e.slice(r,r+4)==="let "&&(r===0||!/[\w$]/.test(e[r-1]))){let c=r+4;for(;c<e.length&&/\s/.test(e[c]);)c++;if(c<e.length&&/[a-zA-Z_$]/.test(e[c])){let p=c;for(;c<e.length&&/[\w$]/.test(e[c]);)c++;let m=c,u=e.slice(p,m),d=c;for(;d<e.length&&/\s/.test(e[d]);)d++;if(d<e.length&&e[d]===":"&&e[d+1]!==":"){let y=d+1;for(;y<e.length&&/[ \t]/.test(e[y]);)y++;let w=sr(e,y);if(w>y){let E=e.slice(y,w).trim();n.set(u,E),t.push({start:m,end:w,replacement:""}),r=w;continue}}}}break}r++}if(t.length===0)return{source:e,annotations:n};let i=e;for(let a=t.length-1;a>=0;a--){let l=t[a];i=i.slice(0,l.start)+l.replacement+i.slice(l.end)}return{source:i,annotations:n}}function sr(e,n){let t=n,r=0,s=0,o=0,i="normal",a=[];for(;t<e.length;){let l=e[t];if(i==="sq"){if(l==="\\"){t+=2;continue}l==="'"&&(i="normal"),t++;continue}if(i==="dq"){if(l==="\\"){t+=2;continue}l==='"'&&(i="normal"),t++;continue}if(i==="tpl"){if(l==="\\"){t+=2;continue}if(l==="$"&&e[t+1]==="{"){a.push(1),i="normal",t+=2;continue}l==="`"&&(i="normal"),t++;continue}if(a.length>0){if(l==="{")a[a.length-1]++;else if(l==="}"&&(a[a.length-1]--,a[a.length-1]===0)){a.pop(),i="tpl",t++;continue}}if(l==="'"){i="sq",t++;continue}if(l==='"'){i="dq",t++;continue}if(l==="`"){i="tpl",t++;continue}if(l==="("?r++:l===")"?r--:l==="{"?s++:l==="}"?s--:l==="["?o++:l==="]"&&o--,r===0&&s===0&&o===0&&(l==="="||l===","||l===";"||l===`
|
|
47
|
+
`))return t;t++}return t}function ge(e,n){let t="",r=0,s,o,i="normal",a=[],l=[{type:"top-level",braceDepth:0}],c=0,p=()=>l[l.length-1]?.type||"top-level",m=()=>{let u=l[l.length-1];return u?.type==="class-body"&&c===u.braceDepth+1};for(;r<e.length;){let u=e[r],d=e[r+1];switch(i){case"single-string":if(t+=u,u==="\\"&&r+1<e.length){t+=d,r+=2;continue}u==="'"&&(i="normal"),r++;continue;case"double-string":if(t+=u,u==="\\"&&r+1<e.length){t+=d,r+=2;continue}u==='"'&&(i="normal"),r++;continue;case"template-string":if(t+=u,u==="\\"&&r+1<e.length){t+=d,r+=2;continue}if(u==="$"&&d==="{"){t+=d,r+=2,a.push(1),i="normal";continue}u==="`"&&(i="normal"),r++;continue;case"line-comment":t+=u,u===`
|
|
48
|
+
`&&(i="normal"),r++;continue;case"block-comment":if(t+=u,u==="*"&&d==="/"){t+=d,r+=2,i="normal";continue}r++;continue;case"regex":if(t+=u,u==="\\"&&r+1<e.length){t+=d,r+=2;continue}if(u==="["){for(r++;r<e.length&&e[r]!=="]";)t+=e[r],e[r]==="\\"&&r+1<e.length?(t+=e[r+1],r+=2):r++;r<e.length&&(t+=e[r],r++);continue}if(u==="/"){for(r++;r<e.length&&/[gimsuy]/.test(e[r]);)t+=e[r],r++;i="normal";continue}r++;continue;case"normal":if(a.length>0){if(u==="{")a[a.length-1]++;else if(u==="}"&&(a[a.length-1]--,a[a.length-1]===0)){a.pop(),t+=u,r++,i="template-string";continue}}if(u==="'"){t+=u,r++,i="single-string";continue}if(u==='"'){t+=u,r++,i="double-string";continue}if(u==="`"){t+=u,r++,i="template-string";continue}if(u==="/"&&d==="/"){t+=u+d,r+=2,i="line-comment";continue}if(u==="/"&&d==="*"){t+=u+d,r+=2,i="block-comment";continue}if(u==="/"){let h=t.trimEnd();if(!h[h.length-1]||/[=(!,;:{[&|?+\-*%<>~^]$/.test(h)||/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)\s*$/.test(h)){t+=u,r++,i="regex";continue}}break}if(u==="{"){c++,t+=u,r++;continue}if(u==="}"){c--;let h=l[l.length-1];h&&c===h.braceDepth&&l.pop(),t+=u,r++;continue}let g=e.slice(r).match(/^class\s+\w+(?:\s+extends\s+\w+)?\s*\{/);if(g){let h=g[0].slice(0,-1);t+=h,r+=h.length,l.push({type:"class-body",braceDepth:c});continue}let y=e.slice(r).match(/^function\s+(\w+)\s*\(/);if(y){let h=y[1],T=y[0].length,$=e[r+T],b,v=r+T;($==="?"||$==="!")&&(b=$,v++,b==="!"?n.unsafeFunctions.add(h):n.safeFunctions.add(h)),t+=`function ${h}(`,r=v;let j=pe(e,r,"(",")");if(!j){t+=e[r],r++;continue}let{content:A,endPos:M}=j;r=M;let C=ke(A,n,!0);t+=C+")";let R=r;for(;R<e.length&&/\s/.test(e[R]);)R++;if(e[R]===":"){let ee=e.slice(R,R+2),te;for(ee===":?"||ee===":!"?(R+=2,te=ee===":?"?"safe":"unsafe"):R+=1;R<e.length&&/\s/.test(e[R]);)R++;let ne=Me(e,R);ne&&(s===void 0&&(s=ne.type,te&&(o=te)),r=ne.endPos)}let L=r;for(;L<e.length&&/\s/.test(e[L]);)L++;if(e[L]==="="&&e[L+1]===">")throw new _("Unexpected '=>' after function declaration. Function declarations use `function name(params) { body }`, not arrow syntax. Remove the `=>`.",J(n.originalSource,L),n.originalSource);continue}let w=e.slice(r).match(/^(constructor|(?:get|set)\s+\w+|async\s+\w+|\w+)\s*\(/),E=(()=>{for(let h=t.length-1;h>=0;h--)if(!/\s/.test(t[h]))return t[h];return`
|
|
49
|
+
`})(),S=E!=="="&&E!==","&&E!=="("&&E!=="["&&E!==">";if(w&&m()&&!S){let h=w[1].length;t+=e.slice(r,r+h),r+=h;continue}if(w&&m()&&S){let h=w[1],T=w[0].length,$=r+T;t+=h+"(",r=$;let b=pe(e,r,"(",")");if(!b){t+=e[r],r++;continue}let{content:v,endPos:j}=b;r=j;let A=ke(v,n,!0);t+=A+")";let M=r;for(;M<e.length&&/\s/.test(e[M]);)M++;if(e[M]===":"){let R=e.slice(M,M+2);for(R===":?"||R===":!"?M+=2:M++;M<e.length&&/\s/.test(e[M]);)M++;let L=Me(e,M);L&&(r=L.endPos)}let C=r;for(;C<e.length&&/\s/.test(e[C]);)C++;if(e[C]==="="&&e[C+1]===">")throw new _("Unexpected '=>' after method declaration. Methods use `name(params) { body }`, not arrow syntax. Remove the `=>`.",J(n.originalSource,C),n.originalSource);continue}if(e[r]==="("){let h=pe(e,r+1,"(",")");if(!h){t+=e[r],r++;continue}let T=h.content,$=h.endPos,b=$;for(;b<e.length&&/\s/.test(e[b]);)b++;let v;if(e[b]===":"){let j=e.slice(b,b+2);for(j===":?"||j===":!"?b+=2:b++;b<e.length&&/\s/.test(e[b]);)b++;let A=Me(e,b);if(A)for(v=A.type,b=A.endPos;b<e.length&&/\s/.test(e[b]);)b++}if(e.slice(b,b+2)==="=>"){let j=null,A=T,M=T.trimStart();M.startsWith("?")&&(M.length===1||/\s/.test(M[1]))?(j="?",A=M.slice(1)):M.startsWith("!")&&(M.length===1||/\s/.test(M[1]))&&(j="!",A=M.slice(1));let C=ke(A,n,!1);for(t+=`(${j==="?"?"/* safe */ ":j==="!"?"/* unsafe */ ":""}${C})`,r=$;r<b&&/\s/.test(e[r]);)t+=e[r],r++;v&&(r=b)}else{let j=ge(T,n);t+=`(${j.source})`,r=$}continue}t+=e[r],r++}return{source:t,returnType:s,returnSafety:o}}function pe(e,n,t,r){let s=1,o=n,i=!1,a="";for(;o<e.length&&s>0;){let l=e[o];!i&&(l==="'"||l==='"'||l==="`")?(i=!0,a=l):i&&l===a&&e[o-1]!=="\\"?i=!1:i||(l===t?s++:l===r&&s--),o++}return s!==0?null:{content:e.slice(n,o-1),endPos:o}}function Et(e,n){let t=n;for(;t<e.length&&/\s/.test(e[t]);)t++;if(t>=e.length)return null;let r=t,s=e[t];if(s==="{"||s==="["){let i=s==="{"?"}":"]",a=pe(e,t+1,s,i);return a?{value:e.slice(r,a.endPos),endPos:a.endPos}:null}if(s==="'"||s==='"'||s==="`"){for(t++;t<e.length;){if(e[t]===s&&e[t-1]!=="\\")return t++,{value:e.slice(r,t),endPos:t};t++}return null}if(/[-+\d]/.test(s)){for(;t<e.length&&/[\d.eE+-]/.test(e[t]);)t++;return{value:e.slice(r,t),endPos:t}}let o=e.slice(t).match(/^(true|false|null|undefined)\b/);return o?{value:o[1],endPos:t+o[1].length}:null}function ie(e){return e.replace(/(?<!\|)\|(?!\|)/g," || ")}function Me(e,n){let t=n,r=0,s=!1,o="",i=!1,a=l=>({type:ie(e.slice(n,l).trim()),endPos:l});for(;t<e.length;){let l=e[t];if(!s&&(l==="'"||l==='"'||l==="`")){s=!0,o=l,i=!0,t++;continue}if(s){if(l===o&&e[t-1]!=="\\"){if(s=!1,t++,r===0){let c=t;for(;c<e.length&&/\s/.test(e[c]);)c++;if(e[c]==="{"&&!e.slice(c+1).match(/^\s*(\w+)\s*:/)||e[c]!=="|"&&e[c]!=="&")return a(t)}continue}t++;continue}if(l==="{"||l==="["||l==="("){r++,i=!0,t++;continue}if(l==="}"||l==="]"||l===")"){if(r--,r===0){t++;let c=t;for(;c<e.length&&/\s/.test(e[c]);)c++;if(e[c]==="|"||e[c]==="&")continue;return a(t)}t++;continue}if(r===0&&l==="{"){if(i)return a(t);if(e.slice(t+1).match(/^\s*(\w+)\s*:/)){r++,i=!0,t++;continue}return a(t)}if(r===0&&(l==="|"||l==="&")){for(t++,t<e.length&&e[t]==="|"&&t++;t<e.length&&/\s/.test(e[t]);)t++;continue}if(r===0&&(/\d/.test(l)||l==="-"&&/\d/.test(e[t+1]))){let c=t;for(e[c]==="-"&&c++;c<e.length&&/\d/.test(e[c]);)c++;if(c<e.length&&e[c]==="."&&/\d/.test(e[c+1]))for(c++;c<e.length&&/\d/.test(e[c]);)c++;if(c<e.length&&(e[c]==="e"||e[c]==="E"))for(c++,c<e.length&&(e[c]==="+"||e[c]==="-")&&c++;c<e.length&&/\d/.test(e[c]);)c++;for(i=!0,t=c;t<e.length&&/\s/.test(e[t]);)t++;if(t<e.length&&e[t]==="{")return{type:ie(e.slice(n,c).trim()),endPos:c};if(e[t]!=="|"&&e[t]!=="&")return{type:ie(e.slice(n,c).trim()),endPos:c};continue}if(r===0&&/[a-zA-Z_]/.test(l)){let c=t;for(;c<e.length&&/\w/.test(e[c]);)c++;for(i=!0,t=c;t<e.length&&/\s/.test(e[t]);)t++;if(t<e.length&&e[t]==="("){r++,t++;continue}if(t<e.length&&e[t]==="{"&&!e.slice(t+1).match(/^\s*(\w+)\s*:/)){let m=c;for(;m>n&&/\s/.test(e[m-1]);)m--;return{type:ie(e.slice(n,m).trim()),endPos:c}}if(e[t]!=="|"&&e[t]!=="&")return{type:ie(e.slice(n,c).trim()),endPos:c};continue}t++}return i?a(t):null}function he(e){let n=[],t="",r=0,s=!1,o=!1,i=0;for(;i<e.length;){let a=e[i],l=e[i+1];if(!o&&a==="/"&&l==="/"){s=!0,t+="//",i+=2;continue}if(!s&&a==="/"&&l==="*"){o=!0,t+="/*",i+=2;continue}if(s&&a===`
|
|
50
|
+
`){s=!1,t+=a,i++;continue}if(o&&a==="*"&&l==="/"){o=!1,t+="*/",i+=2;continue}if(s||o){t+=a,i++;continue}a==="("||a==="{"||a==="["?(r++,t+=a):a===")"||a==="}"||a==="]"?(r--,t+=a):a===","&&r===0?(n.push(t),t=""):t+=a,i++}return t.trim()&&n.push(t),n}function ke(e,n,t){let r=ge(e,{originalSource:e,requiredParams:n.requiredParams,unsafeFunctions:n.unsafeFunctions,safeFunctions:n.safeFunctions}).source,s=he(r),o=!1,i=new Set,a=c=>{if(t&&/^\w+$/.test(c)){if(i.has(c))throw new Error(`Duplicate parameter name '${c}'`);i.add(c)}};return s.map(c=>{let p=c.trim();if(!p)return c;if(t&&p.startsWith("{")&&p.endsWith("}")){let d=p.slice(1,-1);return`{ ${Tt(d,n)} }`}if(t&&p.startsWith("[")&&p.endsWith("]")){let d=p.slice(1,-1);return`[ ${Tt(d,n)} ]`}if(p.startsWith("...")){let d=xt(p);return d!==-1?p.slice(0,d).trim():c}let m=p.match(/^(\w+)\s*\?\s*:\s*(.+)$/);if(m){let[,d,g]=m;return a(d),o=!0,`${d} = ${g}`}if(!ir(p)){let d=p.match(/^(\w+)\s*=/);return d&&a(d[1]),o=!0,c}let u=xt(p);if(u!==-1){let d=p.slice(0,u).trim(),g=p.slice(u+1).trim();return a(d),o&&t&&/^\w+$/.test(d),t&&/^\w+$/.test(d)&&n.requiredParams.add(d),`${d} = ${g}`}return c}).join(",")}function Tt(e,n){return he(e).map(s=>{let o=s.trim();if(!o)return s;let i=o.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if(i){let[,c,p]=i;n.requiredParams.add(c);let m=me(p);return`${c} = ${m}`}let a=o.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(a){let[,c,p]=a;n.requiredParams.add(c);let m=de(p);return`${c} = ${m}`}let l=o.match(/^(\w+)\s*:\s*([\s\S]+)$/);if(l){let[,c,p]=l;return n.requiredParams.add(c),`${c} = ${p}`}return s}).join(", ")}function me(e){let n=e.slice(1,-1).trim();return`{ ${he(n).map(s=>{let o=s.trim();if(!o)return s;let i=o.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if(i){let[,m,u]=i;return`${m}: ${me(u)}`}let a=o.match(/^(\w+)\s*=\s*(\{[\s\S]*\})$/);if(a){let[,m,u]=a;return`${m}: ${me(u)}`}let l=o.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(l){let[,m,u]=l;return`${m}: ${de(u)}`}let c=o.match(/^(\w+)\s*=\s*(\[[\s\S]*\])$/);if(c){let[,m,u]=c;return`${m}: ${de(u)}`}let p=o.match(/^(\w+)\s*=\s*([\s\S]+)$/);if(p){let[,m,u]=p;return`${m}: ${u}`}return s}).join(", ")} }`}function de(e){let n=e.slice(1,-1).trim();return`[ ${he(n).map(s=>{let o=s.trim();return o?o.startsWith("{")&&o.endsWith("}")?me(o):o.startsWith("[")&&o.endsWith("]")?de(o):s:s}).join(", ")} ]`}function ir(e){let n=0,t=!1,r=!1,s=!1,o="";for(let i=0;i<e.length;i++){let a=e[i];if(!s&&(a==="'"||a==='"'||a==="`")){s=!0,o=a;continue}if(s){a===o&&e[i-1]!=="\\"&&(s=!1);continue}a==="("||a==="{"||a==="["?n++:a===")"||a==="}"||a==="]"?n--:n===0&&(a===":"&&(t=!0),a==="="&&e[i+1]!==">"&&(r=!0))}return t&&!r}function xt(e){let n=0,t=!1,r="";for(let s=0;s<e.length;s++){let o=e[s];if(!t&&(o==="'"||o==='"'||o==="`")){t=!0,r=o;continue}if(t){o===r&&e[s-1]!=="\\"&&(t=!1);continue}if(o==="("||o==="{"||o==="[")n++;else if(o===")"||o==="}"||o==="]")n--;else if(n===0&&o===":")return s}return-1}function or(e){let n="",t=0;for(;t<e.length;){let r=e[t];if(r==="'"||r==='"'||r==="`"){let s=r;for(n+=r,t++;t<e.length&&e[t]!==s;)e[t]==="\\"&&(n+=e[t++]),t<e.length&&(n+=e[t++]);t<e.length&&(n+=e[t++]);continue}if(r==="/"&&e[t+1]==="*"){let s=e.indexOf("*/",t+2),o=s===-1?e.slice(t):e.slice(t,s+2);n+=o,t+=o.length;continue}if(r==="/"&&e[t+1]==="/"){let s=e.indexOf(`
|
|
51
|
+
`,t),o=s===-1?e.length:s;n+=" ".repeat(o-t),t=o;continue}n+=r,t++}return n}function ar(e,n={}){let t=e,r,s=new Set,o=new Set,i=new Set,a=/\/\*\s*tjs\s*<-\s*\S+\s*\*\//.test(e),l=n.dialect==="js"?!0:n.dialect==="tjs"?!1:a||n.vmTarget,c=l?{tjsEquals:!1,tjsClass:!1,tjsDate:!1,tjsNoeval:!1,tjsStandard:!1,tjsSafeEval:!1,tjsNoVar:!1,tjsSafeAssign:!1}:{tjsEquals:!0,tjsClass:!0,tjsDate:!0,tjsNoeval:!0,tjsStandard:!0,tjsSafeEval:!1,tjsNoVar:!0,tjsSafeAssign:!0};l&&(r="none");let p=e.match(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\b/);p&&(r=p[2],e=e.replace(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\s*/,"$1"));let m=/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*(TjsStrict|TjsCompat|TjsEquals|TjsClass|TjsDate|TjsNoeval|TjsNoVar|TjsStandard|TjsSafeEval|TjsSafeAssign)\b/,u;for(;u=e.match(m);){let M=u[2];M==="TjsStrict"?(c.tjsEquals=!0,c.tjsClass=!0,c.tjsDate=!0,c.tjsNoeval=!0,c.tjsNoVar=!0,c.tjsStandard=!0,c.tjsSafeAssign=!0):M==="TjsCompat"?(c.tjsEquals=!1,c.tjsClass=!1,c.tjsDate=!1,c.tjsNoeval=!1,c.tjsNoVar=!1,c.tjsStandard=!1,c.tjsSafeEval=!1,c.tjsSafeAssign=!1):M==="TjsEquals"?c.tjsEquals=!0:M==="TjsClass"?c.tjsClass=!0:M==="TjsDate"?c.tjsDate=!0:M==="TjsNoeval"?c.tjsNoeval=!0:M==="TjsNoVar"?c.tjsNoVar=!0:M==="TjsStandard"?c.tjsStandard=!0:M==="TjsSafeEval"?c.tjsSafeEval=!0:M==="TjsSafeAssign"&&(c.tjsSafeAssign=!0),e=e.replace(new RegExp(`^(\\s*(?:\\/\\/[^\\n]*\\n|\\/\\*[\\s\\S]*?\\*\\/\\s*)*)\\s*${M}\\s*`),"$1")}e=or(e),c.tjsStandard&&(e=tt(e)),e=yt(e),e=St(e);let d=$t(e);e=d.source;let g=d.annotations,y=Xe(e);e=y.source,e=et(e),c.tjsEquals&&!n.vmTarget&&(e=nt(e)),e=rt(e),e=it(e),e=st(e),e=ot(e),e=at(e),e=pt(e);let w=Qe(e,{loader:n.moduleLoader,importerPath:n.filename});e=w.source;let{source:E,returnType:S,returnSafety:h}=ge(e,{originalSource:t,requiredParams:s,unsafeFunctions:o,safeFunctions:i});e=E;let T=lt(e);e=T.source,e=Ke(e);let $=ft(e,s);e=$.source;let b=Ye(e);e=b.source;let v=[...y.blocks,...w.blocks,...b.blocks],j=mt(e,n.dangerouslySkipTests);e=j.source;let A=dt(e,s);e=A.source;for(let M of A.polyCtorClasses)o.add(`${M}$dispatch`);return c.tjsClass&&(e=gt(e,A.polyCtorClasses)),c.tjsDate&&(e=ht(e)),c.tjsNoeval&&(e=wt(e)),c.tjsNoVar&&(e=bt(e)),e=ct(e,T.extensions),{source:e,returnType:S,returnSafety:h,moduleSafety:r,tjsModes:c,originalSource:t,requiredParams:s,unsafeFunctions:o,safeFunctions:i,wasmBlocks:v,tests:j.tests,testErrors:j.errors,polymorphicNames:$.polymorphicNames,extensions:T.extensions,letAnnotations:g}}function At(e,n={}){let{filename:t="<source>",colonShorthand:r=!0,vmTarget:s=!1,dialect:o}=n,{source:i,returnType:a,returnSafety:l,moduleSafety:c,originalSource:p,requiredParams:m,unsafeFunctions:u,safeFunctions:d,wasmBlocks:g,tests:y,testErrors:w,letAnnotations:E,tjsModes:S}=r?ar(e,{vmTarget:s,dialect:o,moduleLoader:n.moduleLoader,filename:n.filename}):{source:e,returnType:void 0,returnSafety:void 0,moduleSafety:void 0,originalSource:e,requiredParams:new Set,unsafeFunctions:new Set,safeFunctions:new Set,wasmBlocks:[],tests:[],testErrors:[],letAnnotations:new Map,tjsModes:{tjsEquals:!1,tjsClass:!1,tjsDate:!1,tjsNoeval:!1,tjsStandard:!1,tjsSafeEval:!1,tjsNoVar:!1,tjsSafeAssign:!1}};try{return{ast:vt.parse(i,{ecmaVersion:2022,sourceType:"module",locations:!0,allowReturnOutsideFunction:!1}),returnType:a,returnSafety:l,moduleSafety:c,originalSource:p,requiredParams:m,unsafeFunctions:u,safeFunctions:d,wasmBlocks:g,tests:y,testErrors:w,letAnnotations:E,tjsModes:S}}catch(h){let T=h.loc||{line:1,column:0};throw new _(h.message.replace(/\s*\(\d+:\d+\)$/,""),T,p,t)}}function jt(e,n){for(let o of e.body){if(o.type==="ImportDeclaration")throw new _("Imports are not supported. All atoms must be registered with the VM.",o.loc?.start||{line:1,column:0},void 0,n);if(o.type==="ExportNamedDeclaration"||o.type==="ExportDefaultDeclaration")throw new _("Exports are not supported. The function is automatically exported.",o.loc?.start||{line:1,column:0},void 0,n);if(o.type==="ClassDeclaration")throw new _("Classes are not supported. Agent99 uses functional composition.",o.loc?.start||{line:1,column:0},void 0,n)}let t=e.body.filter(o=>o.type==="FunctionDeclaration");if(t.length===0)throw new _("Source must contain a function declaration",{line:1,column:0},void 0,n);let r=t[t.length-1],s=new Map;for(let o=0;o<t.length-1;o++){let i=t[o],a=i.id?.name;if(!a)throw new _("Helper function must have a name",i.loc?.start||{line:1,column:0},void 0,n);if(s.has(a))throw new _(`Duplicate helper function name: ${a}`,i.loc?.start||{line:1,column:0},void 0,n);if(a===r.id?.name)throw new _(`Helper function cannot share a name with the entry function: ${a}`,i.loc?.start||{line:1,column:0},void 0,n);s.set(a,i)}return{entry:r,helpers:s}}function Mt(e,n){let t={params:{}};if(!n.loc)return t;let r=e.substring(0,n.start),s=[...r.matchAll(/\/\*#([\s\S]*?)\*\//g)];if(s.length>0){let p=s[s.length-1],m=r.substring(p.index+p[0].length);if(/^(?:\s|\/\/[^\n]*)*$/.test(m)){let u=p[1],d=u.split(`
|
|
52
|
+
`),g=d.filter(y=>y.trim().length>0).reduce((y,w)=>{let E=w.match(/^(\s*)/)?.[1].length||0;return Math.min(y,E)},1/0);return g>0&&g<1/0&&(u=d.map(y=>y.slice(g)).join(`
|
|
53
|
+
`)),t.description=u.trim(),t}}let o=r.match(/\/\*\*[\s\S]*?\*\/\s*$/);if(!o)return t;let i=o[0],a=i.match(/\/\*\*\s*\n?\s*\*?\s*([^@\n][^\n]*)/m);a&&(t.description=a[1].trim());let l=/@param\s+(?:\{[^}]+\}\s+)?(\w+)\s*-?\s*(.*)/g,c;for(;(c=l.exec(i))!==null;)t.params[c[1]]=c[2].trim();return t}import{parseExpressionAt as lr}from"acorn";function U(e){switch(e.type){case"Literal":{let n=e.value;if(n===null)return{kind:"null"};if(typeof n=="string")return{kind:"string"};if(typeof n=="number"){let t=e.raw;return t&&t.includes(".")?{kind:"number"}:{kind:"integer"}}return typeof n=="boolean"?{kind:"boolean"}:{kind:"any"}}case"ArrayExpression":{let n=e.elements;if(n.length===0)return{kind:"array",items:{kind:"any"}};let t=n.filter(i=>i!=null).map(i=>U(i));if(t.length===0)return{kind:"array",items:{kind:"any"}};let r=new Map;for(let i of t){let a=JSON.stringify(i);r.has(a)||r.set(a,i)}let s=[...r.values()];return{kind:"array",items:s.length===1?s[0]:{kind:"union",members:s}}}case"ObjectExpression":{let n=e.properties,t={};for(let r of n)if(r.type==="Property"&&r.key.type==="Identifier"){let s=r.key.name;t[s]=U(r.value)}return{kind:"object",shape:t}}case"LogicalExpression":{let{operator:n,left:t,right:r}=e;return n==="||"?U(t):n==="&&"||n==="??"?U(r):{kind:"any"}}case"BinaryExpression":{let{operator:n,left:t,right:r}=e;if(n==="|"){let s=U(t),o=U(r);return o.kind==="null"?{...s,nullable:!0}:s.kind==="null"?{...o,nullable:!0}:{kind:"union",members:[s,o]}}return{kind:"any"}}case"Identifier":return e.name==="undefined"?{kind:"undefined"}:{kind:"any"};case"ArrowFunctionExpression":case"FunctionExpression":{let n=e,t=n.params.map(s=>cr(s)),r={kind:"any"};return n.type==="ArrowFunctionExpression"&&n.body&&n.body.type!=="BlockStatement"&&(r=U(n.body)),{kind:"function",params:t,returns:r}}case"UnaryExpression":{let n=e.operator,t=e.argument;if(n==="+"&&t.type==="Literal"&&typeof t.value=="number")return{kind:"non-negative-integer"};if(n==="-"&&t.type==="Literal"&&typeof t.value=="number"){let s=t.raw;return s&&s.includes(".")?{kind:"number"}:{kind:"integer"}}return{kind:"any"}}default:return{kind:"any"}}}function cr(e){return e.type==="Identifier"?{name:e.name,type:{kind:"any"}}:e.type==="AssignmentPattern"&&e.left?.type==="Identifier"?{name:e.left.name,type:U(e.right)}:e.type==="RestElement"&&e.argument?.type==="Identifier"?{name:`...${e.argument.name}`,type:{kind:"array",items:{kind:"any"}}}:{name:"?",type:{kind:"any"}}}function Ce(e,n){if(e.type==="Identifier")return{name:e.name,type:{kind:"any"},required:!0};if(e.type==="AssignmentPattern"){let{left:t,right:r}=e;if(t.type!=="Identifier")throw new P("Only simple parameter names are supported",I(e));let s=t.name,o=n?.has(s)??!1,i=U(r),a=V(r);return{name:s,type:i,required:o,default:o?null:a,example:a,loc:{start:e.start,end:e.end}}}if(e.type==="ObjectPattern"){let t=e.properties,r={},s={};for(let o of t)if(o.type==="Property"){let i=o.key.type==="Identifier"?o.key.name:String(o.key.value);if(o.value.type==="Identifier")r[i]={kind:"any"},s[i]={name:i,type:{kind:"any"},required:!0};else if(o.value.type==="AssignmentPattern"){let a=Ce(o.value,n),l=n?.has(i)??!1;r[i]=a.type,s[i]={name:i,type:a.type,required:l,default:l?null:a.example,example:a.example}}}return{name:"__destructured__",type:{kind:"object",shape:r,destructuredParams:s},required:!0}}throw new P(`Unsupported parameter pattern: ${e.type}`,I(e))}function V(e){switch(e.type){case"Literal":return e.value;case"ArrayExpression":return e.elements.map(n=>n?V(n):null);case"ObjectExpression":{let n={};for(let t of e.properties)t.type==="Property"&&t.key.type==="Identifier"&&(n[t.key.name]=V(t.value));return n}case"UnaryExpression":if(e.operator==="-"){let n=V(e.argument);return typeof n=="number"?-n:void 0}if(e.operator==="+"){let n=V(e.argument);return typeof n=="number"?+n:void 0}return;case"BinaryExpression":{let{operator:n,left:t}=e;return n==="|"?V(t):void 0}case"LogicalExpression":{let{operator:n,left:t,right:r}=e;return n==="&&"&&t.type==="Literal"&&t.value===null?null:n==="||"||n==="??"?V(t)??V(r):void 0}default:return}}function kt(e){try{let n=lr(e,0,{ecmaVersion:2022});return U(n)}catch{return{kind:"any"}}}function ye(e){switch(e.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:e.items?ye(e.items):{}};case"object":if(e.shape){let n={};for(let[t,r]of Object.entries(e.shape))n[t]=ye(r);return{type:"object",properties:n,additionalProperties:!1}}return{type:"object"};case"union":return e.members?{oneOf:e.members.map(ye)}:{};default:return{}}}function ur(e){let n={},t=[];for(let[r,s]of Object.entries(e))n[r]=ye(s.type),s.required&&t.push(r);return{type:"object",properties:n,required:t.length>0?t:void 0,additionalProperties:!1}}function Nt(e,n,t,r={},s,o){let i=Mt(n,e),a=new Map;for(let S of e.params){let h=Ce(S,s);if(h.name==="__destructured__"&&h.type.kind==="object"&&h.type.destructuredParams)for(let[T,$]of Object.entries(h.type.destructuredParams))a.set(T,{...$,description:i.params[T]});else h.description=i.params[h.name],a.set(h.name,h)}let l;t&&(l=kt(t));let c={depth:0,locals:new Map,parameters:a,atoms:new Set(Object.keys(r.atoms||{})),warnings:[],source:n,filename:r.filename||"<source>",options:r,helpers:o,helperSteps:o?new Map:void 0,helperTransforming:o?new Set:void 0},p=W(e.body,c),m=[],u=[],d=[];for(let[S,h]of a.entries())h.required?u.push(S):h.default!==void 0?d.push({name:S,defaultValue:h.default}):u.push(S);u.length>0&&m.push({op:"varsImport",keys:u});for(let{name:S,defaultValue:h}of d)m.push({op:"varsImport",keys:[S]}),m.push({op:"if",condition:{$expr:"binary",op:"==",left:{$expr:"ident",name:S},right:{$expr:"literal",value:null}},then:[{op:"varSet",key:S,value:h}]});m.push(...p);let g=Object.fromEntries(a),y={name:e.id?.name||"anonymous",description:i.description,parameters:g,returns:l},w=ur(g),E=c.helperSteps&&c.helperSteps.size>0?Object.fromEntries(c.helperSteps):void 0;return{ast:{op:"seq",steps:m,inputSchema:w,...E&&{helpers:E}},signature:y,warnings:c.warnings}}function W(e,n){let t=[];for(let r of e.body){let s=oe(r,n);s&&(Array.isArray(s)?t.push(...s):t.push(s))}return t}function oe(e,n){switch(e.type){case"VariableDeclaration":return fr(e,n);case"ExpressionStatement":return pr(e,n);case"IfStatement":return dr(e,n);case"WhileStatement":return gr(e,n);case"ForOfStatement":return hr(e,n);case"TryStatement":return yr(e,n);case"ReturnStatement":return br(e,n);case"ThrowStatement":throw new P("'throw' is not supported in AsyncJS. Use Error('message') to trigger error flow",I(e),n.source,n.filename);case"BlockStatement":return{op:"scope",steps:W(e,q(n))};case"EmptyStatement":return null;default:throw new P(`Unsupported statement type: ${e.type}`,I(e),n.source,n.filename)}}function fr(e,n){let t=[],r=e.kind==="const",s=r?"constSet":"varSet";for(let o of e.declarations){if(o.id.type!=="Identifier")throw new P("Only simple variable names are supported",I(o),n.source,n.filename);let i=o.id.name;if(o.init){let{step:a,resultVar:l}=K(o.init,n,i,r);a?t.push(a):l!==i&&t.push({op:s,key:i,value:l});let c=U(o.init);n.locals.set(i,c)}else{if(r)throw new P("const declarations must be initialized",I(o),n.source,n.filename);t.push({op:"varSet",key:i,value:null}),n.locals.set(i,{kind:"any",nullable:!0})}}return t}function pr(e,n){let t=e.expression;if(t.type==="AssignmentExpression")return mr(t,n);if(t.type==="CallExpression"){let{step:r,resultVar:s}=K(t,n);return r||(s?{op:"varSet",key:"_",value:s}:null)}return n.warnings.push({message:"Expression statement has no effect",line:I(e).line,column:I(e).column}),null}function mr(e,n){if(e.left.type!=="Identifier")throw new P("Only simple variable assignment is supported",I(e),n.source,n.filename);let t=e.left.name,{step:r,resultVar:s}=K(e.right,n,t);return r||{op:"varSet",key:t,value:s}}function dr(e,n){let t=N(e.test,n),r=e.consequent.type==="BlockStatement"?W(e.consequent,q(n)):[oe(e.consequent,n)].filter(Boolean),s;return e.alternate&&(s=e.alternate.type==="BlockStatement"?W(e.alternate,q(n)):[oe(e.alternate,n)].filter(Boolean)),{op:"if",condition:t,then:r,...s&&{else:s}}}function gr(e,n){let t=N(e.test,n),r=e.body.type==="BlockStatement"?W(e.body,q(n)):[oe(e.body,n)].filter(Boolean);return{op:"while",condition:t,body:r}}function hr(e,n){let t;if(e.left.type==="VariableDeclaration"){let i=e.left.declarations[0];if(i.id.type!=="Identifier")throw new P("Only simple variable names are supported in for...of",I(e.left),n.source,n.filename);t=i.id.name}else if(e.left.type==="Identifier")t=e.left.name;else throw new P("Unsupported for...of left-hand side",I(e.left),n.source,n.filename);let r=D(e.right,n),s=q(n);s.locals.set(t,{kind:"any"});let o=e.body.type==="BlockStatement"?W(e.body,s):[oe(e.body,s)].filter(Boolean);return{op:"map",items:r,as:t,steps:o}}function yr(e,n){let t=W(e.block,q(n)),r,s;if(e.handler){let o=q(n);e.handler.param?.type==="Identifier"&&(s=e.handler.param.name,o.locals.set(s,{kind:"any"})),r=W(e.handler.body,o)}return{op:"try",try:t,...r&&{catch:r},...s&&{catchParam:s}}}function br(e,n){if(!e.argument)return{op:"return",value:{}};let{step:t,resultVar:r}=K(e.argument,n,"__returnVal__");return t?[t,{op:"return",value:r}]:{op:"return",value:D(e.argument,n)}}var Rt=new Set(["Math","JSON","Array","Object","String","Number","console","Date","Schema"]),wr=new Set(["parseInt","parseFloat","isNaN","isFinite","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent","Set","Date","filter"]),ae=new Set(["RegExp","Promise","Map","WeakSet","WeakMap","Symbol","Proxy","Reflect","Function","eval","setTimeout","setInterval","fetch","require","import","process","window","document","global","globalThis"]),Sr=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 $r(e){if(e.callee.type==="Identifier"){let n=e.callee.name;return wr.has(n)||ae.has(n)}if(e.callee.type==="MemberExpression"){let n=e.callee;if(n.object.type==="Identifier"){let t=n.object.name;if(Rt.has(t)||ae.has(t))return!0}if(n.property.type==="Identifier"){let t=n.property.name;if(Sr.has(t))return!0}}return!1}function Er(e){if(e.object.type==="Identifier"){let n=e.object.name;return Rt.has(n)||ae.has(n)}return!1}var Ct={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 Tr(e){if(e.callee.type==="Identifier"){let n=e.callee.name;if(ae.has(n))return Ct[n]||`${n} is not available in AsyncJS.`}if(e.callee.type==="MemberExpression"){let n=e.callee;if(n.object.type==="Identifier"){let t=n.object.name;if(ae.has(t))return Ct[t]||`${t} is not available in AsyncJS.`}}return null}function Pt(e){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."}[e]||" Use factory functions or object literals instead."}function K(e,n,t,r){let s=r?"constSet":"varSet";if(e.type==="ChainExpression")return K(e.expression,n,t,r);if(e.type==="NewExpression"){let i=e,a="constructor";i.callee.type==="Identifier"&&(a=i.callee.name);let l=Pt(a);throw new P(`The 'new' keyword is not supported in AsyncJS.${l}`,I(e),n.source,n.filename)}if(e.type==="CallExpression"){let i=Tr(e);if(i)throw new P(i,I(e),n.source,n.filename)}if(e.type==="CallExpression"&&$r(e)){let i=N(e,n);return t?{step:{op:s,key:t,value:i},resultVar:t}:{step:null,resultVar:i}}if(e.type==="MemberExpression"&&Er(e)){let i=N(e,n);return t?{step:{op:s,key:t,value:i},resultVar:t}:{step:null,resultVar:i}}if(e.type==="CallExpression")return xr(e,n,t,r);if(e.type==="TemplateLiteral")return jr(e,n,t,r);if(e.type==="BinaryExpression"||e.type==="LogicalExpression"||e.type==="UnaryExpression"){let i=N(e,n);return t?{step:{op:s,key:t,value:i},resultVar:t}:{step:null,resultVar:i}}return{step:null,resultVar:D(e,n)}}function xr(e,n,t,r){let s,o=!1,i;if(e.callee.type==="Identifier")s=e.callee.name;else if(e.callee.type==="MemberExpression"){let l=e.callee;if(l.property.type==="Identifier")s=l.property.name,o=!0,i=D(l.object,n);else throw new P("Computed method names are not supported",I(e),n.source,n.filename)}else throw new P("Only named function calls are supported",I(e),n.source,n.filename);if(o)return Ar(s,i,e.arguments,n,t,r);if(s==="console"&&e.callee.type,n.helpers?.has(s)){let l=vr(s,n,e),c=e.arguments.map(p=>D(p,n));if(c.length!==l.length)throw new P(`Helper '${s}' expects ${l.length} argument(s), got ${c.length}`,I(e),n.source,n.filename);return{step:{op:"callLocal",name:s,args:c,...t&&{result:t},...t&&r&&{resultConst:!0}},resultVar:t}}let a=Mr(e,n);return{step:{op:s,...a,...t&&{result:t},...t&&r&&{resultConst:!0}},resultVar:t}}function vr(e,n,t){let r=n.helpers.get(e),s=[];for(let o of r.params){let i;if(o.type==="Identifier"?i=o:o.type==="AssignmentPattern"&&o.left?.type==="Identifier"&&(i=o.left),!i)throw new P(`Helper '${e}' parameters must be plain identifiers (optionally with an example value); destructuring is not supported`,o.loc?.start??I(t),n.source,n.filename);s.push(i.name)}if(n.helperSteps.has(e)||n.helperTransforming.has(e))return s;n.helperTransforming.add(e);try{let o={depth:0,locals:new Map,parameters:new Map(s.map(a=>[a,{name:a,type:{kind:"any"},required:!0}])),atoms:n.atoms,warnings:n.warnings,source:n.source,filename:n.filename,options:n.options,helpers:n.helpers,helperSteps:n.helperSteps,helperTransforming:n.helperTransforming},i=W(r.body,o);n.helperSteps.set(e,{steps:i,paramNames:s})}finally{n.helperTransforming.delete(e)}return s}function Ar(e,n,t,r,s,o){switch(e){case"map":if(t.length>0&&(t[0].type==="ArrowFunctionExpression"||t[0].type==="FunctionExpression")){let i=t[0],a=i.params[0],l=a?.type==="Identifier"?a.name:"item",c=q(r);c.locals.set(l,{kind:"any"});let p;if(i.body.type==="BlockStatement")p=W(i.body,c);else{let{step:m,resultVar:u}=K(i.body,c,"result");p=m?[m]:[{op:"varSet",key:"result",value:u}]}return{step:{op:"map",items:n,as:l,steps:p,...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}break;case"filter":if(t.length>0&&(t[0].type==="ArrowFunctionExpression"||t[0].type==="FunctionExpression")){let i=t[0],a=i.params[0],l=a?.type==="Identifier"?a.name:"item",c=q(r);c.locals.set(l,{kind:"any"});let p;if(i.body.type==="BlockStatement")throw new P("filter callback must be an expression, not a block",I(t[0]),r.source,r.filename);return p=N(i.body,c),{step:{op:"filter",items:n,as:l,condition:p,...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}break;case"find":if(t.length>0&&(t[0].type==="ArrowFunctionExpression"||t[0].type==="FunctionExpression")){let i=t[0],a=i.params[0],l=a?.type==="Identifier"?a.name:"item",c=q(r);c.locals.set(l,{kind:"any"});let p;if(i.body.type==="BlockStatement")throw new P("find callback must be an expression, not a block",I(t[0]),r.source,r.filename);return p=N(i.body,c),{step:{op:"find",items:n,as:l,condition:p,...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}break;case"reduce":if(t.length>=2&&(t[0].type==="ArrowFunctionExpression"||t[0].type==="FunctionExpression")){let i=t[0],a=i.params[0],l=i.params[1],c=a?.type==="Identifier"?a.name:"acc",p=l?.type==="Identifier"?l.name:"item",m=q(r);m.locals.set(c,{kind:"any"}),m.locals.set(p,{kind:"any"});let u;if(i.body.type==="BlockStatement")u=W(i.body,m);else{let{step:g,resultVar:y}=K(i.body,m,"result");u=g?[g]:[{op:"varSet",key:"result",value:y}]}let d=D(t[1],r);return{step:{op:"reduce",items:n,as:p,accumulator:c,initial:d,steps:u,...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}break;case"slice":break;case"push":return{step:{op:"push",list:n,item:D(t[0],r),...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s};case"join":return{step:{op:"join",list:n,sep:t.length>0?D(t[0],r):"",...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s};case"split":return{step:{op:"split",str:n,sep:t.length>0?D(t[0],r):"",...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}return r.warnings.push({message:`Unknown method '${e}' - treating as atom call`,line:0,column:0}),{step:{op:e,receiver:n,args:t.map(i=>D(i,r)),...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}function jr(e,n,t,r){let s="",o={};for(let i=0;i<e.quasis.length;i++)if(s+=e.quasis[i].value.cooked||e.quasis[i].value.raw,i<e.expressions.length){let a=e.expressions[i],l=`_${i}`;o[l]=D(a,n),s+=`{{${l}}}`}return{step:{op:"template",tmpl:s,vars:o,...t&&{result:t},...t&&r&&{resultConst:!0}},resultVar:t}}function N(e,n){switch(e.type){case"Literal":return{$expr:"literal",value:e.value};case"Identifier":return{$expr:"ident",name:e.name};case"MemberExpression":{let t=e,r=N(t.object,n),s=t.optional===!0;if(t.computed){let i=t.property;return i.type==="Literal"?{$expr:"member",object:r,property:String(i.value),computed:!0,...s&&{optional:!0}}:{$expr:"member",object:r,property:N(i,n),computed:!0,...s&&{optional:!0}}}let o=t.property.name;return{$expr:"member",object:r,property:o,...s&&{optional:!0}}}case"ChainExpression":return N(e.expression,n);case"BinaryExpression":{let t=e;return{$expr:"binary",op:t.operator,left:N(t.left,n),right:N(t.right,n)}}case"LogicalExpression":{let t=e;return{$expr:"logical",op:t.operator,left:N(t.left,n),right:N(t.right,n)}}case"UnaryExpression":{let t=e;return{$expr:"unary",op:t.operator,argument:N(t.argument,n)}}case"ConditionalExpression":{let t=e;return{$expr:"conditional",test:N(t.test,n),consequent:N(t.consequent,n),alternate:N(t.alternate,n)}}case"ArrayExpression":return{$expr:"array",elements:e.elements.filter(r=>r!==null).map(r=>N(r,n))};case"ObjectExpression":{let t=e,r=[];for(let s of t.properties)if(s.type==="Property"){let o=s.key.type==="Identifier"?s.key.name:String(s.key.value);r.push({key:o,value:N(s.value,n)})}return{$expr:"object",properties:r}}case"CallExpression":{let t=e;if(t.callee.type==="MemberExpression"){let r=t.callee,s=r.property.type==="Identifier"?r.property.name:String(r.property.value),o=r.optional===!0||t.optional===!0;return{$expr:"methodCall",object:N(r.object,n),method:s,arguments:t.arguments.map(i=>N(i,n)),...o&&{optional:!0}}}if(t.callee.type==="Identifier"){let r=t.callee.name;if(n.helpers?.has(r))throw new P(`Helper '${r}' cannot be called inside an expression. Assign its result to a variable first: const result = ${r}(...); then use result.`,I(e),n.source,n.filename);return{$expr:"call",callee:r,arguments:t.arguments.map(s=>N(s,n))}}throw new P("Complex function calls in expressions should be lifted to statements",I(e),n.source,n.filename)}case"NewExpression":{let t=e,r="constructor";t.callee.type==="Identifier"&&(r=t.callee.name);let s=Pt(r);throw new P(`The 'new' keyword is not supported in AsyncJS.${s}`,I(e),n.source,n.filename)}case"TemplateLiteral":throw new P("Template literals inside expressions are not supported. Assign to a variable first: const msg = `hello ${name}`; then use msg",I(e),n.source,n.filename);default:throw new P(`Unsupported expression type in condition: ${e.type}`,I(e),n.source,n.filename)}}function D(e,n){switch(e.type){case"Literal":return e.value;case"Identifier":return e.name;case"MemberExpression":{let t=e;if(t.optional===!0)return N(e,n);let s=D(t.object,n);if(s&&typeof s=="object"&&s.$expr){let i=t.computed?String(t.property.value):t.property.name;return{$expr:"member",object:s,property:i,...t.computed&&{computed:!0}}}if(t.computed)return N(e,n);let o=t.property.name;return typeof s=="string"?`${s}.${o}`:s&&s.$kind==="arg"?{$kind:"arg",path:`${s.path}.${o}`}:`${s}.${o}`}case"ChainExpression":return D(e.expression,n);case"ArrayExpression":return e.elements.map(t=>t?D(t,n):null);case"ObjectExpression":{let t={};for(let r of e.properties)if(r.type==="Property"){let s=r.key.type==="Identifier"?r.key.name:String(r.key.value);t[s]=D(r.value,n)}return t}case"TemplateLiteral":return N(e,n);case"CallExpression":return N(e,n);case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"ConditionalExpression":return N(e,n);default:return null}}function Mr(e,n){if(e.arguments.length===1&&e.arguments[0].type==="ObjectExpression"){let t=e.arguments[0],r={};for(let s of t.properties)if(s.type==="Property"){let o=s.key.type==="Identifier"?s.key.name:String(s.key.value);r[o]=D(s.value,n)}return r}return{args:e.arguments.map(t=>D(t,n))}}function le(e,n={}){let{ast:t,returnType:r,originalSource:s,requiredParams:o}=At(e,{filename:n.filename,colonShorthand:!0,vmTarget:!0}),{entry:i,helpers:a}=jt(t,n.filename),{ast:l,signature:c,warnings:p}=Nt(i,s,r,n,o,a.size>0?a:void 0);return{ast:l,signature:c,warnings:p}}var Cr=6e4,be=class{atoms;_defaultRunTimeout;constructor(n={}){this.atoms={...ve,...n}}get defaultRunTimeout(){if(this._defaultRunTimeout===void 0){let n=0;for(let t of Object.values(this.atoms)){let r=t.timeoutMs??1e3;r>0&&r>n&&(n=r)}this._defaultRunTimeout=Math.max(Cr,n*2)}return this._defaultRunTimeout}get builder(){return new re(this.atoms)}get Agent(){return new re(this.atoms)}get A99(){return this.Agent}resolve(n){return this.atoms[n]}getTools(n="all"){let t=Object.values(this.atoms);if(Array.isArray(n))t=t.filter(r=>n.includes(r.op));else if(n==="flow"){let r=["seq","if","while","return","try","varSet","varGet","scope"];t=t.filter(s=>r.includes(s.op))}return t.map(r=>({type:"function",function:{name:r.op,description:r.docs,parameters:r.inputSchema?.schema??{}}}))}async run(n,t={},r={}){let s;if(typeof n=="string")if(Ee(n))s=Te(n);else try{s=le(n).ast}catch(g){throw new Error(`AJS transpilation failed: ${g.message}`,{cause:g})}else s=n;let o=r.fuel??1e3,i=r.timeoutMs??this.defaultRunTimeout,a=r.capabilities??{},l=[];if(!a.store){let g=new Map,y=!1;a.store={get:async w=>(y||(y=!0,l.push("Using default in-memory store (not suitable for production)")),g.get(w)),set:async(w,E)=>{y||(y=!0,l.push("Using default in-memory store (not suitable for production)")),g.set(w,E)}}}let c=new AbortController,p=setTimeout(()=>c.abort(),i);r.signal&&r.signal.addEventListener("abort",()=>c.abort());let m={fuel:{current:o},args:t,state:{},consts:new Set,capabilities:a,resolver:g=>this.resolve(g),output:void 0,signal:c.signal,costOverrides:r.costOverrides,timeoutOverrides:r.timeoutOverrides,context:r.context,warnings:l,helpers:s.helpers};if(r.trace&&(m.trace=[]),s.op!=="seq")throw new Error("Root AST must be 'seq'. Ensure you're passing a transpiled agent (use ajs`...` or transpile()).");let u=s.inputSchema;if(u&&!kr(t,u)){let g=new O("Input validation failed: args do not match expected schema","vm.run");return{result:g,error:g,fuelUsed:0,trace:m.trace,warnings:l.length>0?l:void 0}}try{await Promise.race([this.resolve("seq")?.exec(s,m),new Promise((g,y)=>{c.signal.addEventListener("abort",()=>{y(new Error(`Execution timeout after ${i}ms. Pass a higher \`timeoutMs\` to vm.run() or set per-atom \`timeoutOverrides\` for slow IO atoms.`))}),c.signal.aborted&&y(new Error(`Execution timeout after ${i}ms. Pass a higher \`timeoutMs\` to vm.run() or set per-atom \`timeoutOverrides\` for slow IO atoms.`))})])}catch(g){if(g.message?.includes("timeout")||g.message?.includes("aborted")||c.signal.aborted)m.error=new O(`Execution timeout after ${i}ms. Pass a higher \`timeoutMs\` to vm.run() or set per-atom \`timeoutOverrides\` for slow IO atoms.`,"vm.run");else throw g}finally{clearTimeout(p)}m.error&&m.output===void 0&&(m.output=m.error);let d=[...l,...m.warnings??[]];return{result:m.output,error:m.error,fuelUsed:o-m.fuel.current,trace:m.trace,warnings:d.length>0?d:void 0}}};var Nr=null,It=()=>Nr??=new be;function Y(e){if(!(!e||typeof e!="object")){if(Array.isArray(e)){for(let n of e)Y(n);return}e.op==="return"&&"value"in e&&(e.value={__result:e.value}),e.steps&&Y(e.steps),e.then&&Y(e.then),e.else&&Y(e.else),e.body&&Y(e.body)}}async function us(e){let{code:n,context:t={},fuel:r=1e3,timeoutMs:s,capabilities:o={}}=e,i=It(),l=/\breturn\b/.test(n)?`function __eval() { ${n} }`:`function __eval() { return (${n}) }`;try{let{ast:c}=le(l);Y(c);let p=await i.run(c,t,{fuel:r,timeoutMs:s,capabilities:o}),m=p.result;return{result:m&&typeof m=="object"&&"__result"in m?m.__result:m,fuelUsed:p.fuelUsed,error:p.error?{message:p.error.message||String(p.error)}:void 0}}catch(c){return{result:void 0,fuelUsed:r,error:{message:c.message||String(c)}}}}async function fs(e){let{body:n,params:t=[],fuel:r=1e3,timeoutMs:s,capabilities:o={}}=e,i=It(),l=`function __safeFn(${t.join(", ")}) { ${n} }`,{ast:c}=le(l);return Y(c),async(...p)=>{let m={};for(let u=0;u<t.length;u++)m[t[u]]=p[u];try{let u=await i.run(c,m,{fuel:r,timeoutMs:s,capabilities:o}),d=u.result;return{result:d&&typeof d=="object"&&"__result"in d?d.__result:d,fuelUsed:u.fuelUsed,error:u.error?{message:u.error.message||String(u.error)}:void 0}}catch(u){return{result:void 0,fuelUsed:r,error:{message:u.message||String(u)}}}}}export{us as Eval,fs as SafeFunction};
|
|
54
54
|
//# sourceMappingURL=tjs-eval.js.map
|