@manifesto-ai/compiler 3.6.0 → 3.7.1

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.
@@ -1,12 +0,0 @@
1
- var He={domain:"DOMAIN",state:"STATE",computed:"COMPUTED",action:"ACTION",effect:"EFFECT",when:"WHEN",once:"ONCE",patch:"PATCH",unset:"UNSET",merge:"MERGE",true:"TRUE",false:"FALSE",null:"NULL",as:"AS",available:"AVAILABLE",dispatchable:"DISPATCHABLE",fail:"FAIL",stop:"STOP",with:"WITH",type:"TYPE",import:"IMPORT",from:"FROM",export:"EXPORT"},Cn=new Set(["function","var","let","const","if","else","for","while","do","switch","case","break","continue","return","throw","try","catch","finally","new","delete","instanceof","void","debugger","this","super","arguments","eval","async","await","yield","class","extends","interface","enum","namespace","module"]);function Wr(t){return t in He}function xt(t){return Cn.has(t)}function vt(t){return Object.hasOwn(He,t)?He[t]:void 0}function Ke(t,e,n,o){return{kind:t,lexeme:e,location:n,value:o}}function At(t,e,n){return{line:t,column:e,offset:n}}function wt(t,e,n){return{start:t,end:e,source:n}}function Qr(t,e){return{start:t,end:t,source:e}}function h(t,e){return{start:t.start.offset<e.start.offset?t.start:e.start,end:t.end.offset>e.end.offset?t.end:e.end,source:t.source??e.source}}var We=class{source;sourcePath;tokens=[];diagnostics=[];start=0;current=0;line=1;column=1;lineStart=0;constructor(e,n){this.source=e,this.sourcePath=n}tokenize(){for(;!this.isAtEnd();)this.start=this.current,this.scanToken();return this.tokens.push(Ke("EOF","",this.currentLocation())),{tokens:this.tokens,diagnostics:this.diagnostics}}scanToken(){let e=this.advance();switch(e){case"(":this.addToken("LPAREN");break;case")":this.addToken("RPAREN");break;case"{":this.addToken("LBRACE");break;case"}":this.addToken("RBRACE");break;case"[":this.addToken("LBRACKET");break;case"]":this.addToken("RBRACKET");break;case",":this.addToken("COMMA");break;case";":this.addToken("SEMICOLON");break;case".":this.addToken("DOT");break;case"+":this.addToken("PLUS");break;case"-":this.addToken("MINUS");break;case"*":this.addToken("STAR");break;case"%":this.addToken("PERCENT");break;case":":this.addToken("COLON");break;case"@":this.addToken("AT");break;case"=":this.addToken(this.match("=")?"EQ_EQ":"EQ");break;case"!":this.addToken(this.match("=")?"BANG_EQ":"BANG");break;case"<":this.addToken(this.match("=")?"LT_EQ":"LT");break;case">":this.addToken(this.match("=")?"GT_EQ":"GT");break;case"&":this.match("&")?this.addToken("AMP_AMP"):this.error("Expected '&&' for logical AND");break;case"|":this.match("|")?this.addToken("PIPE_PIPE"):this.addToken("PIPE");break;case"?":this.addToken(this.match("?")?"QUESTION_QUESTION":"QUESTION");break;case"/":this.match("/")?this.lineComment():this.match("*")?this.blockComment():this.addToken("SLASH");break;case" ":case"\r":case" ":break;case`
2
- `:this.newline();break;case'"':this.string('"');break;case"'":this.string("'");break;case"$":this.systemIdentifier();break;default:this.isDigit(e)?this.number():this.isAlpha(e)?this.identifier():this.error(`Unexpected character '${e}'`)}}lineComment(){for(;this.peek()!==`
3
- `&&!this.isAtEnd();)this.advance()}blockComment(){let e=this.line,n=this.column-2;for(;!this.isAtEnd();){if(this.peek()==="*"&&this.peekNext()==="/"){this.advance(),this.advance();return}this.peek()===`
4
- `&&this.newline(),this.advance()}this.error(`Unterminated block comment starting at line ${e}:${n}`)}string(e){let n=this.line,o=this.column-1,r="";for(;this.peek()!==e&&!this.isAtEnd();){if(this.peek()===`
5
- `){this.error("Unterminated string literal");return}if(this.peek()==="\\"){this.advance();let i=this.advance();switch(i){case"n":r+=`
6
- `;break;case"r":r+="\r";break;case"t":r+=" ";break;case"\\":r+="\\";break;case"'":r+="'";break;case'"':r+='"';break;case"0":r+="\0";break;default:this.error(`Invalid escape sequence '\\${i}'`),r+=i}}else r+=this.advance()}if(this.isAtEnd()){this.error(`Unterminated string starting at line ${n}:${o}`);return}this.advance(),this.addToken("STRING",r)}number(){if(this.source[this.start]==="0"&&(this.peek()==="x"||this.peek()==="X")){for(this.advance();this.isHexDigit(this.peek());)this.advance();let n=this.source.slice(this.start+2,this.current),o=parseInt(n,16);this.addToken("NUMBER",o);return}for(;this.isDigit(this.peek());)this.advance();if(this.peek()==="."&&this.isDigit(this.peekNext()))for(this.advance();this.isDigit(this.peek());)this.advance();if(this.peek()==="e"||this.peek()==="E"){if(this.advance(),(this.peek()==="+"||this.peek()==="-")&&this.advance(),!this.isDigit(this.peek())){this.error("Invalid number: expected digits after exponent");return}for(;this.isDigit(this.peek());)this.advance()}let e=parseFloat(this.source.slice(this.start,this.current));this.addToken("NUMBER",e)}identifier(){for(;this.isAlphaNumeric(this.peek());){if(this.peek()==="$"){this.advance(),this.error("'$' is forbidden in identifiers (MEL A17)","E004");continue}this.advance()}let e=this.source.slice(this.start,this.current);if(e.startsWith("__sys__")){this.error("'__sys__' prefix is reserved for compiler-generated identifiers (MEL A26)","E004"),this.addToken("ERROR");return}if(xt(e)){this.error(`'${e}' is a reserved keyword and cannot be used`),this.addToken("ERROR");return}let n=vt(e);n?this.addToken(n):this.addToken("IDENTIFIER")}systemIdentifier(){if(!this.isAlpha(this.peek())){this.error("Expected identifier after '$'"),this.addToken("ERROR");return}for(;this.isAlphaNumeric(this.peek());)this.advance();let e=this.source.slice(this.start,this.current);if(e==="$item"){this.addToken("ITEM");return}if(e==="$system"||e==="$meta"||e==="$input"){for(;this.peek()==="."&&this.isAlpha(this.peekNext());)for(this.advance();this.isAlphaNumeric(this.peek());)this.advance();this.addToken("SYSTEM_IDENT");return}this.error(`Invalid system identifier '${e}'. Expected $system.*, $meta.*, $input.*, or $item`),this.addToken("ERROR")}isAtEnd(){return this.current>=this.source.length}advance(){let e=this.source[this.current];return this.current++,this.column++,e}peek(){return this.isAtEnd()?"\0":this.source[this.current]}peekNext(){return this.current+1>=this.source.length?"\0":this.source[this.current+1]}match(e){return this.isAtEnd()||this.source[this.current]!==e?!1:(this.current++,this.column++,!0)}newline(){this.line++,this.column=1,this.lineStart=this.current}isDigit(e){return e>="0"&&e<="9"}isHexDigit(e){return this.isDigit(e)||e>="a"&&e<="f"||e>="A"&&e<="F"}isAlpha(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"}isAlphaNumeric(e){return this.isAlpha(e)||this.isDigit(e)}currentLocation(){let e=this.positionAt(this.start),n=this.positionAt(this.current);return wt(e,n,this.sourcePath)}positionAt(e){let n=1,o=0;for(let r=0;r<e;r++)this.source[r]===`
7
- `&&(n++,o=r+1);return At(n,e-o+1,e)}addToken(e,n){let o=this.source.slice(this.start,this.current);this.tokens.push(Ke(e,o,this.currentLocation(),n))}error(e,n="MEL_LEXER"){let o=this.currentLocation();this.diagnostics.push({severity:"error",code:n,message:e,location:o,source:this.getSourceLine(o.start.line)})}getSourceLine(e){return this.source.split(`
8
- `)[e-1]??""}};function be(t,e){return new We(t,e).tokenize()}function ii(t){return["literal","identifier","systemIdent","iterationVar","propertyAccess","indexAccess","functionCall","unary","binary","ternary","objectLiteral","arrayLiteral"].includes(t.kind)}function ai(t){return["when","once","onceIntent","patch","effect","fail","stop"].includes(t.kind)}var Ct=(m=>(m[m.NONE=0]="NONE",m[m.TERNARY=1]="TERNARY",m[m.NULLISH=2]="NULLISH",m[m.OR=3]="OR",m[m.AND=4]="AND",m[m.EQUALITY=5]="EQUALITY",m[m.COMPARISON=6]="COMPARISON",m[m.ADDITIVE=7]="ADDITIVE",m[m.MULTIPLICATIVE=8]="MULTIPLICATIVE",m[m.UNARY=9]="UNARY",m[m.CALL=10]="CALL",m[m.ACCESS=11]="ACCESS",m))(Ct||{});function Ye(t){switch(t){case"QUESTION":return 1;case"QUESTION_QUESTION":return 2;case"PIPE_PIPE":return 3;case"AMP_AMP":return 4;case"EQ_EQ":case"BANG_EQ":return 5;case"LT":case"LT_EQ":case"GT":case"GT_EQ":return 6;case"PLUS":case"MINUS":return 7;case"STAR":case"SLASH":case"PERCENT":return 8;default:return 0}}function It(t){switch(t){case"PLUS":return"+";case"MINUS":return"-";case"STAR":return"*";case"SLASH":return"/";case"PERCENT":return"%";case"EQ_EQ":return"==";case"BANG_EQ":return"!=";case"LT":return"<";case"LT_EQ":return"<=";case"GT":return">";case"GT_EQ":return">=";case"AMP_AMP":return"&&";case"PIPE_PIPE":return"||";case"QUESTION_QUESTION":return"??";default:return null}}function ci(t){return Ye(t)!==0}function li(t){return t==="BANG"||t==="MINUS"}function Pt(t){return t==="QUESTION"||t==="QUESTION_QUESTION"}var Qe=class{tokens;current=0;diagnostics=[];constructor(e){this.tokens=e}parse(){try{return{program:this.parseProgram(),diagnostics:this.diagnostics}}catch{return{program:null,diagnostics:this.diagnostics}}}parseProgram(){let e=this.peek().location,n=[];for(;this.check("IMPORT");)n.push(this.parseImport());let o=this.parseAnnotationList();o.length>0&&!this.check("DOMAIN")&&this.reportUnsupportedAnnotations(o);let r=this.parseDomain(o);return{kind:"program",imports:n,domain:r,location:h(e,r.location)}}parseImport(){let e=this.consume("IMPORT","Expected 'import'").location;this.consume("LBRACE","Expected '{' after 'import'");let n=[];do n.push(this.consume("IDENTIFIER","Expected identifier").lexeme);while(this.match("COMMA"));this.consume("RBRACE","Expected '}' after import names"),this.consume("FROM","Expected 'from' after import names");let o=this.consume("STRING","Expected string after 'from'");return{kind:"import",names:n,from:o.value,location:h(e,o.location)}}parseDomain(e=[]){let n=this.consume("DOMAIN","Expected 'domain'").location,o=this.consume("IDENTIFIER","Expected domain name").lexeme;this.consume("LBRACE","Expected '{' after domain name");let r=[],i=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let s=this.parseAnnotationList();if(s.length>0&&(this.check("RBRACE")||this.isAtEnd())){this.reportUnsupportedAnnotations(s);continue}if(this.check("TYPE"))r.push(this.parseTypeDecl(s));else{let c=this.parseDomainMember(s);c&&i.push(c)}}let a=this.consume("RBRACE","Expected '}' to close domain").location;return{kind:"domain",name:o,annotations:e.length>0?e:void 0,types:r,members:i,location:h(n,a)}}parseTypeDecl(e=[]){let n=this.consume("TYPE","Expected 'type'").location,o=this.consume("IDENTIFIER","Expected type name").lexeme;this.consume("EQ","Expected '=' after type name");let r=this.parseTypeExpr();return{kind:"typeDecl",name:o,annotations:e.length>0?e:void 0,typeExpr:r,location:h(n,r.location)}}parseDomainMember(e=[]){return this.check("STATE")?(this.reportUnsupportedAnnotations(e),this.parseState()):this.check("COMPUTED")?this.parseComputed(e):this.check("ACTION")?this.parseAction(e):this.isFlowDeclContext()?(this.reportUnsupportedAnnotations(e),this.parseFlowDecl()):(this.reportUnsupportedAnnotations(e),this.error(`Unexpected token '${this.peek().lexeme}'. Expected 'state', 'computed', 'action', or 'flow'.`),this.advance(),null)}parseState(){let e=this.consume("STATE","Expected 'state'").location;this.consume("LBRACE","Expected '{' after 'state'");let n=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let r=this.parseAnnotationList();if(r.length>0&&(this.check("RBRACE")||this.isAtEnd())){this.reportUnsupportedAnnotations(r);continue}n.push(this.parseStateField(r))}let o=this.consume("RBRACE","Expected '}' to close state block").location;return{kind:"state",fields:n,location:h(e,o)}}parseStateField(e=[]){let n=this.consume("IDENTIFIER","Expected field name");this.consume("COLON","Expected ':' after field name");let o=this.parseTypeExpr(),r;return this.match("EQ")&&(r=this.parseExpression()),{kind:"stateField",name:n.lexeme,annotations:e.length>0?e:void 0,typeExpr:o,initializer:r,location:h(n.location,r?.location??o.location)}}parseComputed(e=[]){let n=this.consume("COMPUTED","Expected 'computed'").location,o=this.consume("IDENTIFIER","Expected computed name").lexeme;this.consume("EQ","Expected '=' after computed name");let r=this.parseExpression();return{kind:"computed",name:o,annotations:e.length>0?e:void 0,expression:r,location:h(n,r.location)}}parseAction(e=[]){let n=this.consume("ACTION","Expected 'action'").location,o=this.consume("IDENTIFIER","Expected action name").lexeme;this.consume("LPAREN","Expected '(' after action name");let r=[];if(!this.check("RPAREN"))do{let d=this.parseAnnotationList();if(d.length>0&&(this.check("RPAREN")||this.isAtEnd())){this.reportUnsupportedAnnotations(d);break}r.push(this.parseParam(d))}while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after parameters");let i;this.match("AVAILABLE")&&(this.consume("WHEN","Expected 'when' after 'available'"),i=this.parseExpression());let a;if(this.match("DISPATCHABLE")&&(this.consume("WHEN","Expected 'when' after 'dispatchable'"),a=this.parseExpression()),this.check("AVAILABLE")){let d=a?"'available when' must appear before 'dispatchable when' in an action":"Action can declare 'available when' at most once";throw this.errorAtCurrent(d)}if(this.check("DISPATCHABLE"))throw this.errorAtCurrent("Action can declare 'dispatchable when' at most once");this.consume("LBRACE","Expected '{' to start action body");let s=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let d=this.parseGuardedStmt();d&&s.push(d)}let c=this.consume("RBRACE","Expected '}' to close action").location;return{kind:"action",name:o,annotations:e.length>0?e:void 0,params:r,available:i,dispatchable:a,body:s,location:h(n,c)}}parseFlowDecl(){let e=this.consume("IDENTIFIER","Expected 'flow'"),n=this.consume("IDENTIFIER","Expected flow name").lexeme;this.consume("LPAREN","Expected '(' after flow name");let o=[];if(!this.check("RPAREN"))do{let a=this.parseAnnotationList();if(this.reportUnsupportedAnnotations(a),a.length>0&&(this.check("RPAREN")||this.isAtEnd()))break;o.push(this.parseParam(a))}while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after parameters"),this.consume("LBRACE","Expected '{' to start flow body");let r=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let a=this.parseFlowStmt();a&&r.push(a)}let i=this.consume("RBRACE","Expected '}' to close flow").location;return{kind:"flow",name:n,params:o,body:r,location:h(e.location,i)}}parseParam(e=[]){let n=this.consume("IDENTIFIER","Expected parameter name");this.consume("COLON","Expected ':' after parameter name");let o=this.parseTypeExpr();return{kind:"param",name:n.lexeme,annotations:e.length>0?e:void 0,typeExpr:o,location:h(n.location,o.location)}}parseGuardedStmt(){let e=this.parseAnnotationList();if(this.reportUnsupportedAnnotations(e),this.check("WHEN"))return this.parseWhenStmt();if(this.check("ONCE"))return this.parseOnceStmt();if(this.isOnceIntentContext())return this.parseOnceIntentStmt();if(this.isIncludeContext())return this.parseIncludeStmt();if(this.check("FAIL"))return this.parseFailStmt();if(this.check("STOP"))return this.parseStopStmt();let n=this.peek();return n.kind==="PATCH"||n.lexeme==="patch"||n.kind==="EFFECT"||n.lexeme==="effect"?(this.error(`'${n.lexeme}' must be inside a guard block (when, once, or onceIntent). Wrap it: when true { ${n.lexeme} ... }`),this.skipToRecoveryPoint(),null):(this.error(`Unexpected token '${n.lexeme}'. Expected 'when', 'once', 'onceIntent', 'include', 'fail', or 'stop'.`),this.advance(),null)}parseFlowStmt(){let e=this.parseAnnotationList();return this.reportUnsupportedAnnotations(e),this.check("WHEN")?this.parseWhenStmt():this.isIncludeContext()?this.parseIncludeStmt():this.check("ONCE")?this.parseOnceStmt():this.isOnceIntentContext()?this.parseOnceIntentStmt():this.check("PATCH")?this.parsePatchStmt():this.check("EFFECT")?this.parseEffectStmt():(this.error(`Unexpected token '${this.peek().lexeme}'. Expected 'when', 'include', 'once', 'onceIntent', 'patch', or 'effect'.`),this.advance(),null)}skipToRecoveryPoint(){let e=0;for(;!this.isAtEnd();){let n=this.peek();if(n.kind==="LBRACE"){e++,this.advance();continue}if(n.kind==="RBRACE"){if(e===0)return;e--,this.advance();continue}if(e===0&&(n.kind==="WHEN"||n.kind==="ONCE"||n.lexeme==="onceIntent"||this.isIncludeContext()||n.kind==="FAIL"||n.kind==="STOP"))return;this.advance()}}parseWhenStmt(){let e=this.consume("WHEN","Expected 'when'").location,n=this.parseExpression();this.consume("LBRACE","Expected '{' after when condition");let o=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let i=this.parseInnerStmt();i&&o.push(i)}let r=this.consume("RBRACE","Expected '}' to close when block").location;return{kind:"when",condition:n,body:o,location:h(e,r)}}parseOnceStmt(){let e=this.consume("ONCE","Expected 'once'").location;this.consume("LPAREN","Expected '(' after 'once'");let n=this.parsePath();this.consume("RPAREN","Expected ')' after marker");let o;this.match("WHEN")&&(o=this.parseExpression()),this.consume("LBRACE","Expected '{' to start once block");let r=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let a=this.parseInnerStmt();a&&r.push(a)}let i=this.consume("RBRACE","Expected '}' to close once block").location;return{kind:"once",marker:n,condition:o,body:r,location:h(e,i)}}parseOnceIntentStmt(){let e=this.consume("IDENTIFIER","Expected 'onceIntent'"),n;this.match("WHEN")&&(n=this.parseExpression()),this.consume("LBRACE","Expected '{' to start onceIntent block");let o=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let i=this.parseInnerStmt();i&&o.push(i)}let r=this.consume("RBRACE","Expected '}' to close onceIntent block").location;return{kind:"onceIntent",condition:n,body:o,location:h(e.location,r)}}parseInnerStmt(){let e=this.parseAnnotationList();return this.reportUnsupportedAnnotations(e),this.check("PATCH")?this.parsePatchStmt():this.check("EFFECT")?this.parseEffectStmt():this.check("WHEN")?this.parseWhenStmt():this.check("ONCE")?this.parseOnceStmt():this.isOnceIntentContext()?this.parseOnceIntentStmt():this.isIncludeContext()?this.parseIncludeStmt():this.check("FAIL")?this.parseFailStmt():this.check("STOP")?this.parseStopStmt():(this.error(`Unexpected token '${this.peek().lexeme}'. Expected 'patch', 'effect', 'when', 'once', 'onceIntent', 'include', 'fail', or 'stop'.`),this.advance(),null)}parseIncludeStmt(){let e=this.consume("IDENTIFIER","Expected 'include'"),n=this.consume("IDENTIFIER","Expected flow name after 'include'");this.consume("LPAREN","Expected '(' after flow name");let o=[];if(!this.check("RPAREN"))do o.push(this.parseExpression());while(this.match("COMMA"));let r=this.consume("RPAREN","Expected ')' after include arguments").location;return{kind:"include",flowName:n.lexeme,args:o,location:h(e.location,r)}}parsePatchStmt(){let e=this.consume("PATCH","Expected 'patch'").location,n=this.parsePath(),o,r,i;return this.match("UNSET")?(o="unset",i=this.previous().location):this.match("MERGE")?(o="merge",r=this.parseExpression(),i=r.location):(this.consume("EQ","Expected '=', 'unset', or 'merge' after path"),o="set",r=this.parseExpression(),i=r.location),{kind:"patch",path:n,op:o,value:r,location:h(e,i)}}parseEffectStmt(){let e=this.consume("EFFECT","Expected 'effect'").location,n=this.consume("IDENTIFIER","Expected effect type").lexeme;for(;this.match("DOT");)n+="."+this.consume("IDENTIFIER","Expected identifier after '.'").lexeme;this.consume("LPAREN","Expected '(' after effect type"),this.consume("LBRACE","Expected '{' for effect arguments");let o=[];for(;!this.check("RBRACE")&&!this.isAtEnd();)o.push(this.parseEffectArg()),this.match("COMMA");this.consume("RBRACE","Expected '}' after effect arguments");let r=this.consume("RPAREN","Expected ')' to close effect").location;return{kind:"effect",effectType:n,args:o,location:h(e,r)}}parseEffectArg(){let e=this.match("IDENTIFIER","FAIL")?this.previous():this.consume("IDENTIFIER","Expected argument name");this.consume("COLON","Expected ':' after argument name");let n=["into","pass","fail"].includes(e.lexeme),o=n?this.parsePath():this.parseExpression();return{kind:"effectArg",name:e.lexeme,value:o,isPath:n,location:h(e.location,o.location)}}parseFailStmt(){let e=this.consume("FAIL","Expected 'fail'").location,n=this.consume("STRING","Expected error code string after 'fail'"),o=n.value,r,i=n.location;return this.match("WITH")&&(r=this.parseExpression(),i=r.location),{kind:"fail",code:o,message:r,location:h(e,i)}}parseStopStmt(){let e=this.consume("STOP","Expected 'stop'").location,n=this.consume("STRING","Expected reason string after 'stop'");return{kind:"stop",reason:n.value,location:h(e,n.location)}}parseTypeExpr(){let e=this.parseBaseType();if(this.check("PIPE")){let n=[e];for(;this.match("PIPE");)n.push(this.parseBaseType());e={kind:"unionType",types:n,location:h(n[0].location,n[n.length-1].location)}}return e}parseBaseType(){if(this.check("LBRACE"))return this.parseObjectType();if(this.check("STRING")){let n=this.advance();return{kind:"literalType",value:n.value,location:n.location}}if(this.check("NUMBER")){let n=this.advance();return{kind:"literalType",value:n.value,location:n.location}}if(this.check("TRUE")||this.check("FALSE")){let n=this.advance();return{kind:"literalType",value:n.kind==="TRUE",location:n.location}}if(this.check("NULL"))return{kind:"literalType",value:null,location:this.advance().location};let e=this.consume("IDENTIFIER","Expected type name");if(this.match("LT"))if(e.lexeme==="Array"){let n=this.parseTypeExpr(),o=this.consume("GT","Expected '>' after array element type").location;return{kind:"arrayType",elementType:n,location:h(e.location,o)}}else if(e.lexeme==="Record"){let n=this.parseTypeExpr();this.consume("COMMA","Expected ',' between Record type parameters");let o=this.parseTypeExpr(),r=this.consume("GT","Expected '>' after Record value type").location;return{kind:"recordType",keyType:n,valueType:o,location:h(e.location,r)}}else{for(this.error(`Unknown generic type '${e.lexeme}'`);!this.check("GT")&&!this.isAtEnd();)this.advance();this.match("GT")}return{kind:"simpleType",name:e.lexeme,location:e.location}}parseObjectType(){let e=this.consume("LBRACE","Expected '{'").location,n=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let r=this.parseAnnotationList();if(r.length>0&&(this.check("RBRACE")||this.isAtEnd())){this.reportUnsupportedAnnotations(r);continue}let i=this.consume("IDENTIFIER","Expected field name"),a=this.match("QUESTION");this.consume("COLON","Expected ':' after field name");let s=this.parseTypeExpr();n.push({kind:"typeField",name:i.lexeme,annotations:r.length>0?r:void 0,typeExpr:s,optional:a,location:h(i.location,s.location)}),this.match("COMMA")}let o=this.consume("RBRACE","Expected '}' to close object type").location;return{kind:"objectType",fields:n,location:h(e,o)}}parseExpression(e=0){let n=this.parsePrimary();for(;;){let o=Ye(this.peek().kind);if(o<=e)break;if(this.peek().kind==="QUESTION"){n=this.parseTernary(n);continue}let r=It(this.peek().kind);if(!r)break;this.advance();let i=Pt(this.previous().kind)?o-1:o,a=this.parseExpression(i);n={kind:"binary",operator:r,left:n,right:a,location:h(n.location,a.location)}}return n}parseTernary(e){this.consume("QUESTION","Expected '?'");let n=this.parseExpression();this.consume("COLON","Expected ':' in ternary expression");let o=this.parseExpression(0);return{kind:"ternary",condition:e,consequent:n,alternate:o,location:h(e.location,o.location)}}parsePrimary(){if(this.check("BANG")||this.check("MINUS")&&this.isUnaryContext()){let e=this.advance(),n=this.parsePrimary();return{kind:"unary",operator:e.kind==="BANG"?"!":"-",operand:n,location:h(e.location,n.location)}}if(this.match("LPAREN")){let e=this.parseExpression();return this.consume("RPAREN","Expected ')' after expression"),e}if(this.check("LBRACE"))return this.parseObjectLiteral();if(this.check("LBRACKET"))return this.parseArrayLiteral();if(this.check("NUMBER")){let e=this.advance();return{kind:"literal",value:e.value,literalType:"number",location:e.location}}if(this.check("STRING")){let e=this.advance();return{kind:"literal",value:e.value,literalType:"string",location:e.location}}if(this.check("TRUE")||this.check("FALSE")){let e=this.advance();return{kind:"literal",value:e.kind==="TRUE",literalType:"boolean",location:e.location}}if(this.check("NULL"))return{kind:"literal",value:null,literalType:"null",location:this.advance().location};if(this.check("SYSTEM_IDENT")){let e=this.advance(),n=e.lexeme.slice(1).split(".");return this.parsePostfix({kind:"systemIdent",path:n,location:e.location})}if(this.check("ITEM")){let e=this.advance();return this.parsePostfix({kind:"iterationVar",name:"item",location:e.location})}if(this.check("MERGE")&&this.peekNext()?.kind==="LPAREN"){let e=this.advance();return this.parseFunctionCall(e)}if(this.check("IDENTIFIER")){let e=this.advance();return this.check("LPAREN")?this.parseFunctionCall(e):this.parsePostfix({kind:"identifier",name:e.lexeme,location:e.location})}return this.error(`Unexpected token '${this.peek().lexeme}'`),{kind:"literal",value:null,literalType:"null",location:this.peek().location}}parseFunctionCall(e){this.consume("LPAREN","Expected '(' for function call");let n=[];if(!this.check("RPAREN"))do n.push(this.parseExpression());while(this.match("COMMA"));let o=this.consume("RPAREN","Expected ')' after arguments").location;return this.parsePostfix({kind:"functionCall",name:e.lexeme,args:n,location:h(e.location,o)})}parsePostfix(e){for(;;)if(this.match("DOT")){let n=this.consume("IDENTIFIER","Expected property name after '.'");e={kind:"propertyAccess",object:e,property:n.lexeme,location:h(e.location,n.location)}}else if(this.match("LBRACKET")){let n=this.parseExpression(),o=this.consume("RBRACKET","Expected ']' after index").location;e={kind:"indexAccess",object:e,index:n,location:h(e.location,o)}}else break;return e}parseObjectLiteral(){let e=this.consume("LBRACE","Expected '{'").location,n=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let r=this.consume("IDENTIFIER","Expected property name");this.consume("COLON","Expected ':' after property name");let i=this.parseExpression();n.push({kind:"objectProperty",key:r.lexeme,value:i,location:h(r.location,i.location)}),this.check("RBRACE")||this.consume("COMMA","Expected ',' between properties")}let o=this.consume("RBRACE","Expected '}' to close object").location;return{kind:"objectLiteral",properties:n,location:h(e,o)}}parseArrayLiteral(){let e=this.consume("LBRACKET","Expected '['").location,n=[];for(;!this.check("RBRACKET")&&!this.isAtEnd();)n.push(this.parseExpression()),this.check("RBRACKET")||this.consume("COMMA","Expected ',' between elements");let o=this.consume("RBRACKET","Expected ']' to close array").location;return{kind:"arrayLiteral",elements:n,location:h(e,o)}}parsePath(){let e=[],n=this.peek().location,o=this.consume("IDENTIFIER","Expected identifier");for(e.push({kind:"propertySegment",name:o.lexeme,location:o.location});;)if(this.match("DOT")){let i=this.consume("IDENTIFIER","Expected property name");e.push({kind:"propertySegment",name:i.lexeme,location:i.location})}else if(this.match("LBRACKET")){let i=this.parseExpression(),a=this.consume("RBRACKET","Expected ']'").location;e.push({kind:"indexSegment",index:i,location:h(i.location,a)})}else break;let r=e[e.length-1];return{kind:"path",segments:e,location:h(n,r.location)}}isUnaryContext(){if(this.current===0)return!0;let e=this.previous();return["LPAREN","LBRACKET","LBRACE","COMMA","COLON","EQ","PLUS","MINUS","STAR","SLASH","PERCENT","AT","EQ_EQ","BANG_EQ","LT","LT_EQ","GT","GT_EQ","AMP_AMP","PIPE_PIPE","BANG","QUESTION","QUESTION_QUESTION"].includes(e.kind)}peek(){return this.tokens[this.current]}peekNext(){return this.peekAt(1)}peekAt(e){return this.current+e>=this.tokens.length?this.tokens[this.tokens.length-1]:this.tokens[this.current+e]}previous(){return this.tokens[this.current-1]}isAtEnd(){return this.peek().kind==="EOF"}advance(){return this.isAtEnd()||this.current++,this.previous()}check(e){return this.isAtEnd()?!1:this.peek().kind===e}isOnceIntentContext(){if(!this.check("IDENTIFIER")||this.peek().lexeme!=="onceIntent")return!1;let n=this.peekNext();return n.kind==="LBRACE"||n.kind==="WHEN"}isFlowDeclContext(){return!this.check("IDENTIFIER")||this.peek().lexeme!=="flow"?!1:this.peekNext().kind==="IDENTIFIER"&&this.peekAt(2).kind==="LPAREN"}isIncludeContext(){return!this.check("IDENTIFIER")||this.peek().lexeme!=="include"?!1:this.peekNext().kind==="IDENTIFIER"&&this.peekAt(2).kind==="LPAREN"}match(...e){for(let n of e)if(this.check(n))return this.advance(),!0;return!1}consume(e,n){if(this.check(e))return this.advance();throw this.errorAtCurrent(n)}parseAnnotationList(){let e=[];for(;this.check("AT");)e.push(this.parseAnnotation());return e}parseAnnotation(){let e=this.consume("AT","Expected '@'").location,n=this.consume("IDENTIFIER","Expected annotation name after '@'");if(n.lexeme!=="meta")throw this.errorAtToken(n,"Expected 'meta' after '@'");this.consume("LPAREN","Expected '(' after '@meta'");let o=this.consume("STRING","Expected string tag as first @meta argument"),r;this.match("COMMA")&&(r=this.parseExpression());let i=this.consume("RPAREN","Expected ')' after @meta arguments").location;return{kind:"annotation",tag:o.value,payload:r,location:h(e,i)}}reportUnsupportedAnnotations(e){for(let n of e)this.diagnostics.push({severity:"error",code:"E053",message:"@meta can attach only to domain, type, type field, state field, computed, or action declarations.",location:n.location})}error(e){this.diagnostics.push({severity:"error",code:"MEL_PARSER",message:e,location:this.previous().location})}errorAtCurrent(e){return this.diagnostics.push({severity:"error",code:"MEL_PARSER",message:e,location:this.peek().location}),new Error(e)}errorAtToken(e,n){return this.diagnostics.push({severity:"error",code:"MEL_PARSER",message:n,location:e.location}),new Error(n)}};function Se(t){return new Qe(t).parse()}var xe=class{parent;symbols=new Map;kind;constructor(e,n=null){this.kind=e,this.parent=n}define(e){this.symbols.set(e.name,e)}lookup(e){let n=this.symbols.get(e);return n||this.parent?.lookup(e)}isDefined(e){return this.symbols.has(e)}},Xe=class{diagnostics=[];scopes=new Map;currentScope=null;domainScope=null;analyze(e){return this.diagnostics=[],this.scopes=new Map,this.currentScope=null,this.domainScope=null,this.analyzeDomain(e.domain),{scopes:this.scopes,diagnostics:this.diagnostics}}analyzeDomain(e){let n=new xe("domain");this.domainScope=n,this.currentScope=n,this.scopes.set("domain",n);for(let o of e.members)if(o.kind==="state")for(let r of o.fields)this.defineSymbol({name:r.name,kind:"state",location:r.location});else o.kind==="computed"?this.defineSymbol({name:o.name,kind:"computed",location:o.location}):o.kind==="action"?this.defineSymbol({name:o.name,kind:"action",location:o.location}):o.kind;for(let o of e.members)o.kind==="computed"?this.analyzeComputedExpr(o):o.kind==="action"&&this.analyzeAction(o)}analyzeComputedExpr(e){this.analyzeExpr(e.expression,"computed")}analyzeAction(e){let n=new xe("action",this.domainScope);this.currentScope=n,this.scopes.set(`action.${e.name}`,n);for(let o of e.params)n.define({name:o.name,kind:"param",location:o.location});for(let o of e.body)this.analyzeStmt(o);this.currentScope=this.domainScope}analyzeStmt(e){switch(e.kind){case"when":this.analyzeExpr(e.condition,"action");for(let n of e.body)this.analyzeStmt(n);break;case"onceIntent":e.condition&&this.analyzeExpr(e.condition,"action");for(let n of e.body)this.analyzeStmt(n);break;case"once":this.validatePath(e.marker),e.condition&&this.analyzeExpr(e.condition,"action");for(let n of e.body)this.analyzeStmt(n);break;case"patch":this.validatePath(e.path),e.value&&this.analyzeExpr(e.value,"action");break;case"effect":for(let n of e.args)n.isPath?this.validatePath(n.value):this.analyzeExpr(n.value,"action");break;case"include":case"fail":case"stop":break}}analyzeExpr(e,n){switch(e.kind){case"identifier":this.checkIdentifier(e.name,e.location,n);break;case"systemIdent":this.checkSystemIdent(e.path,e.location,n);break;case"propertyAccess":this.analyzeExpr(e.object,n);break;case"indexAccess":this.analyzeExpr(e.object,n),this.analyzeExpr(e.index,n);break;case"functionCall":for(let o of e.args)this.analyzeExpr(o,n);break;case"binary":this.analyzeExpr(e.left,n),this.analyzeExpr(e.right,n);break;case"unary":this.analyzeExpr(e.operand,n);break;case"ternary":this.analyzeExpr(e.condition,n),this.analyzeExpr(e.consequent,n),this.analyzeExpr(e.alternate,n);break;case"objectLiteral":for(let o of e.properties)this.analyzeExpr(o.value,n);break;case"arrayLiteral":for(let o of e.elements)this.analyzeExpr(o,n);break;case"iterationVar":break;case"literal":break}}checkIdentifier(e,n,o){let r=this.currentScope?.lookup(e);if(!r){this.error(`Undefined identifier '${e}'`,n,"E_UNDEFINED");return}o==="computed"&&r.kind==="param"&&this.error(`Cannot access parameter '${e}' in computed expression`,n,"E_INVALID_ACCESS")}checkSystemIdent(e,n,o){let[r,...i]=e;if(r==="system"&&o==="computed"&&this.error("Cannot use $system.* in computed expressions (non-deterministic)",n,"E001"),r==="system"){let a=["uuid","timestamp","time.now","random"],s=i.join(".");s&&!a.includes(s)&&this.error(`Invalid system value '$system.${s}'. Valid values: ${a.join(", ")}`,n,"E003")}if(r==="meta"){let a=["intentId","actionName","timestamp"],s=i.join(".");s&&!a.includes(s)&&this.error(`Invalid meta value '$meta.${s}'. Valid values: ${a.join(", ")}`,n,"E003")}}validatePath(e){if(!e||!e.segments)return;let n=e.segments[0];n?.kind==="propertySegment"&&(this.currentScope?.lookup(n.name)||this.error(`Undefined identifier '${n.name}' in path`,e.location,"E_UNDEFINED"))}defineSymbol(e){if(this.currentScope){if(this.currentScope.isDefined(e.name)){this.error(`Duplicate identifier '${e.name}'`,e.location,"E_DUPLICATE");return}this.currentScope.define(e)}}error(e,n,o){this.diagnostics.push({severity:"error",code:o,message:e,location:n})}};function Mt(t){return new Xe().analyze(t)}function O(t,e,n,o){return{severity:"error",code:t,message:e,location:n,...o}}function Dt(t,e,n,o){return{severity:"warning",code:t,message:e,location:n,...o}}function ki(t,e,n){return{severity:"info",code:t,message:e,location:n}}function In(t){return t.severity==="error"}function Ni(t){return t.some(In)}function Ti(t,e){return t.filter(n=>n.severity===e)}var Rt=new Set(["eq","neq","gt","gte","lt","lte","and","or","not","isNull","isNotNull","hasKey","startsWith","endsWith","strIncludes","includes","every","some","existsById"]),Lt=new Set(["add","sub","mul","div","mod","absDiff","abs","clamp","floor","ceil","round","sqrt","pow","len","strlen","indexOf","streak","sum","min","max","toNumber"]),Ot=new Set(["trim","lower","upper","concat","typeof","toString","substring","substr","replace"]),Pn=new Set(["keys","values","entries","merge","filter","map","append","reverse","unique","flat","split","fromEntries"]),Mn=new Set(["updateById","removeById"]);function ve(t){let e=new Map,n=new Map,o=new Map;for(let r of t.types)o.set(r.name,r);for(let r of t.members){if(r.kind==="state"){for(let i of r.fields)e.set(i.name,i.typeExpr);continue}r.kind==="computed"&&n.set(r.name,r)}return{stateTypes:e,computedDecls:n,typeDefs:o,computedTypeCache:new Map,computedTypeInFlight:new Set}}function Ae(t){let e=new Map;for(let n of t)e.set(n.name,n.typeExpr);return e}function k(t,e,n){switch(t.kind){case"literal":return _n(t.value,t.location);case"identifier":return e.get(t.name)??n.stateTypes.get(t.name)??Dn(t.name,n);case"propertyAccess":return Y(k(t.object,e,n),t.property,n);case"indexAccess":return pe(k(t.object,e,n),n);case"objectLiteral":return{kind:"objectType",fields:t.properties.map(o=>{let r=k(o.value,e,n);return r?{kind:"typeField",name:o.key,typeExpr:r,optional:!1,location:o.location}:null}).filter(o=>o!==null),location:t.location};case"arrayLiteral":{let o=P(t.elements.map(r=>k(r,e,n)),t.location);return o?{kind:"arrayType",elementType:o,location:t.location}:null}case"unary":return Rn(t);case"binary":return Ln(t,e,n);case"ternary":return P([k(t.consequent,e,n),k(t.alternate,e,n)],t.location);case"functionCall":return On(t,e,n);case"systemIdent":return null;case"iterationVar":return e.get("$item")??null}}function $(t,e,n){let o=k(t,e,n);if(o)return Ft(o,n);switch(t.kind){case"literal":return"primitive";case"objectLiteral":case"arrayLiteral":return"nonprimitive";case"binary":return t.operator==="??"?de([$(t.left,e,n),$(t.right,e,n)]):t.operator==="=="||t.operator==="!="||t.operator==="+"||t.operator==="-"||t.operator==="*"||t.operator==="/"||t.operator==="%"||t.operator==="<"||t.operator==="<="||t.operator===">"||t.operator===">="||t.operator==="&&"||t.operator==="||"?"primitive":"unknown";case"unary":return"primitive";case"ternary":return de([$(t.consequent,e,n),$(t.alternate,e,n)]);case"functionCall":return Pn.has(t.name)?"nonprimitive":Rt.has(t.name)||Lt.has(t.name)||Ot.has(t.name)||t.name==="toBoolean"?"primitive":(t.name==="cond"||t.name==="if")&&t.args.length>=3?de([$(t.args[1],e,n),$(t.args[2],e,n)]):t.name==="coalesce"?de(t.args.map(r=>$(r,e,n))):"unknown";case"identifier":case"propertyAccess":case"indexAccess":case"systemIdent":case"iterationVar":return"unknown"}}function Ft(t,e){let n=M(t,e);if(!n)return"unknown";switch(n.kind){case"simpleType":return n.name==="object"?"nonprimitive":n.name==="string"||n.name==="number"||n.name==="boolean"||n.name==="null"?"primitive":"unknown";case"literalType":return"primitive";case"arrayType":case"recordType":case"objectType":return"nonprimitive";case"unionType":return de(n.types.map(o=>Ft(o,e)))}}function M(t,e,n=new Set){return t?t.kind==="simpleType"&&e.typeDefs.has(t.name)?n.has(t.name)?null:(n.add(t.name),M(e.typeDefs.get(t.name).typeExpr,e,n)):t:null}function Y(t,e,n){let o=M(t,n);if(!o)return null;if(o.kind==="objectType")return o.fields.find(i=>i.name===e)?.typeExpr??null;if(o.kind==="unionType"){let r=o.types.filter(i=>!Z(i)).map(i=>Y(i,e,n)).filter(i=>i!==null);return P(r,o.location)}return null}function pe(t,e){let n=M(t,e);if(!n)return null;if(n.kind==="arrayType")return n.elementType;if(n.kind==="recordType")return n.valueType;if(n.kind==="unionType"){let o=n.types.filter(r=>!Z(r)).map(r=>pe(r,e)).filter(r=>r!==null);return P(o,n.location)}return null}function G(t,e){let n=M(t,e);if(!n)return null;if(n.kind==="arrayType")return n.elementType;if(n.kind==="unionType"){let o=n.types.filter(r=>!Z(r)).map(r=>G(r,e)).filter(r=>r!==null);return P(o,n.location)}return null}function we(t,e){let n=M(t,e);if(!n)return!1;switch(n.kind){case"simpleType":return n.name==="string"||n.name==="number";case"literalType":return typeof n.value=="string"||typeof n.value=="number";case"unionType":return n.types.length>0&&n.types.every(o=>we(o,e));default:return!1}}function Z(t){return t.kind==="simpleType"&&t.name==="null"||t.kind==="literalType"&&t.value===null}function Dn(t,e){if(e.computedTypeCache.has(t))return e.computedTypeCache.get(t)??null;let n=e.computedDecls.get(t);if(!n||e.computedTypeInFlight.has(t))return null;e.computedTypeInFlight.add(t);let o=k(n.expression,new Map,e);return e.computedTypeInFlight.delete(t),e.computedTypeCache.set(t,o),o}function Rn(t){return t.operator==="!"?C("boolean",t.location):C("number",t.location)}function Ln(t,e,n){switch(t.operator){case"==":case"!=":case"<":case"<=":case">":case">=":case"&&":case"||":return C("boolean",t.location);case"+":case"-":case"*":case"/":case"%":return C("number",t.location);case"??":return P([k(t.left,e,n),k(t.right,e,n)],t.location)}}function On(t,e,n){if(Rt.has(t.name))return C("boolean",t.location);if(Lt.has(t.name))return C("number",t.location);if(t.name==="idiv")return P([C("number",t.location),C("null",t.location)],t.location);if(Ot.has(t.name))return C("string",t.location);if(t.name==="toBoolean")return C("boolean",t.location);if(t.name==="findById"&&t.args.length>=1){let o=G(k(t.args[0],e,n),n);return o?P([o,C("null",t.location)],t.location):null}if(t.name==="find"&&t.args.length>=1){let o=G(k(t.args[0],e,n),n);return o?P([o,C("null",t.location)],t.location):null}if(t.name==="filter"&&t.args.length>=1)return k(t.args[0],e,n);if(t.name==="map"&&t.args.length>=2){let o=k(t.args[0],e,n),r=G(o,n);if(!r)return null;let i=k(t.args[1],Gn(e,r),n);return i?{kind:"arrayType",elementType:i,location:t.location}:null}if((t.name==="first"||t.name==="last")&&t.args.length>=1)return G(k(t.args[0],e,n),n);if(t.name==="at"&&t.args.length>=1)return pe(k(t.args[0],e,n),n);if(t.name==="field"&&t.args.length>=2){let o=$n(t.args[1]);return o?Y(k(t.args[0],e,n),o,n):null}return Mn.has(t.name)&&t.args.length>=1?k(t.args[0],e,n):(t.name==="cond"||t.name==="if")&&t.args.length>=3?P([k(t.args[1],e,n),k(t.args[2],e,n)],t.location):t.name==="coalesce"?P(t.args.map(o=>k(o,e,n)),t.location):t.name==="match"?Fn(t,e,n):t.name==="argmax"||t.name==="argmin"?jn(t,e,n):t.name==="slice"&&t.args.length>=1?k(t.args[0],e,n):t.name==="split"?{kind:"arrayType",elementType:C("string",t.location),location:t.location}:t.name==="keys"?{kind:"arrayType",elementType:C("string",t.location),location:t.location}:null}function de(t){let e=!1;for(let n of t){if(n==="nonprimitive")return"nonprimitive";n==="unknown"&&(e=!0)}return e?"unknown":"primitive"}function P(t,e){let n=t.filter(i=>i!==null);if(n.length===0)return null;if(n.length===1)return n[0];let o=[],r=new Set;for(let i of n){let a=JSON.stringify(i);r.has(a)||(r.add(a),o.push(i))}return o.length===1?o[0]:{kind:"unionType",types:o,location:e}}function Fn(t,e,n){if(t.args.length<3)return null;let o=[];for(let r=1;r<t.args.length-1;r+=1){let i=t.args[r];if(i.kind!=="arrayLiteral"||i.elements.length!==2)return null;o.push(k(i.elements[1],e,n))}return o.push(k(t.args[t.args.length-1],e,n)),P(o,t.location)}function jn(t,e,n){if(t.args.length<2)return null;let o=[];for(let i=0;i<t.args.length-1;i+=1){let a=t.args[i];if(a.kind!=="arrayLiteral"||a.elements.length!==3)return null;o.push(k(a.elements[0],e,n))}let r=P(o,t.location);return r?P([r,C("null",t.location)],t.location):null}function _n(t,e){return{kind:"literalType",value:t,location:e}}function C(t,e){return{kind:"simpleType",name:t,location:e}}function $n(t){return t.kind==="literal"&&typeof t.value=="string"?t.value:null}function Gn(t,e){let n=new Map(t);return n.set("$item",e),n}var Un=new Set(["findById","existsById"]),Ze=new Set(["updateById","removeById"]),Bn=new Set([...Un,...Ze]);function z(t,e,n,o,r){let i=`${n}:${r.start.offset}:${r.end.offset}:${o}`;e.has(i)||(e.add(i),t.push(O(n,o,r)))}function jt(t){let e=[],n=new Set,o=ve(t.domain);Hn(t.domain,o,e,n);for(let r of t.domain.members)switch(r.kind){case"computed":b(r.expression,"computed",new Map,o,e,n,0);break;case"action":{let i=Ae(r.params);qn(r,i,o,e,n);break}case"state":case"flow":break}return e}function qn(t,e,n,o,r){t.available&&b(t.available,"available",e,n,o,r,0),t.dispatchable&&b(t.dispatchable,"dispatchable",e,n,o,r,0);for(let i of t.body)zn(i,e,n,o,r)}function zn(t,e,n,o,r){switch(t.kind){case"when":b(t.condition,"guard",e,n,o,r,0);for(let i of t.body)ee(i,e,n,o,r);break;case"once":t.condition&&b(t.condition,"guard",e,n,o,r,0);for(let i of t.body)ee(i,e,n,o,r);break;case"onceIntent":t.condition&&b(t.condition,"guard",e,n,o,r,0);for(let i of t.body)ee(i,e,n,o,r);break;case"include":break}}function ee(t,e,n,o,r){switch(t.kind){case"when":b(t.condition,"guard",e,n,o,r,0);for(let i of t.body)ee(i,e,n,o,r);break;case"once":t.condition&&b(t.condition,"guard",e,n,o,r,0);for(let i of t.body)ee(i,e,n,o,r);break;case"onceIntent":t.condition&&b(t.condition,"guard",e,n,o,r,0);for(let i of t.body)ee(i,e,n,o,r);break;case"patch":t.value&&b(t.value,"patch",e,n,o,r,0);break;case"effect":for(let i of t.args)i.isPath||b(i.value,"action",e,n,o,r,0);break;case"fail":t.message&&b(t.message,"action",e,n,o,r,0);break;case"include":case"stop":break}}function b(t,e,n,o,r,i,a){switch(t.kind){case"functionCall":{Vn(t,e,n,o,r,i,a);let s=a+(Ze.has(t.name)?1:0);for(let c of t.args)b(c,e,n,o,r,i,s);break}case"binary":b(t.left,e,n,o,r,i,a),b(t.right,e,n,o,r,i,a);break;case"unary":b(t.operand,e,n,o,r,i,a);break;case"ternary":b(t.condition,e,n,o,r,i,a),b(t.consequent,e,n,o,r,i,a),b(t.alternate,e,n,o,r,i,a);break;case"propertyAccess":b(t.object,e,n,o,r,i,a);break;case"indexAccess":b(t.object,e,n,o,r,i,a),b(t.index,e,n,o,r,i,a);break;case"objectLiteral":for(let s of t.properties)b(s.value,e,n,o,r,i,a);break;case"arrayLiteral":for(let s of t.elements)b(s,e,n,o,r,i,a);break;case"literal":case"identifier":case"systemIdent":case"iterationVar":break}}function Vn(t,e,n,o,r,i,a){if(!Bn.has(t.name)||t.args.length===0)return;Ze.has(t.name)&&(e==="available"?z(r,i,"E035","updateById/removeById are not allowed in available conditions.",t.location):e==="dispatchable"?z(r,i,"E048","updateById/removeById are not allowed in dispatchable conditions.",t.location):e==="guard"?z(r,i,"E034","updateById/removeById are not allowed in guard conditions.",t.location):e!=="patch"&&z(r,i,"E031","updateById/removeById are only allowed in patch RHS.",t.location),a>0&&z(r,i,"E032","Nested transform primitives are not allowed.",t.location),e==="patch"&&!Je(t.args[0],o)&&z(r,i,"E033","Transform primitive collection argument must resolve to a state path.",t.args[0].location));let s=Wn(t.args[0],n,o);if(!s)return;let c=_t(s,o);if(!c){z(r,i,"E030","Collection element type must declare an 'id' field for entity primitives.",t.args[0].location);return}we(c,o)||z(r,i,"E030a","Entity 'id' field must be string or number.",t.args[0].location)}function Hn(t,e,n,o){for(let r of t.members)if(r.kind==="state")for(let i of r.fields)Kn(i,e,n,o)}function Kn(t,e,n,o){if(!t.initializer||t.initializer.kind!=="arrayLiteral")return;let r=G(t.typeExpr,e);if(!r)return;let i=_t(r,e);if(!i||!we(i,e))return;let a=new Map;for(let s of t.initializer.elements){if(s.kind!=="objectLiteral")continue;let c=s.properties.find(p=>p.key==="id");if(!c||c.value.kind!=="literal"||typeof c.value.value!="string"&&typeof c.value.value!="number")continue;let d=`${typeof c.value.value}:${String(c.value.value)}`;if(a.get(d)){z(n,o,"E030b","Duplicate '.id' values detected in state initializer.",c.value.location);continue}a.set(d,c.value.location)}}function Wn(t,e,n){return G(k(t,e,n),n)}function _t(t,e){return Y(t,"id",e)}function Je(t,e){switch(t.kind){case"identifier":return e.stateTypes.has(t.name);case"propertyAccess":return Je(t.object,e);case"indexAccess":return Je(t.object,e);default:return!1}}function $t(){return{inAction:!1,inGuard:!1,guardDepth:0,hasMarkerPatch:!1,currentActionParamTypes:new Map,diagnostics:[]}}var Yn=/\b(await(?:ing)?|wait(?:ing)?|pending)\b/i;function E(t,e){return{kind:"simpleType",name:t,location:e}}function V(t,e,n){let o=M(t,n),r=M(e,n);if(!o||!r)return null;if(r.kind==="unionType"){let i=o.kind==="unionType"?o.types:[o],a=!1;for(let s of i){let c=r.types.map(d=>V(s,d,n));if(!c.includes(!0)){if(c.every(d=>d===!1))return!1;a=!0}}return a?null:!0}if(o.kind==="unionType"){let i=!1;for(let a of o.types){let s=V(a,r,n);if(s===!1)return!1;s===null&&(i=!0)}return i?null:!0}if(r.kind==="simpleType"){if(o.kind==="simpleType")return o.name===r.name;if(o.kind==="literalType")return r.name==="null"?o.value===null:typeof o.value===r.name}if(r.kind==="literalType")return o.kind!=="literalType"?!1:o.value===r.value;if(r.kind==="arrayType")return o.kind!=="arrayType"?!1:V(o.elementType,r.elementType,n);if(r.kind==="objectType"){if(o.kind!=="objectType")return!1;for(let i of r.fields){let a=o.fields.find(c=>c.name===i.name);if(!a){if(i.optional)continue;return!1}let s=V(a.typeExpr,i.typeExpr,n);if(s!==!0)return s}return!0}return r.kind==="recordType"?o.kind!=="recordType"?null:V(o.valueType,r.valueType,n):null}function x(t,e){let n=M(t,e);if(!n)return"unknown";switch(n.kind){case"simpleType":return n.name;case"literalType":return JSON.stringify(n.value);case"arrayType":return`Array<${x(n.elementType,e)}>`;case"recordType":return`Record<${x(n.keyType,e)}, ${x(n.valueType,e)}>`;case"objectType":return`{ ${n.fields.map(o=>`${o.name}${o.optional?"?":""}: ${x(o.typeExpr,e)}`).join("; ")} }`;case"unionType":return n.types.map(o=>x(o,e)).join(" | ")}}function Ce(t,e){let n=M(t,e);if(!n)return null;switch(n.kind){case"simpleType":return n.name==="string"||n.name==="number"||n.name==="boolean"||n.name==="null"?new Set([n.name]):n.name==="object"?"nonprimitive":null;case"literalType":return new Set([n.value===null?"null":typeof n.value]);case"arrayType":case"recordType":case"objectType":return"nonprimitive";case"unionType":{let o=new Set;for(let r of n.types){let i=Ce(r,e);if(i===null)return null;if(i==="nonprimitive")return"nonprimitive";for(let a of i)o.add(a)}return o}}}function et(t,e){let n=Ce(t,e);if(n===null)return null;if(n==="nonprimitive")return"invalid";let o=[...n].filter(r=>r!=="null");return o.length!==1||n.has("null")?"invalid":o[0]}function Ut(t,e,n){let o=Ce(t,n),r=Ce(e,n);if(o===null||r===null)return null;if(o==="nonprimitive"||r==="nonprimitive")return!1;if(!(o instanceof Set)||!(r instanceof Set))return null;let i=[...o].filter(s=>s!=="null"),a=[...r].filter(s=>s!=="null");return i.length===0||a.length===0?!0:i.some(s=>a.includes(s))}function Qn(t,e){let n=M(t,e);if(!n||Z(n))return null;if(n.kind!=="unionType")return n;let o=n.types.filter(r=>!Z(r));return o.length===0?null:o.length===1?o[0]:{kind:"unionType",types:o,location:n.location}}function tt(t,e,n){if(!t||!e)return null;let o=V(t,e,n);if(o===!0)return!0;let r=V(e,t,n);if(r===!0)return!0;let i=Ut(t,e,n);return i!==null?i:o===!1&&r===!1?!1:null}function Bt(t,e){let n=M(t,e);if(!n)return null;if(n.kind==="unionType"){let o=n.types.map(r=>Bt(r,e));return o.every(r=>r===!0)?!0:o.some(r=>r===!1)?!1:null}return n.kind==="arrayType"}function qt(t,e){let n=M(t,e);if(!n)return null;if(n.kind==="unionType"){let o=n.types.map(r=>qt(r,e));return o.every(r=>r===!0)?!0:o.some(r=>r===!1)?!1:null}return n.kind==="arrayType"||n.kind==="recordType"||n.kind==="objectType"?!0:n.kind==="literalType"?typeof n.value=="string":n.kind==="simpleType"?n.name==="string"||n.name==="object":!1}function Xn(t,e){let n=new Map(t);return n.set("$item",e),n}function Gt(t){let e=Ie(t);if(typeof e=="number")return e;if(t.kind==="literal")return t.literalType==="null"?null:typeof t.value=="string"||typeof t.value=="number"||typeof t.value=="boolean"?t.value:void 0}function Ie(t){if(t.kind==="literal"&&t.literalType==="number"&&typeof t.value=="number")return t.value;if(t.kind==="unary"&&t.operator==="-"){let e=Ie(t.operand);return typeof e=="number"?-e:void 0}}function Jn(t,e){let[n,...o]=t.segments;if(!n||n.kind!=="propertySegment")return null;let r=e.stateTypes.get(n.name)??null;for(let i of o){if(!r)return null;r=i.kind==="propertySegment"?Y(r,i.name,e):pe(r,e)}return r}function Zn(t){let e="";for(let[n,o]of t.segments.entries()){if(o.kind==="propertySegment"){e+=n===0?o.name:`.${o.name}`;continue}o.index.kind==="literal"?e+=`[${JSON.stringify(o.index.value)}]`:e+="[*]"}return e}var nt=class{ctx=$t();symbols=null;validate(e){return this.ctx=$t(),this.symbols=ve(e.domain),this.validateDomain(e.domain),this.symbols=null,{valid:!this.ctx.diagnostics.some(n=>n.severity==="error"),diagnostics:this.ctx.diagnostics}}validateDomain(e){e.name.startsWith("__")&&this.error("Domain name cannot start with '__' (reserved prefix)",e.location,"E_RESERVED_NAME");for(let n of e.members)switch(n.kind){case"state":this.validateState(n);break;case"computed":this.validateExpr(n.expression,"computed");break;case"action":this.validateAction(n);break;case"flow":break}}validateState(e){let n=new Map;for(let o of e.fields){let r=n.get(o.name);r?this.error(`Duplicate state field '${o.name}'. First declared at line ${r.start.line}`,o.location,"E_DUPLICATE_FIELD"):n.set(o.name,o.location),this.validateStateField(o)}}validateStateField(e){this.checkAnonymousObjectType(e.typeExpr,e.location),e.initializer&&this.validateStateInitializer(e.initializer)}validateStateInitializer(e){switch(e.kind){case"literal":return;case"identifier":case"iterationVar":this.error("State initializers must be compile-time constants",e.location,"E042");return;case"systemIdent":e.path[0]==="system"?this.error("$system.* cannot be used in state initializers",e.location,"E002"):this.error("State initializers must be compile-time constants",e.location,"E042");return;case"objectLiteral":for(let n of e.properties)this.validateStateInitializer(n.value);return;case"arrayLiteral":for(let n of e.elements)this.validateStateInitializer(n);return;case"functionCall":{let n=this.ctx.diagnostics.length;for(let o of e.args)this.validateStateInitializer(o);this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}case"binary":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(e.left),this.validateStateInitializer(e.right),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}case"unary":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(e.operand),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}case"ternary":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(e.condition),this.validateStateInitializer(e.consequent),this.validateStateInitializer(e.alternate),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}case"propertyAccess":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(e.object),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}case"indexAccess":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(e.object),this.validateStateInitializer(e.index),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}}}checkAnonymousObjectType(e,n){switch(e.kind){case"objectType":this.ctx.diagnostics.push(Dt("W012","Anonymous object type in state field. Use a named type declaration instead: type MyType = { ... }",e.location,{suggestion:"Define this type using 'type TypeName = { ... }' and reference it by name"}));for(let o of e.fields)this.checkAnonymousObjectType(o.typeExpr,n);break;case"arrayType":this.checkAnonymousObjectType(e.elementType,n);break;case"recordType":this.checkAnonymousObjectType(e.keyType,n),this.checkAnonymousObjectType(e.valueType,n);break;case"unionType":for(let o of e.types)this.checkAnonymousObjectType(o,n);break}}validateAction(e){this.ctx.inAction=!0,this.ctx.currentActionParamTypes=Ae(e.params),e.available&&this.validateAvailableExpr(e.available),e.dispatchable&&this.validateDispatchableExpr(e.dispatchable);for(let n of e.body)this.validateGuardedStmt(n);this.ctx.inAction=!1,this.ctx.currentActionParamTypes=new Map}validateAvailableExpr(e){switch(e.kind){case"identifier":this.ctx.currentActionParamTypes.has(e.name)&&this.error("Action parameters cannot be used in available condition",e.location,"E005");break;case"systemIdent":e.path[0]==="system"&&this.error("$system.* cannot be used in available condition (must be pure expression)",e.location,"E005"),e.path[0]==="input"&&this.error("$input.* cannot be used in available condition (parameters not available at availability check)",e.location,"E005"),e.path[0]==="meta"&&this.error("$meta.* cannot be used in available condition (availability is schema-context only)",e.location,"E005");break;case"functionCall":for(let n of e.args)this.validateAvailableExpr(n);break;case"binary":this.validateAvailableExpr(e.left),this.validateAvailableExpr(e.right);break;case"unary":this.validateAvailableExpr(e.operand);break;case"ternary":this.validateAvailableExpr(e.condition),this.validateAvailableExpr(e.consequent),this.validateAvailableExpr(e.alternate);break;case"propertyAccess":this.validateAvailableExpr(e.object);break;case"indexAccess":this.validateAvailableExpr(e.object),this.validateAvailableExpr(e.index);break;case"objectLiteral":for(let n of e.properties)this.validateAvailableExpr(n.value);break;case"arrayLiteral":for(let n of e.elements)this.validateAvailableExpr(n);break}}validateDispatchableExpr(e){switch(e.kind){case"systemIdent":e.path[0]==="system"&&this.error("$system.* cannot be used in dispatchable condition (must be pure expression)",e.location,"E047"),e.path[0]==="input"&&this.error("$input.* cannot be used in dispatchable condition (use bare action parameter names)",e.location,"E047"),e.path[0]==="meta"&&this.error("$meta.* cannot be used in dispatchable condition (dispatchability is snapshot + bound-input only)",e.location,"E047");break;case"functionCall":for(let n of e.args)this.validateDispatchableExpr(n);break;case"binary":this.validateDispatchableExpr(e.left),this.validateDispatchableExpr(e.right);break;case"unary":this.validateDispatchableExpr(e.operand);break;case"ternary":this.validateDispatchableExpr(e.condition),this.validateDispatchableExpr(e.consequent),this.validateDispatchableExpr(e.alternate);break;case"propertyAccess":this.validateDispatchableExpr(e.object);break;case"indexAccess":this.validateDispatchableExpr(e.object),this.validateDispatchableExpr(e.index);break;case"objectLiteral":for(let n of e.properties)this.validateDispatchableExpr(n.value);break;case"arrayLiteral":for(let n of e.elements)this.validateDispatchableExpr(n);break}}validateGuardedStmt(e){switch(e.kind){case"when":this.validateWhen(e);break;case"once":this.validateOnce(e);break;case"onceIntent":this.validateOnceIntent(e);break;case"patch":this.validatePatch(e);break;case"effect":this.validateEffect(e);break;case"include":break;case"fail":this.validateFail(e);break;case"stop":this.validateStop(e);break}}validateWhen(e){this.ctx.inGuard=!0,this.ctx.guardDepth++,this.validateCondition(e.condition,"when");for(let n of e.body)this.validateGuardedStmt(n);this.ctx.guardDepth--,this.ctx.guardDepth===0&&(this.ctx.inGuard=!1)}validateOnce(e){this.ctx.inGuard=!0,this.ctx.guardDepth++,this.ctx.hasMarkerPatch=!1,e.condition&&this.validateCondition(e.condition,"once");for(let n of e.body)this.validateGuardedStmt(n);this.ctx.guardDepth--,this.ctx.guardDepth===0&&(this.ctx.inGuard=!1)}validateOnceIntent(e){this.ctx.inGuard=!0,this.ctx.guardDepth++,e.condition&&this.validateCondition(e.condition,"onceIntent");for(let n of e.body)this.validateGuardedStmt(n);this.ctx.guardDepth--,this.ctx.guardDepth===0&&(this.ctx.inGuard=!1)}validatePatch(e){if(this.ctx.inGuard||this.error("Patch must be inside a guard (when, once, or onceIntent)",e.location,"E_UNGUARDED_PATCH"),e.value){let n=this.ctx.diagnostics.length,o=this.validateExpr(e.value,"action");if(!this.symbols||n!==this.ctx.diagnostics.length)return;let r=Jn(e.path,this.symbols);if(!r||!o)return;V(o,r,this.symbols)===!1&&this.error(`Patch value for '${Zn(e.path)}' must be assignable to ${x(r,this.symbols)}, got ${x(o,this.symbols)}`,e.value.location,"E_TYPE_MISMATCH")}}validateEffect(e){this.ctx.inGuard||this.error("Effect must be inside a guard (when, once, or onceIntent)",e.location,"E_UNGUARDED_EFFECT");for(let n of e.args)n.isPath||this.validateExpr(n.value,"action")}validateFail(e){this.ctx.inGuard||this.error("fail must be inside a guard (when, once, or onceIntent)",e.location,"E006"),e.message&&this.validateExpr(e.message,"action")}validateStop(e){this.ctx.inGuard||this.error("stop must be inside a guard (when, once, or onceIntent)",e.location,"E007"),Yn.test(e.reason)&&this.error("stop message suggests waiting/pending - use 'Already processed' style instead",e.location,"E008")}validateCondition(e,n){let o=this.ctx.diagnostics.length,r=this.validateExpr(e,"action");o===this.ctx.diagnostics.length&&this.requireAssignable(r,E("boolean",e.location),e.location,`Condition in ${n} must evaluate to boolean`)}validateExpr(e,n,o=this.ctx.currentActionParamTypes){switch(e.kind){case"functionCall":return this.validateFunctionCall(e,n,o),this.inferType(e,o);case"binary":{let r=this.ctx.diagnostics.length,i=this.validateExpr(e.left,n,o),a=this.validateExpr(e.right,n,o);if(!(r!==this.ctx.diagnostics.length))switch(e.operator){case"==":case"!=":this.validatePrimitiveEquality(e.left,e.right,i,a,e.location);break;case"<":case"<=":case">":case">=":this.requireAssignable(i,E("number",e.left.location),e.left.location,`Operator '${e.operator}' requires a numeric left operand`),this.requireAssignable(a,E("number",e.right.location),e.right.location,`Operator '${e.operator}' requires a numeric right operand`);break;case"&&":case"||":this.requireAssignable(i,E("boolean",e.left.location),e.left.location,`Operator '${e.operator}' requires a boolean left operand`),this.requireAssignable(a,E("boolean",e.right.location),e.right.location,`Operator '${e.operator}' requires a boolean right operand`);break;case"+":case"-":case"*":case"/":case"%":this.requireAssignable(i,E("number",e.left.location),e.left.location,`Operator '${e.operator}' requires a numeric left operand`),this.requireAssignable(a,E("number",e.right.location),e.right.location,`Operator '${e.operator}' requires a numeric right operand`);break;case"??":this.validateCoalesceTypes([i,a],e.location);break}return this.inferType(e,o)}case"unary":{let r=this.ctx.diagnostics.length,i=this.validateExpr(e.operand,n,o);return r===this.ctx.diagnostics.length&&this.requireAssignable(i,E(e.operator==="!"?"boolean":"number",e.operand.location),e.operand.location,e.operator==="!"?"Unary '!' requires a boolean operand":"Unary '-' requires a numeric operand"),this.inferType(e,o)}case"ternary":{let r=this.ctx.diagnostics.length,i=this.validateExpr(e.condition,n,o);return this.validateExpr(e.consequent,n,o),this.validateExpr(e.alternate,n,o),r===this.ctx.diagnostics.length&&this.requireAssignable(i,E("boolean",e.condition.location),e.condition.location,"Ternary condition must evaluate to boolean"),this.inferType(e,o)}case"propertyAccess":return this.validateExpr(e.object,n,o),this.inferType(e,o);case"indexAccess":return this.validateExpr(e.object,n,o),this.validateExpr(e.index,n,o),this.inferType(e,o);case"objectLiteral":for(let r of e.properties)this.validateExpr(r.value,n,o);return this.inferType(e,o);case"arrayLiteral":for(let r of e.elements)this.validateExpr(r,n,o);return this.inferType(e,o);case"systemIdent":return this.inferType(e,o);case"literal":case"identifier":case"iterationVar":return this.inferType(e,o)}}validateFunctionCall(e,n,o){let{name:r,args:i,location:a}=e;if(["reduce","fold","foldl","foldr","scan"].includes(r)&&this.error(`Function '${r}' is forbidden. Use sum(), min(), max() for aggregation instead`,a,"E011"),["sum","min","max"].includes(r)&&i.length===1){n==="action"&&this.error(`Primitive aggregation '${r}()' can only be used in computed expressions, not in actions`,a,"E009");let c=i[0];c.kind==="functionCall"&&this.error(`Primitive aggregation '${r}()' does not allow composition. Use a direct reference, not '${c.name}()'`,a,"E010")}switch(r){case"eq":case"neq":break;case"len":case"sum":i.length!==1&&this.error(`Function '${r}' expects 1 argument, got ${i.length}`,a,"E_ARG_COUNT");break;case"add":case"sub":case"mul":case"div":case"mod":case"absDiff":case"idiv":case"gt":case"gte":case"lt":case"lte":i.length!==2&&this.error(`Function '${r}' expects 2 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"not":case"neg":case"abs":case"floor":case"ceil":case"round":case"sqrt":case"isNull":case"isNotNull":case"trim":case"lower":case"upper":case"strlen":case"keys":case"values":case"entries":case"first":case"last":case"typeof":case"toString":case"toNumber":case"toBoolean":case"reverse":case"unique":case"flat":case"fromEntries":i.length!==1&&this.error(`Function '${r}' expects 1 argument, got ${i.length}`,a,"E_ARG_COUNT");break;case"pow":case"findById":case"existsById":case"filter":case"map":case"find":case"every":case"some":case"at":case"includes":case"field":case"hasKey":case"pick":case"omit":case"startsWith":case"endsWith":case"strIncludes":case"indexOf":i.length!==2&&this.error(`Function '${r}' expects 2 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"updateById":case"clamp":i.length!==3&&this.error(`Function '${r}' expects 3 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"removeById":case"streak":i.length!==2&&this.error(`Function '${r}' expects 2 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"slice":case"substring":case"substr":case"replace":(i.length<2||i.length>3)&&this.error(`Function '${r}' expects 2-3 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"split":i.length!==2&&this.error(`Function '${r}' expects 2 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"and":case"or":case"concat":case"min":case"max":case"merge":case"coalesce":case"append":i.length<1&&this.error(`Function '${r}' expects at least 1 argument`,a,"E_ARG_COUNT");break;case"match":i.length<3&&this.error("Function 'match' expects a selector, at least one [key, value] arm, and a default value",a,"E050");break;case"argmax":case"argmin":i.length<2&&this.error(`Function '${r}' expects at least one [label, eligible, score] candidate and a tie-break literal`,a,"E052");break;case"if":case"cond":i.length!==3&&this.error(`Function '${r}' expects 3 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;default:this.error(`Unknown function '${r}'. Check spelling or see MEL builtin function reference`,a,"E_UNKNOWN_FN");break}let s=[];if(["filter","map","find","every","some"].includes(r)&&i.length>0){let c=this.validateExpr(i[0],n,o);s.push(c);let d=o;if(this.symbols){let l=G(c,this.symbols);l&&(d=Xn(o,l))}for(let l=1;l<i.length;l+=1)s.push(this.validateExpr(i[l],n,l===1?d:o))}else for(let c of i)s.push(this.validateExpr(c,n,o));if(this.symbols)switch(r){case"eq":case"neq":i.length===2&&this.validatePrimitiveEquality(i[0],i[1],s[0],s[1],a);break;case"add":case"sub":case"mul":case"div":case"mod":case"absDiff":case"idiv":case"pow":i.length===2&&(this.requireAssignable(s[0],E("number",i[0].location),i[0].location,`Function '${r}' expects a numeric first argument`),this.requireAssignable(s[1],E("number",i[1].location),i[1].location,`Function '${r}' expects a numeric second argument`));break;case"gt":case"gte":case"lt":case"lte":i.length===2&&(this.requireAssignable(s[0],E("number",i[0].location),i[0].location,`Function '${r}' expects a numeric first argument`),this.requireAssignable(s[1],E("number",i[1].location),i[1].location,`Function '${r}' expects a numeric second argument`));break;case"and":case"or":for(let[c,d]of i.entries())this.requireAssignable(s[c],E("boolean",d.location),d.location,`Function '${r}' expects boolean arguments`);break;case"not":i.length===1&&this.requireAssignable(s[0],E("boolean",i[0].location),i[0].location,"Function 'not' expects a boolean argument");break;case"neg":case"abs":case"floor":case"ceil":case"round":case"sqrt":i.length===1&&this.requireAssignable(s[0],E("number",i[0].location),i[0].location,`Function '${r}' expects a numeric argument`);break;case"clamp":if(i.length===3){this.requireAssignable(s[0],E("number",i[0].location),i[0].location,"Function 'clamp' expects a numeric first argument"),this.requireAssignable(s[1],E("number",i[1].location),i[1].location,"Function 'clamp' expects a numeric second argument"),this.requireAssignable(s[2],E("number",i[2].location),i[2].location,"Function 'clamp' expects a numeric third argument");let c=Ie(i[1]),d=Ie(i[2]);typeof c=="number"&&typeof d=="number"&&c>d&&this.error("Function 'clamp' requires literal bounds in lo, hi order",a,"E049")}break;case"streak":i.length===2&&(this.requireAssignable(s[0],E("number",i[0].location),i[0].location,"Function 'streak' expects a numeric first argument"),this.requireAssignable(s[1],E("boolean",i[1].location),i[1].location,"Function 'streak' expects a boolean second argument"));break;case"trim":case"lower":case"upper":case"strlen":i.length===1&&this.requireAssignable(s[0],E("string",i[0].location),i[0].location,`Function '${r}' expects a string argument`);break;case"startsWith":case"endsWith":case"strIncludes":case"indexOf":case"split":i.length===2&&(this.requireAssignable(s[0],E("string",i[0].location),i[0].location,`Function '${r}' expects a string first argument`),this.requireAssignable(s[1],E("string",i[1].location),i[1].location,`Function '${r}' expects a string second argument`));break;case"replace":i.length>=2&&(this.requireAssignable(s[0],E("string",i[0].location),i[0].location,"Function 'replace' expects a string first argument"),this.requireAssignable(s[1],E("string",i[1].location),i[1].location,"Function 'replace' expects a string second argument")),i.length===3&&this.requireAssignable(s[2],E("string",i[2].location),i[2].location,"Function 'replace' expects a string replacement argument");break;case"substring":case"substr":i.length>=2&&(this.requireAssignable(s[0],E("string",i[0].location),i[0].location,`Function '${r}' expects a string first argument`),this.requireAssignable(s[1],E("number",i[1].location),i[1].location,`Function '${r}' expects a numeric second argument`)),i.length===3&&this.requireAssignable(s[2],E("number",i[2].location),i[2].location,`Function '${r}' expects a numeric third argument`);break;case"len":i.length===1&&this.requireLenCompatible(s[0],i[0].location);break;case"filter":case"find":case"every":case"some":i.length===2&&(this.requireArrayCompatible(s[0],i[0].location,r),this.requireAssignable(s[1],E("boolean",i[1].location),i[1].location,`Function '${r}' requires a boolean-valued callback`));break;case"map":i.length===2&&this.requireArrayCompatible(s[0],i[0].location,r);break;case"coalesce":this.validateCoalesceTypes(s,a);break;case"match":this.validateMatchCall(i,s,a,o);break;case"argmax":case"argmin":this.validateArgSelectionCall(r,i,a,o);break;case"if":case"cond":i.length===3&&this.requireAssignable(s[0],E("boolean",i[0].location),i[0].location,`Function '${r}' expects a boolean condition`);break}}validatePrimitiveEquality(e,n,o,r,i){if(!this.symbols)return;if(e.kind==="objectLiteral"||e.kind==="arrayLiteral"||n.kind==="objectLiteral"||n.kind==="arrayLiteral"){this.error("eq/neq operands must be compatible primitive types, not object or array literals",i,"E_TYPE_MISMATCH");return}Ut(o,r,this.symbols)===!1&&this.error(`eq/neq operands must be compatible primitive types, got ${x(o,this.symbols)} and ${x(r,this.symbols)}`,i,"E_TYPE_MISMATCH")}inferType(e,n){return this.symbols?k(e,n,this.symbols):null}requireAssignable(e,n,o,r){if(!this.symbols||!e)return;V(e,n,this.symbols)===!1&&this.error(`${r}, got ${x(e,this.symbols)}`,o,"E_TYPE_MISMATCH")}requireArrayCompatible(e,n,o){if(!this.symbols||!e)return;Bt(e,this.symbols)===!1&&this.error(`Function '${o}' expects an array first argument, got ${x(e,this.symbols)}`,n,"E_TYPE_MISMATCH")}requireLenCompatible(e,n){if(!this.symbols||!e)return;qt(e,this.symbols)===!1&&this.error(`Function 'len' expects a string, array, object, or record argument, got ${x(e,this.symbols)}`,n,"E_TYPE_MISMATCH")}validateCoalesceTypes(e,n){if(!this.symbols)return;let o=e.map(r=>Qn(r,this.symbols)).filter(r=>r!==null);for(let r=0;r<o.length;r+=1)for(let i=r+1;i<o.length;i+=1)if(tt(o[r],o[i],this.symbols)===!1){this.error(`coalesce arguments must have compatible non-null types, got ${x(o[r],this.symbols)} and ${x(o[i],this.symbols)}`,n,"E_TYPE_MISMATCH");return}}validateMatchCall(e,n,o,r){if(!this.symbols||e.length<3)return;let i=n[0],a=et(i,this.symbols);a==="invalid"&&this.error(`Function 'match' requires a selector of type string, number, or boolean, got ${x(i,this.symbols)}`,e[0].location,"E_TYPE_MISMATCH");let s=new Set,c=[];for(let d=1;d<e.length-1;d+=1){let l=e[d];if(l.kind!=="arrayLiteral"||l.elements.length!==2){this.error("Function 'match' requires each arm to be an inline [key, value] array literal",l.location,"E050");continue}let[p,m]=l.elements,f=Gt(p);if(f==null)this.error("Function 'match' requires literal string, number, or boolean arm keys",p.location,"E050");else{let _=`${typeof f}:${String(f)}`;s.has(_)?this.error(`Function 'match' has duplicate arm key ${JSON.stringify(f)}`,p.location,"E051"):s.add(_)}let T=this.inferType(p,r),S=et(T,this.symbols);(S==="invalid"||a!==null&&S!==null&&a!==S)&&this.error(`Function 'match' selector and arm keys must use the same primitive type, got ${x(i,this.symbols)} and ${x(T,this.symbols)}`,p.location,"E_TYPE_MISMATCH"),c.push(this.inferType(m,r))}c.push(n[n.length-1]);for(let d=0;d<c.length;d+=1)for(let l=d+1;l<c.length;l+=1)if(tt(c[d],c[l],this.symbols)===!1){this.error(`Function 'match' arm values and default must have compatible types, got ${x(c[d],this.symbols)} and ${x(c[l],this.symbols)}`,o,"E_TYPE_MISMATCH");return}}validateArgSelectionCall(e,n,o,r){if(!this.symbols||n.length<2)return;let i=n[n.length-1],a=Gt(i);a!=="first"&&a!=="last"&&this.error(`Function '${e}' requires a final tie-break literal of "first" or "last"`,i.location,"E052");let s=[],c=null;for(let d=0;d<n.length-1;d+=1){let l=n[d];if(l.kind!=="arrayLiteral"||l.elements.length!==3){this.error(`Function '${e}' requires inline [label, eligible, score] array literal candidates`,l.location,"E052");continue}let[p,m,f]=l.elements,T=this.inferType(p,r),S=et(T,this.symbols);S==="invalid"?this.error(`Function '${e}' requires labels with exactly one primitive scalar type, got ${x(T,this.symbols)}`,p.location,"E_TYPE_MISMATCH"):c===null?c=S:S!==null&&S!==c&&this.error(`Function '${e}' candidate labels must share one primitive scalar type, got ${c} and ${S}`,p.location,"E_TYPE_MISMATCH"),this.requireAssignable(this.inferType(m,r),E("boolean",m.location),m.location,`Function '${e}' expects a boolean eligible value`),this.requireAssignable(this.inferType(f,r),E("number",f.location),f.location,`Function '${e}' expects a numeric score value`),s.push(T)}for(let d=0;d<s.length;d+=1)for(let l=d+1;l<s.length;l+=1)if(tt(s[d],s[l],this.symbols)===!1){this.error(`Function '${e}' candidate labels must have compatible scalar types, got ${x(s[d],this.symbols)} and ${x(s[l],this.symbols)}`,o,"E_TYPE_MISMATCH");return}}error(e,n,o){this.ctx.diagnostics.push({severity:"error",code:o,message:e,location:n})}warn(e,n,o){this.ctx.diagnostics.push({severity:"warning",code:o,message:e,location:n})}};function zt(t){let n=new nt().validate(t),o=jt(t),r=[...n.diagnostics,...o];return{valid:!r.some(i=>i.severity==="error"),diagnostics:r}}var ot={mode:"schema",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!1},rt={mode:"action",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!1},it={mode:"action",allowSysPaths:{prefixes:["input"]},fnTableVersion:"1.0",allowItem:!1},at={mode:"action",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!0},eo={allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0"};var j=class extends Error{code;path;details;constructor(e,n,o){super(n),this.name="LoweringError",this.code=e,this.path=o?.path,this.details=o?.details}};function Pe(t,e,n){return new j("INVALID_KIND_FOR_CONTEXT",`Node kind '${t}' is not allowed in ${e} context`,{path:n,details:{kind:t,context:e}})}function y(t,e){return new j("UNKNOWN_CALL_FN",`Unknown function '${t}' in call expression`,{path:e,details:{fn:t}})}function Me(t,e){return new j("INVALID_SYS_PATH",`System path '${t.join(".")}' is not allowed in Translator path`,{path:e,details:{sysPath:t}})}function st(t,e){return new j("UNSUPPORTED_BASE",`Unsupported base expression kind '${t}'. Only var(item) is supported.`,{path:e,details:{baseKind:t}})}function to(t,e){return new j("INVALID_SHAPE",`Invalid node shape: ${t}`,{path:e,details:{description:t}})}function ct(t,e){return new j("UNKNOWN_NODE_KIND",`Unknown expression node kind '${t}'`,{path:e,details:{kind:t}})}function no(t,e){let n=Array.from(t),o=Array.from(e),r=Math.min(n.length,o.length);for(let i=0;i<r;i+=1){let a=n[i].codePointAt(0)??0,s=o[i].codePointAt(0)??0;if(a!==s)return a-s}return n.length-o.length}function Vt(t){return t.map((e,n)=>({item:e,index:n})).sort((e,n)=>{let o=no(e.item.key,n.item.key);return o!==0?o:e.index-n.index}).map(({item:e})=>e)}function u(t,e){switch(t.kind){case"lit":return oo(t);case"var":return ro(t,e);case"sys":return io(t,e);case"get":return ao(t,e);case"field":return Ht(t,e);case"call":return so(t,e);case"obj":return co(t,e);case"arr":return lo(t,e);default:throw ct(t.kind)}}function oo(t){return{kind:"lit",value:t.value}}function ro(t,e){if(!e.allowItem)throw Pe("var",e.mode);return{kind:"get",path:"$item"}}function io(t,e){if(t.path.length===0)throw Me(t.path);let n=t.path[0];if(!(e.allowSysPaths?.prefixes??["meta","input"]).includes(n))throw Me(t.path);return{kind:"get",path:t.path.join(".")}}function ao(t,e){let n=t.path.map(o=>o.name).join(".");if(t.base===void 0)return{kind:"get",path:n};if(t.base.kind==="var"&&t.base.name==="item"){if(!e.allowItem)throw Pe("var",e.mode);return{kind:"get",path:`$item.${n}`}}throw st(t.base.kind)}function Ht(t,e){if(t.object.kind==="get"&&t.object.base===void 0){let n=t.object.path.map(o=>o.name).join(".");return{kind:"get",path:n?`${n}.${t.property}`:t.property}}return{kind:"field",object:u(t.object,e),property:t.property}}function so(t,e){let{fn:n,args:o}=t;if(n==="absDiff"){if(o.length!==2)throw y(n);return{kind:"abs",arg:{kind:"sub",left:u(o[0],e),right:u(o[1],e)}}}if(n==="clamp"){if(o.length!==3)throw y(n);return{kind:"min",args:[{kind:"max",args:[u(o[0],e),u(o[1],e)]},u(o[2],e)]}}if(n==="idiv"){if(o.length!==2)throw y(n);return{kind:"floor",arg:{kind:"div",left:u(o[0],e),right:u(o[1],e)}}}if(n==="streak"){if(o.length!==2)throw y(n);return{kind:"if",cond:u(o[1],e),then:{kind:"add",left:u(o[0],e),right:{kind:"lit",value:1}},else:{kind:"lit",value:0}}}if(n==="match")return po(o,e);if(n==="argmax"||n==="argmin")return uo(n,o,e);if(go(n)){if(o.length!==2)throw y(n);let[r,i]=o;return{kind:n,left:u(r,e),right:u(i,e)}}if(n==="isNotNull"){if(o.length!==1)throw y(n);return{kind:"not",arg:{kind:"isNull",arg:u(o[0],e)}}}if(Kt(n)){if(o.length!==1)throw y(n);return{kind:Eo(n),arg:u(o[0],e)}}if(n==="trim"){if(o.length!==1)throw y(n);return{kind:"trim",str:u(o[0],e)}}if(n==="lower"||n==="toLowerCase"){if(o.length!==1)throw y(n);return{kind:"toLowerCase",str:u(o[0],e)}}if(n==="upper"||n==="toUpperCase"){if(o.length!==1)throw y(n);return{kind:"toUpperCase",str:u(o[0],e)}}if(n==="strlen"||n==="strLen"){if(o.length!==1)throw y(n);return{kind:"strLen",str:u(o[0],e)}}if(ko(n))return o.length===1?{kind:n==="min"?"minArray":"maxArray",array:u(o[0],e)}:{kind:n,args:o.map(r=>u(r,e))};if(n==="sum"){if(o.length!==1)throw y(n);return{kind:"sumArray",array:u(o[0],e)}}if(n==="pow"){if(o.length!==2)throw y(n);return{kind:"pow",base:u(o[0],e),exponent:u(o[1],e)}}if(No(n))return{kind:n,args:o.map(r=>u(r,e))};if(n==="if"||n==="cond"){if(o.length!==3)throw y(n);return{kind:"if",cond:u(o[0],e),then:u(o[1],e),else:u(o[2],e)}}if(n==="field"){if(o.length!==2)throw y(n);let r=u(o[0],e),i=o[1];if(i.kind!=="lit"||typeof i.value!="string")throw y(n);return Ht({kind:"field",object:o[0],property:i.value},e)}if(To(n)){if(o.length!==1)throw y(n);return{kind:n,array:u(o[0],e)}}if(bo(n)){if(o.length!==1)throw y(n);return{kind:n,obj:u(o[0],e)}}if(n==="at"){if(o.length!==2)throw y(n);return{kind:"at",array:u(o[0],e),index:u(o[1],e)}}if(n==="includes"){if(o.length!==2)throw y(n);return{kind:"includes",array:u(o[0],e),item:u(o[1],e)}}if(So(n)){if(o.length!==2)throw y(n);let r={...e,allowItem:!0};return n==="map"?{kind:"map",array:u(o[0],e),mapper:u(o[1],r)}:{kind:n,array:u(o[0],e),predicate:u(o[1],r)}}if(n==="slice"){if(o.length<2||o.length>3)throw y(n);let r={kind:"slice",array:u(o[0],e),start:u(o[1],e)};return o.length===3&&(r.end=u(o[2],e)),r}if(n==="substring"||n==="substr"){if(o.length<2||o.length>3)throw y(n);let r={kind:"substring",str:u(o[0],e),start:u(o[1],e)};return o.length===3&&(r.end=u(o[2],e)),r}if(n==="append"){if(o.length<1)throw y(n);return{kind:"append",array:u(o[0],e),items:o.slice(1).map(r=>u(r,e))}}if(n==="merge")return{kind:"merge",objects:o.map(r=>u(r,e))};throw y(n)}function co(t,e){let n={};for(let o of Vt(t.fields))n[o.key]=u(o.value,e);return{kind:"object",fields:n}}function lo(t,e){if(t.elements.every(r=>r.kind==="lit"))return{kind:"lit",value:t.elements.map(i=>i.value)};let o=t.elements.map(r=>u(r,e));return o.length===0?{kind:"lit",value:[]}:{kind:"append",array:{kind:"lit",value:[]},items:o}}function po(t,e){if(t.length<3)throw y("match");let n=u(t[0],e),o=u(t[t.length-1],e);for(let r=t.length-2;r>=1;r-=1){let i=t[r];if(i.kind!=="arr"||i.elements.length!==2)throw y("match");o={kind:"if",cond:{kind:"eq",left:n,right:u(i.elements[0],e)},then:u(i.elements[1],e),else:o}}return o}function uo(t,e,n){if(e.length<2)throw y(t);let o=e[e.length-1];if(o.kind!=="lit"||o.value!=="first"&&o.value!=="last")throw y(t);let r=e.slice(0,-1).map(i=>mo(i,n,t));if(r.length===0)throw y(t);return fo(t,r,o.value)}function mo(t,e,n){if(t.kind!=="arr"||t.elements.length!==3)throw y(n);return{label:u(t.elements[0],e),eligible:u(t.elements[1],e),score:u(t.elements[2],e)}}function fo(t,e,n){let o={kind:"lit",value:null};for(let r=e.length-1;r>=0;r-=1)o={kind:"if",cond:ho(t,e,n,r),then:e[r].label,else:o};return o}function ho(t,e,n,o){let r=e[o],i=[];for(let a=0;a<e.length;a+=1){if(a===o)continue;let s=e[a];i.push({kind:"or",args:[{kind:"not",arg:s.eligible},{kind:yo(t,n,o,a),left:r.score,right:s.score}]})}return i.length===0?r.eligible:{kind:"and",args:[r.eligible,...i]}}function yo(t,e,n,o){let r=e==="first"?n<o:n>o;return t==="argmax"?r?"gte":"gt":r?"lte":"lt"}function go(t){return["eq","neq","gt","gte","lt","lte","add","sub","mul","div","mod"].includes(t)}function Kt(t){return["not","neg","abs","floor","ceil","round","sqrt","len","typeof","isNull","toString"].includes(t)}function Eo(t){if(t==="isNotNull")throw y(t);if(!Kt(t))throw y(t);return t}function ko(t){return t==="min"||t==="max"}function No(t){return["and","or","concat","coalesce"].includes(t)}function To(t){return["first","last"].includes(t)}function bo(t){return["keys","values","entries"].includes(t)}function So(t){return["filter","find","every","some","map"].includes(t)}function xo(t,e){return t.map(n=>vo(n,e))}function vo(t,e){let n=t.condition?u(t.condition,De(e,"action")):void 0,o=Ao(t.op,e);return{fragmentId:t.fragmentId,condition:n,op:o,confidence:t.confidence}}function Ao(t,e){switch(t.kind){case"addType":return{kind:"addType",typeName:t.typeName,typeExpr:te(t.typeExpr)};case"addField":return{kind:"addField",typeName:t.typeName,field:{name:t.field.name,type:te(t.field.type),optional:t.field.optional,defaultValue:t.field.defaultValue}};case"setFieldType":return{kind:"setFieldType",path:t.path,typeExpr:te(t.typeExpr)};case"setDefaultValue":return{kind:"setDefaultValue",path:t.path,value:t.value};case"addConstraint":return{kind:"addConstraint",targetPath:t.targetPath,rule:u(t.rule,De(e,"schema")),message:t.message};case"addComputed":return{kind:"addComputed",name:t.name,expr:u(t.expr,De(e,"schema")),deps:t.deps};case"addActionAvailable":return{kind:"addActionAvailable",actionName:t.actionName,expr:u(t.expr,De(e,"schema"))}}}function te(t){switch(t.kind){case"primitive":return{kind:"primitive",name:t.name};case"array":return{kind:"array",element:te(t.element)};case"object":return{kind:"object",fields:t.fields.map(e=>({name:e.name,type:te(e.type),optional:e.optional}))};case"union":return{kind:"union",members:t.members.map(te)};case"literal":return{kind:"literal",value:t.value};case"ref":return{kind:"ref",name:t.name}}}function De(t,e){return{mode:e,allowSysPaths:t.allowSysPaths,fnTableVersion:t.fnTableVersion,actionName:t.actionName,allowItem:!1}}function wo(t,e){return t.map(n=>Re(n,e))}function Re(t,e){let n=t.condition?u(t.condition,e):void 0,o=t.value?u(t.value,e):void 0;return{condition:n,op:t.op,path:Co(t.path,e),value:o}}function Co(t,e){return t.map(n=>n.kind==="prop"?n:{kind:"expr",expr:u(n.expr,e)})}function w(t,e={}){switch(t.kind){case"literal":return{kind:"lit",value:Mo(t.value,t.literalType)};case"identifier":return e.resolveIdentifier?.(t.name)??U(t.name);case"systemIdent":return Io(t,e);case"iterationVar":return{kind:"var",name:t.name};case"propertyAccess":return Po(t.object,t.property,e);case"indexAccess":return{kind:"call",fn:"at",args:[w(t.object,e),w(t.index,e)]};case"functionCall":return{kind:"call",fn:t.name,args:t.args.map(n=>w(n,e))};case"unary":return{kind:"call",fn:t.operator==="!"?"not":"neg",args:[w(t.operand,e)]};case"binary":return{kind:"call",fn:Do(t.operator),args:[w(t.left,e),w(t.right,e)]};case"ternary":return{kind:"call",fn:"cond",args:[w(t.condition,e),w(t.consequent,e),w(t.alternate,e)]};case"objectLiteral":return{kind:"obj",fields:t.properties.map(n=>({key:n.key,value:w(n.value,e)}))};case"arrayLiteral":return{kind:"arr",elements:t.elements.map(n=>w(n,e))}}}function U(...t){return{kind:"get",path:Wt(...t)}}function lt(t,...e){return{kind:"get",base:t,path:Wt(...e)}}function ue(...t){return{kind:"sys",path:t}}function Le(t){return{kind:"obj",fields:Object.entries(t).map(([e,n])=>({key:e,value:n}))}}function Wt(...t){return t.map(e=>({kind:"prop",name:e}))}function Io(t,e){return e.resolveSystemIdent?.(t.path)??ue(...t.path)}function Po(t,e,n){let o=w(t,n);return o.kind==="get"?{kind:"get",...o.base?{base:o.base}:void 0,path:[...o.path,{kind:"prop",name:e}]}:o.kind==="var"&&o.name==="item"?lt(o,e):{kind:"field",object:o,property:e}}function Mo(t,e){if(e==="null")return null;if(e==="number"){if(typeof t=="number")return t;if(typeof t=="bigint")return Number(t);if(typeof t=="string"&&t.length>0){let n=Number(t);if(!Number.isNaN(n))return n}throw new Error("Invalid number literal")}if(e==="string"){if(typeof t=="string")return t;throw new Error("Invalid string literal")}if(e==="boolean"){if(typeof t=="boolean")return t;throw new Error("Invalid boolean literal")}throw new Error("Unsupported literal type")}function Do(t){switch(t){case"+":return"add";case"-":return"sub";case"*":return"mul";case"/":return"div";case"%":return"mod";case"==":return"eq";case"!=":return"neq";case"<":return"lt";case"<=":return"lte";case">":return"gt";case">=":return"gte";case"&&":return"and";case"||":return"or";case"??":return"coalesce"}}import{hashSchemaSync as _o,semanticPathToPatchPath as $o,sha256Sync as Go}from"@manifesto-ai/core";var Ro=new Set(["findById","existsById","updateById","removeById"]);function Yt(t){return{...t,computed:{fields:Object.fromEntries(Object.entries(t.computed.fields).map(([e,n])=>[e,Lo(n)]))},actions:Object.fromEntries(Object.entries(t.actions).map(([e,n])=>[e,Oo(n)]))}}function Lo(t){return{...t,expr:Qt(t.expr)}}function Oo(t){return{...t,flow:Oe(t.flow),available:t.available?Qt(t.available):void 0,dispatchable:t.dispatchable?Fo(t.dispatchable):void 0}}function Oe(t){switch(t.kind){case"seq":return{kind:"seq",steps:t.steps.map(e=>Oe(e))};case"if":return{kind:"if",cond:dt(t.cond),then:Oe(t.then),else:t.else?Oe(t.else):void 0};case"patch":return{kind:"patch",op:t.op,path:t.path,value:t.value?dt(t.value):void 0};case"effect":return{kind:"effect",type:t.type,params:Object.fromEntries(Object.entries(t.params).map(([e,n])=>[e,jo(n)]))};case"fail":return{kind:"fail",code:t.code,message:t.message?dt(t.message):void 0};case"call":case"halt":return t}}function Qt(t){return u(D(t),ot)}function dt(t){return u(D(t),rt)}function Fo(t){return u(D(t),it)}function jo(t){return u(D(t),at)}function D(t){switch(t.kind){case"lit":case"var":return t;case"sys":return t.path[0]==="system"?U("$system",...t.path.slice(1)):t;case"get":return{kind:"get",...t.base?{base:D(t.base)}:void 0,path:t.path};case"field":return{kind:"field",object:D(t.object),property:t.property};case"obj":return{kind:"obj",fields:t.fields.map(e=>({key:e.key,value:D(e.value)}))};case"arr":return{kind:"arr",elements:t.elements.map(e=>D(e))};case"call":return Ro.has(t.fn)?D(Xt(t.fn,t.args)):{kind:"call",fn:t.fn,args:t.args.map(e=>D(e))}}}function Xt(t,e){let[n,o,r]=e,i=D(n),a=o?D(o):{kind:"lit",value:null},s={kind:"var",name:"item"},c=lt(s,"id");switch(t){case"findById":return{kind:"call",fn:"find",args:[i,{kind:"call",fn:"eq",args:[c,a]}]};case"existsById":return{kind:"call",fn:"not",args:[{kind:"call",fn:"isNull",args:[Xt("findById",e)]}]};case"updateById":{let d=r?D(r):Le({});return{kind:"call",fn:"map",args:[i,{kind:"call",fn:"cond",args:[{kind:"call",fn:"eq",args:[c,a]},{kind:"call",fn:"merge",args:[s,d]},s]}]}}case"removeById":return{kind:"call",fn:"filter",args:[i,{kind:"call",fn:"not",args:[{kind:"call",fn:"eq",args:[c,a]}]}]};default:return{kind:"call",fn:t,args:e.map(d=>D(d))}}}function Uo(t){return{domainName:t,stateFields:new Set,computedFields:new Set,actionParams:new Map,onceIntentCounters:new Map,currentAction:null,diagnostics:[],typeDefs:new Map,typeDefinitions:new Map,stateFieldSpecs:new Map,stateFieldTypes:new Map}}function Bo(t){let e=Uo(t.domain.name);qo(t.domain,e);let n=zo(t.domain,e),o=Vo(t.domain,e),r=Ko(t.domain,e),i=Jo(t.domain,e);if(e.diagnostics.some(d=>d.severity==="error"))return{schema:null,diagnostics:e.diagnostics};let a={id:`mel:${t.domain.name.toLowerCase()}`,version:"1.0.0",types:n,state:o,computed:r,actions:i,meta:{name:t.domain.name}},s=dr(a);return{schema:{...a,hash:s},diagnostics:e.diagnostics}}function Jt(t){let e=Bo(t);return e.schema?{schema:Yt(e.schema),diagnostics:e.diagnostics}:{schema:null,diagnostics:e.diagnostics}}function qo(t,e){for(let n of t.types)e.typeDefs.set(n.name,n);for(let n of t.members)if(n.kind==="state")for(let o of n.fields)e.stateFields.add(o.name);else n.kind==="computed"?e.computedFields.add(n.name):n.kind}function zo(t,e){let n={};for(let o of t.types){let r=H(o.typeExpr);e.typeDefinitions.set(o.name,r),n[o.name]={name:o.name,definition:r}}return n}function H(t){switch(t.kind){case"simpleType":return["string","number","boolean","null","object","array"].includes(t.name)?{kind:"primitive",type:t.name}:{kind:"ref",name:t.name};case"arrayType":return{kind:"array",element:H(t.elementType)};case"recordType":return{kind:"record",key:H(t.keyType),value:H(t.valueType)};case"objectType":let e={};for(let o of t.fields)e[o.name]={type:H(o.typeExpr),optional:o.optional};return{kind:"object",fields:e};case"unionType":return{kind:"union",types:t.types.map(H)};case"literalType":return{kind:"literal",value:t.value};default:let n=t;throw new Error(`Unknown type expression kind: ${t.kind}`)}}function Vo(t,e){let n={},o={};for(let r of t.members)if(r.kind==="state")for(let i of r.fields){let a=H(i.typeExpr);o[i.name]=a,e.stateFieldTypes.set(i.name,a);let s=X(i.typeExpr,e);s&&e.stateFieldSpecs.set(i.name,s);let c=Ho(i,e);c&&(n[i.name]=c)}return{fields:n,fieldTypes:o}}function Ho(t,e){let n=X(t.typeExpr,e);if(!n)return null;let o=t.initializer?je(t.initializer,e):void 0;return o!==void 0&&fe(o,H(t.typeExpr),t.name,t.location,e),{...n,required:!0,default:o}}function X(t,e,n=[]){switch(t.kind){case"simpleType":switch(t.name){case"string":return{type:"string",required:!0};case"number":return{type:"number",required:!0};case"boolean":return{type:"boolean",required:!0};case"null":return{type:"null",required:!0};default:{let o=e.typeDefs.get(t.name);return o?n.includes(t.name)?(pt(e,"E044",`Recursive type '${t.name}' cannot be lowered to FieldSpec in a schema position`,t.location),null):X(o.typeExpr,e,[...n,t.name]):{type:"object",required:!0}}}case"unionType":{let o=t.types.filter(s=>!(s.kind==="simpleType"&&s.name==="null")&&!(s.kind==="literalType"&&s.value===null)),r=o.length!==t.types.length,i=[],a=!r;for(let s of o){if(s.kind!=="literalType"){a=!1;break}i.push(s.value)}return a&&i.length>0?{type:{enum:i},required:!0}:r&&o.length===1?X(o[0],e,n):(pt(e,"E043",`Union type '${ne(t)}' cannot be soundly lowered to FieldSpec`,t.location),null)}case"arrayType":{let o=X(t.elementType,e,n);return o?{type:"array",required:!0,items:o}:null}case"recordType":return{type:"object",required:!0};case"literalType":return typeof t.value=="string"?{type:"string",required:!0}:typeof t.value=="number"?{type:"number",required:!0}:typeof t.value=="boolean"?{type:"boolean",required:!0}:{type:"null",required:!0};case"objectType":{let o={};for(let r of t.fields){let i=X(r.typeExpr,e,n);if(!i)return null;o[r.name]={...i,required:!r.optional}}return{type:"object",required:!0,fields:o}}}}function pt(t,e,n,o){t.diagnostics.push({severity:"error",code:e,message:n,location:o})}function ne(t){switch(t.kind){case"simpleType":return t.name;case"unionType":return t.types.map(e=>ne(e)).join(" | ");case"arrayType":return`Array<${ne(t.elementType)}>`;case"recordType":return`Record<${ne(t.keyType)}, ${ne(t.valueType)}>`;case"literalType":return JSON.stringify(t.value);case"objectType":return`{ ${t.fields.map(e=>`${e.name}${e.optional?"?":""}: ${ne(e.typeExpr)}`).join("; ")} }`}}function he(t,e,n=[]){if(t.kind!=="ref")return t;if(n.includes(t.name))return null;let o=e.typeDefinitions.get(t.name);return o?he(o,e,[...n,t.name]):null}function K(t){switch(t.kind){case"primitive":return t.type;case"array":return`Array<${K(t.element)}>`;case"record":return`Record<${K(t.key)}, ${K(t.value)}>`;case"object":return`{ ${Object.entries(t.fields).map(([e,n])=>`${e}${n.optional?"?":""}: ${K(n.type)}`).join("; ")} }`;case"union":return t.types.map(e=>K(e)).join(" | ");case"literal":return JSON.stringify(t.value);case"ref":return t.name}}function me(t,e,n){let o=he(e,n);if(!o)return!1;switch(o.kind){case"primitive":switch(o.type){case"null":return t===null;case"string":return typeof t=="string";case"number":return typeof t=="number";case"boolean":return typeof t=="boolean";case"object":return t!==null&&!Array.isArray(t)&&typeof t=="object";case"array":return Array.isArray(t);default:return!1}case"literal":return Object.is(t,o.value);case"array":return Array.isArray(t)&&t.every(r=>me(r,o.element,n));case"record":return t!==null&&!Array.isArray(t)&&typeof t=="object"&&Object.values(t).every(r=>me(r,o.value,n));case"object":if(t===null||Array.isArray(t)||typeof t!="object")return!1;for(let r of Object.keys(t))if(!(r in o.fields))return!1;for(let[r,i]of Object.entries(o.fields)){if(!(r in t)){if(!i.optional)return!1;continue}if(!me(t[r],i.type,n))return!1}return!0;case"union":return o.types.some(r=>me(t,r,n));case"ref":return!1}}function fe(t,e,n,o,r){if(t===void 0)return;let i=he(e,r);if(!i){r.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${K(e)}, got ${JSON.stringify(t)}`,location:o});return}if(i.kind==="union"){if(me(t,i,r))return;r.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${K(i)}, got ${JSON.stringify(t)}`,location:o});return}switch(i.kind){case"primitive":{let a=Array.isArray(t)?"array":t===null?"null":typeof t;switch(i.type){case"null":t!==null&&Q(r,n,"null",a,o);return;case"string":case"number":case"boolean":typeof t!==i.type&&Q(r,n,i.type,a,o);return;case"object":(t===null||Array.isArray(t)||typeof t!="object")&&Q(r,n,"object",a,o);return;case"array":Array.isArray(t)||Q(r,n,"array",a,o);return}return}case"literal":Object.is(t,i.value)||r.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects literal ${JSON.stringify(i.value)}, got ${JSON.stringify(t)}`,location:o});return;case"array":if(!Array.isArray(t)){Q(r,n,"array",t===null?"null":typeof t=="object"?"object":typeof t,o);return}for(let a=0;a<t.length;a+=1)fe(t[a],i.element,`${n}[${a}]`,o,r);return;case"record":if(t===null||Array.isArray(t)||typeof t!="object"){let a=Array.isArray(t)?"array":t===null?"null":typeof t;Q(r,n,"object",a,o);return}for(let[a,s]of Object.entries(t))fe(s,i.value,`${n}.${a}`,o,r);return;case"object":if(t===null||Array.isArray(t)||typeof t!="object"){let a=Array.isArray(t)?"array":t===null?"null":typeof t;Q(r,n,"object",a,o);return}for(let a of Object.keys(t))a in i.fields||r.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}.${a}' is not declared in ${K(i)}`,location:o});for(let[a,s]of Object.entries(i.fields)){if(!(a in t)){s.optional||r.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}.${a}' is required`,location:o});continue}fe(t[a],s.type,`${n}.${a}`,o,r)}return;case"ref":r.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${K(e)}, got ${JSON.stringify(t)}`,location:o});return}}function Q(t,e,n,o,r){t.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${e}' expects ${n}, got ${o}`,location:r})}function je(t,e){switch(t.kind){case"literal":return t.value;case"arrayLiteral":return t.elements.map(n=>je(n,e));case"objectLiteral":{let n={};for(let o of t.properties)n[o.key]=je(o.value,e);return n}default:return}}function Ko(t,e){let n=[],o=0;for(let i of t.members)if(i.kind==="computed"){let a=B(i.expression,e),s=Xo(a);n.push({name:i.name,deps:s,expr:a,location:i.location,order:o}),o+=1}let r={};for(let i of Wo(n,e))r[i.name]={deps:i.deps,expr:i.expr};return{fields:r}}function Wo(t,e){if(t.length<=1)return[...t];let n=new Map(t.map(c=>[c.name,c])),o=new Map,r=new Map,i=new Map;for(let c of t)r.set(c.name,[]),i.set(c.name,0);for(let c of t){let d=Array.from(new Set(c.deps.filter(l=>n.has(l))));o.set(c.name,d),i.set(c.name,d.length);for(let l of d)r.get(l).push(c.name)}let a=t.filter(c=>(i.get(c.name)??0)===0).map(c=>c.name),s=[];for(;a.length>0;){let c=a.shift();s.push(n.get(c));for(let d of r.get(c)??[]){let l=(i.get(d)??0)-1;i.set(d,l),l===0&&Yo(a,d,n)}}if(s.length!==t.length){let c=new Set(s.map(m=>m.name)),d=t.filter(m=>!c.has(m.name)),l=Qo(d[0].name,o),p=l?l.join(" -> "):d.map(m=>m.name).join(", ");return pt(e,"E040",`Circular computed dependency: ${p}`,(l?n.get(l[0]):d[0]).location),[...t]}return s}function Yo(t,e,n){let o=n.get(e)?.order??Number.MAX_SAFE_INTEGER,r=t.length;for(let i=0;i<t.length;i+=1){let a=n.get(t[i])?.order??Number.MAX_SAFE_INTEGER;if(o<a){r=i;break}}t.splice(r,0,e)}function Qo(t,e){let n=new Set,o=[],r=new Set;function i(a){n.add(a),o.push(a),r.add(a);for(let s of e.get(a)??[])if(n.has(s)){if(r.has(s)){let c=o.indexOf(s);return[...o.slice(c),s]}}else{let c=i(s);if(c)return c}return o.pop(),r.delete(a),null}return i(t)}function Xo(t){let e=new Set;function n(o){switch(o.kind){case"lit":case"sys":case"var":return;case"get":o.base===void 0?e.add(o.path.map(r=>r.name).join(".")):n(o.base);return;case"field":n(o.object);return;case"call":for(let r of o.args)n(r);return;case"obj":for(let r of o.fields)n(r.value);return;case"arr":for(let r of o.elements)n(r);return}}return n(t),Array.from(e)}function Jo(t,e){let n={};for(let o of t.members)if(o.kind==="action"){e.currentAction=o.name,e.onceIntentCounters.set(o.name,0);let r=new Set;for(let p of o.params)r.add(p.name);e.actionParams.set(o.name,r);let i=o.params.map(p=>p.name),a=Zt(o.body,e),s,c;if(o.params.length>0){let p={},m={};for(let f of o.params){let T=X(f.typeExpr,e);T&&(p[f.name]=structuredClone(T),m[f.name]={type:H(f.typeExpr),optional:!1})}s={type:"object",required:!0,fields:p},c={kind:"object",fields:m}}let d;o.available&&(d=B(o.available,e));let l;o.dispatchable&&(l=B(o.dispatchable,e,{preferActionParams:!0})),n[o.name]={flow:a,input:s,inputType:c,params:i,available:d,dispatchable:l},e.currentAction=null}return n}function Zt(t,e){return t.length===0?{kind:"seq",steps:[]}:t.length===1?_e(t[0],e):{kind:"seq",steps:t.map(n=>_e(n,e))}}function _e(t,e){switch(t.kind){case"when":return Zo(t,e);case"once":return er(t,e);case"onceIntent":return tr(t,e);case"patch":return nr(t,e);case"effect":return or(t,e);case"fail":return ir(t,e);case"stop":return ar(t,e);case"include":return{kind:"seq",steps:[]}}}function Zo(t,e){let n=B(t.condition,e),o=Zt(t.body,e);return{kind:"if",cond:n,then:o}}function er(t,e){let n=ut(t.marker,e),o=ue("meta","intentId"),r=$e("neq",[U(...en(n)),o]);if(t.condition){let s=B(t.condition,e);r=$e("and",[r,s])}let i={kind:"patch",op:"set",path:mt(n),value:o},a=t.body.map(s=>_e(s,e));return{kind:"if",cond:r,then:{kind:"seq",steps:[i,...a]}}}function tr(t,e){let n=e.currentAction??"unknown",o=e.onceIntentCounters.get(n)??0;e.onceIntentCounters.set(n,o+1);let r=Go(`${n}:${o}:intent`),i=`$mel.guards.intent.${r}`,a=ue("meta","intentId"),s=$e("neq",[U(...en(i)),a]);if(t.condition){let l=B(t.condition,e);s=$e("and",[s,l])}let c={kind:"patch",op:"merge",path:mt("$mel.guards.intent"),value:Le({[r]:a})},d=t.body.map(l=>_e(l,e));return{kind:"if",cond:s,then:{kind:"seq",steps:[c,...d]}}}function nr(t,e){let n=ut(t.path,e),o={kind:"patch",op:t.op,path:mt(n)};if(t.value){let r=B(t.value,e);if(o.value=r,t.op==="set"){let i=t.path.segments[0];if(i.kind==="propertySegment"){let a=e.stateFieldTypes.get(i.name);if(a){let s=a,c=t.path.segments;for(let d=1;d<c.length;d++){let l=c[d],p=s?he(s,e):null;if(!p){s=null;break}if(p.kind==="union"){let m=p.types.filter(f=>{let T=he(f,e);return!(T?.kind==="primitive"&&T.type==="null")&&!(T?.kind==="literal"&&T.value===null)});if(m.length!==1){s=null;break}s=m[0],d-=1;continue}if(l.kind==="propertySegment"&&p.kind==="object"&&p.fields[l.name])s=p.fields[l.name].type;else if(l.kind==="propertySegment"&&p.kind==="record")s=p.value;else if(l.kind==="indexSegment"&&p.kind==="array")s=p.element;else{s=null;break}}if(s){let d=rr(t.value,e);if(d!==void 0){let l=t.path.segments.map(p=>p.kind==="propertySegment"?p.name:"[*]").join(".");fe(d,s,l,t.location,e)}}}}}}return o}function or(t,e){let n={};for(let o of t.args)o.isPath?n[o.name]={kind:"lit",value:ut(o.value,e)}:n[o.name]=B(o.value,e);return{kind:"effect",type:t.effectType,params:n}}function rr(t,e){return je(t,e)}function ir(t,e){let n={kind:"fail",code:t.code};return t.message&&(n.message=B(t.message,e)),n}function ar(t,e){return{kind:"halt",reason:t.reason}}function sr(t){return t.replaceAll("\\","\\\\").replaceAll(".","\\.")}function Fe(...t){return t.map(sr).join(".")}function ut(t,e){let n=[];for(let r of t.segments)if(r.kind==="propertySegment")n.push(r.name);else{let i=B(r.index,e);i.kind==="lit"?n.push(String(i.value)):n.push("*")}let o=n[0];return e.stateFields.has(o)?Fe(...n):e.computedFields.has(o)?Fe(...n):e.currentAction&&e.actionParams.get(e.currentAction)?.has(o)?`input.${Fe(...n)}`:Fe(...n)}function mt(t){return $o(t)}function $e(t,e){return{kind:"call",fn:t,args:e}}function en(t){return t.split(/(?<!\\)\./g).map(e=>e.replaceAll("\\.",".").replaceAll("\\\\","\\"))}function B(t,e,n={}){return w(t,{resolveIdentifier:o=>cr(o,e,n),resolveSystemIdent:o=>lr(o,e)})}function cr(t,e,n={}){return n.preferActionParams&&e.currentAction&&e.actionParams.get(e.currentAction)?.has(t)?U("input",t):e.stateFields.has(t)||e.computedFields.has(t)?U(t):e.currentAction&&e.actionParams.get(e.currentAction)?.has(t)?U("input",t):(e.diagnostics.push({severity:"error",code:"E_UNKNOWN_IDENT",message:`Unknown identifier '${t}'`,location:{start:{line:0,column:0,offset:0},end:{line:0,column:0,offset:0}}}),U(t))}function lr(t,e){let[n,...o]=t;switch(n){case"system":case"meta":case"input":return ue(n,...o);default:return e.diagnostics.push({severity:"error",code:"E_INVALID_SYSTEM",message:`Invalid system identifier namespace '$${n}'`,location:{start:{line:0,column:0,offset:0},end:{line:0,column:0,offset:0}}}),{kind:"lit",value:null}}}function dr(t){return _o(t)}var pr="@meta can attach only to domain, type, type field, state field, computed, or action declarations.",ur="Action-parameter annotations are not part of the current MEL syntax.",tn="Annotation payloads must be JSON-like literals. MEL expressions are not allowed in @meta payloads.",nn="Annotation payload nesting exceeds the current MEL limit of 2 levels.",mr="Annotation target does not map to the emitted DomainSchema.",on=2;function rn(t,e){let n=[],o=new Map,r=t.domain;oe(r.annotations,`domain:${r.name}`,n,o);for(let a of r.types)oe(a.annotations,`type:${a.name}`,n,o),re(a.typeExpr,a.name,0,n,o);for(let a of r.members)switch(a.kind){case"state":for(let s of a.fields)oe(s.annotations,`state_field:${s.name}`,n,o),J(s.typeExpr,n);break;case"computed":oe(a.annotations,`computed:${a.name}`,n,o);break;case"action":oe(a.annotations,`action:${a.name}`,n,o),fr(a,n);for(let s of a.params)J(s.typeExpr,n);break;case"flow":break}let i={};for(let a of[...o.keys()].sort()){if(!gr(e,a)){n.push(O("E057",mr,Er(t,a)??r.location));continue}let s=o.get(a);s&&s.length>0&&(i[a]=Object.freeze(s.map(c=>yr(c))))}return{annotations:Object.freeze({schemaHash:e.hash,entries:Object.freeze(i)}),diagnostics:n}}function oe(t,e,n,o){if(!t||t.length===0)return;let r=[];for(let a of t){let s=a.payload===void 0?{ok:!0,value:void 0}:ft(a.payload,0,n);s.ok&&r.push({tag:a.tag,...s.value===void 0?{}:{payload:s.value}})}if(r.length===0)return;let i=o.get(e);if(i){i.push(...r);return}o.set(e,r)}function re(t,e,n,o,r){switch(t.kind){case"objectType":for(let i of t.fields)i.annotations?.length&&(n===0?oe(i.annotations,`type_field:${e}.${i.name}`,o,r):an(i.annotations,o)),re(i.typeExpr,e,n+1,o,r);return;case"arrayType":re(t.elementType,e,n,o,r);return;case"recordType":re(t.keyType,e,n,o,r),re(t.valueType,e,n,o,r);return;case"unionType":for(let i of t.types)re(i,e,n,o,r);return;case"simpleType":case"literalType":return}}function J(t,e){switch(t.kind){case"objectType":for(let n of t.fields)an(n.annotations,e),J(n.typeExpr,e);return;case"arrayType":J(t.elementType,e);return;case"recordType":J(t.keyType,e),J(t.valueType,e);return;case"unionType":for(let n of t.types)J(n,e);return;case"simpleType":case"literalType":return}}function fr(t,e){for(let n of t.params)hr(n,e)}function hr(t,e){if(t.annotations)for(let n of t.annotations)e.push(O("E054",ur,n.location))}function an(t,e){if(t)for(let n of t)e.push(O("E053",pr,n.location))}function ft(t,e,n){switch(t.kind){case"literal":return t.literalType==="string"||t.literalType==="number"||t.literalType==="boolean"||t.literalType==="null"?{ok:!0,value:t.value}:(n.push(O("E055",tn,t.location)),{ok:!1});case"arrayLiteral":{if(e+1>on)return n.push(O("E056",nn,t.location)),{ok:!1};let o=[];for(let r of t.elements){let i=ft(r,e+1,n);if(!i.ok)return{ok:!1};o.push(i.value)}return{ok:!0,value:o}}case"objectLiteral":{if(e+1>on)return n.push(O("E056",nn,t.location)),{ok:!1};let o={};for(let r of t.properties){let i=ft(r.value,e+1,n);if(!i.ok)return{ok:!1};o[r.key]=i.value}return{ok:!0,value:o}}default:return n.push(O("E055",tn,t.location)),{ok:!1}}}function yr(t){return t.payload===void 0?Object.freeze({tag:t.tag}):Object.freeze({tag:t.tag,payload:ht(t.payload)})}function ht(t){if(Array.isArray(t))return Object.freeze(t.map(e=>ht(e)));if(t!==null&&typeof t=="object"){let e={};for(let[n,o]of Object.entries(t))e[n]=ht(o);return Object.freeze(e)}return t}function gr(t,e){let n=e.indexOf(":");if(n<0)return!1;let o=e.slice(0,n),r=e.slice(n+1);switch(o){case"domain":return t.meta?.name===r||t.id===`mel:${r.toLowerCase()}`;case"type":return Object.hasOwn(t.types,r);case"type_field":{let i=r.indexOf(".");if(i<=0||i!==r.lastIndexOf("."))return!1;let a=r.slice(0,i),s=r.slice(i+1),c=t.types[a];return!c||c.definition.kind!=="object"?!1:Object.hasOwn(c.definition.fields,s)}case"state_field":return Object.hasOwn(t.state.fields,r);case"computed":return Object.hasOwn(t.computed.fields,r);case"action":return Object.hasOwn(t.actions,r);default:return!1}}function Er(t,e){let n=e.indexOf(":");if(n<0)return null;let o=e.slice(0,n),r=e.slice(n+1),i=t.domain;if(o==="domain"&&i.name===r)return i.location;if(o==="type")return i.types.find(a=>a.name===r)?.location??null;if(o==="type_field"){let a=r.indexOf(".");if(a<=0)return null;let s=r.slice(0,a),c=r.slice(a+1),d=i.types.find(l=>l.name===s);return!d||d.typeExpr.kind!=="objectType"?d?.location??null:d.typeExpr.fields.find(l=>l.name===c)?.location??d.location}if(o==="state_field"){for(let a of i.members){if(a.kind!=="state")continue;let s=a.fields.find(c=>c.name===r);if(s)return s.location}return null}return o==="computed"?i.members.find(a=>a.kind==="computed"&&a.name===r)?.location??null:o==="action"?i.members.find(a=>a.kind==="action"&&a.name===r)?.location??null:null}var yt=16;function N(t){return structuredClone(t)}function A(t,e,n,o,r){let i=`${n}:${r.start.offset}:${r.end.offset}:${o}`;e.has(i)||(e.add(i),t.push(O(n,o,r)))}function kr(t){let e=new Map,n=new Set,o=new Map,r=new Set,i=new Map;for(let a of t.types)o.set(a.name,a);for(let a of t.members)switch(a.kind){case"state":for(let s of a.fields)e.set(s.name,s.typeExpr);break;case"computed":n.add(a.name);break;case"action":r.add(a.name);break;case"flow":i.has(a.name)||i.set(a.name,a);break}return{stateTypes:e,computedNames:n,typeDefs:o,actionNames:r,flows:i}}function Nr(t){let e=new Map;for(let n of t.params)e.set(n.name,n.typeExpr);return e}function Tr(t){let e=new Map;for(let n of t.params)e.set(n.name,n.typeExpr);return e}function br(t,e,n,o){let r=new Map;for(let i of e.flows.values()){r.set(i.name,[]),e.actionNames.has(i.name)&&A(n,o,"E022",`Flow '${i.name}' conflicts with action '${i.name}'.`,i.location);for(let s of i.params)(e.stateTypes.has(s.name)||e.computedNames.has(s.name)||e.typeDefs.has(s.name))&&A(n,o,"E021",`Flow parameter '${s.name}' conflicts with a top-level identifier.`,s.location);let a=Nr(i);for(let s of i.body)xr(s,i.name,a,e,n,o,r.get(i.name))}for(let i of t.members)if(i.kind==="action"){let a=Tr(i);for(let s of i.body)Sr(s,a,e,n,o)}return r}function Sr(t,e,n,o,r){switch(t.kind){case"include":Ue(t,e,n,o,r);break;case"when":for(let i of t.body)ae(i,e,n,o,r);break;case"once":for(let i of t.body)ae(i,e,n,o,r);break;case"onceIntent":for(let i of t.body)ae(i,e,n,o,r);break;case"fail":case"stop":break}}function ae(t,e,n,o,r){switch(t.kind){case"include":A(o,r,"E016","include is only allowed at action or flow body top-level.",t.location),Ue(t,e,n,o,r);break;case"when":for(let i of t.body)ae(i,e,n,o,r);break;case"once":for(let i of t.body)ae(i,e,n,o,r);break;case"onceIntent":for(let i of t.body)ae(i,e,n,o,r);break;case"patch":case"effect":case"fail":case"stop":break}}function xr(t,e,n,o,r,i,a){switch(t.kind){case"include":Ue(t,n,o,r,i)&&a.push({target:t.flowName,location:t.location});break;case"when":for(let s of t.body)Ge(s,e,n,o,r,i);break;case"once":A(r,i,"E017","once() is not allowed in flow bodies.",t.location);break;case"onceIntent":A(r,i,"E018","onceIntent is not allowed in flow bodies.",t.location);break;case"patch":A(r,i,"E019","patch is not allowed in flow bodies.",t.location);break;case"effect":A(r,i,"E020","effect is not allowed in flow bodies.",t.location);break}}function Ge(t,e,n,o,r,i){switch(t.kind){case"include":A(r,i,"E016","include is only allowed at action or flow body top-level.",t.location),Ue(t,n,o,r,i);break;case"when":for(let a of t.body)Ge(a,e,n,o,r,i);break;case"once":A(r,i,"E017","once() is not allowed in flow bodies.",t.location);for(let a of t.body)Ge(a,e,n,o,r,i);break;case"onceIntent":A(r,i,"E018","onceIntent is not allowed in flow bodies.",t.location);for(let a of t.body)Ge(a,e,n,o,r,i);break;case"patch":A(r,i,"E019","patch is not allowed in flow bodies.",t.location);break;case"effect":A(r,i,"E020","effect is not allowed in flow bodies.",t.location);break;case"fail":case"stop":break}}function Ue(t,e,n,o,r){let i=n.flows.get(t.flowName);if(!i)return A(o,r,"E015",`'${t.flowName}' is not a declared flow.`,t.location),!1;if(t.args.length!==i.params.length)return A(o,r,"E023",`include '${t.flowName}' expected ${i.params.length} argument(s), got ${t.args.length}.`,t.location),!0;for(let a=0;a<t.args.length;a+=1){let s=t.args[a],c=i.params[a],d=ye(s,e,n);if(!d)continue;ie(d,c.typeExpr,n)===!1&&A(o,r,"E024",`include '${t.flowName}' argument ${a+1} is not assignable to parameter '${c.name}'.`,s.location)}return!0}function vr(t,e,n,o){function r(i,a,s){s.add(i);for(let c of t.get(i)??[]){if(a+1>yt){A(n,o,"E014",`Include expansion depth exceeds limit (${yt}).`,c.location);continue}if(s.has(c.target)){A(n,o,"E013","Circular include detected.",c.location);continue}r(c.target,a+1,new Set(s))}}for(let i of e.flows.keys())r(i,1,new Set)}function I(t,e){switch(t.kind){case"identifier":return e.has(t.name)?N(e.get(t.name)):N(t);case"systemIdent":case"literal":case"iterationVar":return N(t);case"functionCall":return{...N(t),args:t.args.map(n=>I(n,e))};case"binary":return{...N(t),left:I(t.left,e),right:I(t.right,e)};case"unary":return{...N(t),operand:I(t.operand,e)};case"ternary":return{...N(t),condition:I(t.condition,e),consequent:I(t.consequent,e),alternate:I(t.alternate,e)};case"propertyAccess":return{...N(t),object:I(t.object,e)};case"indexAccess":return{...N(t),object:I(t.object,e),index:I(t.index,e)};case"objectLiteral":return{...N(t),properties:t.properties.map(n=>({...N(n),value:I(n.value,e)}))};case"arrayLiteral":return{...N(t),elements:t.elements.map(n=>I(n,e))}}}function Ar(t,e){switch(t.kind){case"when":return[sn(t,e)];case"fail":return[{...N(t),message:t.message?I(t.message,e):void 0}];case"stop":return[N(t)];case"patch":case"effect":case"once":case"onceIntent":case"include":return[]}}function sn(t,e){return{...N(t),condition:I(t.condition,e),body:t.body.flatMap(n=>Ar(n,e))}}function wr(t,e,n){let o=new Map;for(let r=0;r<t.params.length;r+=1)o.set(t.params[r].name,I(e.args[r],n));return o}function Cr(t,e,n,o,r){switch(t.kind){case"when":return[sn(t,n)];case"include":return cn(t,e,n,o,r);case"once":case"onceIntent":case"patch":case"effect":return[]}}function cn(t,e,n,o,r){let i=e.flows.get(t.flowName);if(!i||t.args.length!==i.params.length||o>yt||r.includes(t.flowName))return[];let a=wr(i,t,n),s=[...r,t.flowName];return i.body.flatMap(c=>Cr(c,e,a,o+1,s))}function se(t){switch(t.kind){case"when":return[{...N(t),body:t.body.flatMap(e=>se(e))}];case"once":return[{...N(t),body:t.body.flatMap(e=>se(e))}];case"onceIntent":return[{...N(t),body:t.body.flatMap(e=>se(e))}];case"include":return[];case"patch":case"effect":case"fail":case"stop":return[N(t)]}}function Ir(t,e,n){switch(t.kind){case"include":return cn(t,e,new Map,n,[]);case"when":return[{...N(t),body:t.body.flatMap(o=>se(o))}];case"once":return[{...N(t),body:t.body.flatMap(o=>se(o))}];case"onceIntent":return[{...N(t),body:t.body.flatMap(o=>se(o))}];case"fail":case"stop":return[N(t)]}}function Pr(t,e){let n=[];for(let o of t.domain.members)switch(o.kind){case"state":case"computed":n.push(N(o));break;case"action":n.push({...N(o),body:o.body.flatMap(r=>Ir(r,e,1))});break;case"flow":break}return{...N(t),domain:{...N(t.domain),types:t.domain.types.map(o=>N(o)),members:n}}}function ye(t,e,n){switch(t.kind){case"literal":return{kind:"literalType",value:t.value,location:t.location};case"identifier":return e.get(t.name)??n.stateTypes.get(t.name)??null;case"propertyAccess":{let o=ye(t.object,e,n);return ln(o,t.property,n)}case"indexAccess":{let o=ye(t.object,e,n);return dn(o,n)}case"objectLiteral":return{kind:"objectType",fields:t.properties.map(o=>{let r=ye(o.value,e,n);return r?{kind:"typeField",name:o.key,typeExpr:r,optional:!1,location:o.location}:null}).filter(o=>o!==null),location:t.location};case"arrayLiteral":{if(t.elements.length===0)return null;let o=ye(t.elements[0],e,n);return o?{kind:"arrayType",elementType:o,location:t.location}:null}case"systemIdent":case"functionCall":case"binary":case"unary":case"ternary":case"iterationVar":return null}}function ge(t,e,n=new Set){return t?t.kind==="simpleType"&&e.typeDefs.has(t.name)?n.has(t.name)?null:(n.add(t.name),ge(e.typeDefs.get(t.name).typeExpr,e,n)):t:null}function ln(t,e,n){let o=ge(t,n);if(!o)return null;if(o.kind==="objectType")return o.fields.find(i=>i.name===e)?.typeExpr??null;if(o.kind==="unionType")for(let r of o.types){if(r.kind==="simpleType"&&r.name==="null")continue;let i=ln(r,e,n);if(i)return i}return null}function dn(t,e){let n=ge(t,e);if(!n)return null;if(n.kind==="arrayType")return n.elementType;if(n.kind==="recordType")return n.valueType;if(n.kind==="unionType")for(let o of n.types){if(o.kind==="simpleType"&&o.name==="null")continue;let r=dn(o,e);if(r)return r}return null}function ie(t,e,n){let o=ge(t,n),r=ge(e,n);if(!o||!r)return null;if(r.kind==="unionType"){let i=r.types.map(a=>ie(o,a,n));return i.includes(!0)?!0:i.every(a=>a===!1)?!1:null}if(o.kind==="unionType"){let i=o.types.map(a=>ie(a,r,n));return i.every(a=>a===!0)?!0:i.some(a=>a===!1)?!1:null}if(r.kind==="simpleType"){if(o.kind==="simpleType")return o.name===r.name;if(o.kind==="literalType")return r.name==="null"?o.value===null:typeof o.value===r.name}if(r.kind==="literalType")return o.kind!=="literalType"?!1:o.value===r.value;if(r.kind==="arrayType")return o.kind!=="arrayType"?!1:ie(o.elementType,r.elementType,n);if(r.kind==="objectType"){if(o.kind!=="objectType")return!1;for(let i of r.fields){let a=o.fields.find(c=>c.name===i.name);if(!a){if(i.optional)continue;return!1}let s=ie(a.typeExpr,i.typeExpr,n);if(s!==!0)return s}return!0}return r.kind==="recordType"?o.kind!=="recordType"?null:ie(o.valueType,r.valueType,n):null}function pn(t){let e=kr(t.domain),n=[],o=new Set,r=br(t.domain,e,n,o);return vr(r,e,n,o),{program:Pr(t,e),diagnostics:n}}var Mr=new Set(["$item","$index","$array"]);function fn(t){let e=Object.keys(t.state.fields).filter(l=>!l.startsWith("$")),n=Dr(t),o=new Set(n),r=new Set(e),i=Object.keys(t.actions),a=[...e.map(l=>({id:gt(l),kind:"state",name:l})),...n.map(l=>({id:Et(l),kind:"computed",name:l})),...i.map(l=>({id:mn(l),kind:"action",name:l}))],s=new Set,c=[],d=(l,p,m)=>{if(!l||!p)return;let f=`${l}|${m}|${p}`;s.has(f)||(s.add(f),c.push({from:l,to:p,relation:m}))};for(let l of n){let p=t.computed.fields[l];if(p)for(let m of p.deps)d(un(m,t,o,r),Et(l),"feeds")}for(let l of i){let p=t.actions[l],m=mn(l);for(let f of Rr(p.flow,t))r.has(f)&&d(m,gt(f),"mutates");if(p.available)for(let f of kn(p.available))d(un(f,t,o,r),m,"unlocks")}return Fr({nodes:a,edges:c})}function Dr(t){let e=t.computed.fields,n=new Map,o=(r,i)=>{let a=n.get(r);if(a!==void 0)return a;if(i.has(r))return!1;i.add(r);let s=e[r];if(!s)return i.delete(r),n.set(r,!0),!0;for(let c of kn(s.expr)){if(En(c))return i.delete(r),n.set(r,!1),!1;let d=hn(c,e);if(d!==null&&!o(d,i))return i.delete(r),n.set(r,!1),!1}return i.delete(r),n.set(r,!0),!0};return Object.keys(e).filter(r=>o(r,new Set))}function Rr(t,e){let n=new Set,o=(r,i)=>{if(r)switch(r.kind){case"seq":r.steps.forEach(a=>o(a,i));return;case"if":o(r.then,i),o(r.else,i);return;case"patch":{let a=Lr(r.path);a&&n.add(a);return}case"effect":{let a=Or(r.params.into);a&&n.add(a);return}case"call":{if(i.has(r.flow))return;let a=e.actions[r.flow];if(!a)return;let s=new Set(i);s.add(r.flow),o(a.flow,s);return}case"halt":case"fail":return}};return o(t,new Set),[...n]}function Lr(t){let[e]=t;return!e||e.kind!=="prop"||e.name.startsWith("$")?null:e.name}function Or(t){return typeof t!="object"||t===null||t.kind!=="lit"||typeof t.value!="string"?null:yn(t.value)}function un(t,e,n,o){let r=hn(t,e.computed.fields);if(r!==null&&n.has(r))return Et(r);if(En(t))return null;let i=yn(t);return!i||!o.has(i)?null:gt(i)}function hn(t,e){if(Object.prototype.hasOwnProperty.call(e,t))return t;if(!t.startsWith("computed."))return null;let n=t.slice(9);return Object.prototype.hasOwnProperty.call(e,n)?n:null}function yn(t){let e=gn(t),n=e.startsWith("data.")?e.slice(5):e,o=/^([^.[\]]+)/.exec(n);if(!o)return null;let[r]=o.slice(1);return!r||r.startsWith("$")?null:r}function gn(t){return t.startsWith("/")?t.slice(1).replace(/\//g,"."):t}function En(t){let e=gn(t),n=e.startsWith("data.")?e.slice(5):e,r=/^([^.[\]]+)/.exec(n)?.[1]??"";return r.startsWith("$")?!Mr.has(r):!1}function kn(t){let e=[],n=new WeakSet,o=r=>{if(r==null)return;if(Array.isArray(r)){r.forEach(o);return}if(typeof r!="object")return;let i=r;if(!n.has(i)&&(n.add(i),i.kind!=="lit")){if(i.kind==="get"&&typeof i.path=="string"){e.push(i.path);return}for(let a of Object.values(i))o(a)}};return o(t),e}function gt(t){return`state:${t}`}function Et(t){return`computed:${t}`}function mn(t){return`action:${t}`}function Fr(t){return Object.freeze({nodes:Object.freeze(t.nodes.map(e=>Object.freeze(e))),edges:Object.freeze([...t.edges].sort(jr).map(e=>Object.freeze(e)))})}function jr(t,e){return t.from.localeCompare(e.from)||t.to.localeCompare(e.to)||t.relation.localeCompare(e.relation)}import{sha256Sync as Be}from"@manifesto-ai/core";function Nn(t){return t.kind==="literal"&&t.literalType==="boolean"&&t.value===!0}function ce(t){return w(t)}var qe=class{constructor(e){this.deps=e;this.exprValidator=new Nt(e.mapLocation)}conditionComposer=new kt;exprValidator;collect(e,n,o,r){return this.collectPatchStatements(e,n,o,r)}collectPatchStatements(e,n,o,r){let i=[];for(let a of e){if(a.kind==="patch"){this.exprValidator.validatePath(a.path,n),a.value&&this.exprValidator.validateExpr(a.value,n),i.push({patch:a,condition:r});continue}if(a.kind==="when"){this.exprValidator.validateExpr(a.condition,n);let s=r;try{s=this.conditionComposer.and(r,this.deps.toMelExpr(a.condition))}catch(m){n.push({severity:"error",code:"E_LOWER",message:m.message,location:this.deps.mapLocation(a.condition.location)})}let c=Be(`${o.actionName}:${o.whenCounter}:when`);o.whenCounter+=1;let d={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:a.location},{kind:"propertySegment",name:"__whenGuards",location:a.location},{kind:"propertySegment",name:c,location:a.location}],location:a.location},l=Ee(d),p=this.collectPatchStatements(a.body,n,o,void 0).map(m=>({patch:m.patch,condition:this.conditionComposer.and(l,m.condition)}));i.push({patch:{kind:"patch",op:"set",path:d,value:{kind:"literal",literalType:"boolean",value:!0,location:a.location},location:a.location},condition:s},...p,{patch:{kind:"patch",op:"unset",path:d,location:a.location}});continue}if(a.kind==="once"){this.exprValidator.validatePath(a.marker,n);let s=r,c=Ee(a.marker),d=a.marker,l=a.location,p={kind:"call",fn:"neq",args:[c,{kind:"sys",path:["meta","intentId"]}]};if(a.condition){this.exprValidator.validateExpr(a.condition,n);try{p=this.conditionComposer.and(p,this.deps.toMelExpr(a.condition))??p}catch(_){n.push({severity:"error",code:"E_LOWER",message:_.message,location:this.deps.mapLocation(a.condition.location)})}}s=this.conditionComposer.and(r,p);let m=Be(`${o.actionName}:${o.onceCounter}:once`);o.onceCounter+=1;let f={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:l},{kind:"propertySegment",name:"__onceScopeGuards",location:l},{kind:"propertySegment",name:m,location:l}],location:l},T=Ee(f),S=this.collectPatchStatements(a.body,n,o,T);i.push({patch:{kind:"patch",op:"set",path:f,value:{kind:"literal",literalType:"boolean",value:!0,location:l},location:l},condition:s},{patch:{kind:"patch",op:"set",path:d,value:{kind:"systemIdent",path:["meta","intentId"],location:l},location:l},condition:T},...S,{patch:{kind:"patch",op:"unset",path:f,location:l},condition:s});continue}if(a.kind==="onceIntent"){let s=Be(`${o.actionName}:${o.onceCounter}:onceIntent`);o.onceCounter+=1;let c={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:a.location},{kind:"propertySegment",name:"__onceScopeGuards",location:a.location},{kind:"propertySegment",name:s,location:a.location}],location:a.location},d=Ee(c),l=Be(`${o.actionName}:${o.onceIntentCounter}:intent`);o.onceIntentCounter+=1;let p=a.location,f={kind:"call",fn:"neq",args:[Ee({kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:p},{kind:"propertySegment",name:"guards",location:p},{kind:"propertySegment",name:"intent",location:p},{kind:"propertySegment",name:l,location:p}],location:p}),{kind:"sys",path:["meta","intentId"]}]};if(a.condition){this.exprValidator.validateExpr(a.condition,n);try{f=this.conditionComposer.and(f,this.deps.toMelExpr(a.condition))??f}catch(q){n.push({severity:"error",code:"E_LOWER",message:q.message,location:this.deps.mapLocation(a.condition.location)})}}let T=this.conditionComposer.and(r,f),S={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:p},{kind:"propertySegment",name:"guards",location:p},{kind:"propertySegment",name:"intent",location:p}],location:p},_=this.collectPatchStatements(a.body,n,o,d);i.push({patch:{kind:"patch",op:"set",path:c,value:{kind:"literal",literalType:"boolean",value:!0,location:p},location:p},condition:T},{patch:{kind:"patch",op:"merge",path:S,value:{kind:"objectLiteral",properties:[{kind:"objectProperty",key:l,value:{kind:"systemIdent",path:["meta","intentId"],location:p},location:p}],location:p},location:p},condition:d},..._,{patch:{kind:"patch",op:"unset",path:c,location:p},condition:T});continue}n.push({severity:"error",code:"E_UNSUPPORTED_STMT",message:`Unsupported statement '${a.kind}' in patch text. Only patch statements are allowed.`,location:this.deps.mapLocation(a.location)})}return i}};function Tn(t){return{op:t.patch.op,path:_r(t.patch.path),...t.condition?{condition:t.condition}:void 0,...t.patch.value?{value:ce(t.patch.value)}:void 0}}function Ee(t){let e=t.segments,n;for(let o of e){if(o.kind==="propertySegment"){let r={kind:"prop",name:o.name};n?n={kind:"call",fn:"field",args:[n,{kind:"lit",value:o.name}]}:n={kind:"get",path:[r]};continue}if(!n)throw new Error("Path cannot start with index access in compileMelPatch guard.");n={kind:"call",fn:"at",args:[n,ce(o.index)]}}if(!n)throw new Error("Empty patch guard path.");return n}function _r(t){return t.segments.map(e=>e.kind==="propertySegment"?{kind:"prop",name:e.name}:{kind:"expr",expr:ce(e.index)})}var kt=class{and(e,n){return e?n?{kind:"call",fn:"and",args:[e,n]}:e:n}},Nt=class{constructor(e){this.mapLocation=e}symbols={stateTypes:new Map,computedDecls:new Map,typeDefs:new Map,computedTypeCache:new Map,computedTypeInFlight:new Set};validatePath(e,n){for(let o of e.segments)o.kind==="indexSegment"&&this.validateExpr(o.index,n)}validateExpr(e,n){switch(e.kind){case"functionCall":(e.name==="eq"||e.name==="neq")&&e.args.length>=2&&this.validatePrimitiveEquality(e.args[0],e.args[1],e.location,n);for(let o of e.args)this.validateExpr(o,n);return;case"binary":(e.operator==="=="||e.operator==="!=")&&this.validatePrimitiveEquality(e.left,e.right,e.location,n),this.validateExpr(e.left,n),this.validateExpr(e.right,n);return;case"unary":this.validateExpr(e.operand,n);return;case"ternary":this.validateExpr(e.condition,n),this.validateExpr(e.consequent,n),this.validateExpr(e.alternate,n);return;case"propertyAccess":this.validateExpr(e.object,n);return;case"indexAccess":this.validateExpr(e.object,n),this.validateExpr(e.index,n);return;case"objectLiteral":for(let o of e.properties)this.validateExpr(o.value,n);return;case"arrayLiteral":for(let o of e.elements)this.validateExpr(o,n);return;case"literal":case"identifier":case"systemIdent":case"iterationVar":return}}validatePrimitiveEquality(e,n,o,r){let i=$(e,new Map,this.symbols),a=$(n,new Map,this.symbols);i!=="nonprimitive"&&a!=="nonprimitive"||r.push({severity:"error",code:"E_TYPE_MISMATCH",message:"eq/neq operands must be primitive types (null, boolean, number, string)",location:this.mapLocation(o)})}};function Sn(t){let e=[],n=0;for(let o of t)e.push(n),n+=o.length+1;return e}function xn(t,e){return n=>vn(n,t,e)}function Tt(t,e,n){return t.map(o=>$r(o,e,n))}function $r(t,e,n){return{...t,location:vn(t.location,e,n)}}function vn(t,e,n){return{...t,start:bn(t.start,e,n),end:bn(t.end,e,n)}}function bn(t,e,n){let o=t.line-3,r=e.length,i=Math.min(Math.max(o,1),r),a=n[i-1]??0,s=e[i-1]??"",c=Math.max(s.length+1,1),d=Math.min(Math.max(t.column-6,1),c);return{line:i,column:d,offset:Math.max(a+d-1,0)}}var ke="__compileMelPatch",Ur="__patchDomain",Br=" ";function An(t,e){let n=[],o=[],r=[],i=t.split(`
9
- `),a=Sn(i),s=xn(i,a),c=qr(t,ke),d=performance.now(),l;try{let v=be(c);l=v.tokens;let L=Tt(v.diagnostics.filter(Te=>Te.severity==="error"),i,a);if(L.length>0)return r.push(...L),n.push({phase:"lex",durationMs:performance.now()-d,details:{tokenCount:l.length}}),{ops:[],trace:n,warnings:o,errors:r}}catch(v){return r.push({severity:"error",code:"E_LEX",message:v.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"lex",durationMs:performance.now()-d}),{ops:[],trace:n,warnings:o,errors:r}}n.push({phase:"lex",durationMs:performance.now()-d,details:{tokenCount:l.length}});let p=performance.now(),m;try{let v=Se(l),L=Tt(v.diagnostics,i,a),Te=L.filter(Ve=>Ve.severity==="error"),ze=L.filter(Ve=>Ve.severity!=="error");if(Te.length>0)return r.push(...Te),o.push(...ze),n.push({phase:"parse",durationMs:performance.now()-p}),{ops:[],trace:n,warnings:o,errors:r};if(!v.program)return r.push({severity:"error",code:"E_PARSE",message:"Failed to parse MEL patch program",location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),o.push(...ze),n.push({phase:"parse",durationMs:performance.now()-p}),{ops:[],trace:n,warnings:o,errors:r};m=v.program,o.push(...ze)}catch(v){return r.push({severity:"error",code:"E_PARSE",message:v.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"parse",durationMs:performance.now()-p}),{ops:[],trace:n,warnings:o,errors:r}}n.push({phase:"parse",durationMs:performance.now()-p});let f=performance.now(),T={actionName:e.actionName,onceCounter:0,onceIntentCounter:0,whenCounter:0},S=m.domain.members.find(v=>v.kind==="action"&&v.name===ke);if(!S)return r.push({severity:"error",code:"E_ANALYZE",message:`Synthetic patch action '${ke}' not found during parsing`,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"analyze",durationMs:performance.now()-f}),{ops:[],trace:n,warnings:o,errors:r};let _=i.length+3+2;if(S.location.end.line!==_)return r.push({severity:"error",code:"E_PATCH_WRAPPER",message:`Malformed synthetic patch wrapper for action '${ke}'.`,location:s(S.location)}),n.push({phase:"analyze",durationMs:performance.now()-f}),{ops:[],trace:n,warnings:o,errors:r};let[q]=S.body;if(!q||q.kind!=="when"||!Nn(q.condition)||S.body.length!==1)return r.push({severity:"error",code:"E_PATCH_WRAPPER",message:`Malformed synthetic patch wrapper for action '${ke}'.`,location:s(S.location)}),n.push({phase:"analyze",durationMs:performance.now()-f}),{ops:[],trace:n,warnings:o,errors:r};let g=new qe({mapLocation:s,toMelExpr:ce}).collect(q.body,r,T,void 0);if(r.length===0&&t.trim()!==""&&g.length===0&&r.push({severity:"error",code:"E_PATCH_WRAPPER",message:"Patch wrapper parsing produced no patch statements. The patch source may be malformed.",location:s(q.location)}),n.push({phase:"analyze",durationMs:performance.now()-f,details:{count:g.length}}),r.length>0)return{ops:[],trace:n,warnings:o,errors:r};let R=performance.now(),W={mode:"action",allowSysPaths:e.allowSysPaths??{prefixes:["meta","input"]},fnTableVersion:e.fnTableVersion??"1.0",actionName:e.actionName},F=[];for(let v of g)try{let L=Tn(v);F.push(Re(L,W))}catch(L){L instanceof j?r.push({severity:"error",code:L.code,message:L.message,location:s(v.patch.location)}):L instanceof Error?r.push({severity:"error",code:"E_LOWER",message:L.message,location:s(v.patch.location)}):r.push({severity:"error",code:"E_LOWER",message:"Unknown lowering failure",location:s(v.patch.location)})}return n.push({phase:"lower",durationMs:performance.now()-R,details:{count:F.length}}),r.length>0?{ops:[],trace:n,warnings:o,errors:r}:{ops:F,trace:n,warnings:o,errors:r}}function qr(t,e){let n=t.split(`
10
- `).map(o=>`${Br}${o}`).join(`
11
- `);return[`domain ${Ur} {`,` action ${e}() {`," when true {",n," }"," }","}"].join(`
12
- `)}function zr(t,e){let n=wn(t,e);return{schema:n.schema,trace:n.trace,warnings:n.warnings,errors:n.errors}}function Vr(t,e){let n=wn(t,e);return n.errors.length>0||!n.schema||!n.annotations?{module:null,trace:n.trace,warnings:n.warnings,errors:n.errors}:{module:Hr(n.schema,n.annotations),trace:n.trace,warnings:n.warnings,errors:n.errors}}function wn(t,e){let n=[],o=[],r=[],i=performance.now(),a;try{let g=be(t);a=g.tokens;let R=g.diagnostics.filter(F=>F.severity==="error");if(R.length>0)return r.push(...R),n.push({phase:"lex",durationMs:performance.now()-i,details:{tokenCount:a.length}}),{program:null,schema:null,annotations:null,trace:n,warnings:o,errors:r};let W=g.diagnostics.filter(F=>F.severity==="warning");o.push(...W)}catch(g){let R=g;return r.push({severity:"error",code:"E_LEX",message:R.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"lex",durationMs:performance.now()-i}),{program:null,schema:null,annotations:null,trace:n,warnings:o,errors:r}}n.push({phase:"lex",durationMs:performance.now()-i,details:{tokenCount:a.length}});let s=performance.now(),c;try{let g=Se(a),R=g.diagnostics.filter(W=>W.severity==="error");if(R.length>0)return r.push(...R),n.push({phase:"parse",durationMs:performance.now()-s}),{program:null,schema:null,annotations:null,trace:n,warnings:o,errors:Ne(r)};c=g.program}catch(g){let R=g;return r.push({severity:"error",code:"E_PARSE",message:R.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"parse",durationMs:performance.now()-s}),{program:null,schema:null,annotations:null,trace:n,warnings:o,errors:r}}n.push({phase:"parse",durationMs:performance.now()-s});let d=performance.now(),l=pn(c),p=l.diagnostics.filter(g=>g.severity==="error"),m=l.diagnostics.filter(g=>g.severity==="warning"),f=Mt(l.program),T=zt(l.program),S=[...p,...f.diagnostics.filter(g=>g.severity==="error"),...T.diagnostics.filter(g=>g.severity==="error")],_=[...m,...f.diagnostics.filter(g=>g.severity==="warning"),...T.diagnostics.filter(g=>g.severity==="warning")];if(o.push(..._),n.push({phase:"analyze",durationMs:performance.now()-d}),S.length>0)return r.push(...S),{program:l.program,schema:null,annotations:null,trace:n,warnings:o,errors:Ne(r)};let q=performance.now(),le=Jt(l.program);n.push({phase:"generate",durationMs:performance.now()-q});for(let g of le.diagnostics)g.severity==="warning"?o.push(g):r.push(g);if(le.schema){let g=rn(l.program,le.schema),R=g.diagnostics.filter(F=>F.severity==="warning"),W=g.diagnostics.filter(F=>F.severity==="error");return o.push(...R),r.push(...W),W.length>0?{program:l.program,schema:null,annotations:null,trace:n,warnings:o,errors:Ne(r)}:{program:l.program,schema:le.schema,annotations:g.annotations,trace:n,warnings:o,errors:Ne(r)}}return{program:l.program,schema:null,annotations:null,trace:n,warnings:o,errors:Ne(r)}}function Hr(t,e){return Object.freeze({schema:t,graph:St(fn(t)),annotations:e})}function St(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){for(let e of t)St(e);return Object.freeze(t)}for(let e of Object.values(t))St(e);return Object.freeze(t)}var bt=10;function Ne(t){if(t.length<=bt)return t;let e=t.slice(0,bt);return e.push({severity:"error",code:"E_TOO_MANY",message:`... and ${t.length-bt} more error(s). Fix the errors above first.`,location:{start:{line:0,column:0,offset:0},end:{line:0,column:0,offset:0}}}),e}function Kr(t,e){return An(t,e)}export{He as a,Cn as b,Wr as c,xt as d,vt as e,Ke as f,At as g,wt as h,Qr as i,h as j,We as k,be as l,ii as m,ai as n,Ct as o,Ye as p,It as q,ci as r,li as s,Pt as t,Qe as u,Se as v,xe as w,Xe as x,Mt as y,O as z,Dt as A,ki as B,In as C,Ni as D,Ti as E,nt as F,zt as G,ot as H,rt as I,it as J,at as K,eo as L,j as M,Pe as N,y as O,Me as P,st as Q,to as R,ct as S,no as T,u as U,xo as V,wo as W,Re as X,Bo as Y,Jt as Z,rn as _,pn as $,fn as aa,zr as ba,Vr as ca,Kr as da};