mevento 4.0.0 → 4.0.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Mahamadou DOUMBIA
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,17 +1,24 @@
1
- # MEvento TypeScript
1
+ # mevento — Embedded scripting for JavaScript and TypeScript
2
2
 
3
- MEvento is a tiny single-file scripting VM for host applications. The host keeps
4
- control of native behavior by exposing functions, while scripts stored in a
5
- database or loaded at runtime can compose those functions without rebuilding the
6
- host app.
3
+ `mevento` is an npm package providing an embeddable C-like scripting language
4
+ and virtual machine for JavaScript and TypeScript host applications. The host
5
+ keeps control of native behavior by exposing functions, while scripts stored in
6
+ a database or loaded at runtime can compose those functions without rebuilding
7
+ the host application.
7
8
 
8
- This module is the TypeScript implementation. It provides synchronous
9
- `MEvento` and async `MEventoAsync` runtimes.
9
+ It provides the synchronous `MEvento` and asynchronous `MEventoAsync` runtimes.
10
10
 
11
- ## v2 Status
11
+ ## Installation
12
12
 
13
- v2 is a superset of v1 script syntax, with stricter diagnostics and new
14
- runtime helpers. Existing v1 scripts should still parse and execute in v2.
13
+ ```bash
14
+ npm install mevento
15
+ ```
16
+
17
+ ## Language v2 Status
18
+
19
+ MEvento language v2 is a superset of v1 script syntax, with stricter diagnostics
20
+ and new runtime helpers. The language version is separate from the npm package
21
+ version. Existing v1 scripts should still parse and execute in language v2.
15
22
 
16
23
  By default, v2 is stricter: unknown host functions raise `unknown_function`
17
24
  instead of silently returning `null`. For existing database scripts that depend
@@ -24,7 +31,8 @@ v2 additions include:
24
31
 
25
32
  - Dot property access: `user.name` is equivalent to `user['name']`.
26
33
  - `_try_` result capture and helper functions.
27
- - Function specs with arity, argument type hints, tags, and return type hints.
34
+ - Function specs with arity, argument type hints, tags, return type hints, and
35
+ optional documentation metadata.
28
36
  - Script manifest validation for required host functions, inputs, and outputs.
29
37
  - Trace mode and execution step budgets.
30
38
  - v1 compatibility mode for existing scripts that call optional host functions.
@@ -99,13 +107,17 @@ MEvento.register("log", (args) => {
99
107
 
100
108
  MEvento.register("add", (args) => Number(args[0]) + Number(args[1]), {
101
109
  name: "add",
110
+ description: "Adds two numeric values.",
102
111
  minArgs: 2,
103
112
  maxArgs: 2,
104
113
  args: [
105
- { name: "left", type: "number" },
106
- { name: "right", type: "number" },
114
+ { name: "left", type: "number", description: "First value." },
115
+ { name: "right", type: "number", description: "Second value." },
107
116
  ],
108
117
  returnType: "number",
118
+ returnDescription: "The sum of the two values.",
119
+ examples: [{ script: "add(12, 23)", result: 35 }],
120
+ metadata: { category: "math" },
109
121
  });
110
122
 
111
123
  const value = MEvento.run("add(12, 23)");
@@ -152,6 +164,14 @@ const total = MEvento.run("base + bonus", false, {
152
164
  });
153
165
  ```
154
166
 
167
+ ## Documenting Host Functions
168
+
169
+ Function and argument specs can carry optional documentation metadata:
170
+ `description`, `returnDescription`, `examples`, and `metadata` on functions,
171
+ plus `description` and `metadata` on arguments. The runtime exposes those fields
172
+ through `capabilities()` for diagnostics, documentation, and UI tooling, but
173
+ they do not change script execution.
174
+
155
175
  ## Validation And Manifests
156
176
 
157
177
  Function specs drive preflight validation and runtime argument checks:
@@ -123,11 +123,27 @@ type MEventoFunctionSpec = {
123
123
  tags?: Iterable<string>;
124
124
  args?: MEventoArgSpec[];
125
125
  returnType?: string;
126
+ description?: string;
127
+ returnDescription?: string;
128
+ examples?: MEventoFunctionExample[];
129
+ metadata?: {
130
+ [name: string]: unknown;
131
+ };
132
+ };
133
+ type MEventoFunctionExample = {
134
+ title?: string;
135
+ script: string;
136
+ result?: unknown;
137
+ description?: string;
126
138
  };
127
139
  type MEventoArgSpec = {
128
140
  name: string;
129
141
  type?: string;
130
142
  required?: boolean;
143
+ description?: string;
144
+ metadata?: {
145
+ [name: string]: unknown;
146
+ };
131
147
  };
132
148
  type MEventoOptions = {
133
149
  maxSteps?: number;
@@ -489,4 +505,4 @@ declare class MEventoAsync extends MEvento {
489
505
  clone(): MEventoAsync;
490
506
  }
491
507
 
492
- export { AST, ArrayExpression, AssignmentExpressionAST, BinaryExpressionAST, BlockStatementAST, BreakAST, BreakBranch, CallExpressionAST, ContinueAST, ContinueBranch, ExpressionStatementAST, ForLoopStatement, ForOfStatement, IdentifierAST, IfStatementAST, IndexAccessorAST, LexerDictionary, LiteralAST, LogicalExpressionAST, LoopControl, MEventScope, MEvento, type MEventoArgSpec, MEventoAsync, type MEventoDiagnostic, type MEventoFBinding, type MEventoFunctionList, type MEventoFunctionSpec, type MEventoOptions, MEventoRuntimeError, type MEventoScriptManifest, type MEventoTraceEvent, type MEventoValidationError, type MEventoValidationResult, type MEventoValueSpec, NodeVisitor, ObjectExpression, ObjectProperty, ReturnAST, ReturnBranch, RootAST, Token, TokenType, TupleExpression, UnaryExpressionAST, WhileLoopStatement };
508
+ export { AST, ArrayExpression, AssignmentExpressionAST, BinaryExpressionAST, BlockStatementAST, BreakAST, BreakBranch, CallExpressionAST, ContinueAST, ContinueBranch, ExpressionStatementAST, ForLoopStatement, ForOfStatement, IdentifierAST, IfStatementAST, IndexAccessorAST, LexerDictionary, LiteralAST, LogicalExpressionAST, LoopControl, MEventScope, MEvento, type MEventoArgSpec, MEventoAsync, type MEventoDiagnostic, type MEventoFBinding, type MEventoFunctionExample, type MEventoFunctionList, type MEventoFunctionSpec, type MEventoOptions, MEventoRuntimeError, type MEventoScriptManifest, type MEventoTraceEvent, type MEventoValidationError, type MEventoValidationResult, type MEventoValueSpec, NodeVisitor, ObjectExpression, ObjectProperty, ReturnAST, ReturnBranch, RootAST, Token, TokenType, TupleExpression, UnaryExpressionAST, WhileLoopStatement };
package/dist/cjs/index.js CHANGED
@@ -1,8 +1,8 @@
1
- var pt=Object.defineProperty;var Tt=Object.getOwnPropertyDescriptor;var kt=Object.getOwnPropertyNames;var Ct=Object.prototype.hasOwnProperty;var Mt=(a,e)=>{for(var t in e)pt(a,t,{get:e[t],enumerable:!0})},Lt=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of kt(e))!Ct.call(a,r)&&r!==t&&pt(a,r,{get:()=>e[r],enumerable:!(n=Tt(e,r))||n.enumerable});return a};var Ot=a=>Lt(pt({},"__esModule",{value:!0}),a);var Ut={};Mt(Ut,{AST:()=>m,ArrayExpression:()=>$,AssignmentExpressionAST:()=>L,BinaryExpressionAST:()=>P,BlockStatementAST:()=>F,BreakAST:()=>Z,BreakBranch:()=>C,CallExpressionAST:()=>j,ContinueAST:()=>tt,ContinueBranch:()=>M,ExpressionStatementAST:()=>G,ForLoopStatement:()=>D,ForOfStatement:()=>K,IdentifierAST:()=>x,IfStatementAST:()=>U,IndexAccessorAST:()=>w,LexerDictionary:()=>X,LiteralAST:()=>A,LogicalExpressionAST:()=>W,LoopControl:()=>R,MEventScope:()=>rt,MEvento:()=>it,MEventoAsync:()=>lt,MEventoRuntimeError:()=>S,NodeVisitor:()=>ct,ObjectExpression:()=>I,ObjectProperty:()=>O,ReturnAST:()=>H,ReturnBranch:()=>y,RootAST:()=>q,Token:()=>l,TokenType:()=>i,TupleExpression:()=>N,UnaryExpressionAST:()=>z,WhileLoopStatement:()=>B});module.exports=Ot(Ut);function T(a,e){let t=`Invalid token ${a.type}[${a.value}] at ${a.line}, ${a.col} ${e?`: expecting ${e} token`:""}
2
- `;throw Error(t)}function h(a){return typeof a=="number"}function Nt(a){return typeof a=="boolean"}function Y(a){return typeof a=="string"}function b(a){return!(a===null||h(a)&&a===0||Y(a)&&a.length===0||Nt(a)&&!a)}function It(a){let e=0,t=0,n;if(a.length===0)return e;for(t=0;t<a.length;t++)n=a.charCodeAt(t),e=(e<<5)-e+n,e|=0;return e}var i=class{};i.id=0,i.comma=1,i.semi=2,i.numberConst=3,i.stringConst=4,i.equal=5,i.lparen=6,i.rparen=7,i.eol=8,i.eof=9,i.lbrace=10,i.rbrace=11,i.lbracket=12,i.rbracket=13,i.great=14,i.greatEq=15,i.less=16,i.lessEq=17,i.eqeq=18,i.IF=19,i.ELSE=20,i.TRUE=21,i.FALSE=22,i.NULL=23,i.not=24,i.notEq=25,i.and=26,i.or=27,i.plus=28,i.minus=29,i.div=30,i.mult=31,i.mod=32,i.invalid=33,i.colon=34,i.WHILE_TILL=35,i.FOR_LOOP=36,i.up=37,i.down=38,i.with=39,i.in=40,i.TILL=41,i.BREAK=42,i.CONTINUE=43,i.nullity=44,i.RETURN=45,i.dot=46;var l=class a{constructor(e,t,n=1,r=1){this.type=e,this.value=t,this.line=n,this.col=r}static from(e,t){return new a(e,t)}toString(){return`[${this.type.toString()}, ${this.value}]`}},c=class{};c.equal=61,c.comma=44,c.semiColon=59,c.lparen=40,c.rparen=41,c.backslash=92,c.quote=34,c.squote=39,c.plus=43,c.minus=45,c.star=42,c.slash=47,c.percent=37,c.lbrace=123,c.rbrace=125,c.lbracket=91,c.rbracket=93,c.not=33,c.great=62,c.less=60,c.and=38,c.pipe=124,c.colon=58,c.questionMark=63,c.shebang=35,c.dot=46;var X=class{constructor(e,t){this.keywords={};this.keywords={...t},this.lang=e}},k=class k{constructor(e){this._position=0;this._line=1;this._col=1;this._currentChar=-1;this._source=e,this._currentChar=this._source[this._position].charCodeAt(0),this._resolveLanguage()}get source(){return this._source}_resolveLanguage(){var t;let e=this.nextToken();if(e.type===i.less){let n=this.nextToken();n.type!==i.id&&T(e);let r=n.value.toString();this._language=(t=k.languages.find(s=>s.lang===r))!=null?t:k._defaultLanguage,e=this.nextToken(),e.type!==i.great&&T(e)}else this._language=k._defaultLanguage,this._position=0,this._currentChar=this._source[this._position].charCodeAt(0)}_advance(){if(this._position++,this._position>=this._source.length){this._currentChar=-1;return}this._currentChar=this._source[this._position].charCodeAt(0),this._col++}_jump(e){if(this._position+=e,this._position>=this._source.length){this._currentChar=-1;return}this._currentChar=this._source[this._position].charCodeAt(0),this._col+=e}_pick(){return this._position+1>=this._source.length?-1:this._source[this._position+1].charCodeAt(0)}_isId(e){return e<48?e===36:e<58?!0:e<65?!1:e<91?!0:e<97?e===95:e<123}_isIdStart(e){return e<65?e===36:e<91?!0:e<97?e===95:e<123}_id(){var o,u;let e="",t=this._col,n=this._position,r=this._line;for(;this._isId(this._currentChar);)e+=String.fromCharCode(this._currentChar),this._advance();let s=this._language&&(o=this._language.keywords[e])!=null?o:e;return(u=k.RESERVED[s])!=null?u:new l(i.id,e,r,t)}_isLineEnd(e){return e===10||e===13||[`
3
- `,"\r","\u2028","\u2029"].includes(String.fromCharCode(e))}_isWhiteSpace(e){return[" "," "].includes(String.fromCharCode(e))}_isDigit(e){return e>0&&(e^48)<=9}_skipWhiteSpace(){for(;this._isWhiteSpace(this._currentChar)===!0;)this._advance()}_number(){let e="",t=this._col,n=this._position,r=this._line,s=String.fromCharCode(this._currentChar);this._advance();let o=String.fromCharCode(this._currentChar),u=10;if(s==="0"&&["b","B","x","X","o","O"].includes(o))switch(this._advance(),o.toLowerCase()){case"b":u=2;break;case"o":u=8;break;case"x":u=16;break;default:u=10}else e+=s,u=10;for(;this._isDigit(this._currentChar)||u===16&&["A","a","B","b","C","c","D","d","E","e","F","f"].includes(String.fromCharCode(this._currentChar));)e+=String.fromCharCode(this._currentChar),this._advance();if(String.fromCharCode(this._currentChar)==="."&&this._isDigit(this._pick())===!0){for(u!==10&&T(new l(i.id,o,r,n)),e+=String.fromCharCode(this._currentChar),this._advance();this._isDigit(this._currentChar);)e+=String.fromCharCode(this._currentChar),this._advance();return new l(i.numberConst,parseFloat(e),r,t)}return new l(i.numberConst,parseInt(e,u),r,t)}_literalString(e){let t="",n=-1,r=this._position,s=this._col,o=this._line;for(;this._currentChar!==-1;){let u=String.fromCharCode(this._pick());if(this._currentChar==c.backslash){switch(u){case"\\":t+="\\";break;case"0":t+="\0";break;case"a":t+="a";break;case"b":t+="\b";break;case"f":t+="\f";break;case"n":t+=`
4
- `;break;case"r":t+="\r";break;case"t":t+=" ";break;case"u":t+=String.fromCharCode(Number.parseInt(this._source.substring(this._position+2,this._position+6),16)),this._jump(4);break;case"v":t+="\v";break;case"x":t+=String.fromCharCode(Number.parseInt(this._source.substring(this._position+2,this._position+4),16)),this._jump(2);break;default:if(String.fromCharCode(e)==u)t+=String.fromCharCode(e);else{this._advance(),n=this._currentChar,t+=String.fromCharCode(this._currentChar),this._advance();continue}}this._jump(2),n=this._currentChar;continue}if(this._currentChar===e&&n!==c.backslash)break;t+=String.fromCharCode(this._currentChar),n=this._currentChar,this._advance()}return new l(i.stringConst,t,o,s)}_skipLineComment(){for(;!this._isLineEnd(this._currentChar)&&this._currentChar!=-1;)this._advance()}_skipComment(){for(;this._currentChar!==-1;){if(this._currentChar===c.star&&this._pick()===c.shebang){this._advance(),this._advance();break}this._advance()}}nextToken(){let e=this._line,t=this._col,n=this._position;for(;this._currentChar!==-1;){if(this._isLineEnd(this._currentChar))return this._line++,this._col=1,this._advance(),new l(i.eol,`
5
- `,e,t);if(this._isWhiteSpace(this._currentChar)){this._skipWhiteSpace();continue}if(this._currentChar==c.shebang){this._advance(),this._currentChar===c.star?(this._advance(),this._skipComment()):this._skipLineComment();continue}if(this._isDigit(this._currentChar))return this._number();if(this._isIdStart(this._currentChar))return this._id();if(this._currentChar===c.equal)return this._advance(),this._currentChar===c.equal?(this._advance(),new l(i.eqeq,"==",e,t)):new l(i.equal,"=",e,t);if(this._currentChar===c.great)return this._advance(),this._currentChar===c.equal?(this._advance(),new l(i.greatEq,">=",e,t)):new l(i.great,">",e,t);if(this._currentChar===c.less)return this._advance(),this._currentChar===c.equal?(this._advance(),new l(i.lessEq,"<=",e,t)):new l(i.less,"<",e,t);if(this._currentChar===c.semiColon)return this._advance(),new l(i.semi,";",e,t);if(this._currentChar===c.lparen)return this._advance(),new l(i.lparen,"(",e,t);if(this._currentChar===c.rparen)return this._advance(),new l(i.rparen,")",e,t);if(this._currentChar===c.comma)return this._advance(),new l(i.comma,",",e,t);if(this._currentChar===c.lbrace)return this._advance(),new l(i.lbrace,"{",e,t);if(this._currentChar===c.rbrace)return this._advance(),new l(i.rbrace,"}",e,t);if(this._currentChar===c.lbracket)return this._advance(),new l(i.lbracket,"[",e,t);if(this._currentChar===c.rbracket)return this._advance(),new l(i.rbracket,"]",e,t);if(this._currentChar===c.plus)return this._advance(),new l(i.plus,"+",e,t);if(this._currentChar===c.minus)return this._advance(),new l(i.minus,"-",e,t);if(this._currentChar===c.slash)return this._advance(),new l(i.div,"/",e,t);if(this._currentChar===c.star)return this._advance(),new l(i.mult,"*",e,t);if(this._currentChar===c.percent)return this._advance(),new l(i.mod,"%",e,t);if(this._currentChar===c.colon)return this._advance(),new l(i.colon,":",e,t);if(this._currentChar===c.dot)return this._advance(),new l(i.dot,".",e,t);if(this._currentChar===c.not)return this._advance(),this._currentChar===c.equal?(this._advance(),new l(i.notEq,"!=",e,t)):new l(i.not,"!",e,t);if(this._currentChar===c.and&&this._pick()===c.and)return this._advance(),this._advance(),new l(i.and,"&&",e,t);if(this._currentChar===c.pipe&&this._pick()===c.pipe)return this._advance(),this._advance(),new l(i.or,"||",e,t);if(this._currentChar===c.questionMark&&this._pick()===c.questionMark)return this._advance(),this._advance(),new l(i.nullity,"??",e,t);if(this._currentChar===c.quote||this._currentChar===c.squote){let r=this._currentChar;this._advance();let s=this._literalString(r);return this._advance(),s}return new l(i.invalid,String.fromCharCode(this._currentChar),e,t)}return new l(i.eof,"",e,t)}};k._defaultLanguage=new X("en",{if:"if",else:"else",true:"true",false:"false",null:"null",while:"while",for:"for",with:"with",up:"up",down:"down",till:"till",in:"in",break:"break",continue:"continue",return:"return"}),k.languages=[k._defaultLanguage,new X("fr",{si:"if",sinon:"else",vrai:"true",faux:"false",nul:"null",tanque:"while",pour:"for",avec:"with",mont:"up",desc:"down",jusqua:"till",dans:"in",couper:"break",continuer:"continue",returner:"return"}),new X("bm",{nii:"if",note:"else",tien:"true",galon:"false",gansan:"null",foo:"while",seginka:"for",niin:"with",kay:"up",kaj:"down",kata:"till",kono:"in",tike:"break",ipan:"continue",segin:"return"})],k.RESERVED={if:l.from(i.IF,"if"),else:l.from(i.ELSE,"else"),true:l.from(i.TRUE,!0),false:l.from(i.FALSE,!1),null:l.from(i.NULL,null),for:l.from(i.FOR_LOOP,"for"),while:l.from(i.WHILE_TILL,"while"),with:l.from(i.with,"with"),up:l.from(i.up,"up"),down:l.from(i.down,"down"),till:l.from(i.TILL,"till"),in:l.from(i.in,"in"),break:l.from(i.BREAK,"break"),continue:l.from(i.CONTINUE,"continue"),return:l.from(i.RETURN,"return")};var mt=k,m=class{constructor(e,t){this.line=e,this.col=t}dump(){return this.toString()}},S=class a extends Error{constructor(e,t,n,r,s,o){var u;super(a.format(e,t,n,r)),this.name="MEventoRuntimeError",this.detail=e,this.line=t,this.col=n,this.nodeType=r,this.cause=s,this.code=(u=o==null?void 0:o.code)!=null?u:"runtime_error",this.diagnosticName=o==null?void 0:o.name,this.argCount=o==null?void 0:o.argCount,this.minArgs=o==null?void 0:o.minArgs,this.maxArgs=o==null?void 0:o.maxArgs,this.argIndex=o==null?void 0:o.argIndex,this.expectedType=o==null?void 0:o.expectedType,this.actualType=o==null?void 0:o.actualType,this.stepCount=o==null?void 0:o.stepCount,this.maxSteps=o==null?void 0:o.maxSteps}static fromNode(e,t){if(t instanceof a)return t;let n=t instanceof Error?t.message:String(t);return new a(n,e.line,e.col,e.constructor.name,t)}static format(e,t,n,r){let s=t!=null&&n!=null?` at ${t}:${n}`:"",o=r?` [${r}]`:"";return`MEvento runtime error${s}${o}: ${e}`}diagnostic(){return{code:this.code,message:this.detail,line:this.line,col:this.col,node:this.nodeType,name:this.diagnosticName,argCount:this.argCount,minArgs:this.minArgs,maxArgs:this.maxArgs,argIndex:this.argIndex,expectedType:this.expectedType,actualType:this.actualType,stepCount:this.stepCount,maxSteps:this.maxSteps}}};function g(a,e){var r;let t={name:a,minArgs:e==null?void 0:e.minArgs,maxArgs:e==null?void 0:e.maxArgs,tags:e!=null&&e.tags?Array.from(e.tags):[],args:e!=null&&e.args?e.args.map($t):[],returnType:(r=e==null?void 0:e.returnType)!=null?r:"any"};if(t.minArgs!=null&&t.minArgs<0)throw new Error("minArgs must be greater than or equal to 0");if(t.maxArgs!=null&&t.maxArgs<0)throw new Error("maxArgs must be greater than or equal to 0");let n=J(t);if(n!=null&&t.maxArgs!=null&&n>t.maxArgs)throw new Error("minArgs must be less than or equal to maxArgs");if(!yt.has(t.returnType))throw new Error(`Unsupported return type '${t.returnType}'`);return t}function $t(a){var t,n;let e={name:a.name,type:(t=a.type)!=null?t:"any",required:(n=a.required)!=null?n:!0};if(!Ft.has(e.type))throw new Error(`Unsupported argument type '${e.type}'`);return e}var yt=new Set(["any","null","boolean","number","string","array","object"]),Ft=yt;function Rt(a){var t,n;let e={maxSteps:a==null?void 0:a.maxSteps,trace:(t=a==null?void 0:a.trace)!=null?t:!1,compatV1:(n=a==null?void 0:a.compatV1)!=null?n:!1};if(e.maxSteps!=null&&(!Number.isInteger(e.maxSteps)||e.maxSteps<=0))throw new Error("maxSteps must be a positive integer");return e}function xt(a){var t,n;let e={name:a.name,type:(t=a.type)!=null?t:"any",required:(n=a.required)!=null?n:!0};if(!yt.has(e.type))throw new Error(`Unsupported value type '${e.type}'`);return e}function Vt(a){var e;return{name:a.name,minArgs:a.minArgs,maxArgs:a.maxArgs,tags:a.tags?Array.from(a.tags):[],args:a.args?a.args.map(t=>({...t})):[],returnType:(e=a.returnType)!=null?e:"any"}}function Et(a){return Object.fromEntries(Object.entries(a).map(([e,t])=>[e,Vt(t)]))}function vt(a,e){let t=J(a);return!(t!=null&&e<t||a.maxArgs!=null&&e>a.maxArgs)}function J(a){var n;let e=0;if(a.args){for(let r=a.args.length-1;r>=0;r-=1)if((n=a.args[r].required)==null||n){e=r+1;break}}let t=[a.minArgs,e>0?e:void 0].filter(r=>r!=null);return t.length>0?Math.max(...t):void 0}function gt(a){let e=J(a);return e==null&&a.maxArgs==null?"any number of":e!=null&&a.maxArgs!=null&&e===a.maxArgs?String(e):e!=null&&a.maxArgs!=null?`${e}..${a.maxArgs}`:e!=null?`at least ${e}`:`at most ${a.maxArgs}`}function et(a){return a==null?"null":typeof a=="boolean"?"boolean":typeof a=="number"?"number":typeof a=="string"?"string":Array.isArray(a)?"array":"object"}var q=class extends m{constructor(e,t,n){super(1,1),this.body=e,this.name=t,this.source=n}dump(){let e=`Module ${this.name} Start {`;for(let t of this.body)e+=`${t.dump()}
1
+ var mt=Object.defineProperty;var Mt=Object.getOwnPropertyDescriptor;var Lt=Object.getOwnPropertyNames;var Ot=Object.prototype.hasOwnProperty;var Nt=(s,e)=>{for(var t in e)mt(s,t,{get:e[t],enumerable:!0})},It=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Lt(e))!Ot.call(s,r)&&r!==t&&mt(s,r,{get:()=>e[r],enumerable:!(n=Mt(e,r))||n.enumerable});return s};var $t=s=>It(mt({},"__esModule",{value:!0}),s);var Bt={};Nt(Bt,{AST:()=>m,ArrayExpression:()=>$,AssignmentExpressionAST:()=>L,BinaryExpressionAST:()=>P,BlockStatementAST:()=>F,BreakAST:()=>Z,BreakBranch:()=>C,CallExpressionAST:()=>j,ContinueAST:()=>tt,ContinueBranch:()=>M,ExpressionStatementAST:()=>G,ForLoopStatement:()=>B,ForOfStatement:()=>K,IdentifierAST:()=>E,IfStatementAST:()=>U,IndexAccessorAST:()=>w,LexerDictionary:()=>X,LiteralAST:()=>A,LogicalExpressionAST:()=>D,LoopControl:()=>R,MEventScope:()=>rt,MEvento:()=>it,MEventoAsync:()=>pt,MEventoRuntimeError:()=>S,NodeVisitor:()=>ht,ObjectExpression:()=>I,ObjectProperty:()=>O,ReturnAST:()=>H,ReturnBranch:()=>y,RootAST:()=>q,Token:()=>l,TokenType:()=>i,TupleExpression:()=>N,UnaryExpressionAST:()=>z,WhileLoopStatement:()=>W});module.exports=$t(Bt);function T(s,e){let t=`Invalid token ${s.type}[${s.value}] at ${s.line}, ${s.col} ${e?`: expecting ${e} token`:""}
2
+ `;throw Error(t)}function h(s){return typeof s=="number"}function Ft(s){return typeof s=="boolean"}function Y(s){return typeof s=="string"}function b(s){return!(s===null||h(s)&&s===0||Y(s)&&s.length===0||Ft(s)&&!s)}function Rt(s){let e=0,t=0,n;if(s.length===0)return e;for(t=0;t<s.length;t++)n=s.charCodeAt(t),e=(e<<5)-e+n,e|=0;return e}var i=class{};i.id=0,i.comma=1,i.semi=2,i.numberConst=3,i.stringConst=4,i.equal=5,i.lparen=6,i.rparen=7,i.eol=8,i.eof=9,i.lbrace=10,i.rbrace=11,i.lbracket=12,i.rbracket=13,i.great=14,i.greatEq=15,i.less=16,i.lessEq=17,i.eqeq=18,i.IF=19,i.ELSE=20,i.TRUE=21,i.FALSE=22,i.NULL=23,i.not=24,i.notEq=25,i.and=26,i.or=27,i.plus=28,i.minus=29,i.div=30,i.mult=31,i.mod=32,i.invalid=33,i.colon=34,i.WHILE_TILL=35,i.FOR_LOOP=36,i.up=37,i.down=38,i.with=39,i.in=40,i.TILL=41,i.BREAK=42,i.CONTINUE=43,i.nullity=44,i.RETURN=45,i.dot=46;var l=class s{constructor(e,t,n=1,r=1){this.type=e,this.value=t,this.line=n,this.col=r}static from(e,t){return new s(e,t)}toString(){return`[${this.type.toString()}, ${this.value}]`}},c=class{};c.equal=61,c.comma=44,c.semiColon=59,c.lparen=40,c.rparen=41,c.backslash=92,c.quote=34,c.squote=39,c.plus=43,c.minus=45,c.star=42,c.slash=47,c.percent=37,c.lbrace=123,c.rbrace=125,c.lbracket=91,c.rbracket=93,c.not=33,c.great=62,c.less=60,c.and=38,c.pipe=124,c.colon=58,c.questionMark=63,c.shebang=35,c.dot=46;var X=class{constructor(e,t){this.keywords={};this.keywords={...t},this.lang=e}},k=class k{constructor(e){this._position=0;this._line=1;this._col=1;this._currentChar=-1;this._source=e,this._currentChar=this._source[this._position].charCodeAt(0),this._resolveLanguage()}get source(){return this._source}_resolveLanguage(){var t;let e=this.nextToken();if(e.type===i.less){let n=this.nextToken();n.type!==i.id&&T(e);let r=n.value.toString();this._language=(t=k.languages.find(a=>a.lang===r))!=null?t:k._defaultLanguage,e=this.nextToken(),e.type!==i.great&&T(e)}else this._language=k._defaultLanguage,this._position=0,this._currentChar=this._source[this._position].charCodeAt(0)}_advance(){if(this._position++,this._position>=this._source.length){this._currentChar=-1;return}this._currentChar=this._source[this._position].charCodeAt(0),this._col++}_jump(e){if(this._position+=e,this._position>=this._source.length){this._currentChar=-1;return}this._currentChar=this._source[this._position].charCodeAt(0),this._col+=e}_pick(){return this._position+1>=this._source.length?-1:this._source[this._position+1].charCodeAt(0)}_isId(e){return e<48?e===36:e<58?!0:e<65?!1:e<91?!0:e<97?e===95:e<123}_isIdStart(e){return e<65?e===36:e<91?!0:e<97?e===95:e<123}_id(){var o,u;let e="",t=this._col,n=this._position,r=this._line;for(;this._isId(this._currentChar);)e+=String.fromCharCode(this._currentChar),this._advance();let a=this._language&&(o=this._language.keywords[e])!=null?o:e;return(u=k.RESERVED[a])!=null?u:new l(i.id,e,r,t)}_isLineEnd(e){return e===10||e===13||[`
3
+ `,"\r","\u2028","\u2029"].includes(String.fromCharCode(e))}_isWhiteSpace(e){return[" "," "].includes(String.fromCharCode(e))}_isDigit(e){return e>0&&(e^48)<=9}_skipWhiteSpace(){for(;this._isWhiteSpace(this._currentChar)===!0;)this._advance()}_number(){let e="",t=this._col,n=this._position,r=this._line,a=String.fromCharCode(this._currentChar);this._advance();let o=String.fromCharCode(this._currentChar),u=10;if(a==="0"&&["b","B","x","X","o","O"].includes(o))switch(this._advance(),o.toLowerCase()){case"b":u=2;break;case"o":u=8;break;case"x":u=16;break;default:u=10}else e+=a,u=10;for(;this._isDigit(this._currentChar)||u===16&&["A","a","B","b","C","c","D","d","E","e","F","f"].includes(String.fromCharCode(this._currentChar));)e+=String.fromCharCode(this._currentChar),this._advance();if(String.fromCharCode(this._currentChar)==="."&&this._isDigit(this._pick())===!0){for(u!==10&&T(new l(i.id,o,r,n)),e+=String.fromCharCode(this._currentChar),this._advance();this._isDigit(this._currentChar);)e+=String.fromCharCode(this._currentChar),this._advance();return new l(i.numberConst,parseFloat(e),r,t)}return new l(i.numberConst,parseInt(e,u),r,t)}_literalString(e){let t="",n=-1,r=this._position,a=this._col,o=this._line;for(;this._currentChar!==-1;){let u=String.fromCharCode(this._pick());if(this._currentChar==c.backslash){switch(u){case"\\":t+="\\";break;case"0":t+="\0";break;case"a":t+="a";break;case"b":t+="\b";break;case"f":t+="\f";break;case"n":t+=`
4
+ `;break;case"r":t+="\r";break;case"t":t+=" ";break;case"u":t+=String.fromCharCode(Number.parseInt(this._source.substring(this._position+2,this._position+6),16)),this._jump(4);break;case"v":t+="\v";break;case"x":t+=String.fromCharCode(Number.parseInt(this._source.substring(this._position+2,this._position+4),16)),this._jump(2);break;default:if(String.fromCharCode(e)==u)t+=String.fromCharCode(e);else{this._advance(),n=this._currentChar,t+=String.fromCharCode(this._currentChar),this._advance();continue}}this._jump(2),n=this._currentChar;continue}if(this._currentChar===e&&n!==c.backslash)break;t+=String.fromCharCode(this._currentChar),n=this._currentChar,this._advance()}return new l(i.stringConst,t,o,a)}_skipLineComment(){for(;!this._isLineEnd(this._currentChar)&&this._currentChar!=-1;)this._advance()}_skipComment(){for(;this._currentChar!==-1;){if(this._currentChar===c.star&&this._pick()===c.shebang){this._advance(),this._advance();break}this._advance()}}nextToken(){let e=this._line,t=this._col,n=this._position;for(;this._currentChar!==-1;){if(this._isLineEnd(this._currentChar))return this._line++,this._col=1,this._advance(),new l(i.eol,`
5
+ `,e,t);if(this._isWhiteSpace(this._currentChar)){this._skipWhiteSpace();continue}if(this._currentChar==c.shebang){this._advance(),this._currentChar===c.star?(this._advance(),this._skipComment()):this._skipLineComment();continue}if(this._isDigit(this._currentChar))return this._number();if(this._isIdStart(this._currentChar))return this._id();if(this._currentChar===c.equal)return this._advance(),this._currentChar===c.equal?(this._advance(),new l(i.eqeq,"==",e,t)):new l(i.equal,"=",e,t);if(this._currentChar===c.great)return this._advance(),this._currentChar===c.equal?(this._advance(),new l(i.greatEq,">=",e,t)):new l(i.great,">",e,t);if(this._currentChar===c.less)return this._advance(),this._currentChar===c.equal?(this._advance(),new l(i.lessEq,"<=",e,t)):new l(i.less,"<",e,t);if(this._currentChar===c.semiColon)return this._advance(),new l(i.semi,";",e,t);if(this._currentChar===c.lparen)return this._advance(),new l(i.lparen,"(",e,t);if(this._currentChar===c.rparen)return this._advance(),new l(i.rparen,")",e,t);if(this._currentChar===c.comma)return this._advance(),new l(i.comma,",",e,t);if(this._currentChar===c.lbrace)return this._advance(),new l(i.lbrace,"{",e,t);if(this._currentChar===c.rbrace)return this._advance(),new l(i.rbrace,"}",e,t);if(this._currentChar===c.lbracket)return this._advance(),new l(i.lbracket,"[",e,t);if(this._currentChar===c.rbracket)return this._advance(),new l(i.rbracket,"]",e,t);if(this._currentChar===c.plus)return this._advance(),new l(i.plus,"+",e,t);if(this._currentChar===c.minus)return this._advance(),new l(i.minus,"-",e,t);if(this._currentChar===c.slash)return this._advance(),new l(i.div,"/",e,t);if(this._currentChar===c.star)return this._advance(),new l(i.mult,"*",e,t);if(this._currentChar===c.percent)return this._advance(),new l(i.mod,"%",e,t);if(this._currentChar===c.colon)return this._advance(),new l(i.colon,":",e,t);if(this._currentChar===c.dot)return this._advance(),new l(i.dot,".",e,t);if(this._currentChar===c.not)return this._advance(),this._currentChar===c.equal?(this._advance(),new l(i.notEq,"!=",e,t)):new l(i.not,"!",e,t);if(this._currentChar===c.and&&this._pick()===c.and)return this._advance(),this._advance(),new l(i.and,"&&",e,t);if(this._currentChar===c.pipe&&this._pick()===c.pipe)return this._advance(),this._advance(),new l(i.or,"||",e,t);if(this._currentChar===c.questionMark&&this._pick()===c.questionMark)return this._advance(),this._advance(),new l(i.nullity,"??",e,t);if(this._currentChar===c.quote||this._currentChar===c.squote){let r=this._currentChar;this._advance();let a=this._literalString(r);return this._advance(),a}return new l(i.invalid,String.fromCharCode(this._currentChar),e,t)}return new l(i.eof,"",e,t)}};k._defaultLanguage=new X("en",{if:"if",else:"else",true:"true",false:"false",null:"null",while:"while",for:"for",with:"with",up:"up",down:"down",till:"till",in:"in",break:"break",continue:"continue",return:"return"}),k.languages=[k._defaultLanguage,new X("fr",{si:"if",sinon:"else",vrai:"true",faux:"false",nul:"null",tanque:"while",pour:"for",avec:"with",mont:"up",desc:"down",jusqua:"till",dans:"in",couper:"break",continuer:"continue",returner:"return"}),new X("bm",{nii:"if",note:"else",tien:"true",galon:"false",gansan:"null",foo:"while",seginka:"for",niin:"with",kay:"up",kaj:"down",kata:"till",kono:"in",tike:"break",ipan:"continue",segin:"return"})],k.RESERVED={if:l.from(i.IF,"if"),else:l.from(i.ELSE,"else"),true:l.from(i.TRUE,!0),false:l.from(i.FALSE,!1),null:l.from(i.NULL,null),for:l.from(i.FOR_LOOP,"for"),while:l.from(i.WHILE_TILL,"while"),with:l.from(i.with,"with"),up:l.from(i.up,"up"),down:l.from(i.down,"down"),till:l.from(i.TILL,"till"),in:l.from(i.in,"in"),break:l.from(i.BREAK,"break"),continue:l.from(i.CONTINUE,"continue"),return:l.from(i.RETURN,"return")};var gt=k,m=class{constructor(e,t){this.line=e,this.col=t}dump(){return this.toString()}},S=class s extends Error{constructor(e,t,n,r,a,o){var u;super(s.format(e,t,n,r)),this.name="MEventoRuntimeError",this.detail=e,this.line=t,this.col=n,this.nodeType=r,this.cause=a,this.code=(u=o==null?void 0:o.code)!=null?u:"runtime_error",this.diagnosticName=o==null?void 0:o.name,this.argCount=o==null?void 0:o.argCount,this.minArgs=o==null?void 0:o.minArgs,this.maxArgs=o==null?void 0:o.maxArgs,this.argIndex=o==null?void 0:o.argIndex,this.expectedType=o==null?void 0:o.expectedType,this.actualType=o==null?void 0:o.actualType,this.stepCount=o==null?void 0:o.stepCount,this.maxSteps=o==null?void 0:o.maxSteps}static fromNode(e,t){if(t instanceof s)return t;let n=t instanceof Error?t.message:String(t);return new s(n,e.line,e.col,e.constructor.name,t)}static format(e,t,n,r){let a=t!=null&&n!=null?` at ${t}:${n}`:"",o=r?` [${r}]`:"";return`MEvento runtime error${a}${o}: ${e}`}diagnostic(){return{code:this.code,message:this.detail,line:this.line,col:this.col,node:this.nodeType,name:this.diagnosticName,argCount:this.argCount,minArgs:this.minArgs,maxArgs:this.maxArgs,argIndex:this.argIndex,expectedType:this.expectedType,actualType:this.actualType,stepCount:this.stepCount,maxSteps:this.maxSteps}}};function g(s,e){var r;let t={name:s,minArgs:e==null?void 0:e.minArgs,maxArgs:e==null?void 0:e.maxArgs,tags:e!=null&&e.tags?Array.from(e.tags):[],args:e!=null&&e.args?e.args.map(Vt):[],returnType:(r=e==null?void 0:e.returnType)!=null?r:"any"};if((e==null?void 0:e.description)!=null&&(t.description=e.description),(e==null?void 0:e.returnDescription)!=null&&(t.returnDescription=e.returnDescription),(e==null?void 0:e.examples)!=null&&(t.examples=e.examples.map(Ct)),(e==null?void 0:e.metadata)!=null&&(t.metadata=lt(e.metadata)),t.minArgs!=null&&t.minArgs<0)throw new Error("minArgs must be greater than or equal to 0");if(t.maxArgs!=null&&t.maxArgs<0)throw new Error("maxArgs must be greater than or equal to 0");let n=J(t);if(n!=null&&t.maxArgs!=null&&n>t.maxArgs)throw new Error("minArgs must be less than or equal to maxArgs");if(!bt.has(t.returnType))throw new Error(`Unsupported return type '${t.returnType}'`);return t}function Vt(s){var t,n;let e={name:s.name,type:(t=s.type)!=null?t:"any",required:(n=s.required)!=null?n:!0};if(s.description!=null&&(e.description=s.description),s.metadata!=null&&(e.metadata=lt(s.metadata)),!qt.has(e.type))throw new Error(`Unsupported argument type '${e.type}'`);return e}var bt=new Set(["any","null","boolean","number","string","array","object"]),qt=bt;function jt(s){var t,n;let e={maxSteps:s==null?void 0:s.maxSteps,trace:(t=s==null?void 0:s.trace)!=null?t:!1,compatV1:(n=s==null?void 0:s.compatV1)!=null?n:!1};if(e.maxSteps!=null&&(!Number.isInteger(e.maxSteps)||e.maxSteps<=0))throw new Error("maxSteps must be a positive integer");return e}function wt(s){var t,n;let e={name:s.name,type:(t=s.type)!=null?t:"any",required:(n=s.required)!=null?n:!0};if(!bt.has(e.type))throw new Error(`Unsupported value type '${e.type}'`);return e}function ct(s){return Array.isArray(s)?s.map(ct):s!=null&&typeof s=="object"?Object.fromEntries(Object.entries(s).map(([e,t])=>[e,ct(t)])):s}function lt(s){return s==null?void 0:ct(s)}function Ct(s){let e={script:s.script};return s.title!=null&&(e.title=s.title),s.result!==void 0&&(e.result=ct(s.result)),s.description!=null&&(e.description=s.description),e}function Pt(s){var t;let e={name:s.name,minArgs:s.minArgs,maxArgs:s.maxArgs,tags:s.tags?Array.from(s.tags):[],args:s.args?s.args.map(n=>{let r={name:n.name,type:n.type,required:n.required};return n.description!=null&&(r.description=n.description),n.metadata!=null&&(r.metadata=lt(n.metadata)),r}):[],returnType:(t=s.returnType)!=null?t:"any"};return s.description!=null&&(e.description=s.description),s.returnDescription!=null&&(e.returnDescription=s.returnDescription),s.examples!=null&&(e.examples=s.examples.map(Ct)),s.metadata!=null&&(e.metadata=lt(s.metadata)),e}function Tt(s){return Object.fromEntries(Object.entries(s).map(([e,t])=>[e,Pt(t)]))}function dt(s,e){let t=J(s);return!(t!=null&&e<t||s.maxArgs!=null&&e>s.maxArgs)}function J(s){var n;let e=0;if(s.args){for(let r=s.args.length-1;r>=0;r-=1)if((n=s.args[r].required)==null||n){e=r+1;break}}let t=[s.minArgs,e>0?e:void 0].filter(r=>r!=null);return t.length>0?Math.max(...t):void 0}function _t(s){let e=J(s);return e==null&&s.maxArgs==null?"any number of":e!=null&&s.maxArgs!=null&&e===s.maxArgs?String(e):e!=null&&s.maxArgs!=null?`${e}..${s.maxArgs}`:e!=null?`at least ${e}`:`at most ${s.maxArgs}`}function et(s){return s==null?"null":typeof s=="boolean"?"boolean":typeof s=="number"?"number":typeof s=="string"?"string":Array.isArray(s)?"array":"object"}var q=class extends m{constructor(e,t,n){super(1,1),this.body=e,this.name=t,this.source=n}dump(){let e=`Module ${this.name} Start {`;for(let t of this.body)e+=`${t.dump()}
6
6
  `;return e+="}",e}},F=class extends m{constructor(e,t){super(t.line,t.col),this.body=e}toString(){return`{
7
7
  ${this.body.map(e=>e.toString()).join(`
8
- `)}}`}},x=class extends m{constructor(e){super(e.line,e.col),this.value=e.value.toString()}toString(){return this.value}},A=class extends m{constructor(e,t){super(e.line,e.col),this.value=e.value,this.raw=t}toString(){return this.value.toString()}},L=class extends m{constructor(e,t){super(e.line,e.col),this.identifier=e,this.init=t}toString(){return`${this.identifier} = ${this.init}`}},G=class extends m{constructor(e){super(e.line,e.col),this.expression=e}toString(){return this.expression.toString()}},j=class extends m{constructor(e,t){super(e.line,e.col),this.callee=e,this.arguments=t}toString(){return`${this.callee.toString()}(...${this.arguments.length})`}},P=class extends m{constructor(e,t,n){super(e.line,e.col),this.left=e,this.operation=t,this.right=n}toString(){return`${this.left} ${this.operation} ${this.right}`}},z=class extends m{constructor(e,t){super(e.line,e.col),this.operation=e,this.argument=t}toString(){return`${this.operation} ${this.argument}`}},U=class extends m{constructor(e,t,n){super(e.line,e.col),this.test=e,this.consequent=t,this.alternate=n}toString(){return`if ${this.test} ${this.consequent} ${this.alternate?`else ${this.alternate} `:""}`}},W=class extends m{constructor(e,t,n){super(e.line,e.col),this.left=e,this.operator=t,this.right=n}toString(){return`${this.left} ${this.operator.value} ${this.right}`}},w=class extends m{constructor(t,n,r=!1){super(t.line,t.col);this.computed=!1;this.owner=t,this.key=n,this.computed=r}toString(){return`${this.owner}[${this.key}]`}},I=class extends m{constructor(e,t,n){super(t==null?void 0:t.line,t==null?void 0:t.col),this.properties=e}toString(){return"{...}"}},$=class extends m{constructor(e,t,n){super(t==null?void 0:t.line,t==null?void 0:t.col),this.elements=e}toString(){return"[...]"}},O=class extends m{constructor(e,t){super(e.line,e.col),this.value=t,this.key=e}},B=class extends m{constructor(t,n,r,s,o=!1){super(r==null?void 0:r.line,r==null?void 0:r.col);this.retain=!1;this.test=t,this.body=n,this.retain=o}},D=class extends m{constructor(t,n,r,s,o,u,p,f=!1){super(u==null?void 0:u.line,u==null?void 0:u.col);this.init=t;this.test=n;this.update=r;this.direction=s;this.body=o;this.retain=f}},K=class extends m{constructor(t,n,r,s,o,u=!1){super(s==null?void 0:s.line,s==null?void 0:s.col);this.identifier=t;this.collection=n;this.body=r;this.retain=u}},N=class extends m{constructor(t,n){super(t.line,t.col);this.first=t;this.second=n}},Z=class extends m{constructor(e,t){super(e,t)}},H=class extends m{constructor(e,t,n){super(t,n),this.value=e}},tt=class extends m{constructor(e,t){super(e,t)}};function qt(a){return a instanceof q?"RootAST":a instanceof F?"BlockStatementAST":a instanceof x?"IdentifierAST":a instanceof A?"LiteralAST":a instanceof L?"AssignmentExpressionAST":a instanceof G?"ExpressionStatementAST":a instanceof j?"CallExpressionAST":a instanceof P?"BinaryExpressionAST":a instanceof z?"UnaryExpressionAST":a instanceof U?"IfStatementAST":a instanceof W?"LogicalExpressionAST":a instanceof w?"IndexAccessorAST":a instanceof I?"ObjectExpression":a instanceof O?"ObjectProperty":a instanceof $?"ArrayExpression":a instanceof B?"WhileLoopStatement":a instanceof D?"ForLoopStatement":a instanceof K?"ForOfStatement":a instanceof N?"TupleExpression":a instanceof Z?"BreakAST":a instanceof H?"ReturnAST":a instanceof tt?"ContinueAST":a.constructor.name}var _t=class{constructor(e=1/0){this.capacity=e;this.storage=[]}push(e){if(this.size()===this.capacity)throw Error("Stack has reached max capacity, you cannot add more items");this.storage.push(e)}pop(){return this.storage.pop()}peek(){return this.storage[this.size()-1]}size(){return this.storage.length}get isEmpty(){return this.storage.length===0}},nt=class nt{constructor(e){this._loopTrack=new _t;this.currentToken=e.nextToken(),this.lexer=e}_eat(e){var t;((t=this.currentToken)==null?void 0:t.type)===e?this.currentToken=this.lexer.nextToken():T(this.currentToken,e)}_eatEOL(){var e;for(;((e=this.currentToken)==null?void 0:e.type)===i.eol;)this._eat(i.eol)}_eatSemiOrEOL(){var e,t;for(;((e=this.currentToken)==null?void 0:e.type)===i.eol||((t=this.currentToken)==null?void 0:t.type)===i.semi;)this._eat(this.currentToken.type)}_eatSemi(){var e;for(;((e=this.currentToken)==null?void 0:e.type)===i.semi;)this._eat(i.semi)}_variable(){let e=new x(this.currentToken);return this._eat(i.id),e}_return(){let e=this.currentToken,t;return!this._expect(i.eol)&&!this._expect(i.semi)&&(t=this._expression()),new H(t,e==null?void 0:e.line,e==null?void 0:e.col)}_factor(){let e=this.currentToken;switch(e.type){case i.plus:case i.minus:case i.not:return this._eat(this.currentToken.type),new z(e,this._term());case i.numberConst:return this._eat(i.numberConst),new A(e,e.value.toString());case i.stringConst:return this._eat(i.stringConst),new A(e,e.value.toString());case i.lparen:this._eat(i.lparen);let t=this._expression();return this._eat(i.rparen),t;case i.TRUE:case i.FALSE:return this._eat(this.currentToken.type),new A(e,e.value.toString());case i.NULL:return this._eat(i.NULL),new A(e,"null");case i.lbracket:return this._arrayExpression();case i.lbrace:return this._objectExpression();case i.IF:return this._ifStatement();case i.WHILE_TILL:return this._whileLoop(!0);case i.FOR_LOOP:return this._forLoop(!0);case i.BREAK:return this._breakExpression();case i.CONTINUE:return this._continueExpression();default:return this._variable()}}_breakExpression(){var e,t;return this._loopTrack.isEmpty&&T(this.currentToken),this._eat(i.BREAK),new Z((e=this.currentToken)==null?void 0:e.line,(t=this.currentToken)==null?void 0:t.col)}_continueExpression(){var e,t;return this._loopTrack.isEmpty&&T(this.currentToken),this._eat(i.CONTINUE),new tt((e=this.currentToken)==null?void 0:e.line,(t=this.currentToken)==null?void 0:t.col)}_term(){let e=this._factor();return e=this._tryParsingFunctionCall(e),e=this._tryParsingMemberExpression(e),e}_expression(){let e=this._term();for(e=this._tryBinaryExpression(0,e);[i.and,i.or,i.nullity].includes(this.currentToken.type);){let t=this.currentToken;this._eat(t.type),e=new W(e,t,this._expression())}if(this._expect(i.equal))if(e instanceof x||e instanceof w){let t=this.currentToken;this._eat(i.equal),e=new L(e,this._expression())}else throw new Error("Unexpected token");return e}_objectProperty(){var r;let e;switch((r=this.currentToken)==null?void 0:r.type){case i.stringConst:{e=new A(this.currentToken,this.currentToken.value),this._eat(i.stringConst);break}case i.lbracket:{this._eat(i.lbracket);var t=this._expression();this._eat(i.rbracket),e=t;break}case i.id:{let s=this._variable();e=new A(new l(i.id,s.value,s.line,s.col),s.value);break}default:throw`Unexpected token ${this.currentToken}`}this._eat(i.colon);var n=this._expression();return new O(e,n)}_property(){return this._objectProperty()}_objectProperties(){var t,n;let e=[];for(((t=this.currentToken)==null?void 0:t.type)!=i.rbrace&&(this._eatEOL(),e.push(this._property()),this._eatEOL());((n=this.currentToken)==null?void 0:n.type)===i.comma&&(this._eat(i.comma),this._eatEOL(),!this._expect(i.rbrace));)e.push(this._property()),this._eatEOL();return e}_objectExpression(e){var t=e!=null?e:this.currentToken;e||this._eat(i.lbrace);var n=this._objectProperties();return this._eat(i.rbrace),new I(n,t,this.currentToken)}_arrayExpression(){this._eat(i.lbracket);let e=this._expect(i.rbracket)?[]:this._expressionsList();this._eat(i.rbracket);var t=e.length!==0?e[0]:void 0,n=e.length!==0?e[e.length-1]:void 0;return new $(e,t,n)}_tryParsingMemberExpression(e){let t=e;for(;this.currentToken.type===i.lbracket||this.currentToken.type===i.dot;)if(this.currentToken.type===i.lbracket){this._eat(i.lbracket);let n=this._expression();t=new w(t,n,!0),this._eat(i.rbracket)}else{this._eat(i.dot);let n=this.currentToken;n.type!==i.id&&T(n);let r=new A(new l(i.stringConst,n.value,n.line,n.col),n.value);this._eat(i.id),t=new w(t,r)}return t}_tryBinaryExpression(e,t){let n=t;for(;;){let r=nt._binopPrecdences[this.currentToken.type]||-1;if(r<e)return n;let s=this.currentToken;this._eat(s.type);let o=this._term(),u=nt._binopPrecdences[this.currentToken.type]||-1;if(r<u){let p=this._tryBinaryExpression(r+1,o);if(p===n)return p;o=p}n=new P(n,s,o)}}_expressionsList(){var n;this._eatEOL();let e=this._expression();this._eatEOL();let t=[e];for(;((n=this.currentToken)==null?void 0:n.type)===i.comma&&(this._eat(i.comma),this._eatEOL(),!this._expect(i.rbracket));)e=this._expression(),t.push(e),this._eatEOL();return t}_callExpression(e){this._eat(i.lparen);let t=[];return this._expect(i.rparen)||(t=this._expressionsList()),this._eat(i.rparen),e instanceof x||T(this.currentToken),new j(e,t)}_tryParsingFunctionCall(e){let t=e;for(;this.currentToken.type===i.lparen;)t=this._callExpression(t);return t}_statementExpression(){let e=this._expression();return[i.semi,i.eol,i.eof].includes(this.currentToken.type)||T(this.currentToken),e}_blockStatement(e=!1){var n;if(e||this._eat(i.lbrace),this._eatEOL(),this._expect(i.rbrace))return this._eat(i.rbrace),new F([],this.currentToken);let t=[this._statement()];for(;this._eatSemiOrEOL(),!(this.currentToken.type===i.rbrace||this.currentToken.type===i.eof||(t.push(this._statement()),this._expect(i.rbrace)));)this.currentToken.type!==i.eol&&this.currentToken.type!==i.semi&&this.currentToken.type!==i.eof&&T(this.currentToken);return this._eat(i.rbrace),((n=this.currentToken)==null?void 0:n.type)===i.rbrace&&this._eat(i.rbrace),new F(t,this.currentToken)}_ifStatement(){this._eat(i.IF);let e=this.currentToken.type===i.lparen;e&&this._eat(i.lparen);let t=this._expression();e&&this._eat(i.rparen);let n;this.currentToken.type===i.lbrace?n=this._blockStatement():n=this._expression();let r;if(this.currentToken.type===i.ELSE)switch(this._eat(i.ELSE),this.currentToken.type){case i.IF:r=this._ifStatement();break;case i.lbrace:r=this._blockStatement();break;default:r=this._expression()}return new U(t,n,r)}_pushLoop(){this._loopTrack.push(!0)}_popLoop(){this._loopTrack.pop()}_whileLoop(e=!1){let t=this.currentToken;this._eat(i.WHILE_TILL),this._pushLoop();let n=this._expression(),r=this.currentToken.type===i.lbrace?this._blockStatement():this._expression();return this._popLoop(),new B(n,r,t,this.currentToken,e)}_forOfIdentifier(){switch(this.currentToken.type){case i.lparen:{this._eat(i.lparen);let e=this._variable();this._eat(i.comma);let t=this._variable();return this._eat(i.rparen),new N(e,t)}default:return this._variable()}}_forLoop(e=!1){let t=this.currentToken;this._eat(i.FOR_LOOP),this._pushLoop();let n=[i.lparen].includes(this.currentToken.type),r;if(n)r=this._forOfIdentifier();else{let s=this._expression();s instanceof L||(n=!0),r=s}if(!n&&r instanceof L){this._eat(i.TILL);let s=this._expression(),o;if(this.currentToken.type===i.up||this.currentToken.type===i.down){let f=this.currentToken;this._eat(f.type),o=f}else o=new l(i.up,"up");let u;this._expect(i.with)?(this._eat(i.with),u=this._expression()):u=new A(new l(i.numberConst,1,this.currentToken.line,this.currentToken.col),"1");let p=this.currentToken.type===i.lbrace?this._blockStatement():this._expression();r=new D(r,s,u,o,p,t,this.currentToken,e),this._popLoop()}else if(n){this._eat(i.in);let s=this._expression(),o=this.currentToken.type===i.lbrace?this._blockStatement():this._expression();r=new K(r,s,o,t,this.currentToken,e),this._popLoop()}else T(this.currentToken);return r}_statement(){switch(this.currentToken.type){case i.BREAK:return this._breakExpression();case i.CONTINUE:return this._continueExpression();case i.RETURN:return this._eat(i.RETURN),this._return();case i.semi:return this._eatSemi(),this._statement();case i.eol:return this._eatEOL(),this._statement();case i.WHILE_TILL:return this._whileLoop();case i.FOR_LOOP:return this._forLoop();default:return this._statementExpression()}}_expect(e){var t;return((t=this.currentToken)==null?void 0:t.type)===e}_definition(){if(this._eatSemiOrEOL(),this._expect(i.eof))return[];let e=[this._statement()];for(;;){if(this._eatSemiOrEOL(),this.currentToken.type===i.eof){this._eat(i.eof);break}this.currentToken.type===i.lbrace?e.push(this._blockStatement()):e.push(this._statement())}return e}_root(){let e=this.lexer.source,t="<module>",n=this._definition();return new q(n,t,e)}parse(){return this._root()}};nt._binopPrecdences={[i.eqeq]:10,[i.notEq]:10,[i.great]:10,[i.greatEq]:10,[i.less]:10,[i.lessEq]:10,[i.plus]:20,[i.minus]:20,[i.mult]:40,[i.div]:40,[i.mod]:40};var dt=nt,R=class{},C=class extends R{},M=class extends R{},y=class{constructor(e){this.value=e}},St=class{constructor(){this._nodesVisitors={}}registerVisitor(e,t){let n=`visit${e.name}`;this._nodesVisitors[n]=t}},ct=class extends St{constructor(){super(),this.registerVisitor(q,this.visitRootAST),this.registerVisitor(F,this.visitBlockStatementAST),this.registerVisitor(x,this.visitIdentifierAST),this.registerVisitor(A,this.visitLiteralAST),this.registerVisitor(L,this.visitAssignmentExpressionAST),this.registerVisitor(G,this.visitExpressionStatementAST),this.registerVisitor(j,this.visitCallExpressionAST),this.registerVisitor(P,this.visitBinaryExpressionAST),this.registerVisitor(z,this.visitUnaryExpressionAST),this.registerVisitor(U,this.visitIfStatementAST),this.registerVisitor(W,this.visitLogicalExpressionAST),this.registerVisitor(w,this.visitIndexAccessorAST),this.registerVisitor(O,this.visitObjectProperty),this.registerVisitor(I,this.visitObjectExpression),this.registerVisitor($,this.visitArrayExpression),this.registerVisitor(B,this.visitWhileLoopStatement),this.registerVisitor(D,this.visitForLoopStatement),this.registerVisitor(K,this.visitForOfStatement),this.registerVisitor(Z,this.visitBreakAST),this.registerVisitor(tt,this.visitContinueAST),this.registerVisitor(H,this.visitReturnAST)}visit(e){this.beforeVisit(e);let t=`visit${e.constructor.name}`,n=this._nodesVisitors[t];if(!n)throw new S(`No ${t} declared`,e.line,e.col,e.constructor.name);try{let r=n.call(this,e);return r&&typeof r.then=="function"?r.catch(s=>{throw S.fromNode(e,s)}):r!=null?r:null}catch(r){throw S.fromNode(e,r)}}beforeVisit(e){}assignProperty(e,t,n){(Array.isArray(e)||typeof e=="object")&&(e[t]=n)}},rt=class{constructor(e,t,n){this.memory={};this.name=e,this.memory=t,this.parent=n}resolve(e){var t,n;return Object.keys(this.memory).includes(e)?this.memory[e]:(n=(t=this.parent)==null?void 0:t.resolve(e))!=null?n:null}change(e,t,n=!0){return Object.keys(this.memory).includes(e)?(this.memory[e]=t,!0):this.parent&&this.parent.change(e,t,!1)?!0:n?(this.memory[e]=t,!0):!1}},st={_ok_:g("_ok_",{name:"_ok_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"boolean"}),_err_:g("_err_",{name:"_err_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"boolean"}),_value_:g("_value_",{name:"_value_",minArgs:1,maxArgs:2,args:[{name:"result"},{name:"fallback",required:!1}],returnType:"any"}),_error_:g("_error_",{name:"_error_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"object"}),_code_:g("_code_",{name:"_code_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"string"}),_message_:g("_message_",{name:"_message_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"string"}),_unwrap_:g("_unwrap_",{name:"_unwrap_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"any"}),_len_:g("_len_",{name:"_len_",minArgs:1,maxArgs:1,args:[{name:"target"}],returnType:"number"}),_push_:g("_push_",{name:"_push_",minArgs:2,maxArgs:2,args:[{name:"array",type:"array"},{name:"value"}],returnType:"array"}),_pop_:g("_pop_",{name:"_pop_",minArgs:1,maxArgs:1,args:[{name:"array",type:"array"}],returnType:"any"}),_insert_:g("_insert_",{name:"_insert_",minArgs:3,maxArgs:3,args:[{name:"array",type:"array"},{name:"index",type:"number"},{name:"value"}],returnType:"array"}),_remove_at_:g("_remove_at_",{name:"_remove_at_",minArgs:2,maxArgs:2,args:[{name:"array",type:"array"},{name:"index",type:"number"}],returnType:"any"}),_has_:g("_has_",{name:"_has_",minArgs:2,maxArgs:2,args:[{name:"object",type:"object"},{name:"key"}],returnType:"boolean"}),_keys_:g("_keys_",{name:"_keys_",minArgs:1,maxArgs:1,args:[{name:"object",type:"object"}],returnType:"array"}),_values_:g("_values_",{name:"_values_",minArgs:1,maxArgs:1,args:[{name:"object",type:"object"}],returnType:"array"})};function at(a){return typeof a=="object"&&a!=null&&a.ok===!0}function ut(a){if(typeof a!="object"||a==null)return;let e=a;if(!(e.ok!==!1||typeof e.error!="object"||e.error==null))return e.error}function V(a){return typeof a=="number"?a:void 0}function Q(a){return typeof a=="string"?a:void 0}function jt(a){var t,n;let e=ut(a);return new S((t=Q(e==null?void 0:e.message))!=null?t:"Cannot unwrap failed _try_ result",V(e==null?void 0:e.line),V(e==null?void 0:e.col),Q(e==null?void 0:e.node),void 0,{code:(n=Q(e==null?void 0:e.code))!=null?n:"invalid_try_result",name:Q(e==null?void 0:e.name),argCount:V(e==null?void 0:e.argCount),minArgs:V(e==null?void 0:e.minArgs),maxArgs:V(e==null?void 0:e.maxArgs),argIndex:V(e==null?void 0:e.argIndex),expectedType:Q(e==null?void 0:e.expectedType),actualType:Q(e==null?void 0:e.actualType),stepCount:V(e==null?void 0:e.stepCount),maxSteps:V(e==null?void 0:e.maxSteps)})}function ht(a,e,t,n){let r=et(n);return new S(`Function '${a}' argument ${e} expects ${t}, got ${r}`,void 0,void 0,void 0,void 0,{code:"invalid_argument_type",name:a,argIndex:e,expectedType:t,actualType:r})}function ot(a,e,t){let n=e[t];if(Array.isArray(n))return n;throw ht(a,t,"array",n)}function ft(a,e,t){let n=e[t];if(typeof n=="object"&&n!=null&&!Array.isArray(n))return n;throw ht(a,t,"object",n)}function wt(a,e,t){let n=e[t];if(typeof n=="number")return Math.trunc(n);throw ht(a,t,"number",n)}function Pt(a,e,t){return new S(`Function '${a}' index ${e} is out of range for array of length ${t}`,void 0,void 0,void 0,void 0,{code:"index_out_of_range",name:a})}var zt={_ok_:a=>at(a[0]),_err_:a=>!at(a[0]),_value_:a=>{var e,t;return at(a[0])?(e=a[0].value)!=null?e:null:(t=a[1])!=null?t:null},_error_:a=>{var e;return(e=ut(a[0]))!=null?e:null},_code_:a=>{var e,t;return(t=(e=ut(a[0]))==null?void 0:e.code)!=null?t:null},_message_:a=>{var e,t;return(t=(e=ut(a[0]))==null?void 0:e.message)!=null?t:null},_unwrap_:a=>{var e;if(at(a[0]))return(e=a[0].value)!=null?e:null;throw jt(a[0])},_len_:a=>{let e=a[0];if(Array.isArray(e)||typeof e=="string")return e.length;if(typeof e=="object"&&e!=null)return Object.keys(e).length;throw ht("_len_",0,"array|object|string",e)},_push_:a=>{var t;let e=ot("_push_",a,0);return e.push((t=a[1])!=null?t:null),e},_pop_:a=>{var t;let e=ot("_pop_",a,0);return e.length===0?null:(t=e.pop())!=null?t:null},_insert_:a=>{var n;let e=ot("_insert_",a,0),t=wt("_insert_",a,1);if(t<0||t>e.length)throw Pt("_insert_",t,e.length);return e.splice(t,0,(n=a[2])!=null?n:null),e},_remove_at_:a=>{var n;let e=ot("_remove_at_",a,0),t=wt("_remove_at_",a,1);return t<0||t>=e.length?null:(n=e.splice(t,1)[0])!=null?n:null},_has_:a=>Object.prototype.hasOwnProperty.call(ft("_has_",a,0),a[1]),_keys_:a=>Object.keys(ft("_keys_",a,0)),_values_:a=>Object.values(ft("_values_",a,0))},d=class d extends ct{constructor(t){super();this.rootScope=new rt("Program",{});this.currentScope=this.rootScope;this.debug=!1;this._functionsRegistry={};this._functionSpecs={};this._executionStepCount=0;this._traceEvents=[];this._options=Rt(t),this._functionsRegistry={...zt,...d._globalFunctionsRegistry},this._functionSpecs={...st,...d._globalFunctionSpecs}}get options(){return{...this._options}}get executionStepCount(){return this._executionStepCount}trace(){return this._traceEvents.map(t=>({...t,detail:{...t.detail}}))}resetExecutionBudget(){this._executionStepCount=0}beforeVisit(t){this._executionStepCount+=1,this.recordTrace("visit",t);let n=this._options.maxSteps;if(n!=null&&this._executionStepCount>n)throw new S(`Execution budget exceeded after ${this._executionStepCount} step(s)`,t.line,t.col,t.constructor.name,void 0,{code:"execution_budget_exceeded",stepCount:this._executionStepCount,maxSteps:n})}clearTrace(){this._traceEvents=[]}recordTrace(t,n,r,s={}){this._options.trace&&this._traceEvents.push({kind:t,line:n.line,col:n.col,node:qt(n),name:r,stepCount:this._executionStepCount,detail:s})}resolve(t){var n,r;return(r=(n=this.currentScope)==null?void 0:n.resolve(t))!=null?r:null}changeVariable(t,n){var r;return(r=this.currentScope)!=null&&r.change(t,n)?n:null}pushScope(t){let n=new rt(t,{},this.currentScope);this.currentScope=n}popScope(){var t;this.currentScope=(t=this.currentScope)==null?void 0:t.parent}log(t){this.debug&&console.log(t)}successResult(t){return{ok:!0,value:t,error:null}}errorResult(t){return{ok:!1,value:null,error:t.diagnostic()}}visitRootAST(t){var s;let n=t.body,r;for(let o of n)if(r=this.visit(o),r instanceof y)return(s=r.value)!=null?s:null;return r!=null?r:null}visitBlockStatementAST(t){let n=t.body,r;this.pushScope("Block");for(let s of n)if(r=this.visit(s),r instanceof R||r instanceof y)break;return this.popScope(),r!=null?r:null}visitIdentifierAST(t){var r;let n=t.value;return(r=this==null?void 0:this.resolve(n))!=null?r:null}visitLiteralAST(t){return t.value}visitAssignmentExpressionAST(t){let n=t.identifier,r=t.init,s=null;if(n instanceof w){var o=this.visit(n.owner);s=this.visit(t.init);var u=this.visit(n.key);this.assignProperty(o,u,s)}else n instanceof x&&(s=this.visit(r),this.changeVariable(n.value,s));return s}visitExpressionStatementAST(t){let n=t.expression;return this.visit(n)}visitCallExpressionAST(t){var v,_;let n=t.callee,r=t.arguments,s=n.value;if(s==="_try_"){if(r.length!==1)throw new S("_try_ expects exactly one expression",t.line,t.col,t.constructor.name,void 0,{code:"invalid_try_arity",name:"_try_",argCount:r.length,minArgs:1,maxArgs:1});try{let E=this.visit(r[0]);return E instanceof R||E instanceof y?E:this.successResult(E)}catch(E){if(E instanceof S)return this.errorResult(E);throw E}}let o=this.resolveFunction(s);if(!o){if(this._options.compatV1)return null;throw new S(`Unknown function '${s}'`,t.line,t.col,t.constructor.name,void 0,{code:"unknown_function",name:s})}let u=this.resolveFunctionSpec(s);if(u&&!vt(u,r.length))throw new S(`Function '${s}' expects ${gt(u)} argument(s), got ${r.length}`,t.line,t.col,t.constructor.name,void 0,{code:"invalid_function_arity",name:s,argCount:r.length,minArgs:J(u),maxArgs:u.maxArgs});let p=r.map(E=>this.visit(E));u&&this.validateRuntimeArgumentTypes(t,u,p),this.recordTrace("call",t,s,{argCount:p.length,returnType:(v=u==null?void 0:u.returnType)!=null?v:"any"});let f=o(p,this);return this.recordTrace("call_result",t,s,{returnType:(_=u==null?void 0:u.returnType)!=null?_:"any",actualType:et(f)}),f}visitBinaryExpressionAST(t){let n=t.left,r=t.right,s=t.operation,o=this.visit(n),u=this.visit(r);switch(s.type){case i.plus:return h(o)&&h(u)?o+u:`${o}${u}`;case i.minus:if(h(o)&&h(u))return o-u;throw new Error(`Operation ${s.value} not allowed no num value`);case i.mult:if(h(o)&&h(u))return o*u;if(Y(o)&&h(u))return o.repeat(u);if(h(o)&&Y(u))return u.repeat(o);throw new Error(`Operation ${s.value} not allowed no num value`);case i.div:if(h(o)&&h(u)){if(u===0)throw new Error("Invalid division by 0");return o/u}throw new Error(`Operation ${s.value} not allowed no num value`);case i.mod:if(h(o)&&h(u))return o%u;throw new Error(`Operation ${s.value} not allowed no num value`);case i.great:if(h(o)&&h(u))return o>u;throw new Error(`Operation ${s.value} not allowed no num value`);case i.greatEq:if(h(o)&&h(u))return o>=u;throw new Error(`Operation ${s.value} not allowed no num value`);case i.less:if(h(o)&&h(u))return o<u;throw new Error(`Operation ${s.value} not allowed no num value`);case i.lessEq:if(h(o)&&h(u))return o<=u;throw new Error(`Operation ${s.value} not allowed no num value`);case i.eqeq:return o===u;case i.notEq:return o!==u;default:throw new Error(`Operation ${s.value} not allowed no num value`)}}visitUnaryExpressionAST(t){let n=t.argument,r=t.operation,s=this.visit(n);if(r.type===i.not)return b(s)===!1;if(!h(s))throw new Error(`Operation ${r.value} not allowed no num value`);if(r.type===i.plus)return s;if(r.type===i.minus)return-s;throw new Error(`Operation ${r.value} not allowed no num value`)}visitIfStatementAST(t){let n=t.test,r=this.visit(n);return b(r)?this.visit(t.consequent):t.alternate?this.visit(t.alternate):null}visitLogicalExpressionAST(t){let n=t.left,r=this.visit(n);if(t.operator.type===i.nullity)return r!=null?r:this.visit(t.right);let s=b(r);return t.operator.type===i.and?s?b(this.visit(t.right)):!1:t.operator.type===i.or?s?!0:b(this.visit(t.right)):null}visitIndexAccessorAST(t){var s,o;let n=t.owner,r=this.visit(n);if(r==null)return null;if(Array.isArray(r)){let u=this.visit(t.key);return h(u)&&Number.isInteger(u)&&r.length>u&&u>=0&&(s=r[u])!=null?s:null}else if(typeof r=="object"){let u=this.visit(t.key);return(o=r[u])!=null?o:null}return null}visitObjectProperty(t){}visitObjectExpression(t){let n={},r=t;for(let s of r.properties)if(s instanceof O){let o=this.visit(s.key);o=Y(o)?o:o.toString(),n[o]=this.visit(s.value)}return n}visitArrayExpression(t){let n=t;return this.resolveArguments(n.elements)}visitBreakAST(t){return new C}visitWhileLoopStatement(t){this.log(`WhileLoopStatement ${t.test} ${t.body}`);let n=t.retain?[]:void 0;for(;b(this.visit(t.test));){let r=this.visit(t.body);if(r instanceof C)break;if(!(r instanceof M)){if(r instanceof y)return this.popScope(),r;n==null||n.push(r)}}return n!=null?n:null}visitForLoopStatement(t){let n=t.retain?[]:void 0,r=t.init.identifier;if(!(r instanceof x))throw new Error("Unexpected identifer found");this.pushScope("ForLoopStatement");let s=this.visit(t.init.init);this.changeVariable(r.value,s);let o=()=>{let p=this.visit(t.test);if(h(p)){let f=this.resolve(r.value);return t.direction.type===i.up?p>=f:p<=f}return b(p)},u=()=>{let p=this.visit(t.update);if(h(p)){let f=this.resolve(r.value);if(!h(f))throw Error("Cant update value");this.changeVariable(r.value,t.direction.type===i.up?f+p:f-p)}else throw Error("Update value cant be non number")};for(;o();){let p=this.visit(t.body);if(p instanceof C)break;if(p instanceof M){u();continue}if(p instanceof y)return this.popScope(),p;n==null||n.push(p),u()}return this.popScope(),n!=null?n:null}visitForOfStatement(t){let n=this.visit(t.collection);if(!Array.isArray(n))throw Error("Can iterate non array object");let r=t.retain?[]:void 0;this.pushScope("ForOfStatement");for(let s of n){this._declareForIdentifier(t.identifier,s);let o=this.visit(t.body);if(o instanceof C)break;if(!(o instanceof M)){if(o instanceof y)return this.popScope(),o;r==null||r.push(o)}}return this.popScope(),r!=null?r:null}visitContinueAST(t){return new M}visitReturnAST(t){return new y(t.value!=null?this.visit(t.value):null)}_declareForIdentifier(t,n){if(t instanceof N){if(!Array.isArray(n))throw Error("Unable to make a tuple from non Array element");this.changeVariable(t.first.value,n[0]),this.changeVariable(t.second.value,n[1])}this.changeVariable(t.value,n)}resolveArguments(t){return t.map(n=>this.visit(n))}setFunctionResolver(t){this._functionResolver=t}resolveFunction(t){var n,r;return(r=this._functionsRegistry[t])!=null?r:(n=this._functionResolver)==null?void 0:n.call(this,t)}resolveFunctionSpec(t){return this._functionSpecs[t]}capabilities(){return Et(this._functionSpecs)}registerFunction(t,n,r){this._functionsRegistry[t]=n,this._functionSpecs[t]=g(t,r)}unregisterFunction(t){delete this._functionsRegistry[t],delete this._functionSpecs[t]}validate(t,n,r=!1){let s=[],o=this.validationFunctionSpecs(n);try{this.validateNode(d.compile(t,r),o,s)}catch(u){s.push({code:"syntax_error",message:u instanceof Error?u.message:String(u)})}return{ok:s.length===0,errors:s}}validateManifest(t,n,r=!1){let s=[],o=this.validationFunctionSpecs(n.functions);try{let u=d.compile(t,r);this.validateNode(u,o,s),this.validateManifestNode(u,n,s)}catch(u){s.push({code:"syntax_error",message:u instanceof Error?u.message:String(u)})}return{ok:s.length===0,errors:s}}validationFunctionSpecs(t){let n=new Map;return Object.keys(st).forEach(r=>{var s;return n.set(r,(s=this._functionSpecs[r])!=null?s:st[r])}),t==null?(Object.keys(this._functionSpecs).forEach(r=>n.set(r,this._functionSpecs[r])),n):t instanceof Set?(t.forEach(r=>{var s;return n.set(r,(s=this._functionSpecs[r])!=null?s:g(r))}),n):Array.isArray(t)?(t.forEach(r=>{var s;typeof r=="string"?n.set(r,(s=this._functionSpecs[r])!=null?s:g(r)):n.set(r.name,g(r.name,r))}),n):(Object.keys(t).forEach(r=>n.set(r,g(r,t[r]))),n)}validateNode(t,n,r,s=!1){t&&(t instanceof q||t instanceof F?t.body.forEach(o=>this.validateNode(o,n,r,s)):t instanceof L?(this.validateNode(t.identifier,n,r,s),this.validateNode(t.init,n,r,s)):t instanceof G?this.validateNode(t.expression,n,r,s):t instanceof j?this.validateCallExpression(t,n,r,s):t instanceof P?(this.validateNode(t.left,n,r,s),this.validateNode(t.right,n,r,s)):t instanceof z?this.validateNode(t.argument,n,r,s):t instanceof U?(this.validateNode(t.test,n,r,s),this.validateNode(t.consequent,n,r,s),this.validateNode(t.alternate,n,r,s)):t instanceof W?(this.validateNode(t.left,n,r,s),this.validateNode(t.right,n,r,s)):t instanceof w?(this.validateNode(t.owner,n,r,s),this.validateNode(t.key,n,r,s)):t instanceof I?t.properties.forEach(o=>this.validateNode(o,n,r,s)):t instanceof O?(this.validateNode(t.key,n,r,s),this.validateNode(t.value,n,r,s)):t instanceof $?t.elements.forEach(o=>this.validateNode(o,n,r,s)):t instanceof B?(this.validateNode(t.test,n,r,s),this.validateNode(t.body,n,r,s)):t instanceof D?(this.validateNode(t.init,n,r,s),this.validateNode(t.test,n,r,s),this.validateNode(t.update,n,r,s),this.validateNode(t.body,n,r,s)):t instanceof K?(this.validateNode(t.identifier,n,r,s),this.validateNode(t.collection,n,r,s),this.validateNode(t.body,n,r,s)):t instanceof N?(this.validateNode(t.first,n,r,s),this.validateNode(t.second,n,r,s)):t instanceof H&&this.validateNode(t.value,n,r,s))}validateCallExpression(t,n,r,s){let o=t.callee.value;if(o==="_try_"){t.arguments.length!==1&&r.push(this.validationError("invalid_try_arity",t,"_try_ expects exactly one expression","_try_",{argCount:t.arguments.length,minArgs:1,maxArgs:1})),t.arguments.forEach(u=>this.validateNode(u,n,r,!0));return}if(!s){let u=n.get(o);u?vt(u,t.arguments.length)?this.validateStaticArgumentTypes(t,u,r):r.push(this.validationError("invalid_function_arity",t,`Function '${o}' expects ${gt(u)} argument(s), got ${t.arguments.length}`,o,{argCount:t.arguments.length,minArgs:J(u),maxArgs:u.maxArgs})):this._options.compatV1||r.push(this.validationError("unknown_function",t,`Unknown function '${o}'`,o))}t.arguments.forEach(u=>this.validateNode(u,n,r,s))}validateStaticArgumentTypes(t,n,r){var s;(s=n.args)==null||s.forEach((o,u)=>{var v,_;let p=t.arguments[u];if(!p)return;let f=this.staticArgumentType(p);!f||this.argumentTypeMatches(o,f)||r.push(this.validationError("invalid_argument_type",t,`Function '${n.name}' argument ${u} expects ${(v=o.type)!=null?v:"any"}, got ${f}`,n.name,{argIndex:u,expectedType:(_=o.type)!=null?_:"any",actualType:f}))})}staticArgumentType(t){if(t instanceof A)return et(t.value);if(t instanceof $)return"array";if(t instanceof I)return"object"}argumentTypeMatches(t,n){var s;let r=(s=t.type)!=null?s:"any";return r==="any"||t.required===!1&&n==="null"?!0:r===n}validateManifestNode(t,n,r){var p,f;let s=((p=n.inputs)!=null?p:[]).map(xt),o=((f=n.outputs)!=null?f:[]).map(xt),u={knownInputs:new Set(s.map(v=>v.name)),assigned:new Set,assignedTypes:new Map,reportedInputs:new Set};this.analyzeManifestNode(t,u,r),o.forEach(v=>{var E,At,bt;if(((E=v.required)==null||E)&&!u.assigned.has(v.name)){r.push(this.validationError("missing_output",t,`Required output '${v.name}' is not assigned`,v.name));return}let _=u.assignedTypes.get(v.name);!_||this.valueSpecTypeMatches(v,_)||r.push(this.validationError("invalid_output_type",t,`Output '${v.name}' expects ${(At=v.type)!=null?At:"any"}, got ${_}`,v.name,{expectedType:(bt=v.type)!=null?bt:"any",actualType:_}))})}analyzeManifestNode(t,n,r){t&&(t instanceof q||t instanceof F?t.body.forEach(s=>this.analyzeManifestNode(s,n,r)):t instanceof L?(this.analyzeManifestNode(t.init,n,r),t.identifier instanceof w&&this.analyzeManifestNode(t.identifier,n,r),this.markAssignedTarget(t.identifier,this.staticArgumentType(t.init),n)):t instanceof G?this.analyzeManifestNode(t.expression,n,r):t instanceof j?t.arguments.forEach(s=>this.analyzeManifestNode(s,n,r)):t instanceof P?(this.analyzeManifestNode(t.left,n,r),this.analyzeManifestNode(t.right,n,r)):t instanceof z?this.analyzeManifestNode(t.argument,n,r):t instanceof U?(this.analyzeManifestNode(t.test,n,r),this.analyzeManifestNode(t.consequent,n,r),this.analyzeManifestNode(t.alternate,n,r)):t instanceof W?(this.analyzeManifestNode(t.left,n,r),this.analyzeManifestNode(t.right,n,r)):t instanceof w?(this.analyzeManifestNode(t.owner,n,r),this.analyzeManifestNode(t.key,n,r)):t instanceof I?t.properties.forEach(s=>this.analyzeManifestNode(s,n,r)):t instanceof O?(this.analyzeManifestNode(t.key,n,r),this.analyzeManifestNode(t.value,n,r)):t instanceof $?t.elements.forEach(s=>this.analyzeManifestNode(s,n,r)):t instanceof B?(this.analyzeManifestNode(t.test,n,r),this.analyzeManifestNode(t.body,n,r)):t instanceof D?(this.analyzeManifestNode(t.init,n,r),this.analyzeManifestNode(t.test,n,r),this.analyzeManifestNode(t.body,n,r),this.analyzeManifestNode(t.update,n,r)):t instanceof K?(this.analyzeManifestNode(t.collection,n,r),this.markAssignedTarget(t.identifier,void 0,n),this.analyzeManifestNode(t.body,n,r)):t instanceof N?(this.analyzeManifestNode(t.first,n,r),this.analyzeManifestNode(t.second,n,r)):t instanceof H?this.analyzeManifestNode(t.value,n,r):t instanceof x&&!n.knownInputs.has(t.value)&&!n.assigned.has(t.value)&&!n.reportedInputs.has(t.value)&&(n.reportedInputs.add(t.value),r.push(this.validationError("unknown_input",t,`Unknown input '${t.value}'`,t.value))))}markAssignedTarget(t,n,r){t instanceof x?(r.assigned.add(t.value),n&&r.assignedTypes.set(t.value,n)):t instanceof N&&(this.markAssignedTarget(t.first,void 0,r),this.markAssignedTarget(t.second,void 0,r))}valueSpecTypeMatches(t,n){var s;let r=(s=t.type)!=null?s:"any";return r==="any"||t.required===!1&&n==="null"?!0:r===n}validationError(t,n,r,s,o){return{code:t,message:r,name:s,line:n.line,col:n.col,node:n.constructor.name,argCount:o==null?void 0:o.argCount,minArgs:o==null?void 0:o.minArgs,maxArgs:o==null?void 0:o.maxArgs,argIndex:o==null?void 0:o.argIndex,expectedType:o==null?void 0:o.expectedType,actualType:o==null?void 0:o.actualType}}validateRuntimeArgumentTypes(t,n,r){var s;(s=n.args)==null||s.forEach((o,u)=>{var f,v;if(u>=r.length)return;let p=et(r[u]);if(!this.argumentTypeMatches(o,p))throw new S(`Function '${n.name}' argument ${u} expects ${(f=o.type)!=null?f:"any"}, got ${p}`,t.line,t.col,t.constructor.name,void 0,{code:"invalid_argument_type",name:n.name,argIndex:u,expectedType:(v=o.type)!=null?v:"any",actualType:p})})}execute(t,n=!0,r){let s=d.compile(t,n);return r&&Object.keys(r).forEach(o=>this.changeVariable(o,r[o])),this.resetExecutionBudget(),this.clearTrace(),this.visit(s)}static compile(t,n=!1){let r=It(t);if(n&&this._cache.has(r))return this._cache.get(r);let s=new mt(t),u=new dt(s).parse();return n&&this._cache.set(r,u),u}static register(t,n,r){d._globalFunctionsRegistry[t]=n,d._globalFunctionSpecs[t]=g(t,r)}static unregister(t){delete d._globalFunctionsRegistry[t],delete d._globalFunctionSpecs[t]}static capabilities(){return Et({...st,...d._globalFunctionSpecs})}static validateSource(t,n,r=!1){return new d().validate(t,n,r)}static validateManifestSource(t,n,r=!1){return new d().validateManifest(t,n,r)}static run(t,n=!1,r,s){return new d(s).execute(t,n,r)}static newInstance(t){return new d(t)}clone(){var t=new d(this.options);return t._functionsRegistry={...this._functionsRegistry},t._functionSpecs={...this._functionSpecs},t.rootScope.memory={...this.rootScope.memory},t}newAsyncInstance(){let t=lt.newInstance(this.options);return t.rootScope.memory=this.rootScope.memory,t._functionsRegistry=this._functionsRegistry,t._functionSpecs=this._functionSpecs,t}};d._globalFunctionsRegistry={},d._globalFunctionSpecs={},d._cache=new Map;var it=d,lt=class a extends it{constructor(e){super(e)}async visitRootAST(e){var r;let t=e.body,n;for(let s of t)if(n=await this.visit(s),n instanceof y)return(r=n.value)!=null?r:null;return n!=null?n:null}async visitBlockStatementAST(e){let t=e.body,n;this.pushScope("Block");for(let r of t)if(n=await this.visit(r),n instanceof R||n instanceof y)break;return this.popScope(),n}async visitIdentifierAST(e){let t=e.value;return this.resolve(t)}async visitLiteralAST(e){return e.value}async visitAssignmentExpressionAST(e){let t=e.identifier,n=e.init,r=null;if(t instanceof w){var s=await this.visit(t.owner);r=await this.visit(e.init);var o=await this.visit(t.key);this.assignProperty(s,o,r)}else t instanceof x&&(r=await this.visit(n),this.changeVariable(t.value,r));return r}async visitExpressionStatementAST(e){let t=e.expression;return await this.visit(t)}async visitCallExpressionAST(e){var f,v;let t=e.callee,n=e.arguments,r=t.value;if(r==="_try_"){if(n.length!==1)throw new S("_try_ expects exactly one expression",e.line,e.col,e.constructor.name,void 0,{code:"invalid_try_arity",name:"_try_",argCount:n.length,minArgs:1,maxArgs:1});try{let _=await this.visit(n[0]);return _ instanceof R||_ instanceof y?_:this.successResult(_)}catch(_){if(_ instanceof S)return this.errorResult(_);throw _}}let s=this.resolveFunction(r);if(!s){if(this._options.compatV1)return null;throw new S(`Unknown function '${r}'`,e.line,e.col,e.constructor.name,void 0,{code:"unknown_function",name:r})}let o=this.resolveFunctionSpec(r);if(o&&!vt(o,n.length))throw new S(`Function '${r}' expects ${gt(o)} argument(s), got ${n.length}`,e.line,e.col,e.constructor.name,void 0,{code:"invalid_function_arity",name:r,argCount:n.length,minArgs:J(o),maxArgs:o.maxArgs});let u=await Promise.all(n.map(_=>this.visit(_)));o&&this.validateRuntimeArgumentTypes(e,o,u),this.recordTrace("call",e,r,{argCount:u.length,returnType:(f=o==null?void 0:o.returnType)!=null?f:"any"});let p=await s(u,this);return this.recordTrace("call_result",e,r,{returnType:(v=o==null?void 0:o.returnType)!=null?v:"any",actualType:et(p)}),p}async visitBinaryExpressionAST(e){let t=e.left,n=e.right,r=e.operation,s=await this.visit(t),o=await this.visit(n);switch(r.type){case i.plus:return h(s)&&h(o)?s+o:`${s}${o}`;case i.minus:if(h(s)&&h(o))return s-o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.mult:if(h(s)&&h(o))return s*o;if(Y(s)&&h(o))return s.repeat(o);if(h(s)&&Y(o))return o.repeat(s);throw new Error(`Operation ${r.value} not allowed no num value`);case i.div:if(h(s)&&h(o)){if(o===0)throw new Error("Invalid division by 0");return s/o}throw new Error(`Operation ${r.value} not allowed no num value`);case i.mod:if(h(s)&&h(o))return s%o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.great:if(h(s)&&h(o))return s>o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.greatEq:if(h(s)&&h(o))return s>=o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.less:if(h(s)&&h(o))return s<o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.lessEq:if(h(s)&&h(o))return s<=o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.eqeq:return s===o;case i.notEq:return s!==o;default:throw new Error(`Operation ${r.value} not allowed no num value`)}}async visitUnaryExpressionAST(e){let t=e.argument,n=e.operation,r=await this.visit(t);if(n.type===i.not)return b(r)===!1;if(!h(r))throw new Error(`Operation ${n.value} not allowed no num value`);if(n.type===i.plus)return r;if(n.type===i.minus)return-r;throw new Error(`Operation ${n.value} not allowed no num value`)}async visitIfStatementAST(e){let t=e.test,n=await this.visit(t);return b(n)?await this.visit(e.consequent):e.alternate?await this.visit(e.alternate):null}async visitLogicalExpressionAST(e){let t=e.left,n=await this.visit(t);if(e.operator.type===i.nullity)return n!=null?n:await this.visit(e.right);let r=b(n);return e.operator.type===i.and?r?b(await this.visit(e.right)):!1:e.operator.type===i.or?r?!0:b(await this.visit(e.right)):!1}async visitIndexAccessorAST(e){var r,s;let t=e.owner,n=await this.visit(t);if(n==null)return null;if(Array.isArray(n)){let o=await this.visit(e.key);return h(o)&&Number.isInteger(o)&&n.length>o&&o>=0&&(r=n[o])!=null?r:null}else if(typeof n=="object"){let o=await this.visit(e.key);return(s=n[o])!=null?s:null}return null}async visitObjectProperty(e){}async visitObjectExpression(e){let t={},n=e;for(let r of n.properties)if(r instanceof O){let s=await this.visit(r.key);s=Y(s)?s:s.toString(),t[s]=await this.visit(r.value)}return t}async visitArrayExpression(e){let t=e;return await this.resolveArgumentsAsync(t.elements)}async visitWhileLoopStatement(e){this.log(`WhileLoopStatement ${e.test} ${e.body}`);let t=e.retain?[]:void 0;for(;b(await this.visit(e.test));){let n=await this.visit(e.body);if(n instanceof C)break;if(!(n instanceof M)){if(n instanceof y)return this.popScope(),n;t==null||t.push(n)}}return t}async visitForLoopStatement(e){let t=e.retain?[]:void 0,n=e.init.identifier;if(!(n instanceof x))throw new Error("Unexpected identifer found");this.pushScope("ForLoopStatement");let r=await this.visit(e.init.init);this.changeVariable(n.value,r);let s=async()=>{let u=await this.visit(e.test);if(h(u)){let p=this.resolve(n.value);return e.direction.type===i.up?u>=p:u<=p}return b(u)},o=async()=>{let u=await this.visit(e.update);if(h(u)){let p=this.resolve(n.value);if(!h(p))throw Error("Cant update value");this.changeVariable(n.value,e.direction.type===i.up?p+u:p-u)}else throw Error("Update value cant be non number")};for(;await s();){let u=await this.visit(e.body);if(u instanceof C)break;if(u instanceof M){await o();continue}if(u instanceof y)return this.popScope(),u;t==null||t.push(u),await o()}return this.popScope(),t!=null?t:null}async visitForOfStatement(e){let t=await this.visit(e.collection);if(!Array.isArray(t))throw Error("Can iterate non array object");let n=e.retain?[]:void 0;this.pushScope("ForOfStatement");for(let r of t){this._declareForIdentifier(e.identifier,r);let s=await this.visit(e.body);if(s instanceof C)break;if(!(s instanceof M)){if(s instanceof y)return this.popScope(),s;n==null||n.push(s)}}return this.popScope(),n}async visitReturnAST(e){return new y(e.value!=null?await this.visit(e.value):null)}async resolveArgumentsAsync(e){return await Promise.all(e.map(async t=>await this.visit(t)))}registerFunction(e,t,n){this._functionsRegistry[e]=t,this._functionSpecs[e]=g(e,n)}unregisterFunction(e){delete this._functionsRegistry[e],delete this._functionSpecs[e]}async execute(e,t=!0,n){let r=it.compile(e,t);return n&&Object.keys(n).forEach(s=>this.changeVariable(s,n[s])),this.resetExecutionBudget(),this.clearTrace(),await this.visit(r)}static async run(e,t=!1,n,r){return await new a(r).execute(e,t,n)}static newInstance(e){return new a(e)}clone(){var e=new a(this.options);return e._functionsRegistry={...this._functionsRegistry},e._functionSpecs={...this._functionSpecs},e.rootScope.memory={...this.rootScope.memory},e}};0&&(module.exports={AST,ArrayExpression,AssignmentExpressionAST,BinaryExpressionAST,BlockStatementAST,BreakAST,BreakBranch,CallExpressionAST,ContinueAST,ContinueBranch,ExpressionStatementAST,ForLoopStatement,ForOfStatement,IdentifierAST,IfStatementAST,IndexAccessorAST,LexerDictionary,LiteralAST,LogicalExpressionAST,LoopControl,MEventScope,MEvento,MEventoAsync,MEventoRuntimeError,NodeVisitor,ObjectExpression,ObjectProperty,ReturnAST,ReturnBranch,RootAST,Token,TokenType,TupleExpression,UnaryExpressionAST,WhileLoopStatement});
8
+ `)}}`}},E=class extends m{constructor(e){super(e.line,e.col),this.value=e.value.toString()}toString(){return this.value}},A=class extends m{constructor(e,t){super(e.line,e.col),this.value=e.value,this.raw=t}toString(){return this.value.toString()}},L=class extends m{constructor(e,t){super(e.line,e.col),this.identifier=e,this.init=t}toString(){return`${this.identifier} = ${this.init}`}},G=class extends m{constructor(e){super(e.line,e.col),this.expression=e}toString(){return this.expression.toString()}},j=class extends m{constructor(e,t){super(e.line,e.col),this.callee=e,this.arguments=t}toString(){return`${this.callee.toString()}(...${this.arguments.length})`}},P=class extends m{constructor(e,t,n){super(e.line,e.col),this.left=e,this.operation=t,this.right=n}toString(){return`${this.left} ${this.operation} ${this.right}`}},z=class extends m{constructor(e,t){super(e.line,e.col),this.operation=e,this.argument=t}toString(){return`${this.operation} ${this.argument}`}},U=class extends m{constructor(e,t,n){super(e.line,e.col),this.test=e,this.consequent=t,this.alternate=n}toString(){return`if ${this.test} ${this.consequent} ${this.alternate?`else ${this.alternate} `:""}`}},D=class extends m{constructor(e,t,n){super(e.line,e.col),this.left=e,this.operator=t,this.right=n}toString(){return`${this.left} ${this.operator.value} ${this.right}`}},w=class extends m{constructor(t,n,r=!1){super(t.line,t.col);this.computed=!1;this.owner=t,this.key=n,this.computed=r}toString(){return`${this.owner}[${this.key}]`}},I=class extends m{constructor(e,t,n){super(t==null?void 0:t.line,t==null?void 0:t.col),this.properties=e}toString(){return"{...}"}},$=class extends m{constructor(e,t,n){super(t==null?void 0:t.line,t==null?void 0:t.col),this.elements=e}toString(){return"[...]"}},O=class extends m{constructor(e,t){super(e.line,e.col),this.value=t,this.key=e}},W=class extends m{constructor(t,n,r,a,o=!1){super(r==null?void 0:r.line,r==null?void 0:r.col);this.retain=!1;this.test=t,this.body=n,this.retain=o}},B=class extends m{constructor(t,n,r,a,o,u,p,f=!1){super(u==null?void 0:u.line,u==null?void 0:u.col);this.init=t;this.test=n;this.update=r;this.direction=a;this.body=o;this.retain=f}},K=class extends m{constructor(t,n,r,a,o,u=!1){super(a==null?void 0:a.line,a==null?void 0:a.col);this.identifier=t;this.collection=n;this.body=r;this.retain=u}},N=class extends m{constructor(t,n){super(t.line,t.col);this.first=t;this.second=n}},Z=class extends m{constructor(e,t){super(e,t)}},H=class extends m{constructor(e,t,n){super(t,n),this.value=e}},tt=class extends m{constructor(e,t){super(e,t)}};function zt(s){return s instanceof q?"RootAST":s instanceof F?"BlockStatementAST":s instanceof E?"IdentifierAST":s instanceof A?"LiteralAST":s instanceof L?"AssignmentExpressionAST":s instanceof G?"ExpressionStatementAST":s instanceof j?"CallExpressionAST":s instanceof P?"BinaryExpressionAST":s instanceof z?"UnaryExpressionAST":s instanceof U?"IfStatementAST":s instanceof D?"LogicalExpressionAST":s instanceof w?"IndexAccessorAST":s instanceof I?"ObjectExpression":s instanceof O?"ObjectProperty":s instanceof $?"ArrayExpression":s instanceof W?"WhileLoopStatement":s instanceof B?"ForLoopStatement":s instanceof K?"ForOfStatement":s instanceof N?"TupleExpression":s instanceof Z?"BreakAST":s instanceof H?"ReturnAST":s instanceof tt?"ContinueAST":s.constructor.name}var St=class{constructor(e=1/0){this.capacity=e;this.storage=[]}push(e){if(this.size()===this.capacity)throw Error("Stack has reached max capacity, you cannot add more items");this.storage.push(e)}pop(){return this.storage.pop()}peek(){return this.storage[this.size()-1]}size(){return this.storage.length}get isEmpty(){return this.storage.length===0}},nt=class nt{constructor(e){this._loopTrack=new St;this.currentToken=e.nextToken(),this.lexer=e}_eat(e){var t;((t=this.currentToken)==null?void 0:t.type)===e?this.currentToken=this.lexer.nextToken():T(this.currentToken,e)}_eatEOL(){var e;for(;((e=this.currentToken)==null?void 0:e.type)===i.eol;)this._eat(i.eol)}_eatSemiOrEOL(){var e,t;for(;((e=this.currentToken)==null?void 0:e.type)===i.eol||((t=this.currentToken)==null?void 0:t.type)===i.semi;)this._eat(this.currentToken.type)}_eatSemi(){var e;for(;((e=this.currentToken)==null?void 0:e.type)===i.semi;)this._eat(i.semi)}_variable(){let e=new E(this.currentToken);return this._eat(i.id),e}_return(){let e=this.currentToken,t;return!this._expect(i.eol)&&!this._expect(i.semi)&&(t=this._expression()),new H(t,e==null?void 0:e.line,e==null?void 0:e.col)}_factor(){let e=this.currentToken;switch(e.type){case i.plus:case i.minus:case i.not:return this._eat(this.currentToken.type),new z(e,this._term());case i.numberConst:return this._eat(i.numberConst),new A(e,e.value.toString());case i.stringConst:return this._eat(i.stringConst),new A(e,e.value.toString());case i.lparen:this._eat(i.lparen);let t=this._expression();return this._eat(i.rparen),t;case i.TRUE:case i.FALSE:return this._eat(this.currentToken.type),new A(e,e.value.toString());case i.NULL:return this._eat(i.NULL),new A(e,"null");case i.lbracket:return this._arrayExpression();case i.lbrace:return this._objectExpression();case i.IF:return this._ifStatement();case i.WHILE_TILL:return this._whileLoop(!0);case i.FOR_LOOP:return this._forLoop(!0);case i.BREAK:return this._breakExpression();case i.CONTINUE:return this._continueExpression();default:return this._variable()}}_breakExpression(){var e,t;return this._loopTrack.isEmpty&&T(this.currentToken),this._eat(i.BREAK),new Z((e=this.currentToken)==null?void 0:e.line,(t=this.currentToken)==null?void 0:t.col)}_continueExpression(){var e,t;return this._loopTrack.isEmpty&&T(this.currentToken),this._eat(i.CONTINUE),new tt((e=this.currentToken)==null?void 0:e.line,(t=this.currentToken)==null?void 0:t.col)}_term(){let e=this._factor();return e=this._tryParsingFunctionCall(e),e=this._tryParsingMemberExpression(e),e}_expression(){let e=this._term();for(e=this._tryBinaryExpression(0,e);[i.and,i.or,i.nullity].includes(this.currentToken.type);){let t=this.currentToken;this._eat(t.type),e=new D(e,t,this._expression())}if(this._expect(i.equal))if(e instanceof E||e instanceof w){let t=this.currentToken;this._eat(i.equal),e=new L(e,this._expression())}else throw new Error("Unexpected token");return e}_objectProperty(){var r;let e;switch((r=this.currentToken)==null?void 0:r.type){case i.stringConst:{e=new A(this.currentToken,this.currentToken.value),this._eat(i.stringConst);break}case i.lbracket:{this._eat(i.lbracket);var t=this._expression();this._eat(i.rbracket),e=t;break}case i.id:{let a=this._variable();e=new A(new l(i.id,a.value,a.line,a.col),a.value);break}default:throw`Unexpected token ${this.currentToken}`}this._eat(i.colon);var n=this._expression();return new O(e,n)}_property(){return this._objectProperty()}_objectProperties(){var t,n;let e=[];for(((t=this.currentToken)==null?void 0:t.type)!=i.rbrace&&(this._eatEOL(),e.push(this._property()),this._eatEOL());((n=this.currentToken)==null?void 0:n.type)===i.comma&&(this._eat(i.comma),this._eatEOL(),!this._expect(i.rbrace));)e.push(this._property()),this._eatEOL();return e}_objectExpression(e){var t=e!=null?e:this.currentToken;e||this._eat(i.lbrace);var n=this._objectProperties();return this._eat(i.rbrace),new I(n,t,this.currentToken)}_arrayExpression(){this._eat(i.lbracket);let e=this._expect(i.rbracket)?[]:this._expressionsList();this._eat(i.rbracket);var t=e.length!==0?e[0]:void 0,n=e.length!==0?e[e.length-1]:void 0;return new $(e,t,n)}_tryParsingMemberExpression(e){let t=e;for(;this.currentToken.type===i.lbracket||this.currentToken.type===i.dot;)if(this.currentToken.type===i.lbracket){this._eat(i.lbracket);let n=this._expression();t=new w(t,n,!0),this._eat(i.rbracket)}else{this._eat(i.dot);let n=this.currentToken;n.type!==i.id&&T(n);let r=new A(new l(i.stringConst,n.value,n.line,n.col),n.value);this._eat(i.id),t=new w(t,r)}return t}_tryBinaryExpression(e,t){let n=t;for(;;){let r=nt._binopPrecdences[this.currentToken.type]||-1;if(r<e)return n;let a=this.currentToken;this._eat(a.type);let o=this._term(),u=nt._binopPrecdences[this.currentToken.type]||-1;if(r<u){let p=this._tryBinaryExpression(r+1,o);if(p===n)return p;o=p}n=new P(n,a,o)}}_expressionsList(){var n;this._eatEOL();let e=this._expression();this._eatEOL();let t=[e];for(;((n=this.currentToken)==null?void 0:n.type)===i.comma&&(this._eat(i.comma),this._eatEOL(),!this._expect(i.rbracket));)e=this._expression(),t.push(e),this._eatEOL();return t}_callExpression(e){this._eat(i.lparen);let t=[];return this._expect(i.rparen)||(t=this._expressionsList()),this._eat(i.rparen),e instanceof E||T(this.currentToken),new j(e,t)}_tryParsingFunctionCall(e){let t=e;for(;this.currentToken.type===i.lparen;)t=this._callExpression(t);return t}_statementExpression(){let e=this._expression();return[i.semi,i.eol,i.eof,i.rbrace].includes(this.currentToken.type)||T(this.currentToken),e}_blockStatement(e=!1){if(e||this._eat(i.lbrace),this._eatEOL(),this._expect(i.rbrace))return this._eat(i.rbrace),new F([],this.currentToken);let t=[this._statement()];for(;this._eatSemiOrEOL(),!(this.currentToken.type===i.rbrace||this.currentToken.type===i.eof||(t.push(this._statement()),this._expect(i.rbrace)));)this.currentToken.type!==i.eol&&this.currentToken.type!==i.semi&&this.currentToken.type!==i.eof&&T(this.currentToken);return this._eat(i.rbrace),new F(t,this.currentToken)}_ifStatement(){this._eat(i.IF);let e=this.currentToken.type===i.lparen;e&&this._eat(i.lparen);let t=this._expression();e&&this._eat(i.rparen);let n;this.currentToken.type===i.lbrace?n=this._blockStatement():n=this._expression();let r;if(this.currentToken.type===i.ELSE)switch(this._eat(i.ELSE),this.currentToken.type){case i.IF:r=this._ifStatement();break;case i.lbrace:r=this._blockStatement();break;default:r=this._expression()}return new U(t,n,r)}_pushLoop(){this._loopTrack.push(!0)}_popLoop(){this._loopTrack.pop()}_whileLoop(e=!1){let t=this.currentToken;this._eat(i.WHILE_TILL),this._pushLoop();let n=this._expression(),r=this.currentToken.type===i.lbrace?this._blockStatement():this._expression();return this._popLoop(),new W(n,r,t,this.currentToken,e)}_forOfIdentifier(){switch(this.currentToken.type){case i.lparen:{this._eat(i.lparen);let e=this._variable();this._eat(i.comma);let t=this._variable();return this._eat(i.rparen),new N(e,t)}default:return this._variable()}}_forLoop(e=!1){let t=this.currentToken;this._eat(i.FOR_LOOP),this._pushLoop();let n=[i.lparen].includes(this.currentToken.type),r;if(n)r=this._forOfIdentifier();else{let a=this._expression();a instanceof L||(n=!0),r=a}if(!n&&r instanceof L){this._eat(i.TILL);let a=this._expression(),o;if(this.currentToken.type===i.up||this.currentToken.type===i.down){let f=this.currentToken;this._eat(f.type),o=f}else o=new l(i.up,"up");let u;this._expect(i.with)?(this._eat(i.with),u=this._expression()):u=new A(new l(i.numberConst,1,this.currentToken.line,this.currentToken.col),"1");let p=this.currentToken.type===i.lbrace?this._blockStatement():this._expression();r=new B(r,a,u,o,p,t,this.currentToken,e),this._popLoop()}else if(n){this._eat(i.in);let a=this._expression(),o=this.currentToken.type===i.lbrace?this._blockStatement():this._expression();r=new K(r,a,o,t,this.currentToken,e),this._popLoop()}else T(this.currentToken);return r}_statement(){switch(this.currentToken.type){case i.BREAK:return this._breakExpression();case i.CONTINUE:return this._continueExpression();case i.RETURN:return this._eat(i.RETURN),this._return();case i.semi:return this._eatSemi(),this._statement();case i.eol:return this._eatEOL(),this._statement();case i.WHILE_TILL:return this._whileLoop();case i.FOR_LOOP:return this._forLoop();default:return this._statementExpression()}}_expect(e){var t;return((t=this.currentToken)==null?void 0:t.type)===e}_definition(){if(this._eatSemiOrEOL(),this._expect(i.eof))return[];let e=[this._statement()];for(;;){if(this._eatSemiOrEOL(),this.currentToken.type===i.eof){this._eat(i.eof);break}this.currentToken.type===i.lbrace?e.push(this._blockStatement()):e.push(this._statement())}return e}_root(){let e=this.lexer.source,t="<module>",n=this._definition();return new q(n,t,e)}parse(){return this._root()}};nt._binopPrecdences={[i.eqeq]:10,[i.notEq]:10,[i.great]:10,[i.greatEq]:10,[i.less]:10,[i.lessEq]:10,[i.plus]:20,[i.minus]:20,[i.mult]:40,[i.div]:40,[i.mod]:40};var yt=nt,R=class{},C=class extends R{},M=class extends R{},y=class{constructor(e){this.value=e}},At=class{constructor(){this._nodesVisitors={}}registerVisitor(e,t){let n=`visit${e.name}`;this._nodesVisitors[n]=t}},ht=class extends At{constructor(){super(),this.registerVisitor(q,this.visitRootAST),this.registerVisitor(F,this.visitBlockStatementAST),this.registerVisitor(E,this.visitIdentifierAST),this.registerVisitor(A,this.visitLiteralAST),this.registerVisitor(L,this.visitAssignmentExpressionAST),this.registerVisitor(G,this.visitExpressionStatementAST),this.registerVisitor(j,this.visitCallExpressionAST),this.registerVisitor(P,this.visitBinaryExpressionAST),this.registerVisitor(z,this.visitUnaryExpressionAST),this.registerVisitor(U,this.visitIfStatementAST),this.registerVisitor(D,this.visitLogicalExpressionAST),this.registerVisitor(w,this.visitIndexAccessorAST),this.registerVisitor(O,this.visitObjectProperty),this.registerVisitor(I,this.visitObjectExpression),this.registerVisitor($,this.visitArrayExpression),this.registerVisitor(W,this.visitWhileLoopStatement),this.registerVisitor(B,this.visitForLoopStatement),this.registerVisitor(K,this.visitForOfStatement),this.registerVisitor(Z,this.visitBreakAST),this.registerVisitor(tt,this.visitContinueAST),this.registerVisitor(H,this.visitReturnAST)}visit(e){this.beforeVisit(e);let t=`visit${e.constructor.name}`,n=this._nodesVisitors[t];if(!n)throw new S(`No ${t} declared`,e.line,e.col,e.constructor.name);try{let r=n.call(this,e);return r&&typeof r.then=="function"?r.catch(a=>{throw S.fromNode(e,a)}):r!=null?r:null}catch(r){throw S.fromNode(e,r)}}beforeVisit(e){}assignProperty(e,t,n){(Array.isArray(e)||typeof e=="object")&&(e[t]=n)}},rt=class{constructor(e,t,n){this.memory={};this.name=e,this.memory=t,this.parent=n}resolve(e){var t,n;return Object.keys(this.memory).includes(e)?this.memory[e]:(n=(t=this.parent)==null?void 0:t.resolve(e))!=null?n:null}change(e,t,n=!0){return Object.keys(this.memory).includes(e)?(this.memory[e]=t,!0):this.parent&&this.parent.change(e,t,!1)?!0:n?(this.memory[e]=t,!0):!1}},st={_ok_:g("_ok_",{name:"_ok_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"boolean"}),_err_:g("_err_",{name:"_err_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"boolean"}),_value_:g("_value_",{name:"_value_",minArgs:1,maxArgs:2,args:[{name:"result"},{name:"fallback",required:!1}],returnType:"any"}),_error_:g("_error_",{name:"_error_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"object"}),_code_:g("_code_",{name:"_code_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"string"}),_message_:g("_message_",{name:"_message_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"string"}),_unwrap_:g("_unwrap_",{name:"_unwrap_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"any"}),_len_:g("_len_",{name:"_len_",minArgs:1,maxArgs:1,args:[{name:"target"}],returnType:"number"}),_push_:g("_push_",{name:"_push_",minArgs:2,maxArgs:2,args:[{name:"array",type:"array"},{name:"value"}],returnType:"array"}),_pop_:g("_pop_",{name:"_pop_",minArgs:1,maxArgs:1,args:[{name:"array",type:"array"}],returnType:"any"}),_insert_:g("_insert_",{name:"_insert_",minArgs:3,maxArgs:3,args:[{name:"array",type:"array"},{name:"index",type:"number"},{name:"value"}],returnType:"array"}),_remove_at_:g("_remove_at_",{name:"_remove_at_",minArgs:2,maxArgs:2,args:[{name:"array",type:"array"},{name:"index",type:"number"}],returnType:"any"}),_has_:g("_has_",{name:"_has_",minArgs:2,maxArgs:2,args:[{name:"object",type:"object"},{name:"key"}],returnType:"boolean"}),_keys_:g("_keys_",{name:"_keys_",minArgs:1,maxArgs:1,args:[{name:"object",type:"object"}],returnType:"array"}),_values_:g("_values_",{name:"_values_",minArgs:1,maxArgs:1,args:[{name:"object",type:"object"}],returnType:"array"})};function at(s){return typeof s=="object"&&s!=null&&s.ok===!0}function ut(s){if(typeof s!="object"||s==null)return;let e=s;if(!(e.ok!==!1||typeof e.error!="object"||e.error==null))return e.error}function V(s){return typeof s=="number"?s:void 0}function Q(s){return typeof s=="string"?s:void 0}function Ut(s){var t,n;let e=ut(s);return new S((t=Q(e==null?void 0:e.message))!=null?t:"Cannot unwrap failed _try_ result",V(e==null?void 0:e.line),V(e==null?void 0:e.col),Q(e==null?void 0:e.node),void 0,{code:(n=Q(e==null?void 0:e.code))!=null?n:"invalid_try_result",name:Q(e==null?void 0:e.name),argCount:V(e==null?void 0:e.argCount),minArgs:V(e==null?void 0:e.minArgs),maxArgs:V(e==null?void 0:e.maxArgs),argIndex:V(e==null?void 0:e.argIndex),expectedType:Q(e==null?void 0:e.expectedType),actualType:Q(e==null?void 0:e.actualType),stepCount:V(e==null?void 0:e.stepCount),maxSteps:V(e==null?void 0:e.maxSteps)})}function ft(s,e,t,n){let r=et(n);return new S(`Function '${s}' argument ${e} expects ${t}, got ${r}`,void 0,void 0,void 0,void 0,{code:"invalid_argument_type",name:s,argIndex:e,expectedType:t,actualType:r})}function ot(s,e,t){let n=e[t];if(Array.isArray(n))return n;throw ft(s,t,"array",n)}function vt(s,e,t){let n=e[t];if(typeof n=="object"&&n!=null&&!Array.isArray(n))return n;throw ft(s,t,"object",n)}function kt(s,e,t){let n=e[t];if(typeof n=="number")return Math.trunc(n);throw ft(s,t,"number",n)}function Dt(s,e,t){return new S(`Function '${s}' index ${e} is out of range for array of length ${t}`,void 0,void 0,void 0,void 0,{code:"index_out_of_range",name:s})}var Wt={_ok_:s=>at(s[0]),_err_:s=>!at(s[0]),_value_:s=>{var e,t;return at(s[0])?(e=s[0].value)!=null?e:null:(t=s[1])!=null?t:null},_error_:s=>{var e;return(e=ut(s[0]))!=null?e:null},_code_:s=>{var e,t;return(t=(e=ut(s[0]))==null?void 0:e.code)!=null?t:null},_message_:s=>{var e,t;return(t=(e=ut(s[0]))==null?void 0:e.message)!=null?t:null},_unwrap_:s=>{var e;if(at(s[0]))return(e=s[0].value)!=null?e:null;throw Ut(s[0])},_len_:s=>{let e=s[0];if(Array.isArray(e)||typeof e=="string")return e.length;if(typeof e=="object"&&e!=null)return Object.keys(e).length;throw ft("_len_",0,"array|object|string",e)},_push_:s=>{var t;let e=ot("_push_",s,0);return e.push((t=s[1])!=null?t:null),e},_pop_:s=>{var t;let e=ot("_pop_",s,0);return e.length===0?null:(t=e.pop())!=null?t:null},_insert_:s=>{var n;let e=ot("_insert_",s,0),t=kt("_insert_",s,1);if(t<0||t>e.length)throw Dt("_insert_",t,e.length);return e.splice(t,0,(n=s[2])!=null?n:null),e},_remove_at_:s=>{var n;let e=ot("_remove_at_",s,0),t=kt("_remove_at_",s,1);return t<0||t>=e.length?null:(n=e.splice(t,1)[0])!=null?n:null},_has_:s=>Object.prototype.hasOwnProperty.call(vt("_has_",s,0),s[1]),_keys_:s=>Object.keys(vt("_keys_",s,0)),_values_:s=>Object.values(vt("_values_",s,0))},_=class _ extends ht{constructor(t){super();this.rootScope=new rt("Program",{});this.currentScope=this.rootScope;this.debug=!1;this._functionsRegistry={};this._functionSpecs={};this._executionStepCount=0;this._traceEvents=[];this._options=jt(t),this._functionsRegistry={...Wt,..._._globalFunctionsRegistry},this._functionSpecs={...st,..._._globalFunctionSpecs}}get options(){return{...this._options}}get executionStepCount(){return this._executionStepCount}trace(){return this._traceEvents.map(t=>({...t,detail:{...t.detail}}))}resetExecutionBudget(){this._executionStepCount=0}beforeVisit(t){this._executionStepCount+=1,this.recordTrace("visit",t);let n=this._options.maxSteps;if(n!=null&&this._executionStepCount>n)throw new S(`Execution budget exceeded after ${this._executionStepCount} step(s)`,t.line,t.col,t.constructor.name,void 0,{code:"execution_budget_exceeded",stepCount:this._executionStepCount,maxSteps:n})}clearTrace(){this._traceEvents=[]}recordTrace(t,n,r,a={}){this._options.trace&&this._traceEvents.push({kind:t,line:n.line,col:n.col,node:zt(n),name:r,stepCount:this._executionStepCount,detail:a})}resolve(t){var n,r;return(r=(n=this.currentScope)==null?void 0:n.resolve(t))!=null?r:null}changeVariable(t,n){var r;return(r=this.currentScope)!=null&&r.change(t,n)?n:null}pushScope(t){let n=new rt(t,{},this.currentScope);this.currentScope=n}popScope(){var t;this.currentScope=(t=this.currentScope)==null?void 0:t.parent}log(t){this.debug&&console.log(t)}successResult(t){return{ok:!0,value:t,error:null}}errorResult(t){return{ok:!1,value:null,error:t.diagnostic()}}visitRootAST(t){var a;let n=t.body,r;for(let o of n)if(r=this.visit(o),r instanceof y)return(a=r.value)!=null?a:null;return r!=null?r:null}visitBlockStatementAST(t){let n=t.body,r;this.pushScope("Block");for(let a of n)if(r=this.visit(a),r instanceof R||r instanceof y)break;return this.popScope(),r!=null?r:null}visitIdentifierAST(t){var r;let n=t.value;return(r=this==null?void 0:this.resolve(n))!=null?r:null}visitLiteralAST(t){return t.value}visitAssignmentExpressionAST(t){let n=t.identifier,r=t.init,a=null;if(n instanceof w){var o=this.visit(n.owner);a=this.visit(t.init);var u=this.visit(n.key);this.assignProperty(o,u,a)}else n instanceof E&&(a=this.visit(r),this.changeVariable(n.value,a));return a}visitExpressionStatementAST(t){let n=t.expression;return this.visit(n)}visitCallExpressionAST(t){var v,d;let n=t.callee,r=t.arguments,a=n.value;if(a==="_try_"){if(r.length!==1)throw new S("_try_ expects exactly one expression",t.line,t.col,t.constructor.name,void 0,{code:"invalid_try_arity",name:"_try_",argCount:r.length,minArgs:1,maxArgs:1});try{let x=this.visit(r[0]);return x instanceof R||x instanceof y?x:this.successResult(x)}catch(x){if(x instanceof S)return this.errorResult(x);throw x}}let o=this.resolveFunction(a);if(!o){if(this._options.compatV1)return null;throw new S(`Unknown function '${a}'`,t.line,t.col,t.constructor.name,void 0,{code:"unknown_function",name:a})}let u=this.resolveFunctionSpec(a);if(u&&!dt(u,r.length))throw new S(`Function '${a}' expects ${_t(u)} argument(s), got ${r.length}`,t.line,t.col,t.constructor.name,void 0,{code:"invalid_function_arity",name:a,argCount:r.length,minArgs:J(u),maxArgs:u.maxArgs});let p=r.map(x=>this.visit(x));u&&this.validateRuntimeArgumentTypes(t,u,p),this.recordTrace("call",t,a,{argCount:p.length,returnType:(v=u==null?void 0:u.returnType)!=null?v:"any"});let f=o(p,this);return this.recordTrace("call_result",t,a,{returnType:(d=u==null?void 0:u.returnType)!=null?d:"any",actualType:et(f)}),f}visitBinaryExpressionAST(t){let n=t.left,r=t.right,a=t.operation,o=this.visit(n),u=this.visit(r);switch(a.type){case i.plus:return h(o)&&h(u)?o+u:`${o}${u}`;case i.minus:if(h(o)&&h(u))return o-u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.mult:if(h(o)&&h(u))return o*u;if(Y(o)&&h(u))return o.repeat(u);if(h(o)&&Y(u))return u.repeat(o);throw new Error(`Operation ${a.value} not allowed no num value`);case i.div:if(h(o)&&h(u)){if(u===0)throw new Error("Invalid division by 0");return o/u}throw new Error(`Operation ${a.value} not allowed no num value`);case i.mod:if(h(o)&&h(u))return o%u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.great:if(h(o)&&h(u))return o>u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.greatEq:if(h(o)&&h(u))return o>=u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.less:if(h(o)&&h(u))return o<u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.lessEq:if(h(o)&&h(u))return o<=u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.eqeq:return o===u;case i.notEq:return o!==u;default:throw new Error(`Operation ${a.value} not allowed no num value`)}}visitUnaryExpressionAST(t){let n=t.argument,r=t.operation,a=this.visit(n);if(r.type===i.not)return b(a)===!1;if(!h(a))throw new Error(`Operation ${r.value} not allowed no num value`);if(r.type===i.plus)return a;if(r.type===i.minus)return-a;throw new Error(`Operation ${r.value} not allowed no num value`)}visitIfStatementAST(t){let n=t.test,r=this.visit(n);return b(r)?this.visit(t.consequent):t.alternate?this.visit(t.alternate):null}visitLogicalExpressionAST(t){let n=t.left,r=this.visit(n);if(t.operator.type===i.nullity)return r!=null?r:this.visit(t.right);let a=b(r);return t.operator.type===i.and?a?b(this.visit(t.right)):!1:t.operator.type===i.or?a?!0:b(this.visit(t.right)):null}visitIndexAccessorAST(t){var a,o;let n=t.owner,r=this.visit(n);if(r==null)return null;if(Array.isArray(r)){let u=this.visit(t.key);return h(u)&&Number.isInteger(u)&&r.length>u&&u>=0&&(a=r[u])!=null?a:null}else if(typeof r=="object"){let u=this.visit(t.key);return(o=r[u])!=null?o:null}return null}visitObjectProperty(t){}visitObjectExpression(t){let n={},r=t;for(let a of r.properties)if(a instanceof O){let o=this.visit(a.key);o=Y(o)?o:o.toString(),n[o]=this.visit(a.value)}return n}visitArrayExpression(t){let n=t;return this.resolveArguments(n.elements)}visitBreakAST(t){return new C}visitWhileLoopStatement(t){this.log(`WhileLoopStatement ${t.test} ${t.body}`);let n=t.retain?[]:void 0;for(;b(this.visit(t.test));){let r=this.visit(t.body);if(r instanceof C)break;if(!(r instanceof M)){if(r instanceof y)return this.popScope(),r;n==null||n.push(r)}}return n!=null?n:null}visitForLoopStatement(t){let n=t.retain?[]:void 0,r=t.init.identifier;if(!(r instanceof E))throw new Error("Unexpected identifer found");this.pushScope("ForLoopStatement");let a=this.visit(t.init.init);this.changeVariable(r.value,a);let o=()=>{let p=this.visit(t.test);if(h(p)){let f=this.resolve(r.value);return t.direction.type===i.up?p>=f:p<=f}return b(p)},u=()=>{let p=this.visit(t.update);if(h(p)){let f=this.resolve(r.value);if(!h(f))throw Error("Cant update value");this.changeVariable(r.value,t.direction.type===i.up?f+p:f-p)}else throw Error("Update value cant be non number")};for(;o();){let p=this.visit(t.body);if(p instanceof C)break;if(p instanceof M){u();continue}if(p instanceof y)return this.popScope(),p;n==null||n.push(p),u()}return this.popScope(),n!=null?n:null}visitForOfStatement(t){let n=this.visit(t.collection);if(!Array.isArray(n))throw Error("Can iterate non array object");let r=t.retain?[]:void 0;this.pushScope("ForOfStatement");for(let a of n){this._declareForIdentifier(t.identifier,a);let o=this.visit(t.body);if(o instanceof C)break;if(!(o instanceof M)){if(o instanceof y)return this.popScope(),o;r==null||r.push(o)}}return this.popScope(),r!=null?r:null}visitContinueAST(t){return new M}visitReturnAST(t){return new y(t.value!=null?this.visit(t.value):null)}_declareForIdentifier(t,n){if(t instanceof N){if(!Array.isArray(n))throw Error("Unable to make a tuple from non Array element");this.changeVariable(t.first.value,n[0]),this.changeVariable(t.second.value,n[1])}this.changeVariable(t.value,n)}resolveArguments(t){return t.map(n=>this.visit(n))}setFunctionResolver(t){this._functionResolver=t}resolveFunction(t){var n,r;return(r=this._functionsRegistry[t])!=null?r:(n=this._functionResolver)==null?void 0:n.call(this,t)}resolveFunctionSpec(t){return this._functionSpecs[t]}capabilities(){return Tt(this._functionSpecs)}registerFunction(t,n,r){this._functionsRegistry[t]=n,this._functionSpecs[t]=g(t,r)}unregisterFunction(t){delete this._functionsRegistry[t],delete this._functionSpecs[t]}validate(t,n,r=!1){let a=[],o=this.validationFunctionSpecs(n);try{this.validateNode(_.compile(t,r),o,a)}catch(u){a.push({code:"syntax_error",message:u instanceof Error?u.message:String(u)})}return{ok:a.length===0,errors:a}}validateManifest(t,n,r=!1){let a=[],o=this.validationFunctionSpecs(n.functions);try{let u=_.compile(t,r);this.validateNode(u,o,a),this.validateManifestNode(u,n,a)}catch(u){a.push({code:"syntax_error",message:u instanceof Error?u.message:String(u)})}return{ok:a.length===0,errors:a}}validationFunctionSpecs(t){let n=new Map;return Object.keys(st).forEach(r=>{var a;return n.set(r,(a=this._functionSpecs[r])!=null?a:st[r])}),t==null?(Object.keys(this._functionSpecs).forEach(r=>n.set(r,this._functionSpecs[r])),n):t instanceof Set?(t.forEach(r=>{var a;return n.set(r,(a=this._functionSpecs[r])!=null?a:g(r))}),n):Array.isArray(t)?(t.forEach(r=>{var a;typeof r=="string"?n.set(r,(a=this._functionSpecs[r])!=null?a:g(r)):n.set(r.name,g(r.name,r))}),n):(Object.keys(t).forEach(r=>n.set(r,g(r,t[r]))),n)}validateNode(t,n,r,a=!1){t&&(t instanceof q||t instanceof F?t.body.forEach(o=>this.validateNode(o,n,r,a)):t instanceof L?(this.validateNode(t.identifier,n,r,a),this.validateNode(t.init,n,r,a)):t instanceof G?this.validateNode(t.expression,n,r,a):t instanceof j?this.validateCallExpression(t,n,r,a):t instanceof P?(this.validateNode(t.left,n,r,a),this.validateNode(t.right,n,r,a)):t instanceof z?this.validateNode(t.argument,n,r,a):t instanceof U?(this.validateNode(t.test,n,r,a),this.validateNode(t.consequent,n,r,a),this.validateNode(t.alternate,n,r,a)):t instanceof D?(this.validateNode(t.left,n,r,a),this.validateNode(t.right,n,r,a)):t instanceof w?(this.validateNode(t.owner,n,r,a),this.validateNode(t.key,n,r,a)):t instanceof I?t.properties.forEach(o=>this.validateNode(o,n,r,a)):t instanceof O?(this.validateNode(t.key,n,r,a),this.validateNode(t.value,n,r,a)):t instanceof $?t.elements.forEach(o=>this.validateNode(o,n,r,a)):t instanceof W?(this.validateNode(t.test,n,r,a),this.validateNode(t.body,n,r,a)):t instanceof B?(this.validateNode(t.init,n,r,a),this.validateNode(t.test,n,r,a),this.validateNode(t.update,n,r,a),this.validateNode(t.body,n,r,a)):t instanceof K?(this.validateNode(t.identifier,n,r,a),this.validateNode(t.collection,n,r,a),this.validateNode(t.body,n,r,a)):t instanceof N?(this.validateNode(t.first,n,r,a),this.validateNode(t.second,n,r,a)):t instanceof H&&this.validateNode(t.value,n,r,a))}validateCallExpression(t,n,r,a){let o=t.callee.value;if(o==="_try_"){t.arguments.length!==1&&r.push(this.validationError("invalid_try_arity",t,"_try_ expects exactly one expression","_try_",{argCount:t.arguments.length,minArgs:1,maxArgs:1})),t.arguments.forEach(u=>this.validateNode(u,n,r,!0));return}if(!a){let u=n.get(o);u?dt(u,t.arguments.length)?this.validateStaticArgumentTypes(t,u,r):r.push(this.validationError("invalid_function_arity",t,`Function '${o}' expects ${_t(u)} argument(s), got ${t.arguments.length}`,o,{argCount:t.arguments.length,minArgs:J(u),maxArgs:u.maxArgs})):this._options.compatV1||r.push(this.validationError("unknown_function",t,`Unknown function '${o}'`,o))}t.arguments.forEach(u=>this.validateNode(u,n,r,a))}validateStaticArgumentTypes(t,n,r){var a;(a=n.args)==null||a.forEach((o,u)=>{var v,d;let p=t.arguments[u];if(!p)return;let f=this.staticArgumentType(p);!f||this.argumentTypeMatches(o,f)||r.push(this.validationError("invalid_argument_type",t,`Function '${n.name}' argument ${u} expects ${(v=o.type)!=null?v:"any"}, got ${f}`,n.name,{argIndex:u,expectedType:(d=o.type)!=null?d:"any",actualType:f}))})}staticArgumentType(t){if(t instanceof A)return et(t.value);if(t instanceof $)return"array";if(t instanceof I)return"object"}argumentTypeMatches(t,n){var a;let r=(a=t.type)!=null?a:"any";return r==="any"||t.required===!1&&n==="null"?!0:r===n}validateManifestNode(t,n,r){var p,f;let a=((p=n.inputs)!=null?p:[]).map(wt),o=((f=n.outputs)!=null?f:[]).map(wt),u={knownInputs:new Set(a.map(v=>v.name)),assigned:new Set,assignedTypes:new Map,reportedInputs:new Set};this.analyzeManifestNode(t,u,r),o.forEach(v=>{var x,Et,xt;if(((x=v.required)==null||x)&&!u.assigned.has(v.name)){r.push(this.validationError("missing_output",t,`Required output '${v.name}' is not assigned`,v.name));return}let d=u.assignedTypes.get(v.name);!d||this.valueSpecTypeMatches(v,d)||r.push(this.validationError("invalid_output_type",t,`Output '${v.name}' expects ${(Et=v.type)!=null?Et:"any"}, got ${d}`,v.name,{expectedType:(xt=v.type)!=null?xt:"any",actualType:d}))})}analyzeManifestNode(t,n,r){t&&(t instanceof q||t instanceof F?t.body.forEach(a=>this.analyzeManifestNode(a,n,r)):t instanceof L?(this.analyzeManifestNode(t.init,n,r),t.identifier instanceof w&&this.analyzeManifestNode(t.identifier,n,r),this.markAssignedTarget(t.identifier,this.staticArgumentType(t.init),n)):t instanceof G?this.analyzeManifestNode(t.expression,n,r):t instanceof j?t.arguments.forEach(a=>this.analyzeManifestNode(a,n,r)):t instanceof P?(this.analyzeManifestNode(t.left,n,r),this.analyzeManifestNode(t.right,n,r)):t instanceof z?this.analyzeManifestNode(t.argument,n,r):t instanceof U?(this.analyzeManifestNode(t.test,n,r),this.analyzeManifestNode(t.consequent,n,r),this.analyzeManifestNode(t.alternate,n,r)):t instanceof D?(this.analyzeManifestNode(t.left,n,r),this.analyzeManifestNode(t.right,n,r)):t instanceof w?(this.analyzeManifestNode(t.owner,n,r),this.analyzeManifestNode(t.key,n,r)):t instanceof I?t.properties.forEach(a=>this.analyzeManifestNode(a,n,r)):t instanceof O?(this.analyzeManifestNode(t.key,n,r),this.analyzeManifestNode(t.value,n,r)):t instanceof $?t.elements.forEach(a=>this.analyzeManifestNode(a,n,r)):t instanceof W?(this.analyzeManifestNode(t.test,n,r),this.analyzeManifestNode(t.body,n,r)):t instanceof B?(this.analyzeManifestNode(t.init,n,r),this.analyzeManifestNode(t.test,n,r),this.analyzeManifestNode(t.body,n,r),this.analyzeManifestNode(t.update,n,r)):t instanceof K?(this.analyzeManifestNode(t.collection,n,r),this.markAssignedTarget(t.identifier,void 0,n),this.analyzeManifestNode(t.body,n,r)):t instanceof N?(this.analyzeManifestNode(t.first,n,r),this.analyzeManifestNode(t.second,n,r)):t instanceof H?this.analyzeManifestNode(t.value,n,r):t instanceof E&&!n.knownInputs.has(t.value)&&!n.assigned.has(t.value)&&!n.reportedInputs.has(t.value)&&(n.reportedInputs.add(t.value),r.push(this.validationError("unknown_input",t,`Unknown input '${t.value}'`,t.value))))}markAssignedTarget(t,n,r){t instanceof E?(r.assigned.add(t.value),n&&r.assignedTypes.set(t.value,n)):t instanceof N&&(this.markAssignedTarget(t.first,void 0,r),this.markAssignedTarget(t.second,void 0,r))}valueSpecTypeMatches(t,n){var a;let r=(a=t.type)!=null?a:"any";return r==="any"||t.required===!1&&n==="null"?!0:r===n}validationError(t,n,r,a,o){return{code:t,message:r,name:a,line:n.line,col:n.col,node:n.constructor.name,argCount:o==null?void 0:o.argCount,minArgs:o==null?void 0:o.minArgs,maxArgs:o==null?void 0:o.maxArgs,argIndex:o==null?void 0:o.argIndex,expectedType:o==null?void 0:o.expectedType,actualType:o==null?void 0:o.actualType}}validateRuntimeArgumentTypes(t,n,r){var a;(a=n.args)==null||a.forEach((o,u)=>{var f,v;if(u>=r.length)return;let p=et(r[u]);if(!this.argumentTypeMatches(o,p))throw new S(`Function '${n.name}' argument ${u} expects ${(f=o.type)!=null?f:"any"}, got ${p}`,t.line,t.col,t.constructor.name,void 0,{code:"invalid_argument_type",name:n.name,argIndex:u,expectedType:(v=o.type)!=null?v:"any",actualType:p})})}execute(t,n=!0,r){let a=_.compile(t,n);return r&&Object.keys(r).forEach(o=>this.changeVariable(o,r[o])),this.resetExecutionBudget(),this.clearTrace(),this.visit(a)}static compile(t,n=!1){let r=Rt(t);if(n&&this._cache.has(r))return this._cache.get(r);let a=new gt(t),u=new yt(a).parse();return n&&this._cache.set(r,u),u}static register(t,n,r){_._globalFunctionsRegistry[t]=n,_._globalFunctionSpecs[t]=g(t,r)}static unregister(t){delete _._globalFunctionsRegistry[t],delete _._globalFunctionSpecs[t]}static capabilities(){return Tt({...st,..._._globalFunctionSpecs})}static validateSource(t,n,r=!1){return new _().validate(t,n,r)}static validateManifestSource(t,n,r=!1){return new _().validateManifest(t,n,r)}static run(t,n=!1,r,a){return new _(a).execute(t,n,r)}static newInstance(t){return new _(t)}clone(){var t=new _(this.options);return t._functionsRegistry={...this._functionsRegistry},t._functionSpecs={...this._functionSpecs},t.rootScope.memory={...this.rootScope.memory},t}newAsyncInstance(){let t=pt.newInstance(this.options);return t.rootScope.memory=this.rootScope.memory,t._functionsRegistry=this._functionsRegistry,t._functionSpecs=this._functionSpecs,t}};_._globalFunctionsRegistry={},_._globalFunctionSpecs={},_._cache=new Map;var it=_,pt=class s extends it{constructor(e){super(e)}async visitRootAST(e){var r;let t=e.body,n;for(let a of t)if(n=await this.visit(a),n instanceof y)return(r=n.value)!=null?r:null;return n!=null?n:null}async visitBlockStatementAST(e){let t=e.body,n;this.pushScope("Block");for(let r of t)if(n=await this.visit(r),n instanceof R||n instanceof y)break;return this.popScope(),n}async visitIdentifierAST(e){let t=e.value;return this.resolve(t)}async visitLiteralAST(e){return e.value}async visitAssignmentExpressionAST(e){let t=e.identifier,n=e.init,r=null;if(t instanceof w){var a=await this.visit(t.owner);r=await this.visit(e.init);var o=await this.visit(t.key);this.assignProperty(a,o,r)}else t instanceof E&&(r=await this.visit(n),this.changeVariable(t.value,r));return r}async visitExpressionStatementAST(e){let t=e.expression;return await this.visit(t)}async visitCallExpressionAST(e){var f,v;let t=e.callee,n=e.arguments,r=t.value;if(r==="_try_"){if(n.length!==1)throw new S("_try_ expects exactly one expression",e.line,e.col,e.constructor.name,void 0,{code:"invalid_try_arity",name:"_try_",argCount:n.length,minArgs:1,maxArgs:1});try{let d=await this.visit(n[0]);return d instanceof R||d instanceof y?d:this.successResult(d)}catch(d){if(d instanceof S)return this.errorResult(d);throw d}}let a=this.resolveFunction(r);if(!a){if(this._options.compatV1)return null;throw new S(`Unknown function '${r}'`,e.line,e.col,e.constructor.name,void 0,{code:"unknown_function",name:r})}let o=this.resolveFunctionSpec(r);if(o&&!dt(o,n.length))throw new S(`Function '${r}' expects ${_t(o)} argument(s), got ${n.length}`,e.line,e.col,e.constructor.name,void 0,{code:"invalid_function_arity",name:r,argCount:n.length,minArgs:J(o),maxArgs:o.maxArgs});let u=await Promise.all(n.map(d=>this.visit(d)));o&&this.validateRuntimeArgumentTypes(e,o,u),this.recordTrace("call",e,r,{argCount:u.length,returnType:(f=o==null?void 0:o.returnType)!=null?f:"any"});let p=await a(u,this);return this.recordTrace("call_result",e,r,{returnType:(v=o==null?void 0:o.returnType)!=null?v:"any",actualType:et(p)}),p}async visitBinaryExpressionAST(e){let t=e.left,n=e.right,r=e.operation,a=await this.visit(t),o=await this.visit(n);switch(r.type){case i.plus:return h(a)&&h(o)?a+o:`${a}${o}`;case i.minus:if(h(a)&&h(o))return a-o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.mult:if(h(a)&&h(o))return a*o;if(Y(a)&&h(o))return a.repeat(o);if(h(a)&&Y(o))return o.repeat(a);throw new Error(`Operation ${r.value} not allowed no num value`);case i.div:if(h(a)&&h(o)){if(o===0)throw new Error("Invalid division by 0");return a/o}throw new Error(`Operation ${r.value} not allowed no num value`);case i.mod:if(h(a)&&h(o))return a%o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.great:if(h(a)&&h(o))return a>o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.greatEq:if(h(a)&&h(o))return a>=o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.less:if(h(a)&&h(o))return a<o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.lessEq:if(h(a)&&h(o))return a<=o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.eqeq:return a===o;case i.notEq:return a!==o;default:throw new Error(`Operation ${r.value} not allowed no num value`)}}async visitUnaryExpressionAST(e){let t=e.argument,n=e.operation,r=await this.visit(t);if(n.type===i.not)return b(r)===!1;if(!h(r))throw new Error(`Operation ${n.value} not allowed no num value`);if(n.type===i.plus)return r;if(n.type===i.minus)return-r;throw new Error(`Operation ${n.value} not allowed no num value`)}async visitIfStatementAST(e){let t=e.test,n=await this.visit(t);return b(n)?await this.visit(e.consequent):e.alternate?await this.visit(e.alternate):null}async visitLogicalExpressionAST(e){let t=e.left,n=await this.visit(t);if(e.operator.type===i.nullity)return n!=null?n:await this.visit(e.right);let r=b(n);return e.operator.type===i.and?r?b(await this.visit(e.right)):!1:e.operator.type===i.or?r?!0:b(await this.visit(e.right)):!1}async visitIndexAccessorAST(e){var r,a;let t=e.owner,n=await this.visit(t);if(n==null)return null;if(Array.isArray(n)){let o=await this.visit(e.key);return h(o)&&Number.isInteger(o)&&n.length>o&&o>=0&&(r=n[o])!=null?r:null}else if(typeof n=="object"){let o=await this.visit(e.key);return(a=n[o])!=null?a:null}return null}async visitObjectProperty(e){}async visitObjectExpression(e){let t={},n=e;for(let r of n.properties)if(r instanceof O){let a=await this.visit(r.key);a=Y(a)?a:a.toString(),t[a]=await this.visit(r.value)}return t}async visitArrayExpression(e){let t=e;return await this.resolveArgumentsAsync(t.elements)}async visitWhileLoopStatement(e){this.log(`WhileLoopStatement ${e.test} ${e.body}`);let t=e.retain?[]:void 0;for(;b(await this.visit(e.test));){let n=await this.visit(e.body);if(n instanceof C)break;if(!(n instanceof M)){if(n instanceof y)return this.popScope(),n;t==null||t.push(n)}}return t}async visitForLoopStatement(e){let t=e.retain?[]:void 0,n=e.init.identifier;if(!(n instanceof E))throw new Error("Unexpected identifer found");this.pushScope("ForLoopStatement");let r=await this.visit(e.init.init);this.changeVariable(n.value,r);let a=async()=>{let u=await this.visit(e.test);if(h(u)){let p=this.resolve(n.value);return e.direction.type===i.up?u>=p:u<=p}return b(u)},o=async()=>{let u=await this.visit(e.update);if(h(u)){let p=this.resolve(n.value);if(!h(p))throw Error("Cant update value");this.changeVariable(n.value,e.direction.type===i.up?p+u:p-u)}else throw Error("Update value cant be non number")};for(;await a();){let u=await this.visit(e.body);if(u instanceof C)break;if(u instanceof M){await o();continue}if(u instanceof y)return this.popScope(),u;t==null||t.push(u),await o()}return this.popScope(),t!=null?t:null}async visitForOfStatement(e){let t=await this.visit(e.collection);if(!Array.isArray(t))throw Error("Can iterate non array object");let n=e.retain?[]:void 0;this.pushScope("ForOfStatement");for(let r of t){this._declareForIdentifier(e.identifier,r);let a=await this.visit(e.body);if(a instanceof C)break;if(!(a instanceof M)){if(a instanceof y)return this.popScope(),a;n==null||n.push(a)}}return this.popScope(),n}async visitReturnAST(e){return new y(e.value!=null?await this.visit(e.value):null)}async resolveArgumentsAsync(e){return await Promise.all(e.map(async t=>await this.visit(t)))}registerFunction(e,t,n){this._functionsRegistry[e]=t,this._functionSpecs[e]=g(e,n)}unregisterFunction(e){delete this._functionsRegistry[e],delete this._functionSpecs[e]}async execute(e,t=!0,n){let r=it.compile(e,t);return n&&Object.keys(n).forEach(a=>this.changeVariable(a,n[a])),this.resetExecutionBudget(),this.clearTrace(),await this.visit(r)}static async run(e,t=!1,n,r){return await new s(r).execute(e,t,n)}static newInstance(e){return new s(e)}clone(){var e=new s(this.options);return e._functionsRegistry={...this._functionsRegistry},e._functionSpecs={...this._functionSpecs},e.rootScope.memory={...this.rootScope.memory},e}};0&&(module.exports={AST,ArrayExpression,AssignmentExpressionAST,BinaryExpressionAST,BlockStatementAST,BreakAST,BreakBranch,CallExpressionAST,ContinueAST,ContinueBranch,ExpressionStatementAST,ForLoopStatement,ForOfStatement,IdentifierAST,IfStatementAST,IndexAccessorAST,LexerDictionary,LiteralAST,LogicalExpressionAST,LoopControl,MEventScope,MEvento,MEventoAsync,MEventoRuntimeError,NodeVisitor,ObjectExpression,ObjectProperty,ReturnAST,ReturnBranch,RootAST,Token,TokenType,TupleExpression,UnaryExpressionAST,WhileLoopStatement});
@@ -123,11 +123,27 @@ type MEventoFunctionSpec = {
123
123
  tags?: Iterable<string>;
124
124
  args?: MEventoArgSpec[];
125
125
  returnType?: string;
126
+ description?: string;
127
+ returnDescription?: string;
128
+ examples?: MEventoFunctionExample[];
129
+ metadata?: {
130
+ [name: string]: unknown;
131
+ };
132
+ };
133
+ type MEventoFunctionExample = {
134
+ title?: string;
135
+ script: string;
136
+ result?: unknown;
137
+ description?: string;
126
138
  };
127
139
  type MEventoArgSpec = {
128
140
  name: string;
129
141
  type?: string;
130
142
  required?: boolean;
143
+ description?: string;
144
+ metadata?: {
145
+ [name: string]: unknown;
146
+ };
131
147
  };
132
148
  type MEventoOptions = {
133
149
  maxSteps?: number;
@@ -489,4 +505,4 @@ declare class MEventoAsync extends MEvento {
489
505
  clone(): MEventoAsync;
490
506
  }
491
507
 
492
- export { AST, ArrayExpression, AssignmentExpressionAST, BinaryExpressionAST, BlockStatementAST, BreakAST, BreakBranch, CallExpressionAST, ContinueAST, ContinueBranch, ExpressionStatementAST, ForLoopStatement, ForOfStatement, IdentifierAST, IfStatementAST, IndexAccessorAST, LexerDictionary, LiteralAST, LogicalExpressionAST, LoopControl, MEventScope, MEvento, type MEventoArgSpec, MEventoAsync, type MEventoDiagnostic, type MEventoFBinding, type MEventoFunctionList, type MEventoFunctionSpec, type MEventoOptions, MEventoRuntimeError, type MEventoScriptManifest, type MEventoTraceEvent, type MEventoValidationError, type MEventoValidationResult, type MEventoValueSpec, NodeVisitor, ObjectExpression, ObjectProperty, ReturnAST, ReturnBranch, RootAST, Token, TokenType, TupleExpression, UnaryExpressionAST, WhileLoopStatement };
508
+ export { AST, ArrayExpression, AssignmentExpressionAST, BinaryExpressionAST, BlockStatementAST, BreakAST, BreakBranch, CallExpressionAST, ContinueAST, ContinueBranch, ExpressionStatementAST, ForLoopStatement, ForOfStatement, IdentifierAST, IfStatementAST, IndexAccessorAST, LexerDictionary, LiteralAST, LogicalExpressionAST, LoopControl, MEventScope, MEvento, type MEventoArgSpec, MEventoAsync, type MEventoDiagnostic, type MEventoFBinding, type MEventoFunctionExample, type MEventoFunctionList, type MEventoFunctionSpec, type MEventoOptions, MEventoRuntimeError, type MEventoScriptManifest, type MEventoTraceEvent, type MEventoValidationError, type MEventoValidationResult, type MEventoValueSpec, NodeVisitor, ObjectExpression, ObjectProperty, ReturnAST, ReturnBranch, RootAST, Token, TokenType, TupleExpression, UnaryExpressionAST, WhileLoopStatement };
@@ -1,8 +1,8 @@
1
- function T(a,e){let t=`Invalid token ${a.type}[${a.value}] at ${a.line}, ${a.col} ${e?`: expecting ${e} token`:""}
2
- `;throw Error(t)}function h(a){return typeof a=="number"}function wt(a){return typeof a=="boolean"}function q(a){return typeof a=="string"}function A(a){return!(a===null||h(a)&&a===0||q(a)&&a.length===0||wt(a)&&!a)}function Tt(a){let e=0,t=0,n;if(a.length===0)return e;for(t=0;t<a.length;t++)n=a.charCodeAt(t),e=(e<<5)-e+n,e|=0;return e}var i=class{};i.id=0,i.comma=1,i.semi=2,i.numberConst=3,i.stringConst=4,i.equal=5,i.lparen=6,i.rparen=7,i.eol=8,i.eof=9,i.lbrace=10,i.rbrace=11,i.lbracket=12,i.rbracket=13,i.great=14,i.greatEq=15,i.less=16,i.lessEq=17,i.eqeq=18,i.IF=19,i.ELSE=20,i.TRUE=21,i.FALSE=22,i.NULL=23,i.not=24,i.notEq=25,i.and=26,i.or=27,i.plus=28,i.minus=29,i.div=30,i.mult=31,i.mod=32,i.invalid=33,i.colon=34,i.WHILE_TILL=35,i.FOR_LOOP=36,i.up=37,i.down=38,i.with=39,i.in=40,i.TILL=41,i.BREAK=42,i.CONTINUE=43,i.nullity=44,i.RETURN=45,i.dot=46;var l=class a{constructor(e,t,n=1,r=1){this.type=e,this.value=t,this.line=n,this.col=r}static from(e,t){return new a(e,t)}toString(){return`[${this.type.toString()}, ${this.value}]`}},c=class{};c.equal=61,c.comma=44,c.semiColon=59,c.lparen=40,c.rparen=41,c.backslash=92,c.quote=34,c.squote=39,c.plus=43,c.minus=45,c.star=42,c.slash=47,c.percent=37,c.lbrace=123,c.rbrace=125,c.lbracket=91,c.rbracket=93,c.not=33,c.great=62,c.less=60,c.and=38,c.pipe=124,c.colon=58,c.questionMark=63,c.shebang=35,c.dot=46;var J=class{constructor(e,t){this.keywords={};this.keywords={...t},this.lang=e}},k=class k{constructor(e){this._position=0;this._line=1;this._col=1;this._currentChar=-1;this._source=e,this._currentChar=this._source[this._position].charCodeAt(0),this._resolveLanguage()}get source(){return this._source}_resolveLanguage(){var t;let e=this.nextToken();if(e.type===i.less){let n=this.nextToken();n.type!==i.id&&T(e);let r=n.value.toString();this._language=(t=k.languages.find(s=>s.lang===r))!=null?t:k._defaultLanguage,e=this.nextToken(),e.type!==i.great&&T(e)}else this._language=k._defaultLanguage,this._position=0,this._currentChar=this._source[this._position].charCodeAt(0)}_advance(){if(this._position++,this._position>=this._source.length){this._currentChar=-1;return}this._currentChar=this._source[this._position].charCodeAt(0),this._col++}_jump(e){if(this._position+=e,this._position>=this._source.length){this._currentChar=-1;return}this._currentChar=this._source[this._position].charCodeAt(0),this._col+=e}_pick(){return this._position+1>=this._source.length?-1:this._source[this._position+1].charCodeAt(0)}_isId(e){return e<48?e===36:e<58?!0:e<65?!1:e<91?!0:e<97?e===95:e<123}_isIdStart(e){return e<65?e===36:e<91?!0:e<97?e===95:e<123}_id(){var o,u;let e="",t=this._col,n=this._position,r=this._line;for(;this._isId(this._currentChar);)e+=String.fromCharCode(this._currentChar),this._advance();let s=this._language&&(o=this._language.keywords[e])!=null?o:e;return(u=k.RESERVED[s])!=null?u:new l(i.id,e,r,t)}_isLineEnd(e){return e===10||e===13||[`
3
- `,"\r","\u2028","\u2029"].includes(String.fromCharCode(e))}_isWhiteSpace(e){return[" "," "].includes(String.fromCharCode(e))}_isDigit(e){return e>0&&(e^48)<=9}_skipWhiteSpace(){for(;this._isWhiteSpace(this._currentChar)===!0;)this._advance()}_number(){let e="",t=this._col,n=this._position,r=this._line,s=String.fromCharCode(this._currentChar);this._advance();let o=String.fromCharCode(this._currentChar),u=10;if(s==="0"&&["b","B","x","X","o","O"].includes(o))switch(this._advance(),o.toLowerCase()){case"b":u=2;break;case"o":u=8;break;case"x":u=16;break;default:u=10}else e+=s,u=10;for(;this._isDigit(this._currentChar)||u===16&&["A","a","B","b","C","c","D","d","E","e","F","f"].includes(String.fromCharCode(this._currentChar));)e+=String.fromCharCode(this._currentChar),this._advance();if(String.fromCharCode(this._currentChar)==="."&&this._isDigit(this._pick())===!0){for(u!==10&&T(new l(i.id,o,r,n)),e+=String.fromCharCode(this._currentChar),this._advance();this._isDigit(this._currentChar);)e+=String.fromCharCode(this._currentChar),this._advance();return new l(i.numberConst,parseFloat(e),r,t)}return new l(i.numberConst,parseInt(e,u),r,t)}_literalString(e){let t="",n=-1,r=this._position,s=this._col,o=this._line;for(;this._currentChar!==-1;){let u=String.fromCharCode(this._pick());if(this._currentChar==c.backslash){switch(u){case"\\":t+="\\";break;case"0":t+="\0";break;case"a":t+="a";break;case"b":t+="\b";break;case"f":t+="\f";break;case"n":t+=`
4
- `;break;case"r":t+="\r";break;case"t":t+=" ";break;case"u":t+=String.fromCharCode(Number.parseInt(this._source.substring(this._position+2,this._position+6),16)),this._jump(4);break;case"v":t+="\v";break;case"x":t+=String.fromCharCode(Number.parseInt(this._source.substring(this._position+2,this._position+4),16)),this._jump(2);break;default:if(String.fromCharCode(e)==u)t+=String.fromCharCode(e);else{this._advance(),n=this._currentChar,t+=String.fromCharCode(this._currentChar),this._advance();continue}}this._jump(2),n=this._currentChar;continue}if(this._currentChar===e&&n!==c.backslash)break;t+=String.fromCharCode(this._currentChar),n=this._currentChar,this._advance()}return new l(i.stringConst,t,o,s)}_skipLineComment(){for(;!this._isLineEnd(this._currentChar)&&this._currentChar!=-1;)this._advance()}_skipComment(){for(;this._currentChar!==-1;){if(this._currentChar===c.star&&this._pick()===c.shebang){this._advance(),this._advance();break}this._advance()}}nextToken(){let e=this._line,t=this._col,n=this._position;for(;this._currentChar!==-1;){if(this._isLineEnd(this._currentChar))return this._line++,this._col=1,this._advance(),new l(i.eol,`
5
- `,e,t);if(this._isWhiteSpace(this._currentChar)){this._skipWhiteSpace();continue}if(this._currentChar==c.shebang){this._advance(),this._currentChar===c.star?(this._advance(),this._skipComment()):this._skipLineComment();continue}if(this._isDigit(this._currentChar))return this._number();if(this._isIdStart(this._currentChar))return this._id();if(this._currentChar===c.equal)return this._advance(),this._currentChar===c.equal?(this._advance(),new l(i.eqeq,"==",e,t)):new l(i.equal,"=",e,t);if(this._currentChar===c.great)return this._advance(),this._currentChar===c.equal?(this._advance(),new l(i.greatEq,">=",e,t)):new l(i.great,">",e,t);if(this._currentChar===c.less)return this._advance(),this._currentChar===c.equal?(this._advance(),new l(i.lessEq,"<=",e,t)):new l(i.less,"<",e,t);if(this._currentChar===c.semiColon)return this._advance(),new l(i.semi,";",e,t);if(this._currentChar===c.lparen)return this._advance(),new l(i.lparen,"(",e,t);if(this._currentChar===c.rparen)return this._advance(),new l(i.rparen,")",e,t);if(this._currentChar===c.comma)return this._advance(),new l(i.comma,",",e,t);if(this._currentChar===c.lbrace)return this._advance(),new l(i.lbrace,"{",e,t);if(this._currentChar===c.rbrace)return this._advance(),new l(i.rbrace,"}",e,t);if(this._currentChar===c.lbracket)return this._advance(),new l(i.lbracket,"[",e,t);if(this._currentChar===c.rbracket)return this._advance(),new l(i.rbracket,"]",e,t);if(this._currentChar===c.plus)return this._advance(),new l(i.plus,"+",e,t);if(this._currentChar===c.minus)return this._advance(),new l(i.minus,"-",e,t);if(this._currentChar===c.slash)return this._advance(),new l(i.div,"/",e,t);if(this._currentChar===c.star)return this._advance(),new l(i.mult,"*",e,t);if(this._currentChar===c.percent)return this._advance(),new l(i.mod,"%",e,t);if(this._currentChar===c.colon)return this._advance(),new l(i.colon,":",e,t);if(this._currentChar===c.dot)return this._advance(),new l(i.dot,".",e,t);if(this._currentChar===c.not)return this._advance(),this._currentChar===c.equal?(this._advance(),new l(i.notEq,"!=",e,t)):new l(i.not,"!",e,t);if(this._currentChar===c.and&&this._pick()===c.and)return this._advance(),this._advance(),new l(i.and,"&&",e,t);if(this._currentChar===c.pipe&&this._pick()===c.pipe)return this._advance(),this._advance(),new l(i.or,"||",e,t);if(this._currentChar===c.questionMark&&this._pick()===c.questionMark)return this._advance(),this._advance(),new l(i.nullity,"??",e,t);if(this._currentChar===c.quote||this._currentChar===c.squote){let r=this._currentChar;this._advance();let s=this._literalString(r);return this._advance(),s}return new l(i.invalid,String.fromCharCode(this._currentChar),e,t)}return new l(i.eof,"",e,t)}};k._defaultLanguage=new J("en",{if:"if",else:"else",true:"true",false:"false",null:"null",while:"while",for:"for",with:"with",up:"up",down:"down",till:"till",in:"in",break:"break",continue:"continue",return:"return"}),k.languages=[k._defaultLanguage,new J("fr",{si:"if",sinon:"else",vrai:"true",faux:"false",nul:"null",tanque:"while",pour:"for",avec:"with",mont:"up",desc:"down",jusqua:"till",dans:"in",couper:"break",continuer:"continue",returner:"return"}),new J("bm",{nii:"if",note:"else",tien:"true",galon:"false",gansan:"null",foo:"while",seginka:"for",niin:"with",kay:"up",kaj:"down",kata:"till",kono:"in",tike:"break",ipan:"continue",segin:"return"})],k.RESERVED={if:l.from(i.IF,"if"),else:l.from(i.ELSE,"else"),true:l.from(i.TRUE,!0),false:l.from(i.FALSE,!1),null:l.from(i.NULL,null),for:l.from(i.FOR_LOOP,"for"),while:l.from(i.WHILE_TILL,"while"),with:l.from(i.with,"with"),up:l.from(i.up,"up"),down:l.from(i.down,"down"),till:l.from(i.TILL,"till"),in:l.from(i.in,"in"),break:l.from(i.BREAK,"break"),continue:l.from(i.CONTINUE,"continue"),return:l.from(i.RETURN,"return")};var ht=k,v=class{constructor(e,t){this.line=e,this.col=t}dump(){return this.toString()}},S=class a extends Error{constructor(e,t,n,r,s,o){var u;super(a.format(e,t,n,r)),this.name="MEventoRuntimeError",this.detail=e,this.line=t,this.col=n,this.nodeType=r,this.cause=s,this.code=(u=o==null?void 0:o.code)!=null?u:"runtime_error",this.diagnosticName=o==null?void 0:o.name,this.argCount=o==null?void 0:o.argCount,this.minArgs=o==null?void 0:o.minArgs,this.maxArgs=o==null?void 0:o.maxArgs,this.argIndex=o==null?void 0:o.argIndex,this.expectedType=o==null?void 0:o.expectedType,this.actualType=o==null?void 0:o.actualType,this.stepCount=o==null?void 0:o.stepCount,this.maxSteps=o==null?void 0:o.maxSteps}static fromNode(e,t){if(t instanceof a)return t;let n=t instanceof Error?t.message:String(t);return new a(n,e.line,e.col,e.constructor.name,t)}static format(e,t,n,r){let s=t!=null&&n!=null?` at ${t}:${n}`:"",o=r?` [${r}]`:"";return`MEvento runtime error${s}${o}: ${e}`}diagnostic(){return{code:this.code,message:this.detail,line:this.line,col:this.col,node:this.nodeType,name:this.diagnosticName,argCount:this.argCount,minArgs:this.minArgs,maxArgs:this.maxArgs,argIndex:this.argIndex,expectedType:this.expectedType,actualType:this.actualType,stepCount:this.stepCount,maxSteps:this.maxSteps}}};function g(a,e){var r;let t={name:a,minArgs:e==null?void 0:e.minArgs,maxArgs:e==null?void 0:e.maxArgs,tags:e!=null&&e.tags?Array.from(e.tags):[],args:e!=null&&e.args?e.args.map(kt):[],returnType:(r=e==null?void 0:e.returnType)!=null?r:"any"};if(t.minArgs!=null&&t.minArgs<0)throw new Error("minArgs must be greater than or equal to 0");if(t.maxArgs!=null&&t.maxArgs<0)throw new Error("maxArgs must be greater than or equal to 0");let n=Q(t);if(n!=null&&t.maxArgs!=null&&n>t.maxArgs)throw new Error("minArgs must be less than or equal to maxArgs");if(!St.has(t.returnType))throw new Error(`Unsupported return type '${t.returnType}'`);return t}function kt(a){var t,n;let e={name:a.name,type:(t=a.type)!=null?t:"any",required:(n=a.required)!=null?n:!0};if(!Ct.has(e.type))throw new Error(`Unsupported argument type '${e.type}'`);return e}var St=new Set(["any","null","boolean","number","string","array","object"]),Ct=St;function Mt(a){var t,n;let e={maxSteps:a==null?void 0:a.maxSteps,trace:(t=a==null?void 0:a.trace)!=null?t:!1,compatV1:(n=a==null?void 0:a.compatV1)!=null?n:!1};if(e.maxSteps!=null&&(!Number.isInteger(e.maxSteps)||e.maxSteps<=0))throw new Error("maxSteps must be a positive integer");return e}function bt(a){var t,n;let e={name:a.name,type:(t=a.type)!=null?t:"any",required:(n=a.required)!=null?n:!0};if(!St.has(e.type))throw new Error(`Unsupported value type '${e.type}'`);return e}function Lt(a){var e;return{name:a.name,minArgs:a.minArgs,maxArgs:a.maxArgs,tags:a.tags?Array.from(a.tags):[],args:a.args?a.args.map(t=>({...t})):[],returnType:(e=a.returnType)!=null?e:"any"}}function xt(a){return Object.fromEntries(Object.entries(a).map(([e,t])=>[e,Lt(t)]))}function pt(a,e){let t=Q(a);return!(t!=null&&e<t||a.maxArgs!=null&&e>a.maxArgs)}function Q(a){var n;let e=0;if(a.args){for(let r=a.args.length-1;r>=0;r-=1)if((n=a.args[r].required)==null||n){e=r+1;break}}let t=[a.minArgs,e>0?e:void 0].filter(r=>r!=null);return t.length>0?Math.max(...t):void 0}function ft(a){let e=Q(a);return e==null&&a.maxArgs==null?"any number of":e!=null&&a.maxArgs!=null&&e===a.maxArgs?String(e):e!=null&&a.maxArgs!=null?`${e}..${a.maxArgs}`:e!=null?`at least ${e}`:`at most ${a.maxArgs}`}function Z(a){return a==null?"null":typeof a=="boolean"?"boolean":typeof a=="number"?"number":typeof a=="string"?"string":Array.isArray(a)?"array":"object"}var j=class extends v{constructor(e,t,n){super(1,1),this.body=e,this.name=t,this.source=n}dump(){let e=`Module ${this.name} Start {`;for(let t of this.body)e+=`${t.dump()}
1
+ function T(s,e){let t=`Invalid token ${s.type}[${s.value}] at ${s.line}, ${s.col} ${e?`: expecting ${e} token`:""}
2
+ `;throw Error(t)}function h(s){return typeof s=="number"}function Ct(s){return typeof s=="boolean"}function q(s){return typeof s=="string"}function A(s){return!(s===null||h(s)&&s===0||q(s)&&s.length===0||Ct(s)&&!s)}function Mt(s){let e=0,t=0,n;if(s.length===0)return e;for(t=0;t<s.length;t++)n=s.charCodeAt(t),e=(e<<5)-e+n,e|=0;return e}var i=class{};i.id=0,i.comma=1,i.semi=2,i.numberConst=3,i.stringConst=4,i.equal=5,i.lparen=6,i.rparen=7,i.eol=8,i.eof=9,i.lbrace=10,i.rbrace=11,i.lbracket=12,i.rbracket=13,i.great=14,i.greatEq=15,i.less=16,i.lessEq=17,i.eqeq=18,i.IF=19,i.ELSE=20,i.TRUE=21,i.FALSE=22,i.NULL=23,i.not=24,i.notEq=25,i.and=26,i.or=27,i.plus=28,i.minus=29,i.div=30,i.mult=31,i.mod=32,i.invalid=33,i.colon=34,i.WHILE_TILL=35,i.FOR_LOOP=36,i.up=37,i.down=38,i.with=39,i.in=40,i.TILL=41,i.BREAK=42,i.CONTINUE=43,i.nullity=44,i.RETURN=45,i.dot=46;var l=class s{constructor(e,t,n=1,r=1){this.type=e,this.value=t,this.line=n,this.col=r}static from(e,t){return new s(e,t)}toString(){return`[${this.type.toString()}, ${this.value}]`}},c=class{};c.equal=61,c.comma=44,c.semiColon=59,c.lparen=40,c.rparen=41,c.backslash=92,c.quote=34,c.squote=39,c.plus=43,c.minus=45,c.star=42,c.slash=47,c.percent=37,c.lbrace=123,c.rbrace=125,c.lbracket=91,c.rbracket=93,c.not=33,c.great=62,c.less=60,c.and=38,c.pipe=124,c.colon=58,c.questionMark=63,c.shebang=35,c.dot=46;var J=class{constructor(e,t){this.keywords={};this.keywords={...t},this.lang=e}},k=class k{constructor(e){this._position=0;this._line=1;this._col=1;this._currentChar=-1;this._source=e,this._currentChar=this._source[this._position].charCodeAt(0),this._resolveLanguage()}get source(){return this._source}_resolveLanguage(){var t;let e=this.nextToken();if(e.type===i.less){let n=this.nextToken();n.type!==i.id&&T(e);let r=n.value.toString();this._language=(t=k.languages.find(a=>a.lang===r))!=null?t:k._defaultLanguage,e=this.nextToken(),e.type!==i.great&&T(e)}else this._language=k._defaultLanguage,this._position=0,this._currentChar=this._source[this._position].charCodeAt(0)}_advance(){if(this._position++,this._position>=this._source.length){this._currentChar=-1;return}this._currentChar=this._source[this._position].charCodeAt(0),this._col++}_jump(e){if(this._position+=e,this._position>=this._source.length){this._currentChar=-1;return}this._currentChar=this._source[this._position].charCodeAt(0),this._col+=e}_pick(){return this._position+1>=this._source.length?-1:this._source[this._position+1].charCodeAt(0)}_isId(e){return e<48?e===36:e<58?!0:e<65?!1:e<91?!0:e<97?e===95:e<123}_isIdStart(e){return e<65?e===36:e<91?!0:e<97?e===95:e<123}_id(){var o,u;let e="",t=this._col,n=this._position,r=this._line;for(;this._isId(this._currentChar);)e+=String.fromCharCode(this._currentChar),this._advance();let a=this._language&&(o=this._language.keywords[e])!=null?o:e;return(u=k.RESERVED[a])!=null?u:new l(i.id,e,r,t)}_isLineEnd(e){return e===10||e===13||[`
3
+ `,"\r","\u2028","\u2029"].includes(String.fromCharCode(e))}_isWhiteSpace(e){return[" "," "].includes(String.fromCharCode(e))}_isDigit(e){return e>0&&(e^48)<=9}_skipWhiteSpace(){for(;this._isWhiteSpace(this._currentChar)===!0;)this._advance()}_number(){let e="",t=this._col,n=this._position,r=this._line,a=String.fromCharCode(this._currentChar);this._advance();let o=String.fromCharCode(this._currentChar),u=10;if(a==="0"&&["b","B","x","X","o","O"].includes(o))switch(this._advance(),o.toLowerCase()){case"b":u=2;break;case"o":u=8;break;case"x":u=16;break;default:u=10}else e+=a,u=10;for(;this._isDigit(this._currentChar)||u===16&&["A","a","B","b","C","c","D","d","E","e","F","f"].includes(String.fromCharCode(this._currentChar));)e+=String.fromCharCode(this._currentChar),this._advance();if(String.fromCharCode(this._currentChar)==="."&&this._isDigit(this._pick())===!0){for(u!==10&&T(new l(i.id,o,r,n)),e+=String.fromCharCode(this._currentChar),this._advance();this._isDigit(this._currentChar);)e+=String.fromCharCode(this._currentChar),this._advance();return new l(i.numberConst,parseFloat(e),r,t)}return new l(i.numberConst,parseInt(e,u),r,t)}_literalString(e){let t="",n=-1,r=this._position,a=this._col,o=this._line;for(;this._currentChar!==-1;){let u=String.fromCharCode(this._pick());if(this._currentChar==c.backslash){switch(u){case"\\":t+="\\";break;case"0":t+="\0";break;case"a":t+="a";break;case"b":t+="\b";break;case"f":t+="\f";break;case"n":t+=`
4
+ `;break;case"r":t+="\r";break;case"t":t+=" ";break;case"u":t+=String.fromCharCode(Number.parseInt(this._source.substring(this._position+2,this._position+6),16)),this._jump(4);break;case"v":t+="\v";break;case"x":t+=String.fromCharCode(Number.parseInt(this._source.substring(this._position+2,this._position+4),16)),this._jump(2);break;default:if(String.fromCharCode(e)==u)t+=String.fromCharCode(e);else{this._advance(),n=this._currentChar,t+=String.fromCharCode(this._currentChar),this._advance();continue}}this._jump(2),n=this._currentChar;continue}if(this._currentChar===e&&n!==c.backslash)break;t+=String.fromCharCode(this._currentChar),n=this._currentChar,this._advance()}return new l(i.stringConst,t,o,a)}_skipLineComment(){for(;!this._isLineEnd(this._currentChar)&&this._currentChar!=-1;)this._advance()}_skipComment(){for(;this._currentChar!==-1;){if(this._currentChar===c.star&&this._pick()===c.shebang){this._advance(),this._advance();break}this._advance()}}nextToken(){let e=this._line,t=this._col,n=this._position;for(;this._currentChar!==-1;){if(this._isLineEnd(this._currentChar))return this._line++,this._col=1,this._advance(),new l(i.eol,`
5
+ `,e,t);if(this._isWhiteSpace(this._currentChar)){this._skipWhiteSpace();continue}if(this._currentChar==c.shebang){this._advance(),this._currentChar===c.star?(this._advance(),this._skipComment()):this._skipLineComment();continue}if(this._isDigit(this._currentChar))return this._number();if(this._isIdStart(this._currentChar))return this._id();if(this._currentChar===c.equal)return this._advance(),this._currentChar===c.equal?(this._advance(),new l(i.eqeq,"==",e,t)):new l(i.equal,"=",e,t);if(this._currentChar===c.great)return this._advance(),this._currentChar===c.equal?(this._advance(),new l(i.greatEq,">=",e,t)):new l(i.great,">",e,t);if(this._currentChar===c.less)return this._advance(),this._currentChar===c.equal?(this._advance(),new l(i.lessEq,"<=",e,t)):new l(i.less,"<",e,t);if(this._currentChar===c.semiColon)return this._advance(),new l(i.semi,";",e,t);if(this._currentChar===c.lparen)return this._advance(),new l(i.lparen,"(",e,t);if(this._currentChar===c.rparen)return this._advance(),new l(i.rparen,")",e,t);if(this._currentChar===c.comma)return this._advance(),new l(i.comma,",",e,t);if(this._currentChar===c.lbrace)return this._advance(),new l(i.lbrace,"{",e,t);if(this._currentChar===c.rbrace)return this._advance(),new l(i.rbrace,"}",e,t);if(this._currentChar===c.lbracket)return this._advance(),new l(i.lbracket,"[",e,t);if(this._currentChar===c.rbracket)return this._advance(),new l(i.rbracket,"]",e,t);if(this._currentChar===c.plus)return this._advance(),new l(i.plus,"+",e,t);if(this._currentChar===c.minus)return this._advance(),new l(i.minus,"-",e,t);if(this._currentChar===c.slash)return this._advance(),new l(i.div,"/",e,t);if(this._currentChar===c.star)return this._advance(),new l(i.mult,"*",e,t);if(this._currentChar===c.percent)return this._advance(),new l(i.mod,"%",e,t);if(this._currentChar===c.colon)return this._advance(),new l(i.colon,":",e,t);if(this._currentChar===c.dot)return this._advance(),new l(i.dot,".",e,t);if(this._currentChar===c.not)return this._advance(),this._currentChar===c.equal?(this._advance(),new l(i.notEq,"!=",e,t)):new l(i.not,"!",e,t);if(this._currentChar===c.and&&this._pick()===c.and)return this._advance(),this._advance(),new l(i.and,"&&",e,t);if(this._currentChar===c.pipe&&this._pick()===c.pipe)return this._advance(),this._advance(),new l(i.or,"||",e,t);if(this._currentChar===c.questionMark&&this._pick()===c.questionMark)return this._advance(),this._advance(),new l(i.nullity,"??",e,t);if(this._currentChar===c.quote||this._currentChar===c.squote){let r=this._currentChar;this._advance();let a=this._literalString(r);return this._advance(),a}return new l(i.invalid,String.fromCharCode(this._currentChar),e,t)}return new l(i.eof,"",e,t)}};k._defaultLanguage=new J("en",{if:"if",else:"else",true:"true",false:"false",null:"null",while:"while",for:"for",with:"with",up:"up",down:"down",till:"till",in:"in",break:"break",continue:"continue",return:"return"}),k.languages=[k._defaultLanguage,new J("fr",{si:"if",sinon:"else",vrai:"true",faux:"false",nul:"null",tanque:"while",pour:"for",avec:"with",mont:"up",desc:"down",jusqua:"till",dans:"in",couper:"break",continuer:"continue",returner:"return"}),new J("bm",{nii:"if",note:"else",tien:"true",galon:"false",gansan:"null",foo:"while",seginka:"for",niin:"with",kay:"up",kaj:"down",kata:"till",kono:"in",tike:"break",ipan:"continue",segin:"return"})],k.RESERVED={if:l.from(i.IF,"if"),else:l.from(i.ELSE,"else"),true:l.from(i.TRUE,!0),false:l.from(i.FALSE,!1),null:l.from(i.NULL,null),for:l.from(i.FOR_LOOP,"for"),while:l.from(i.WHILE_TILL,"while"),with:l.from(i.with,"with"),up:l.from(i.up,"up"),down:l.from(i.down,"down"),till:l.from(i.TILL,"till"),in:l.from(i.in,"in"),break:l.from(i.BREAK,"break"),continue:l.from(i.CONTINUE,"continue"),return:l.from(i.RETURN,"return")};var ft=k,v=class{constructor(e,t){this.line=e,this.col=t}dump(){return this.toString()}},S=class s extends Error{constructor(e,t,n,r,a,o){var u;super(s.format(e,t,n,r)),this.name="MEventoRuntimeError",this.detail=e,this.line=t,this.col=n,this.nodeType=r,this.cause=a,this.code=(u=o==null?void 0:o.code)!=null?u:"runtime_error",this.diagnosticName=o==null?void 0:o.name,this.argCount=o==null?void 0:o.argCount,this.minArgs=o==null?void 0:o.minArgs,this.maxArgs=o==null?void 0:o.maxArgs,this.argIndex=o==null?void 0:o.argIndex,this.expectedType=o==null?void 0:o.expectedType,this.actualType=o==null?void 0:o.actualType,this.stepCount=o==null?void 0:o.stepCount,this.maxSteps=o==null?void 0:o.maxSteps}static fromNode(e,t){if(t instanceof s)return t;let n=t instanceof Error?t.message:String(t);return new s(n,e.line,e.col,e.constructor.name,t)}static format(e,t,n,r){let a=t!=null&&n!=null?` at ${t}:${n}`:"",o=r?` [${r}]`:"";return`MEvento runtime error${a}${o}: ${e}`}diagnostic(){return{code:this.code,message:this.detail,line:this.line,col:this.col,node:this.nodeType,name:this.diagnosticName,argCount:this.argCount,minArgs:this.minArgs,maxArgs:this.maxArgs,argIndex:this.argIndex,expectedType:this.expectedType,actualType:this.actualType,stepCount:this.stepCount,maxSteps:this.maxSteps}}};function g(s,e){var r;let t={name:s,minArgs:e==null?void 0:e.minArgs,maxArgs:e==null?void 0:e.maxArgs,tags:e!=null&&e.tags?Array.from(e.tags):[],args:e!=null&&e.args?e.args.map(Lt):[],returnType:(r=e==null?void 0:e.returnType)!=null?r:"any"};if((e==null?void 0:e.description)!=null&&(t.description=e.description),(e==null?void 0:e.returnDescription)!=null&&(t.returnDescription=e.returnDescription),(e==null?void 0:e.examples)!=null&&(t.examples=e.examples.map(kt)),(e==null?void 0:e.metadata)!=null&&(t.metadata=ut(e.metadata)),t.minArgs!=null&&t.minArgs<0)throw new Error("minArgs must be greater than or equal to 0");if(t.maxArgs!=null&&t.maxArgs<0)throw new Error("maxArgs must be greater than or equal to 0");let n=Q(t);if(n!=null&&t.maxArgs!=null&&n>t.maxArgs)throw new Error("minArgs must be less than or equal to maxArgs");if(!At.has(t.returnType))throw new Error(`Unsupported return type '${t.returnType}'`);return t}function Lt(s){var t,n;let e={name:s.name,type:(t=s.type)!=null?t:"any",required:(n=s.required)!=null?n:!0};if(s.description!=null&&(e.description=s.description),s.metadata!=null&&(e.metadata=ut(s.metadata)),!Ot.has(e.type))throw new Error(`Unsupported argument type '${e.type}'`);return e}var At=new Set(["any","null","boolean","number","string","array","object"]),Ot=At;function Nt(s){var t,n;let e={maxSteps:s==null?void 0:s.maxSteps,trace:(t=s==null?void 0:s.trace)!=null?t:!1,compatV1:(n=s==null?void 0:s.compatV1)!=null?n:!1};if(e.maxSteps!=null&&(!Number.isInteger(e.maxSteps)||e.maxSteps<=0))throw new Error("maxSteps must be a positive integer");return e}function xt(s){var t,n;let e={name:s.name,type:(t=s.type)!=null?t:"any",required:(n=s.required)!=null?n:!0};if(!At.has(e.type))throw new Error(`Unsupported value type '${e.type}'`);return e}function ot(s){return Array.isArray(s)?s.map(ot):s!=null&&typeof s=="object"?Object.fromEntries(Object.entries(s).map(([e,t])=>[e,ot(t)])):s}function ut(s){return s==null?void 0:ot(s)}function kt(s){let e={script:s.script};return s.title!=null&&(e.title=s.title),s.result!==void 0&&(e.result=ot(s.result)),s.description!=null&&(e.description=s.description),e}function It(s){var t;let e={name:s.name,minArgs:s.minArgs,maxArgs:s.maxArgs,tags:s.tags?Array.from(s.tags):[],args:s.args?s.args.map(n=>{let r={name:n.name,type:n.type,required:n.required};return n.description!=null&&(r.description=n.description),n.metadata!=null&&(r.metadata=ut(n.metadata)),r}):[],returnType:(t=s.returnType)!=null?t:"any"};return s.description!=null&&(e.description=s.description),s.returnDescription!=null&&(e.returnDescription=s.returnDescription),s.examples!=null&&(e.examples=s.examples.map(kt)),s.metadata!=null&&(e.metadata=ut(s.metadata)),e}function wt(s){return Object.fromEntries(Object.entries(s).map(([e,t])=>[e,It(t)]))}function mt(s,e){let t=Q(s);return!(t!=null&&e<t||s.maxArgs!=null&&e>s.maxArgs)}function Q(s){var n;let e=0;if(s.args){for(let r=s.args.length-1;r>=0;r-=1)if((n=s.args[r].required)==null||n){e=r+1;break}}let t=[s.minArgs,e>0?e:void 0].filter(r=>r!=null);return t.length>0?Math.max(...t):void 0}function vt(s){let e=Q(s);return e==null&&s.maxArgs==null?"any number of":e!=null&&s.maxArgs!=null&&e===s.maxArgs?String(e):e!=null&&s.maxArgs!=null?`${e}..${s.maxArgs}`:e!=null?`at least ${e}`:`at most ${s.maxArgs}`}function Z(s){return s==null?"null":typeof s=="boolean"?"boolean":typeof s=="number"?"number":typeof s=="string"?"string":Array.isArray(s)?"array":"object"}var j=class extends v{constructor(e,t,n){super(1,1),this.body=e,this.name=t,this.source=n}dump(){let e=`Module ${this.name} Start {`;for(let t of this.body)e+=`${t.dump()}
6
6
  `;return e+="}",e}},R=class extends v{constructor(e,t){super(t.line,t.col),this.body=e}toString(){return`{
7
7
  ${this.body.map(e=>e.toString()).join(`
8
- `)}}`}},E=class extends v{constructor(e){super(e.line,e.col),this.value=e.value.toString()}toString(){return this.value}},x=class extends v{constructor(e,t){super(e.line,e.col),this.value=e.value,this.raw=t}toString(){return this.value.toString()}},L=class extends v{constructor(e,t){super(e.line,e.col),this.identifier=e,this.init=t}toString(){return`${this.identifier} = ${this.init}`}},X=class extends v{constructor(e){super(e.line,e.col),this.expression=e}toString(){return this.expression.toString()}},P=class extends v{constructor(e,t){super(e.line,e.col),this.callee=e,this.arguments=t}toString(){return`${this.callee.toString()}(...${this.arguments.length})`}},z=class extends v{constructor(e,t,n){super(e.line,e.col),this.left=e,this.operation=t,this.right=n}toString(){return`${this.left} ${this.operation} ${this.right}`}},U=class extends v{constructor(e,t){super(e.line,e.col),this.operation=e,this.argument=t}toString(){return`${this.operation} ${this.argument}`}},W=class extends v{constructor(e,t,n){super(e.line,e.col),this.test=e,this.consequent=t,this.alternate=n}toString(){return`if ${this.test} ${this.consequent} ${this.alternate?`else ${this.alternate} `:""}`}},B=class extends v{constructor(e,t,n){super(e.line,e.col),this.left=e,this.operator=t,this.right=n}toString(){return`${this.left} ${this.operator.value} ${this.right}`}},w=class extends v{constructor(t,n,r=!1){super(t.line,t.col);this.computed=!1;this.owner=t,this.key=n,this.computed=r}toString(){return`${this.owner}[${this.key}]`}},$=class extends v{constructor(e,t,n){super(t==null?void 0:t.line,t==null?void 0:t.col),this.properties=e}toString(){return"{...}"}},F=class extends v{constructor(e,t,n){super(t==null?void 0:t.line,t==null?void 0:t.col),this.elements=e}toString(){return"[...]"}},O=class extends v{constructor(e,t){super(e.line,e.col),this.value=t,this.key=e}},D=class extends v{constructor(t,n,r,s,o=!1){super(r==null?void 0:r.line,r==null?void 0:r.col);this.retain=!1;this.test=t,this.body=n,this.retain=o}},K=class extends v{constructor(t,n,r,s,o,u,p,f=!1){super(u==null?void 0:u.line,u==null?void 0:u.col);this.init=t;this.test=n;this.update=r;this.direction=s;this.body=o;this.retain=f}},H=class extends v{constructor(t,n,r,s,o,u=!1){super(s==null?void 0:s.line,s==null?void 0:s.col);this.identifier=t;this.collection=n;this.body=r;this.retain=u}},I=class extends v{constructor(t,n){super(t.line,t.col);this.first=t;this.second=n}},et=class extends v{constructor(e,t){super(e,t)}},Y=class extends v{constructor(e,t,n){super(t,n),this.value=e}},nt=class extends v{constructor(e,t){super(e,t)}};function Ot(a){return a instanceof j?"RootAST":a instanceof R?"BlockStatementAST":a instanceof E?"IdentifierAST":a instanceof x?"LiteralAST":a instanceof L?"AssignmentExpressionAST":a instanceof X?"ExpressionStatementAST":a instanceof P?"CallExpressionAST":a instanceof z?"BinaryExpressionAST":a instanceof U?"UnaryExpressionAST":a instanceof W?"IfStatementAST":a instanceof B?"LogicalExpressionAST":a instanceof w?"IndexAccessorAST":a instanceof $?"ObjectExpression":a instanceof O?"ObjectProperty":a instanceof F?"ArrayExpression":a instanceof D?"WhileLoopStatement":a instanceof K?"ForLoopStatement":a instanceof H?"ForOfStatement":a instanceof I?"TupleExpression":a instanceof et?"BreakAST":a instanceof Y?"ReturnAST":a instanceof nt?"ContinueAST":a.constructor.name}var mt=class{constructor(e=1/0){this.capacity=e;this.storage=[]}push(e){if(this.size()===this.capacity)throw Error("Stack has reached max capacity, you cannot add more items");this.storage.push(e)}pop(){return this.storage.pop()}peek(){return this.storage[this.size()-1]}size(){return this.storage.length}get isEmpty(){return this.storage.length===0}},tt=class tt{constructor(e){this._loopTrack=new mt;this.currentToken=e.nextToken(),this.lexer=e}_eat(e){var t;((t=this.currentToken)==null?void 0:t.type)===e?this.currentToken=this.lexer.nextToken():T(this.currentToken,e)}_eatEOL(){var e;for(;((e=this.currentToken)==null?void 0:e.type)===i.eol;)this._eat(i.eol)}_eatSemiOrEOL(){var e,t;for(;((e=this.currentToken)==null?void 0:e.type)===i.eol||((t=this.currentToken)==null?void 0:t.type)===i.semi;)this._eat(this.currentToken.type)}_eatSemi(){var e;for(;((e=this.currentToken)==null?void 0:e.type)===i.semi;)this._eat(i.semi)}_variable(){let e=new E(this.currentToken);return this._eat(i.id),e}_return(){let e=this.currentToken,t;return!this._expect(i.eol)&&!this._expect(i.semi)&&(t=this._expression()),new Y(t,e==null?void 0:e.line,e==null?void 0:e.col)}_factor(){let e=this.currentToken;switch(e.type){case i.plus:case i.minus:case i.not:return this._eat(this.currentToken.type),new U(e,this._term());case i.numberConst:return this._eat(i.numberConst),new x(e,e.value.toString());case i.stringConst:return this._eat(i.stringConst),new x(e,e.value.toString());case i.lparen:this._eat(i.lparen);let t=this._expression();return this._eat(i.rparen),t;case i.TRUE:case i.FALSE:return this._eat(this.currentToken.type),new x(e,e.value.toString());case i.NULL:return this._eat(i.NULL),new x(e,"null");case i.lbracket:return this._arrayExpression();case i.lbrace:return this._objectExpression();case i.IF:return this._ifStatement();case i.WHILE_TILL:return this._whileLoop(!0);case i.FOR_LOOP:return this._forLoop(!0);case i.BREAK:return this._breakExpression();case i.CONTINUE:return this._continueExpression();default:return this._variable()}}_breakExpression(){var e,t;return this._loopTrack.isEmpty&&T(this.currentToken),this._eat(i.BREAK),new et((e=this.currentToken)==null?void 0:e.line,(t=this.currentToken)==null?void 0:t.col)}_continueExpression(){var e,t;return this._loopTrack.isEmpty&&T(this.currentToken),this._eat(i.CONTINUE),new nt((e=this.currentToken)==null?void 0:e.line,(t=this.currentToken)==null?void 0:t.col)}_term(){let e=this._factor();return e=this._tryParsingFunctionCall(e),e=this._tryParsingMemberExpression(e),e}_expression(){let e=this._term();for(e=this._tryBinaryExpression(0,e);[i.and,i.or,i.nullity].includes(this.currentToken.type);){let t=this.currentToken;this._eat(t.type),e=new B(e,t,this._expression())}if(this._expect(i.equal))if(e instanceof E||e instanceof w){let t=this.currentToken;this._eat(i.equal),e=new L(e,this._expression())}else throw new Error("Unexpected token");return e}_objectProperty(){var r;let e;switch((r=this.currentToken)==null?void 0:r.type){case i.stringConst:{e=new x(this.currentToken,this.currentToken.value),this._eat(i.stringConst);break}case i.lbracket:{this._eat(i.lbracket);var t=this._expression();this._eat(i.rbracket),e=t;break}case i.id:{let s=this._variable();e=new x(new l(i.id,s.value,s.line,s.col),s.value);break}default:throw`Unexpected token ${this.currentToken}`}this._eat(i.colon);var n=this._expression();return new O(e,n)}_property(){return this._objectProperty()}_objectProperties(){var t,n;let e=[];for(((t=this.currentToken)==null?void 0:t.type)!=i.rbrace&&(this._eatEOL(),e.push(this._property()),this._eatEOL());((n=this.currentToken)==null?void 0:n.type)===i.comma&&(this._eat(i.comma),this._eatEOL(),!this._expect(i.rbrace));)e.push(this._property()),this._eatEOL();return e}_objectExpression(e){var t=e!=null?e:this.currentToken;e||this._eat(i.lbrace);var n=this._objectProperties();return this._eat(i.rbrace),new $(n,t,this.currentToken)}_arrayExpression(){this._eat(i.lbracket);let e=this._expect(i.rbracket)?[]:this._expressionsList();this._eat(i.rbracket);var t=e.length!==0?e[0]:void 0,n=e.length!==0?e[e.length-1]:void 0;return new F(e,t,n)}_tryParsingMemberExpression(e){let t=e;for(;this.currentToken.type===i.lbracket||this.currentToken.type===i.dot;)if(this.currentToken.type===i.lbracket){this._eat(i.lbracket);let n=this._expression();t=new w(t,n,!0),this._eat(i.rbracket)}else{this._eat(i.dot);let n=this.currentToken;n.type!==i.id&&T(n);let r=new x(new l(i.stringConst,n.value,n.line,n.col),n.value);this._eat(i.id),t=new w(t,r)}return t}_tryBinaryExpression(e,t){let n=t;for(;;){let r=tt._binopPrecdences[this.currentToken.type]||-1;if(r<e)return n;let s=this.currentToken;this._eat(s.type);let o=this._term(),u=tt._binopPrecdences[this.currentToken.type]||-1;if(r<u){let p=this._tryBinaryExpression(r+1,o);if(p===n)return p;o=p}n=new z(n,s,o)}}_expressionsList(){var n;this._eatEOL();let e=this._expression();this._eatEOL();let t=[e];for(;((n=this.currentToken)==null?void 0:n.type)===i.comma&&(this._eat(i.comma),this._eatEOL(),!this._expect(i.rbracket));)e=this._expression(),t.push(e),this._eatEOL();return t}_callExpression(e){this._eat(i.lparen);let t=[];return this._expect(i.rparen)||(t=this._expressionsList()),this._eat(i.rparen),e instanceof E||T(this.currentToken),new P(e,t)}_tryParsingFunctionCall(e){let t=e;for(;this.currentToken.type===i.lparen;)t=this._callExpression(t);return t}_statementExpression(){let e=this._expression();return[i.semi,i.eol,i.eof].includes(this.currentToken.type)||T(this.currentToken),e}_blockStatement(e=!1){var n;if(e||this._eat(i.lbrace),this._eatEOL(),this._expect(i.rbrace))return this._eat(i.rbrace),new R([],this.currentToken);let t=[this._statement()];for(;this._eatSemiOrEOL(),!(this.currentToken.type===i.rbrace||this.currentToken.type===i.eof||(t.push(this._statement()),this._expect(i.rbrace)));)this.currentToken.type!==i.eol&&this.currentToken.type!==i.semi&&this.currentToken.type!==i.eof&&T(this.currentToken);return this._eat(i.rbrace),((n=this.currentToken)==null?void 0:n.type)===i.rbrace&&this._eat(i.rbrace),new R(t,this.currentToken)}_ifStatement(){this._eat(i.IF);let e=this.currentToken.type===i.lparen;e&&this._eat(i.lparen);let t=this._expression();e&&this._eat(i.rparen);let n;this.currentToken.type===i.lbrace?n=this._blockStatement():n=this._expression();let r;if(this.currentToken.type===i.ELSE)switch(this._eat(i.ELSE),this.currentToken.type){case i.IF:r=this._ifStatement();break;case i.lbrace:r=this._blockStatement();break;default:r=this._expression()}return new W(t,n,r)}_pushLoop(){this._loopTrack.push(!0)}_popLoop(){this._loopTrack.pop()}_whileLoop(e=!1){let t=this.currentToken;this._eat(i.WHILE_TILL),this._pushLoop();let n=this._expression(),r=this.currentToken.type===i.lbrace?this._blockStatement():this._expression();return this._popLoop(),new D(n,r,t,this.currentToken,e)}_forOfIdentifier(){switch(this.currentToken.type){case i.lparen:{this._eat(i.lparen);let e=this._variable();this._eat(i.comma);let t=this._variable();return this._eat(i.rparen),new I(e,t)}default:return this._variable()}}_forLoop(e=!1){let t=this.currentToken;this._eat(i.FOR_LOOP),this._pushLoop();let n=[i.lparen].includes(this.currentToken.type),r;if(n)r=this._forOfIdentifier();else{let s=this._expression();s instanceof L||(n=!0),r=s}if(!n&&r instanceof L){this._eat(i.TILL);let s=this._expression(),o;if(this.currentToken.type===i.up||this.currentToken.type===i.down){let f=this.currentToken;this._eat(f.type),o=f}else o=new l(i.up,"up");let u;this._expect(i.with)?(this._eat(i.with),u=this._expression()):u=new x(new l(i.numberConst,1,this.currentToken.line,this.currentToken.col),"1");let p=this.currentToken.type===i.lbrace?this._blockStatement():this._expression();r=new K(r,s,u,o,p,t,this.currentToken,e),this._popLoop()}else if(n){this._eat(i.in);let s=this._expression(),o=this.currentToken.type===i.lbrace?this._blockStatement():this._expression();r=new H(r,s,o,t,this.currentToken,e),this._popLoop()}else T(this.currentToken);return r}_statement(){switch(this.currentToken.type){case i.BREAK:return this._breakExpression();case i.CONTINUE:return this._continueExpression();case i.RETURN:return this._eat(i.RETURN),this._return();case i.semi:return this._eatSemi(),this._statement();case i.eol:return this._eatEOL(),this._statement();case i.WHILE_TILL:return this._whileLoop();case i.FOR_LOOP:return this._forLoop();default:return this._statementExpression()}}_expect(e){var t;return((t=this.currentToken)==null?void 0:t.type)===e}_definition(){if(this._eatSemiOrEOL(),this._expect(i.eof))return[];let e=[this._statement()];for(;;){if(this._eatSemiOrEOL(),this.currentToken.type===i.eof){this._eat(i.eof);break}this.currentToken.type===i.lbrace?e.push(this._blockStatement()):e.push(this._statement())}return e}_root(){let e=this.lexer.source,t="<module>",n=this._definition();return new j(n,t,e)}parse(){return this._root()}};tt._binopPrecdences={[i.eqeq]:10,[i.notEq]:10,[i.great]:10,[i.greatEq]:10,[i.less]:10,[i.lessEq]:10,[i.plus]:20,[i.minus]:20,[i.mult]:40,[i.div]:40,[i.mod]:40};var vt=tt,V=class{},C=class extends V{},M=class extends V{},y=class{constructor(e){this.value=e}},gt=class{constructor(){this._nodesVisitors={}}registerVisitor(e,t){let n=`visit${e.name}`;this._nodesVisitors[n]=t}},_t=class extends gt{constructor(){super(),this.registerVisitor(j,this.visitRootAST),this.registerVisitor(R,this.visitBlockStatementAST),this.registerVisitor(E,this.visitIdentifierAST),this.registerVisitor(x,this.visitLiteralAST),this.registerVisitor(L,this.visitAssignmentExpressionAST),this.registerVisitor(X,this.visitExpressionStatementAST),this.registerVisitor(P,this.visitCallExpressionAST),this.registerVisitor(z,this.visitBinaryExpressionAST),this.registerVisitor(U,this.visitUnaryExpressionAST),this.registerVisitor(W,this.visitIfStatementAST),this.registerVisitor(B,this.visitLogicalExpressionAST),this.registerVisitor(w,this.visitIndexAccessorAST),this.registerVisitor(O,this.visitObjectProperty),this.registerVisitor($,this.visitObjectExpression),this.registerVisitor(F,this.visitArrayExpression),this.registerVisitor(D,this.visitWhileLoopStatement),this.registerVisitor(K,this.visitForLoopStatement),this.registerVisitor(H,this.visitForOfStatement),this.registerVisitor(et,this.visitBreakAST),this.registerVisitor(nt,this.visitContinueAST),this.registerVisitor(Y,this.visitReturnAST)}visit(e){this.beforeVisit(e);let t=`visit${e.constructor.name}`,n=this._nodesVisitors[t];if(!n)throw new S(`No ${t} declared`,e.line,e.col,e.constructor.name);try{let r=n.call(this,e);return r&&typeof r.then=="function"?r.catch(s=>{throw S.fromNode(e,s)}):r!=null?r:null}catch(r){throw S.fromNode(e,r)}}beforeVisit(e){}assignProperty(e,t,n){(Array.isArray(e)||typeof e=="object")&&(e[t]=n)}},ot=class{constructor(e,t,n){this.memory={};this.name=e,this.memory=t,this.parent=n}resolve(e){var t,n;return Object.keys(this.memory).includes(e)?this.memory[e]:(n=(t=this.parent)==null?void 0:t.resolve(e))!=null?n:null}change(e,t,n=!0){return Object.keys(this.memory).includes(e)?(this.memory[e]=t,!0):this.parent&&this.parent.change(e,t,!1)?!0:n?(this.memory[e]=t,!0):!1}},rt={_ok_:g("_ok_",{name:"_ok_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"boolean"}),_err_:g("_err_",{name:"_err_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"boolean"}),_value_:g("_value_",{name:"_value_",minArgs:1,maxArgs:2,args:[{name:"result"},{name:"fallback",required:!1}],returnType:"any"}),_error_:g("_error_",{name:"_error_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"object"}),_code_:g("_code_",{name:"_code_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"string"}),_message_:g("_message_",{name:"_message_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"string"}),_unwrap_:g("_unwrap_",{name:"_unwrap_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"any"}),_len_:g("_len_",{name:"_len_",minArgs:1,maxArgs:1,args:[{name:"target"}],returnType:"number"}),_push_:g("_push_",{name:"_push_",minArgs:2,maxArgs:2,args:[{name:"array",type:"array"},{name:"value"}],returnType:"array"}),_pop_:g("_pop_",{name:"_pop_",minArgs:1,maxArgs:1,args:[{name:"array",type:"array"}],returnType:"any"}),_insert_:g("_insert_",{name:"_insert_",minArgs:3,maxArgs:3,args:[{name:"array",type:"array"},{name:"index",type:"number"},{name:"value"}],returnType:"array"}),_remove_at_:g("_remove_at_",{name:"_remove_at_",minArgs:2,maxArgs:2,args:[{name:"array",type:"array"},{name:"index",type:"number"}],returnType:"any"}),_has_:g("_has_",{name:"_has_",minArgs:2,maxArgs:2,args:[{name:"object",type:"object"},{name:"key"}],returnType:"boolean"}),_keys_:g("_keys_",{name:"_keys_",minArgs:1,maxArgs:1,args:[{name:"object",type:"object"}],returnType:"array"}),_values_:g("_values_",{name:"_values_",minArgs:1,maxArgs:1,args:[{name:"object",type:"object"}],returnType:"array"})};function it(a){return typeof a=="object"&&a!=null&&a.ok===!0}function at(a){if(typeof a!="object"||a==null)return;let e=a;if(!(e.ok!==!1||typeof e.error!="object"||e.error==null))return e.error}function N(a){return typeof a=="number"?a:void 0}function G(a){return typeof a=="string"?a:void 0}function Nt(a){var t,n;let e=at(a);return new S((t=G(e==null?void 0:e.message))!=null?t:"Cannot unwrap failed _try_ result",N(e==null?void 0:e.line),N(e==null?void 0:e.col),G(e==null?void 0:e.node),void 0,{code:(n=G(e==null?void 0:e.code))!=null?n:"invalid_try_result",name:G(e==null?void 0:e.name),argCount:N(e==null?void 0:e.argCount),minArgs:N(e==null?void 0:e.minArgs),maxArgs:N(e==null?void 0:e.maxArgs),argIndex:N(e==null?void 0:e.argIndex),expectedType:G(e==null?void 0:e.expectedType),actualType:G(e==null?void 0:e.actualType),stepCount:N(e==null?void 0:e.stepCount),maxSteps:N(e==null?void 0:e.maxSteps)})}function ct(a,e,t,n){let r=Z(n);return new S(`Function '${a}' argument ${e} expects ${t}, got ${r}`,void 0,void 0,void 0,void 0,{code:"invalid_argument_type",name:a,argIndex:e,expectedType:t,actualType:r})}function st(a,e,t){let n=e[t];if(Array.isArray(n))return n;throw ct(a,t,"array",n)}function lt(a,e,t){let n=e[t];if(typeof n=="object"&&n!=null&&!Array.isArray(n))return n;throw ct(a,t,"object",n)}function Et(a,e,t){let n=e[t];if(typeof n=="number")return Math.trunc(n);throw ct(a,t,"number",n)}function It(a,e,t){return new S(`Function '${a}' index ${e} is out of range for array of length ${t}`,void 0,void 0,void 0,void 0,{code:"index_out_of_range",name:a})}var $t={_ok_:a=>it(a[0]),_err_:a=>!it(a[0]),_value_:a=>{var e,t;return it(a[0])?(e=a[0].value)!=null?e:null:(t=a[1])!=null?t:null},_error_:a=>{var e;return(e=at(a[0]))!=null?e:null},_code_:a=>{var e,t;return(t=(e=at(a[0]))==null?void 0:e.code)!=null?t:null},_message_:a=>{var e,t;return(t=(e=at(a[0]))==null?void 0:e.message)!=null?t:null},_unwrap_:a=>{var e;if(it(a[0]))return(e=a[0].value)!=null?e:null;throw Nt(a[0])},_len_:a=>{let e=a[0];if(Array.isArray(e)||typeof e=="string")return e.length;if(typeof e=="object"&&e!=null)return Object.keys(e).length;throw ct("_len_",0,"array|object|string",e)},_push_:a=>{var t;let e=st("_push_",a,0);return e.push((t=a[1])!=null?t:null),e},_pop_:a=>{var t;let e=st("_pop_",a,0);return e.length===0?null:(t=e.pop())!=null?t:null},_insert_:a=>{var n;let e=st("_insert_",a,0),t=Et("_insert_",a,1);if(t<0||t>e.length)throw It("_insert_",t,e.length);return e.splice(t,0,(n=a[2])!=null?n:null),e},_remove_at_:a=>{var n;let e=st("_remove_at_",a,0),t=Et("_remove_at_",a,1);return t<0||t>=e.length?null:(n=e.splice(t,1)[0])!=null?n:null},_has_:a=>Object.prototype.hasOwnProperty.call(lt("_has_",a,0),a[1]),_keys_:a=>Object.keys(lt("_keys_",a,0)),_values_:a=>Object.values(lt("_values_",a,0))},d=class d extends _t{constructor(t){super();this.rootScope=new ot("Program",{});this.currentScope=this.rootScope;this.debug=!1;this._functionsRegistry={};this._functionSpecs={};this._executionStepCount=0;this._traceEvents=[];this._options=Mt(t),this._functionsRegistry={...$t,...d._globalFunctionsRegistry},this._functionSpecs={...rt,...d._globalFunctionSpecs}}get options(){return{...this._options}}get executionStepCount(){return this._executionStepCount}trace(){return this._traceEvents.map(t=>({...t,detail:{...t.detail}}))}resetExecutionBudget(){this._executionStepCount=0}beforeVisit(t){this._executionStepCount+=1,this.recordTrace("visit",t);let n=this._options.maxSteps;if(n!=null&&this._executionStepCount>n)throw new S(`Execution budget exceeded after ${this._executionStepCount} step(s)`,t.line,t.col,t.constructor.name,void 0,{code:"execution_budget_exceeded",stepCount:this._executionStepCount,maxSteps:n})}clearTrace(){this._traceEvents=[]}recordTrace(t,n,r,s={}){this._options.trace&&this._traceEvents.push({kind:t,line:n.line,col:n.col,node:Ot(n),name:r,stepCount:this._executionStepCount,detail:s})}resolve(t){var n,r;return(r=(n=this.currentScope)==null?void 0:n.resolve(t))!=null?r:null}changeVariable(t,n){var r;return(r=this.currentScope)!=null&&r.change(t,n)?n:null}pushScope(t){let n=new ot(t,{},this.currentScope);this.currentScope=n}popScope(){var t;this.currentScope=(t=this.currentScope)==null?void 0:t.parent}log(t){this.debug&&console.log(t)}successResult(t){return{ok:!0,value:t,error:null}}errorResult(t){return{ok:!1,value:null,error:t.diagnostic()}}visitRootAST(t){var s;let n=t.body,r;for(let o of n)if(r=this.visit(o),r instanceof y)return(s=r.value)!=null?s:null;return r!=null?r:null}visitBlockStatementAST(t){let n=t.body,r;this.pushScope("Block");for(let s of n)if(r=this.visit(s),r instanceof V||r instanceof y)break;return this.popScope(),r!=null?r:null}visitIdentifierAST(t){var r;let n=t.value;return(r=this==null?void 0:this.resolve(n))!=null?r:null}visitLiteralAST(t){return t.value}visitAssignmentExpressionAST(t){let n=t.identifier,r=t.init,s=null;if(n instanceof w){var o=this.visit(n.owner);s=this.visit(t.init);var u=this.visit(n.key);this.assignProperty(o,u,s)}else n instanceof E&&(s=this.visit(r),this.changeVariable(n.value,s));return s}visitExpressionStatementAST(t){let n=t.expression;return this.visit(n)}visitCallExpressionAST(t){var m,_;let n=t.callee,r=t.arguments,s=n.value;if(s==="_try_"){if(r.length!==1)throw new S("_try_ expects exactly one expression",t.line,t.col,t.constructor.name,void 0,{code:"invalid_try_arity",name:"_try_",argCount:r.length,minArgs:1,maxArgs:1});try{let b=this.visit(r[0]);return b instanceof V||b instanceof y?b:this.successResult(b)}catch(b){if(b instanceof S)return this.errorResult(b);throw b}}let o=this.resolveFunction(s);if(!o){if(this._options.compatV1)return null;throw new S(`Unknown function '${s}'`,t.line,t.col,t.constructor.name,void 0,{code:"unknown_function",name:s})}let u=this.resolveFunctionSpec(s);if(u&&!pt(u,r.length))throw new S(`Function '${s}' expects ${ft(u)} argument(s), got ${r.length}`,t.line,t.col,t.constructor.name,void 0,{code:"invalid_function_arity",name:s,argCount:r.length,minArgs:Q(u),maxArgs:u.maxArgs});let p=r.map(b=>this.visit(b));u&&this.validateRuntimeArgumentTypes(t,u,p),this.recordTrace("call",t,s,{argCount:p.length,returnType:(m=u==null?void 0:u.returnType)!=null?m:"any"});let f=o(p,this);return this.recordTrace("call_result",t,s,{returnType:(_=u==null?void 0:u.returnType)!=null?_:"any",actualType:Z(f)}),f}visitBinaryExpressionAST(t){let n=t.left,r=t.right,s=t.operation,o=this.visit(n),u=this.visit(r);switch(s.type){case i.plus:return h(o)&&h(u)?o+u:`${o}${u}`;case i.minus:if(h(o)&&h(u))return o-u;throw new Error(`Operation ${s.value} not allowed no num value`);case i.mult:if(h(o)&&h(u))return o*u;if(q(o)&&h(u))return o.repeat(u);if(h(o)&&q(u))return u.repeat(o);throw new Error(`Operation ${s.value} not allowed no num value`);case i.div:if(h(o)&&h(u)){if(u===0)throw new Error("Invalid division by 0");return o/u}throw new Error(`Operation ${s.value} not allowed no num value`);case i.mod:if(h(o)&&h(u))return o%u;throw new Error(`Operation ${s.value} not allowed no num value`);case i.great:if(h(o)&&h(u))return o>u;throw new Error(`Operation ${s.value} not allowed no num value`);case i.greatEq:if(h(o)&&h(u))return o>=u;throw new Error(`Operation ${s.value} not allowed no num value`);case i.less:if(h(o)&&h(u))return o<u;throw new Error(`Operation ${s.value} not allowed no num value`);case i.lessEq:if(h(o)&&h(u))return o<=u;throw new Error(`Operation ${s.value} not allowed no num value`);case i.eqeq:return o===u;case i.notEq:return o!==u;default:throw new Error(`Operation ${s.value} not allowed no num value`)}}visitUnaryExpressionAST(t){let n=t.argument,r=t.operation,s=this.visit(n);if(r.type===i.not)return A(s)===!1;if(!h(s))throw new Error(`Operation ${r.value} not allowed no num value`);if(r.type===i.plus)return s;if(r.type===i.minus)return-s;throw new Error(`Operation ${r.value} not allowed no num value`)}visitIfStatementAST(t){let n=t.test,r=this.visit(n);return A(r)?this.visit(t.consequent):t.alternate?this.visit(t.alternate):null}visitLogicalExpressionAST(t){let n=t.left,r=this.visit(n);if(t.operator.type===i.nullity)return r!=null?r:this.visit(t.right);let s=A(r);return t.operator.type===i.and?s?A(this.visit(t.right)):!1:t.operator.type===i.or?s?!0:A(this.visit(t.right)):null}visitIndexAccessorAST(t){var s,o;let n=t.owner,r=this.visit(n);if(r==null)return null;if(Array.isArray(r)){let u=this.visit(t.key);return h(u)&&Number.isInteger(u)&&r.length>u&&u>=0&&(s=r[u])!=null?s:null}else if(typeof r=="object"){let u=this.visit(t.key);return(o=r[u])!=null?o:null}return null}visitObjectProperty(t){}visitObjectExpression(t){let n={},r=t;for(let s of r.properties)if(s instanceof O){let o=this.visit(s.key);o=q(o)?o:o.toString(),n[o]=this.visit(s.value)}return n}visitArrayExpression(t){let n=t;return this.resolveArguments(n.elements)}visitBreakAST(t){return new C}visitWhileLoopStatement(t){this.log(`WhileLoopStatement ${t.test} ${t.body}`);let n=t.retain?[]:void 0;for(;A(this.visit(t.test));){let r=this.visit(t.body);if(r instanceof C)break;if(!(r instanceof M)){if(r instanceof y)return this.popScope(),r;n==null||n.push(r)}}return n!=null?n:null}visitForLoopStatement(t){let n=t.retain?[]:void 0,r=t.init.identifier;if(!(r instanceof E))throw new Error("Unexpected identifer found");this.pushScope("ForLoopStatement");let s=this.visit(t.init.init);this.changeVariable(r.value,s);let o=()=>{let p=this.visit(t.test);if(h(p)){let f=this.resolve(r.value);return t.direction.type===i.up?p>=f:p<=f}return A(p)},u=()=>{let p=this.visit(t.update);if(h(p)){let f=this.resolve(r.value);if(!h(f))throw Error("Cant update value");this.changeVariable(r.value,t.direction.type===i.up?f+p:f-p)}else throw Error("Update value cant be non number")};for(;o();){let p=this.visit(t.body);if(p instanceof C)break;if(p instanceof M){u();continue}if(p instanceof y)return this.popScope(),p;n==null||n.push(p),u()}return this.popScope(),n!=null?n:null}visitForOfStatement(t){let n=this.visit(t.collection);if(!Array.isArray(n))throw Error("Can iterate non array object");let r=t.retain?[]:void 0;this.pushScope("ForOfStatement");for(let s of n){this._declareForIdentifier(t.identifier,s);let o=this.visit(t.body);if(o instanceof C)break;if(!(o instanceof M)){if(o instanceof y)return this.popScope(),o;r==null||r.push(o)}}return this.popScope(),r!=null?r:null}visitContinueAST(t){return new M}visitReturnAST(t){return new y(t.value!=null?this.visit(t.value):null)}_declareForIdentifier(t,n){if(t instanceof I){if(!Array.isArray(n))throw Error("Unable to make a tuple from non Array element");this.changeVariable(t.first.value,n[0]),this.changeVariable(t.second.value,n[1])}this.changeVariable(t.value,n)}resolveArguments(t){return t.map(n=>this.visit(n))}setFunctionResolver(t){this._functionResolver=t}resolveFunction(t){var n,r;return(r=this._functionsRegistry[t])!=null?r:(n=this._functionResolver)==null?void 0:n.call(this,t)}resolveFunctionSpec(t){return this._functionSpecs[t]}capabilities(){return xt(this._functionSpecs)}registerFunction(t,n,r){this._functionsRegistry[t]=n,this._functionSpecs[t]=g(t,r)}unregisterFunction(t){delete this._functionsRegistry[t],delete this._functionSpecs[t]}validate(t,n,r=!1){let s=[],o=this.validationFunctionSpecs(n);try{this.validateNode(d.compile(t,r),o,s)}catch(u){s.push({code:"syntax_error",message:u instanceof Error?u.message:String(u)})}return{ok:s.length===0,errors:s}}validateManifest(t,n,r=!1){let s=[],o=this.validationFunctionSpecs(n.functions);try{let u=d.compile(t,r);this.validateNode(u,o,s),this.validateManifestNode(u,n,s)}catch(u){s.push({code:"syntax_error",message:u instanceof Error?u.message:String(u)})}return{ok:s.length===0,errors:s}}validationFunctionSpecs(t){let n=new Map;return Object.keys(rt).forEach(r=>{var s;return n.set(r,(s=this._functionSpecs[r])!=null?s:rt[r])}),t==null?(Object.keys(this._functionSpecs).forEach(r=>n.set(r,this._functionSpecs[r])),n):t instanceof Set?(t.forEach(r=>{var s;return n.set(r,(s=this._functionSpecs[r])!=null?s:g(r))}),n):Array.isArray(t)?(t.forEach(r=>{var s;typeof r=="string"?n.set(r,(s=this._functionSpecs[r])!=null?s:g(r)):n.set(r.name,g(r.name,r))}),n):(Object.keys(t).forEach(r=>n.set(r,g(r,t[r]))),n)}validateNode(t,n,r,s=!1){t&&(t instanceof j||t instanceof R?t.body.forEach(o=>this.validateNode(o,n,r,s)):t instanceof L?(this.validateNode(t.identifier,n,r,s),this.validateNode(t.init,n,r,s)):t instanceof X?this.validateNode(t.expression,n,r,s):t instanceof P?this.validateCallExpression(t,n,r,s):t instanceof z?(this.validateNode(t.left,n,r,s),this.validateNode(t.right,n,r,s)):t instanceof U?this.validateNode(t.argument,n,r,s):t instanceof W?(this.validateNode(t.test,n,r,s),this.validateNode(t.consequent,n,r,s),this.validateNode(t.alternate,n,r,s)):t instanceof B?(this.validateNode(t.left,n,r,s),this.validateNode(t.right,n,r,s)):t instanceof w?(this.validateNode(t.owner,n,r,s),this.validateNode(t.key,n,r,s)):t instanceof $?t.properties.forEach(o=>this.validateNode(o,n,r,s)):t instanceof O?(this.validateNode(t.key,n,r,s),this.validateNode(t.value,n,r,s)):t instanceof F?t.elements.forEach(o=>this.validateNode(o,n,r,s)):t instanceof D?(this.validateNode(t.test,n,r,s),this.validateNode(t.body,n,r,s)):t instanceof K?(this.validateNode(t.init,n,r,s),this.validateNode(t.test,n,r,s),this.validateNode(t.update,n,r,s),this.validateNode(t.body,n,r,s)):t instanceof H?(this.validateNode(t.identifier,n,r,s),this.validateNode(t.collection,n,r,s),this.validateNode(t.body,n,r,s)):t instanceof I?(this.validateNode(t.first,n,r,s),this.validateNode(t.second,n,r,s)):t instanceof Y&&this.validateNode(t.value,n,r,s))}validateCallExpression(t,n,r,s){let o=t.callee.value;if(o==="_try_"){t.arguments.length!==1&&r.push(this.validationError("invalid_try_arity",t,"_try_ expects exactly one expression","_try_",{argCount:t.arguments.length,minArgs:1,maxArgs:1})),t.arguments.forEach(u=>this.validateNode(u,n,r,!0));return}if(!s){let u=n.get(o);u?pt(u,t.arguments.length)?this.validateStaticArgumentTypes(t,u,r):r.push(this.validationError("invalid_function_arity",t,`Function '${o}' expects ${ft(u)} argument(s), got ${t.arguments.length}`,o,{argCount:t.arguments.length,minArgs:Q(u),maxArgs:u.maxArgs})):this._options.compatV1||r.push(this.validationError("unknown_function",t,`Unknown function '${o}'`,o))}t.arguments.forEach(u=>this.validateNode(u,n,r,s))}validateStaticArgumentTypes(t,n,r){var s;(s=n.args)==null||s.forEach((o,u)=>{var m,_;let p=t.arguments[u];if(!p)return;let f=this.staticArgumentType(p);!f||this.argumentTypeMatches(o,f)||r.push(this.validationError("invalid_argument_type",t,`Function '${n.name}' argument ${u} expects ${(m=o.type)!=null?m:"any"}, got ${f}`,n.name,{argIndex:u,expectedType:(_=o.type)!=null?_:"any",actualType:f}))})}staticArgumentType(t){if(t instanceof x)return Z(t.value);if(t instanceof F)return"array";if(t instanceof $)return"object"}argumentTypeMatches(t,n){var s;let r=(s=t.type)!=null?s:"any";return r==="any"||t.required===!1&&n==="null"?!0:r===n}validateManifestNode(t,n,r){var p,f;let s=((p=n.inputs)!=null?p:[]).map(bt),o=((f=n.outputs)!=null?f:[]).map(bt),u={knownInputs:new Set(s.map(m=>m.name)),assigned:new Set,assignedTypes:new Map,reportedInputs:new Set};this.analyzeManifestNode(t,u,r),o.forEach(m=>{var b,yt,At;if(((b=m.required)==null||b)&&!u.assigned.has(m.name)){r.push(this.validationError("missing_output",t,`Required output '${m.name}' is not assigned`,m.name));return}let _=u.assignedTypes.get(m.name);!_||this.valueSpecTypeMatches(m,_)||r.push(this.validationError("invalid_output_type",t,`Output '${m.name}' expects ${(yt=m.type)!=null?yt:"any"}, got ${_}`,m.name,{expectedType:(At=m.type)!=null?At:"any",actualType:_}))})}analyzeManifestNode(t,n,r){t&&(t instanceof j||t instanceof R?t.body.forEach(s=>this.analyzeManifestNode(s,n,r)):t instanceof L?(this.analyzeManifestNode(t.init,n,r),t.identifier instanceof w&&this.analyzeManifestNode(t.identifier,n,r),this.markAssignedTarget(t.identifier,this.staticArgumentType(t.init),n)):t instanceof X?this.analyzeManifestNode(t.expression,n,r):t instanceof P?t.arguments.forEach(s=>this.analyzeManifestNode(s,n,r)):t instanceof z?(this.analyzeManifestNode(t.left,n,r),this.analyzeManifestNode(t.right,n,r)):t instanceof U?this.analyzeManifestNode(t.argument,n,r):t instanceof W?(this.analyzeManifestNode(t.test,n,r),this.analyzeManifestNode(t.consequent,n,r),this.analyzeManifestNode(t.alternate,n,r)):t instanceof B?(this.analyzeManifestNode(t.left,n,r),this.analyzeManifestNode(t.right,n,r)):t instanceof w?(this.analyzeManifestNode(t.owner,n,r),this.analyzeManifestNode(t.key,n,r)):t instanceof $?t.properties.forEach(s=>this.analyzeManifestNode(s,n,r)):t instanceof O?(this.analyzeManifestNode(t.key,n,r),this.analyzeManifestNode(t.value,n,r)):t instanceof F?t.elements.forEach(s=>this.analyzeManifestNode(s,n,r)):t instanceof D?(this.analyzeManifestNode(t.test,n,r),this.analyzeManifestNode(t.body,n,r)):t instanceof K?(this.analyzeManifestNode(t.init,n,r),this.analyzeManifestNode(t.test,n,r),this.analyzeManifestNode(t.body,n,r),this.analyzeManifestNode(t.update,n,r)):t instanceof H?(this.analyzeManifestNode(t.collection,n,r),this.markAssignedTarget(t.identifier,void 0,n),this.analyzeManifestNode(t.body,n,r)):t instanceof I?(this.analyzeManifestNode(t.first,n,r),this.analyzeManifestNode(t.second,n,r)):t instanceof Y?this.analyzeManifestNode(t.value,n,r):t instanceof E&&!n.knownInputs.has(t.value)&&!n.assigned.has(t.value)&&!n.reportedInputs.has(t.value)&&(n.reportedInputs.add(t.value),r.push(this.validationError("unknown_input",t,`Unknown input '${t.value}'`,t.value))))}markAssignedTarget(t,n,r){t instanceof E?(r.assigned.add(t.value),n&&r.assignedTypes.set(t.value,n)):t instanceof I&&(this.markAssignedTarget(t.first,void 0,r),this.markAssignedTarget(t.second,void 0,r))}valueSpecTypeMatches(t,n){var s;let r=(s=t.type)!=null?s:"any";return r==="any"||t.required===!1&&n==="null"?!0:r===n}validationError(t,n,r,s,o){return{code:t,message:r,name:s,line:n.line,col:n.col,node:n.constructor.name,argCount:o==null?void 0:o.argCount,minArgs:o==null?void 0:o.minArgs,maxArgs:o==null?void 0:o.maxArgs,argIndex:o==null?void 0:o.argIndex,expectedType:o==null?void 0:o.expectedType,actualType:o==null?void 0:o.actualType}}validateRuntimeArgumentTypes(t,n,r){var s;(s=n.args)==null||s.forEach((o,u)=>{var f,m;if(u>=r.length)return;let p=Z(r[u]);if(!this.argumentTypeMatches(o,p))throw new S(`Function '${n.name}' argument ${u} expects ${(f=o.type)!=null?f:"any"}, got ${p}`,t.line,t.col,t.constructor.name,void 0,{code:"invalid_argument_type",name:n.name,argIndex:u,expectedType:(m=o.type)!=null?m:"any",actualType:p})})}execute(t,n=!0,r){let s=d.compile(t,n);return r&&Object.keys(r).forEach(o=>this.changeVariable(o,r[o])),this.resetExecutionBudget(),this.clearTrace(),this.visit(s)}static compile(t,n=!1){let r=Tt(t);if(n&&this._cache.has(r))return this._cache.get(r);let s=new ht(t),u=new vt(s).parse();return n&&this._cache.set(r,u),u}static register(t,n,r){d._globalFunctionsRegistry[t]=n,d._globalFunctionSpecs[t]=g(t,r)}static unregister(t){delete d._globalFunctionsRegistry[t],delete d._globalFunctionSpecs[t]}static capabilities(){return xt({...rt,...d._globalFunctionSpecs})}static validateSource(t,n,r=!1){return new d().validate(t,n,r)}static validateManifestSource(t,n,r=!1){return new d().validateManifest(t,n,r)}static run(t,n=!1,r,s){return new d(s).execute(t,n,r)}static newInstance(t){return new d(t)}clone(){var t=new d(this.options);return t._functionsRegistry={...this._functionsRegistry},t._functionSpecs={...this._functionSpecs},t.rootScope.memory={...this.rootScope.memory},t}newAsyncInstance(){let t=dt.newInstance(this.options);return t.rootScope.memory=this.rootScope.memory,t._functionsRegistry=this._functionsRegistry,t._functionSpecs=this._functionSpecs,t}};d._globalFunctionsRegistry={},d._globalFunctionSpecs={},d._cache=new Map;var ut=d,dt=class a extends ut{constructor(e){super(e)}async visitRootAST(e){var r;let t=e.body,n;for(let s of t)if(n=await this.visit(s),n instanceof y)return(r=n.value)!=null?r:null;return n!=null?n:null}async visitBlockStatementAST(e){let t=e.body,n;this.pushScope("Block");for(let r of t)if(n=await this.visit(r),n instanceof V||n instanceof y)break;return this.popScope(),n}async visitIdentifierAST(e){let t=e.value;return this.resolve(t)}async visitLiteralAST(e){return e.value}async visitAssignmentExpressionAST(e){let t=e.identifier,n=e.init,r=null;if(t instanceof w){var s=await this.visit(t.owner);r=await this.visit(e.init);var o=await this.visit(t.key);this.assignProperty(s,o,r)}else t instanceof E&&(r=await this.visit(n),this.changeVariable(t.value,r));return r}async visitExpressionStatementAST(e){let t=e.expression;return await this.visit(t)}async visitCallExpressionAST(e){var f,m;let t=e.callee,n=e.arguments,r=t.value;if(r==="_try_"){if(n.length!==1)throw new S("_try_ expects exactly one expression",e.line,e.col,e.constructor.name,void 0,{code:"invalid_try_arity",name:"_try_",argCount:n.length,minArgs:1,maxArgs:1});try{let _=await this.visit(n[0]);return _ instanceof V||_ instanceof y?_:this.successResult(_)}catch(_){if(_ instanceof S)return this.errorResult(_);throw _}}let s=this.resolveFunction(r);if(!s){if(this._options.compatV1)return null;throw new S(`Unknown function '${r}'`,e.line,e.col,e.constructor.name,void 0,{code:"unknown_function",name:r})}let o=this.resolveFunctionSpec(r);if(o&&!pt(o,n.length))throw new S(`Function '${r}' expects ${ft(o)} argument(s), got ${n.length}`,e.line,e.col,e.constructor.name,void 0,{code:"invalid_function_arity",name:r,argCount:n.length,minArgs:Q(o),maxArgs:o.maxArgs});let u=await Promise.all(n.map(_=>this.visit(_)));o&&this.validateRuntimeArgumentTypes(e,o,u),this.recordTrace("call",e,r,{argCount:u.length,returnType:(f=o==null?void 0:o.returnType)!=null?f:"any"});let p=await s(u,this);return this.recordTrace("call_result",e,r,{returnType:(m=o==null?void 0:o.returnType)!=null?m:"any",actualType:Z(p)}),p}async visitBinaryExpressionAST(e){let t=e.left,n=e.right,r=e.operation,s=await this.visit(t),o=await this.visit(n);switch(r.type){case i.plus:return h(s)&&h(o)?s+o:`${s}${o}`;case i.minus:if(h(s)&&h(o))return s-o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.mult:if(h(s)&&h(o))return s*o;if(q(s)&&h(o))return s.repeat(o);if(h(s)&&q(o))return o.repeat(s);throw new Error(`Operation ${r.value} not allowed no num value`);case i.div:if(h(s)&&h(o)){if(o===0)throw new Error("Invalid division by 0");return s/o}throw new Error(`Operation ${r.value} not allowed no num value`);case i.mod:if(h(s)&&h(o))return s%o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.great:if(h(s)&&h(o))return s>o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.greatEq:if(h(s)&&h(o))return s>=o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.less:if(h(s)&&h(o))return s<o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.lessEq:if(h(s)&&h(o))return s<=o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.eqeq:return s===o;case i.notEq:return s!==o;default:throw new Error(`Operation ${r.value} not allowed no num value`)}}async visitUnaryExpressionAST(e){let t=e.argument,n=e.operation,r=await this.visit(t);if(n.type===i.not)return A(r)===!1;if(!h(r))throw new Error(`Operation ${n.value} not allowed no num value`);if(n.type===i.plus)return r;if(n.type===i.minus)return-r;throw new Error(`Operation ${n.value} not allowed no num value`)}async visitIfStatementAST(e){let t=e.test,n=await this.visit(t);return A(n)?await this.visit(e.consequent):e.alternate?await this.visit(e.alternate):null}async visitLogicalExpressionAST(e){let t=e.left,n=await this.visit(t);if(e.operator.type===i.nullity)return n!=null?n:await this.visit(e.right);let r=A(n);return e.operator.type===i.and?r?A(await this.visit(e.right)):!1:e.operator.type===i.or?r?!0:A(await this.visit(e.right)):!1}async visitIndexAccessorAST(e){var r,s;let t=e.owner,n=await this.visit(t);if(n==null)return null;if(Array.isArray(n)){let o=await this.visit(e.key);return h(o)&&Number.isInteger(o)&&n.length>o&&o>=0&&(r=n[o])!=null?r:null}else if(typeof n=="object"){let o=await this.visit(e.key);return(s=n[o])!=null?s:null}return null}async visitObjectProperty(e){}async visitObjectExpression(e){let t={},n=e;for(let r of n.properties)if(r instanceof O){let s=await this.visit(r.key);s=q(s)?s:s.toString(),t[s]=await this.visit(r.value)}return t}async visitArrayExpression(e){let t=e;return await this.resolveArgumentsAsync(t.elements)}async visitWhileLoopStatement(e){this.log(`WhileLoopStatement ${e.test} ${e.body}`);let t=e.retain?[]:void 0;for(;A(await this.visit(e.test));){let n=await this.visit(e.body);if(n instanceof C)break;if(!(n instanceof M)){if(n instanceof y)return this.popScope(),n;t==null||t.push(n)}}return t}async visitForLoopStatement(e){let t=e.retain?[]:void 0,n=e.init.identifier;if(!(n instanceof E))throw new Error("Unexpected identifer found");this.pushScope("ForLoopStatement");let r=await this.visit(e.init.init);this.changeVariable(n.value,r);let s=async()=>{let u=await this.visit(e.test);if(h(u)){let p=this.resolve(n.value);return e.direction.type===i.up?u>=p:u<=p}return A(u)},o=async()=>{let u=await this.visit(e.update);if(h(u)){let p=this.resolve(n.value);if(!h(p))throw Error("Cant update value");this.changeVariable(n.value,e.direction.type===i.up?p+u:p-u)}else throw Error("Update value cant be non number")};for(;await s();){let u=await this.visit(e.body);if(u instanceof C)break;if(u instanceof M){await o();continue}if(u instanceof y)return this.popScope(),u;t==null||t.push(u),await o()}return this.popScope(),t!=null?t:null}async visitForOfStatement(e){let t=await this.visit(e.collection);if(!Array.isArray(t))throw Error("Can iterate non array object");let n=e.retain?[]:void 0;this.pushScope("ForOfStatement");for(let r of t){this._declareForIdentifier(e.identifier,r);let s=await this.visit(e.body);if(s instanceof C)break;if(!(s instanceof M)){if(s instanceof y)return this.popScope(),s;n==null||n.push(s)}}return this.popScope(),n}async visitReturnAST(e){return new y(e.value!=null?await this.visit(e.value):null)}async resolveArgumentsAsync(e){return await Promise.all(e.map(async t=>await this.visit(t)))}registerFunction(e,t,n){this._functionsRegistry[e]=t,this._functionSpecs[e]=g(e,n)}unregisterFunction(e){delete this._functionsRegistry[e],delete this._functionSpecs[e]}async execute(e,t=!0,n){let r=ut.compile(e,t);return n&&Object.keys(n).forEach(s=>this.changeVariable(s,n[s])),this.resetExecutionBudget(),this.clearTrace(),await this.visit(r)}static async run(e,t=!1,n,r){return await new a(r).execute(e,t,n)}static newInstance(e){return new a(e)}clone(){var e=new a(this.options);return e._functionsRegistry={...this._functionsRegistry},e._functionSpecs={...this._functionSpecs},e.rootScope.memory={...this.rootScope.memory},e}};export{v as AST,F as ArrayExpression,L as AssignmentExpressionAST,z as BinaryExpressionAST,R as BlockStatementAST,et as BreakAST,C as BreakBranch,P as CallExpressionAST,nt as ContinueAST,M as ContinueBranch,X as ExpressionStatementAST,K as ForLoopStatement,H as ForOfStatement,E as IdentifierAST,W as IfStatementAST,w as IndexAccessorAST,J as LexerDictionary,x as LiteralAST,B as LogicalExpressionAST,V as LoopControl,ot as MEventScope,ut as MEvento,dt as MEventoAsync,S as MEventoRuntimeError,_t as NodeVisitor,$ as ObjectExpression,O as ObjectProperty,Y as ReturnAST,y as ReturnBranch,j as RootAST,l as Token,i as TokenType,I as TupleExpression,U as UnaryExpressionAST,D as WhileLoopStatement};
8
+ `)}}`}},x=class extends v{constructor(e){super(e.line,e.col),this.value=e.value.toString()}toString(){return this.value}},E=class extends v{constructor(e,t){super(e.line,e.col),this.value=e.value,this.raw=t}toString(){return this.value.toString()}},L=class extends v{constructor(e,t){super(e.line,e.col),this.identifier=e,this.init=t}toString(){return`${this.identifier} = ${this.init}`}},X=class extends v{constructor(e){super(e.line,e.col),this.expression=e}toString(){return this.expression.toString()}},P=class extends v{constructor(e,t){super(e.line,e.col),this.callee=e,this.arguments=t}toString(){return`${this.callee.toString()}(...${this.arguments.length})`}},z=class extends v{constructor(e,t,n){super(e.line,e.col),this.left=e,this.operation=t,this.right=n}toString(){return`${this.left} ${this.operation} ${this.right}`}},U=class extends v{constructor(e,t){super(e.line,e.col),this.operation=e,this.argument=t}toString(){return`${this.operation} ${this.argument}`}},D=class extends v{constructor(e,t,n){super(e.line,e.col),this.test=e,this.consequent=t,this.alternate=n}toString(){return`if ${this.test} ${this.consequent} ${this.alternate?`else ${this.alternate} `:""}`}},W=class extends v{constructor(e,t,n){super(e.line,e.col),this.left=e,this.operator=t,this.right=n}toString(){return`${this.left} ${this.operator.value} ${this.right}`}},w=class extends v{constructor(t,n,r=!1){super(t.line,t.col);this.computed=!1;this.owner=t,this.key=n,this.computed=r}toString(){return`${this.owner}[${this.key}]`}},$=class extends v{constructor(e,t,n){super(t==null?void 0:t.line,t==null?void 0:t.col),this.properties=e}toString(){return"{...}"}},F=class extends v{constructor(e,t,n){super(t==null?void 0:t.line,t==null?void 0:t.col),this.elements=e}toString(){return"[...]"}},O=class extends v{constructor(e,t){super(e.line,e.col),this.value=t,this.key=e}},B=class extends v{constructor(t,n,r,a,o=!1){super(r==null?void 0:r.line,r==null?void 0:r.col);this.retain=!1;this.test=t,this.body=n,this.retain=o}},K=class extends v{constructor(t,n,r,a,o,u,p,f=!1){super(u==null?void 0:u.line,u==null?void 0:u.col);this.init=t;this.test=n;this.update=r;this.direction=a;this.body=o;this.retain=f}},H=class extends v{constructor(t,n,r,a,o,u=!1){super(a==null?void 0:a.line,a==null?void 0:a.col);this.identifier=t;this.collection=n;this.body=r;this.retain=u}},I=class extends v{constructor(t,n){super(t.line,t.col);this.first=t;this.second=n}},et=class extends v{constructor(e,t){super(e,t)}},Y=class extends v{constructor(e,t,n){super(t,n),this.value=e}},nt=class extends v{constructor(e,t){super(e,t)}};function $t(s){return s instanceof j?"RootAST":s instanceof R?"BlockStatementAST":s instanceof x?"IdentifierAST":s instanceof E?"LiteralAST":s instanceof L?"AssignmentExpressionAST":s instanceof X?"ExpressionStatementAST":s instanceof P?"CallExpressionAST":s instanceof z?"BinaryExpressionAST":s instanceof U?"UnaryExpressionAST":s instanceof D?"IfStatementAST":s instanceof W?"LogicalExpressionAST":s instanceof w?"IndexAccessorAST":s instanceof $?"ObjectExpression":s instanceof O?"ObjectProperty":s instanceof F?"ArrayExpression":s instanceof B?"WhileLoopStatement":s instanceof K?"ForLoopStatement":s instanceof H?"ForOfStatement":s instanceof I?"TupleExpression":s instanceof et?"BreakAST":s instanceof Y?"ReturnAST":s instanceof nt?"ContinueAST":s.constructor.name}var gt=class{constructor(e=1/0){this.capacity=e;this.storage=[]}push(e){if(this.size()===this.capacity)throw Error("Stack has reached max capacity, you cannot add more items");this.storage.push(e)}pop(){return this.storage.pop()}peek(){return this.storage[this.size()-1]}size(){return this.storage.length}get isEmpty(){return this.storage.length===0}},tt=class tt{constructor(e){this._loopTrack=new gt;this.currentToken=e.nextToken(),this.lexer=e}_eat(e){var t;((t=this.currentToken)==null?void 0:t.type)===e?this.currentToken=this.lexer.nextToken():T(this.currentToken,e)}_eatEOL(){var e;for(;((e=this.currentToken)==null?void 0:e.type)===i.eol;)this._eat(i.eol)}_eatSemiOrEOL(){var e,t;for(;((e=this.currentToken)==null?void 0:e.type)===i.eol||((t=this.currentToken)==null?void 0:t.type)===i.semi;)this._eat(this.currentToken.type)}_eatSemi(){var e;for(;((e=this.currentToken)==null?void 0:e.type)===i.semi;)this._eat(i.semi)}_variable(){let e=new x(this.currentToken);return this._eat(i.id),e}_return(){let e=this.currentToken,t;return!this._expect(i.eol)&&!this._expect(i.semi)&&(t=this._expression()),new Y(t,e==null?void 0:e.line,e==null?void 0:e.col)}_factor(){let e=this.currentToken;switch(e.type){case i.plus:case i.minus:case i.not:return this._eat(this.currentToken.type),new U(e,this._term());case i.numberConst:return this._eat(i.numberConst),new E(e,e.value.toString());case i.stringConst:return this._eat(i.stringConst),new E(e,e.value.toString());case i.lparen:this._eat(i.lparen);let t=this._expression();return this._eat(i.rparen),t;case i.TRUE:case i.FALSE:return this._eat(this.currentToken.type),new E(e,e.value.toString());case i.NULL:return this._eat(i.NULL),new E(e,"null");case i.lbracket:return this._arrayExpression();case i.lbrace:return this._objectExpression();case i.IF:return this._ifStatement();case i.WHILE_TILL:return this._whileLoop(!0);case i.FOR_LOOP:return this._forLoop(!0);case i.BREAK:return this._breakExpression();case i.CONTINUE:return this._continueExpression();default:return this._variable()}}_breakExpression(){var e,t;return this._loopTrack.isEmpty&&T(this.currentToken),this._eat(i.BREAK),new et((e=this.currentToken)==null?void 0:e.line,(t=this.currentToken)==null?void 0:t.col)}_continueExpression(){var e,t;return this._loopTrack.isEmpty&&T(this.currentToken),this._eat(i.CONTINUE),new nt((e=this.currentToken)==null?void 0:e.line,(t=this.currentToken)==null?void 0:t.col)}_term(){let e=this._factor();return e=this._tryParsingFunctionCall(e),e=this._tryParsingMemberExpression(e),e}_expression(){let e=this._term();for(e=this._tryBinaryExpression(0,e);[i.and,i.or,i.nullity].includes(this.currentToken.type);){let t=this.currentToken;this._eat(t.type),e=new W(e,t,this._expression())}if(this._expect(i.equal))if(e instanceof x||e instanceof w){let t=this.currentToken;this._eat(i.equal),e=new L(e,this._expression())}else throw new Error("Unexpected token");return e}_objectProperty(){var r;let e;switch((r=this.currentToken)==null?void 0:r.type){case i.stringConst:{e=new E(this.currentToken,this.currentToken.value),this._eat(i.stringConst);break}case i.lbracket:{this._eat(i.lbracket);var t=this._expression();this._eat(i.rbracket),e=t;break}case i.id:{let a=this._variable();e=new E(new l(i.id,a.value,a.line,a.col),a.value);break}default:throw`Unexpected token ${this.currentToken}`}this._eat(i.colon);var n=this._expression();return new O(e,n)}_property(){return this._objectProperty()}_objectProperties(){var t,n;let e=[];for(((t=this.currentToken)==null?void 0:t.type)!=i.rbrace&&(this._eatEOL(),e.push(this._property()),this._eatEOL());((n=this.currentToken)==null?void 0:n.type)===i.comma&&(this._eat(i.comma),this._eatEOL(),!this._expect(i.rbrace));)e.push(this._property()),this._eatEOL();return e}_objectExpression(e){var t=e!=null?e:this.currentToken;e||this._eat(i.lbrace);var n=this._objectProperties();return this._eat(i.rbrace),new $(n,t,this.currentToken)}_arrayExpression(){this._eat(i.lbracket);let e=this._expect(i.rbracket)?[]:this._expressionsList();this._eat(i.rbracket);var t=e.length!==0?e[0]:void 0,n=e.length!==0?e[e.length-1]:void 0;return new F(e,t,n)}_tryParsingMemberExpression(e){let t=e;for(;this.currentToken.type===i.lbracket||this.currentToken.type===i.dot;)if(this.currentToken.type===i.lbracket){this._eat(i.lbracket);let n=this._expression();t=new w(t,n,!0),this._eat(i.rbracket)}else{this._eat(i.dot);let n=this.currentToken;n.type!==i.id&&T(n);let r=new E(new l(i.stringConst,n.value,n.line,n.col),n.value);this._eat(i.id),t=new w(t,r)}return t}_tryBinaryExpression(e,t){let n=t;for(;;){let r=tt._binopPrecdences[this.currentToken.type]||-1;if(r<e)return n;let a=this.currentToken;this._eat(a.type);let o=this._term(),u=tt._binopPrecdences[this.currentToken.type]||-1;if(r<u){let p=this._tryBinaryExpression(r+1,o);if(p===n)return p;o=p}n=new z(n,a,o)}}_expressionsList(){var n;this._eatEOL();let e=this._expression();this._eatEOL();let t=[e];for(;((n=this.currentToken)==null?void 0:n.type)===i.comma&&(this._eat(i.comma),this._eatEOL(),!this._expect(i.rbracket));)e=this._expression(),t.push(e),this._eatEOL();return t}_callExpression(e){this._eat(i.lparen);let t=[];return this._expect(i.rparen)||(t=this._expressionsList()),this._eat(i.rparen),e instanceof x||T(this.currentToken),new P(e,t)}_tryParsingFunctionCall(e){let t=e;for(;this.currentToken.type===i.lparen;)t=this._callExpression(t);return t}_statementExpression(){let e=this._expression();return[i.semi,i.eol,i.eof,i.rbrace].includes(this.currentToken.type)||T(this.currentToken),e}_blockStatement(e=!1){if(e||this._eat(i.lbrace),this._eatEOL(),this._expect(i.rbrace))return this._eat(i.rbrace),new R([],this.currentToken);let t=[this._statement()];for(;this._eatSemiOrEOL(),!(this.currentToken.type===i.rbrace||this.currentToken.type===i.eof||(t.push(this._statement()),this._expect(i.rbrace)));)this.currentToken.type!==i.eol&&this.currentToken.type!==i.semi&&this.currentToken.type!==i.eof&&T(this.currentToken);return this._eat(i.rbrace),new R(t,this.currentToken)}_ifStatement(){this._eat(i.IF);let e=this.currentToken.type===i.lparen;e&&this._eat(i.lparen);let t=this._expression();e&&this._eat(i.rparen);let n;this.currentToken.type===i.lbrace?n=this._blockStatement():n=this._expression();let r;if(this.currentToken.type===i.ELSE)switch(this._eat(i.ELSE),this.currentToken.type){case i.IF:r=this._ifStatement();break;case i.lbrace:r=this._blockStatement();break;default:r=this._expression()}return new D(t,n,r)}_pushLoop(){this._loopTrack.push(!0)}_popLoop(){this._loopTrack.pop()}_whileLoop(e=!1){let t=this.currentToken;this._eat(i.WHILE_TILL),this._pushLoop();let n=this._expression(),r=this.currentToken.type===i.lbrace?this._blockStatement():this._expression();return this._popLoop(),new B(n,r,t,this.currentToken,e)}_forOfIdentifier(){switch(this.currentToken.type){case i.lparen:{this._eat(i.lparen);let e=this._variable();this._eat(i.comma);let t=this._variable();return this._eat(i.rparen),new I(e,t)}default:return this._variable()}}_forLoop(e=!1){let t=this.currentToken;this._eat(i.FOR_LOOP),this._pushLoop();let n=[i.lparen].includes(this.currentToken.type),r;if(n)r=this._forOfIdentifier();else{let a=this._expression();a instanceof L||(n=!0),r=a}if(!n&&r instanceof L){this._eat(i.TILL);let a=this._expression(),o;if(this.currentToken.type===i.up||this.currentToken.type===i.down){let f=this.currentToken;this._eat(f.type),o=f}else o=new l(i.up,"up");let u;this._expect(i.with)?(this._eat(i.with),u=this._expression()):u=new E(new l(i.numberConst,1,this.currentToken.line,this.currentToken.col),"1");let p=this.currentToken.type===i.lbrace?this._blockStatement():this._expression();r=new K(r,a,u,o,p,t,this.currentToken,e),this._popLoop()}else if(n){this._eat(i.in);let a=this._expression(),o=this.currentToken.type===i.lbrace?this._blockStatement():this._expression();r=new H(r,a,o,t,this.currentToken,e),this._popLoop()}else T(this.currentToken);return r}_statement(){switch(this.currentToken.type){case i.BREAK:return this._breakExpression();case i.CONTINUE:return this._continueExpression();case i.RETURN:return this._eat(i.RETURN),this._return();case i.semi:return this._eatSemi(),this._statement();case i.eol:return this._eatEOL(),this._statement();case i.WHILE_TILL:return this._whileLoop();case i.FOR_LOOP:return this._forLoop();default:return this._statementExpression()}}_expect(e){var t;return((t=this.currentToken)==null?void 0:t.type)===e}_definition(){if(this._eatSemiOrEOL(),this._expect(i.eof))return[];let e=[this._statement()];for(;;){if(this._eatSemiOrEOL(),this.currentToken.type===i.eof){this._eat(i.eof);break}this.currentToken.type===i.lbrace?e.push(this._blockStatement()):e.push(this._statement())}return e}_root(){let e=this.lexer.source,t="<module>",n=this._definition();return new j(n,t,e)}parse(){return this._root()}};tt._binopPrecdences={[i.eqeq]:10,[i.notEq]:10,[i.great]:10,[i.greatEq]:10,[i.less]:10,[i.lessEq]:10,[i.plus]:20,[i.minus]:20,[i.mult]:40,[i.div]:40,[i.mod]:40};var dt=tt,V=class{},C=class extends V{},M=class extends V{},y=class{constructor(e){this.value=e}},_t=class{constructor(){this._nodesVisitors={}}registerVisitor(e,t){let n=`visit${e.name}`;this._nodesVisitors[n]=t}},St=class extends _t{constructor(){super(),this.registerVisitor(j,this.visitRootAST),this.registerVisitor(R,this.visitBlockStatementAST),this.registerVisitor(x,this.visitIdentifierAST),this.registerVisitor(E,this.visitLiteralAST),this.registerVisitor(L,this.visitAssignmentExpressionAST),this.registerVisitor(X,this.visitExpressionStatementAST),this.registerVisitor(P,this.visitCallExpressionAST),this.registerVisitor(z,this.visitBinaryExpressionAST),this.registerVisitor(U,this.visitUnaryExpressionAST),this.registerVisitor(D,this.visitIfStatementAST),this.registerVisitor(W,this.visitLogicalExpressionAST),this.registerVisitor(w,this.visitIndexAccessorAST),this.registerVisitor(O,this.visitObjectProperty),this.registerVisitor($,this.visitObjectExpression),this.registerVisitor(F,this.visitArrayExpression),this.registerVisitor(B,this.visitWhileLoopStatement),this.registerVisitor(K,this.visitForLoopStatement),this.registerVisitor(H,this.visitForOfStatement),this.registerVisitor(et,this.visitBreakAST),this.registerVisitor(nt,this.visitContinueAST),this.registerVisitor(Y,this.visitReturnAST)}visit(e){this.beforeVisit(e);let t=`visit${e.constructor.name}`,n=this._nodesVisitors[t];if(!n)throw new S(`No ${t} declared`,e.line,e.col,e.constructor.name);try{let r=n.call(this,e);return r&&typeof r.then=="function"?r.catch(a=>{throw S.fromNode(e,a)}):r!=null?r:null}catch(r){throw S.fromNode(e,r)}}beforeVisit(e){}assignProperty(e,t,n){(Array.isArray(e)||typeof e=="object")&&(e[t]=n)}},ct=class{constructor(e,t,n){this.memory={};this.name=e,this.memory=t,this.parent=n}resolve(e){var t,n;return Object.keys(this.memory).includes(e)?this.memory[e]:(n=(t=this.parent)==null?void 0:t.resolve(e))!=null?n:null}change(e,t,n=!0){return Object.keys(this.memory).includes(e)?(this.memory[e]=t,!0):this.parent&&this.parent.change(e,t,!1)?!0:n?(this.memory[e]=t,!0):!1}},rt={_ok_:g("_ok_",{name:"_ok_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"boolean"}),_err_:g("_err_",{name:"_err_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"boolean"}),_value_:g("_value_",{name:"_value_",minArgs:1,maxArgs:2,args:[{name:"result"},{name:"fallback",required:!1}],returnType:"any"}),_error_:g("_error_",{name:"_error_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"object"}),_code_:g("_code_",{name:"_code_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"string"}),_message_:g("_message_",{name:"_message_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"string"}),_unwrap_:g("_unwrap_",{name:"_unwrap_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"any"}),_len_:g("_len_",{name:"_len_",minArgs:1,maxArgs:1,args:[{name:"target"}],returnType:"number"}),_push_:g("_push_",{name:"_push_",minArgs:2,maxArgs:2,args:[{name:"array",type:"array"},{name:"value"}],returnType:"array"}),_pop_:g("_pop_",{name:"_pop_",minArgs:1,maxArgs:1,args:[{name:"array",type:"array"}],returnType:"any"}),_insert_:g("_insert_",{name:"_insert_",minArgs:3,maxArgs:3,args:[{name:"array",type:"array"},{name:"index",type:"number"},{name:"value"}],returnType:"array"}),_remove_at_:g("_remove_at_",{name:"_remove_at_",minArgs:2,maxArgs:2,args:[{name:"array",type:"array"},{name:"index",type:"number"}],returnType:"any"}),_has_:g("_has_",{name:"_has_",minArgs:2,maxArgs:2,args:[{name:"object",type:"object"},{name:"key"}],returnType:"boolean"}),_keys_:g("_keys_",{name:"_keys_",minArgs:1,maxArgs:1,args:[{name:"object",type:"object"}],returnType:"array"}),_values_:g("_values_",{name:"_values_",minArgs:1,maxArgs:1,args:[{name:"object",type:"object"}],returnType:"array"})};function it(s){return typeof s=="object"&&s!=null&&s.ok===!0}function at(s){if(typeof s!="object"||s==null)return;let e=s;if(!(e.ok!==!1||typeof e.error!="object"||e.error==null))return e.error}function N(s){return typeof s=="number"?s:void 0}function G(s){return typeof s=="string"?s:void 0}function Ft(s){var t,n;let e=at(s);return new S((t=G(e==null?void 0:e.message))!=null?t:"Cannot unwrap failed _try_ result",N(e==null?void 0:e.line),N(e==null?void 0:e.col),G(e==null?void 0:e.node),void 0,{code:(n=G(e==null?void 0:e.code))!=null?n:"invalid_try_result",name:G(e==null?void 0:e.name),argCount:N(e==null?void 0:e.argCount),minArgs:N(e==null?void 0:e.minArgs),maxArgs:N(e==null?void 0:e.maxArgs),argIndex:N(e==null?void 0:e.argIndex),expectedType:G(e==null?void 0:e.expectedType),actualType:G(e==null?void 0:e.actualType),stepCount:N(e==null?void 0:e.stepCount),maxSteps:N(e==null?void 0:e.maxSteps)})}function ht(s,e,t,n){let r=Z(n);return new S(`Function '${s}' argument ${e} expects ${t}, got ${r}`,void 0,void 0,void 0,void 0,{code:"invalid_argument_type",name:s,argIndex:e,expectedType:t,actualType:r})}function st(s,e,t){let n=e[t];if(Array.isArray(n))return n;throw ht(s,t,"array",n)}function pt(s,e,t){let n=e[t];if(typeof n=="object"&&n!=null&&!Array.isArray(n))return n;throw ht(s,t,"object",n)}function Tt(s,e,t){let n=e[t];if(typeof n=="number")return Math.trunc(n);throw ht(s,t,"number",n)}function Rt(s,e,t){return new S(`Function '${s}' index ${e} is out of range for array of length ${t}`,void 0,void 0,void 0,void 0,{code:"index_out_of_range",name:s})}var Vt={_ok_:s=>it(s[0]),_err_:s=>!it(s[0]),_value_:s=>{var e,t;return it(s[0])?(e=s[0].value)!=null?e:null:(t=s[1])!=null?t:null},_error_:s=>{var e;return(e=at(s[0]))!=null?e:null},_code_:s=>{var e,t;return(t=(e=at(s[0]))==null?void 0:e.code)!=null?t:null},_message_:s=>{var e,t;return(t=(e=at(s[0]))==null?void 0:e.message)!=null?t:null},_unwrap_:s=>{var e;if(it(s[0]))return(e=s[0].value)!=null?e:null;throw Ft(s[0])},_len_:s=>{let e=s[0];if(Array.isArray(e)||typeof e=="string")return e.length;if(typeof e=="object"&&e!=null)return Object.keys(e).length;throw ht("_len_",0,"array|object|string",e)},_push_:s=>{var t;let e=st("_push_",s,0);return e.push((t=s[1])!=null?t:null),e},_pop_:s=>{var t;let e=st("_pop_",s,0);return e.length===0?null:(t=e.pop())!=null?t:null},_insert_:s=>{var n;let e=st("_insert_",s,0),t=Tt("_insert_",s,1);if(t<0||t>e.length)throw Rt("_insert_",t,e.length);return e.splice(t,0,(n=s[2])!=null?n:null),e},_remove_at_:s=>{var n;let e=st("_remove_at_",s,0),t=Tt("_remove_at_",s,1);return t<0||t>=e.length?null:(n=e.splice(t,1)[0])!=null?n:null},_has_:s=>Object.prototype.hasOwnProperty.call(pt("_has_",s,0),s[1]),_keys_:s=>Object.keys(pt("_keys_",s,0)),_values_:s=>Object.values(pt("_values_",s,0))},_=class _ extends St{constructor(t){super();this.rootScope=new ct("Program",{});this.currentScope=this.rootScope;this.debug=!1;this._functionsRegistry={};this._functionSpecs={};this._executionStepCount=0;this._traceEvents=[];this._options=Nt(t),this._functionsRegistry={...Vt,..._._globalFunctionsRegistry},this._functionSpecs={...rt,..._._globalFunctionSpecs}}get options(){return{...this._options}}get executionStepCount(){return this._executionStepCount}trace(){return this._traceEvents.map(t=>({...t,detail:{...t.detail}}))}resetExecutionBudget(){this._executionStepCount=0}beforeVisit(t){this._executionStepCount+=1,this.recordTrace("visit",t);let n=this._options.maxSteps;if(n!=null&&this._executionStepCount>n)throw new S(`Execution budget exceeded after ${this._executionStepCount} step(s)`,t.line,t.col,t.constructor.name,void 0,{code:"execution_budget_exceeded",stepCount:this._executionStepCount,maxSteps:n})}clearTrace(){this._traceEvents=[]}recordTrace(t,n,r,a={}){this._options.trace&&this._traceEvents.push({kind:t,line:n.line,col:n.col,node:$t(n),name:r,stepCount:this._executionStepCount,detail:a})}resolve(t){var n,r;return(r=(n=this.currentScope)==null?void 0:n.resolve(t))!=null?r:null}changeVariable(t,n){var r;return(r=this.currentScope)!=null&&r.change(t,n)?n:null}pushScope(t){let n=new ct(t,{},this.currentScope);this.currentScope=n}popScope(){var t;this.currentScope=(t=this.currentScope)==null?void 0:t.parent}log(t){this.debug&&console.log(t)}successResult(t){return{ok:!0,value:t,error:null}}errorResult(t){return{ok:!1,value:null,error:t.diagnostic()}}visitRootAST(t){var a;let n=t.body,r;for(let o of n)if(r=this.visit(o),r instanceof y)return(a=r.value)!=null?a:null;return r!=null?r:null}visitBlockStatementAST(t){let n=t.body,r;this.pushScope("Block");for(let a of n)if(r=this.visit(a),r instanceof V||r instanceof y)break;return this.popScope(),r!=null?r:null}visitIdentifierAST(t){var r;let n=t.value;return(r=this==null?void 0:this.resolve(n))!=null?r:null}visitLiteralAST(t){return t.value}visitAssignmentExpressionAST(t){let n=t.identifier,r=t.init,a=null;if(n instanceof w){var o=this.visit(n.owner);a=this.visit(t.init);var u=this.visit(n.key);this.assignProperty(o,u,a)}else n instanceof x&&(a=this.visit(r),this.changeVariable(n.value,a));return a}visitExpressionStatementAST(t){let n=t.expression;return this.visit(n)}visitCallExpressionAST(t){var m,d;let n=t.callee,r=t.arguments,a=n.value;if(a==="_try_"){if(r.length!==1)throw new S("_try_ expects exactly one expression",t.line,t.col,t.constructor.name,void 0,{code:"invalid_try_arity",name:"_try_",argCount:r.length,minArgs:1,maxArgs:1});try{let b=this.visit(r[0]);return b instanceof V||b instanceof y?b:this.successResult(b)}catch(b){if(b instanceof S)return this.errorResult(b);throw b}}let o=this.resolveFunction(a);if(!o){if(this._options.compatV1)return null;throw new S(`Unknown function '${a}'`,t.line,t.col,t.constructor.name,void 0,{code:"unknown_function",name:a})}let u=this.resolveFunctionSpec(a);if(u&&!mt(u,r.length))throw new S(`Function '${a}' expects ${vt(u)} argument(s), got ${r.length}`,t.line,t.col,t.constructor.name,void 0,{code:"invalid_function_arity",name:a,argCount:r.length,minArgs:Q(u),maxArgs:u.maxArgs});let p=r.map(b=>this.visit(b));u&&this.validateRuntimeArgumentTypes(t,u,p),this.recordTrace("call",t,a,{argCount:p.length,returnType:(m=u==null?void 0:u.returnType)!=null?m:"any"});let f=o(p,this);return this.recordTrace("call_result",t,a,{returnType:(d=u==null?void 0:u.returnType)!=null?d:"any",actualType:Z(f)}),f}visitBinaryExpressionAST(t){let n=t.left,r=t.right,a=t.operation,o=this.visit(n),u=this.visit(r);switch(a.type){case i.plus:return h(o)&&h(u)?o+u:`${o}${u}`;case i.minus:if(h(o)&&h(u))return o-u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.mult:if(h(o)&&h(u))return o*u;if(q(o)&&h(u))return o.repeat(u);if(h(o)&&q(u))return u.repeat(o);throw new Error(`Operation ${a.value} not allowed no num value`);case i.div:if(h(o)&&h(u)){if(u===0)throw new Error("Invalid division by 0");return o/u}throw new Error(`Operation ${a.value} not allowed no num value`);case i.mod:if(h(o)&&h(u))return o%u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.great:if(h(o)&&h(u))return o>u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.greatEq:if(h(o)&&h(u))return o>=u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.less:if(h(o)&&h(u))return o<u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.lessEq:if(h(o)&&h(u))return o<=u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.eqeq:return o===u;case i.notEq:return o!==u;default:throw new Error(`Operation ${a.value} not allowed no num value`)}}visitUnaryExpressionAST(t){let n=t.argument,r=t.operation,a=this.visit(n);if(r.type===i.not)return A(a)===!1;if(!h(a))throw new Error(`Operation ${r.value} not allowed no num value`);if(r.type===i.plus)return a;if(r.type===i.minus)return-a;throw new Error(`Operation ${r.value} not allowed no num value`)}visitIfStatementAST(t){let n=t.test,r=this.visit(n);return A(r)?this.visit(t.consequent):t.alternate?this.visit(t.alternate):null}visitLogicalExpressionAST(t){let n=t.left,r=this.visit(n);if(t.operator.type===i.nullity)return r!=null?r:this.visit(t.right);let a=A(r);return t.operator.type===i.and?a?A(this.visit(t.right)):!1:t.operator.type===i.or?a?!0:A(this.visit(t.right)):null}visitIndexAccessorAST(t){var a,o;let n=t.owner,r=this.visit(n);if(r==null)return null;if(Array.isArray(r)){let u=this.visit(t.key);return h(u)&&Number.isInteger(u)&&r.length>u&&u>=0&&(a=r[u])!=null?a:null}else if(typeof r=="object"){let u=this.visit(t.key);return(o=r[u])!=null?o:null}return null}visitObjectProperty(t){}visitObjectExpression(t){let n={},r=t;for(let a of r.properties)if(a instanceof O){let o=this.visit(a.key);o=q(o)?o:o.toString(),n[o]=this.visit(a.value)}return n}visitArrayExpression(t){let n=t;return this.resolveArguments(n.elements)}visitBreakAST(t){return new C}visitWhileLoopStatement(t){this.log(`WhileLoopStatement ${t.test} ${t.body}`);let n=t.retain?[]:void 0;for(;A(this.visit(t.test));){let r=this.visit(t.body);if(r instanceof C)break;if(!(r instanceof M)){if(r instanceof y)return this.popScope(),r;n==null||n.push(r)}}return n!=null?n:null}visitForLoopStatement(t){let n=t.retain?[]:void 0,r=t.init.identifier;if(!(r instanceof x))throw new Error("Unexpected identifer found");this.pushScope("ForLoopStatement");let a=this.visit(t.init.init);this.changeVariable(r.value,a);let o=()=>{let p=this.visit(t.test);if(h(p)){let f=this.resolve(r.value);return t.direction.type===i.up?p>=f:p<=f}return A(p)},u=()=>{let p=this.visit(t.update);if(h(p)){let f=this.resolve(r.value);if(!h(f))throw Error("Cant update value");this.changeVariable(r.value,t.direction.type===i.up?f+p:f-p)}else throw Error("Update value cant be non number")};for(;o();){let p=this.visit(t.body);if(p instanceof C)break;if(p instanceof M){u();continue}if(p instanceof y)return this.popScope(),p;n==null||n.push(p),u()}return this.popScope(),n!=null?n:null}visitForOfStatement(t){let n=this.visit(t.collection);if(!Array.isArray(n))throw Error("Can iterate non array object");let r=t.retain?[]:void 0;this.pushScope("ForOfStatement");for(let a of n){this._declareForIdentifier(t.identifier,a);let o=this.visit(t.body);if(o instanceof C)break;if(!(o instanceof M)){if(o instanceof y)return this.popScope(),o;r==null||r.push(o)}}return this.popScope(),r!=null?r:null}visitContinueAST(t){return new M}visitReturnAST(t){return new y(t.value!=null?this.visit(t.value):null)}_declareForIdentifier(t,n){if(t instanceof I){if(!Array.isArray(n))throw Error("Unable to make a tuple from non Array element");this.changeVariable(t.first.value,n[0]),this.changeVariable(t.second.value,n[1])}this.changeVariable(t.value,n)}resolveArguments(t){return t.map(n=>this.visit(n))}setFunctionResolver(t){this._functionResolver=t}resolveFunction(t){var n,r;return(r=this._functionsRegistry[t])!=null?r:(n=this._functionResolver)==null?void 0:n.call(this,t)}resolveFunctionSpec(t){return this._functionSpecs[t]}capabilities(){return wt(this._functionSpecs)}registerFunction(t,n,r){this._functionsRegistry[t]=n,this._functionSpecs[t]=g(t,r)}unregisterFunction(t){delete this._functionsRegistry[t],delete this._functionSpecs[t]}validate(t,n,r=!1){let a=[],o=this.validationFunctionSpecs(n);try{this.validateNode(_.compile(t,r),o,a)}catch(u){a.push({code:"syntax_error",message:u instanceof Error?u.message:String(u)})}return{ok:a.length===0,errors:a}}validateManifest(t,n,r=!1){let a=[],o=this.validationFunctionSpecs(n.functions);try{let u=_.compile(t,r);this.validateNode(u,o,a),this.validateManifestNode(u,n,a)}catch(u){a.push({code:"syntax_error",message:u instanceof Error?u.message:String(u)})}return{ok:a.length===0,errors:a}}validationFunctionSpecs(t){let n=new Map;return Object.keys(rt).forEach(r=>{var a;return n.set(r,(a=this._functionSpecs[r])!=null?a:rt[r])}),t==null?(Object.keys(this._functionSpecs).forEach(r=>n.set(r,this._functionSpecs[r])),n):t instanceof Set?(t.forEach(r=>{var a;return n.set(r,(a=this._functionSpecs[r])!=null?a:g(r))}),n):Array.isArray(t)?(t.forEach(r=>{var a;typeof r=="string"?n.set(r,(a=this._functionSpecs[r])!=null?a:g(r)):n.set(r.name,g(r.name,r))}),n):(Object.keys(t).forEach(r=>n.set(r,g(r,t[r]))),n)}validateNode(t,n,r,a=!1){t&&(t instanceof j||t instanceof R?t.body.forEach(o=>this.validateNode(o,n,r,a)):t instanceof L?(this.validateNode(t.identifier,n,r,a),this.validateNode(t.init,n,r,a)):t instanceof X?this.validateNode(t.expression,n,r,a):t instanceof P?this.validateCallExpression(t,n,r,a):t instanceof z?(this.validateNode(t.left,n,r,a),this.validateNode(t.right,n,r,a)):t instanceof U?this.validateNode(t.argument,n,r,a):t instanceof D?(this.validateNode(t.test,n,r,a),this.validateNode(t.consequent,n,r,a),this.validateNode(t.alternate,n,r,a)):t instanceof W?(this.validateNode(t.left,n,r,a),this.validateNode(t.right,n,r,a)):t instanceof w?(this.validateNode(t.owner,n,r,a),this.validateNode(t.key,n,r,a)):t instanceof $?t.properties.forEach(o=>this.validateNode(o,n,r,a)):t instanceof O?(this.validateNode(t.key,n,r,a),this.validateNode(t.value,n,r,a)):t instanceof F?t.elements.forEach(o=>this.validateNode(o,n,r,a)):t instanceof B?(this.validateNode(t.test,n,r,a),this.validateNode(t.body,n,r,a)):t instanceof K?(this.validateNode(t.init,n,r,a),this.validateNode(t.test,n,r,a),this.validateNode(t.update,n,r,a),this.validateNode(t.body,n,r,a)):t instanceof H?(this.validateNode(t.identifier,n,r,a),this.validateNode(t.collection,n,r,a),this.validateNode(t.body,n,r,a)):t instanceof I?(this.validateNode(t.first,n,r,a),this.validateNode(t.second,n,r,a)):t instanceof Y&&this.validateNode(t.value,n,r,a))}validateCallExpression(t,n,r,a){let o=t.callee.value;if(o==="_try_"){t.arguments.length!==1&&r.push(this.validationError("invalid_try_arity",t,"_try_ expects exactly one expression","_try_",{argCount:t.arguments.length,minArgs:1,maxArgs:1})),t.arguments.forEach(u=>this.validateNode(u,n,r,!0));return}if(!a){let u=n.get(o);u?mt(u,t.arguments.length)?this.validateStaticArgumentTypes(t,u,r):r.push(this.validationError("invalid_function_arity",t,`Function '${o}' expects ${vt(u)} argument(s), got ${t.arguments.length}`,o,{argCount:t.arguments.length,minArgs:Q(u),maxArgs:u.maxArgs})):this._options.compatV1||r.push(this.validationError("unknown_function",t,`Unknown function '${o}'`,o))}t.arguments.forEach(u=>this.validateNode(u,n,r,a))}validateStaticArgumentTypes(t,n,r){var a;(a=n.args)==null||a.forEach((o,u)=>{var m,d;let p=t.arguments[u];if(!p)return;let f=this.staticArgumentType(p);!f||this.argumentTypeMatches(o,f)||r.push(this.validationError("invalid_argument_type",t,`Function '${n.name}' argument ${u} expects ${(m=o.type)!=null?m:"any"}, got ${f}`,n.name,{argIndex:u,expectedType:(d=o.type)!=null?d:"any",actualType:f}))})}staticArgumentType(t){if(t instanceof E)return Z(t.value);if(t instanceof F)return"array";if(t instanceof $)return"object"}argumentTypeMatches(t,n){var a;let r=(a=t.type)!=null?a:"any";return r==="any"||t.required===!1&&n==="null"?!0:r===n}validateManifestNode(t,n,r){var p,f;let a=((p=n.inputs)!=null?p:[]).map(xt),o=((f=n.outputs)!=null?f:[]).map(xt),u={knownInputs:new Set(a.map(m=>m.name)),assigned:new Set,assignedTypes:new Map,reportedInputs:new Set};this.analyzeManifestNode(t,u,r),o.forEach(m=>{var b,bt,Et;if(((b=m.required)==null||b)&&!u.assigned.has(m.name)){r.push(this.validationError("missing_output",t,`Required output '${m.name}' is not assigned`,m.name));return}let d=u.assignedTypes.get(m.name);!d||this.valueSpecTypeMatches(m,d)||r.push(this.validationError("invalid_output_type",t,`Output '${m.name}' expects ${(bt=m.type)!=null?bt:"any"}, got ${d}`,m.name,{expectedType:(Et=m.type)!=null?Et:"any",actualType:d}))})}analyzeManifestNode(t,n,r){t&&(t instanceof j||t instanceof R?t.body.forEach(a=>this.analyzeManifestNode(a,n,r)):t instanceof L?(this.analyzeManifestNode(t.init,n,r),t.identifier instanceof w&&this.analyzeManifestNode(t.identifier,n,r),this.markAssignedTarget(t.identifier,this.staticArgumentType(t.init),n)):t instanceof X?this.analyzeManifestNode(t.expression,n,r):t instanceof P?t.arguments.forEach(a=>this.analyzeManifestNode(a,n,r)):t instanceof z?(this.analyzeManifestNode(t.left,n,r),this.analyzeManifestNode(t.right,n,r)):t instanceof U?this.analyzeManifestNode(t.argument,n,r):t instanceof D?(this.analyzeManifestNode(t.test,n,r),this.analyzeManifestNode(t.consequent,n,r),this.analyzeManifestNode(t.alternate,n,r)):t instanceof W?(this.analyzeManifestNode(t.left,n,r),this.analyzeManifestNode(t.right,n,r)):t instanceof w?(this.analyzeManifestNode(t.owner,n,r),this.analyzeManifestNode(t.key,n,r)):t instanceof $?t.properties.forEach(a=>this.analyzeManifestNode(a,n,r)):t instanceof O?(this.analyzeManifestNode(t.key,n,r),this.analyzeManifestNode(t.value,n,r)):t instanceof F?t.elements.forEach(a=>this.analyzeManifestNode(a,n,r)):t instanceof B?(this.analyzeManifestNode(t.test,n,r),this.analyzeManifestNode(t.body,n,r)):t instanceof K?(this.analyzeManifestNode(t.init,n,r),this.analyzeManifestNode(t.test,n,r),this.analyzeManifestNode(t.body,n,r),this.analyzeManifestNode(t.update,n,r)):t instanceof H?(this.analyzeManifestNode(t.collection,n,r),this.markAssignedTarget(t.identifier,void 0,n),this.analyzeManifestNode(t.body,n,r)):t instanceof I?(this.analyzeManifestNode(t.first,n,r),this.analyzeManifestNode(t.second,n,r)):t instanceof Y?this.analyzeManifestNode(t.value,n,r):t instanceof x&&!n.knownInputs.has(t.value)&&!n.assigned.has(t.value)&&!n.reportedInputs.has(t.value)&&(n.reportedInputs.add(t.value),r.push(this.validationError("unknown_input",t,`Unknown input '${t.value}'`,t.value))))}markAssignedTarget(t,n,r){t instanceof x?(r.assigned.add(t.value),n&&r.assignedTypes.set(t.value,n)):t instanceof I&&(this.markAssignedTarget(t.first,void 0,r),this.markAssignedTarget(t.second,void 0,r))}valueSpecTypeMatches(t,n){var a;let r=(a=t.type)!=null?a:"any";return r==="any"||t.required===!1&&n==="null"?!0:r===n}validationError(t,n,r,a,o){return{code:t,message:r,name:a,line:n.line,col:n.col,node:n.constructor.name,argCount:o==null?void 0:o.argCount,minArgs:o==null?void 0:o.minArgs,maxArgs:o==null?void 0:o.maxArgs,argIndex:o==null?void 0:o.argIndex,expectedType:o==null?void 0:o.expectedType,actualType:o==null?void 0:o.actualType}}validateRuntimeArgumentTypes(t,n,r){var a;(a=n.args)==null||a.forEach((o,u)=>{var f,m;if(u>=r.length)return;let p=Z(r[u]);if(!this.argumentTypeMatches(o,p))throw new S(`Function '${n.name}' argument ${u} expects ${(f=o.type)!=null?f:"any"}, got ${p}`,t.line,t.col,t.constructor.name,void 0,{code:"invalid_argument_type",name:n.name,argIndex:u,expectedType:(m=o.type)!=null?m:"any",actualType:p})})}execute(t,n=!0,r){let a=_.compile(t,n);return r&&Object.keys(r).forEach(o=>this.changeVariable(o,r[o])),this.resetExecutionBudget(),this.clearTrace(),this.visit(a)}static compile(t,n=!1){let r=Mt(t);if(n&&this._cache.has(r))return this._cache.get(r);let a=new ft(t),u=new dt(a).parse();return n&&this._cache.set(r,u),u}static register(t,n,r){_._globalFunctionsRegistry[t]=n,_._globalFunctionSpecs[t]=g(t,r)}static unregister(t){delete _._globalFunctionsRegistry[t],delete _._globalFunctionSpecs[t]}static capabilities(){return wt({...rt,..._._globalFunctionSpecs})}static validateSource(t,n,r=!1){return new _().validate(t,n,r)}static validateManifestSource(t,n,r=!1){return new _().validateManifest(t,n,r)}static run(t,n=!1,r,a){return new _(a).execute(t,n,r)}static newInstance(t){return new _(t)}clone(){var t=new _(this.options);return t._functionsRegistry={...this._functionsRegistry},t._functionSpecs={...this._functionSpecs},t.rootScope.memory={...this.rootScope.memory},t}newAsyncInstance(){let t=yt.newInstance(this.options);return t.rootScope.memory=this.rootScope.memory,t._functionsRegistry=this._functionsRegistry,t._functionSpecs=this._functionSpecs,t}};_._globalFunctionsRegistry={},_._globalFunctionSpecs={},_._cache=new Map;var lt=_,yt=class s extends lt{constructor(e){super(e)}async visitRootAST(e){var r;let t=e.body,n;for(let a of t)if(n=await this.visit(a),n instanceof y)return(r=n.value)!=null?r:null;return n!=null?n:null}async visitBlockStatementAST(e){let t=e.body,n;this.pushScope("Block");for(let r of t)if(n=await this.visit(r),n instanceof V||n instanceof y)break;return this.popScope(),n}async visitIdentifierAST(e){let t=e.value;return this.resolve(t)}async visitLiteralAST(e){return e.value}async visitAssignmentExpressionAST(e){let t=e.identifier,n=e.init,r=null;if(t instanceof w){var a=await this.visit(t.owner);r=await this.visit(e.init);var o=await this.visit(t.key);this.assignProperty(a,o,r)}else t instanceof x&&(r=await this.visit(n),this.changeVariable(t.value,r));return r}async visitExpressionStatementAST(e){let t=e.expression;return await this.visit(t)}async visitCallExpressionAST(e){var f,m;let t=e.callee,n=e.arguments,r=t.value;if(r==="_try_"){if(n.length!==1)throw new S("_try_ expects exactly one expression",e.line,e.col,e.constructor.name,void 0,{code:"invalid_try_arity",name:"_try_",argCount:n.length,minArgs:1,maxArgs:1});try{let d=await this.visit(n[0]);return d instanceof V||d instanceof y?d:this.successResult(d)}catch(d){if(d instanceof S)return this.errorResult(d);throw d}}let a=this.resolveFunction(r);if(!a){if(this._options.compatV1)return null;throw new S(`Unknown function '${r}'`,e.line,e.col,e.constructor.name,void 0,{code:"unknown_function",name:r})}let o=this.resolveFunctionSpec(r);if(o&&!mt(o,n.length))throw new S(`Function '${r}' expects ${vt(o)} argument(s), got ${n.length}`,e.line,e.col,e.constructor.name,void 0,{code:"invalid_function_arity",name:r,argCount:n.length,minArgs:Q(o),maxArgs:o.maxArgs});let u=await Promise.all(n.map(d=>this.visit(d)));o&&this.validateRuntimeArgumentTypes(e,o,u),this.recordTrace("call",e,r,{argCount:u.length,returnType:(f=o==null?void 0:o.returnType)!=null?f:"any"});let p=await a(u,this);return this.recordTrace("call_result",e,r,{returnType:(m=o==null?void 0:o.returnType)!=null?m:"any",actualType:Z(p)}),p}async visitBinaryExpressionAST(e){let t=e.left,n=e.right,r=e.operation,a=await this.visit(t),o=await this.visit(n);switch(r.type){case i.plus:return h(a)&&h(o)?a+o:`${a}${o}`;case i.minus:if(h(a)&&h(o))return a-o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.mult:if(h(a)&&h(o))return a*o;if(q(a)&&h(o))return a.repeat(o);if(h(a)&&q(o))return o.repeat(a);throw new Error(`Operation ${r.value} not allowed no num value`);case i.div:if(h(a)&&h(o)){if(o===0)throw new Error("Invalid division by 0");return a/o}throw new Error(`Operation ${r.value} not allowed no num value`);case i.mod:if(h(a)&&h(o))return a%o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.great:if(h(a)&&h(o))return a>o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.greatEq:if(h(a)&&h(o))return a>=o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.less:if(h(a)&&h(o))return a<o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.lessEq:if(h(a)&&h(o))return a<=o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.eqeq:return a===o;case i.notEq:return a!==o;default:throw new Error(`Operation ${r.value} not allowed no num value`)}}async visitUnaryExpressionAST(e){let t=e.argument,n=e.operation,r=await this.visit(t);if(n.type===i.not)return A(r)===!1;if(!h(r))throw new Error(`Operation ${n.value} not allowed no num value`);if(n.type===i.plus)return r;if(n.type===i.minus)return-r;throw new Error(`Operation ${n.value} not allowed no num value`)}async visitIfStatementAST(e){let t=e.test,n=await this.visit(t);return A(n)?await this.visit(e.consequent):e.alternate?await this.visit(e.alternate):null}async visitLogicalExpressionAST(e){let t=e.left,n=await this.visit(t);if(e.operator.type===i.nullity)return n!=null?n:await this.visit(e.right);let r=A(n);return e.operator.type===i.and?r?A(await this.visit(e.right)):!1:e.operator.type===i.or?r?!0:A(await this.visit(e.right)):!1}async visitIndexAccessorAST(e){var r,a;let t=e.owner,n=await this.visit(t);if(n==null)return null;if(Array.isArray(n)){let o=await this.visit(e.key);return h(o)&&Number.isInteger(o)&&n.length>o&&o>=0&&(r=n[o])!=null?r:null}else if(typeof n=="object"){let o=await this.visit(e.key);return(a=n[o])!=null?a:null}return null}async visitObjectProperty(e){}async visitObjectExpression(e){let t={},n=e;for(let r of n.properties)if(r instanceof O){let a=await this.visit(r.key);a=q(a)?a:a.toString(),t[a]=await this.visit(r.value)}return t}async visitArrayExpression(e){let t=e;return await this.resolveArgumentsAsync(t.elements)}async visitWhileLoopStatement(e){this.log(`WhileLoopStatement ${e.test} ${e.body}`);let t=e.retain?[]:void 0;for(;A(await this.visit(e.test));){let n=await this.visit(e.body);if(n instanceof C)break;if(!(n instanceof M)){if(n instanceof y)return this.popScope(),n;t==null||t.push(n)}}return t}async visitForLoopStatement(e){let t=e.retain?[]:void 0,n=e.init.identifier;if(!(n instanceof x))throw new Error("Unexpected identifer found");this.pushScope("ForLoopStatement");let r=await this.visit(e.init.init);this.changeVariable(n.value,r);let a=async()=>{let u=await this.visit(e.test);if(h(u)){let p=this.resolve(n.value);return e.direction.type===i.up?u>=p:u<=p}return A(u)},o=async()=>{let u=await this.visit(e.update);if(h(u)){let p=this.resolve(n.value);if(!h(p))throw Error("Cant update value");this.changeVariable(n.value,e.direction.type===i.up?p+u:p-u)}else throw Error("Update value cant be non number")};for(;await a();){let u=await this.visit(e.body);if(u instanceof C)break;if(u instanceof M){await o();continue}if(u instanceof y)return this.popScope(),u;t==null||t.push(u),await o()}return this.popScope(),t!=null?t:null}async visitForOfStatement(e){let t=await this.visit(e.collection);if(!Array.isArray(t))throw Error("Can iterate non array object");let n=e.retain?[]:void 0;this.pushScope("ForOfStatement");for(let r of t){this._declareForIdentifier(e.identifier,r);let a=await this.visit(e.body);if(a instanceof C)break;if(!(a instanceof M)){if(a instanceof y)return this.popScope(),a;n==null||n.push(a)}}return this.popScope(),n}async visitReturnAST(e){return new y(e.value!=null?await this.visit(e.value):null)}async resolveArgumentsAsync(e){return await Promise.all(e.map(async t=>await this.visit(t)))}registerFunction(e,t,n){this._functionsRegistry[e]=t,this._functionSpecs[e]=g(e,n)}unregisterFunction(e){delete this._functionsRegistry[e],delete this._functionSpecs[e]}async execute(e,t=!0,n){let r=lt.compile(e,t);return n&&Object.keys(n).forEach(a=>this.changeVariable(a,n[a])),this.resetExecutionBudget(),this.clearTrace(),await this.visit(r)}static async run(e,t=!1,n,r){return await new s(r).execute(e,t,n)}static newInstance(e){return new s(e)}clone(){var e=new s(this.options);return e._functionsRegistry={...this._functionsRegistry},e._functionSpecs={...this._functionSpecs},e.rootScope.memory={...this.rootScope.memory},e}};export{v as AST,F as ArrayExpression,L as AssignmentExpressionAST,z as BinaryExpressionAST,R as BlockStatementAST,et as BreakAST,C as BreakBranch,P as CallExpressionAST,nt as ContinueAST,M as ContinueBranch,X as ExpressionStatementAST,K as ForLoopStatement,H as ForOfStatement,x as IdentifierAST,D as IfStatementAST,w as IndexAccessorAST,J as LexerDictionary,E as LiteralAST,W as LogicalExpressionAST,V as LoopControl,ct as MEventScope,lt as MEvento,yt as MEventoAsync,S as MEventoRuntimeError,St as NodeVisitor,$ as ObjectExpression,O as ObjectProperty,Y as ReturnAST,y as ReturnBranch,j as RootAST,l as Token,i as TokenType,I as TupleExpression,U as UnaryExpressionAST,B as WhileLoopStatement};
package/package.json CHANGED
@@ -1,6 +1,18 @@
1
1
  {
2
2
  "name": "mevento",
3
- "version": "4.0.0",
3
+ "version": "4.0.2",
4
+ "description": "An embeddable C-like scripting language with synchronous and asynchronous VMs for JavaScript and TypeScript host applications.",
5
+ "license": "MIT",
6
+ "keywords": [
7
+ "embedded-scripting",
8
+ "scripting-language",
9
+ "scripting-engine",
10
+ "interpreter",
11
+ "virtual-machine",
12
+ "typescript",
13
+ "javascript",
14
+ "dsl"
15
+ ],
4
16
  "main": "dist/cjs/index.js",
5
17
  "module": "dist/esm/index.mjs",
6
18
  "types": "dist/esm/index.d.mts",