tjs-lang 0.8.7 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/CLAUDE.md +12 -4
  2. package/dist/experiments/ambient/probe.d.ts +52 -0
  3. package/dist/index.js +115 -171
  4. package/dist/index.js.map +4 -4
  5. package/dist/scripts/build-editors.d.ts +19 -0
  6. package/dist/src/css/dimensions.d.ts +23 -0
  7. package/dist/src/css/index.d.ts +85 -0
  8. package/dist/src/css/predicates.d.ts +38 -0
  9. package/dist/src/css/shorthands.d.ts +31 -0
  10. package/dist/src/css/style.d.ts +48 -0
  11. package/dist/src/lang/emitters/js.d.ts +9 -1
  12. package/dist/src/lang/index.d.ts +2 -2
  13. package/dist/src/lang/parser-transforms.d.ts +9 -5
  14. package/dist/src/lang/parser.d.ts +2 -0
  15. package/dist/src/lang/predicate.d.ts +60 -0
  16. package/dist/src/lang/transpiler.d.ts +3 -2
  17. package/dist/src/lang/types.d.ts +16 -0
  18. package/dist/src/schema/index.d.ts +12 -0
  19. package/dist/tjs-browser-from-ts.js +20 -20
  20. package/dist/tjs-browser-from-ts.js.map +3 -3
  21. package/dist/tjs-browser.js +100 -90
  22. package/dist/tjs-browser.js.map +4 -4
  23. package/dist/tjs-css.js +193 -0
  24. package/dist/tjs-css.js.map +7 -0
  25. package/dist/tjs-eval.js +43 -42
  26. package/dist/tjs-eval.js.map +4 -4
  27. package/dist/tjs-from-ts.js +13 -13
  28. package/dist/tjs-from-ts.js.map +2 -2
  29. package/dist/tjs-lang.js +102 -92
  30. package/dist/tjs-lang.js.map +4 -4
  31. package/dist/tjs-runtime.js +10 -0
  32. package/dist/tjs-runtime.js.map +7 -0
  33. package/dist/tjs-schema.js +6 -0
  34. package/dist/tjs-schema.js.map +7 -0
  35. package/dist/tjs-vm.js +55 -54
  36. package/dist/tjs-vm.js.map +4 -4
  37. package/docs/ambient-contracts.md +261 -0
  38. package/editors/ace/ajs-mode.js +214 -233
  39. package/editors/codemirror/ajs-language.js +1570 -233
  40. package/editors/editors-build.test.ts +29 -0
  41. package/editors/monaco/ajs-monarch.js +239 -195
  42. package/llms.txt +4 -0
  43. package/package.json +35 -4
  44. package/src/css/css.test.ts +122 -0
  45. package/src/css/dimensions.test.ts +112 -0
  46. package/src/css/dimensions.ts +146 -0
  47. package/src/css/index.ts +243 -0
  48. package/src/css/perf.bench.test.ts +109 -0
  49. package/src/css/predicates.ts +232 -0
  50. package/src/css/property-aware.test.ts +84 -0
  51. package/src/css/shorthands.test.ts +90 -0
  52. package/src/css/shorthands.ts +113 -0
  53. package/src/css/style.test.ts +125 -0
  54. package/src/css/style.ts +134 -0
  55. package/src/index-tsfree.test.ts +58 -0
  56. package/src/lang/emit-verified-predicate.test.ts +95 -0
  57. package/src/lang/emitters/dts.test.ts +31 -0
  58. package/src/lang/emitters/dts.ts +23 -4
  59. package/src/lang/emitters/js.ts +33 -1
  60. package/src/lang/from-ts.test.ts +1 -1
  61. package/src/lang/generic-verified-predicate.test.ts +39 -0
  62. package/src/lang/index.ts +14 -5
  63. package/src/lang/parser-transforms.ts +109 -14
  64. package/src/lang/parser.ts +9 -2
  65. package/src/lang/predicate-evaluator.test.ts +49 -0
  66. package/src/lang/predicate-report.test.ts +54 -0
  67. package/src/lang/predicate.ts +268 -0
  68. package/src/lang/redos-lint.test.ts +81 -0
  69. package/src/lang/transpiler.ts +13 -0
  70. package/src/lang/type-verified-predicate.test.ts +83 -0
  71. package/src/lang/types.ts +17 -0
  72. package/src/lang/typescript-syntax.test.ts +2 -1
  73. package/src/schema/index.ts +62 -0
  74. package/src/schema/schema.test.ts +66 -0
  75. package/src/use-cases/bootstrap.test.ts +14 -4
package/dist/tjs-eval.js CHANGED
@@ -1,54 +1,55 @@
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
- `),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 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
- `)}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 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(`,
1
+ import{s as m,validate as xe,filter as ze}from"tosijs-schema";function Oe(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 D=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 Vt(e){return e instanceof D||e&&e.$error===!0}var te=new Map,zt=3600*1e3,Jt=100*1024,$e="proc_";function ve(e){return typeof e=="string"&&e.startsWith($e)}function Te(e){let n=te.get(e);if(!n)throw new Error(`Procedure not found: ${e}`);if(Date.now()>n.expiresAt)throw te.delete(e),new Error(`Procedure expired: ${e}`);return n.ast}function Zt(){return typeof crypto<"u"&&crypto.randomUUID?$e+crypto.randomUUID():$e+Math.random().toString(36).slice(2)+Date.now().toString(36)}var Je=new Set(["__proto__","constructor","prototype"]);function De(e){if(Je.has(e))throw new Error(`Security Error: Access to '${e}' is forbidden`)}var Gt=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","metadata.google.internal"]);function Ht(e){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return!0;let t=n.hostname.toLowerCase();return!!(Gt.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 Kt(e){return!!(/\([^)]*[+*][^)]*\)[+*]/.test(e)||/\(([^|)]+)\|\1\)[+*]/.test(e)||/\(\.\*\)\+/.test(e)||/\(\.\+\)\+/.test(e)||/\(\[.*\]\+\)\+/.test(e))}function H(e){return{...e,state:Object.create(e.state)}}function Yt(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 A(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(Je.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]=A(e[r],n);return t}return Array.isArray(e)?e.map(t=>A(t,n)):e}function K(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 ee(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:ee(e[0])};if(n==="object"){let t={},r=[];for(let[s,o]of Object.entries(e))t[s]=ee(o),r.push(s);return{type:"object",properties:t,required:r}}return{}}var J={Math:K("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:K("JSON",{parse:e=>JSON.parse(e),stringify:(e,n,t)=>JSON.stringify(e,n,t)}),console:K("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:K("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:K("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:K("String",{fromCharCode:(...e)=>String.fromCharCode(...e),fromCodePoint:(...e)=>String.fromCodePoint(...e)}),Number:K("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=ee(n),r=ze(e,t);if(r instanceof Error)throw r;return r},Schema:{...m,response:(e,n)=>{let t=n?.schema!=null?n.schema:ee(n);return{type:"json_schema",json_schema:{name:e,strict:!0,schema:t}}},fromExample:e=>ee(e),isValid:(e,n)=>n?.schema!=null?xe(e,n):xe(e,ee(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 J.Set([...n,...r])},intersection(t){let r=t?.toArray?.()??t??[];return J.Set(n.filter(s=>r.includes(s)))},diff(t){let r=t?.toArray?.()??t??[];return J.Set(n.filter(s=>!r.includes(s)))},forEach(t){n.forEach(t)},map(t){return J.Set(n.map(t))},filter(t){return J.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 u=new globalThis.Date(t.getTime());return r&&u.setFullYear(u.getFullYear()+r),s&&u.setMonth(u.getMonth()+s),o&&u.setDate(u.getDate()+o),i&&u.setHours(u.getHours()+i),a&&u.setMinutes(u.getMinutes()+a),l&&u.setSeconds(u.getSeconds()+l),c&&u.setMilliseconds(u.getMilliseconds()+c),e(u)},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})()},fe={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."},Xt=.01,Fe=1e-4,Ue=.001,Qt=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-=Xt,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 J)return J[e.name];if(e.name in fe)throw new Error(fe[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 De(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*Fe,n.fuel.current<=0)){n.error=new D("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 Oe(t,r);case"!=":return!Oe(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 D(s,"Error");return}if(e.callee in J){let r=J[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 fe?new Error(fe[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(De(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&&Qt.has(r)){let a=0;if(typeof i=="string"?a=i.length*Fe:Array.isArray(i)?a=i.length*Ue:typeof i=="object"&&i!==null&&(a=Object.keys(i).length*Ue),n.fuel.current-=a,n.fuel.current<=0){n.error=new D("Out of Fuel",`expr.${r}`);return}}return i}default:throw new Error(`Unknown expression type: ${e.$expr}`)}}function P(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(u,p)=>{let{op:f,result:d,...g}=u;if(p.error)return;let b=p.trace?{...p.state}:null,w=p.fuel.current,E,v;try{let h=p.costOverrides?.[e],$=h!==void 0?h:a,S=typeof $=="function"?$(g,p):$;if((p.fuel.current-=S)<=0){p.error=new D("Out of Fuel",e);return}let y=p.timeoutOverrides?.[e],T=y!==void 0?y:i,M=typeof T=="function"?T(g,p):T,k,C=async()=>r(u,p);if(E=M>0?await Promise.race([C(),new Promise((j,R)=>{k=setTimeout(()=>R(new Error(`Atom '${e}' timed out`)),M)})]).finally(()=>clearTimeout(k)):await C(),u.result){if(p.consts.has(u.result))throw new Error(`Cannot reassign const variable '${u.result}'`);if(E!==void 0&&t&&!xe(E,t)){p.error=new D(`Output validation failed for '${e}'`,e);return}p.state[u.result]=E,u.resultConst&&p.consts.add(u.result)}}catch(h){v=h.message||String(h),p.error=new D(v,e,h)}finally{if(p.trace&&b){let h=Yt(b,p.state);p.trace.push({op:e,input:g,stateDiff:h,result:E,error:v,fuelBefore:w,fuelAfter:p.fuel.current,timestamp:new Date().toISOString()})}}},docs:o,timeoutMs:i,cost:a,effects:l,create:u=>({op:e,...u})}}var U=P("seq",m.object({steps:m.array(m.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}),en=P("if",m.object({condition:m.any,then:m.array(m.any),else:m.array(m.any).optional}),void 0,async(e,n)=>{B(e.condition,n)?await U.exec({op:"seq",steps:e.then},n):e.else&&await U.exec({op:"seq",steps:e.else},n)},{docs:"If/Else",timeoutMs:0,cost:.1}),tn=P("while",m.object({condition:m.any,body:m.array(m.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 U.exec({op:"seq",steps:e.body},n),n.output!==void 0||n.error)return}},{docs:"While Loop",timeoutMs:0,cost:.1}),nn=P("return",void 0,m.any,async(e,n)=>{if(n.error)return n.output=n.error,n.error;if("value"in e){let r=A(e.value,n);if(!n.localCall&&r!==void 0&&r!==null&&!Vt(r)&&(typeof r!="object"||Array.isArray(r))){let s=new D(`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=ze(t,e.schema);r instanceof Error||(t=r)}}return n.output=t,t},{docs:"Return",cost:.1}),rn=P("try",m.object({try:m.array(m.any),catch:m.array(m.any).optional,catchParam:m.string.optional}),void 0,async(e,n)=>{if(await U.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 U.exec({op:"seq",steps:e.catch},n)}},{docs:"Try/Catch",timeoutMs:0,cost:.1}),sn=P("Error",m.object({args:m.array(m.any).optional}),void 0,async(e,n)=>{let t=e.args?.[0]??"Error";n.error=new D(String(t),"Error")},{docs:"Trigger error flow",cost:.1}),on=P("varSet",m.object({key:m.string,value:m.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]=A(n,t)},{docs:"Set Variable",cost:.1}),an=P("constSet",m.object({key:m.string,value:m.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]=A(n,t),t.consts.add(e)},{docs:"Set Const Variable (immutable)",cost:.1}),ln=P("varGet",m.object({key:m.string}),m.any,async({key:e},n)=>A(e,n),{docs:"Get Variable",cost:.1}),cn=P("varsImport",m.object({keys:m.union([m.array(m.string),m.record(m.string)])}),void 0,async({keys:e},n)=>{if(Array.isArray(e))for(let t of e)n.state[t]=A({$kind:"arg",path:t},n);else for(let[t,r]of Object.entries(e))n.state[t]=A({$kind:"arg",path:r},n)},{docs:"Import variables from args into the current scope, with optional renaming.",cost:.2}),un=P("varsLet",m.record(m.any),void 0,async(e,n)=>{for(let t of Object.keys(e))t==="op"||t==="result"||(n.state[t]=A(e[t],n))},{docs:"Initialize a set of variables in the current scope from the step object properties.",cost:.1}),fn=P("varsExport",m.object({keys:m.union([m.array(m.string),m.record(m.string)])}),m.record(m.any),async({keys:e},n)=>{let t={};if(Array.isArray(e))for(let r of e)t[r]=A(r,n);else for(let[r,s]of Object.entries(e))t[r]=A(s,n);return t},{docs:"Export variables from the current scope, with optional renaming.",cost:.2}),pn=P("scope",m.object({steps:m.array(m.any)}),void 0,async({steps:e},n)=>{let t=H(n);await U.exec({op:"seq",steps:e},t),t.output!==void 0&&(n.output=t.output)},{docs:"Create new scope",timeoutMs:0,cost:.1}),Le=256,mn=P("callLocal",m.object({name:m.string,args:m.array(m.any)}),void 0,async({name:e,args:n},t)=>{let r=t.helpers?.[e];if(!r)return t.error=new D(`Unknown helper: ${e}`,"callLocal"),t.error;let s=(t.callDepth??0)+1;if(s>Le)return t.error=new D(`Maximum helper call depth (${Le}) exceeded \u2014 likely infinite recursion in '${e}'`,"callLocal"),t.error;let o=n.map(a=>A(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 U.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}),dn=P("map",m.object({items:m.array(m.any),as:m.string,steps:m.array(m.any)}),m.array(m.any),async({items:e,as:n,steps:t},r)=>{let s=[],o=A(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=H(r);a.state[n]=i,await U.exec({op:"seq",steps:t},a),s.push(a.state.result??null)}return s},{docs:"Map Array",timeoutMs:0,cost:1}),gn=P("filter",m.object({items:m.array(m.any),as:m.string,condition:m.any}),m.array(m.any),async({items:e,as:n,condition:t},r)=>{let s=[],o=A(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=H(r);a.state[n]=i,B(t,a)&&s.push(i)}return s},{docs:"Filter Array",timeoutMs:0,cost:1}),hn=P("reduce",m.object({items:m.array(m.any),as:m.string,accumulator:m.string,initial:m.any,steps:m.array(m.any)}),m.any,async({items:e,as:n,accumulator:t,initial:r,steps:s},o)=>{let i=A(e,o),a=A(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 u=H(o);u.state[n]=c,u.state[t]=l,await U.exec({op:"seq",steps:s},u),l=u.state.result??l}return l},{docs:"Reduce Array",timeoutMs:0,cost:1}),yn=P("find",m.object({items:m.array(m.any),as:m.string,condition:m.any}),m.any,async({items:e,as:n,condition:t},r)=>{let s=A(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=H(r);if(i.state[n]=o,B(t,i))return o}return null},{docs:"Find in Array",timeoutMs:0,cost:1}),bn=P("push",m.object({list:m.array(m.any),item:m.any}),m.array(m.any),async({list:e,item:n},t)=>{let r=A(e,t),s=A(n,t);return Array.isArray(r)&&r.push(s),r},{docs:"Push to Array",cost:1}),wn=P("len",m.object({list:m.any}),m.number,async({list:e},n)=>{let t=A(e,n);return Array.isArray(t)||typeof t=="string"?t.length:0},{docs:"Length",cost:1}),Sn=P("split",m.object({str:m.string,sep:m.string}),m.array(m.string),async({str:e,sep:n},t)=>A(e,t).split(A(n,t)),{docs:"Split String",cost:1}),En=P("join",m.object({list:m.array(m.string),sep:m.string}),m.string,async({list:e,sep:n},t)=>A(e,t).join(A(n,t)),{docs:"Join String",cost:1}),xn=P("template",m.object({tmpl:m.string,vars:m.record(m.any)}),m.string,async({tmpl:e,vars:n},t)=>A(e,t).replace(/\{\{(\w+)\}\}/g,(s,o)=>String(A(n[o],t)??"")),{docs:"String Template",cost:1}),$n=P("regexMatch",m.object({pattern:m.string,value:m.any}),m.boolean,async({pattern:e,value:n},t)=>{if(Kt(e))throw new Error(`Suspicious regex pattern rejected (potential ReDoS): ${e}`);let r=A(n,t);return new RegExp(e).test(r)},{docs:"Returns true if the value matches the regex pattern.",cost:2}),vn=P("pick",m.object({obj:m.record(m.any),keys:m.array(m.string)}),m.record(m.any),async({obj:e,keys:n},t)=>{let r=A(e,t),s=A(n,t),o={};return r&&Array.isArray(s)&&s.forEach(i=>o[i]=r[i]),o},{docs:"Pick Keys",cost:1}),Tn=P("omit",m.object({obj:m.record(m.any),keys:m.array(m.string)}),m.record(m.any),async({obj:e,keys:n},t)=>{let r=A(e,t),s=new Set(A(n,t)),o={};return r&&Object.keys(r).forEach(i=>{s.has(i)||(o[i]=r[i])}),o},{docs:"Omit Keys",cost:1}),An=P("merge",m.object({a:m.record(m.any),b:m.record(m.any)}),m.record(m.any),async({a:e,b:n},t)=>({...A(e,t),...A(n,t)}),{docs:"Merge Objects",cost:1}),kn=P("keys",m.object({obj:m.record(m.any)}),m.array(m.string),async({obj:e},n)=>Object.keys(A(e,n)??{}),{docs:"Object Keys",cost:1}),qe=10,We="X-Agent-Depth";function jn(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 Mn=P("httpFetch",m.object({url:m.string,method:m.string.optional,headers:m.record(m.string).optional,body:m.any.optional,responseType:m.string.optional}),m.any,async(e,n)=>{let t=A(e.url,n),r=A(e.method,n),s=A(e.headers,n)||{},o=A(e.body,n),i=A(e.responseType,n),a=n.context?.requestDepth??0;if(a>=qe)throw new Error(`Agent request depth exceeded (max ${qe}). This prevents recursive agent loops.`);if(n.capabilities.fetch)return n.capabilities.fetch(t,{method:r,headers:{...s,[We]:String(a+1)},body:o,signal:n.signal,responseType:i});let l=n.context?.allowedFetchDomains;if(l){if(!jn(t,l))throw new Error(`Fetch blocked: domain not in allowlist. Allowed: ${l.join(", ")}`)}else{if(Ht(t))throw new Error("Blocked URL: private/internal addresses not allowed in default fetch");try{let u=new URL(t).hostname.toLowerCase();if(u!=="localhost"&&u!=="127.0.0.1"&&u!=="[::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,[We]:String(a+1)},body:o?JSON.stringify(o):void 0,signal:n.signal});if(i==="dataUrl"){let p=await c.arrayBuffer(),f=new Uint8Array(p),d="";for(let w=0;w<f.length;w++)d+=String.fromCharCode(f[w]);let g=btoa(d);return`data:${c.headers.get("content-type")||"application/octet-stream"};base64,${g}`}let u=c.headers.get("content-type");return i==="json"||u&&u.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}),Pn=P("storeGet",m.object({key:m.string}),m.any,async({key:e},n)=>{let t=A(e,n);return n.capabilities.store?.get(t)},{docs:"Store Get",cost:5}),Cn=P("storeSet",m.object({key:m.string,value:m.any}),void 0,async({key:e,value:n},t)=>{let r=A(e,t),s=A(n,t);return t.capabilities.store?.set(r,s)},{docs:"Store Set",cost:5}),Rn=P("storeQuery",m.object({query:m.any}),m.array(m.any),async({query:e},n)=>n.capabilities.store?.query?.(A(e,n))??[],{docs:"Store Query",cost:5}),Nn=P("storeVectorSearch",m.object({collection:m.string.optional,vector:m.array(m.number),k:m.number.optional}),m.array(m.any),async({collection:e,vector:n,k:t},r)=>r.capabilities.store?.vectorSearch?.(A(e,r),A(n,r),A(t,r))??[],{docs:"Vector Search",cost:(e,n)=>5+(A(e.k,n)??5)}),In=P("llmPredict",m.object({prompt:m.string,options:m.any.optional}),m.string,async({prompt:e,options:n},t)=>{if(!t.capabilities.llm?.predict)throw new Error("Capability 'llm.predict' missing");return t.capabilities.llm.predict(A(e,t),A(n,t))},{docs:"LLM Predict",timeoutMs:12e4,cost:100}),_n=P("agentRun",m.object({agentId:m.any,input:m.any}),m.any,async({agentId:e,input:n},t)=>{let r=A(e,t),s=A(n,t),o=s;if(s&&typeof s=="object"&&!Array.isArray(s)){o={};for(let a in s)o[a]=A(s[a],t)}if(ve(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}),Bn=P("transpileCode",m.object({code:m.string}),m.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=A(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}),Ve=10,On=P("runCode",m.object({code:m.string,args:m.record(m.any).optional}),m.any,async({code:e,args:n},t)=>{let r=t.runCodeDepth??0;if(r>=Ve)throw new Error(`runCode recursion limit exceeded (max ${Ve}). 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=A(e,t),o=n?A(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=H(t);if(a.args=o,a.output=void 0,a.runCodeDepth=r+1,await U.exec(i,a),a.error){t.error=a.error;return}return a.output},{docs:"Run dynamically generated AsyncJS code",cost:1}),Dn=P("jsonParse",m.object({str:m.string}),m.any,async({str:e},n)=>JSON.parse(A(e,n)),{docs:"Parse JSON",cost:1}),Fn=P("jsonStringify",m.object({value:m.any}),m.string,async({value:e},n)=>JSON.stringify(A(e,n)),{docs:"Stringify JSON",cost:1}),Un=P("xmlParse",m.object({str:m.string}),m.any,async({str:e},n)=>{if(!n.capabilities.xml?.parse)throw new Error("Capability 'xml.parse' missing");return n.capabilities.xml.parse(A(e,n))},{docs:"Parse XML",cost:1}),Ln=P("memoize",m.object({key:m.string.optional,steps:m.array(m.any)}),m.any,async({key:e,steps:n},t)=>{t.memo||(t.memo=new Map);let r=A(e,t)??await Ae.exec({value:n,algorithm:"SHA-256"},t);if(t.memo.has(r))return t.memo.get(r);let s=H(t);await U.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}),qn=P("cache",m.object({key:m.string.optional,steps:m.array(m.any),ttlMs:m.number.optional}),m.any,async({key:e,steps:n,ttlMs:t},r)=>{if(!r.capabilities.store)throw new Error("Capability 'store' missing for caching");let o=`cache:${A(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=H(r);await U.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}),Wn=P("random",m.object({min:m.number.optional,max:m.number.optional,format:m.string.optional,length:m.number.optional}),m.any,async({min:e,max:n,format:t,length:r},s)=>{let o=A(t,s)??"float",i=A(r,s)??10,a=A(e,s)??0,l=A(n,s)??1;if(o==="base36"){let f="0123456789abcdefghijklmnopqrstuvwxyz",d="";if(typeof crypto<"u"&&crypto.getRandomValues){let g=new Uint8Array(i);crypto.getRandomValues(g);for(let b=0;b<i;b++)d+=f[g[b]%36]}else for(let g=0;g<i;g++)d+=f.charAt(Math.floor(Math.random()*36));return d}let c;if(typeof crypto<"u"&&crypto.getRandomValues){let f=new Uint32Array(1);crypto.getRandomValues(f),c=f[0]/4294967296}else c=Math.random();let u=l-a,p=c*u+a;return o==="integer"?Math.floor(p):p},{docs:"Generate Random",cost:1}),Vn=P("uuid",void 0,m.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=P("hash",m.object({value:m.any,algorithm:m.string.optional}),m.string,async({value:e,algorithm:n},t)=>{let r=typeof e=="string"?e:JSON.stringify(A(e,t)),s=A(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(u=>u.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}),zn=P("consoleLog",m.object({message:m.any}),void 0,async({message:e},n)=>{let t=A(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}),Jn=P("consoleWarn",m.object({message:m.any}),void 0,async({message:e},n)=>{let t=A(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}),Zn=P("consoleError",m.object({message:m.any}),void 0,async({message:e},n)=>{let t=A(e,n),r=typeof t=="string"?t:JSON.stringify(t);n.error=new D(r,"console.error")},{docs:"Emit error and stop",cost:.1}),Gn=P("storeProcedure",m.object({ast:m.any,ttl:m.number.optional,maxSize:m.number.optional}),m.string,async({ast:e,ttl:n,maxSize:t},r)=>{let s=A(e,r),o=n?A(n,r):zt,i=t?A(t,r):Jt;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=Zt(),c=Date.now();return te.set(l,{ast:s,createdAt:c,expiresAt:c+o}),l},{docs:"Store an AST and return a token for later execution",cost:1}),Hn=P("releaseProcedure",m.object({token:m.string}),m.boolean,async({token:e},n)=>{let t=A(e,n);return te.delete(t)},{docs:"Release a stored procedure by token",cost:.1}),Kn=P("clearExpiredProcedures",void 0,m.number,async()=>{let e=Date.now(),n=0;for(let[t,r]of te)e>r.expiresAt&&(te.delete(t),n++);return n},{docs:"Clear all expired procedures and return count",cost:.5}),ke={seq:U,if:en,while:tn,return:nn,try:rn,Error:sn,varSet:on,constSet:an,varGet:ln,varsImport:cn,varsLet:un,varsExport:fn,scope:pn,callLocal:mn,map:dn,filter:gn,reduce:hn,find:yn,push:bn,len:wn,split:Sn,join:En,template:xn,regexMatch:$n,pick:vn,omit:Tn,merge:An,keys:kn,httpFetch:Mn,storeGet:Pn,storeSet:Cn,storeQuery:Rn,storeVectorSearch:Nn,llmPredict:In,agentRun:_n,transpileCode:Bn,runCode:On,jsonParse:Dn,jsonStringify:Fn,xmlParse:Un,memoize:Ln,cache:qn,random:Wn,uuid:Vn,hash:Ae,consoleLog:zn,consoleWarn:Jn,consoleError:Zn,storeProcedure:Gn,releaseProcedure:Hn,clearExpiredProcedures:Kn},Yn=["httpFetch","storeGet","storeSet","storeQuery","storeVectorSearch","llmPredict","agentRun","transpileCode","runCode","random","uuid","consoleLog","consoleWarn","consoleError","storeProcedure","releaseProcedure","clearExpiredProcedures","cache","memoize"];for(let e of Yn){let n=ke[e];n&&(n.effects="io")}var Xn=new Set(["true","false","null","undefined","and","or","not"]);function Qn(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=>!Xn.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){Qn(e,n);let t=er(e),r=Ye(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 er(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 Ye(e,n,t){return tr(e,n,t)}function tr(e,n,t){let{node:r,pos:s}=Ze(e,n,t);for(;e[s]==="||";){s++;let{node:o,pos:i}=Ze(e,s,t);r={$expr:"logical",op:"||",left:r,right:o},s=i}return{node:r,pos:s}}function Ze(e,n,t){let{node:r,pos:s}=Ge(e,n,t);for(;e[s]==="&&";){s++;let{node:o,pos:i}=Ge(e,s,t);r={$expr:"logical",op:"&&",left:r,right:o},s=i}return{node:r,pos:s}}function Ge(e,n,t){let{node:r,pos:s}=He(e,n,t),o=["==","!=",">","<",">=","<="];for(;o.includes(e[s]);){let i=e[s++],{node:a,pos:l}=He(e,s,t);r={$expr:"binary",op:i,left:r,right:a},s=l}return{node:r,pos:s}}function He(e,n,t){let{node:r,pos:s}=Ke(e,n,t);for(;e[s]==="+"||e[s]==="-";){let o=e[s++],{node:i,pos:a}=Ke(e,s,t);r={$expr:"binary",op:o,left:r,right:i},s=a}return{node:r,pos:s}}function Ke(e,n,t){let{node:r,pos:s}=je(e,n,t);for(;e[s]==="*"||e[s]==="/"||e[s]==="%";){let o=e[s++],{node:i,pos:a}=je(e,s,t);r={$expr:"binary",op:o,left:r,right:i},s=a}return{node:r,pos:s}}function je(e,n,t){if(e[n]==="!"||e[n]==="-"){let r=e[n++],{node:s,pos:o}=je(e,n,t);return{node:{$expr:"unary",op:r,argument:s},pos:o}}return nr(e,n,t)}function nr(e,n,t){let r=e[n];if(r==="("){let{node:s,pos:o}=Ye(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 ie=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=pe(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=pe(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=pe(r,s),i=this.atoms.filter;return this.add(i.create({items:n,as:t,condition:o}))}find(n,t,r,s={}){let o=pe(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 Zr}from"tosijs-schema";import*as It from"acorn";var I=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}},O=class extends I{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
+ `),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),u=l===r?">":" ";if(i.push(`${u} ${c} | ${t[l]}`),l===r){let p=" ".repeat(a+4+this.column);i.push(`${p}^ ${this.message.split(" at ")[0]}`)}}return i.join(`
4
+ `)}};function W(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 _(e){return e.loc?{line:e.loc.start.line,column:e.loc.start.column}:{line:1,column:0}}import*as Ce from"acorn";function Me(e,n,t,r,s){t||(t=x),(function o(i,a,l){var c=l||i.type;t[c](i,a,o),n[c]&&n[c](i,a)})(e,r,s)}function Pe(e,n,t){t(e,n)}function Y(e,n,t){}var x={};x.Program=x.BlockStatement=x.StaticBlock=function(e,n,t){for(var r=0,s=e.body;r<s.length;r+=1){var o=s[r];t(o,n,"Statement")}};x.Statement=Pe;x.EmptyStatement=Y;x.ExpressionStatement=x.ParenthesizedExpression=x.ChainExpression=function(e,n,t){return t(e.expression,n,"Expression")};x.IfStatement=function(e,n,t){t(e.test,n,"Expression"),t(e.consequent,n,"Statement"),e.alternate&&t(e.alternate,n,"Statement")};x.LabeledStatement=function(e,n,t){return t(e.body,n,"Statement")};x.BreakStatement=x.ContinueStatement=Y;x.WithStatement=function(e,n,t){t(e.object,n,"Expression"),t(e.body,n,"Statement")};x.SwitchStatement=function(e,n,t){t(e.discriminant,n,"Expression");for(var r=0,s=e.cases;r<s.length;r+=1){var o=s[r];t(o,n)}};x.SwitchCase=function(e,n,t){e.test&&t(e.test,n,"Expression");for(var r=0,s=e.consequent;r<s.length;r+=1){var o=s[r];t(o,n,"Statement")}};x.ReturnStatement=x.YieldExpression=x.AwaitExpression=function(e,n,t){e.argument&&t(e.argument,n,"Expression")};x.ThrowStatement=x.SpreadElement=function(e,n,t){return t(e.argument,n,"Expression")};x.TryStatement=function(e,n,t){t(e.block,n,"Statement"),e.handler&&t(e.handler,n),e.finalizer&&t(e.finalizer,n,"Statement")};x.CatchClause=function(e,n,t){e.param&&t(e.param,n,"Pattern"),t(e.body,n,"Statement")};x.WhileStatement=x.DoWhileStatement=function(e,n,t){t(e.test,n,"Expression"),t(e.body,n,"Statement")};x.ForStatement=function(e,n,t){e.init&&t(e.init,n,"ForInit"),e.test&&t(e.test,n,"Expression"),e.update&&t(e.update,n,"Expression"),t(e.body,n,"Statement")};x.ForInStatement=x.ForOfStatement=function(e,n,t){t(e.left,n,"ForInit"),t(e.right,n,"Expression"),t(e.body,n,"Statement")};x.ForInit=function(e,n,t){e.type==="VariableDeclaration"?t(e,n):t(e,n,"Expression")};x.DebuggerStatement=Y;x.FunctionDeclaration=function(e,n,t){return t(e,n,"Function")};x.VariableDeclaration=function(e,n,t){for(var r=0,s=e.declarations;r<s.length;r+=1){var o=s[r];t(o,n)}};x.VariableDeclarator=function(e,n,t){t(e.id,n,"Pattern"),e.init&&t(e.init,n,"Expression")};x.Function=function(e,n,t){e.id&&t(e.id,n,"Pattern");for(var r=0,s=e.params;r<s.length;r+=1){var o=s[r];t(o,n,"Pattern")}t(e.body,n,e.expression?"Expression":"Statement")};x.Pattern=function(e,n,t){e.type==="Identifier"?t(e,n,"VariablePattern"):e.type==="MemberExpression"?t(e,n,"MemberPattern"):t(e,n)};x.VariablePattern=Y;x.MemberPattern=Pe;x.RestElement=function(e,n,t){return t(e.argument,n,"Pattern")};x.ArrayPattern=function(e,n,t){for(var r=0,s=e.elements;r<s.length;r+=1){var o=s[r];o&&t(o,n,"Pattern")}};x.ObjectPattern=function(e,n,t){for(var r=0,s=e.properties;r<s.length;r+=1){var o=s[r];o.type==="Property"?(o.computed&&t(o.key,n,"Expression"),t(o.value,n,"Pattern")):o.type==="RestElement"&&t(o.argument,n,"Pattern")}};x.Expression=Pe;x.ThisExpression=x.Super=x.MetaProperty=Y;x.ArrayExpression=function(e,n,t){for(var r=0,s=e.elements;r<s.length;r+=1){var o=s[r];o&&t(o,n,"Expression")}};x.ObjectExpression=function(e,n,t){for(var r=0,s=e.properties;r<s.length;r+=1){var o=s[r];t(o,n)}};x.FunctionExpression=x.ArrowFunctionExpression=x.FunctionDeclaration;x.SequenceExpression=function(e,n,t){for(var r=0,s=e.expressions;r<s.length;r+=1){var o=s[r];t(o,n,"Expression")}};x.TemplateLiteral=function(e,n,t){for(var r=0,s=e.quasis;r<s.length;r+=1){var o=s[r];t(o,n)}for(var i=0,a=e.expressions;i<a.length;i+=1){var l=a[i];t(l,n,"Expression")}};x.TemplateElement=Y;x.UnaryExpression=x.UpdateExpression=function(e,n,t){t(e.argument,n,"Expression")};x.BinaryExpression=x.LogicalExpression=function(e,n,t){t(e.left,n,"Expression"),t(e.right,n,"Expression")};x.AssignmentExpression=x.AssignmentPattern=function(e,n,t){t(e.left,n,"Pattern"),t(e.right,n,"Expression")};x.ConditionalExpression=function(e,n,t){t(e.test,n,"Expression"),t(e.consequent,n,"Expression"),t(e.alternate,n,"Expression")};x.NewExpression=x.CallExpression=function(e,n,t){if(t(e.callee,n,"Expression"),e.arguments)for(var r=0,s=e.arguments;r<s.length;r+=1){var o=s[r];t(o,n,"Expression")}};x.MemberExpression=function(e,n,t){t(e.object,n,"Expression"),e.computed&&t(e.property,n,"Expression")};x.ExportNamedDeclaration=x.ExportDefaultDeclaration=function(e,n,t){e.declaration&&t(e.declaration,n,e.type==="ExportNamedDeclaration"||e.declaration.id?"Statement":"Expression"),e.source&&t(e.source,n,"Expression")};x.ExportAllDeclaration=function(e,n,t){e.exported&&t(e.exported,n),t(e.source,n,"Expression")};x.ImportDeclaration=function(e,n,t){for(var r=0,s=e.specifiers;r<s.length;r+=1){var o=s[r];t(o,n)}t(e.source,n,"Expression")};x.ImportExpression=function(e,n,t){t(e.source,n,"Expression")};x.ImportSpecifier=x.ImportDefaultSpecifier=x.ImportNamespaceSpecifier=x.Identifier=x.PrivateIdentifier=x.Literal=Y;x.TaggedTemplateExpression=function(e,n,t){t(e.tag,n,"Expression"),t(e.quasi,n,"Expression")};x.ClassDeclaration=x.ClassExpression=function(e,n,t){return t(e,n,"Class")};x.Class=function(e,n,t){e.id&&t(e.id,n,"Pattern"),e.superClass&&t(e.superClass,n,"Expression"),t(e.body,n)};x.ClassBody=function(e,n,t){for(var r=0,s=e.body;r<s.length;r+=1){var o=s[r];t(o,n)}};x.MethodDefinition=x.PropertyDefinition=x.Property=function(e,n,t){e.computed&&t(e.key,n,"Expression"),e.value&&t(e.value,n,"Expression")};var sr=new Set(["parseInt","parseFloat","isNaN","isFinite","encodeURIComponent","decodeURIComponent","String","Number","Boolean","Array","Object","Eq","NotEq","Is","IsNot","TypeOf"]),ir=new Set(["Math","JSON","Object","Array","String","Number"]),or=new Set(["Math.random","Date.now"]);function Xe(e,n){let t=e[n],r=0;if(t==="*"||t==="+")r=1;else if(t==="{"){let s=e.slice(n).match(/^\{\d+,\}/);s&&(r=s[0].length)}return r===0?0:(e[n+r]==="?"&&r++,r)}function ar(e){let n=[],t=0,r=!1;for(;t<e.length;){let s=e[t];if(s==="\\"){t+=2;continue}if(r){s==="]"&&(r=!1),t++;continue}if(s==="["){r=!0,t++;continue}if(s==="("){n.push({hadUnbounded:!1}),t++;continue}if(s===")"){let i=n.pop()??{hadUnbounded:!1},a=Xe(e,t+1);if(a>0){if(i.hadUnbounded)return"an unbounded quantifier is nested inside another (e.g. `(a+)+`)";n.length&&(n[n.length-1].hadUnbounded=!0),t+=1+a;continue}i.hadUnbounded&&n.length&&(n[n.length-1].hadUnbounded=!0),t++;continue}let o=Xe(e,t);if(o>0){n.length&&(n[n.length-1].hadUnbounded=!0),t+=o;continue}t++}return null}var lr=new Set(["startsWith","endsWith","includes","indexOf","lastIndexOf","slice","substring","substr","toLowerCase","toUpperCase","trim","trimStart","trimEnd","split","replace","replaceAll","match","matchAll","charAt","charCodeAt","codePointAt","padStart","padEnd","repeat","concat","at","normalize","search","localeCompare","every","some","map","filter","reduce","reduceRight","find","findIndex","findLast","findLastIndex","flat","flatMap","join","keys","entries","values","forEach","test","exec","toFixed","toPrecision","toString","valueOf","hasOwnProperty"]),cr=["fetch","XMLHttpRequest","WebSocket","Date","console","setTimeout","setInterval","requestAnimationFrame","queueMicrotask","localStorage","sessionStorage","indexedDB","document","window","globalThis","self","process","require","eval","Function","import","crypto","performance","navigator"];function ur(e,n={}){let t=n.effectful??new Set(cr),r;try{r=Ce.parse(e,{ecmaVersion:"latest",locations:!0})}catch(i){return{safe:!1,predicates:[],diagnostics:[{predicate:"<source>",message:`parse error: ${i.message}`,line:i.loc?.line??0,column:i.loc?.column??0}]}}let s=new Set(n.knownPredicates??[]);for(let i of r.body)i.type==="FunctionDeclaration"&&i.id&&s.add(i.id.name);let o=[];for(let i of r.body){if(i.type!=="FunctionDeclaration"||!i.id)continue;let a=i.id.name,l=(u,p)=>o.push({predicate:a,message:u,line:p?.loc?.start?.line??0,column:p?.loc?.start?.column??0}),c=u=>l("loops are not allowed \u2014 iterate with recursion or array methods (every/some/map/filter/reduce) so work stays fuel-bounded",u);Me(i,{AwaitExpression(u){l("`await` not allowed \u2014 predicates must be synchronous",u)},NewExpression(u){l("`new` not allowed in a predicate (non-pure construction)",u)},WhileStatement:c,DoWhileStatement:c,ForStatement:c,ForInStatement:c,ForOfStatement:c,Literal(u){if(u.regex&&typeof u.regex.pattern=="string"){let p=ar(u.regex.pattern);p&&l(`regex /${u.regex.pattern}/ risks catastrophic backtracking (ReDoS): ${p}. A single match is not fuel-bounded, so it can't be certified predicate-safe \u2014 simplify the pattern or validate without it.`,u)}},CallExpression(u){let p=u.callee;if(p.type==="Identifier"){let f=p.name;t.has(f)?l(`'${f}' is effectful \u2014 not allowed in a predicate`,p):s.has(f)||sr.has(f)||l(`unknown reference '${f}' \u2014 not a predicate or pure builtin`,p);return}if(p.type==="MemberExpression"&&!p.computed){let f=p.property.name,d=p.object;d.type==="Identifier"&&t.has(d.name)?l(`'${d.name}.${f}' is effectful`,p):d.type==="Identifier"&&ir.has(d.name)?or.has(`${d.name}.${f}`)&&l(`'${d.name}.${f}' is nondeterministic`,p):lr.has(f)||l(`method '.${f}()' is not a known pure method`,p.property);return}l("unsupported call form in a predicate",p)}})}return{safe:o.length===0,predicates:[...s],diagnostics:o}}function Qe(e){return e.map(n=>` ${n.predicate} (${n.line}:${n.column}): ${n.message}`).join(`
5
+ `)}function fr(e){let n=Ce.parse(e,{ecmaVersion:"latest"}),t=[],r=o=>t.push([o.body.start+1,"__fuel();"]);Me(n,{FunctionDeclaration:r,FunctionExpression:r,ArrowFunctionExpression(o){o.body.type==="BlockStatement"?t.push([o.body.start+1,"__fuel();"]):(t.push([o.body.start,"(__fuel(), "]),t.push([o.body.end,")"]))}}),t.sort((o,i)=>i[0]-o[0]);let s=e;for(let[o,i]of t)s=s.slice(0,o)+i+s.slice(o);return s}function et(e,n,t={}){let r=ur(e,t);if(!r.safe)return{safe:!1,diagnostics:r.diagnostics};if(!r.predicates.includes(n))return{safe:!1,diagnostics:[{predicate:n,message:`entry predicate '${n}' not found in the verified cluster`,line:0,column:0}]};let s=t.fuel??1e6;return{safe:!0,code:`(() => {let __f = 0;const __fuel = () => { if (--__f < 0) throw new RangeError('tjs:predicate-fuel'); };${fr(e)}return (...__a) => {__f = ${s};try { return !!${n}(...__a); }catch (e) {if (e instanceof RangeError && /tjs:predicate-fuel|stack/i.test(e.message)) return false;throw e;}};})()`,diagnostics:[]}}function pr(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 Re(e,n,t,r,s,o){let i=`__pred_${e}`,a=`function ${i}(${t}) { ${r} }`,l=et(a,i,s?{knownPredicates:new Set(s)}:{});return l.safe?(o?.push({name:e,kind:n,verified:!0}),l.code):(o?.push({name:e,kind:n,verified:!1,reason:Qe(l.diagnostics).replace(/__pred_/g,"")}),null)}function it(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 ot(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 y=e[c];y==="{"?l++:y==="}"&&l--,c++}if(l!==0){t+=e[r],r++;continue}let u=e.slice(a,c-1),p,f=c,d=e.slice(c).match(/^\s*fallback\s*\{/);if(d){let y=c+d[0].length;l=1;let T=y;for(;T<e.length&&l>0;){let M=e[T];M==="{"?l++:M==="}"&&l--,T++}l===0&&(p=e.slice(y,T-1),f=T)}let b=gr(u).map(y=>{let T=hr(e,i,y);return T?`${y}: ${T}`:y}),w={id:`__tjs_wasm_${s}`,body:u,fallback:p,captures:b,start:i,end:f};n.push(w);let E=p??u,v=b.map(y=>y.split(":")[0].trim()),h=v.length>0?v.join(", "):"",$=v.length>0?`globalThis.${w.id}(${h})`:`globalThis.${w.id}()`,S=`(globalThis.${w.id} ? ${$} : (() => {${E}})())`;t+=S,r=f,s++}else t+=e[r],r++}return{source:t,blocks:n}}function at(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,u=1,p=c;for(;p<e.length&&u>0;)e[p]==="("?u++:e[p]===")"&&u--,p++;if(u!==0){t+=e[r],r++;continue}let f=e.slice(c,p-1);if(f.match(/^\s*!/))throw new O(`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.`,Z(e,l));let g,b=p,w=e.slice(p).match(/^\s*:\s*(\w+)/);w&&(g=w[1],b=p+w[0].length);let E=e.slice(b).match(/^\s*\{/);if(!E){t+=e[r],r++;continue}let v=b+E[0].length,h=1,$=v;for(;$<e.length&&h>0;)e[$]==="{"?h++:e[$]==="}"&&h--,$++;if(h!==0){t+=e[r],r++;continue}let S=e.slice(v,$-1),y=mr(f),T=`__tjs_wasm_${a}`,M={id:T,name:a,returnType:g,body:S,captures:y,start:l,end:$};n.push(M);let k=y.map(R=>R.split(":")[0].trim()),j=`${i?"export ":""}function ${a}(${k.join(", ")}) { return globalThis.${T}(${k.join(", ")}) }`;t+=j,r=$}return{source:t,blocks:n}}function lt(e,n){let{loader:t,importerPath:r}=n;if(!t)return{source:e,blocks:[]};let s=[],o=new Set;function i(c,u){if(!o.has(c.id)){s.push(c),o.add(c.id);for(let[p,f]of u){if(p===c.name||o.has(f.id))continue;new RegExp(`\\b${p}\\s*\\(`).test(c.body)&&i(f,u)}}}let a=/^(\s*)import\s*\{([^}]*?)\}\s*from\s*(['"])([^'"]+)\3\s*;?\s*$/gm;return{source:e.replace(a,(c,u,p,f,d)=>{let g=t.load(d,r);if(!g)return c;let b=new Map;for(let S of g.parseResult.wasmBlocks)S.name&&b.set(S.name,S);if(b.size===0)return c;let w=p.split(",").map(S=>S.trim()).filter(S=>S.length>0),E=[],v=[];for(let S of w){let y=S.match(/^(\w+)(?:\s+as\s+(\w+))?$/);if(!y){v.push(S);continue}let T=y[1],M=y[2]??y[1],k=b.get(T);if(!k){v.push(S);continue}i(k,b);let C=k.captures.map(j=>j.split(":")[0].trim());E.push(`function ${M}(${C.join(", ")}) { return globalThis.${k.id}(${C.join(", ")}) }`)}let h=E.join(`
6
+ `);if(v.length===0)return h?`${u}${h}`:`${u}`;let $=`${u}import { ${v.join(", ")} } from '${d}'`;return h?`${$}
7
+ ${u}${h}`:$}),blocks:s}}function mr(e){let n=e.trim();return n?n.split(",").map(t=>t.trim()).filter(t=>t.length>0):[]}function dr(e){return e.startsWith("f32x4_")||e.startsWith("v128_")}function gr(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 f of t){if(!i.has(f))continue;let d=new RegExp(`(?<!\\.)\\b${f}\\b`,"g"),g=new RegExp(`\\.${f}\\b`,"g"),b=n.match(d)?.length||0,w=n.match(g)?.length||0;b<=w&&i.delete(f)}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 u=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"]),p=[];for(let f of i)!a.has(f)&&!u.has(f)&&!dr(f)&&p.push(f);return p.sort()}function hr(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?tt(a[1],t):void 0}return tt(o[1],t)}function tt(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 ct(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 ut(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(`
8
+ `),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 u=l.indexOf("/*"),p=l.indexOf("*/");if(u!==-1&&(p===-1||p<u)){i=!0,o.push(l);continue}if(a>0&&n.test(l)){let f=c.replace(/\/\/.*$/,"").replace(/\/\*.*\*\/\s*$/,"");if(!t.test(f)&&!r.test(f)){let d=l.match(/^(\s*)/),g=d?d[1]:"",b=l.slice(g.length);o.push(g+";"+b);continue}}o.push(l)}return o.join(`
9
+ `)}function yr(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==="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 ft(e){e=yr(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===`
11
+ `&&(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",u=br(o,a),p=wr(o,a+2),f=o.slice(u,a).trim(),d=o.slice(a+2,p).trim();if(f&&d){let g=o.slice(0,u),b=o.slice(p),E=/[a-zA-Z0-9_$]$/.test(g)?" ":"";o=`${g}${E}${c}(${f}, ${d})${b}`}}return o}function br(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 u=e.slice(c,l),p=c>0?e[c-1]:"";if(!/[a-zA-Z0-9_$]/.test(p)){if(["return","throw","case","typeof","void","delete","await","yield"].includes(u))return l;if(u==="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 wr(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 pt(e,n){let t="",r=0;for(;r<e.length;){let s=e.slice(r).match(/^\bType\s+([A-Z_][a-zA-Z0-9_]*)\s*/);if(s){let o=s[1],i=r+s[0].length,a=o,l=!1,c=e.slice(i).match(/^(['"`])([^]*?)\1\s*/);if(c){let d=i+c[0].length,g=e[d],b=g===void 0||d>=e.length||g!=="="&&g!=="{";if(g==="="||g==="{")a=c[2],l=!0,i=d;else if(b){let w=c[0].trim(),E=c[0].slice(w.length);t+=`const ${o} = Type('${o}', ${w})${E}`,r=d;continue}}let u,p=i,f=e.slice(i).match(/^=\s*/);if(f){i+=f[0].length;let d=e.slice(i).match(/^(\+?\d+(?:\.\d+)?|['"`][^'"`]*['"`]|\{[^}]*\}|\[[^\]]*\]|true|false|null)/);if(d){u=d[0],i+=d[0].length,p=i;let g=e.slice(i).match(/^\s*/);g&&(i+=g[0].length)}}if(e[i]==="{"){let d=i+1,g=1,b=d;for(;b<e.length&&g>0;){let y=e[b];y==="{"?g++:y==="}"&&g--,b++}if(g!==0){t+=e[r],r++;continue}let w=e.slice(d,b-1).trim(),E=b,v=w.match(/description\s*:\s*(['"`])([^]*?)\1/);v&&!l&&(a=v[2]);let h,$=w.match(/example\s*:\s*/);if($){let y=$.index+$[0].length,T=Ct(w,y);T&&(h=T.value.trim())}let S=w.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/);if(S&&h){let y=S[1].trim(),T=S[2].trim(),M=u?`, ${u}`:"",k=`globalThis.__tjs?.validate(${y}, globalThis.__tjs?.infer(${h}))`,C=Re(o,"Type",y,T,void 0,n),j=C?`(__g => (${y}) => (${k} ? __g(${y}) : false))(${C})`:`(${y}) => { if (!${k}) return false; ${T} }`;t+=`const ${o} = Type('${a}', ${j}, ${h}${M})`}else if(S){let y=S[1].trim(),T=S[2].trim(),M=u?`, undefined, ${u}`:"",C=Re(o,"Type",y,T,void 0,n)??`(${y}) => { ${T} }`;t+=`const ${o} = Type('${a}', ${C}${M})`}else if(h){let y=u?`, ${u}`:"";t+=`const ${o} = Type('${a}', undefined, ${h}${y})`}else u?t+=`const ${o} = Type('${a}', ${u})`:t+=`const ${o} = Type('${a}')`;r=E;continue}else if(u){t+=`const ${o} = Type('${a}', ${u})`,r=p;continue}else if(!c){let d=e.slice(i).match(/^(['"`][^]*?['"`]|\+?\d+(?:\.\d+)?|true|false|null|\{[^]*?\}|\[[^]*?\])/);if(d){let g=d[0];t+=`const ${o} = Type('${o}', ${g})`,r=i+d[0].length;continue}}}t+=e[r],r++}return t}function mt(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(),u=pr(c,/params\s*:\s*\{/),p=c.match(/returns\s*:\s*(.+?)(?:\n|$)/),f=c.match(/returnContract\s*:\s*['"](\w+)['"]/),d=c.match(/description\s*:\s*(['"])([^]*?)\1/),g=[];u&&g.push(`params: ${u[1]}`),p&&g.push(`returns: ${p[1].trim()}`),f&&g.push(`returnContract: '${f[1]}'`);let b=d?d[2]:s;if(o){let w=o.split(",").map(v=>{let h=v.trim().split("=").map($=>$.trim());if(h.length===2){let $=h[1]==="any"||h[1]==="undefined"?"null":h[1];return`['${h[0]}', ${$}]`}return`'${h[0]}'`}),E=o.split(",").map(v=>v.trim().split("=")[0].trim());n+=`const ${s} = FunctionPredicate('${b}', [${w.join(", ")}], (${E.join(", ")}) => ({ ${g.join(", ")} }))`}else n+=`const ${s} = FunctionPredicate('${b}', { ${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(),u=c.indexOf(",");if(u!==-1){let p=c.slice(0,u).trim(),f=c.slice(u+1).trim();n+=`const ${s} = FunctionPredicate(${f}, ${p})`}else n+=`const ${s} = FunctionPredicate('${s}', ${c})`;t=l;continue}}}n+=e[t],t++}return n}function dt(e,n){let t="",r=0;for(;r<e.length;){let s=e.slice(r).match(/^\bGeneric\s+([A-Z][a-zA-Z0-9_]*)\s*<([^>]+)>\s*\{/);if(s){let o=s[1],i=s[2],l=r+s[0].length-1+1,c=1,u=l;for(;u<e.length&&c>0;){let h=e[u];h==="{"?c++:h==="}"&&c--,u++}if(c!==0){t+=e[r],r++;continue}let p=e.slice(l,u-1).trim(),f=u,d=i.split(",").map(h=>{let $=h.trim().split("=").map(S=>S.trim());if($.length===2){let S=$[1]==="any"||$[1]==="undefined"?"null":$[1];return`['${$[0]}', ${S}]`}return`'${$[0]}'`}),g=p,b=g.search(/\bdeclaration\s*\{/);if(b!==-1){let h=g.indexOf("{",b),$=1,S=h+1;for(;S<g.length&&$>0;)g[S]==="{"?$++:g[S]==="}"&&$--,S++;g=g.slice(0,b)+g.slice(S)}let w=g.match(/description\s*:\s*(['"`])([^]*?)\1/),E=g.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/),v=w?w[2]:o;if(E){let h=E[1].trim().split(",").map(j=>j.trim()),$=E[2].trim(),S=h[0]||"x",y=h.slice(1),T=y.map(j=>`check${j}`);y.forEach((j,R)=>{$=$.replace(new RegExp(`\\b${j}\\s*\\(`,"g"),`${T[R]}(`)});let M=[S,...T].join(", "),C=Re(o,"Generic",M,$,T,n)??`(${M}) => { ${$} }`;t+=`const ${o} = Generic([${d.join(", ")}], ${C}, '${v}')`}else t+=`const ${o} = Generic([${d.join(", ")}], () => true, '${v}')`;r=f;continue}t+=e[r],r++}return t}function gt(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 u=e.slice(a,c-1).trim(),p=c,f=nt(u);n+=`const ${s} = Union('${o}', [${f.join(", ")}])`,t=p;continue}else{let a=e.indexOf(`
12
+ `,i);a===-1&&(a=e.length);let l=e.slice(i,a).trim();if(l){let c=nt(l);n+=`const ${s} = Union('${o}', [${c.join(", ")}])`,t=a;continue}}}n+=e[t],t++}return n}function nt(e){let n=[],t=e.split("|").map(r=>r.trim());for(let r of t)r&&n.push(r);return n}function ht(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 u=e.slice(a,c-1).trim(),p=c,d=Sr(u).map(([g,b])=>`${g}: ${b}`).join(", ");n+=`const ${s} = Enum('${o}', { ${d} })`,t=p;continue}n+=e[t],t++}return n}function Sr(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 yt(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]===`
13
+ `||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=oe(e,l),u=e.slice(l+1,c-1).trim(),p=[],f=0,d=e.slice(l+1,c-1);for(;f<d.length;){let h=d.slice(f).match(/^(\s*)(async\s+)?(\w+)\s*\(/);if(!h){f++;continue}let $=h[1],S=!!h[2],y=h[3],T=f+h[0].length-1,M=1,k=T+1;for(;k<d.length&&M>0;)d[k]==="("&&M++,d[k]===")"&&M--,k++;let C=d.slice(T+1,k-1),j=k;for(;j<d.length&&/\s/.test(d[j]);)j++;if(d[j]==="="&&d[j+1]===">"){let G=Z(e,l+1+f);throw new O(`Arrow functions are not allowed in extend blocks (method '${y}' in extend ${a}). Use regular function syntax instead, as extension methods need 'this' binding.`,G)}if(d[j]!=="{"){f++;continue}let R=oe(d,j),q=d.slice(f,R).trim(),ne=C.split(",").map(G=>G.trim()).filter(G=>G.length>0).map(G=>{let Ee=G.match(/^(\w+)\s*:\s*(.+)$/);return Ee?`${Ee[1]} = ${Ee[2]}`:G}).join(", "),re=S?"async ":"",se=d.slice(j+1,R-1);p.push({name:y,isAsync:S,fullText:`${y}: ${re}function(${ne}) {${se}}`}),f=R}let g=!n.has(a);g&&n.set(a,new Set);let b=n.get(a);for(let v of p)b.add(v.name);let w=p.map(v=>` ${v.fullText}`).join(`,
13
14
  `),E;g?E=`${i}const __ext_${a} = {
14
15
  ${w}
15
16
  ${i}}
16
17
  `:E=`${i}Object.assign(__ext_${a}, {
17
18
  ${w}
18
19
  ${i}})
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 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
- ${S.join(`
20
+ `;for(let v of p)E+=`${i}if (__tjs?.registerExtension) { __tjs.registerExtension('${a}', '${v.name}', __ext_${a}.${v.name}) }
21
+ `;t+=E,r=c}return r<=e.length&&t.length<e.length,{source:t,extensions:n}}function bt(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,u,p,f)=>f?`__ext_String.${p}.call(${u})`:`__ext_String.${p}.call(${u}, `);let a=new RegExp(`("(?:[^"\\\\]|\\\\.)*")\\.(${s})\\((\\))?`,"g");r=r.replace(a,(c,u,p,f)=>f?`__ext_String.${p}.call(${u})`:`__ext_String.${p}.call(${u}, `);let l=new RegExp("(`(?:[^`\\\\]|\\\\.)*`)\\."+s+"\\((\\))?","g");r=r.replace(l,(c,u,p)=>p?`__ext_String.${s}.call(${u})`:`__ext_String.${s}.call(${u}, `)}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,u=l-1,p=!1;for(;u>=0&&c>0;){let f=r[u];p?f===p&&(u===0||r[u-1]!=="\\")&&(p=!1):(f==="]"&&c++,f==="["&&c--,(f==="'"||f==='"'||f==="`")&&(p=f)),u--}if(c===0){let f=r.slice(u+1,l+1),d=r.slice(0,u+1),g=r.slice(l+i.length);g[0]===")"?r=`${d}__ext_Array.${s}.call(${f})${g.slice(1)}`:r=`${d}__ext_Array.${s}.call(${f}, ${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,u)=>u?`__ext_Number.${c}.call(${l})`:`__ext_Number.${c}.call(${l}, `)}return r}function Z(e,n){let t=1,r=0;for(let s=0;s<n&&s<e.length;s++)e[s]===`
22
+ `?(t++,r=0):r++;return{line:t,column:r}}function wt(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 me(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 Ne(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=rt(s.trim(),n);c&&t.push(c),s="";continue}s+=l}let i=s.trim();if(i){let a=rt(i,n);a&&t.push(a)}return t}function rt(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 oe(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===`
23
+ `&&(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 St(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 p=!!o[1],f=!!o[2],d=o[3],g=o.index,b=g,E=o[0].indexOf("function");E>=0&&(b=g+E),i.push({name:d,fullMatchStart:g,funcKeywordStart:b,exported:p,isAsync:f})}for(let p of i)s.has(p.name)||s.set(p.name,[]);let a=new Map;for(let p of i)a.set(p.name,(a.get(p.name)||0)+1);let l=new Set;for(let[p,f]of a)f>1&&l.add(p);if(l.size===0)return{source:e,polymorphicNames:t};for(let p of i){if(!l.has(p.name))continue;let f=e.indexOf("(",p.funcKeywordStart);if(f===-1)continue;let d=1,g=f+1;for(;g<e.length&&d>0;)e[g]==="("&&d++,e[g]===")"&&d--,g++;let b=g-1,w=e.slice(f+1,b),E=g;for(;E<e.length&&e[E]!=="{";)E++;if(E>=e.length)continue;let v=oe(e,E),h=p.fullMatchStart;for(;h>0&&e[h-1]===" ";)h--;let $=s.get(p.name),S=Ne(w,n);if(w.includes("...")){let T=Z(e,p.funcKeywordStart);throw new O(`Rest parameters are not supported in polymorphic function '${p.name}'. Use separate function names instead.`,T)}$.push({index:$.length+1,start:h,end:v,text:e.slice(h,v),exported:p.exported,isAsync:p.isAsync,params:S})}for(let[p,f]of s){if(f.length<2)continue;let d=f.filter(g=>g.isAsync).length;if(d>0&&d<f.length){let g=Z(e,f[0].start);throw new O(`Polymorphic function '${p}': all variants must be either sync or async, not mixed.`,g)}for(let g=0;g<f.length;g++)for(let b=g+1;b<f.length;b++){let w=f[g],E=f[b];if(w.params.length!==E.params.length)continue;let v=!0;for(let h=0;h<w.params.length;h++){let $=w.params[h].defaultValue?me(w.params[h].defaultValue):"any",S=E.params[h].defaultValue?me(E.params[h].defaultValue):"any";if($!==S){v=!1;break}}if(v){let h=Z(e,E.start);throw new O(`Polymorphic function '${p}': variants ${g+1} and ${b+1} have ambiguous signatures (same parameter types at every position). Overloads must differ by arity or parameter types.`,h)}}}let c=[];for(let[p,f]of s)if(!(f.length<2))for(let d of f)c.push({name:p,variant:d});c.sort((p,f)=>f.variant.start-p.variant.start);let u=e;for(let{name:p,variant:f}of c){let d=f.isAsync?"async ":"",g=f.text.replace(new RegExp(`(?:export\\s+)?${d?d.replace(/\s+$/,"\\s+"):""}function\\s+${p}\\s*\\(`),`${d}function ${p}$$${f.index}(`);u=u.slice(0,f.start)+g+u.slice(f.end)}for(let[p,f]of s){if(f.length<2)continue;t.add(p);let d=f[0].isAsync,g=f.some($=>$.exported),b=d?"async ":"",w=g?"export ":"",E=[...f].sort(($,S)=>{if($.params.length!==S.params.length)return 0;let y=0,T=0;for(let M of $.params){let k=M.defaultValue?me(M.defaultValue):"any";k==="non-negative-integer"?y+=3:k==="integer"?y+=2:k!=="any"&&(y+=1)}for(let M of S.params){let k=M.defaultValue?me(M.defaultValue):"any";k==="non-negative-integer"?T+=3:k==="integer"?T+=2:k!=="any"&&(T+=1)}return T-y}),v=[];for(let $ of E){let S=[`__args.length === ${$.params.length}`],y=[];for(let T=0;T<$.params.length;T++){let M=$.params[T];if(y.push(`__args[${T}]`),M.defaultValue){let k=wt(`__args[${T}]`,M.defaultValue);k!=="true"&&S.push(k)}}v.push(` if (${S.join(" && ")}) return ${p}$${$.index}(${y.join(", ")})`)}let h=`
24
+ ${w}${b}function ${p}(...__args) {
25
+ ${v.join(`
25
26
  `)}
26
- return __tjs.typeError('${m}', 'no matching overload', __args)
27
+ return __tjs.typeError('${p}', 'no matching overload', __args)
27
28
  }
28
- `;p+=h}return{source:p,polymorphicNames:t}}function pt(e){let n=new Set,t=/\b(?:let|const|var|function|class)\s+([A-Z][a-zA-Z0-9_]*)/g;for(let r;r=t.exec(e);)n.add(r[1]);return e.replace(/(?<=^|[;\n{])(\s*)([A-Z][a-zA-Z0-9_]*)\s*=(?!=)/gm,(r,s,o)=>n.has(o)?r:r.replace(o,`const ${o}`))}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
- `,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
- ${$.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 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
- function ${l}$ctor$${b.index}(${b.paramStr}) {`,S+=`
34
- const __obj = Object.create(${l}.prototype)`,S+=`
35
- ;(function() {${b.bodyText}}).call(__obj)`,S+=`
36
- return __obj`,S+=`
29
+ `;u+=h}return{source:u,polymorphicNames:t}}function Et(e){let n=new Set,t=/\b(?:let|const|var|function|class)\s+([A-Z][a-zA-Z0-9_]*)/g;for(let r;r=t.exec(e);)n.add(r[1]);return e.replace(/(?<=^|[;\n{])(\s*)([A-Z][a-zA-Z0-9_]*)\s*=(?!=)/gm,(r,s,o)=>n.has(o)?r:r.replace(o,`const ${o}`))}function xt(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,u=e.slice(l).match(/^(['"`])([^]*?)\1\s*/);if(u&&(c=u[2],l+=u[0].length),e[l]==="{"){let p=l+1,f=1,d=p,g=null,b=!1;for(;d<e.length&&f>0;){let w=e[d];if(b){b=!1,d++;continue}if(w==="\\"&&g){b=!0,d++;continue}if(g){w===g&&(g=null),d++;continue}if(w==="/"&&e[d+1]==="/"){let E=e.indexOf(`
30
+ `,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==="{"?f++:w==="}"&&f--,d++}if(f===0){let w=e.slice(p,d-1).trim(),E=d,v=(e.slice(0,a).match(/\n/g)||[]).length+1;if(t.push({description:c,body:w,start:a,end:E,line:v}),!n)try{new Function(w)()}catch(S){let y=c||`test at line ${v}`;r.push(`Test failed: ${y} (line ${v})
31
+ ${S.message||S}`)}let $=(e.slice(a,E).match(/\n/g)||[]).length;s+=`
32
+ `.repeat($),o=E;continue}}}s+=e[o],o++}return{source:s,tests:t,errors:r}}function $t(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,u=oe(e,c),p=e.slice(c,u);o.push({className:a,extendsClause:l,bodyStart:c,bodyEnd:u,body:p})}let i=e;for(let a=o.length-1;a>=0;a--){let{className:l,extendsClause:c,bodyStart:u,bodyEnd:p,body:f}=o[a],d=/\bconstructor\s*\(/g,g,b=[];for(;(g=d.exec(f))!==null;)b.push(g.index);if(b.length<2)continue;t.add(l);let w=[];for(let S=0;S<b.length;S++){let y=b[S],T=f.indexOf("(",y),M=1,k=T+1;for(;k<f.length&&M>0;)f[k]==="("&&M++,f[k]===")"&&M--,k++;let C=f.slice(T+1,k-1),j=k;for(;j<f.length&&f[j]!=="{";)j++;let R=oe(f,j),q=f.slice(j+1,R-1);w.push({index:S+1,paramStr:C,bodyText:q,fullStart:y,fullEnd:R})}let E=f;for(let S=w.length-1;S>=1;S--){let y=w[S],T=y.fullStart;for(;T>0&&E[T-1]===" ";)T--;T>0&&E[T-1]===`
33
+ `&&T--,E=E.slice(0,T)+E.slice(y.fullEnd)}let v="";for(let S=1;S<w.length;S++){let y=w[S],T=Ne(y.paramStr,n);if(y.paramStr.includes("...")){let k=Z(e,u+y.fullStart);throw new O(`Rest parameters are not supported in polymorphic constructors for '${l}'.`,k)}v+=`
34
+ function ${l}$ctor$${y.index}(${y.paramStr}) {`,v+=`
35
+ const __obj = Object.create(${l}.prototype)`,v+=`
36
+ ;(function() {${y.bodyText}}).call(__obj)`,v+=`
37
+ return __obj`,v+=`
37
38
  }
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
+ `}let h=[];for(let S=0;S<w.length;S++){let y=w[S],T=Ne(y.paramStr,n),M=[`a.length === ${T.length}`];for(let k=0;k<T.length;k++){let C=T[k];if(C.defaultValue){let j=wt(`a[${k}]`,C.defaultValue);j!=="true"&&M.push(j)}}if(S===0)h.push(` if (${M.join(" && ")}) return Reflect.construct(t, a)`);else{let k=T.map((C,j)=>`a[${j}]`).join(", ");h.push(` if (${M.join(" && ")}) return ${l}$ctor$${y.index}(${k})`)}}v+=`
39
40
  function ${l}$dispatch(t, a) {
40
- `,S+=h.join(`
41
+ `,v+=h.join(`
41
42
  `)+`
42
- `,S+=` return __tjs.typeError('${l}', 'no matching constructor', a)
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 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),c.tjsSafeAssign&&(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(/(?<=^[ \t]*)\/\*#([\s\S]*?)\*\//gm)];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};
43
+ `,v+=` return __tjs.typeError('${l}', 'no matching constructor', a)
44
+ `,v+=`}
45
+ `,i=i.slice(0,u)+E+i.slice(p);let $=u+E.length;i=i.slice(0,$)+v+i.slice($)}return{source:i,polyCtorClasses:t}}function vt(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,u=1,p=c+1;for(;p<e.length&&u>0;){let f=e[p];f==="{"?u++:f==="}"&&u--,p++}if(u===0){let f=p,d=e.slice(c,f);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=f}}return r+=e.slice(s),r}function Tt(e){let n=[{pattern:/\bnew\s+Date\b/,message:"new Date() is not allowed in TjsDate mode. Use Timestamp.now()/Timestamp.from() for wall-clock dates, or performance.now() for a monotonic counter (timing, id generation)"},{pattern:/\bDate\.now\b/,message:"Date.now() is not allowed in TjsDate mode. Use Timestamp.now() for a wall-clock date, or performance.now() for a monotonic counter (timing, id generation)"},{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 At(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 kt(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 jt(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 Mt(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=Er(n);if(l<a){let c=n.slice(l);n=n.slice(0,l);let u=t+2;for(;u<e.length&&/[\w$]/.test(e[u]);)u++;let p=e.slice(t+2,u);n+=`__tjs.bang(${c},'${p}')`,t=u;continue}}n+=o,t++}else r==="line-comment"?(n+=o,o===`
46
+ `&&(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 Er(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=st(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=st(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 st(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 Pt(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===`
47
+ `&&(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 u=c>=0?e[c]:"";if(!u||/[=(!,;:{[&|?+\-*%<>~^]/.test(u)||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 u=c;for(;c<e.length&&/[\w$]/.test(e[c]);)c++;let p=c,f=e.slice(u,p),d=c;for(;d<e.length&&/\s/.test(e[d]);)d++;if(d<e.length&&e[d]===":"&&e[d+1]!==":"){let b=d+1;for(;b<e.length&&/[ \t]/.test(e[b]);)b++;let w=xr(e,b);if(w>b){let E=e.slice(b,w).trim();n.set(f,E),t.push({start:p,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 xr(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===`
48
+ `))return t;t++}return t}function ye(e,n){let t="",r=0,s,o,i="normal",a=[],l=[{type:"top-level",braceDepth:0}],c=0,u=()=>l[l.length-1]?.type||"top-level",p=()=>{let f=l[l.length-1];return f?.type==="class-body"&&c===f.braceDepth+1};for(;r<e.length;){let f=e[r],d=e[r+1];switch(i){case"single-string":if(t+=f,f==="\\"&&r+1<e.length){t+=d,r+=2;continue}f==="'"&&(i="normal"),r++;continue;case"double-string":if(t+=f,f==="\\"&&r+1<e.length){t+=d,r+=2;continue}f==='"'&&(i="normal"),r++;continue;case"template-string":if(t+=f,f==="\\"&&r+1<e.length){t+=d,r+=2;continue}if(f==="$"&&d==="{"){t+=d,r+=2,a.push(1),i="normal";continue}f==="`"&&(i="normal"),r++;continue;case"line-comment":t+=f,f===`
49
+ `&&(i="normal"),r++;continue;case"block-comment":if(t+=f,f==="*"&&d==="/"){t+=d,r+=2,i="normal";continue}r++;continue;case"regex":if(t+=f,f==="\\"&&r+1<e.length){t+=d,r+=2;continue}if(f==="["){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(f==="/"){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(f==="{")a[a.length-1]++;else if(f==="}"&&(a[a.length-1]--,a[a.length-1]===0)){a.pop(),t+=f,r++,i="template-string";continue}}if(f==="'"){t+=f,r++,i="single-string";continue}if(f==='"'){t+=f,r++,i="double-string";continue}if(f==="`"){t+=f,r++,i="template-string";continue}if(f==="/"&&d==="/"){t+=f+d,r+=2,i="line-comment";continue}if(f==="/"&&d==="*"){t+=f+d,r+=2,i="block-comment";continue}if(f==="/"){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+=f,r++,i="regex";continue}}break}if(f==="{"){c++,t+=f,r++;continue}if(f==="}"){c--;let h=l[l.length-1];h&&c===h.braceDepth&&l.pop(),t+=f,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 b=e.slice(r).match(/^function\s+(\w+)\s*\(/);if(b){let h=b[1],$=b[0].length,S=e[r+$],y,T=r+$;(S==="?"||S==="!")&&(y=S,T++,y==="!"?n.unsafeFunctions.add(h):n.safeFunctions.add(h)),t+=`function ${h}(`,r=T;let M=de(e,r,"(",")");if(!M){t+=e[r],r++;continue}let{content:k,endPos:C}=M;r=C;let j=_e(k,n,!0);t+=j+")";let R=r;for(;R<e.length&&/\s/.test(e[R]);)R++;if(e[R]===":"){let ne=e.slice(R,R+2),re;for(ne===":?"||ne===":!"?(R+=2,re=ne===":?"?"safe":"unsafe"):R+=1;R<e.length&&/\s/.test(e[R]);)R++;let se=Ie(e,R);se&&(s===void 0&&(s=se.type,re&&(o=re)),r=se.endPos)}let q=r;for(;q<e.length&&/\s/.test(e[q]);)q++;if(e[q]==="="&&e[q+1]===">")throw new O("Unexpected '=>' after function declaration. Function declarations use `function name(params) { body }`, not arrow syntax. Remove the `=>`.",Z(n.originalSource,q),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`
50
+ `})(),v=E!=="="&&E!==","&&E!=="("&&E!=="["&&E!==">";if(w&&p()&&!v){let h=w[1].length;t+=e.slice(r,r+h),r+=h;continue}if(w&&p()&&v){let h=w[1],$=w[0].length,S=r+$;t+=h+"(",r=S;let y=de(e,r,"(",")");if(!y){t+=e[r],r++;continue}let{content:T,endPos:M}=y;r=M;let k=_e(T,n,!0);t+=k+")";let C=r;for(;C<e.length&&/\s/.test(e[C]);)C++;if(e[C]===":"){let R=e.slice(C,C+2);for(R===":?"||R===":!"?C+=2:C++;C<e.length&&/\s/.test(e[C]);)C++;let q=Ie(e,C);q&&(r=q.endPos)}let j=r;for(;j<e.length&&/\s/.test(e[j]);)j++;if(e[j]==="="&&e[j+1]===">")throw new O("Unexpected '=>' after method declaration. Methods use `name(params) { body }`, not arrow syntax. Remove the `=>`.",Z(n.originalSource,j),n.originalSource);continue}if(e[r]==="("){let h=de(e,r+1,"(",")");if(!h){t+=e[r],r++;continue}let $=h.content,S=h.endPos,y=S;for(;y<e.length&&/\s/.test(e[y]);)y++;let T;if(e[y]===":"){let M=e.slice(y,y+2);for(M===":?"||M===":!"?y+=2:y++;y<e.length&&/\s/.test(e[y]);)y++;let k=Ie(e,y);if(k)for(T=k.type,y=k.endPos;y<e.length&&/\s/.test(e[y]);)y++}if(e.slice(y,y+2)==="=>"){let M=null,k=$,C=$.trimStart();C.startsWith("?")&&(C.length===1||/\s/.test(C[1]))?(M="?",k=C.slice(1)):C.startsWith("!")&&(C.length===1||/\s/.test(C[1]))&&(M="!",k=C.slice(1));let j=_e(k,n,!1);for(t+=`(${M==="?"?"/* safe */ ":M==="!"?"/* unsafe */ ":""}${j})`,r=S;r<y&&/\s/.test(e[r]);)t+=e[r],r++;T&&(r=y)}else{let M=ye($,n);t+=`(${M.source})`,r=S}continue}t+=e[r],r++}return{source:t,returnType:s,returnSafety:o}}function de(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 Ct(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=de(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 ae(e){return e.replace(/(?<!\|)\|(?!\|)/g," || ")}function Ie(e,n){let t=n,r=0,s=!1,o="",i=!1,a=l=>({type:ae(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:ae(e.slice(n,c).trim()),endPos:c};if(e[t]!=="|"&&e[t]!=="&")return{type:ae(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 p=c;for(;p>n&&/\s/.test(e[p-1]);)p--;return{type:ae(e.slice(n,p).trim()),endPos:c}}if(e[t]!=="|"&&e[t]!=="&")return{type:ae(e.slice(n,c).trim()),endPos:c};continue}t++}return i?a(t):null}function be(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===`
51
+ `){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 _e(e,n,t){let r=ye(e,{originalSource:e,requiredParams:n.requiredParams,unsafeFunctions:n.unsafeFunctions,safeFunctions:n.safeFunctions}).source,s=be(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 u=c.trim();if(!u)return c;if(t&&u.startsWith("{")&&u.endsWith("}")){let d=u.slice(1,-1);return`{ ${Rt(d,n)} }`}if(t&&u.startsWith("[")&&u.endsWith("]")){let d=u.slice(1,-1);return`[ ${Rt(d,n)} ]`}if(u.startsWith("...")){let d=Nt(u);return d!==-1?u.slice(0,d).trim():c}let p=u.match(/^(\w+)\s*\?\s*:\s*(.+)$/);if(p){let[,d,g]=p;return a(d),o=!0,`${d} = ${g}`}if(!$r(u)){let d=u.match(/^(\w+)\s*=/);return d&&a(d[1]),o=!0,c}let f=Nt(u);if(f!==-1){let d=u.slice(0,f).trim(),g=u.slice(f+1).trim();return a(d),o&&t&&/^\w+$/.test(d),t&&/^\w+$/.test(d)&&n.requiredParams.add(d),`${d} = ${g}`}return c}).join(",")}function Rt(e,n){return be(e).map(s=>{let o=s.trim();if(!o)return s;let i=o.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if(i){let[,c,u]=i;n.requiredParams.add(c);let p=ge(u);return`${c} = ${p}`}let a=o.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(a){let[,c,u]=a;n.requiredParams.add(c);let p=he(u);return`${c} = ${p}`}let l=o.match(/^(\w+)\s*:\s*([\s\S]+)$/);if(l){let[,c,u]=l;return n.requiredParams.add(c),`${c} = ${u}`}return s}).join(", ")}function ge(e){let n=e.slice(1,-1).trim();return`{ ${be(n).map(s=>{let o=s.trim();if(!o)return s;let i=o.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if(i){let[,p,f]=i;return`${p}: ${ge(f)}`}let a=o.match(/^(\w+)\s*=\s*(\{[\s\S]*\})$/);if(a){let[,p,f]=a;return`${p}: ${ge(f)}`}let l=o.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(l){let[,p,f]=l;return`${p}: ${he(f)}`}let c=o.match(/^(\w+)\s*=\s*(\[[\s\S]*\])$/);if(c){let[,p,f]=c;return`${p}: ${he(f)}`}let u=o.match(/^(\w+)\s*=\s*([\s\S]+)$/);if(u){let[,p,f]=u;return`${p}: ${f}`}return s}).join(", ")} }`}function he(e){let n=e.slice(1,-1).trim();return`[ ${be(n).map(s=>{let o=s.trim();return o?o.startsWith("{")&&o.endsWith("}")?ge(o):o.startsWith("[")&&o.endsWith("]")?he(o):s:s}).join(", ")} ]`}function $r(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 Nt(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 vr(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(`
52
+ `,t),o=s===-1?e.length:s;n+=" ".repeat(o-t),t=o;continue}n+=r,t++}return n}function Tr(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 u=e.match(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\b/);u&&(r=u[2],e=e.replace(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\s*/,"$1"));let p=/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*(TjsStrict|TjsCompat|TjsEquals|TjsClass|TjsDate|TjsNoeval|TjsNoVar|TjsStandard|TjsSafeEval|TjsSafeAssign)\b/,f;for(;f=e.match(p);){let j=f[2];j==="TjsStrict"?(c.tjsEquals=!0,c.tjsClass=!0,c.tjsDate=!0,c.tjsNoeval=!0,c.tjsNoVar=!0,c.tjsStandard=!0,c.tjsSafeAssign=!0):j==="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):j==="TjsEquals"?c.tjsEquals=!0:j==="TjsClass"?c.tjsClass=!0:j==="TjsDate"?c.tjsDate=!0:j==="TjsNoeval"?c.tjsNoeval=!0:j==="TjsNoVar"?c.tjsNoVar=!0:j==="TjsStandard"?c.tjsStandard=!0:j==="TjsSafeEval"?c.tjsSafeEval=!0:j==="TjsSafeAssign"&&(c.tjsSafeAssign=!0),e=e.replace(new RegExp(`^(\\s*(?:\\/\\/[^\\n]*\\n|\\/\\*[\\s\\S]*?\\*\\/\\s*)*)\\s*${j}\\s*`),"$1")}e=vr(e),c.tjsStandard&&(e=ut(e)),e=At(e),e=Mt(e);let d=Pt(e);e=d.source;let g=d.annotations,b=at(e);e=b.source,e=ct(e),c.tjsEquals&&!n.vmTarget&&(e=ft(e));let w=[];e=pt(e,w),e=dt(e,w),e=mt(e),e=gt(e),e=ht(e),c.tjsSafeAssign&&(e=Et(e));let E=lt(e,{loader:n.moduleLoader,importerPath:n.filename});e=E.source;let{source:v,returnType:h,returnSafety:$}=ye(e,{originalSource:t,requiredParams:s,unsafeFunctions:o,safeFunctions:i});e=v;let S=yt(e);e=S.source,e=it(e);let y=St(e,s);e=y.source;let T=ot(e);e=T.source;let M=[...b.blocks,...E.blocks,...T.blocks],k=xt(e,n.dangerouslySkipTests);e=k.source;let C=$t(e,s);e=C.source;for(let j of C.polyCtorClasses)o.add(`${j}$dispatch`);return c.tjsClass&&(e=vt(e,C.polyCtorClasses)),c.tjsDate&&(e=Tt(e)),c.tjsNoeval&&(e=jt(e)),c.tjsNoVar&&(e=kt(e)),e=bt(e,S.extensions),{source:e,returnType:h,returnSafety:$,moduleSafety:r,tjsModes:c,originalSource:t,requiredParams:s,unsafeFunctions:o,safeFunctions:i,wasmBlocks:M,tests:k.tests,testErrors:k.errors,polymorphicNames:y.polymorphicNames,extensions:S.extensions,letAnnotations:g,predicates:w}}function _t(e,n={}){let{filename:t="<source>",colonShorthand:r=!0,vmTarget:s=!1,dialect:o}=n,{source:i,returnType:a,returnSafety:l,moduleSafety:c,originalSource:u,requiredParams:p,unsafeFunctions:f,safeFunctions:d,wasmBlocks:g,tests:b,testErrors:w,letAnnotations:E,tjsModes:v}=r?Tr(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:It.parse(i,{ecmaVersion:2022,sourceType:"module",locations:!0,allowReturnOutsideFunction:!1}),returnType:a,returnSafety:l,moduleSafety:c,originalSource:u,requiredParams:p,unsafeFunctions:f,safeFunctions:d,wasmBlocks:g,tests:b,testErrors:w,letAnnotations:E,tjsModes:v}}catch(h){let $=h.loc||{line:1,column:0};throw new O(h.message.replace(/\s*\(\d+:\d+\)$/,""),$,u,t)}}function Bt(e,n){for(let o of e.body){if(o.type==="ImportDeclaration")throw new O("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 O("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 O("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 O("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 O("Helper function must have a name",i.loc?.start||{line:1,column:0},void 0,n);if(s.has(a))throw new O(`Duplicate helper function name: ${a}`,i.loc?.start||{line:1,column:0},void 0,n);if(a===r.id?.name)throw new O(`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 Ot(e,n){let t={params:{}};if(!n.loc)return t;let r=e.substring(0,n.start),s=[...r.matchAll(/(?<=^[ \t]*)\/\*#([\s\S]*?)\*\//gm)];if(s.length>0){let u=s[s.length-1],p=r.substring(u.index+u[0].length);if(/^(?:\s|\/\/[^\n]*)*$/.test(p)){let f=u[1],d=f.split(`
53
+ `),g=d.filter(b=>b.trim().length>0).reduce((b,w)=>{let E=w.match(/^(\s*)/)?.[1].length||0;return Math.min(b,E)},1/0);return g>0&&g<1/0&&(f=d.map(b=>b.slice(g)).join(`
54
+ `)),t.description=f.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 Ar}from"acorn";function L(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=>L(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]=L(r.value)}return{kind:"object",shape:t}}case"LogicalExpression":{let{operator:n,left:t,right:r}=e;return n==="||"?L(t):n==="&&"||n==="??"?L(r):{kind:"any"}}case"BinaryExpression":{let{operator:n,left:t,right:r}=e;if(n==="|"){let s=L(t),o=L(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=>kr(s)),r={kind:"any"};return n.type==="ArrowFunctionExpression"&&n.body&&n.body.type!=="BlockStatement"&&(r=L(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 kr(e){return e.type==="Identifier"?{name:e.name,type:{kind:"any"}}:e.type==="AssignmentPattern"&&e.left?.type==="Identifier"?{name:e.left.name,type:L(e.right)}:e.type==="RestElement"&&e.argument?.type==="Identifier"?{name:`...${e.argument.name}`,type:{kind:"array",items:{kind:"any"}}}:{name:"?",type:{kind:"any"}}}function Be(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 I("Only simple parameter names are supported",_(e));let s=t.name,o=n?.has(s)??!1,i=L(r),a=z(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=Be(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 I(`Unsupported parameter pattern: ${e.type}`,_(e))}function z(e){switch(e.type){case"Literal":return e.value;case"ArrayExpression":return e.elements.map(n=>n?z(n):null);case"ObjectExpression":{let n={};for(let t of e.properties)t.type==="Property"&&t.key.type==="Identifier"&&(n[t.key.name]=z(t.value));return n}case"UnaryExpression":if(e.operator==="-"){let n=z(e.argument);return typeof n=="number"?-n:void 0}if(e.operator==="+"){let n=z(e.argument);return typeof n=="number"?+n:void 0}return;case"BinaryExpression":{let{operator:n,left:t}=e;return n==="|"?z(t):void 0}case"LogicalExpression":{let{operator:n,left:t,right:r}=e;return n==="&&"&&t.type==="Literal"&&t.value===null?null:n==="||"||n==="??"?z(t)??z(r):void 0}default:return}}function Dt(e){try{let n=Ar(e,0,{ecmaVersion:2022});return L(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 jr(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 Ut(e,n,t,r={},s,o){let i=Ot(n,e),a=new Map;for(let v of e.params){let h=Be(v,s);if(h.name==="__destructured__"&&h.type.kind==="object"&&h.type.destructuredParams)for(let[$,S]of Object.entries(h.type.destructuredParams))a.set($,{...S,description:i.params[$]});else h.description=i.params[h.name],a.set(h.name,h)}let l;t&&(l=Dt(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},u=V(e.body,c),p=[],f=[],d=[];for(let[v,h]of a.entries())h.required?f.push(v):h.default!==void 0?d.push({name:v,defaultValue:h.default}):f.push(v);f.length>0&&p.push({op:"varsImport",keys:f});for(let{name:v,defaultValue:h}of d)p.push({op:"varsImport",keys:[v]}),p.push({op:"if",condition:{$expr:"binary",op:"==",left:{$expr:"ident",name:v},right:{$expr:"literal",value:null}},then:[{op:"varSet",key:v,value:h}]});p.push(...u);let g=Object.fromEntries(a),b={name:e.id?.name||"anonymous",description:i.description,parameters:g,returns:l},w=jr(g),E=c.helperSteps&&c.helperSteps.size>0?Object.fromEntries(c.helperSteps):void 0;return{ast:{op:"seq",steps:p,inputSchema:w,...E&&{helpers:E}},signature:b,warnings:c.warnings}}function V(e,n){let t=[];for(let r of e.body){let s=le(r,n);s&&(Array.isArray(s)?t.push(...s):t.push(s))}return t}function le(e,n){switch(e.type){case"VariableDeclaration":return Mr(e,n);case"ExpressionStatement":return Pr(e,n);case"IfStatement":return Rr(e,n);case"WhileStatement":return Nr(e,n);case"ForOfStatement":return Ir(e,n);case"TryStatement":return _r(e,n);case"ReturnStatement":return Br(e,n);case"ThrowStatement":throw new I("'throw' is not supported in AsyncJS. Use Error('message') to trigger error flow",_(e),n.source,n.filename);case"BlockStatement":return{op:"scope",steps:V(e,W(n))};case"EmptyStatement":return null;default:throw new I(`Unsupported statement type: ${e.type}`,_(e),n.source,n.filename)}}function Mr(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 I("Only simple variable names are supported",_(o),n.source,n.filename);let i=o.id.name;if(o.init){let{step:a,resultVar:l}=X(o.init,n,i,r);a?t.push(a):l!==i&&t.push({op:s,key:i,value:l});let c=L(o.init);n.locals.set(i,c)}else{if(r)throw new I("const declarations must be initialized",_(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 Cr(t,n);if(t.type==="CallExpression"){let{step:r,resultVar:s}=X(t,n);return r||(s?{op:"varSet",key:"_",value:s}:null)}return n.warnings.push({message:"Expression statement has no effect",line:_(e).line,column:_(e).column}),null}function Cr(e,n){if(e.left.type!=="Identifier")throw new I("Only simple variable assignment is supported",_(e),n.source,n.filename);let t=e.left.name,{step:r,resultVar:s}=X(e.right,n,t);return r||{op:"varSet",key:t,value:s}}function Rr(e,n){let t=N(e.test,n),r=e.consequent.type==="BlockStatement"?V(e.consequent,W(n)):[le(e.consequent,n)].filter(Boolean),s;return e.alternate&&(s=e.alternate.type==="BlockStatement"?V(e.alternate,W(n)):[le(e.alternate,n)].filter(Boolean)),{op:"if",condition:t,then:r,...s&&{else:s}}}function Nr(e,n){let t=N(e.test,n),r=e.body.type==="BlockStatement"?V(e.body,W(n)):[le(e.body,n)].filter(Boolean);return{op:"while",condition:t,body:r}}function Ir(e,n){let t;if(e.left.type==="VariableDeclaration"){let i=e.left.declarations[0];if(i.id.type!=="Identifier")throw new I("Only simple variable names are supported in for...of",_(e.left),n.source,n.filename);t=i.id.name}else if(e.left.type==="Identifier")t=e.left.name;else throw new I("Unsupported for...of left-hand side",_(e.left),n.source,n.filename);let r=F(e.right,n),s=W(n);s.locals.set(t,{kind:"any"});let o=e.body.type==="BlockStatement"?V(e.body,s):[le(e.body,s)].filter(Boolean);return{op:"map",items:r,as:t,steps:o}}function _r(e,n){let t=V(e.block,W(n)),r,s;if(e.handler){let o=W(n);e.handler.param?.type==="Identifier"&&(s=e.handler.param.name,o.locals.set(s,{kind:"any"})),r=V(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}=X(e.argument,n,"__returnVal__");return t?[t,{op:"return",value:r}]:{op:"return",value:F(e.argument,n)}}var Lt=new Set(["Math","JSON","Array","Object","String","Number","console","Date","Schema"]),Or=new Set(["parseInt","parseFloat","isNaN","isFinite","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent","Set","Date","filter"]),ce=new Set(["RegExp","Promise","Map","WeakSet","WeakMap","Symbol","Proxy","Reflect","Function","eval","setTimeout","setInterval","fetch","require","import","process","window","document","global","globalThis"]),Dr=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 Fr(e){if(e.callee.type==="Identifier"){let n=e.callee.name;return Or.has(n)||ce.has(n)}if(e.callee.type==="MemberExpression"){let n=e.callee;if(n.object.type==="Identifier"){let t=n.object.name;if(Lt.has(t)||ce.has(t))return!0}if(n.property.type==="Identifier"){let t=n.property.name;if(Dr.has(t))return!0}}return!1}function Ur(e){if(e.object.type==="Identifier"){let n=e.object.name;return Lt.has(n)||ce.has(n)}return!1}var Ft={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 Lr(e){if(e.callee.type==="Identifier"){let n=e.callee.name;if(ce.has(n))return Ft[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(ce.has(t))return Ft[t]||`${t} is not available in AsyncJS.`}}return null}function qt(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 X(e,n,t,r){let s=r?"constSet":"varSet";if(e.type==="ChainExpression")return X(e.expression,n,t,r);if(e.type==="NewExpression"){let i=e,a="constructor";i.callee.type==="Identifier"&&(a=i.callee.name);let l=qt(a);throw new I(`The 'new' keyword is not supported in AsyncJS.${l}`,_(e),n.source,n.filename)}if(e.type==="CallExpression"){let i=Lr(e);if(i)throw new I(i,_(e),n.source,n.filename)}if(e.type==="CallExpression"&&Fr(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"&&Ur(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 qr(e,n,t,r);if(e.type==="TemplateLiteral")return zr(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:F(e,n)}}function qr(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=F(l.object,n);else throw new I("Computed method names are not supported",_(e),n.source,n.filename)}else throw new I("Only named function calls are supported",_(e),n.source,n.filename);if(o)return Vr(s,i,e.arguments,n,t,r);if(s==="console"&&e.callee.type,n.helpers?.has(s)){let l=Wr(s,n,e),c=e.arguments.map(u=>F(u,n));if(c.length!==l.length)throw new I(`Helper '${s}' expects ${l.length} argument(s), got ${c.length}`,_(e),n.source,n.filename);return{step:{op:"callLocal",name:s,args:c,...t&&{result:t},...t&&r&&{resultConst:!0}},resultVar:t}}let a=Jr(e,n);return{step:{op:s,...a,...t&&{result:t},...t&&r&&{resultConst:!0}},resultVar:t}}function Wr(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 I(`Helper '${e}' parameters must be plain identifiers (optionally with an example value); destructuring is not supported`,o.loc?.start??_(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=V(r.body,o);n.helperSteps.set(e,{steps:i,paramNames:s})}finally{n.helperTransforming.delete(e)}return s}function Vr(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=W(r);c.locals.set(l,{kind:"any"});let u;if(i.body.type==="BlockStatement")u=V(i.body,c);else{let{step:p,resultVar:f}=X(i.body,c,"result");u=p?[p]:[{op:"varSet",key:"result",value:f}]}return{step:{op:"map",items:n,as:l,steps:u,...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=W(r);c.locals.set(l,{kind:"any"});let u;if(i.body.type==="BlockStatement")throw new I("filter callback must be an expression, not a block",_(t[0]),r.source,r.filename);return u=N(i.body,c),{step:{op:"filter",items:n,as:l,condition:u,...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=W(r);c.locals.set(l,{kind:"any"});let u;if(i.body.type==="BlockStatement")throw new I("find callback must be an expression, not a block",_(t[0]),r.source,r.filename);return u=N(i.body,c),{step:{op:"find",items:n,as:l,condition:u,...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",u=l?.type==="Identifier"?l.name:"item",p=W(r);p.locals.set(c,{kind:"any"}),p.locals.set(u,{kind:"any"});let f;if(i.body.type==="BlockStatement")f=V(i.body,p);else{let{step:g,resultVar:b}=X(i.body,p,"result");f=g?[g]:[{op:"varSet",key:"result",value:b}]}let d=F(t[1],r);return{step:{op:"reduce",items:n,as:u,accumulator:c,initial:d,steps:f,...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}break;case"slice":break;case"push":return{step:{op:"push",list:n,item:F(t[0],r),...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s};case"join":return{step:{op:"join",list:n,sep:t.length>0?F(t[0],r):"",...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s};case"split":return{step:{op:"split",str:n,sep:t.length>0?F(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=>F(i,r)),...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}function zr(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]=F(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 I(`Helper '${r}' cannot be called inside an expression. Assign its result to a variable first: const result = ${r}(...); then use result.`,_(e),n.source,n.filename);return{$expr:"call",callee:r,arguments:t.arguments.map(s=>N(s,n))}}throw new I("Complex function calls in expressions should be lifted to statements",_(e),n.source,n.filename)}case"NewExpression":{let t=e,r="constructor";t.callee.type==="Identifier"&&(r=t.callee.name);let s=qt(r);throw new I(`The 'new' keyword is not supported in AsyncJS.${s}`,_(e),n.source,n.filename)}case"TemplateLiteral":throw new I("Template literals inside expressions are not supported. Assign to a variable first: const msg = `hello ${name}`; then use msg",_(e),n.source,n.filename);default:throw new I(`Unsupported expression type in condition: ${e.type}`,_(e),n.source,n.filename)}}function F(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=F(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 F(e.expression,n);case"ArrayExpression":return e.elements.map(t=>t?F(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]=F(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 Jr(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]=F(s.value,n)}return r}return{args:e.arguments.map(t=>F(t,n))}}function ue(e,n={}){let{ast:t,returnType:r,originalSource:s,requiredParams:o}=_t(e,{filename:n.filename,colonShorthand:!0,vmTarget:!0}),{entry:i,helpers:a}=Bt(t,n.filename),{ast:l,signature:c,warnings:u}=Ut(i,s,r,n,o,a.size>0?a:void 0);return{ast:l,signature:c,warnings:u}}var Gr=6e4,Se=class{atoms;_defaultRunTimeout;constructor(n={}){this.atoms={...ke,...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(Gr,n*2)}return this._defaultRunTimeout}get builder(){return new ie(this.atoms)}get Agent(){return new ie(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(ve(n))s=Te(n);else try{s=ue(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,b=!1;a.store={get:async w=>(b||(b=!0,l.push("Using default in-memory store (not suitable for production)")),g.get(w)),set:async(w,E)=>{b||(b=!0,l.push("Using default in-memory store (not suitable for production)")),g.set(w,E)}}}let c=new AbortController,u=setTimeout(()=>c.abort(),i);r.signal&&r.signal.addEventListener("abort",()=>c.abort());let p={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&&(p.trace=[]),s.op!=="seq")throw new Error("Root AST must be 'seq'. Ensure you're passing a transpiled agent (use ajs`...` or transpile()).");let f=s.inputSchema;if(f&&!Zr(t,f)){let g=new D("Input validation failed: args do not match expected schema","vm.run");return{result:g,error:g,fuelUsed:0,trace:p.trace,warnings:l.length>0?l:void 0}}try{await Promise.race([this.resolve("seq")?.exec(s,p),new Promise((g,b)=>{c.signal.addEventListener("abort",()=>{b(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&&b(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)p.error=new D(`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(u)}p.error&&p.output===void 0&&(p.output=p.error);let d=[...l,...p.warnings??[]];return{result:p.output,error:p.error,fuelUsed:o-p.fuel.current,trace:p.trace,warnings:d.length>0?d:void 0}}};var Hr=null,Wt=()=>Hr??=new Se;function Q(e){if(!(!e||typeof e!="object")){if(Array.isArray(e)){for(let n of e)Q(n);return}e.op==="return"&&"value"in e&&(e.value={__result:e.value}),e.steps&&Q(e.steps),e.then&&Q(e.then),e.else&&Q(e.else),e.body&&Q(e.body)}}async function Ps(e){let{code:n,context:t={},fuel:r=1e3,timeoutMs:s,capabilities:o={}}=e,i=Wt(),l=/\breturn\b/.test(n)?`function __eval() { ${n} }`:`function __eval() { return (${n}) }`;try{let{ast:c}=ue(l);Q(c);let u=await i.run(c,t,{fuel:r,timeoutMs:s,capabilities:o}),p=u.result;return{result:p&&typeof p=="object"&&"__result"in p?p.__result:p,fuelUsed:u.fuelUsed,error:u.error?{message:u.error.message||String(u.error)}:void 0}}catch(c){return{result:void 0,fuelUsed:r,error:{message:c.message||String(c)}}}}async function Cs(e){let{body:n,params:t=[],fuel:r=1e3,timeoutMs:s,capabilities:o={}}=e,i=Wt(),l=`function __safeFn(${t.join(", ")}) { ${n} }`,{ast:c}=ue(l);return Q(c),async(...u)=>{let p={};for(let f=0;f<t.length;f++)p[t[f]]=u[f];try{let f=await i.run(c,p,{fuel:r,timeoutMs:s,capabilities:o}),d=f.result;return{result:d&&typeof d=="object"&&"__result"in d?d.__result:d,fuelUsed:f.fuelUsed,error:f.error?{message:f.error.message||String(f.error)}:void 0}}catch(f){return{result:void 0,fuelUsed:r,error:{message:f.message||String(f)}}}}}export{Ps as Eval,Cs as SafeFunction};
54
55
  //# sourceMappingURL=tjs-eval.js.map