tjs-lang 0.7.3 → 0.7.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/demo/docs.json +29 -29
- package/dist/index.js +175 -176
- package/dist/index.js.map +5 -44
- package/dist/scripts/build.d.ts +8 -4
- package/dist/src/lang/runtime.d.ts +8 -4
- package/dist/src/types/Type.d.ts +5 -5
- package/dist/tjs-batteries.js +3 -4
- package/dist/tjs-batteries.js.map +5 -13
- package/dist/tjs-eval.js +47 -0
- package/dist/tjs-eval.js.map +7 -0
- package/dist/tjs-from-ts.js +58 -0
- package/dist/tjs-from-ts.js.map +7 -0
- package/dist/tjs-lang.js +349 -0
- package/dist/tjs-lang.js.map +7 -0
- package/dist/tjs-vm.js +51 -52
- package/dist/tjs-vm.js.map +4 -19
- package/package.json +17 -11
- package/src/lang/emitters/js.ts +4 -4
- package/src/lang/function-predicate.test.ts +8 -6
- package/src/lang/runtime.test.ts +58 -0
- package/src/lang/runtime.ts +27 -13
- package/src/types/Type.test.ts +68 -19
- package/src/types/Type.ts +80 -54
- package/dist/tjs-full.js +0 -437
- package/dist/tjs-full.js.map +0 -46
- package/dist/tjs-transpiler.js +0 -3
- package/dist/tjs-transpiler.js.map +0 -11
package/dist/tjs-eval.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import{s as f,validate as Ee,filter as Oe}from"tosijs-schema";var le=Symbol.for("tjs.equals");function ue(e,n){if(e!==null&&typeof e=="object"&&typeof e[le]=="function")return e[le](n);if(n!==null&&typeof n=="object"&&typeof n[le]=="function")return n[le](e);if(e!==null&&typeof e=="object"&&typeof e.Equals=="function")return e.Equals(n);if(n!==null&&typeof n=="object"&&typeof n.Equals=="function")return n.Equals(e);if(e===n||e==null&&n==null)return!0;if(e==null||n===null||n===void 0||typeof e!=typeof n||typeof e!="object")return!1;if(Array.isArray(e)&&Array.isArray(n))return e.length!==n.length?!1:e.every((s,i)=>ue(s,n[i]));if(Array.isArray(e)!==Array.isArray(n))return!1;let t=Object.keys(e),r=Object.keys(n);return t.length!==r.length?!1:t.every(s=>ue(e[s],n[s]))}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 Rt(e){return e instanceof D||e&&e.$error===!0}var ee=new Map,Pt=3600*1e3,It=100*1024,$e="proc_";function xe(e){return typeof e=="string"&&e.startsWith($e)}function Te(e){let n=ee.get(e);if(!n)throw new Error(`Procedure not found: ${e}`);if(Date.now()>n.expiresAt)throw ee.delete(e),new Error(`Procedure expired: ${e}`);return n.ast}function Bt(){return typeof crypto<"u"&&crypto.randomUUID?$e+crypto.randomUUID():$e+Math.random().toString(36).slice(2)+Date.now().toString(36)}var De=new Set(["__proto__","constructor","prototype"]);function Ne(e){if(De.has(e))throw new Error(`Security Error: Access to '${e}' is forbidden`)}var _t=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","metadata.google.internal"]);function Ot(e){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return!0;let t=n.hostname.toLowerCase();return!!(_t.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 Dt(e){return!!(/\([^)]*[+*][^)]*\)[+*]/.test(e)||/\(([^|)]+)\|\1\)[+*]/.test(e)||/\(\.\*\)\+/.test(e)||/\(\.\+\)\+/.test(e)||/\(\[.*\]\+\)\+/.test(e))}function G(e){return{...e,state:Object.create(e.state)}}function Ft(e,n){let t={},r=new Set([...Object.keys(e),...Object.keys(n)]);for(let s of r){let i=e[s],o=n[s];o!==i&&(t[s]=o)}return t}function w(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(De.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]=w(e[r],n);return t}return Array.isArray(e)?e.map(t=>w(t,n)):e}function K(e,n,t){return new Proxy(n,{get(r,s){if(s in r)return r[s];let i=t?.[s];throw i?new Error(`${e}.${s} is not available. ${i}`):new Error(`${e}.${s} is not supported in AsyncJS. Check docs for available ${e} methods.`)}})}function Q(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:Q(e[0])};if(n==="object"){let t={},r=[];for(let[s,i]of Object.entries(e))t[s]=Q(i),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=Q(n),r=Oe(e,t);if(r instanceof Error)throw r;return r},Schema:{...f,response:(e,n)=>{let t=n?.schema!=null?n.schema:Q(n);return{type:"json_schema",json_schema:{name:e,strict:!0,schema:t}}},fromExample:e=>Q(e),isValid:(e,n)=>n?.schema!=null?Ee(e,n):Ee(e,Q(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:i=0,hours:o=0,minutes:a=0,seconds:c=0,ms:l=0}={}){let p=new globalThis.Date(t.getTime());return r&&p.setFullYear(p.getFullYear()+r),s&&p.setMonth(p.getMonth()+s),i&&p.setDate(p.getDate()+i),o&&p.setHours(p.getHours()+o),a&&p.setMinutes(p.getMinutes()+a),c&&p.setSeconds(p.getSeconds()+c),l&&p.setMilliseconds(p.getMilliseconds()+l),e(p)},diff(r,s="ms"){let i=typeof r=="object"&&r.timestamp?r.timestamp:new globalThis.Date(r).getTime(),o=t.getTime()-i;switch(s){case"seconds":return o/1e3;case"minutes":return o/6e4;case"hours":return o/36e5;case"days":return o/864e5;default:return o}},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."},Ut=.01,Re=1e-4,Pe=.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-=Ut,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 ce)throw new Error(ce[e.name]);return}case"member":{let t=B(e.object,n);if(e.optional&&t==null)return;let r=e.property;return Ne(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*Re,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 ue(t,r);case"!=":return!ue(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(i=>B(i,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(i=>B(i,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(Ne(r),t==null)throw new Error(`Cannot call method '${r}' on ${t}`);let s=t[r];if(typeof s!="function")throw new Error(`'${r}' is not a function`);let i=e.arguments.map(a=>B(a,n)),o=s.apply(t,i);if(n.fuel&&qt.has(r)){let a=0;if(typeof o=="string"?a=o.length*Re:Array.isArray(o)?a=o.length*Pe:typeof o=="object"&&o!==null&&(a=Object.keys(o).length*Pe),n.fuel.current-=a,n.fuel.current<=0){n.error=new D("Out of Fuel",`expr.${r}`);return}}return o}default:throw new Error(`Unknown expression type: ${e.$expr}`)}}function j(e,n,t,r,s={}){let{docs:i="",timeoutMs:o=1e3,cost:a=1}=typeof s=="string"?{docs:s}:s;return{op:e,inputSchema:n,outputSchema:t,exec:async(l,p)=>{let{op:d,result:u,...m}=l;if(p.error)return;let y=p.trace?{...p.state}:null,b=p.fuel.current,h,S;try{let x=p.costOverrides?.[e],g=x!==void 0?x:a,E=typeof g=="function"?g(m,p):g;if((p.fuel.current-=E)<=0){p.error=new D("Out of Fuel",e);return}let A,$=async()=>r(l,p);if(h=o>0?await Promise.race([$(),new Promise((T,v)=>{A=setTimeout(()=>v(new Error(`Atom '${e}' timed out`)),o)})]).finally(()=>clearTimeout(A)):await $(),l.result){if(p.consts.has(l.result))throw new Error(`Cannot reassign const variable '${l.result}'`);if(h!==void 0&&t&&!Ee(h,t)){p.error=new D(`Output validation failed for '${e}'`,e);return}p.state[l.result]=h,l.resultConst&&p.consts.add(l.result)}}catch(x){S=x.message||String(x),p.error=new D(S,e,x)}finally{if(p.trace&&y){let x=Ft(y,p.state);p.trace.push({op:e,input:m,stateDiff:x,result:h,error:S,fuelBefore:b,fuelAfter:p.fuel.current,timestamp:new Date().toISOString()})}}},docs:i,timeoutMs:o,cost:a,create:l=>({op:e,...l})}}var U=j("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}),Lt=j("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 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}),Wt=j("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 U.exec({op:"seq",steps:e.body},n),n.output!==void 0)return}},{docs:"While Loop",timeoutMs:0,cost:.1}),Vt=j("return",void 0,f.any,async(e,n)=>{if(n.error)return n.output=n.error,n.error;if("value"in e){let r=w(e.value,n);if(r!=null&&!Rt(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=Oe(t,e.schema);r instanceof Error||(t=r)}}return n.output=t,t},{docs:"Return",cost:.1}),Jt=j("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 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}),zt=j("Error",f.object({args:f.array(f.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}),Zt=j("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]=w(n,t)},{docs:"Set Variable",cost:.1}),Gt=j("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]=w(n,t),t.consts.add(e)},{docs:"Set Const Variable (immutable)",cost:.1}),Ht=j("varGet",f.object({key:f.string}),f.any,async({key:e},n)=>w(e,n),{docs:"Get Variable",cost:.1}),Kt=j("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]=w({$kind:"arg",path:t},n);else for(let[t,r]of Object.entries(e))n.state[t]=w({$kind:"arg",path:r},n)},{docs:"Import variables from args into the current scope, with optional renaming.",cost:.2}),Yt=j("varsLet",f.record(f.any),void 0,async(e,n)=>{for(let t of Object.keys(e))t==="op"||t==="result"||(n.state[t]=w(e[t],n))},{docs:"Initialize a set of variables in the current scope from the step object properties.",cost:.1}),Xt=j("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]=w(r,n);else for(let[r,s]of Object.entries(e))t[r]=w(s,n);return t},{docs:"Export variables from the current scope, with optional renaming.",cost:.2}),Qt=j("scope",f.object({steps:f.array(f.any)}),void 0,async({steps:e},n)=>{let t=G(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}),en=j("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=[],i=w(e,r);if(!Array.isArray(i))throw new Error("map: items is not an array");for(let o of i){if(r.signal?.aborted)throw new Error("Execution aborted");let a=G(r);a.state[n]=o,await U.exec({op:"seq",steps:t},a),s.push(a.state.result??null)}return s},{docs:"Map Array",timeoutMs:0,cost:1}),tn=j("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=[],i=w(e,r);if(!Array.isArray(i))throw new Error("filter: items is not an array");for(let o of i){if(r.signal?.aborted)throw new Error("Execution aborted");let a=G(r);a.state[n]=o,B(t,a)&&s.push(o)}return s},{docs:"Filter Array",timeoutMs:0,cost:1}),nn=j("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},i)=>{let o=w(e,i),a=w(r,i);if(!Array.isArray(o))throw new Error("reduce: items is not an array");let c=a;for(let l of o){if(i.signal?.aborted)throw new Error("Execution aborted");let p=G(i);p.state[n]=l,p.state[t]=c,await U.exec({op:"seq",steps:s},p),c=p.state.result??c}return c},{docs:"Reduce Array",timeoutMs:0,cost:1}),rn=j("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=w(e,r);if(!Array.isArray(s))throw new Error("find: items is not an array");for(let i of s){if(r.signal?.aborted)throw new Error("Execution aborted");let o=G(r);if(o.state[n]=i,B(t,o))return i}return null},{docs:"Find in Array",timeoutMs:0,cost:1}),sn=j("push",f.object({list:f.array(f.any),item:f.any}),f.array(f.any),async({list:e,item:n},t)=>{let r=w(e,t),s=w(n,t);return Array.isArray(r)&&r.push(s),r},{docs:"Push to Array",cost:1}),on=j("len",f.object({list:f.any}),f.number,async({list:e},n)=>{let t=w(e,n);return Array.isArray(t)||typeof t=="string"?t.length:0},{docs:"Length",cost:1}),an=j("split",f.object({str:f.string,sep:f.string}),f.array(f.string),async({str:e,sep:n},t)=>w(e,t).split(w(n,t)),{docs:"Split String",cost:1}),ln=j("join",f.object({list:f.array(f.string),sep:f.string}),f.string,async({list:e,sep:n},t)=>w(e,t).join(w(n,t)),{docs:"Join String",cost:1}),cn=j("template",f.object({tmpl:f.string,vars:f.record(f.any)}),f.string,async({tmpl:e,vars:n},t)=>w(e,t).replace(/\{\{(\w+)\}\}/g,(s,i)=>String(w(n[i],t)??"")),{docs:"String Template",cost:1}),un=j("regexMatch",f.object({pattern:f.string,value:f.any}),f.boolean,async({pattern:e,value:n},t)=>{if(Dt(e))throw new Error(`Suspicious regex pattern rejected (potential ReDoS): ${e}`);let r=w(n,t);return new RegExp(e).test(r)},{docs:"Returns true if the value matches the regex pattern.",cost:2}),fn=j("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=w(e,t),s=w(n,t),i={};return r&&Array.isArray(s)&&s.forEach(o=>i[o]=r[o]),i},{docs:"Pick Keys",cost:1}),pn=j("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=w(e,t),s=new Set(w(n,t)),i={};return r&&Object.keys(r).forEach(o=>{s.has(o)||(i[o]=r[o])}),i},{docs:"Omit Keys",cost:1}),dn=j("merge",f.object({a:f.record(f.any),b:f.record(f.any)}),f.record(f.any),async({a:e,b:n},t)=>({...w(e,t),...w(n,t)}),{docs:"Merge Objects",cost:1}),mn=j("keys",f.object({obj:f.record(f.any)}),f.array(f.string),async({obj:e},n)=>Object.keys(w(e,n)??{}),{docs:"Object Keys",cost:1}),Ie=10,Be="X-Agent-Depth";function yn(e,n){try{let r=new URL(e).hostname.toLowerCase();for(let s of n){let i=s.toLowerCase();if(i.startsWith("*.")){let o=i.slice(1);if(r.endsWith(o)||r===i.slice(2))return!0}else if(r===i)return!0}return!1}catch{return!1}}var gn=j("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=w(e.url,n),r=w(e.method,n),s=w(e.headers,n)||{},i=w(e.body,n),o=w(e.responseType,n),a=n.context?.requestDepth??0;if(a>=Ie)throw new Error(`Agent request depth exceeded (max ${Ie}). This prevents recursive agent loops.`);if(n.capabilities.fetch)return n.capabilities.fetch(t,{method:r,headers:{...s,[Be]:String(a+1)},body:i,signal:n.signal,responseType:o});let c=n.context?.allowedFetchDomains;if(c){if(!yn(t,c))throw new Error(`Fetch blocked: domain not in allowlist. Allowed: ${c.join(", ")}`)}else{if(Ot(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(l){throw l.message.includes("allowedFetchDomains")?l:new Error(`Invalid URL: ${t}`)}}if(typeof globalThis.fetch=="function"){let l=await globalThis.fetch(t,{method:r,headers:{...s,[Be]:String(a+1)},body:i?JSON.stringify(i):void 0,signal:n.signal});if(o==="dataUrl"){let d=await l.arrayBuffer(),u=new Uint8Array(d),m="";for(let h=0;h<u.length;h++)m+=String.fromCharCode(u[h]);let y=btoa(m);return`data:${l.headers.get("content-type")||"application/octet-stream"};base64,${y}`}let p=l.headers.get("content-type");return o==="json"||p&&p.includes("application/json")?l.json():l.text()}throw new Error("Capability 'fetch' missing and no global fetch available")},{docs:"HTTP Fetch",timeoutMs:3e4,cost:5}),hn=j("storeGet",f.object({key:f.string}),f.any,async({key:e},n)=>{let t=w(e,n);return n.capabilities.store?.get(t)},{docs:"Store Get",cost:5}),bn=j("storeSet",f.object({key:f.string,value:f.any}),void 0,async({key:e,value:n},t)=>{let r=w(e,t),s=w(n,t);return t.capabilities.store?.set(r,s)},{docs:"Store Set",cost:5}),wn=j("storeQuery",f.object({query:f.any}),f.array(f.any),async({query:e},n)=>n.capabilities.store?.query?.(w(e,n))??[],{docs:"Store Query",cost:5}),Sn=j("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?.(w(e,r),w(n,r),w(t,r))??[],{docs:"Vector Search",cost:(e,n)=>5+(w(e.k,n)??5)}),En=j("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(w(e,t),w(n,t))},{docs:"LLM Predict",timeoutMs:12e4,cost:100}),$n=j("agentRun",f.object({agentId:f.any,input:f.any}),f.any,async({agentId:e,input:n},t)=>{let r=w(e,t),s=w(n,t),i=s;if(s&&typeof s=="object"&&!Array.isArray(s)){i={};for(let a in s)i[a]=w(s[a],t)}if(xe(r)){let a=Te(r),c={...t,args:i,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(a,c),c.error)throw new Error(c.error.message||"Sub-agent failed");return c.output}if(r&&typeof r=="object"&&"op"in r){let a={...t,args:i,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(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 o=await t.capabilities.agent.run(r,i);if(o&&typeof o=="object"&&"fuelUsed"in o&&typeof o.fuelUsed=="number"){if(o.error)throw new Error(o.error.message||"Sub-agent failed");return o.result}return o},{docs:"Run Sub-Agent (accepts procedure token, AST, or agent ID)",cost:1}),xn=j("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=w(e,n);try{return n.capabilities.code.transpile(t)}catch(r){throw new Error(`Code transpilation failed: ${r.message}`)}},{docs:"Transpile AsyncJS code to AST",cost:1}),_e=10,Tn=j("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>=_e)throw new Error(`runCode recursion limit exceeded (max ${_e}). 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=w(e,t),i=n?w(n,t):{},o;try{o=t.capabilities.code.transpile(s)}catch(c){throw new Error(`Code transpilation failed: ${c.message}`)}if(o.op!=="seq")throw new Error("Transpiled code must be a seq node");let a=G(t);if(a.args=i,a.output=void 0,a.runCodeDepth=r+1,await U.exec(o,a),a.error){t.error=a.error;return}return a.output},{docs:"Run dynamically generated AsyncJS code",cost:1}),An=j("jsonParse",f.object({str:f.string}),f.any,async({str:e},n)=>JSON.parse(w(e,n)),{docs:"Parse JSON",cost:1}),vn=j("jsonStringify",f.object({value:f.any}),f.string,async({value:e},n)=>JSON.stringify(w(e,n)),{docs:"Stringify JSON",cost:1}),jn=j("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(w(e,n))},{docs:"Parse XML",cost:1}),Mn=j("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=w(e,t)??await Ae.exec({value:n,algorithm:"SHA-256"},t);if(t.memo.has(r))return t.memo.get(r);let s=G(t);await U.exec({op:"seq",steps:n},s);let i=s.output??s.state.result;return t.memo.set(r,i),i},{docs:"Memoize steps result in memory",cost:1}),kn=j("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 i=`cache:${w(e,r)??await Ae.exec({value:n,algorithm:"SHA-256"},r)}`,o=await r.capabilities.store.get(i);if(o)if(typeof o=="object"&&o._exp){if(Date.now()<o._exp)return o.val}else return o;let a=G(r);await U.exec({op:"seq",steps:n},a);let c=a.output??a.state.result,l=Date.now()+(t??24*3600*1e3);if((r.fuel.current-=5)<=0)throw new Error("Out of Fuel");return await r.capabilities.store.set(i,{val:c,_exp:l}),c},{docs:"Cache steps result in store with TTL",cost:5}),Cn=j("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 i=w(t,s)??"float",o=w(r,s)??10,a=w(e,s)??0,c=w(n,s)??1;if(i==="base36"){let u="0123456789abcdefghijklmnopqrstuvwxyz",m="";if(typeof crypto<"u"&&crypto.getRandomValues){let y=new Uint8Array(o);crypto.getRandomValues(y);for(let b=0;b<o;b++)m+=u[y[b]%36]}else for(let y=0;y<o;y++)m+=u.charAt(Math.floor(Math.random()*36));return m}let l;if(typeof crypto<"u"&&crypto.getRandomValues){let u=new Uint32Array(1);crypto.getRandomValues(u),l=u[0]/4294967296}else l=Math.random();let p=c-a,d=l*p+a;return i==="integer"?Math.floor(d):d},{docs:"Generate Random",cost:1}),Nn=j("uuid",void 0,f.string,async()=>{if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=Array.from(e,t=>t.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let n=Math.random()*16|0;return(e==="x"?n:n&3|8).toString(16)})},{docs:"Generate UUID",cost:1}),Ae=j("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(w(e,t)),s=w(n,t)||"SHA-256";if(typeof crypto<"u"&&crypto.subtle){let a=new TextEncoder().encode(r),c=await crypto.subtle.digest(s,a);return Array.from(new Uint8Array(c)).map(p=>p.toString(16).padStart(2,"0")).join("")}let i=0;for(let o=0;o<r.length;o++){let a=r.charCodeAt(o);i=(i<<5)-i+a,i|=0}return String(i)},{docs:"Hash a value",cost:1}),Rn=j("consoleLog",f.object({message:f.any}),void 0,async({message:e},n)=>{let t=w(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}),Pn=j("consoleWarn",f.object({message:f.any}),void 0,async({message:e},n)=>{let t=w(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}),In=j("consoleError",f.object({message:f.any}),void 0,async({message:e},n)=>{let t=w(e,n),r=typeof t=="string"?t:JSON.stringify(t);n.error=new D(r,"console.error")},{docs:"Emit error and stop",cost:.1}),Bn=j("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=w(e,r),i=n?w(n,r):Pt,o=t?w(t,r):It;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>o)throw new Error(`AST too large: ${a.length} bytes exceeds limit of ${o} bytes. Consider reducing AST size or using a shorter TTL.`);let c=Bt(),l=Date.now();return ee.set(c,{ast:s,createdAt:l,expiresAt:l+i}),c},{docs:"Store an AST and return a token for later execution",cost:1}),_n=j("releaseProcedure",f.object({token:f.string}),f.boolean,async({token:e},n)=>{let t=w(e,n);return ee.delete(t)},{docs:"Release a stored procedure by token",cost:.1}),On=j("clearExpiredProcedures",void 0,f.number,async()=>{let e=Date.now(),n=0;for(let[t,r]of ee)e>r.expiresAt&&(ee.delete(t),n++);return n},{docs:"Clear all expired procedures and return count",cost:.5}),Fe={seq:U,if:Lt,while:Wt,return:Vt,try:Jt,Error:zt,varSet:Zt,constSet:Gt,varGet:Ht,varsImport:Kt,varsLet:Yt,varsExport:Xt,scope:Qt,map:en,filter:tn,reduce:nn,find:rn,push:sn,len:on,split:an,join:ln,template:cn,regexMatch:un,pick:fn,omit:pn,merge:dn,keys:mn,httpFetch:gn,storeGet:hn,storeSet:bn,storeQuery:wn,storeVectorSearch:Sn,llmPredict:En,agentRun:$n,transpileCode:xn,runCode:Tn,jsonParse:An,jsonStringify:vn,xmlParse:jn,memoize:Mn,cache:kn,random:Cn,uuid:Nn,hash:Ae,consoleLog:Rn,consoleWarn:Pn,consoleError:In,storeProcedure:Bn,releaseProcedure:_n,clearExpiredProcedures:On};var Dn=new Set(["true","false","null","undefined","and","or","not"]);function Fn(e,n){let t=e.replace(/"[^"]*"/g,'""').replace(/'[^']*'/g,"''"),r=[],s=/(?<![.])\b([a-zA-Z_][a-zA-Z0-9_]*)\b/g,i;for(;(i=s.exec(t))!==null;)r.push(i[1]);let a=[...new Set(r)].filter(c=>!Dn.has(c)&&!(c in n)&&!new RegExp(`\\b${c}\\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 fe(e,n){Fn(e,n);let t=Un(e),r=Ve(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 Un(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 Ve(e,n,t){return qn(e,n,t)}function qn(e,n,t){let{node:r,pos:s}=Ue(e,n,t);for(;e[s]==="||";){s++;let{node:i,pos:o}=Ue(e,s,t);r={$expr:"logical",op:"||",left:r,right:i},s=o}return{node:r,pos:s}}function Ue(e,n,t){let{node:r,pos:s}=qe(e,n,t);for(;e[s]==="&&";){s++;let{node:i,pos:o}=qe(e,s,t);r={$expr:"logical",op:"&&",left:r,right:i},s=o}return{node:r,pos:s}}function qe(e,n,t){let{node:r,pos:s}=Le(e,n,t),i=["==","!=",">","<",">=","<="];for(;i.includes(e[s]);){let o=e[s++],{node:a,pos:c}=Le(e,s,t);r={$expr:"binary",op:o,left:r,right:a},s=c}return{node:r,pos:s}}function Le(e,n,t){let{node:r,pos:s}=We(e,n,t);for(;e[s]==="+"||e[s]==="-";){let i=e[s++],{node:o,pos:a}=We(e,s,t);r={$expr:"binary",op:i,left:r,right:o},s=a}return{node:r,pos:s}}function We(e,n,t){let{node:r,pos:s}=ve(e,n,t);for(;e[s]==="*"||e[s]==="/"||e[s]==="%";){let i=e[s++],{node:o,pos:a}=ve(e,s,t);r={$expr:"binary",op:i,left:r,right:o},s=a}return{node:r,pos:s}}function ve(e,n,t){if(e[n]==="!"||e[n]==="-"){let r=e[n++],{node:s,pos:i}=ve(e,n,t);return{node:{$expr:"unary",op:r,argument:s},pos:i}}return Ln(e,n,t)}function Ln(e,n,t){let r=e[n];if(r==="("){let{node:s,pos:i}=Ve(e,n+1,t);return{node:s,pos:i+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},i=n+1;for(;e[i]===".";){i++;let o=e[i++];s={$expr:"member",object:s,property:o}}return{node:s,pos:i}}return{node:{$expr:"literal",value:null},pos:n+1}}var te=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 i=>{let o=t.atoms[r];return t.add(o.create(i)),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 i=new e(this.atoms);r(i);let o;if(s){let l=new e(this.atoms);s(l),o=l.steps}let a=fe(n,t),c=this.atoms.if;return this.add(c.create({condition:a,then:i.steps,else:o}))}while(n,t,r){let s=new e(this.atoms);r(s);let i=fe(n,t),o=this.atoms.while;return this.add(o.create({condition:i,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 i=this.atoms.map;return this.add(i.create({items:n,as:t,steps:s.steps}))}filter(n,t,r,s={}){let i=fe(r,s),o=this.atoms.filter;return this.add(o.create({items:n,as:t,condition:i}))}find(n,t,r,s={}){let i=fe(r,s),o=this.atoms.find;return this.add(o.create({items:n,as:t,condition:i}))}reduce(n,t,r,s,i){let o=new e(this.atoms);i(o);let a=this.atoms.reduce;return this.add(a.create({items:n,as:t,accumulator:r,initial:s,steps:o.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 i=this.atoms.cache;return this.add(i.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 i=new e(this.atoms);n.catch(i),r=i.steps}let s=this.atoms.try;return this.add(s.create({try:t.steps,catch:r}))}};import{validate as br}from"tosijs-schema";import*as Et from"acorn";var P=class extends Error{line;column;source;filename;constructor(n,t,r,s){let i=`${s||"<source>"}:${t.line}:${t.column}`;super(`${n} at ${i}`),this.name="TranspileError",this.line=t.line,this.column=t.column,this.source=r,this.filename=s}},F=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),i=Math.min(t.length-1,r+n),o=[],a=String(i+1).length;for(let c=s;c<=i;c++){let l=String(c+1).padStart(a),p=c===r?">":" ";if(o.push(`${p} ${l} | ${t[c]}`),c===r){let d=" ".repeat(a+4+this.column);o.push(`${d}^ ${this.message.split(" at ")[0]}`)}}return o.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}}function I(e){return e.loc?{line:e.loc.start.line,column:e.loc.start.column}:{line:1,column:0}}function ye(e,n){let t="",r=0,s,i,o="normal",a=[],c=[{type:"top-level",braceDepth:0}],l=0,p=()=>c[c.length-1]?.type||"top-level",d=()=>{let u=c[c.length-1];return u?.type==="class-body"&&l===u.braceDepth+1};for(;r<e.length;){let u=e[r],m=e[r+1];switch(o){case"single-string":if(t+=u,u==="\\"&&r+1<e.length){t+=m,r+=2;continue}u==="'"&&(o="normal"),r++;continue;case"double-string":if(t+=u,u==="\\"&&r+1<e.length){t+=m,r+=2;continue}u==='"'&&(o="normal"),r++;continue;case"template-string":if(t+=u,u==="\\"&&r+1<e.length){t+=m,r+=2;continue}if(u==="$"&&m==="{"){t+=m,r+=2,a.push(1),o="normal";continue}u==="`"&&(o="normal"),r++;continue;case"line-comment":t+=u,u===`
|
|
5
|
+
`&&(o="normal"),r++;continue;case"block-comment":if(t+=u,u==="*"&&m==="/"){t+=m,r+=2,o="normal";continue}r++;continue;case"regex":if(t+=u,u==="\\"&&r+1<e.length){t+=m,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++;o="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++,o="template-string";continue}}if(u==="'"){t+=u,r++,o="single-string";continue}if(u==='"'){t+=u,r++,o="double-string";continue}if(u==="`"){t+=u,r++,o="template-string";continue}if(u==="/"&&m==="/"){t+=u+m,r+=2,o="line-comment";continue}if(u==="/"&&m==="*"){t+=u+m,r+=2,o="block-comment";continue}if(u==="/"){let g=t.trimEnd();if(!g[g.length-1]||/[=(!,;:{[&|?+\-*%<>~^]$/.test(g)||/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)\s*$/.test(g)){t+=u,r++,o="regex";continue}}break}if(u==="{"){l++,t+=u,r++;continue}if(u==="}"){l--;let g=c[c.length-1];g&&l===g.braceDepth&&c.pop(),t+=u,r++;continue}let y=e.slice(r).match(/^class\s+\w+(?:\s+extends\s+\w+)?\s*\{/);if(y){let g=y[0].slice(0,-1);t+=g,r+=g.length,c.push({type:"class-body",braceDepth:l});continue}let b=e.slice(r).match(/^function\s+(\w+)\s*\(/);if(b){let g=b[1],E=b[0].length,A=e[r+E],$=null,T=r+E;(A==="?"||A==="!")&&($=A,T++,$==="!"?n.unsafeFunctions.add(g):n.safeFunctions.add(g)),t+=`function ${g}(`,r=T;let v=pe(e,r,"(",")");if(!v){t+=e[r],r++;continue}let{content:M,endPos:k}=v;r=k;let C=Me(M,n,!0);t+=C+")";let N=r;for(;N<e.length&&/\s/.test(e[N]);)N++;if(e[N]===":"){let O=e.slice(N,N+2),z;for(O===":?"||O===":!"?(N+=2,z=O===":?"?"safe":"unsafe"):N+=1;N<e.length&&/\s/.test(e[N]);)N++;let H=je(e,N);H&&(s===void 0&&(s=H.type,z&&(i=z)),r=H.endPos)}continue}let h=e.slice(r).match(/^(constructor|(?:get|set)\s+\w+|async\s+\w+|\w+)\s*\(/),S=(()=>{for(let g=t.length-1;g>=0;g--)if(!/\s/.test(t[g]))return t[g];return`
|
|
6
|
+
`})(),x=S!=="="&&S!==","&&S!=="("&&S!=="["&&S!==">";if(h&&d()&&!x){let g=h[1].length;t+=e.slice(r,r+g),r+=g;continue}if(h&&d()&&x){let g=h[1],E=h[0].length,A=r+E;t+=g+"(",r=A;let $=pe(e,r,"(",")");if(!$){t+=e[r],r++;continue}let{content:T,endPos:v}=$;r=v;let M=Me(T,n,!0);t+=M+")";let k=r;for(;k<e.length&&/\s/.test(e[k]);)k++;if(e[k]===":"){let C=e.slice(k,k+2);for(C===":?"||C===":!"?k+=2:k++;k<e.length&&/\s/.test(e[k]);)k++;let N=je(e,k);N&&(r=N.endPos)}continue}if(e[r]==="("){let g=pe(e,r+1,"(",")");if(!g){t+=e[r],r++;continue}let E=g.content,A=g.endPos,$=A;for(;$<e.length&&/\s/.test(e[$]);)$++;let T;if(e[$]===":"){let v=e.slice($,$+2);for(v===":?"||v===":!"?$+=2:$++;$<e.length&&/\s/.test(e[$]);)$++;let M=je(e,$);if(M)for(T=M.type,$=M.endPos;$<e.length&&/\s/.test(e[$]);)$++}if(e.slice($,$+2)==="=>"){let v=null,M=E,k=E.trimStart();k.startsWith("?")&&(k.length===1||/\s/.test(k[1]))?(v="?",M=k.slice(1)):k.startsWith("!")&&(k.length===1||/\s/.test(k[1]))&&(v="!",M=k.slice(1));let C=Me(M,n,!1);for(t+=`(${v==="?"?"/* safe */ ":v==="!"?"/* unsafe */ ":""}${C})`,r=A;r<$&&/\s/.test(e[r]);)t+=e[r],r++;T&&(r=$)}else{let v=ye(E,n);t+=`(${v.source})`,r=A}continue}t+=e[r],r++}return{source:t,returnType:s,returnSafety:i}}function pe(e,n,t,r){let s=1,i=n,o=!1,a="";for(;i<e.length&&s>0;){let c=e[i];!o&&(c==="'"||c==='"'||c==="`")?(o=!0,a=c):o&&c===a&&e[i-1]!=="\\"?o=!1:o||(c===t?s++:c===r&&s--),i++}return s!==0?null:{content:e.slice(n,i-1),endPos:i}}function Ze(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 o=s==="{"?"}":"]",a=pe(e,t+1,s,o);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 i=e.slice(t).match(/^(true|false|null|undefined)\b/);return i?{value:i[1],endPos:t+i[1].length}:null}function ne(e){return e.replace(/(?<!\|)\|(?!\|)/g," || ")}function je(e,n){let t=n,r=0,s=!1,i="",o=!1,a=c=>({type:ne(e.slice(n,c).trim()),endPos:c});for(;t<e.length;){let c=e[t];if(!s&&(c==="'"||c==='"'||c==="`")){s=!0,i=c,o=!0,t++;continue}if(s){if(c===i&&e[t-1]!=="\\"){if(s=!1,t++,r===0){let l=t;for(;l<e.length&&/\s/.test(e[l]);)l++;if(e[l]==="{"&&!e.slice(l+1).match(/^\s*(\w+)\s*:/)||e[l]!=="|"&&e[l]!=="&")return a(t)}continue}t++;continue}if(c==="{"||c==="["||c==="("){r++,o=!0,t++;continue}if(c==="}"||c==="]"||c===")"){if(r--,r===0){t++;let l=t;for(;l<e.length&&/\s/.test(e[l]);)l++;if(e[l]==="|"||e[l]==="&")continue;return a(t)}t++;continue}if(r===0&&c==="{"){if(o)return a(t);if(e.slice(t+1).match(/^\s*(\w+)\s*:/)){r++,o=!0,t++;continue}return a(t)}if(r===0&&(c==="|"||c==="&")){for(t++,t<e.length&&e[t]==="|"&&t++;t<e.length&&/\s/.test(e[t]);)t++;continue}if(r===0&&(/\d/.test(c)||c==="-"&&/\d/.test(e[t+1]))){let l=t;for(e[l]==="-"&&l++;l<e.length&&/\d/.test(e[l]);)l++;if(l<e.length&&e[l]==="."&&/\d/.test(e[l+1]))for(l++;l<e.length&&/\d/.test(e[l]);)l++;if(l<e.length&&(e[l]==="e"||e[l]==="E"))for(l++,l<e.length&&(e[l]==="+"||e[l]==="-")&&l++;l<e.length&&/\d/.test(e[l]);)l++;for(o=!0,t=l;t<e.length&&/\s/.test(e[t]);)t++;if(t<e.length&&e[t]==="{")return{type:ne(e.slice(n,l).trim()),endPos:l};if(e[t]!=="|"&&e[t]!=="&")return{type:ne(e.slice(n,l).trim()),endPos:l};continue}if(r===0&&/[a-zA-Z_]/.test(c)){let l=t;for(;l<e.length&&/\w/.test(e[l]);)l++;for(o=!0,t=l;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 d=l;for(;d>n&&/\s/.test(e[d-1]);)d--;return{type:ne(e.slice(n,d).trim()),endPos:l}}if(e[t]!=="|"&&e[t]!=="&")return{type:ne(e.slice(n,l).trim()),endPos:l};continue}t++}return o?a(t):null}function ge(e){let n=[],t="",r=0,s=!1,i=!1,o=0;for(;o<e.length;){let a=e[o],c=e[o+1];if(!i&&a==="/"&&c==="/"){s=!0,t+="//",o+=2;continue}if(!s&&a==="/"&&c==="*"){i=!0,t+="/*",o+=2;continue}if(s&&a===`
|
|
7
|
+
`){s=!1,t+=a,o++;continue}if(i&&a==="*"&&c==="/"){i=!1,t+="*/",o+=2;continue}if(s||i){t+=a,o++;continue}a==="("||a==="{"||a==="["?(r++,t+=a):a===")"||a==="}"||a==="]"?(r--,t+=a):a===","&&r===0?(n.push(t),t=""):t+=a,o++}return t.trim()&&n.push(t),n}function Me(e,n,t){let r=ye(e,{originalSource:e,requiredParams:n.requiredParams,unsafeFunctions:n.unsafeFunctions,safeFunctions:n.safeFunctions}).source,s=ge(r),i=!1,o=new Set,a=l=>{if(t&&/^\w+$/.test(l)){if(o.has(l))throw new Error(`Duplicate parameter name '${l}'`);o.add(l)}};return s.map(l=>{let p=l.trim();if(!p)return l;if(t&&p.startsWith("{")&&p.endsWith("}")){let m=p.slice(1,-1);return`{ ${Je(m,n)} }`}if(t&&p.startsWith("[")&&p.endsWith("]")){let m=p.slice(1,-1);return`[ ${Je(m,n)} ]`}if(p.startsWith("...")){let m=ze(p);return m!==-1?p.slice(0,m).trim():l}let d=p.match(/^(\w+)\s*\?\s*:\s*(.+)$/);if(d){let[,m,y]=d;return a(m),i=!0,`${m} = ${y}`}if(!Wn(p)){let m=p.match(/^(\w+)\s*=/);return m&&a(m[1]),i=!0,l}let u=ze(p);if(u!==-1){let m=p.slice(0,u).trim(),y=p.slice(u+1).trim();return a(m),i&&t&&/^\w+$/.test(m),t&&/^\w+$/.test(m)&&n.requiredParams.add(m),`${m} = ${y}`}return l}).join(",")}function Je(e,n){return ge(e).map(s=>{let i=s.trim();if(!i)return s;let o=i.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if(o){let[,l,p]=o;n.requiredParams.add(l);let d=de(p);return`${l} = ${d}`}let a=i.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(a){let[,l,p]=a;n.requiredParams.add(l);let d=me(p);return`${l} = ${d}`}let c=i.match(/^(\w+)\s*:\s*([\s\S]+)$/);if(c){let[,l,p]=c;return n.requiredParams.add(l),`${l} = ${p}`}return s}).join(", ")}function de(e){let n=e.slice(1,-1).trim();return`{ ${ge(n).map(s=>{let i=s.trim();if(!i)return s;let o=i.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if(o){let[,d,u]=o;return`${d}: ${de(u)}`}let a=i.match(/^(\w+)\s*=\s*(\{[\s\S]*\})$/);if(a){let[,d,u]=a;return`${d}: ${de(u)}`}let c=i.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(c){let[,d,u]=c;return`${d}: ${me(u)}`}let l=i.match(/^(\w+)\s*=\s*(\[[\s\S]*\])$/);if(l){let[,d,u]=l;return`${d}: ${me(u)}`}let p=i.match(/^(\w+)\s*=\s*([\s\S]+)$/);if(p){let[,d,u]=p;return`${d}: ${u}`}return s}).join(", ")} }`}function me(e){let n=e.slice(1,-1).trim();return`[ ${ge(n).map(s=>{let i=s.trim();return i?i.startsWith("{")&&i.endsWith("}")?de(i):i.startsWith("[")&&i.endsWith("]")?me(i):s:s}).join(", ")} ]`}function Wn(e){let n=0,t=!1,r=!1,s=!1,i="";for(let o=0;o<e.length;o++){let a=e[o];if(!s&&(a==="'"||a==='"'||a==="`")){s=!0,i=a;continue}if(s){a===i&&e[o-1]!=="\\"&&(s=!1);continue}a==="("||a==="{"||a==="["?n++:a===")"||a==="}"||a==="]"?n--:n===0&&(a===":"&&(t=!0),a==="="&&e[o+1]!==">"&&(r=!0))}return t&&!r}function ze(e){let n=0,t=!1,r="";for(let s=0;s<e.length;s++){let i=e[s];if(!t&&(i==="'"||i==='"'||i==="`")){t=!0,r=i;continue}if(t){i===r&&e[s-1]!=="\\"&&(t=!1);continue}if(i==="("||i==="{"||i==="[")n++;else if(i===")"||i==="}"||i==="]")n--;else if(n===0&&i===":")return s}return-1}function Vn(e,n){let t=e.match(n);if(!t)return null;let r=t.index+t[0].length-1,s=1,i=r+1;for(;i<e.length&&s>0;)e[i]==="{"?s++:e[i]==="}"&&s--,i++;if(s!==0)return null;let o=e.slice(r,i),a=[t[0].slice(0,-1)+o,o];return a.index=t.index,a}function Xe(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\btry\s*\{/);if(r){let i=t+r[0].length-1+1,o=1,a=i;for(;a<e.length&&o>0;){let l=e[a];l==="{"?o++:l==="}"&&o--,a++}if(o!==0){n+=e[t],t++;continue}if(e.slice(a).match(/^\s*(catch|finally)\b/))n+=e.slice(t,a),t=a;else{let l=e.slice(i,a-1);n+=`try {${l}} 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 Qe(e){let n=[],t="",r=0,s=0;for(;r<e.length;){let i=e.slice(r).match(/^\bwasm\s*\{/);if(i){let o=r,a=r+i[0].length,c=1,l=a;for(;l<e.length&&c>0;){let $=e[l];$==="{"?c++:$==="}"&&c--,l++}if(c!==0){t+=e[r],r++;continue}let p=e.slice(a,l-1),d,u=l,m=e.slice(l).match(/^\s*fallback\s*\{/);if(m){let $=l+m[0].length;c=1;let T=$;for(;T<e.length&&c>0;){let v=e[T];v==="{"?c++:v==="}"&&c--,T++}c===0&&(d=e.slice($,T-1),u=T)}let b=zn(p).map($=>{let T=Zn(e,o,$);return T?`${$}: ${T}`:$}),h={id:`__tjs_wasm_${s}`,body:p,fallback:d,captures:b,start:o,end:u};n.push(h);let S=d??p,x=b.map($=>$.split(":")[0].trim()),g=x.length>0?x.join(", "):"",E=x.length>0?`globalThis.${h.id}(${g})`:`globalThis.${h.id}()`,A=`(globalThis.${h.id} ? ${E} : (() => {${S}})())`;t+=A,r=u,s++}else t+=e[r],r++}return{source:t,blocks:n}}function Jn(e){return e.startsWith("f32x4_")||e.startsWith("v128_")}function zn(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 i=/(?<!\.)(\b[a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,o=new Set;for(;(s=i.exec(n))!==null;)o.add(s[1]);for(let u of t){if(!o.has(u))continue;let m=new RegExp(`(?<!\\.)\\b${u}\\b`,"g"),y=new RegExp(`\\.${u}\\b`,"g"),b=n.match(m)?.length||0,h=n.match(y)?.length||0;b<=h&&o.delete(u)}let a=new Set,c=/\b(?:let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;for(;(s=c.exec(n))!==null;)a.add(s[1]);let l=/\bfor\s*\(\s*(?:let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;for(;(s=l.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"]),d=[];for(let u of o)!a.has(u)&&!p.has(u)&&!Jn(u)&&d.push(u);return d.sort()}function Zn(e,n,t){let r=e.slice(0,n),s=/function\s+\w+\s*\(([^)]*)\)\s*(?:->.*?)?\s*\{[^}]*$/,i=r.match(s);if(!i){let o=/(?:const|let|var)?\s*\w+\s*=\s*(?:async\s*)?\(([^)]*)\)\s*(?:=>|->)?\s*\{[^}]*$/,a=r.match(o);return a?Ge(a[1],t):void 0}return Ge(i[1],t)}function Ge(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 i=r.match(new RegExp(`^${n}\\s*=\\s*(Float32Array|Float64Array|Int32Array|Uint8Array|Int8Array|Int16Array|Uint16Array|Uint32Array)`));if(i)return i[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(`
|
|
8
|
+
`),i=[],o=!1;for(let a=0;a<s.length;a++){let c=s[a],l=a>0?s[a-1]:"";if(o){i.push(c),c.includes("*/")&&(o=!1);continue}let p=c.indexOf("/*"),d=c.indexOf("*/");if(p!==-1&&(d===-1||d<p)){o=!0,i.push(c);continue}if(a>0&&n.test(c)){let u=l.replace(/\/\/.*$/,"").replace(/\/\*.*\*\/\s*$/,"");if(!t.test(u)&&!r.test(u)){let m=c.match(/^(\s*)/),y=m?m[1]:"",b=c.slice(y.length);i.push(y+";"+b);continue}}i.push(c)}return i.join(`
|
|
9
|
+
`)}function nt(e){e=e.replace(/\btypeof\s+([a-zA-Z_$][\w$.]*(?:\?\.[\w$]+)*)/g,"TypeOf($1)");let n=[],t=0,r="normal",s=[];for(;t<e.length;){let o=e[t],a=e[t+1];switch(r){case"single-string":if(o==="\\"&&t+1<e.length){t+=2;continue}o==="'"&&(r="normal"),t++;continue;case"double-string":if(o==="\\"&&t+1<e.length){t+=2;continue}o==='"'&&(r="normal"),t++;continue;case"template-string":if(o==="\\"&&t+1<e.length){t+=2;continue}if(o==="$"&&a==="{"){t+=2,s.push(1),r="normal";continue}o==="`"&&(r="normal"),t++;continue;case"line-comment":o===`
|
|
10
|
+
`&&(r="normal"),t++;continue;case"block-comment":if(o==="*"&&a==="/"){t+=2,r="normal";continue}t++;continue;case"regex":if(o==="\\"&&t+1<e.length){t+=2;continue}if(o==="["){for(t++;t<e.length&&e[t]!=="]";)e[t]==="\\"&&t+1<e.length?t+=2:t++;t<e.length&&t++;continue}if(o==="/"){for(t++;t<e.length&&/[gimsuy]/.test(e[t]);)t++;r="normal";continue}t++;continue;case"normal":if(s.length>0){if(o==="{")s[s.length-1]++;else if(o==="}"&&(s[s.length-1]--,s[s.length-1]===0)){s.pop(),t++,r="template-string";continue}}if(o==="'"){t++,r="single-string";continue}if(o==='"'){t++,r="double-string";continue}if(o==="`"){t++,r="template-string";continue}if(o==="/"&&a==="/"){t+=2,r="line-comment";continue}if(o==="/"&&a==="*"){t+=2,r="block-comment";continue}if(o==="/"){let c=t-1;for(;c>=0&&/\s/.test(e[c]);)c--;let l=c>=0?e[c]:"";if(!l||/[=(!,;:{[&|?+\-*%<>~^]/.test(l)||c>=5&&/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)$/.test(e.slice(Math.max(0,c-10),c+1))){t++,r="regex";continue}}if(o==="="&&a==="="&&e[t+2]!=="="&&e[t-1]!=="!"){n.push({pos:t,op:"=="}),t+=2;continue}if(o==="!"&&a==="="&&e[t+2]!=="="){n.push({pos:t,op:"!="}),t+=2;continue}break}t++}if(n.length===0)return e;let i=e;for(let o=n.length-1;o>=0;o--){let{pos:a,op:c}=n[o],l=c==="=="?"Eq":"NotEq",p=Gn(i,a),d=Hn(i,a+2),u=i.slice(p,a).trim(),m=i.slice(a+2,d).trim();if(u&&m){let y=i.slice(0,p),b=i.slice(d),S=/[a-zA-Z0-9_$]$/.test(y)?" ":"";i=`${y}${S}${l}(${u}, ${m})${b}`}}return i}function Gn(e,n){let t=n-1;for(;t>=0&&/\s/.test(e[t]);)t--;if(t<0)return 0;let r=0,s=!1,i="";for(;t>=0;){let o=e[t],a=t>0?e[t-1]:"";if(s){o===i&&a!=="\\"&&(s=!1),t--;continue}if((o==='"'||o==="'"||o==="`")&&a!=="\\"){s=!0,i=o,t--;continue}if(o===")"||o==="]"||o==="}"){r++,t--;continue}if(o==="("||o==="["){if(r>0){r--,t--;continue}return t+1}if(o==="{"){if(r>0){r--,t--;continue}return t+1}if(r>0){t--;continue}if(o===";")return t+1;if(/[a-z]/.test(o)){let c=t+1,l=t;for(;l>0&&/[a-z]/i.test(e[l-1]);)l--;let p=e.slice(l,c),d=l>0?e[l-1]:"";if(!/[a-zA-Z0-9_$]/.test(d)){if(["return","throw","case","typeof","void","delete","await","yield"].includes(p))return c;if(p==="new")return l}}if(o===">"&&a==="="||o==="="&&a!=="="&&a!=="!"&&a!=="<"&&a!==">"||o==="&"&&a==="&"||o==="|"&&a==="|"||o==="?"||o===":"||o===",")return t+1;t--}return 0}function Hn(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,i="";for(;t<e.length;){let o=e[t],a=t+1<e.length?e[t+1]:"";if(s){o===i&&e[t-1]!=="\\"&&(s=!1),t++;continue}if((o==='"'||o==="'"||o==="`")&&e[t-1]!=="\\"){s=!0,i=o,t++;continue}if(o==="("||o==="["||o==="{"){r++,t++;continue}if(o===")"||o==="]"||o==="}"){if(r>0){r--,t++;continue}return t}if(r>0){t++;continue}if(o===";"||o==="&"&&a==="&"||o==="|"&&a==="|"||o==="?"||o===":"||o===","||(o==="="||o==="!")&&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],i=t+r[0].length,o=s,a=!1,c=e.slice(i).match(/^(['"`])([^]*?)\1\s*/);if(c){let u=i+c[0].length,m=e[u],y=m===void 0||u>=e.length||m!=="="&&m!=="{";if(m==="="||m==="{")o=c[2],a=!0,i=u;else if(y){let b=c[0].trim(),h=c[0].slice(b.length);n+=`const ${s} = Type('${s}', ${b})${h}`,t=u;continue}}let l,p=i,d=e.slice(i).match(/^=\s*/);if(d){i+=d[0].length;let u=e.slice(i).match(/^(\+?\d+(?:\.\d+)?|['"`][^'"`]*['"`]|\{[^}]*\}|\[[^\]]*\]|true|false|null)/);if(u){l=u[0],i+=u[0].length,p=i;let m=e.slice(i).match(/^\s*/);m&&(i+=m[0].length)}}if(e[i]==="{"){let u=i+1,m=1,y=u;for(;y<e.length&&m>0;){let A=e[y];A==="{"?m++:A==="}"&&m--,y++}if(m!==0){n+=e[t],t++;continue}let b=e.slice(u,y-1).trim(),h=y,S=b.match(/description\s*:\s*(['"`])([^]*?)\1/);S&&!a&&(o=S[2]);let x,g=b.match(/example\s*:\s*/);if(g){let A=g.index+g[0].length,$=Ze(b,A);$&&(x=$.value.trim())}let E=b.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/);if(E&&x){let A=E[1].trim(),$=E[2].trim(),T=l?`, ${l}`:"";n+=`const ${s} = Type('${o}', (${A}) => { if (!globalThis.__tjs?.validate(${A}, globalThis.__tjs?.infer(${x}))) return false; ${$} }, ${x}${T})`}else if(E){let A=E[1].trim(),$=E[2].trim(),T=l?`, undefined, ${l}`:"";n+=`const ${s} = Type('${o}', (${A}) => { ${$} }${T})`}else if(x){let A=l?`, ${l}`:"";n+=`const ${s} = Type('${o}', undefined, ${x}${A})`}else l?n+=`const ${s} = Type('${o}', ${l})`:n+=`const ${s} = Type('${o}')`;t=h;continue}else if(l){n+=`const ${s} = Type('${o}', ${l})`,t=p;continue}else if(!c){let u=e.slice(i).match(/^(['"`][^]*?['"`]|\+?\d+(?:\.\d+)?|true|false|null|\{[^]*?\}|\[[^]*?\])/);if(u){let m=u[0];n+=`const ${s} = Type('${s}', ${m})`,t=i+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],i=r[2],o=t+r[0].length;if(e[o]==="{"){let a=1,c=o+1;for(;c<e.length&&a>0;)e[c]==="{"?a++:e[c]==="}"&&a--,c++;if(a===0){let l=e.slice(o+1,c-1).trim(),p=Vn(l,/params\s*:\s*\{/),d=l.match(/returns\s*:\s*(.+?)(?:\n|$)/),u=l.match(/returnContract\s*:\s*['"](\w+)['"]/),m=l.match(/description\s*:\s*(['"])([^]*?)\1/),y=[];p&&y.push(`params: ${p[1]}`),d&&y.push(`returns: ${d[1].trim()}`),u&&y.push(`returnContract: '${u[1]}'`);let b=m?m[2]:s;if(i){let h=i.split(",").map(x=>{let g=x.trim().split("=").map(E=>E.trim());if(g.length===2){let E=g[1]==="any"||g[1]==="undefined"?"null":g[1];return`['${g[0]}', ${E}]`}return`'${g[0]}'`}),S=i.split(",").map(x=>x.trim().split("=")[0].trim());n+=`const ${s} = FunctionPredicate('${b}', [${h.join(", ")}], (${S.join(", ")}) => ({ ${y.join(", ")} }))`}else n+=`const ${s} = FunctionPredicate('${b}', { ${y.join(", ")} })`;t=c;continue}}if(e[o]==="("){let a=1,c=o+1;for(;c<e.length&&a>0;)e[c]==="("?a++:e[c]===")"&&a--,c++;if(a===0){let l=e.slice(o+1,c-1).trim(),p=l.indexOf(",");if(p!==-1){let d=l.slice(0,p).trim(),u=l.slice(p+1).trim();n+=`const ${s} = FunctionPredicate(${u}, ${d})`}else n+=`const ${s} = FunctionPredicate('${s}', ${l})`;t=c;continue}}}n+=e[t],t++}return n}function ot(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],i=r[2],a=t+r[0].length-1+1,c=1,l=a;for(;l<e.length&&c>0;){let x=e[l];x==="{"?c++:x==="}"&&c--,l++}if(c!==0){n+=e[t],t++;continue}let p=e.slice(a,l-1).trim(),d=l,u=i.split(",").map(x=>{let g=x.trim().split("=").map(E=>E.trim());if(g.length===2){let E=g[1]==="any"||g[1]==="undefined"?"null":g[1];return`['${g[0]}', ${E}]`}return`'${g[0]}'`}),m=p,y=m.search(/\bdeclaration\s*\{/);if(y!==-1){let x=m.indexOf("{",y),g=1,E=x+1;for(;E<m.length&&g>0;)m[E]==="{"?g++:m[E]==="}"&&g--,E++;m=m.slice(0,y)+m.slice(E)}let b=m.match(/description\s*:\s*(['"`])([^]*?)\1/),h=m.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/),S=b?b[2]:s;if(h){let x=h[1].trim().split(",").map(T=>T.trim()),g=h[2].trim(),E=x[0]||"x",A=x.slice(1),$=A.map(T=>`check${T}`);A.forEach((T,v)=>{g=g.replace(new RegExp(`\\b${T}\\s*\\(`,"g"),`${$[v]}(`)}),n+=`const ${s} = Generic([${u.join(", ")}], (${E}, ${$.join(", ")}) => { ${g} }, '${S}')`}else n+=`const ${s} = Generic([${u.join(", ")}], () => true, '${S}')`;t=d;continue}n+=e[t],t++}return n}function it(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],i=r[3],o=t+r[0].length;if(e[o]==="{"){let a=o+1,c=1,l=a;for(;l<e.length&&c>0;){let m=e[l];m==="{"?c++:m==="}"&&c--,l++}if(c!==0){n+=e[t],t++;continue}let p=e.slice(a,l-1).trim(),d=l,u=He(p);n+=`const ${s} = Union('${i}', [${u.join(", ")}])`,t=d;continue}else{let a=e.indexOf(`
|
|
11
|
+
`,o);a===-1&&(a=e.length);let c=e.slice(o,a).trim();if(c){let l=He(c);n+=`const ${s} = Union('${i}', [${l.join(", ")}])`,t=a;continue}}}n+=e[t],t++}return n}function He(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],i=r[3],a=t+r[0].length-1+1,c=1,l=a;for(;l<e.length&&c>0;){let y=e[l];y==="{"?c++:y==="}"&&c--,l++}if(c!==0){n+=e[t],t++;continue}let p=e.slice(a,l-1).trim(),d=l,m=Kn(p).map(([y,b])=>`${y}: ${b}`).join(", ");n+=`const ${s} = Enum('${i}', { ${m} })`,t=d;continue}n+=e[t],t++}return n}function Kn(e){let n=[],t=0,r=e.split(/[\n,]/).map(s=>s.trim()).filter(s=>s&&!s.startsWith("//"));for(let s of r){let i=s.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:=\s*(.+))?$/);if(i){let o=i[1],a=i[2]?.trim();if(a!==void 0){n.push([o,a]);let c=Number(a);isNaN(c)||(t=c+1)}else n.push([o,String(t)]),t++}}return n}function lt(e){let n=new Map,t="",r=0;for(;r<e.length;){let s=e.slice(r),i=s.match(/^(\s*)extend\s+([A-Z]\w*)\s*\{/);if(!i){if(r===0||e[r-1]===`
|
|
12
|
+
`||e[r-1]===";"||e[r-1]==="}"){let g=s.match(/^(\s*)extend\s+([A-Z]\w*)\s*\{/)}t+=e[r],r++;continue}let o=i[1],a=i[2],c=r+i[0].length-1,l=se(e,c),p=e.slice(c+1,l-1).trim(),d=[],u=0,m=e.slice(c+1,l-1);for(;u<m.length;){let g=m.slice(u).match(/^(\s*)(async\s+)?(\w+)\s*\(/);if(!g){u++;continue}let E=g[1],A=!!g[2],$=g[3],T=u+g[0].length-1,v=1,M=T+1;for(;M<m.length&&v>0;)m[M]==="("&&v++,m[M]===")"&&v--,M++;let k=m.slice(T+1,M-1),C=M;for(;C<m.length&&/\s/.test(m[C]);)C++;if(m[C]==="="&&m[C+1]===">"){let Z=re(e,c+1+u);throw new F(`Arrow functions are not allowed in extend blocks (method '${$}' in extend ${a}). Use regular function syntax instead, as extension methods need 'this' binding.`,Z)}if(m[C]!=="{"){u++;continue}let N=se(m,C),O=m.slice(u,N).trim(),z=k.split(",").map(Z=>Z.trim()).filter(Z=>Z.length>0).map(Z=>{let Se=Z.match(/^(\w+)\s*:\s*(.+)$/);return Se?`${Se[1]} = ${Se[2]}`:Z}).join(", "),H=A?"async ":"",Nt=m.slice(C+1,N-1);d.push({name:$,isAsync:A,fullText:`${$}: ${H}function(${z}) {${Nt}}`}),u=N}let y=!n.has(a);y&&n.set(a,new Set);let b=n.get(a);for(let x of d)b.add(x.name);let h=d.map(x=>` ${x.fullText}`).join(`,
|
|
13
|
+
`),S;y?S=`${o}const __ext_${a} = {
|
|
14
|
+
${h}
|
|
15
|
+
${o}}
|
|
16
|
+
`:S=`${o}Object.assign(__ext_${a}, {
|
|
17
|
+
${h}
|
|
18
|
+
${o}})
|
|
19
|
+
`;for(let x of d)S+=`${o}if (__tjs?.registerExtension) { __tjs.registerExtension('${a}', '${x.name}', __ext_${a}.${x.name}) }
|
|
20
|
+
`;t+=S,r=l}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,i]of n)for(let o of i)t.has(o)||t.set(o,[]),t.get(o).push(s);let r=e;for(let[s,i]of t){if(!i.includes("String"))continue;let o=new RegExp(`('(?:[^'\\\\]|\\\\.)*')\\.(${s})\\((\\))?`,"g");r=r.replace(o,(l,p,d,u)=>u?`__ext_String.${d}.call(${p})`:`__ext_String.${d}.call(${p}, `);let a=new RegExp(`("(?:[^"\\\\]|\\\\.)*")\\.(${s})\\((\\))?`,"g");r=r.replace(a,(l,p,d,u)=>u?`__ext_String.${d}.call(${p})`:`__ext_String.${d}.call(${p}, `);let c=new RegExp("(`(?:[^`\\\\]|\\\\.)*`)\\."+s+"\\((\\))?","g");r=r.replace(c,(l,p,d)=>d?`__ext_String.${s}.call(${p})`:`__ext_String.${s}.call(${p}, `)}for(let[s,i]of t){if(!i.includes("Array"))continue;let o=`].${s}(`,a=0,c;for(;(c=r.indexOf(o,a))!==-1;){let l=1,p=c-1,d=!1;for(;p>=0&&l>0;){let u=r[p];d?u===d&&(p===0||r[p-1]!=="\\")&&(d=!1):(u==="]"&&l++,u==="["&&l--,(u==="'"||u==='"'||u==="`")&&(d=u)),p--}if(l===0){let u=r.slice(p+1,c+1),m=r.slice(0,p+1),y=r.slice(c+o.length);y[0]===")"?r=`${m}__ext_Array.${s}.call(${u})${y.slice(1)}`:r=`${m}__ext_Array.${s}.call(${u}, ${y}`}a=c+1}}for(let[s,i]of t){if(!i.includes("Number"))continue;let o=new RegExp(`(\\d+(?:\\.\\d+)?)\\.(${s})\\((\\))?`,"g");r=r.replace(o,(a,c,l,p)=>p?`__ext_Number.${l}.call(${c})`:`__ext_Number.${l}.call(${c}, `)}return r}function re(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 he(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 ke(e,n){let t=[],r=0,s="",i=!1;for(let a=0;a<e.length;a++){let c=e[a];if(!i&&(c==="'"||c==='"'||c==="`")){i=c,s+=c;continue}if(i){if(s+=c,c==="\\"){a++,a<e.length&&(s+=e[a]);continue}c===i&&(i=!1);continue}if(c==="("||c==="["||c==="{"){r++,s+=c;continue}if(c===")"||c==="]"||c==="}"){r--,s+=c;continue}if(c===","&&r===0){let l=Ke(s.trim(),n);l&&t.push(l),s="";continue}s+=c}let o=s.trim();if(o){let a=Ke(o,n);a&&t.push(a)}return t}function Ke(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(),i=t.slice(r+1).trim();return{name:s,defaultValue:i,required:n.has(s)}}function se(e,n){let t=1,r=n+1,s=!1,i=!1,o=!1;for(;r<e.length&&t>0;){let a=e[r],c=r+1<e.length?e[r+1]:"";if(i){a===`
|
|
22
|
+
`&&(i=!1),r++;continue}if(o){if(a==="*"&&c==="/"){o=!1,r+=2;continue}r++;continue}if(s){if(a==="\\"){r+=2;continue}a===s&&(s=!1),r++;continue}if(a==="/"&&c==="/"){i=!0,r+=2;continue}if(a==="/"&&c==="*"){o=!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,i,o=[];for(;(i=r.exec(e))!==null;){let d=!!i[1],u=!!i[2],m=i[3],y=i.index,b=y,S=i[0].indexOf("function");S>=0&&(b=y+S),o.push({name:m,fullMatchStart:y,funcKeywordStart:b,exported:d,isAsync:u})}for(let d of o)s.has(d.name)||s.set(d.name,[]);let a=new Map;for(let d of o)a.set(d.name,(a.get(d.name)||0)+1);let c=new Set;for(let[d,u]of a)u>1&&c.add(d);if(c.size===0)return{source:e,polymorphicNames:t};for(let d of o){if(!c.has(d.name))continue;let u=e.indexOf("(",d.funcKeywordStart);if(u===-1)continue;let m=1,y=u+1;for(;y<e.length&&m>0;)e[y]==="("&&m++,e[y]===")"&&m--,y++;let b=y-1,h=e.slice(u+1,b),S=y;for(;S<e.length&&e[S]!=="{";)S++;if(S>=e.length)continue;let x=se(e,S),g=d.fullMatchStart;for(;g>0&&e[g-1]===" ";)g--;let E=s.get(d.name),A=ke(h,n);if(h.includes("...")){let T=re(e,d.funcKeywordStart);throw new F(`Rest parameters are not supported in polymorphic function '${d.name}'. Use separate function names instead.`,T)}E.push({index:E.length+1,start:g,end:x,text:e.slice(g,x),exported:d.exported,isAsync:d.isAsync,params:A})}for(let[d,u]of s){if(u.length<2)continue;let m=u.filter(y=>y.isAsync).length;if(m>0&&m<u.length){let y=re(e,u[0].start);throw new F(`Polymorphic function '${d}': all variants must be either sync or async, not mixed.`,y)}for(let y=0;y<u.length;y++)for(let b=y+1;b<u.length;b++){let h=u[y],S=u[b];if(h.params.length!==S.params.length)continue;let x=!0;for(let g=0;g<h.params.length;g++){let E=h.params[g].defaultValue?he(h.params[g].defaultValue):"any",A=S.params[g].defaultValue?he(S.params[g].defaultValue):"any";if(E!==A){x=!1;break}}if(x){let g=re(e,S.start);throw new F(`Polymorphic function '${d}': variants ${y+1} and ${b+1} have ambiguous signatures (same parameter types at every position). Overloads must differ by arity or parameter types.`,g)}}}let l=[];for(let[d,u]of s)if(!(u.length<2))for(let m of u)l.push({name:d,variant:m});l.sort((d,u)=>u.variant.start-d.variant.start);let p=e;for(let{name:d,variant:u}of l){let m=u.isAsync?"async ":"",y=u.text.replace(new RegExp(`(?:export\\s+)?${m?m.replace(/\s+$/,"\\s+"):""}function\\s+${d}\\s*\\(`),`${m}function ${d}$$${u.index}(`);p=p.slice(0,u.start)+y+p.slice(u.end)}for(let[d,u]of s){if(u.length<2)continue;t.add(d);let m=u[0].isAsync,y=u.some(E=>E.exported),b=m?"async ":"",h=y?"export ":"",S=[...u].sort((E,A)=>{if(E.params.length!==A.params.length)return 0;let $=0,T=0;for(let v of E.params){let M=v.defaultValue?he(v.defaultValue):"any";M==="non-negative-integer"?$+=3:M==="integer"?$+=2:M!=="any"&&($+=1)}for(let v of A.params){let M=v.defaultValue?he(v.defaultValue):"any";M==="non-negative-integer"?T+=3:M==="integer"?T+=2:M!=="any"&&(T+=1)}return T-$}),x=[];for(let E of S){let A=[`__args.length === ${E.params.length}`],$=[];for(let T=0;T<E.params.length;T++){let v=E.params[T];if($.push(`__args[${T}]`),v.defaultValue){let M=ut(`__args[${T}]`,v.defaultValue);M!=="true"&&A.push(M)}}x.push(` if (${A.join(" && ")}) return ${d}$${E.index}(${$.join(", ")})`)}let g=`
|
|
23
|
+
${h}${b}function ${d}(...__args) {
|
|
24
|
+
${x.join(`
|
|
25
|
+
`)}
|
|
26
|
+
return __tjs.typeError('${d}', 'no matching overload', __args)
|
|
27
|
+
}
|
|
28
|
+
`;p+=g}return{source:p,polymorphicNames:t}}function pt(e){return e.replace(/(?<=^|[;\n{])\s*([A-Z][a-zA-Z0-9_]*)\s*=(?!=)/gm,(n,t)=>n.replace(t,`const ${t}`))}function dt(e,n=!1){let t=[],r=[],s="",i=0;for(;i<e.length;){let o=e.slice(i).match(/^\btest\s+/);if(o){let a=i,c=i+o[0].length,l,p=e.slice(c).match(/^(['"`])([^]*?)\1\s*/);if(p&&(l=p[2],c+=p[0].length),e[c]==="{"){let d=c+1,u=1,m=d;for(;m<e.length&&u>0;){let y=e[m];y==="{"?u++:y==="}"&&u--,m++}if(u===0){let y=e.slice(d,m-1).trim(),b=m,h=(e.slice(0,a).match(/\n/g)||[]).length+1;if(t.push({description:l,body:y,start:a,end:b,line:h}),!n)try{new Function(y)()}catch(g){let E=l||`test at line ${h}`;r.push(`Test failed: ${E} (line ${h})
|
|
29
|
+
${g.message||g}`)}let x=(e.slice(a,b).match(/\n/g)||[]).length;s+=`
|
|
30
|
+
`.repeat(x),i=b;continue}}}s+=e[i],i++}return{source:s,tests:t,errors:r}}function mt(e,n){let t=new Set,r=/\bclass\s+(\w+)(\s+extends\s+\w+)?\s*\{/g,s,i=[];for(;(s=r.exec(e))!==null;){let a=s[1],c=s[2]?.trim()||"",l=s.index+s[0].length-1,p=se(e,l),d=e.slice(l,p);i.push({className:a,extendsClause:c,bodyStart:l,bodyEnd:p,body:d})}let o=e;for(let a=i.length-1;a>=0;a--){let{className:c,extendsClause:l,bodyStart:p,bodyEnd:d,body:u}=i[a],m=/\bconstructor\s*\(/g,y,b=[];for(;(y=m.exec(u))!==null;)b.push(y.index);if(b.length<2)continue;t.add(c);let h=[];for(let T=0;T<b.length;T++){let v=b[T],M=u.indexOf("(",v),k=1,C=M+1;for(;C<u.length&&k>0;)u[C]==="("&&k++,u[C]===")"&&k--,C++;let N=u.slice(M+1,C-1),O=C;for(;O<u.length&&u[O]!=="{";)O++;let z=se(u,O),H=u.slice(O+1,z-1);h.push({index:T+1,paramStr:N,bodyText:H,fullStart:v,fullEnd:z})}let S=u.slice(0,h[0].fullEnd),x=h[h.length-1].fullEnd;S+=u.slice(x);let g=u;for(let T=h.length-1;T>=1;T--){let v=h[T],M=v.fullStart;for(;M>0&&g[M-1]===" ";)M--;M>0&&g[M-1]===`
|
|
31
|
+
`&&M--,g=g.slice(0,M)+g.slice(v.fullEnd)}let E="";for(let T=1;T<h.length;T++){let v=h[T],M=ke(v.paramStr,n);if(v.paramStr.includes("...")){let C=re(e,p+v.fullStart);throw new F(`Rest parameters are not supported in polymorphic constructors for '${c}'.`,C)}E+=`
|
|
32
|
+
function ${c}$ctor$${v.index}(${v.paramStr}) {`,E+=`
|
|
33
|
+
const __obj = Object.create(${c}.prototype)`,E+=`
|
|
34
|
+
;(function() {${v.bodyText}}).call(__obj)`,E+=`
|
|
35
|
+
return __obj`,E+=`
|
|
36
|
+
}
|
|
37
|
+
`}let A=[];for(let T=0;T<h.length;T++){let v=h[T],M=ke(v.paramStr,n),k=[`a.length === ${M.length}`];for(let C=0;C<M.length;C++){let N=M[C];if(N.defaultValue){let O=ut(`a[${C}]`,N.defaultValue);O!=="true"&&k.push(O)}}if(T===0)A.push(` if (${k.join(" && ")}) return Reflect.construct(t, a)`);else{let C=M.map((N,O)=>`a[${O}]`).join(", ");A.push(` if (${k.join(" && ")}) return ${c}$ctor$${v.index}(${C})`)}}E+=`
|
|
38
|
+
function ${c}$dispatch(t, a) {
|
|
39
|
+
`,E+=A.join(`
|
|
40
|
+
`)+`
|
|
41
|
+
`,E+=` return __tjs.typeError('${c}', 'no matching constructor', a)
|
|
42
|
+
`,E+=`}
|
|
43
|
+
`,o=o.slice(0,p)+g+o.slice(d);let $=p+g.length;o=o.slice(0,$)+E+o.slice($)}return{source:o,polyCtorClasses:t}}function yt(e,n=new Set){let t=/\bclass\s+(\w+)(\s+extends\s+\w+)?\s*\{/g,r="",s=0,i;for(;(i=t.exec(e))!==null;){let o=i[1],a=i[2]||"",c=i.index,l=c+i[0].length-1,p=1,d=l+1;for(;d<e.length&&p>0;){let u=e[d];u==="{"?p++:u==="}"&&p--,d++}if(p===0){let u=d,m=e.slice(l,u);r+=e.slice(s,c),r+=`let ${o} = class ${o}${a} ${m}; `,n.has(o)?r+=`${o} = new Proxy(${o}, { apply(t, _, a) { return ${o}$dispatch(t, a) }, construct(t, a) { return ${o}$dispatch(t, a) } });`:r+=`${o} = new Proxy(${o}, { apply(t, _, a) { return Reflect.construct(t, a) } });`,s=u}}return r+=e.slice(s),r}function gt(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 ht(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 i of n){if(new RegExp(`\\b${i}\\s*(?:\\.[\\w]+|\\[[^\\]]+\\])\\s*(?:=(?!=)|\\+\\+|--|\\+=|-=|\\*=|\\/=|%=|&&=|\\|\\|=|\\?\\?=|<<=|>>=|>>>=|\\^=|&=|\\|=)`,"g").test(s))throw new Error(`Cannot mutate immutable binding '${i}'. const! bindings are read-only at compile time.`);if(new RegExp(`(?:\\+\\+|--)\\s*${i}\\s*(?:\\.[\\w]+|\\[[^\\]]+\\])`,"g").test(s))throw new Error(`Cannot mutate immutable binding '${i}'. const! bindings are read-only at compile time.`);if(new RegExp(`\\bdelete\\s+${i}\\s*(?:\\.[\\w]+|\\[[^\\]]+\\])`,"g").test(s))throw new Error(`Cannot mutate immutable binding '${i}'. const! bindings are read-only at compile time.`);let l="push|pop|splice|shift|unshift|sort|reverse|fill|copyWithin|set";if(new RegExp(`\\b${i}\\s*\\.\\s*(?:${l})\\s*\\(`,"g").test(s))throw new Error(`Cannot call mutating method on immutable binding '${i}'. 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 i=e[t],o=e[t+1];if(r==="normal"){if(i==="/"&&o==="/"){r="line-comment",n+=i,t++;continue}if(i==="/"&&o==="*"){r="block-comment",n+=i,t++;continue}if(i==="'"){r="string-single",n+=i,t++;continue}if(i==='"'){r="string-double",n+=i,t++;continue}if(i==="`"){r="string-template",s++,n+=i,t++;continue}if(i==="!"&&o==="."&&t+2<e.length&&/[a-zA-Z_$]/.test(e[t+2])){let a=n.length,c=Yn(n);if(c<a){let l=n.slice(c);n=n.slice(0,c);let p=t+2;for(;p<e.length&&/[\w$]/.test(e[p]);)p++;let d=e.slice(t+2,p);n+=`__tjs.bang(${l},'${d}')`,t=p;continue}}n+=i,t++}else r==="line-comment"?(n+=i,i===`
|
|
44
|
+
`&&(r="normal"),t++):r==="block-comment"?(n+=i,i==="*"&&o==="/"?(n+=o,r="normal",t+=2):t++):r==="string-single"?(n+=i,i==="\\"?(n+=o||"",t+=2):(i==="'"&&(r="normal"),t++)):r==="string-double"?(n+=i,i==="\\"?(n+=o||"",t+=2):(i==='"'&&(r="normal"),t++)):r==="string-template"?(n+=i,i==="\\"?(n+=o||"",t+=2):i==="`"?(s--,r=s>0?"string-template":"normal",t++):i==="$"&&o==="{"?(n+=o,t+=2,r="normal"):t++):(n+=i,t++)}return n}function Yn(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=Ye(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=Ye(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 Ye(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 Xn(e,n={}){let t=e,r,s=new Set,i=new Set,o=new Set,c=/\/\*\s*tjs\s*<-\s*\S+\s*\*\//.test(e)||n.vmTarget,l=c?{tjsEquals:!1,tjsClass:!1,tjsDate:!1,tjsNoeval:!1,tjsStandard:!1,tjsSafeEval:!1,tjsNoVar:!1}:{tjsEquals:!0,tjsClass:!0,tjsDate:!0,tjsNoeval:!0,tjsStandard:!0,tjsSafeEval:!1,tjsNoVar:!0};c&&(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 d=/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*(TjsStrict|TjsCompat|TjsEquals|TjsClass|TjsDate|TjsNoeval|TjsNoVar|TjsStandard|TjsSafeEval)\b/,u;for(;u=e.match(d);){let A=u[2];A==="TjsStrict"?(l.tjsEquals=!0,l.tjsClass=!0,l.tjsDate=!0,l.tjsNoeval=!0,l.tjsNoVar=!0,l.tjsStandard=!0):A==="TjsCompat"?(l.tjsEquals=!1,l.tjsClass=!1,l.tjsDate=!1,l.tjsNoeval=!1,l.tjsNoVar=!1,l.tjsStandard=!1,l.tjsSafeEval=!1):A==="TjsEquals"?l.tjsEquals=!0:A==="TjsClass"?l.tjsClass=!0:A==="TjsDate"?l.tjsDate=!0:A==="TjsNoeval"?l.tjsNoeval=!0:A==="TjsNoVar"?l.tjsNoVar=!0:A==="TjsStandard"?l.tjsStandard=!0:A==="TjsSafeEval"&&(l.tjsSafeEval=!0),e=e.replace(new RegExp(`^(\\s*(?:\\/\\/[^\\n]*\\n|\\/\\*[\\s\\S]*?\\*\\/\\s*)*)\\s*${A}\\s*`),"$1")}l.tjsStandard&&(e=tt(e)),e=ht(e),e=St(e),e=et(e),l.tjsEquals&&!n.vmTarget&&(e=nt(e)),e=rt(e),e=ot(e),e=st(e),e=it(e),e=at(e),e=pt(e);let{source:m,returnType:y,returnSafety:b}=ye(e,{originalSource:t,requiredParams:s,unsafeFunctions:i,safeFunctions:o});e=m;let h=lt(e);e=h.source,e=Xe(e);let S=ft(e,s);e=S.source;let x=Qe(e);e=x.source;let g=dt(e,n.dangerouslySkipTests);e=g.source;let E=mt(e,s);e=E.source;for(let A of E.polyCtorClasses)i.add(`${A}$dispatch`);return l.tjsClass&&(e=yt(e,E.polyCtorClasses)),l.tjsDate&&(e=gt(e)),l.tjsNoeval&&(e=wt(e)),l.tjsNoVar&&(e=bt(e)),e=ct(e,h.extensions),{source:e,returnType:y,returnSafety:b,moduleSafety:r,tjsModes:l,originalSource:t,requiredParams:s,unsafeFunctions:i,safeFunctions:o,wasmBlocks:x.blocks,tests:g.tests,testErrors:g.errors,polymorphicNames:S.polymorphicNames,extensions:h.extensions}}function $t(e,n={}){let{filename:t="<source>",colonShorthand:r=!0,vmTarget:s=!1}=n,{source:i,returnType:o,returnSafety:a,moduleSafety:c,originalSource:l,requiredParams:p,unsafeFunctions:d,safeFunctions:u,wasmBlocks:m,tests:y,testErrors:b}=r?Xn(e,{vmTarget:s}):{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:[]};try{return{ast:Et.parse(i,{ecmaVersion:2022,sourceType:"module",locations:!0,allowReturnOutsideFunction:!1}),returnType:o,returnSafety:a,moduleSafety:c,originalSource:l,requiredParams:p,unsafeFunctions:d,safeFunctions:u,wasmBlocks:m,tests:y,testErrors:b}}catch(h){let S=h.loc||{line:1,column:0};throw new F(h.message.replace(/\s*\(\d+:\d+\)$/,""),S,l,t)}}function xt(e,n){for(let r of e.body){if(r.type==="ImportDeclaration")throw new F("Imports are not supported. All atoms must be registered with the VM.",r.loc?.start||{line:1,column:0},void 0,n);if(r.type==="ExportNamedDeclaration"||r.type==="ExportDefaultDeclaration")throw new F("Exports are not supported. The function is automatically exported.",r.loc?.start||{line:1,column:0},void 0,n);if(r.type==="ClassDeclaration")throw new F("Classes are not supported. Agent99 uses functional composition.",r.loc?.start||{line:1,column:0},void 0,n)}let t=e.body.filter(r=>r.type==="FunctionDeclaration");if(t.length===0)throw new F("Source must contain a function declaration",{line:1,column:0},void 0,n);if(t.length>1){let r=t[1];throw new F("Only a single function per agent is allowed",r.loc?.start||{line:1,column:0},void 0,n)}return t[0]}function Tt(e,n){let t={params:{}};if(!n.loc)return t;let r=e.substring(0,n.start),s=[...r.matchAll(/\/\*#([\s\S]*?)\*\//g)];if(s.length>0){let p=s[s.length-1],d=r.substring(p.index+p[0].length);if(/^(?:\s|\/\/[^\n]*)*$/.test(d)){let u=p[1],m=u.split(`
|
|
45
|
+
`),y=m.filter(b=>b.trim().length>0).reduce((b,h)=>{let S=h.match(/^(\s*)/)?.[1].length||0;return Math.min(b,S)},1/0);return y>0&&y<1/0&&(u=m.map(b=>b.slice(y)).join(`
|
|
46
|
+
`)),t.description=u.trim(),t}}let i=r.match(/\/\*\*[\s\S]*?\*\/\s*$/);if(!i)return t;let o=i[0],a=o.match(/\/\*\*\s*\n?\s*\*?\s*([^@\n][^\n]*)/m);a&&(t.description=a[1].trim());let c=/@param\s+(?:\{[^}]+\}\s+)?(\w+)\s*-?\s*(.*)/g,l;for(;(l=c.exec(o))!==null;)t.params[l[1]]=l[2].trim();return t}import{parseExpressionAt as Qn}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(o=>o!=null).map(o=>L(o));if(t.length===0)return{kind:"array",items:{kind:"any"}};let r=new Map;for(let o of t){let a=JSON.stringify(o);r.has(a)||r.set(a,o)}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),i=L(r);return i.kind==="null"?{...s,nullable:!0}:s.kind==="null"?{...i,nullable:!0}:{kind:"union",members:[s,i]}}return{kind:"any"}}case"Identifier":return e.name==="undefined"?{kind:"undefined"}:{kind:"any"};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 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,i=n?.has(s)??!1,o=L(r),a=W(r);return{name:s,type:o,required:i,default:i?null:a,example:a,loc:{start:e.start,end:e.end}}}if(e.type==="ObjectPattern"){let t=e.properties,r={},s={};for(let i of t)if(i.type==="Property"){let o=i.key.type==="Identifier"?i.key.name:String(i.key.value);if(i.value.type==="Identifier")r[o]={kind:"any"},s[o]={name:o,type:{kind:"any"},required:!0};else if(i.value.type==="AssignmentPattern"){let a=Ce(i.value,n),c=n?.has(o)??!1;r[o]=a.type,s[o]={name:o,type:a.type,required:c,default:c?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 W(e){switch(e.type){case"Literal":return e.value;case"ArrayExpression":return e.elements.map(n=>n?W(n):null);case"ObjectExpression":{let n={};for(let t of e.properties)t.type==="Property"&&t.key.type==="Identifier"&&(n[t.key.name]=W(t.value));return n}case"UnaryExpression":if(e.operator==="-"){let n=W(e.argument);return typeof n=="number"?-n:void 0}if(e.operator==="+"){let n=W(e.argument);return typeof n=="number"?+n:void 0}return;case"BinaryExpression":{let{operator:n,left:t}=e;return n==="|"?W(t):void 0}case"LogicalExpression":{let{operator:n,left:t,right:r}=e;return n==="&&"&&t.type==="Literal"&&t.value===null?null:n==="||"||n==="??"?W(t)??W(r):void 0}default:return}}function At(e){try{let n=Qn(e,0,{ecmaVersion:2022});return L(n)}catch{return{kind:"any"}}}function be(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?be(e.items):{}};case"object":if(e.shape){let n={};for(let[t,r]of Object.entries(e.shape))n[t]=be(r);return{type:"object",properties:n,additionalProperties:!1}}return{type:"object"};case"union":return e.members?{oneOf:e.members.map(be)}:{};default:return{}}}function er(e){let n={},t=[];for(let[r,s]of Object.entries(e))n[r]=be(s.type),s.required&&t.push(r);return{type:"object",properties:n,required:t.length>0?t:void 0,additionalProperties:!1}}function jt(e,n,t,r={},s){let i=Tt(n,e),o=new Map;for(let h of e.params){let S=Ce(h,s);if(S.name==="__destructured__"&&S.type.kind==="object"&&S.type.destructuredParams)for(let[x,g]of Object.entries(S.type.destructuredParams))o.set(x,{...g,description:i.params[x]});else S.description=i.params[S.name],o.set(S.name,S)}let a;t&&(a=At(t));let c={depth:0,locals:new Map,parameters:o,atoms:new Set(Object.keys(r.atoms||{})),warnings:[],source:n,filename:r.filename||"<source>",options:r},l=V(e.body,c),p=[],d=[],u=[];for(let[h,S]of o.entries())S.required?d.push(h):S.default!==void 0?u.push({name:h,defaultValue:S.default}):d.push(h);d.length>0&&p.push({op:"varsImport",keys:d});for(let{name:h,defaultValue:S}of u)p.push({op:"varsImport",keys:[h]}),p.push({op:"if",condition:{$expr:"binary",op:"==",left:{$expr:"ident",name:h},right:{$expr:"literal",value:null}},then:[{op:"varSet",key:h,value:S}]});p.push(...l);let m=Object.fromEntries(o),y={name:e.id?.name||"anonymous",description:i.description,parameters:m,returns:a},b=er(m);return{ast:{op:"seq",steps:p,inputSchema:b},signature:y,warnings:c.warnings}}function V(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 tr(e,n);case"ExpressionStatement":return nr(e,n);case"IfStatement":return sr(e,n);case"WhileStatement":return or(e,n);case"ForOfStatement":return ir(e,n);case"TryStatement":return ar(e,n);case"ReturnStatement":return lr(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:V(e,q(n))};case"EmptyStatement":return null;default:throw new P(`Unsupported statement type: ${e.type}`,I(e),n.source,n.filename)}}function tr(e,n){let t=[],r=e.kind==="const",s=r?"constSet":"varSet";for(let i of e.declarations){if(i.id.type!=="Identifier")throw new P("Only simple variable names are supported",I(i),n.source,n.filename);let o=i.id.name;if(i.init){let{step:a,resultVar:c}=Y(i.init,n,o,r);a?t.push(a):c!==o&&t.push({op:s,key:o,value:c});let l=L(i.init);n.locals.set(o,l)}else{if(r)throw new P("const declarations must be initialized",I(i),n.source,n.filename);t.push({op:"varSet",key:o,value:null}),n.locals.set(o,{kind:"any",nullable:!0})}}return t}function nr(e,n){let t=e.expression;if(t.type==="AssignmentExpression")return rr(t,n);if(t.type==="CallExpression"){let{step:r,resultVar:s}=Y(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 rr(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}=Y(e.right,n,t);return r||{op:"varSet",key:t,value:s}}function sr(e,n){let t=R(e.test,n),r=e.consequent.type==="BlockStatement"?V(e.consequent,q(n)):[oe(e.consequent,n)].filter(Boolean),s;return e.alternate&&(s=e.alternate.type==="BlockStatement"?V(e.alternate,q(n)):[oe(e.alternate,n)].filter(Boolean)),{op:"if",condition:t,then:r,...s&&{else:s}}}function or(e,n){let t=R(e.test,n),r=e.body.type==="BlockStatement"?V(e.body,q(n)):[oe(e.body,n)].filter(Boolean);return{op:"while",condition:t,body:r}}function ir(e,n){let t;if(e.left.type==="VariableDeclaration"){let o=e.left.declarations[0];if(o.id.type!=="Identifier")throw new P("Only simple variable names are supported in for...of",I(e.left),n.source,n.filename);t=o.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=_(e.right,n),s=q(n);s.locals.set(t,{kind:"any"});let i=e.body.type==="BlockStatement"?V(e.body,s):[oe(e.body,s)].filter(Boolean);return{op:"map",items:r,as:t,steps:i}}function ar(e,n){let t=V(e.block,q(n)),r,s;if(e.handler){let i=q(n);e.handler.param?.type==="Identifier"&&(s=e.handler.param.name,i.locals.set(s,{kind:"any"})),r=V(e.handler.body,i)}return{op:"try",try:t,...r&&{catch:r},...s&&{catchParam:s}}}function lr(e,n){if(!e.argument)return{op:"return",value:{}};let{step:t,resultVar:r}=Y(e.argument,n,"__returnVal__");return t?[t,{op:"return",value:r}]:{op:"return",value:_(e.argument,n)}}var Mt=new Set(["Math","JSON","Array","Object","String","Number","console","Date","Schema"]),cr=new Set(["parseInt","parseFloat","isNaN","isFinite","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent","Set","Date","filter"]),ie=new Set(["RegExp","Promise","Map","WeakSet","WeakMap","Symbol","Proxy","Reflect","Function","eval","setTimeout","setInterval","fetch","require","import","process","window","document","global","globalThis"]),ur=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 cr.has(n)||ie.has(n)}if(e.callee.type==="MemberExpression"){let n=e.callee;if(n.object.type==="Identifier"){let t=n.object.name;if(Mt.has(t)||ie.has(t))return!0}if(n.property.type==="Identifier"){let t=n.property.name;if(ur.has(t))return!0}}return!1}function pr(e){if(e.object.type==="Identifier"){let n=e.object.name;return Mt.has(n)||ie.has(n)}return!1}var vt={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 dr(e){if(e.callee.type==="Identifier"){let n=e.callee.name;if(ie.has(n))return vt[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(ie.has(t))return vt[t]||`${t} is not available in AsyncJS.`}}return null}function kt(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 Y(e,n,t,r){let s=r?"constSet":"varSet";if(e.type==="ChainExpression")return Y(e.expression,n,t,r);if(e.type==="NewExpression"){let o=e,a="constructor";o.callee.type==="Identifier"&&(a=o.callee.name);let c=kt(a);throw new P(`The 'new' keyword is not supported in AsyncJS.${c}`,I(e),n.source,n.filename)}if(e.type==="CallExpression"){let o=dr(e);if(o)throw new P(o,I(e),n.source,n.filename)}if(e.type==="CallExpression"&&fr(e)){let o=R(e,n);return t?{step:{op:s,key:t,value:o},resultVar:t}:{step:null,resultVar:o}}if(e.type==="MemberExpression"&&pr(e)){let o=R(e,n);return t?{step:{op:s,key:t,value:o},resultVar:t}:{step:null,resultVar:o}}if(e.type==="CallExpression")return mr(e,n,t,r);if(e.type==="TemplateLiteral")return gr(e,n,t,r);if(e.type==="BinaryExpression"||e.type==="LogicalExpression"||e.type==="UnaryExpression"){let o=R(e,n);return t?{step:{op:s,key:t,value:o},resultVar:t}:{step:null,resultVar:o}}return{step:null,resultVar:_(e,n)}}function mr(e,n,t,r){let s,i=!1,o;if(e.callee.type==="Identifier")s=e.callee.name;else if(e.callee.type==="MemberExpression"){let c=e.callee;if(c.property.type==="Identifier")s=c.property.name,i=!0,o=_(c.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(i)return yr(s,o,e.arguments,n,t,r);s==="console"&&e.callee.type;let a=hr(e,n);return{step:{op:s,...a,...t&&{result:t},...t&&r&&{resultConst:!0}},resultVar:t}}function yr(e,n,t,r,s,i){switch(e){case"map":if(t.length>0&&(t[0].type==="ArrowFunctionExpression"||t[0].type==="FunctionExpression")){let o=t[0],a=o.params[0],c=a?.type==="Identifier"?a.name:"item",l=q(r);l.locals.set(c,{kind:"any"});let p;if(o.body.type==="BlockStatement")p=V(o.body,l);else{let{step:d,resultVar:u}=Y(o.body,l,"result");p=d?[d]:[{op:"varSet",key:"result",value:u}]}return{step:{op:"map",items:n,as:c,steps:p,...s&&{result:s},...s&&i&&{resultConst:!0}},resultVar:s}}break;case"filter":if(t.length>0&&(t[0].type==="ArrowFunctionExpression"||t[0].type==="FunctionExpression")){let o=t[0],a=o.params[0],c=a?.type==="Identifier"?a.name:"item",l=q(r);l.locals.set(c,{kind:"any"});let p;if(o.body.type==="BlockStatement")throw new P("filter callback must be an expression, not a block",I(t[0]),r.source,r.filename);return p=R(o.body,l),{step:{op:"filter",items:n,as:c,condition:p,...s&&{result:s},...s&&i&&{resultConst:!0}},resultVar:s}}break;case"find":if(t.length>0&&(t[0].type==="ArrowFunctionExpression"||t[0].type==="FunctionExpression")){let o=t[0],a=o.params[0],c=a?.type==="Identifier"?a.name:"item",l=q(r);l.locals.set(c,{kind:"any"});let p;if(o.body.type==="BlockStatement")throw new P("find callback must be an expression, not a block",I(t[0]),r.source,r.filename);return p=R(o.body,l),{step:{op:"find",items:n,as:c,condition:p,...s&&{result:s},...s&&i&&{resultConst:!0}},resultVar:s}}break;case"reduce":if(t.length>=2&&(t[0].type==="ArrowFunctionExpression"||t[0].type==="FunctionExpression")){let o=t[0],a=o.params[0],c=o.params[1],l=a?.type==="Identifier"?a.name:"acc",p=c?.type==="Identifier"?c.name:"item",d=q(r);d.locals.set(l,{kind:"any"}),d.locals.set(p,{kind:"any"});let u;if(o.body.type==="BlockStatement")u=V(o.body,d);else{let{step:y,resultVar:b}=Y(o.body,d,"result");u=y?[y]:[{op:"varSet",key:"result",value:b}]}let m=_(t[1],r);return{step:{op:"reduce",items:n,as:p,accumulator:l,initial:m,steps:u,...s&&{result:s},...s&&i&&{resultConst:!0}},resultVar:s}}break;case"slice":break;case"push":return{step:{op:"push",list:n,item:_(t[0],r),...s&&{result:s},...s&&i&&{resultConst:!0}},resultVar:s};case"join":return{step:{op:"join",list:n,sep:t.length>0?_(t[0],r):"",...s&&{result:s},...s&&i&&{resultConst:!0}},resultVar:s};case"split":return{step:{op:"split",str:n,sep:t.length>0?_(t[0],r):"",...s&&{result:s},...s&&i&&{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(o=>_(o,r)),...s&&{result:s},...s&&i&&{resultConst:!0}},resultVar:s}}function gr(e,n,t,r){let s="",i={};for(let o=0;o<e.quasis.length;o++)if(s+=e.quasis[o].value.cooked||e.quasis[o].value.raw,o<e.expressions.length){let a=e.expressions[o],c=`_${o}`;i[c]=_(a,n),s+=`{{${c}}}`}return{step:{op:"template",tmpl:s,vars:i,...t&&{result:t},...t&&r&&{resultConst:!0}},resultVar:t}}function R(e,n){switch(e.type){case"Literal":return{$expr:"literal",value:e.value};case"Identifier":return{$expr:"ident",name:e.name};case"MemberExpression":{let t=e,r=R(t.object,n),s=t.optional===!0;if(t.computed){let o=t.property;if(o.type==="Literal")return{$expr:"member",object:r,property:String(o.value),computed:!0,...s&&{optional:!0}};throw new P("Computed member access with variables not yet supported",I(e),n.source,n.filename)}let i=t.property.name;return{$expr:"member",object:r,property:i,...s&&{optional:!0}}}case"ChainExpression":return R(e.expression,n);case"BinaryExpression":{let t=e;return{$expr:"binary",op:t.operator,left:R(t.left,n),right:R(t.right,n)}}case"LogicalExpression":{let t=e;return{$expr:"logical",op:t.operator,left:R(t.left,n),right:R(t.right,n)}}case"UnaryExpression":{let t=e;return{$expr:"unary",op:t.operator,argument:R(t.argument,n)}}case"ConditionalExpression":{let t=e;return{$expr:"conditional",test:R(t.test,n),consequent:R(t.consequent,n),alternate:R(t.alternate,n)}}case"ArrayExpression":return{$expr:"array",elements:e.elements.filter(r=>r!==null).map(r=>R(r,n))};case"ObjectExpression":{let t=e,r=[];for(let s of t.properties)if(s.type==="Property"){let i=s.key.type==="Identifier"?s.key.name:String(s.key.value);r.push({key:i,value:R(s.value,n)})}return{$expr:"object",properties:r}}case"CallExpression":{let t=e;if(t.callee.type==="MemberExpression"){let r=t.callee,s=r.property.type==="Identifier"?r.property.name:String(r.property.value),i=r.optional===!0||t.optional===!0;return{$expr:"methodCall",object:R(r.object,n),method:s,arguments:t.arguments.map(o=>R(o,n)),...i&&{optional:!0}}}if(t.callee.type==="Identifier")return{$expr:"call",callee:t.callee.name,arguments:t.arguments.map(s=>R(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=kt(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 _(e,n){switch(e.type){case"Literal":return e.value;case"Identifier":return e.name;case"MemberExpression":{let t=e;if(t.optional===!0)return R(e,n);let s=_(t.object,n);if(s&&typeof s=="object"&&s.$expr){let o=t.computed?String(t.property.value):t.property.name;return{$expr:"member",object:s,property:o,...t.computed&&{computed:!0}}}if(t.computed)return`${s}[${_(t.property,n)}]`;let i=t.property.name;return typeof s=="string"?`${s}.${i}`:s&&s.$kind==="arg"?{$kind:"arg",path:`${s.path}.${i}`}:`${s}.${i}`}case"ChainExpression":return _(e.expression,n);case"ArrayExpression":return e.elements.map(t=>t?_(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]=_(r.value,n)}return t}case"TemplateLiteral":return R(e,n);case"CallExpression":return R(e,n);case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"ConditionalExpression":return R(e,n);default:return null}}function hr(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 i=s.key.type==="Identifier"?s.key.name:String(s.key.value);r[i]=_(s.value,n)}return r}return{args:e.arguments.map(t=>_(t,n))}}function ae(e,n={}){let{ast:t,returnType:r,originalSource:s,requiredParams:i}=$t(e,{filename:n.filename,colonShorthand:!0,vmTarget:!0}),o=xt(t,n.filename),{ast:a,signature:c,warnings:l}=jt(o,s,r,n,i);return{ast:a,signature:c,warnings:l}}var wr=10,we=class{atoms;constructor(n={}){this.atoms={...Fe,...n}}get builder(){return new te(this.atoms)}get Agent(){return new te(this.atoms)}get A99(){return this.Agent}resolve(n){return this.atoms[n]}getTools(n="all"){let t=Object.values(this.atoms);if(Array.isArray(n))t=t.filter(r=>n.includes(r.op));else if(n==="flow"){let r=["seq","if","while","return","try","varSet","varGet","scope"];t=t.filter(s=>r.includes(s.op))}return t.map(r=>({type:"function",function:{name:r.op,description:r.docs,parameters:r.inputSchema?.schema??{}}}))}async run(n,t={},r={}){let s;if(typeof n=="string")if(xe(n))s=Te(n);else try{s=ae(n).ast}catch(y){throw new Error(`AJS transpilation failed: ${y.message}`)}else s=n;let i=r.fuel??1e3,o=r.timeoutMs??i*wr,a=r.capabilities??{},c=[];if(!a.store){let y=new Map,b=!1;a.store={get:async h=>(b||(b=!0,c.push("Using default in-memory store (not suitable for production)")),y.get(h)),set:async(h,S)=>{b||(b=!0,c.push("Using default in-memory store (not suitable for production)")),y.set(h,S)}}}let l=new AbortController,p=setTimeout(()=>l.abort(),o);r.signal&&r.signal.addEventListener("abort",()=>l.abort());let d={fuel:{current:i},args:t,state:{},consts:new Set,capabilities:a,resolver:y=>this.resolve(y),output:void 0,signal:l.signal,costOverrides:r.costOverrides,context:r.context,warnings:c};if(r.trace&&(d.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&&!br(t,u)){let y=new D("Input validation failed: args do not match expected schema","vm.run");return{result:y,error:y,fuelUsed:0,trace:d.trace,warnings:c.length>0?c:void 0}}try{await Promise.race([this.resolve("seq")?.exec(s,d),new Promise((y,b)=>{l.signal.addEventListener("abort",()=>{b(new Error(`Execution timeout after ${o}ms (fuel: ${i}). Consider increasing fuel or optimizing your agent.`))}),l.signal.aborted&&b(new Error(`Execution timeout after ${o}ms (fuel: ${i}). Consider increasing fuel or optimizing your agent.`))})])}catch(y){if(y.message?.includes("timeout")||y.message?.includes("aborted")||l.signal.aborted)d.error=new D(`Execution timeout after ${o}ms (fuel: ${i}). Consider increasing fuel or optimizing your agent.`,"vm.run");else throw y}finally{clearTimeout(p)}d.error&&d.output===void 0&&(d.output=d.error);let m=[...c,...d.warnings??[]];return{result:d.output,error:d.error,fuelUsed:i-d.fuel.current,trace:d.trace,warnings:m.length>0?m:void 0}}};var Sr=null,Ct=()=>Sr??=new we;function X(e){if(!(!e||typeof e!="object")){if(Array.isArray(e)){for(let n of e)X(n);return}e.op==="return"&&"value"in e&&(e.value={__result:e.value}),e.steps&&X(e.steps),e.then&&X(e.then),e.else&&X(e.else),e.body&&X(e.body)}}async function Yr(e){let{code:n,context:t={},fuel:r=1e3,timeoutMs:s,capabilities:i={}}=e,o=Ct(),c=/\breturn\b/.test(n)?`function __eval() { ${n} }`:`function __eval() { return (${n}) }`;try{let{ast:l}=ae(c);X(l);let p=await o.run(l,t,{fuel:r,timeoutMs:s,capabilities:i}),d=p.result;return{result:d&&typeof d=="object"&&"__result"in d?d.__result:d,fuelUsed:p.fuelUsed,error:p.error?{message:p.error.message||String(p.error)}:void 0}}catch(l){return{result:void 0,fuelUsed:r,error:{message:l.message||String(l)}}}}async function Xr(e){let{body:n,params:t=[],fuel:r=1e3,timeoutMs:s,capabilities:i={}}=e,o=Ct(),c=`function __safeFn(${t.join(", ")}) { ${n} }`,{ast:l}=ae(c);return X(l),async(...p)=>{let d={};for(let u=0;u<t.length;u++)d[t[u]]=p[u];try{let u=await o.run(l,d,{fuel:r,timeoutMs:s,capabilities:i}),m=u.result;return{result:m&&typeof m=="object"&&"__result"in m?m.__result:m,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{Yr as Eval,Xr as SafeFunction};
|
|
47
|
+
//# sourceMappingURL=tjs-eval.js.map
|