@manifesto-ai/compiler 3.5.0 → 3.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -2
- package/dist/annotations.d.ts +28 -0
- package/dist/api/compile-mel.d.ts +26 -0
- package/dist/api/index.d.ts +2 -2
- package/dist/chunk-7BIJ7ZQJ.js +3 -0
- package/dist/chunk-E4EHOM7R.js +4 -0
- package/dist/chunk-YIGJ5PGV.js +12 -0
- package/dist/esbuild.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +15 -15
- package/dist/lexer/tokens.d.ts +1 -1
- package/dist/mel-module.d.ts +1 -0
- package/dist/node-loader.js +1 -1
- package/dist/parser/ast.d.ts +15 -0
- package/dist/parser/parser.d.ts +4 -0
- package/dist/rollup.js +1 -1
- package/dist/rspack.js +1 -1
- package/dist/source-map.d.ts +70 -0
- package/dist/vite.js +1 -1
- package/dist/webpack.js +1 -1
- package/package.json +4 -4
- package/dist/chunk-H5YT4Z3G.js +0 -4
- package/dist/chunk-WE6GIOLD.js +0 -4
- package/dist/chunk-XIAVDXPY.js +0 -12
package/dist/chunk-XIAVDXPY.js
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
var Ge={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"},an=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 cr(t){return t in Ge}function ft(t){return an.has(t)}function yt(t){return Object.hasOwn(Ge,t)?Ge[t]:void 0}function qe(t,e,n,i){return{kind:t,lexeme:e,location:n,value:i}}function gt(t,e,n){return{line:t,column:e,offset:n}}function Et(t,e,n){return{start:t,end:e,source:n}}function dr(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 He=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(qe("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(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,i=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 o=this.advance();switch(o){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 '\\${o}'`),r+=o}}else r+=this.advance()}if(this.isAtEnd()){this.error(`Unterminated string starting at line ${n}:${i}`);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),i=parseInt(n,16);this.addToken("NUMBER",i);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(ft(e)){this.error(`'${e}' is a reserved keyword and cannot be used`),this.addToken("ERROR");return}let n=yt(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 Et(e,n,this.sourcePath)}positionAt(e){let n=1,i=0;for(let r=0;r<e;r++)this.source[r]===`
|
|
7
|
-
`&&(n++,i=r+1);return gt(n,e-i+1,e)}addToken(e,n){let i=this.source.slice(this.start,this.current);this.tokens.push(qe(e,i,this.currentLocation(),n))}error(e,n="MEL_LEXER"){let i=this.currentLocation();this.diagnostics.push({severity:"error",code:n,message:e,location:i,source:this.getSourceLine(i.start.line)})}getSourceLine(e){return this.source.split(`
|
|
8
|
-
`)[e-1]??""}};function ye(t,e){return new He(t,e).tokenize()}function kr(t){return["literal","identifier","systemIdent","iterationVar","propertyAccess","indexAccess","functionCall","unary","binary","ternary","objectLiteral","arrayLiteral"].includes(t.kind)}function Tr(t){return["when","once","onceIntent","patch","effect","fail","stop"].includes(t.kind)}var kt=(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))(kt||{});function Ve(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 Tt(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 br(t){return Ve(t)!==0}function Sr(t){return t==="BANG"||t==="MINUS"}function Nt(t){return t==="QUESTION"||t==="QUESTION_QUESTION"}var ze=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 i=this.parseDomain();return{kind:"program",imports:n,domain:i,location:h(e,i.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 i=this.consume("STRING","Expected string after 'from'");return{kind:"import",names:n,from:i.value,location:h(e,i.location)}}parseDomain(){let e=this.consume("DOMAIN","Expected 'domain'").location,n=this.consume("IDENTIFIER","Expected domain name").lexeme;this.consume("LBRACE","Expected '{' after domain name");let i=[];for(;this.check("TYPE")&&!this.isAtEnd();)i.push(this.parseTypeDecl());let r=[];for(;!this.check("RBRACE")&&!this.isAtEnd();)if(this.check("TYPE"))i.push(this.parseTypeDecl());else{let a=this.parseDomainMember();a&&r.push(a)}let o=this.consume("RBRACE","Expected '}' to close domain").location;return{kind:"domain",name:n,types:i,members:r,location:h(e,o)}}parseTypeDecl(){let e=this.consume("TYPE","Expected 'type'").location,n=this.consume("IDENTIFIER","Expected type name").lexeme;this.consume("EQ","Expected '=' after type name");let i=this.parseTypeExpr();return{kind:"typeDecl",name:n,typeExpr:i,location:h(e,i.location)}}parseDomainMember(){return this.check("STATE")?this.parseState():this.check("COMPUTED")?this.parseComputed():this.check("ACTION")?this.parseAction():this.isFlowDeclContext()?this.parseFlowDecl():(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();)n.push(this.parseStateField());let i=this.consume("RBRACE","Expected '}' to close state block").location;return{kind:"state",fields:n,location:h(e,i)}}parseStateField(){let e=this.consume("IDENTIFIER","Expected field name");this.consume("COLON","Expected ':' after field name");let n=this.parseTypeExpr(),i;return this.match("EQ")&&(i=this.parseExpression()),{kind:"stateField",name:e.lexeme,typeExpr:n,initializer:i,location:h(e.location,i?.location??n.location)}}parseComputed(){let e=this.consume("COMPUTED","Expected 'computed'").location,n=this.consume("IDENTIFIER","Expected computed name").lexeme;this.consume("EQ","Expected '=' after computed name");let i=this.parseExpression();return{kind:"computed",name:n,expression:i,location:h(e,i.location)}}parseAction(){let e=this.consume("ACTION","Expected 'action'").location,n=this.consume("IDENTIFIER","Expected action name").lexeme;this.consume("LPAREN","Expected '(' after action name");let i=[];if(!this.check("RPAREN"))do i.push(this.parseParam());while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after parameters");let r;this.match("AVAILABLE")&&(this.consume("WHEN","Expected 'when' after 'available'"),r=this.parseExpression());let o;if(this.match("DISPATCHABLE")&&(this.consume("WHEN","Expected 'when' after 'dispatchable'"),o=this.parseExpression()),this.check("AVAILABLE")){let c=o?"'available when' must appear before 'dispatchable when' in an action":"Action can declare 'available when' at most once";throw this.errorAtCurrent(c)}if(this.check("DISPATCHABLE"))throw this.errorAtCurrent("Action can declare 'dispatchable when' at most once");this.consume("LBRACE","Expected '{' to start action body");let a=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let c=this.parseGuardedStmt();c&&a.push(c)}let s=this.consume("RBRACE","Expected '}' to close action").location;return{kind:"action",name:n,params:i,available:r,dispatchable:o,body:a,location:h(e,s)}}parseFlowDecl(){let e=this.consume("IDENTIFIER","Expected 'flow'"),n=this.consume("IDENTIFIER","Expected flow name").lexeme;this.consume("LPAREN","Expected '(' after flow name");let i=[];if(!this.check("RPAREN"))do i.push(this.parseParam());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 o=this.consume("RBRACE","Expected '}' to close flow").location;return{kind:"flow",name:n,params:i,body:r,location:h(e.location,o)}}parseParam(){let e=this.consume("IDENTIFIER","Expected parameter name");this.consume("COLON","Expected ':' after parameter name");let n=this.parseTypeExpr();return{kind:"param",name:e.lexeme,typeExpr:n,location:h(e.location,n.location)}}parseGuardedStmt(){if(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 e=this.peek();return e.kind==="PATCH"||e.lexeme==="patch"||e.kind==="EFFECT"||e.lexeme==="effect"?(this.error(`'${e.lexeme}' must be inside a guard block (when, once, or onceIntent). Wrap it: when true { ${e.lexeme} ... }`),this.skipToRecoveryPoint(),null):(this.error(`Unexpected token '${e.lexeme}'. Expected 'when', 'once', 'onceIntent', 'include', 'fail', or 'stop'.`),this.advance(),null)}parseFlowStmt(){return 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 i=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let o=this.parseInnerStmt();o&&i.push(o)}let r=this.consume("RBRACE","Expected '}' to close when block").location;return{kind:"when",condition:n,body:i,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 i;this.match("WHEN")&&(i=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 o=this.consume("RBRACE","Expected '}' to close once block").location;return{kind:"once",marker:n,condition:i,body:r,location:h(e,o)}}parseOnceIntentStmt(){let e=this.consume("IDENTIFIER","Expected 'onceIntent'"),n;this.match("WHEN")&&(n=this.parseExpression()),this.consume("LBRACE","Expected '{' to start onceIntent block");let i=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let o=this.parseInnerStmt();o&&i.push(o)}let r=this.consume("RBRACE","Expected '}' to close onceIntent block").location;return{kind:"onceIntent",condition:n,body:i,location:h(e.location,r)}}parseInnerStmt(){return 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 i=[];if(!this.check("RPAREN"))do i.push(this.parseExpression());while(this.match("COMMA"));let r=this.consume("RPAREN","Expected ')' after include arguments").location;return{kind:"include",flowName:n.lexeme,args:i,location:h(e.location,r)}}parsePatchStmt(){let e=this.consume("PATCH","Expected 'patch'").location,n=this.parsePath(),i,r,o;return this.match("UNSET")?(i="unset",o=this.previous().location):this.match("MERGE")?(i="merge",r=this.parseExpression(),o=r.location):(this.consume("EQ","Expected '=', 'unset', or 'merge' after path"),i="set",r=this.parseExpression(),o=r.location),{kind:"patch",path:n,op:i,value:r,location:h(e,o)}}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 i=[];for(;!this.check("RBRACE")&&!this.isAtEnd();)i.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:i,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),i=n?this.parsePath():this.parseExpression();return{kind:"effectArg",name:e.lexeme,value:i,isPath:n,location:h(e.location,i.location)}}parseFailStmt(){let e=this.consume("FAIL","Expected 'fail'").location,n=this.consume("STRING","Expected error code string after 'fail'"),i=n.value,r,o=n.location;return this.match("WITH")&&(r=this.parseExpression(),o=r.location),{kind:"fail",code:i,message:r,location:h(e,o)}}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(),i=this.consume("GT","Expected '>' after array element type").location;return{kind:"arrayType",elementType:n,location:h(e.location,i)}}else if(e.lexeme==="Record"){let n=this.parseTypeExpr();this.consume("COMMA","Expected ',' between Record type parameters");let i=this.parseTypeExpr(),r=this.consume("GT","Expected '>' after Record value type").location;return{kind:"recordType",keyType:n,valueType:i,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.consume("IDENTIFIER","Expected field name"),o=this.match("QUESTION");this.consume("COLON","Expected ':' after field name");let a=this.parseTypeExpr();n.push({kind:"typeField",name:r.lexeme,typeExpr:a,optional:o,location:h(r.location,a.location)}),this.match("COMMA")}let i=this.consume("RBRACE","Expected '}' to close object type").location;return{kind:"objectType",fields:n,location:h(e,i)}}parseExpression(e=0){let n=this.parsePrimary();for(;;){let i=Ve(this.peek().kind);if(i<=e)break;if(this.peek().kind==="QUESTION"){n=this.parseTernary(n);continue}let r=Tt(this.peek().kind);if(!r)break;this.advance();let o=Nt(this.previous().kind)?i-1:i,a=this.parseExpression(o);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 i=this.parseExpression(0);return{kind:"ternary",condition:e,consequent:n,alternate:i,location:h(e.location,i.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 i=this.consume("RPAREN","Expected ')' after arguments").location;return this.parsePostfix({kind:"functionCall",name:e.lexeme,args:n,location:h(e.location,i)})}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(),i=this.consume("RBRACKET","Expected ']' after index").location;e={kind:"indexAccess",object:e,index:n,location:h(e.location,i)}}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 o=this.parseExpression();n.push({kind:"objectProperty",key:r.lexeme,value:o,location:h(r.location,o.location)}),this.check("RBRACE")||this.consume("COMMA","Expected ',' between properties")}let i=this.consume("RBRACE","Expected '}' to close object").location;return{kind:"objectLiteral",properties:n,location:h(e,i)}}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 i=this.consume("RBRACKET","Expected ']' to close array").location;return{kind:"arrayLiteral",elements:n,location:h(e,i)}}parsePath(){let e=[],n=this.peek().location,i=this.consume("IDENTIFIER","Expected identifier");for(e.push({kind:"propertySegment",name:i.lexeme,location:i.location});;)if(this.match("DOT")){let o=this.consume("IDENTIFIER","Expected property name");e.push({kind:"propertySegment",name:o.lexeme,location:o.location})}else if(this.match("LBRACKET")){let o=this.parseExpression(),a=this.consume("RBRACKET","Expected ']'").location;e.push({kind:"indexSegment",index:o,location:h(o.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","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)}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)}};function ge(t){return new ze(t).parse()}var Ee=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)}},Ke=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 Ee("domain");this.domainScope=n,this.currentScope=n,this.scopes.set("domain",n);for(let i of e.members)if(i.kind==="state")for(let r of i.fields)this.defineSymbol({name:r.name,kind:"state",location:r.location});else i.kind==="computed"?this.defineSymbol({name:i.name,kind:"computed",location:i.location}):i.kind==="action"?this.defineSymbol({name:i.name,kind:"action",location:i.location}):i.kind;for(let i of e.members)i.kind==="computed"?this.analyzeComputedExpr(i):i.kind==="action"&&this.analyzeAction(i)}analyzeComputedExpr(e){this.analyzeExpr(e.expression,"computed")}analyzeAction(e){let n=new Ee("action",this.domainScope);this.currentScope=n,this.scopes.set(`action.${e.name}`,n);for(let i of e.params)n.define({name:i.name,kind:"param",location:i.location});for(let i of e.body)this.analyzeStmt(i);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 i of e.args)this.analyzeExpr(i,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 i of e.properties)this.analyzeExpr(i.value,n);break;case"arrayLiteral":for(let i of e.elements)this.analyzeExpr(i,n);break;case"iterationVar":break;case"literal":break}}checkIdentifier(e,n,i){let r=this.currentScope?.lookup(e);if(!r){this.error(`Undefined identifier '${e}'`,n,"E_UNDEFINED");return}i==="computed"&&r.kind==="param"&&this.error(`Cannot access parameter '${e}' in computed expression`,n,"E_INVALID_ACCESS")}checkSystemIdent(e,n,i){let[r,...o]=e;if(r==="system"&&i==="computed"&&this.error("Cannot use $system.* in computed expressions (non-deterministic)",n,"E001"),r==="system"){let a=["uuid","timestamp","time.now","random"],s=o.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=o.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,i){this.diagnostics.push({severity:"error",code:i,message:e,location:n})}};function bt(t){return new Ke().analyze(t)}function ke(t,e,n,i){return{severity:"error",code:t,message:e,location:n,...i}}function St(t,e,n,i){return{severity:"warning",code:t,message:e,location:n,...i}}function Rr(t,e,n){return{severity:"info",code:t,message:e,location:n}}function sn(t){return t.severity==="error"}function Lr(t){return t.some(sn)}function Fr(t,e){return t.filter(n=>n.severity===e)}var xt=new Set(["eq","neq","gt","gte","lt","lte","and","or","not","isNull","isNotNull","hasKey","startsWith","endsWith","strIncludes","includes","every","some","existsById"]),vt=new Set(["add","sub","mul","div","mod","absDiff","abs","clamp","floor","ceil","round","sqrt","pow","len","strlen","indexOf","streak","sum","min","max","toNumber"]),wt=new Set(["trim","lower","upper","concat","typeof","toString","substring","substr","replace"]),cn=new Set(["keys","values","entries","merge","filter","map","append","reverse","unique","flat","split","fromEntries"]),ln=new Set(["updateById","removeById"]);function Te(t){let e=new Map,n=new Map,i=new Map;for(let r of t.types)i.set(r.name,r);for(let r of t.members){if(r.kind==="state"){for(let o of r.fields)e.set(o.name,o.typeExpr);continue}r.kind==="computed"&&n.set(r.name,r)}return{stateTypes:e,computedDecls:n,typeDefs:i,computedTypeCache:new Map,computedTypeInFlight:new Set}}function Ne(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 yn(t.value,t.location);case"identifier":return e.get(t.name)??n.stateTypes.get(t.name)??dn(t.name,n);case"propertyAccess":return K(k(t.object,e,n),t.property,n);case"indexAccess":return ae(k(t.object,e,n),n);case"objectLiteral":return{kind:"objectType",fields:t.properties.map(i=>{let r=k(i.value,e,n);return r?{kind:"typeField",name:i.key,typeExpr:r,optional:!1,location:i.location}:null}).filter(i=>i!==null),location:t.location};case"arrayLiteral":{let i=I(t.elements.map(r=>k(r,e,n)),t.location);return i?{kind:"arrayType",elementType:i,location:t.location}:null}case"unary":return pn(t);case"binary":return un(t,e,n);case"ternary":return I([k(t.consequent,e,n),k(t.alternate,e,n)],t.location);case"functionCall":return mn(t,e,n);case"systemIdent":return null;case"iterationVar":return e.get("$item")??null}}function j(t,e,n){let i=k(t,e,n);if(i)return At(i,n);switch(t.kind){case"literal":return"primitive";case"objectLiteral":case"arrayLiteral":return"nonprimitive";case"binary":return t.operator==="??"?oe([j(t.left,e,n),j(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 oe([j(t.consequent,e,n),j(t.alternate,e,n)]);case"functionCall":return cn.has(t.name)?"nonprimitive":xt.has(t.name)||vt.has(t.name)||wt.has(t.name)||t.name==="toBoolean"?"primitive":(t.name==="cond"||t.name==="if")&&t.args.length>=3?oe([j(t.args[1],e,n),j(t.args[2],e,n)]):t.name==="coalesce"?oe(t.args.map(r=>j(r,e,n))):"unknown";case"identifier":case"propertyAccess":case"indexAccess":case"systemIdent":case"iterationVar":return"unknown"}}function At(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 oe(n.types.map(i=>At(i,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 K(t,e,n){let i=M(t,n);if(!i)return null;if(i.kind==="objectType")return i.fields.find(o=>o.name===e)?.typeExpr??null;if(i.kind==="unionType"){let r=i.types.filter(o=>!Q(o)).map(o=>K(o,e,n)).filter(o=>o!==null);return I(r,i.location)}return null}function ae(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 i=n.types.filter(r=>!Q(r)).map(r=>ae(r,e)).filter(r=>r!==null);return I(i,n.location)}return null}function _(t,e){let n=M(t,e);if(!n)return null;if(n.kind==="arrayType")return n.elementType;if(n.kind==="unionType"){let i=n.types.filter(r=>!Q(r)).map(r=>_(r,e)).filter(r=>r!==null);return I(i,n.location)}return null}function be(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(i=>be(i,e));default:return!1}}function Q(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 i=k(n.expression,new Map,e);return e.computedTypeInFlight.delete(t),e.computedTypeCache.set(t,i),i}function pn(t){return t.operator==="!"?C("boolean",t.location):C("number",t.location)}function un(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 I([k(t.left,e,n),k(t.right,e,n)],t.location)}}function mn(t,e,n){if(xt.has(t.name))return C("boolean",t.location);if(vt.has(t.name))return C("number",t.location);if(t.name==="idiv")return I([C("number",t.location),C("null",t.location)],t.location);if(wt.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 i=_(k(t.args[0],e,n),n);return i?I([i,C("null",t.location)],t.location):null}if(t.name==="find"&&t.args.length>=1){let i=_(k(t.args[0],e,n),n);return i?I([i,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 i=k(t.args[0],e,n),r=_(i,n);if(!r)return null;let o=k(t.args[1],En(e,r),n);return o?{kind:"arrayType",elementType:o,location:t.location}:null}if((t.name==="first"||t.name==="last")&&t.args.length>=1)return _(k(t.args[0],e,n),n);if(t.name==="at"&&t.args.length>=1)return ae(k(t.args[0],e,n),n);if(t.name==="field"&&t.args.length>=2){let i=gn(t.args[1]);return i?K(k(t.args[0],e,n),i,n):null}return ln.has(t.name)&&t.args.length>=1?k(t.args[0],e,n):(t.name==="cond"||t.name==="if")&&t.args.length>=3?I([k(t.args[1],e,n),k(t.args[2],e,n)],t.location):t.name==="coalesce"?I(t.args.map(i=>k(i,e,n)),t.location):t.name==="match"?hn(t,e,n):t.name==="argmax"||t.name==="argmin"?fn(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 oe(t){let e=!1;for(let n of t){if(n==="nonprimitive")return"nonprimitive";n==="unknown"&&(e=!0)}return e?"unknown":"primitive"}function I(t,e){let n=t.filter(o=>o!==null);if(n.length===0)return null;if(n.length===1)return n[0];let i=[],r=new Set;for(let o of n){let a=JSON.stringify(o);r.has(a)||(r.add(a),i.push(o))}return i.length===1?i[0]:{kind:"unionType",types:i,location:e}}function hn(t,e,n){if(t.args.length<3)return null;let i=[];for(let r=1;r<t.args.length-1;r+=1){let o=t.args[r];if(o.kind!=="arrayLiteral"||o.elements.length!==2)return null;i.push(k(o.elements[1],e,n))}return i.push(k(t.args[t.args.length-1],e,n)),I(i,t.location)}function fn(t,e,n){if(t.args.length<2)return null;let i=[];for(let o=0;o<t.args.length-1;o+=1){let a=t.args[o];if(a.kind!=="arrayLiteral"||a.elements.length!==3)return null;i.push(k(a.elements[0],e,n))}let r=I(i,t.location);return r?I([r,C("null",t.location)],t.location):null}function yn(t,e){return{kind:"literalType",value:t,location:e}}function C(t,e){return{kind:"simpleType",name:t,location:e}}function gn(t){return t.kind==="literal"&&typeof t.value=="string"?t.value:null}function En(t,e){let n=new Map(t);return n.set("$item",e),n}var kn=new Set(["findById","existsById"]),Ye=new Set(["updateById","removeById"]),Tn=new Set([...kn,...Ye]);function G(t,e,n,i,r){let o=`${n}:${r.start.offset}:${r.end.offset}:${i}`;e.has(o)||(e.add(o),t.push(ke(n,i,r)))}function Ct(t){let e=[],n=new Set,i=Te(t.domain);xn(t.domain,i,e,n);for(let r of t.domain.members)switch(r.kind){case"computed":b(r.expression,"computed",new Map,i,e,n,0);break;case"action":{let o=Ne(r.params);Nn(r,o,i,e,n);break}case"state":case"flow":break}return e}function Nn(t,e,n,i,r){t.available&&b(t.available,"available",e,n,i,r,0),t.dispatchable&&b(t.dispatchable,"dispatchable",e,n,i,r,0);for(let o of t.body)bn(o,e,n,i,r)}function bn(t,e,n,i,r){switch(t.kind){case"when":b(t.condition,"guard",e,n,i,r,0);for(let o of t.body)X(o,e,n,i,r);break;case"once":t.condition&&b(t.condition,"guard",e,n,i,r,0);for(let o of t.body)X(o,e,n,i,r);break;case"onceIntent":t.condition&&b(t.condition,"guard",e,n,i,r,0);for(let o of t.body)X(o,e,n,i,r);break;case"include":break}}function X(t,e,n,i,r){switch(t.kind){case"when":b(t.condition,"guard",e,n,i,r,0);for(let o of t.body)X(o,e,n,i,r);break;case"once":t.condition&&b(t.condition,"guard",e,n,i,r,0);for(let o of t.body)X(o,e,n,i,r);break;case"onceIntent":t.condition&&b(t.condition,"guard",e,n,i,r,0);for(let o of t.body)X(o,e,n,i,r);break;case"patch":t.value&&b(t.value,"patch",e,n,i,r,0);break;case"effect":for(let o of t.args)o.isPath||b(o.value,"action",e,n,i,r,0);break;case"fail":t.message&&b(t.message,"action",e,n,i,r,0);break;case"include":case"stop":break}}function b(t,e,n,i,r,o,a){switch(t.kind){case"functionCall":{Sn(t,e,n,i,r,o,a);let s=a+(Ye.has(t.name)?1:0);for(let c of t.args)b(c,e,n,i,r,o,s);break}case"binary":b(t.left,e,n,i,r,o,a),b(t.right,e,n,i,r,o,a);break;case"unary":b(t.operand,e,n,i,r,o,a);break;case"ternary":b(t.condition,e,n,i,r,o,a),b(t.consequent,e,n,i,r,o,a),b(t.alternate,e,n,i,r,o,a);break;case"propertyAccess":b(t.object,e,n,i,r,o,a);break;case"indexAccess":b(t.object,e,n,i,r,o,a),b(t.index,e,n,i,r,o,a);break;case"objectLiteral":for(let s of t.properties)b(s.value,e,n,i,r,o,a);break;case"arrayLiteral":for(let s of t.elements)b(s,e,n,i,r,o,a);break;case"literal":case"identifier":case"systemIdent":case"iterationVar":break}}function Sn(t,e,n,i,r,o,a){if(!Tn.has(t.name)||t.args.length===0)return;Ye.has(t.name)&&(e==="available"?G(r,o,"E035","updateById/removeById are not allowed in available conditions.",t.location):e==="dispatchable"?G(r,o,"E048","updateById/removeById are not allowed in dispatchable conditions.",t.location):e==="guard"?G(r,o,"E034","updateById/removeById are not allowed in guard conditions.",t.location):e!=="patch"&&G(r,o,"E031","updateById/removeById are only allowed in patch RHS.",t.location),a>0&&G(r,o,"E032","Nested transform primitives are not allowed.",t.location),e==="patch"&&!We(t.args[0],i)&&G(r,o,"E033","Transform primitive collection argument must resolve to a state path.",t.args[0].location));let s=wn(t.args[0],n,i);if(!s)return;let c=Pt(s,i);if(!c){G(r,o,"E030","Collection element type must declare an 'id' field for entity primitives.",t.args[0].location);return}be(c,i)||G(r,o,"E030a","Entity 'id' field must be string or number.",t.args[0].location)}function xn(t,e,n,i){for(let r of t.members)if(r.kind==="state")for(let o of r.fields)vn(o,e,n,i)}function vn(t,e,n,i){if(!t.initializer||t.initializer.kind!=="arrayLiteral")return;let r=_(t.typeExpr,e);if(!r)return;let o=Pt(r,e);if(!o||!be(o,e))return;let a=new Map;for(let s of t.initializer.elements){if(s.kind!=="objectLiteral")continue;let c=s.properties.find(u=>u.key==="id");if(!c||c.value.kind!=="literal"||typeof c.value.value!="string"&&typeof c.value.value!="number")continue;let l=`${typeof c.value.value}:${String(c.value.value)}`;if(a.get(l)){G(n,i,"E030b","Duplicate '.id' values detected in state initializer.",c.value.location);continue}a.set(l,c.value.location)}}function wn(t,e,n){return _(k(t,e,n),n)}function Pt(t,e){return K(t,"id",e)}function We(t,e){switch(t.kind){case"identifier":return e.stateTypes.has(t.name);case"propertyAccess":return We(t.object,e);case"indexAccess":return We(t.object,e);default:return!1}}function It(){return{inAction:!1,inGuard:!1,guardDepth:0,hasMarkerPatch:!1,currentActionParamTypes:new Map,diagnostics:[]}}var An=/\b(await(?:ing)?|wait(?:ing)?|pending)\b/i;function y(t,e){return{kind:"simpleType",name:t,location:e}}function q(t,e,n){let i=M(t,n),r=M(e,n);if(!i||!r)return null;if(r.kind==="unionType"){let o=i.kind==="unionType"?i.types:[i],a=!1;for(let s of o){let c=r.types.map(l=>q(s,l,n));if(!c.includes(!0)){if(c.every(l=>l===!1))return!1;a=!0}}return a?null:!0}if(i.kind==="unionType"){let o=!1;for(let a of i.types){let s=q(a,r,n);if(s===!1)return!1;s===null&&(o=!0)}return o?null:!0}if(r.kind==="simpleType"){if(i.kind==="simpleType")return i.name===r.name;if(i.kind==="literalType")return r.name==="null"?i.value===null:typeof i.value===r.name}if(r.kind==="literalType")return i.kind!=="literalType"?!1:i.value===r.value;if(r.kind==="arrayType")return i.kind!=="arrayType"?!1:q(i.elementType,r.elementType,n);if(r.kind==="objectType"){if(i.kind!=="objectType")return!1;for(let o of r.fields){let a=i.fields.find(c=>c.name===o.name);if(!a){if(o.optional)continue;return!1}let s=q(a.typeExpr,o.typeExpr,n);if(s!==!0)return s}return!0}return r.kind==="recordType"?i.kind!=="recordType"?null:q(i.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(i=>`${i.name}${i.optional?"?":""}: ${x(i.typeExpr,e)}`).join("; ")} }`;case"unionType":return n.types.map(i=>x(i,e)).join(" | ")}}function Se(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 i=new Set;for(let r of n.types){let o=Se(r,e);if(o===null)return null;if(o==="nonprimitive")return"nonprimitive";for(let a of o)i.add(a)}return i}}}function Qe(t,e){let n=Se(t,e);if(n===null)return null;if(n==="nonprimitive")return"invalid";let i=[...n].filter(r=>r!=="null");return i.length!==1||n.has("null")?"invalid":i[0]}function Dt(t,e,n){let i=Se(t,n),r=Se(e,n);if(i===null||r===null)return null;if(i==="nonprimitive"||r==="nonprimitive")return!1;if(!(i instanceof Set)||!(r instanceof Set))return null;let o=[...i].filter(s=>s!=="null"),a=[...r].filter(s=>s!=="null");return o.length===0||a.length===0?!0:o.some(s=>a.includes(s))}function Cn(t,e){let n=M(t,e);if(!n||Q(n))return null;if(n.kind!=="unionType")return n;let i=n.types.filter(r=>!Q(r));return i.length===0?null:i.length===1?i[0]:{kind:"unionType",types:i,location:n.location}}function Xe(t,e,n){if(!t||!e)return null;let i=q(t,e,n);if(i===!0)return!0;let r=q(e,t,n);if(r===!0)return!0;let o=Dt(t,e,n);return o!==null?o:i===!1&&r===!1?!1:null}function Rt(t,e){let n=M(t,e);if(!n)return null;if(n.kind==="unionType"){let i=n.types.map(r=>Rt(r,e));return i.every(r=>r===!0)?!0:i.some(r=>r===!1)?!1:null}return n.kind==="arrayType"}function Lt(t,e){let n=M(t,e);if(!n)return null;if(n.kind==="unionType"){let i=n.types.map(r=>Lt(r,e));return i.every(r=>r===!0)?!0:i.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 Pn(t,e){let n=new Map(t);return n.set("$item",e),n}function Mt(t){let e=xe(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 xe(t){if(t.kind==="literal"&&t.literalType==="number"&&typeof t.value=="number")return t.value;if(t.kind==="unary"&&t.operator==="-"){let e=xe(t.operand);return typeof e=="number"?-e:void 0}}function In(t,e){let[n,...i]=t.segments;if(!n||n.kind!=="propertySegment")return null;let r=e.stateTypes.get(n.name)??null;for(let o of i){if(!r)return null;r=o.kind==="propertySegment"?K(r,o.name,e):ae(r,e)}return r}function Mn(t){let e="";for(let[n,i]of t.segments.entries()){if(i.kind==="propertySegment"){e+=n===0?i.name:`.${i.name}`;continue}i.index.kind==="literal"?e+=`[${JSON.stringify(i.index.value)}]`:e+="[*]"}return e}var Je=class{ctx=It();symbols=null;validate(e){return this.ctx=It(),this.symbols=Te(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 i of e.fields){let r=n.get(i.name);r?this.error(`Duplicate state field '${i.name}'. First declared at line ${r.start.line}`,i.location,"E_DUPLICATE_FIELD"):n.set(i.name,i.location),this.validateStateField(i)}}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 i of e.args)this.validateStateInitializer(i);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(St("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 i of e.fields)this.checkAnonymousObjectType(i.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 i of e.types)this.checkAnonymousObjectType(i,n);break}}validateAction(e){this.ctx.inAction=!0,this.ctx.currentActionParamTypes=Ne(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,i=this.validateExpr(e.value,"action");if(!this.symbols||n!==this.ctx.diagnostics.length)return;let r=In(e.path,this.symbols);if(!r||!i)return;q(i,r,this.symbols)===!1&&this.error(`Patch value for '${Mn(e.path)}' must be assignable to ${x(r,this.symbols)}, got ${x(i,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"),An.test(e.reason)&&this.error("stop message suggests waiting/pending - use 'Already processed' style instead",e.location,"E008")}validateCondition(e,n){let i=this.ctx.diagnostics.length,r=this.validateExpr(e,"action");i===this.ctx.diagnostics.length&&this.requireAssignable(r,y("boolean",e.location),e.location,`Condition in ${n} must evaluate to boolean`)}validateExpr(e,n,i=this.ctx.currentActionParamTypes){switch(e.kind){case"functionCall":return this.validateFunctionCall(e,n,i),this.inferType(e,i);case"binary":{let r=this.ctx.diagnostics.length,o=this.validateExpr(e.left,n,i),a=this.validateExpr(e.right,n,i);if(!(r!==this.ctx.diagnostics.length))switch(e.operator){case"==":case"!=":this.validatePrimitiveEquality(e.left,e.right,o,a,e.location);break;case"<":case"<=":case">":case">=":this.requireAssignable(o,y("number",e.left.location),e.left.location,`Operator '${e.operator}' requires a numeric left operand`),this.requireAssignable(a,y("number",e.right.location),e.right.location,`Operator '${e.operator}' requires a numeric right operand`);break;case"&&":case"||":this.requireAssignable(o,y("boolean",e.left.location),e.left.location,`Operator '${e.operator}' requires a boolean left operand`),this.requireAssignable(a,y("boolean",e.right.location),e.right.location,`Operator '${e.operator}' requires a boolean right operand`);break;case"+":case"-":case"*":case"/":case"%":this.requireAssignable(o,y("number",e.left.location),e.left.location,`Operator '${e.operator}' requires a numeric left operand`),this.requireAssignable(a,y("number",e.right.location),e.right.location,`Operator '${e.operator}' requires a numeric right operand`);break;case"??":this.validateCoalesceTypes([o,a],e.location);break}return this.inferType(e,i)}case"unary":{let r=this.ctx.diagnostics.length,o=this.validateExpr(e.operand,n,i);return r===this.ctx.diagnostics.length&&this.requireAssignable(o,y(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,i)}case"ternary":{let r=this.ctx.diagnostics.length,o=this.validateExpr(e.condition,n,i);return this.validateExpr(e.consequent,n,i),this.validateExpr(e.alternate,n,i),r===this.ctx.diagnostics.length&&this.requireAssignable(o,y("boolean",e.condition.location),e.condition.location,"Ternary condition must evaluate to boolean"),this.inferType(e,i)}case"propertyAccess":return this.validateExpr(e.object,n,i),this.inferType(e,i);case"indexAccess":return this.validateExpr(e.object,n,i),this.validateExpr(e.index,n,i),this.inferType(e,i);case"objectLiteral":for(let r of e.properties)this.validateExpr(r.value,n,i);return this.inferType(e,i);case"arrayLiteral":for(let r of e.elements)this.validateExpr(r,n,i);return this.inferType(e,i);case"systemIdent":return this.inferType(e,i);case"literal":case"identifier":case"iterationVar":return this.inferType(e,i)}}validateFunctionCall(e,n,i){let{name:r,args:o,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)&&o.length===1){n==="action"&&this.error(`Primitive aggregation '${r}()' can only be used in computed expressions, not in actions`,a,"E009");let c=o[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":o.length!==1&&this.error(`Function '${r}' expects 1 argument, got ${o.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":o.length!==2&&this.error(`Function '${r}' expects 2 arguments, got ${o.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":o.length!==1&&this.error(`Function '${r}' expects 1 argument, got ${o.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":o.length!==2&&this.error(`Function '${r}' expects 2 arguments, got ${o.length}`,a,"E_ARG_COUNT");break;case"updateById":case"clamp":o.length!==3&&this.error(`Function '${r}' expects 3 arguments, got ${o.length}`,a,"E_ARG_COUNT");break;case"removeById":case"streak":o.length!==2&&this.error(`Function '${r}' expects 2 arguments, got ${o.length}`,a,"E_ARG_COUNT");break;case"slice":case"substring":case"substr":case"replace":(o.length<2||o.length>3)&&this.error(`Function '${r}' expects 2-3 arguments, got ${o.length}`,a,"E_ARG_COUNT");break;case"split":o.length!==2&&this.error(`Function '${r}' expects 2 arguments, got ${o.length}`,a,"E_ARG_COUNT");break;case"and":case"or":case"concat":case"min":case"max":case"merge":case"coalesce":case"append":o.length<1&&this.error(`Function '${r}' expects at least 1 argument`,a,"E_ARG_COUNT");break;case"match":o.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":o.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":o.length!==3&&this.error(`Function '${r}' expects 3 arguments, got ${o.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)&&o.length>0){let c=this.validateExpr(o[0],n,i);s.push(c);let l=i;if(this.symbols){let d=_(c,this.symbols);d&&(l=Pn(i,d))}for(let d=1;d<o.length;d+=1)s.push(this.validateExpr(o[d],n,d===1?l:i))}else for(let c of o)s.push(this.validateExpr(c,n,i));if(this.symbols)switch(r){case"eq":case"neq":o.length===2&&this.validatePrimitiveEquality(o[0],o[1],s[0],s[1],a);break;case"add":case"sub":case"mul":case"div":case"mod":case"absDiff":case"idiv":case"pow":o.length===2&&(this.requireAssignable(s[0],y("number",o[0].location),o[0].location,`Function '${r}' expects a numeric first argument`),this.requireAssignable(s[1],y("number",o[1].location),o[1].location,`Function '${r}' expects a numeric second argument`));break;case"gt":case"gte":case"lt":case"lte":o.length===2&&(this.requireAssignable(s[0],y("number",o[0].location),o[0].location,`Function '${r}' expects a numeric first argument`),this.requireAssignable(s[1],y("number",o[1].location),o[1].location,`Function '${r}' expects a numeric second argument`));break;case"and":case"or":for(let[c,l]of o.entries())this.requireAssignable(s[c],y("boolean",l.location),l.location,`Function '${r}' expects boolean arguments`);break;case"not":o.length===1&&this.requireAssignable(s[0],y("boolean",o[0].location),o[0].location,"Function 'not' expects a boolean argument");break;case"neg":case"abs":case"floor":case"ceil":case"round":case"sqrt":o.length===1&&this.requireAssignable(s[0],y("number",o[0].location),o[0].location,`Function '${r}' expects a numeric argument`);break;case"clamp":if(o.length===3){this.requireAssignable(s[0],y("number",o[0].location),o[0].location,"Function 'clamp' expects a numeric first argument"),this.requireAssignable(s[1],y("number",o[1].location),o[1].location,"Function 'clamp' expects a numeric second argument"),this.requireAssignable(s[2],y("number",o[2].location),o[2].location,"Function 'clamp' expects a numeric third argument");let c=xe(o[1]),l=xe(o[2]);typeof c=="number"&&typeof l=="number"&&c>l&&this.error("Function 'clamp' requires literal bounds in lo, hi order",a,"E049")}break;case"streak":o.length===2&&(this.requireAssignable(s[0],y("number",o[0].location),o[0].location,"Function 'streak' expects a numeric first argument"),this.requireAssignable(s[1],y("boolean",o[1].location),o[1].location,"Function 'streak' expects a boolean second argument"));break;case"trim":case"lower":case"upper":case"strlen":o.length===1&&this.requireAssignable(s[0],y("string",o[0].location),o[0].location,`Function '${r}' expects a string argument`);break;case"startsWith":case"endsWith":case"strIncludes":case"indexOf":case"split":o.length===2&&(this.requireAssignable(s[0],y("string",o[0].location),o[0].location,`Function '${r}' expects a string first argument`),this.requireAssignable(s[1],y("string",o[1].location),o[1].location,`Function '${r}' expects a string second argument`));break;case"replace":o.length>=2&&(this.requireAssignable(s[0],y("string",o[0].location),o[0].location,"Function 'replace' expects a string first argument"),this.requireAssignable(s[1],y("string",o[1].location),o[1].location,"Function 'replace' expects a string second argument")),o.length===3&&this.requireAssignable(s[2],y("string",o[2].location),o[2].location,"Function 'replace' expects a string replacement argument");break;case"substring":case"substr":o.length>=2&&(this.requireAssignable(s[0],y("string",o[0].location),o[0].location,`Function '${r}' expects a string first argument`),this.requireAssignable(s[1],y("number",o[1].location),o[1].location,`Function '${r}' expects a numeric second argument`)),o.length===3&&this.requireAssignable(s[2],y("number",o[2].location),o[2].location,`Function '${r}' expects a numeric third argument`);break;case"len":o.length===1&&this.requireLenCompatible(s[0],o[0].location);break;case"filter":case"find":case"every":case"some":o.length===2&&(this.requireArrayCompatible(s[0],o[0].location,r),this.requireAssignable(s[1],y("boolean",o[1].location),o[1].location,`Function '${r}' requires a boolean-valued callback`));break;case"map":o.length===2&&this.requireArrayCompatible(s[0],o[0].location,r);break;case"coalesce":this.validateCoalesceTypes(s,a);break;case"match":this.validateMatchCall(o,s,a,i);break;case"argmax":case"argmin":this.validateArgSelectionCall(r,o,a,i);break;case"if":case"cond":o.length===3&&this.requireAssignable(s[0],y("boolean",o[0].location),o[0].location,`Function '${r}' expects a boolean condition`);break}}validatePrimitiveEquality(e,n,i,r,o){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",o,"E_TYPE_MISMATCH");return}Dt(i,r,this.symbols)===!1&&this.error(`eq/neq operands must be compatible primitive types, got ${x(i,this.symbols)} and ${x(r,this.symbols)}`,o,"E_TYPE_MISMATCH")}inferType(e,n){return this.symbols?k(e,n,this.symbols):null}requireAssignable(e,n,i,r){if(!this.symbols||!e)return;q(e,n,this.symbols)===!1&&this.error(`${r}, got ${x(e,this.symbols)}`,i,"E_TYPE_MISMATCH")}requireArrayCompatible(e,n,i){if(!this.symbols||!e)return;Rt(e,this.symbols)===!1&&this.error(`Function '${i}' expects an array first argument, got ${x(e,this.symbols)}`,n,"E_TYPE_MISMATCH")}requireLenCompatible(e,n){if(!this.symbols||!e)return;Lt(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 i=e.map(r=>Cn(r,this.symbols)).filter(r=>r!==null);for(let r=0;r<i.length;r+=1)for(let o=r+1;o<i.length;o+=1)if(Xe(i[r],i[o],this.symbols)===!1){this.error(`coalesce arguments must have compatible non-null types, got ${x(i[r],this.symbols)} and ${x(i[o],this.symbols)}`,n,"E_TYPE_MISMATCH");return}}validateMatchCall(e,n,i,r){if(!this.symbols||e.length<3)return;let o=n[0],a=Qe(o,this.symbols);a==="invalid"&&this.error(`Function 'match' requires a selector of type string, number, or boolean, got ${x(o,this.symbols)}`,e[0].location,"E_TYPE_MISMATCH");let s=new Set,c=[];for(let l=1;l<e.length-1;l+=1){let d=e[l];if(d.kind!=="arrayLiteral"||d.elements.length!==2){this.error("Function 'match' requires each arm to be an inline [key, value] array literal",d.location,"E050");continue}let[u,m]=d.elements,g=Mt(u);if(g==null)this.error("Function 'match' requires literal string, number, or boolean arm keys",u.location,"E050");else{let O=`${typeof g}:${String(g)}`;s.has(O)?this.error(`Function 'match' has duplicate arm key ${JSON.stringify(g)}`,u.location,"E051"):s.add(O)}let N=this.inferType(u,r),S=Qe(N,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(o,this.symbols)} and ${x(N,this.symbols)}`,u.location,"E_TYPE_MISMATCH"),c.push(this.inferType(m,r))}c.push(n[n.length-1]);for(let l=0;l<c.length;l+=1)for(let d=l+1;d<c.length;d+=1)if(Xe(c[l],c[d],this.symbols)===!1){this.error(`Function 'match' arm values and default must have compatible types, got ${x(c[l],this.symbols)} and ${x(c[d],this.symbols)}`,i,"E_TYPE_MISMATCH");return}}validateArgSelectionCall(e,n,i,r){if(!this.symbols||n.length<2)return;let o=n[n.length-1],a=Mt(o);a!=="first"&&a!=="last"&&this.error(`Function '${e}' requires a final tie-break literal of "first" or "last"`,o.location,"E052");let s=[],c=null;for(let l=0;l<n.length-1;l+=1){let d=n[l];if(d.kind!=="arrayLiteral"||d.elements.length!==3){this.error(`Function '${e}' requires inline [label, eligible, score] array literal candidates`,d.location,"E052");continue}let[u,m,g]=d.elements,N=this.inferType(u,r),S=Qe(N,this.symbols);S==="invalid"?this.error(`Function '${e}' requires labels with exactly one primitive scalar type, got ${x(N,this.symbols)}`,u.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}`,u.location,"E_TYPE_MISMATCH"),this.requireAssignable(this.inferType(m,r),y("boolean",m.location),m.location,`Function '${e}' expects a boolean eligible value`),this.requireAssignable(this.inferType(g,r),y("number",g.location),g.location,`Function '${e}' expects a numeric score value`),s.push(N)}for(let l=0;l<s.length;l+=1)for(let d=l+1;d<s.length;d+=1)if(Xe(s[l],s[d],this.symbols)===!1){this.error(`Function '${e}' candidate labels must have compatible scalar types, got ${x(s[l],this.symbols)} and ${x(s[d],this.symbols)}`,i,"E_TYPE_MISMATCH");return}}error(e,n,i){this.ctx.diagnostics.push({severity:"error",code:i,message:e,location:n})}warn(e,n,i){this.ctx.diagnostics.push({severity:"warning",code:i,message:e,location:n})}};function Ft(t){let n=new Je().validate(t),i=Ct(t),r=[...n.diagnostics,...i];return{valid:!r.some(o=>o.severity==="error"),diagnostics:r}}var Ze={mode:"schema",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!1},et={mode:"action",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!1},tt={mode:"action",allowSysPaths:{prefixes:["input"]},fnTableVersion:"1.0",allowItem:!1},nt={mode:"action",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!0},Dn={allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0"};var F=class extends Error{code;path;details;constructor(e,n,i){super(n),this.name="LoweringError",this.code=e,this.path=i?.path,this.details=i?.details}};function ve(t,e,n){return new F("INVALID_KIND_FOR_CONTEXT",`Node kind '${t}' is not allowed in ${e} context`,{path:n,details:{kind:t,context:e}})}function f(t,e){return new F("UNKNOWN_CALL_FN",`Unknown function '${t}' in call expression`,{path:e,details:{fn:t}})}function we(t,e){return new F("INVALID_SYS_PATH",`System path '${t.join(".")}' is not allowed in Translator path`,{path:e,details:{sysPath:t}})}function it(t,e){return new F("UNSUPPORTED_BASE",`Unsupported base expression kind '${t}'. Only var(item) is supported.`,{path:e,details:{baseKind:t}})}function Rn(t,e){return new F("INVALID_SHAPE",`Invalid node shape: ${t}`,{path:e,details:{description:t}})}function rt(t,e){return new F("UNKNOWN_NODE_KIND",`Unknown expression node kind '${t}'`,{path:e,details:{kind:t}})}function Ln(t,e){let n=Array.from(t),i=Array.from(e),r=Math.min(n.length,i.length);for(let o=0;o<r;o+=1){let a=n[o].codePointAt(0)??0,s=i[o].codePointAt(0)??0;if(a!==s)return a-s}return n.length-i.length}function Ot(t){return t.map((e,n)=>({item:e,index:n})).sort((e,n)=>{let i=Ln(e.item.key,n.item.key);return i!==0?i:e.index-n.index}).map(({item:e})=>e)}function p(t,e){switch(t.kind){case"lit":return Fn(t);case"var":return On(t,e);case"sys":return jn(t,e);case"get":return _n(t,e);case"field":return jt(t,e);case"call":return $n(t,e);case"obj":return Bn(t,e);case"arr":return Un(t,e);default:throw rt(t.kind)}}function Fn(t){return{kind:"lit",value:t.value}}function On(t,e){if(!e.allowItem)throw ve("var",e.mode);return{kind:"get",path:"$item"}}function jn(t,e){if(t.path.length===0)throw we(t.path);let n=t.path[0];if(!(e.allowSysPaths?.prefixes??["meta","input"]).includes(n))throw we(t.path);return{kind:"get",path:t.path.join(".")}}function _n(t,e){let n=t.path.map(i=>i.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 ve("var",e.mode);return{kind:"get",path:`$item.${n}`}}throw it(t.base.kind)}function jt(t,e){if(t.object.kind==="get"&&t.object.base===void 0){let n=t.object.path.map(i=>i.name).join(".");return{kind:"get",path:n?`${n}.${t.property}`:t.property}}return{kind:"field",object:p(t.object,e),property:t.property}}function $n(t,e){let{fn:n,args:i}=t;if(n==="absDiff"){if(i.length!==2)throw f(n);return{kind:"abs",arg:{kind:"sub",left:p(i[0],e),right:p(i[1],e)}}}if(n==="clamp"){if(i.length!==3)throw f(n);return{kind:"min",args:[{kind:"max",args:[p(i[0],e),p(i[1],e)]},p(i[2],e)]}}if(n==="idiv"){if(i.length!==2)throw f(n);return{kind:"floor",arg:{kind:"div",left:p(i[0],e),right:p(i[1],e)}}}if(n==="streak"){if(i.length!==2)throw f(n);return{kind:"if",cond:p(i[1],e),then:{kind:"add",left:p(i[0],e),right:{kind:"lit",value:1}},else:{kind:"lit",value:0}}}if(n==="match")return Gn(i,e);if(n==="argmax"||n==="argmin")return qn(n,i,e);if(Wn(n)){if(i.length!==2)throw f(n);let[r,o]=i;return{kind:n,left:p(r,e),right:p(o,e)}}if(n==="isNotNull"){if(i.length!==1)throw f(n);return{kind:"not",arg:{kind:"isNull",arg:p(i[0],e)}}}if(_t(n)){if(i.length!==1)throw f(n);return{kind:Yn(n),arg:p(i[0],e)}}if(n==="trim"){if(i.length!==1)throw f(n);return{kind:"trim",str:p(i[0],e)}}if(n==="lower"||n==="toLowerCase"){if(i.length!==1)throw f(n);return{kind:"toLowerCase",str:p(i[0],e)}}if(n==="upper"||n==="toUpperCase"){if(i.length!==1)throw f(n);return{kind:"toUpperCase",str:p(i[0],e)}}if(n==="strlen"||n==="strLen"){if(i.length!==1)throw f(n);return{kind:"strLen",str:p(i[0],e)}}if(Qn(n))return i.length===1?{kind:n==="min"?"minArray":"maxArray",array:p(i[0],e)}:{kind:n,args:i.map(r=>p(r,e))};if(n==="sum"){if(i.length!==1)throw f(n);return{kind:"sumArray",array:p(i[0],e)}}if(n==="pow"){if(i.length!==2)throw f(n);return{kind:"pow",base:p(i[0],e),exponent:p(i[1],e)}}if(Xn(n))return{kind:n,args:i.map(r=>p(r,e))};if(n==="if"||n==="cond"){if(i.length!==3)throw f(n);return{kind:"if",cond:p(i[0],e),then:p(i[1],e),else:p(i[2],e)}}if(n==="field"){if(i.length!==2)throw f(n);let r=p(i[0],e),o=i[1];if(o.kind!=="lit"||typeof o.value!="string")throw f(n);return jt({kind:"field",object:i[0],property:o.value},e)}if(Jn(n)){if(i.length!==1)throw f(n);return{kind:n,array:p(i[0],e)}}if(Zn(n)){if(i.length!==1)throw f(n);return{kind:n,obj:p(i[0],e)}}if(n==="at"){if(i.length!==2)throw f(n);return{kind:"at",array:p(i[0],e),index:p(i[1],e)}}if(n==="includes"){if(i.length!==2)throw f(n);return{kind:"includes",array:p(i[0],e),item:p(i[1],e)}}if(ei(n)){if(i.length!==2)throw f(n);let r={...e,allowItem:!0};return n==="map"?{kind:"map",array:p(i[0],e),mapper:p(i[1],r)}:{kind:n,array:p(i[0],e),predicate:p(i[1],r)}}if(n==="slice"){if(i.length<2||i.length>3)throw f(n);let r={kind:"slice",array:p(i[0],e),start:p(i[1],e)};return i.length===3&&(r.end=p(i[2],e)),r}if(n==="substring"||n==="substr"){if(i.length<2||i.length>3)throw f(n);let r={kind:"substring",str:p(i[0],e),start:p(i[1],e)};return i.length===3&&(r.end=p(i[2],e)),r}if(n==="append"){if(i.length<1)throw f(n);return{kind:"append",array:p(i[0],e),items:i.slice(1).map(r=>p(r,e))}}if(n==="merge")return{kind:"merge",objects:i.map(r=>p(r,e))};throw f(n)}function Bn(t,e){let n={};for(let i of Ot(t.fields))n[i.key]=p(i.value,e);return{kind:"object",fields:n}}function Un(t,e){if(t.elements.every(r=>r.kind==="lit"))return{kind:"lit",value:t.elements.map(o=>o.value)};let i=t.elements.map(r=>p(r,e));return i.length===0?{kind:"lit",value:[]}:{kind:"append",array:{kind:"lit",value:[]},items:i}}function Gn(t,e){if(t.length<3)throw f("match");let n=p(t[0],e),i=p(t[t.length-1],e);for(let r=t.length-2;r>=1;r-=1){let o=t[r];if(o.kind!=="arr"||o.elements.length!==2)throw f("match");i={kind:"if",cond:{kind:"eq",left:n,right:p(o.elements[0],e)},then:p(o.elements[1],e),else:i}}return i}function qn(t,e,n){if(e.length<2)throw f(t);let i=e[e.length-1];if(i.kind!=="lit"||i.value!=="first"&&i.value!=="last")throw f(t);let r=e.slice(0,-1).map(o=>Hn(o,n,t));if(r.length===0)throw f(t);return Vn(t,r,i.value)}function Hn(t,e,n){if(t.kind!=="arr"||t.elements.length!==3)throw f(n);return{label:p(t.elements[0],e),eligible:p(t.elements[1],e),score:p(t.elements[2],e)}}function Vn(t,e,n){let i={kind:"lit",value:null};for(let r=e.length-1;r>=0;r-=1)i={kind:"if",cond:zn(t,e,n,r),then:e[r].label,else:i};return i}function zn(t,e,n,i){let r=e[i],o=[];for(let a=0;a<e.length;a+=1){if(a===i)continue;let s=e[a];o.push({kind:"or",args:[{kind:"not",arg:s.eligible},{kind:Kn(t,n,i,a),left:r.score,right:s.score}]})}return o.length===0?r.eligible:{kind:"and",args:[r.eligible,...o]}}function Kn(t,e,n,i){let r=e==="first"?n<i:n>i;return t==="argmax"?r?"gte":"gt":r?"lte":"lt"}function Wn(t){return["eq","neq","gt","gte","lt","lte","add","sub","mul","div","mod"].includes(t)}function _t(t){return["not","neg","abs","floor","ceil","round","sqrt","len","typeof","isNull","toString"].includes(t)}function Yn(t){if(t==="isNotNull")throw f(t);if(!_t(t))throw f(t);return t}function Qn(t){return t==="min"||t==="max"}function Xn(t){return["and","or","concat","coalesce"].includes(t)}function Jn(t){return["first","last"].includes(t)}function Zn(t){return["keys","values","entries"].includes(t)}function ei(t){return["filter","find","every","some","map"].includes(t)}function ti(t,e){return t.map(n=>ni(n,e))}function ni(t,e){let n=t.condition?p(t.condition,Ae(e,"action")):void 0,i=ii(t.op,e);return{fragmentId:t.fragmentId,condition:n,op:i,confidence:t.confidence}}function ii(t,e){switch(t.kind){case"addType":return{kind:"addType",typeName:t.typeName,typeExpr:J(t.typeExpr)};case"addField":return{kind:"addField",typeName:t.typeName,field:{name:t.field.name,type:J(t.field.type),optional:t.field.optional,defaultValue:t.field.defaultValue}};case"setFieldType":return{kind:"setFieldType",path:t.path,typeExpr:J(t.typeExpr)};case"setDefaultValue":return{kind:"setDefaultValue",path:t.path,value:t.value};case"addConstraint":return{kind:"addConstraint",targetPath:t.targetPath,rule:p(t.rule,Ae(e,"schema")),message:t.message};case"addComputed":return{kind:"addComputed",name:t.name,expr:p(t.expr,Ae(e,"schema")),deps:t.deps};case"addActionAvailable":return{kind:"addActionAvailable",actionName:t.actionName,expr:p(t.expr,Ae(e,"schema"))}}}function J(t){switch(t.kind){case"primitive":return{kind:"primitive",name:t.name};case"array":return{kind:"array",element:J(t.element)};case"object":return{kind:"object",fields:t.fields.map(e=>({name:e.name,type:J(e.type),optional:e.optional}))};case"union":return{kind:"union",members:t.members.map(J)};case"literal":return{kind:"literal",value:t.value};case"ref":return{kind:"ref",name:t.name}}}function Ae(t,e){return{mode:e,allowSysPaths:t.allowSysPaths,fnTableVersion:t.fnTableVersion,actionName:t.actionName,allowItem:!1}}function ri(t,e){return t.map(n=>Ce(n,e))}function Ce(t,e){let n=t.condition?p(t.condition,e):void 0,i=t.value?p(t.value,e):void 0;return{condition:n,op:t.op,path:oi(t.path,e),value:i}}function oi(t,e){return t.map(n=>n.kind==="prop"?n:{kind:"expr",expr:p(n.expr,e)})}function A(t,e={}){switch(t.kind){case"literal":return{kind:"lit",value:ci(t.value,t.literalType)};case"identifier":return e.resolveIdentifier?.(t.name)??$(t.name);case"systemIdent":return ai(t,e);case"iterationVar":return{kind:"var",name:t.name};case"propertyAccess":return si(t.object,t.property,e);case"indexAccess":return{kind:"call",fn:"at",args:[A(t.object,e),A(t.index,e)]};case"functionCall":return{kind:"call",fn:t.name,args:t.args.map(n=>A(n,e))};case"unary":return{kind:"call",fn:t.operator==="!"?"not":"neg",args:[A(t.operand,e)]};case"binary":return{kind:"call",fn:li(t.operator),args:[A(t.left,e),A(t.right,e)]};case"ternary":return{kind:"call",fn:"cond",args:[A(t.condition,e),A(t.consequent,e),A(t.alternate,e)]};case"objectLiteral":return{kind:"obj",fields:t.properties.map(n=>({key:n.key,value:A(n.value,e)}))};case"arrayLiteral":return{kind:"arr",elements:t.elements.map(n=>A(n,e))}}}function $(...t){return{kind:"get",path:$t(...t)}}function ot(t,...e){return{kind:"get",base:t,path:$t(...e)}}function se(...t){return{kind:"sys",path:t}}function Pe(t){return{kind:"obj",fields:Object.entries(t).map(([e,n])=>({key:e,value:n}))}}function $t(...t){return t.map(e=>({kind:"prop",name:e}))}function ai(t,e){return e.resolveSystemIdent?.(t.path)??se(...t.path)}function si(t,e,n){let i=A(t,n);return i.kind==="get"?{kind:"get",...i.base?{base:i.base}:void 0,path:[...i.path,{kind:"prop",name:e}]}:i.kind==="var"&&i.name==="item"?ot(i,e):{kind:"field",object:i,property:e}}function ci(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 li(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 fi,semanticPathToPatchPath as yi,sha256Sync as gi}from"@manifesto-ai/core";var di=new Set(["findById","existsById","updateById","removeById"]);function Bt(t){return{...t,computed:{fields:Object.fromEntries(Object.entries(t.computed.fields).map(([e,n])=>[e,pi(n)]))},actions:Object.fromEntries(Object.entries(t.actions).map(([e,n])=>[e,ui(n)]))}}function pi(t){return{...t,expr:Ut(t.expr)}}function ui(t){return{...t,flow:Ie(t.flow),available:t.available?Ut(t.available):void 0,dispatchable:t.dispatchable?mi(t.dispatchable):void 0}}function Ie(t){switch(t.kind){case"seq":return{kind:"seq",steps:t.steps.map(e=>Ie(e))};case"if":return{kind:"if",cond:at(t.cond),then:Ie(t.then),else:t.else?Ie(t.else):void 0};case"patch":return{kind:"patch",op:t.op,path:t.path,value:t.value?at(t.value):void 0};case"effect":return{kind:"effect",type:t.type,params:Object.fromEntries(Object.entries(t.params).map(([e,n])=>[e,hi(n)]))};case"fail":return{kind:"fail",code:t.code,message:t.message?at(t.message):void 0};case"call":case"halt":return t}}function Ut(t){return p(D(t),Ze)}function at(t){return p(D(t),et)}function mi(t){return p(D(t),tt)}function hi(t){return p(D(t),nt)}function D(t){switch(t.kind){case"lit":case"var":return t;case"sys":return t.path[0]==="system"?$("$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 di.has(t.fn)?D(Gt(t.fn,t.args)):{kind:"call",fn:t.fn,args:t.args.map(e=>D(e))}}}function Gt(t,e){let[n,i,r]=e,o=D(n),a=i?D(i):{kind:"lit",value:null},s={kind:"var",name:"item"},c=ot(s,"id");switch(t){case"findById":return{kind:"call",fn:"find",args:[o,{kind:"call",fn:"eq",args:[c,a]}]};case"existsById":return{kind:"call",fn:"not",args:[{kind:"call",fn:"isNull",args:[Gt("findById",e)]}]};case"updateById":{let l=r?D(r):Pe({});return{kind:"call",fn:"map",args:[o,{kind:"call",fn:"cond",args:[{kind:"call",fn:"eq",args:[c,a]},{kind:"call",fn:"merge",args:[s,l]},s]}]}}case"removeById":return{kind:"call",fn:"filter",args:[o,{kind:"call",fn:"not",args:[{kind:"call",fn:"eq",args:[c,a]}]}]};default:return{kind:"call",fn:t,args:e.map(l=>D(l))}}}function Ei(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 ki(t){let e=Ei(t.domain.name);Ti(t.domain,e);let n=Ni(t.domain,e),i=bi(t.domain,e),r=xi(t.domain,e),o=Pi(t.domain,e);if(e.diagnostics.some(l=>l.severity==="error"))return{schema:null,diagnostics:e.diagnostics};let a={id:`mel:${t.domain.name.toLowerCase()}`,version:"1.0.0",types:n,state:i,computed:r,actions:o,meta:{name:t.domain.name}},s=Ui(a);return{schema:{...a,hash:s},diagnostics:e.diagnostics}}function qt(t){let e=ki(t);return e.schema?{schema:Bt(e.schema),diagnostics:e.diagnostics}:{schema:null,diagnostics:e.diagnostics}}function Ti(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 i of n.fields)e.stateFields.add(i.name);else n.kind==="computed"?e.computedFields.add(n.name):n.kind}function Ni(t,e){let n={};for(let i of t.types){let r=H(i.typeExpr);e.typeDefinitions.set(i.name,r),n[i.name]={name:i.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 i of t.fields)e[i.name]={type:H(i.typeExpr),optional:i.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 bi(t,e){let n={},i={};for(let r of t.members)if(r.kind==="state")for(let o of r.fields){let a=H(o.typeExpr);i[o.name]=a,e.stateFieldTypes.set(o.name,a);let s=Y(o.typeExpr,e);s&&e.stateFieldSpecs.set(o.name,s);let c=Si(o,e);c&&(n[o.name]=c)}return{fields:n,fieldTypes:i}}function Si(t,e){let n=Y(t.typeExpr,e);if(!n)return null;let i=t.initializer?De(t.initializer,e):void 0;return i!==void 0&&le(i,H(t.typeExpr),t.name,t.location,e),{...n,required:!0,default:i}}function Y(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 i=e.typeDefs.get(t.name);return i?n.includes(t.name)?(st(e,"E044",`Recursive type '${t.name}' cannot be lowered to FieldSpec in a schema position`,t.location),null):Y(i.typeExpr,e,[...n,t.name]):{type:"object",required:!0}}}case"unionType":{let i=t.types.filter(s=>!(s.kind==="simpleType"&&s.name==="null")&&!(s.kind==="literalType"&&s.value===null)),r=i.length!==t.types.length,o=[],a=!r;for(let s of i){if(s.kind!=="literalType"){a=!1;break}o.push(s.value)}return a&&o.length>0?{type:{enum:o},required:!0}:r&&i.length===1?Y(i[0],e,n):(st(e,"E043",`Union type '${Z(t)}' cannot be soundly lowered to FieldSpec`,t.location),null)}case"arrayType":{let i=Y(t.elementType,e,n);return i?{type:"array",required:!0,items:i}: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 i={};for(let r of t.fields){let o=Y(r.typeExpr,e,n);if(!o)return null;i[r.name]={...o,required:!r.optional}}return{type:"object",required:!0,fields:i}}}}function st(t,e,n,i){t.diagnostics.push({severity:"error",code:e,message:n,location:i})}function Z(t){switch(t.kind){case"simpleType":return t.name;case"unionType":return t.types.map(e=>Z(e)).join(" | ");case"arrayType":return`Array<${Z(t.elementType)}>`;case"recordType":return`Record<${Z(t.keyType)}, ${Z(t.valueType)}>`;case"literalType":return JSON.stringify(t.value);case"objectType":return`{ ${t.fields.map(e=>`${e.name}${e.optional?"?":""}: ${Z(e.typeExpr)}`).join("; ")} }`}}function de(t,e,n=[]){if(t.kind!=="ref")return t;if(n.includes(t.name))return null;let i=e.typeDefinitions.get(t.name);return i?de(i,e,[...n,t.name]):null}function V(t){switch(t.kind){case"primitive":return t.type;case"array":return`Array<${V(t.element)}>`;case"record":return`Record<${V(t.key)}, ${V(t.value)}>`;case"object":return`{ ${Object.entries(t.fields).map(([e,n])=>`${e}${n.optional?"?":""}: ${V(n.type)}`).join("; ")} }`;case"union":return t.types.map(e=>V(e)).join(" | ");case"literal":return JSON.stringify(t.value);case"ref":return t.name}}function ce(t,e,n){let i=de(e,n);if(!i)return!1;switch(i.kind){case"primitive":switch(i.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,i.value);case"array":return Array.isArray(t)&&t.every(r=>ce(r,i.element,n));case"record":return t!==null&&!Array.isArray(t)&&typeof t=="object"&&Object.values(t).every(r=>ce(r,i.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 i.fields))return!1;for(let[r,o]of Object.entries(i.fields)){if(!(r in t)){if(!o.optional)return!1;continue}if(!ce(t[r],o.type,n))return!1}return!0;case"union":return i.types.some(r=>ce(t,r,n));case"ref":return!1}}function le(t,e,n,i,r){if(t===void 0)return;let o=de(e,r);if(!o){r.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${V(e)}, got ${JSON.stringify(t)}`,location:i});return}if(o.kind==="union"){if(ce(t,o,r))return;r.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${V(o)}, got ${JSON.stringify(t)}`,location:i});return}switch(o.kind){case"primitive":{let a=Array.isArray(t)?"array":t===null?"null":typeof t;switch(o.type){case"null":t!==null&&W(r,n,"null",a,i);return;case"string":case"number":case"boolean":typeof t!==o.type&&W(r,n,o.type,a,i);return;case"object":(t===null||Array.isArray(t)||typeof t!="object")&&W(r,n,"object",a,i);return;case"array":Array.isArray(t)||W(r,n,"array",a,i);return}return}case"literal":Object.is(t,o.value)||r.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects literal ${JSON.stringify(o.value)}, got ${JSON.stringify(t)}`,location:i});return;case"array":if(!Array.isArray(t)){W(r,n,"array",t===null?"null":typeof t=="object"?"object":typeof t,i);return}for(let a=0;a<t.length;a+=1)le(t[a],o.element,`${n}[${a}]`,i,r);return;case"record":if(t===null||Array.isArray(t)||typeof t!="object"){let a=Array.isArray(t)?"array":t===null?"null":typeof t;W(r,n,"object",a,i);return}for(let[a,s]of Object.entries(t))le(s,o.value,`${n}.${a}`,i,r);return;case"object":if(t===null||Array.isArray(t)||typeof t!="object"){let a=Array.isArray(t)?"array":t===null?"null":typeof t;W(r,n,"object",a,i);return}for(let a of Object.keys(t))a in o.fields||r.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}.${a}' is not declared in ${V(o)}`,location:i});for(let[a,s]of Object.entries(o.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:i});continue}le(t[a],s.type,`${n}.${a}`,i,r)}return;case"ref":r.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${V(e)}, got ${JSON.stringify(t)}`,location:i});return}}function W(t,e,n,i,r){t.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${e}' expects ${n}, got ${i}`,location:r})}function De(t,e){switch(t.kind){case"literal":return t.value;case"arrayLiteral":return t.elements.map(n=>De(n,e));case"objectLiteral":{let n={};for(let i of t.properties)n[i.key]=De(i.value,e);return n}default:return}}function xi(t,e){let n=[],i=0;for(let o of t.members)if(o.kind==="computed"){let a=B(o.expression,e),s=Ci(a);n.push({name:o.name,deps:s,expr:a,location:o.location,order:i}),i+=1}let r={};for(let o of vi(n,e))r[o.name]={deps:o.deps,expr:o.expr};return{fields:r}}function vi(t,e){if(t.length<=1)return[...t];let n=new Map(t.map(c=>[c.name,c])),i=new Map,r=new Map,o=new Map;for(let c of t)r.set(c.name,[]),o.set(c.name,0);for(let c of t){let l=Array.from(new Set(c.deps.filter(d=>n.has(d))));i.set(c.name,l),o.set(c.name,l.length);for(let d of l)r.get(d).push(c.name)}let a=t.filter(c=>(o.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 l of r.get(c)??[]){let d=(o.get(l)??0)-1;o.set(l,d),d===0&&wi(a,l,n)}}if(s.length!==t.length){let c=new Set(s.map(m=>m.name)),l=t.filter(m=>!c.has(m.name)),d=Ai(l[0].name,i),u=d?d.join(" -> "):l.map(m=>m.name).join(", ");return st(e,"E040",`Circular computed dependency: ${u}`,(d?n.get(d[0]):l[0]).location),[...t]}return s}function wi(t,e,n){let i=n.get(e)?.order??Number.MAX_SAFE_INTEGER,r=t.length;for(let o=0;o<t.length;o+=1){let a=n.get(t[o])?.order??Number.MAX_SAFE_INTEGER;if(i<a){r=o;break}}t.splice(r,0,e)}function Ai(t,e){let n=new Set,i=[],r=new Set;function o(a){n.add(a),i.push(a),r.add(a);for(let s of e.get(a)??[])if(n.has(s)){if(r.has(s)){let c=i.indexOf(s);return[...i.slice(c),s]}}else{let c=o(s);if(c)return c}return i.pop(),r.delete(a),null}return o(t)}function Ci(t){let e=new Set;function n(i){switch(i.kind){case"lit":case"sys":case"var":return;case"get":i.base===void 0?e.add(i.path.map(r=>r.name).join(".")):n(i.base);return;case"field":n(i.object);return;case"call":for(let r of i.args)n(r);return;case"obj":for(let r of i.fields)n(r.value);return;case"arr":for(let r of i.elements)n(r);return}}return n(t),Array.from(e)}function Pi(t,e){let n={};for(let i of t.members)if(i.kind==="action"){e.currentAction=i.name,e.onceIntentCounters.set(i.name,0);let r=new Set;for(let u of i.params)r.add(u.name);e.actionParams.set(i.name,r);let o=i.params.map(u=>u.name),a=Ht(i.body,e),s,c;if(i.params.length>0){let u={},m={};for(let g of i.params){let N=Y(g.typeExpr,e);N&&(u[g.name]=structuredClone(N),m[g.name]={type:H(g.typeExpr),optional:!1})}s={type:"object",required:!0,fields:u},c={kind:"object",fields:m}}let l;i.available&&(l=B(i.available,e));let d;i.dispatchable&&(d=B(i.dispatchable,e,{preferActionParams:!0})),n[i.name]={flow:a,input:s,inputType:c,params:o,available:l,dispatchable:d},e.currentAction=null}return n}function Ht(t,e){return t.length===0?{kind:"seq",steps:[]}:t.length===1?Re(t[0],e):{kind:"seq",steps:t.map(n=>Re(n,e))}}function Re(t,e){switch(t.kind){case"when":return Ii(t,e);case"once":return Mi(t,e);case"onceIntent":return Di(t,e);case"patch":return Ri(t,e);case"effect":return Li(t,e);case"fail":return Oi(t,e);case"stop":return ji(t,e);case"include":return{kind:"seq",steps:[]}}}function Ii(t,e){let n=B(t.condition,e),i=Ht(t.body,e);return{kind:"if",cond:n,then:i}}function Mi(t,e){let n=ct(t.marker,e),i=se("meta","intentId"),r=Le("neq",[$(...Vt(n)),i]);if(t.condition){let s=B(t.condition,e);r=Le("and",[r,s])}let o={kind:"patch",op:"set",path:lt(n),value:i},a=t.body.map(s=>Re(s,e));return{kind:"if",cond:r,then:{kind:"seq",steps:[o,...a]}}}function Di(t,e){let n=e.currentAction??"unknown",i=e.onceIntentCounters.get(n)??0;e.onceIntentCounters.set(n,i+1);let r=gi(`${n}:${i}:intent`),o=`$mel.guards.intent.${r}`,a=se("meta","intentId"),s=Le("neq",[$(...Vt(o)),a]);if(t.condition){let d=B(t.condition,e);s=Le("and",[s,d])}let c={kind:"patch",op:"merge",path:lt("$mel.guards.intent"),value:Pe({[r]:a})},l=t.body.map(d=>Re(d,e));return{kind:"if",cond:s,then:{kind:"seq",steps:[c,...l]}}}function Ri(t,e){let n=ct(t.path,e),i={kind:"patch",op:t.op,path:lt(n)};if(t.value){let r=B(t.value,e);if(i.value=r,t.op==="set"){let o=t.path.segments[0];if(o.kind==="propertySegment"){let a=e.stateFieldTypes.get(o.name);if(a){let s=a,c=t.path.segments;for(let l=1;l<c.length;l++){let d=c[l],u=s?de(s,e):null;if(!u){s=null;break}if(u.kind==="union"){let m=u.types.filter(g=>{let N=de(g,e);return!(N?.kind==="primitive"&&N.type==="null")&&!(N?.kind==="literal"&&N.value===null)});if(m.length!==1){s=null;break}s=m[0],l-=1;continue}if(d.kind==="propertySegment"&&u.kind==="object"&&u.fields[d.name])s=u.fields[d.name].type;else if(d.kind==="propertySegment"&&u.kind==="record")s=u.value;else if(d.kind==="indexSegment"&&u.kind==="array")s=u.element;else{s=null;break}}if(s){let l=Fi(t.value,e);if(l!==void 0){let d=t.path.segments.map(u=>u.kind==="propertySegment"?u.name:"[*]").join(".");le(l,s,d,t.location,e)}}}}}}return i}function Li(t,e){let n={};for(let i of t.args)i.isPath?n[i.name]={kind:"lit",value:ct(i.value,e)}:n[i.name]=B(i.value,e);return{kind:"effect",type:t.effectType,params:n}}function Fi(t,e){return De(t,e)}function Oi(t,e){let n={kind:"fail",code:t.code};return t.message&&(n.message=B(t.message,e)),n}function ji(t,e){return{kind:"halt",reason:t.reason}}function _i(t){return t.replaceAll("\\","\\\\").replaceAll(".","\\.")}function Me(...t){return t.map(_i).join(".")}function ct(t,e){let n=[];for(let r of t.segments)if(r.kind==="propertySegment")n.push(r.name);else{let o=B(r.index,e);o.kind==="lit"?n.push(String(o.value)):n.push("*")}let i=n[0];return e.stateFields.has(i)?Me(...n):e.computedFields.has(i)?Me(...n):e.currentAction&&e.actionParams.get(e.currentAction)?.has(i)?`input.${Me(...n)}`:Me(...n)}function lt(t){return yi(t)}function Le(t,e){return{kind:"call",fn:t,args:e}}function Vt(t){return t.split(/(?<!\\)\./g).map(e=>e.replaceAll("\\.",".").replaceAll("\\\\","\\"))}function B(t,e,n={}){return A(t,{resolveIdentifier:i=>$i(i,e,n),resolveSystemIdent:i=>Bi(i,e)})}function $i(t,e,n={}){return n.preferActionParams&&e.currentAction&&e.actionParams.get(e.currentAction)?.has(t)?$("input",t):e.stateFields.has(t)||e.computedFields.has(t)?$(t):e.currentAction&&e.actionParams.get(e.currentAction)?.has(t)?$("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}}}),$(t))}function Bi(t,e){let[n,...i]=t;switch(n){case"system":case"meta":case"input":return se(n,...i);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 Ui(t){return fi(t)}var dt=16;function T(t){return structuredClone(t)}function w(t,e,n,i,r){let o=`${n}:${r.start.offset}:${r.end.offset}:${i}`;e.has(o)||(e.add(o),t.push(ke(n,i,r)))}function Gi(t){let e=new Map,n=new Set,i=new Map,r=new Set,o=new Map;for(let a of t.types)i.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":o.has(a.name)||o.set(a.name,a);break}return{stateTypes:e,computedNames:n,typeDefs:i,actionNames:r,flows:o}}function qi(t){let e=new Map;for(let n of t.params)e.set(n.name,n.typeExpr);return e}function Hi(t){let e=new Map;for(let n of t.params)e.set(n.name,n.typeExpr);return e}function Vi(t,e,n,i){let r=new Map;for(let o of e.flows.values()){r.set(o.name,[]),e.actionNames.has(o.name)&&w(n,i,"E022",`Flow '${o.name}' conflicts with action '${o.name}'.`,o.location);for(let s of o.params)(e.stateTypes.has(s.name)||e.computedNames.has(s.name)||e.typeDefs.has(s.name))&&w(n,i,"E021",`Flow parameter '${s.name}' conflicts with a top-level identifier.`,s.location);let a=qi(o);for(let s of o.body)Ki(s,o.name,a,e,n,i,r.get(o.name))}for(let o of t.members)if(o.kind==="action"){let a=Hi(o);for(let s of o.body)zi(s,a,e,n,i)}return r}function zi(t,e,n,i,r){switch(t.kind){case"include":Oe(t,e,n,i,r);break;case"when":for(let o of t.body)te(o,e,n,i,r);break;case"once":for(let o of t.body)te(o,e,n,i,r);break;case"onceIntent":for(let o of t.body)te(o,e,n,i,r);break;case"fail":case"stop":break}}function te(t,e,n,i,r){switch(t.kind){case"include":w(i,r,"E016","include is only allowed at action or flow body top-level.",t.location),Oe(t,e,n,i,r);break;case"when":for(let o of t.body)te(o,e,n,i,r);break;case"once":for(let o of t.body)te(o,e,n,i,r);break;case"onceIntent":for(let o of t.body)te(o,e,n,i,r);break;case"patch":case"effect":case"fail":case"stop":break}}function Ki(t,e,n,i,r,o,a){switch(t.kind){case"include":Oe(t,n,i,r,o)&&a.push({target:t.flowName,location:t.location});break;case"when":for(let s of t.body)Fe(s,e,n,i,r,o);break;case"once":w(r,o,"E017","once() is not allowed in flow bodies.",t.location);break;case"onceIntent":w(r,o,"E018","onceIntent is not allowed in flow bodies.",t.location);break;case"patch":w(r,o,"E019","patch is not allowed in flow bodies.",t.location);break;case"effect":w(r,o,"E020","effect is not allowed in flow bodies.",t.location);break}}function Fe(t,e,n,i,r,o){switch(t.kind){case"include":w(r,o,"E016","include is only allowed at action or flow body top-level.",t.location),Oe(t,n,i,r,o);break;case"when":for(let a of t.body)Fe(a,e,n,i,r,o);break;case"once":w(r,o,"E017","once() is not allowed in flow bodies.",t.location);for(let a of t.body)Fe(a,e,n,i,r,o);break;case"onceIntent":w(r,o,"E018","onceIntent is not allowed in flow bodies.",t.location);for(let a of t.body)Fe(a,e,n,i,r,o);break;case"patch":w(r,o,"E019","patch is not allowed in flow bodies.",t.location);break;case"effect":w(r,o,"E020","effect is not allowed in flow bodies.",t.location);break;case"fail":case"stop":break}}function Oe(t,e,n,i,r){let o=n.flows.get(t.flowName);if(!o)return w(i,r,"E015",`'${t.flowName}' is not a declared flow.`,t.location),!1;if(t.args.length!==o.params.length)return w(i,r,"E023",`include '${t.flowName}' expected ${o.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=o.params[a],l=pe(s,e,n);if(!l)continue;ee(l,c.typeExpr,n)===!1&&w(i,r,"E024",`include '${t.flowName}' argument ${a+1} is not assignable to parameter '${c.name}'.`,s.location)}return!0}function Wi(t,e,n,i){function r(o,a,s){s.add(o);for(let c of t.get(o)??[]){if(a+1>dt){w(n,i,"E014",`Include expansion depth exceeds limit (${dt}).`,c.location);continue}if(s.has(c.target)){w(n,i,"E013","Circular include detected.",c.location);continue}r(c.target,a+1,new Set(s))}}for(let o of e.flows.keys())r(o,1,new Set)}function P(t,e){switch(t.kind){case"identifier":return e.has(t.name)?T(e.get(t.name)):T(t);case"systemIdent":case"literal":case"iterationVar":return T(t);case"functionCall":return{...T(t),args:t.args.map(n=>P(n,e))};case"binary":return{...T(t),left:P(t.left,e),right:P(t.right,e)};case"unary":return{...T(t),operand:P(t.operand,e)};case"ternary":return{...T(t),condition:P(t.condition,e),consequent:P(t.consequent,e),alternate:P(t.alternate,e)};case"propertyAccess":return{...T(t),object:P(t.object,e)};case"indexAccess":return{...T(t),object:P(t.object,e),index:P(t.index,e)};case"objectLiteral":return{...T(t),properties:t.properties.map(n=>({...T(n),value:P(n.value,e)}))};case"arrayLiteral":return{...T(t),elements:t.elements.map(n=>P(n,e))}}}function Yi(t,e){switch(t.kind){case"when":return[zt(t,e)];case"fail":return[{...T(t),message:t.message?P(t.message,e):void 0}];case"stop":return[T(t)];case"patch":case"effect":case"once":case"onceIntent":case"include":return[]}}function zt(t,e){return{...T(t),condition:P(t.condition,e),body:t.body.flatMap(n=>Yi(n,e))}}function Qi(t,e,n){let i=new Map;for(let r=0;r<t.params.length;r+=1)i.set(t.params[r].name,P(e.args[r],n));return i}function Xi(t,e,n,i,r){switch(t.kind){case"when":return[zt(t,n)];case"include":return Kt(t,e,n,i,r);case"once":case"onceIntent":case"patch":case"effect":return[]}}function Kt(t,e,n,i,r){let o=e.flows.get(t.flowName);if(!o||t.args.length!==o.params.length||i>dt||r.includes(t.flowName))return[];let a=Qi(o,t,n),s=[...r,t.flowName];return o.body.flatMap(c=>Xi(c,e,a,i+1,s))}function ne(t){switch(t.kind){case"when":return[{...T(t),body:t.body.flatMap(e=>ne(e))}];case"once":return[{...T(t),body:t.body.flatMap(e=>ne(e))}];case"onceIntent":return[{...T(t),body:t.body.flatMap(e=>ne(e))}];case"include":return[];case"patch":case"effect":case"fail":case"stop":return[T(t)]}}function Ji(t,e,n){switch(t.kind){case"include":return Kt(t,e,new Map,n,[]);case"when":return[{...T(t),body:t.body.flatMap(i=>ne(i))}];case"once":return[{...T(t),body:t.body.flatMap(i=>ne(i))}];case"onceIntent":return[{...T(t),body:t.body.flatMap(i=>ne(i))}];case"fail":case"stop":return[T(t)]}}function Zi(t,e){let n=[];for(let i of t.domain.members)switch(i.kind){case"state":case"computed":n.push(T(i));break;case"action":n.push({...T(i),body:i.body.flatMap(r=>Ji(r,e,1))});break;case"flow":break}return{...T(t),domain:{...T(t.domain),types:t.domain.types.map(i=>T(i)),members:n}}}function pe(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 i=pe(t.object,e,n);return Wt(i,t.property,n)}case"indexAccess":{let i=pe(t.object,e,n);return Yt(i,n)}case"objectLiteral":return{kind:"objectType",fields:t.properties.map(i=>{let r=pe(i.value,e,n);return r?{kind:"typeField",name:i.key,typeExpr:r,optional:!1,location:i.location}:null}).filter(i=>i!==null),location:t.location};case"arrayLiteral":{if(t.elements.length===0)return null;let i=pe(t.elements[0],e,n);return i?{kind:"arrayType",elementType:i,location:t.location}:null}case"systemIdent":case"functionCall":case"binary":case"unary":case"ternary":case"iterationVar":return null}}function ue(t,e,n=new Set){return t?t.kind==="simpleType"&&e.typeDefs.has(t.name)?n.has(t.name)?null:(n.add(t.name),ue(e.typeDefs.get(t.name).typeExpr,e,n)):t:null}function Wt(t,e,n){let i=ue(t,n);if(!i)return null;if(i.kind==="objectType")return i.fields.find(o=>o.name===e)?.typeExpr??null;if(i.kind==="unionType")for(let r of i.types){if(r.kind==="simpleType"&&r.name==="null")continue;let o=Wt(r,e,n);if(o)return o}return null}function Yt(t,e){let n=ue(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 i of n.types){if(i.kind==="simpleType"&&i.name==="null")continue;let r=Yt(i,e);if(r)return r}return null}function ee(t,e,n){let i=ue(t,n),r=ue(e,n);if(!i||!r)return null;if(r.kind==="unionType"){let o=r.types.map(a=>ee(i,a,n));return o.includes(!0)?!0:o.every(a=>a===!1)?!1:null}if(i.kind==="unionType"){let o=i.types.map(a=>ee(a,r,n));return o.every(a=>a===!0)?!0:o.some(a=>a===!1)?!1:null}if(r.kind==="simpleType"){if(i.kind==="simpleType")return i.name===r.name;if(i.kind==="literalType")return r.name==="null"?i.value===null:typeof i.value===r.name}if(r.kind==="literalType")return i.kind!=="literalType"?!1:i.value===r.value;if(r.kind==="arrayType")return i.kind!=="arrayType"?!1:ee(i.elementType,r.elementType,n);if(r.kind==="objectType"){if(i.kind!=="objectType")return!1;for(let o of r.fields){let a=i.fields.find(c=>c.name===o.name);if(!a){if(o.optional)continue;return!1}let s=ee(a.typeExpr,o.typeExpr,n);if(s!==!0)return s}return!0}return r.kind==="recordType"?i.kind!=="recordType"?null:ee(i.valueType,r.valueType,n):null}function Qt(t){let e=Gi(t.domain),n=[],i=new Set,r=Vi(t.domain,e,n,i);return Wi(r,e,n,i),{program:Zi(t,e),diagnostics:n}}import{sha256Sync as je}from"@manifesto-ai/core";function Xt(t){return t.kind==="literal"&&t.literalType==="boolean"&&t.value===!0}function ie(t){return A(t)}var _e=class{constructor(e){this.deps=e;this.exprValidator=new ut(e.mapLocation)}conditionComposer=new pt;exprValidator;collect(e,n,i,r){return this.collectPatchStatements(e,n,i,r)}collectPatchStatements(e,n,i,r){let o=[];for(let a of e){if(a.kind==="patch"){this.exprValidator.validatePath(a.path,n),a.value&&this.exprValidator.validateExpr(a.value,n),o.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=je(`${i.actionName}:${i.whenCounter}:when`);i.whenCounter+=1;let l={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},d=me(l),u=this.collectPatchStatements(a.body,n,i,void 0).map(m=>({patch:m.patch,condition:this.conditionComposer.and(d,m.condition)}));o.push({patch:{kind:"patch",op:"set",path:l,value:{kind:"literal",literalType:"boolean",value:!0,location:a.location},location:a.location},condition:s},...u,{patch:{kind:"patch",op:"unset",path:l,location:a.location}});continue}if(a.kind==="once"){this.exprValidator.validatePath(a.marker,n);let s=r,c=me(a.marker),l=a.marker,d=a.location,u={kind:"call",fn:"neq",args:[c,{kind:"sys",path:["meta","intentId"]}]};if(a.condition){this.exprValidator.validateExpr(a.condition,n);try{u=this.conditionComposer.and(u,this.deps.toMelExpr(a.condition))??u}catch(O){n.push({severity:"error",code:"E_LOWER",message:O.message,location:this.deps.mapLocation(a.condition.location)})}}s=this.conditionComposer.and(r,u);let m=je(`${i.actionName}:${i.onceCounter}:once`);i.onceCounter+=1;let g={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:d},{kind:"propertySegment",name:"__onceScopeGuards",location:d},{kind:"propertySegment",name:m,location:d}],location:d},N=me(g),S=this.collectPatchStatements(a.body,n,i,N);o.push({patch:{kind:"patch",op:"set",path:g,value:{kind:"literal",literalType:"boolean",value:!0,location:d},location:d},condition:s},{patch:{kind:"patch",op:"set",path:l,value:{kind:"systemIdent",path:["meta","intentId"],location:d},location:d},condition:N},...S,{patch:{kind:"patch",op:"unset",path:g,location:d},condition:s});continue}if(a.kind==="onceIntent"){let s=je(`${i.actionName}:${i.onceCounter}:onceIntent`);i.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},l=me(c),d=je(`${i.actionName}:${i.onceIntentCounter}:intent`);i.onceIntentCounter+=1;let u=a.location,g={kind:"call",fn:"neq",args:[me({kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:u},{kind:"propertySegment",name:"guards",location:u},{kind:"propertySegment",name:"intent",location:u},{kind:"propertySegment",name:d,location:u}],location:u}),{kind:"sys",path:["meta","intentId"]}]};if(a.condition){this.exprValidator.validateExpr(a.condition,n);try{g=this.conditionComposer.and(g,this.deps.toMelExpr(a.condition))??g}catch(U){n.push({severity:"error",code:"E_LOWER",message:U.message,location:this.deps.mapLocation(a.condition.location)})}}let N=this.conditionComposer.and(r,g),S={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:u},{kind:"propertySegment",name:"guards",location:u},{kind:"propertySegment",name:"intent",location:u}],location:u},O=this.collectPatchStatements(a.body,n,i,l);o.push({patch:{kind:"patch",op:"set",path:c,value:{kind:"literal",literalType:"boolean",value:!0,location:u},location:u},condition:N},{patch:{kind:"patch",op:"merge",path:S,value:{kind:"objectLiteral",properties:[{kind:"objectProperty",key:d,value:{kind:"systemIdent",path:["meta","intentId"],location:u},location:u}],location:u},location:u},condition:l},...O,{patch:{kind:"patch",op:"unset",path:c,location:u},condition:N});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 o}};function Jt(t){return{op:t.patch.op,path:er(t.patch.path),...t.condition?{condition:t.condition}:void 0,...t.patch.value?{value:ie(t.patch.value)}:void 0}}function me(t){let e=t.segments,n;for(let i of e){if(i.kind==="propertySegment"){let r={kind:"prop",name:i.name};n?n={kind:"call",fn:"field",args:[n,{kind:"lit",value:i.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,ie(i.index)]}}if(!n)throw new Error("Empty patch guard path.");return n}function er(t){return t.segments.map(e=>e.kind==="propertySegment"?{kind:"prop",name:e.name}:{kind:"expr",expr:ie(e.index)})}var pt=class{and(e,n){return e?n?{kind:"call",fn:"and",args:[e,n]}:e:n}},ut=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 i of e.segments)i.kind==="indexSegment"&&this.validateExpr(i.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 i of e.args)this.validateExpr(i,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 i of e.properties)this.validateExpr(i.value,n);return;case"arrayLiteral":for(let i of e.elements)this.validateExpr(i,n);return;case"literal":case"identifier":case"systemIdent":case"iterationVar":return}}validatePrimitiveEquality(e,n,i,r){let o=j(e,new Map,this.symbols),a=j(n,new Map,this.symbols);o!=="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(i)})}};function en(t){let e=[],n=0;for(let i of t)e.push(n),n+=i.length+1;return e}function tn(t,e){return n=>nn(n,t,e)}function mt(t,e,n){return t.map(i=>tr(i,e,n))}function tr(t,e,n){return{...t,location:nn(t.location,e,n)}}function nn(t,e,n){return{...t,start:Zt(t.start,e,n),end:Zt(t.end,e,n)}}function Zt(t,e,n){let i=t.line-3,r=e.length,o=Math.min(Math.max(i,1),r),a=n[o-1]??0,s=e[o-1]??"",c=Math.max(s.length+1,1),l=Math.min(Math.max(t.column-6,1),c);return{line:o,column:l,offset:Math.max(a+l-1,0)}}var he="__compileMelPatch",ir="__patchDomain",rr=" ";function rn(t,e){let n=[],i=[],r=[],o=t.split(`
|
|
9
|
-
`),a=en(o),s=tn(o,a),c=or(t,he),l=performance.now(),d;try{let v=ye(c);d=v.tokens;let R=mt(v.diagnostics.filter(fe=>fe.severity==="error"),o,a);if(R.length>0)return r.push(...R),n.push({phase:"lex",durationMs:performance.now()-l,details:{tokenCount:d.length}}),{ops:[],trace:n,warnings:i,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()-l}),{ops:[],trace:n,warnings:i,errors:r}}n.push({phase:"lex",durationMs:performance.now()-l,details:{tokenCount:d.length}});let u=performance.now(),m;try{let v=ge(d),R=mt(v.diagnostics,o,a),fe=R.filter(Ue=>Ue.severity==="error"),Be=R.filter(Ue=>Ue.severity!=="error");if(fe.length>0)return r.push(...fe),i.push(...Be),n.push({phase:"parse",durationMs:performance.now()-u}),{ops:[],trace:n,warnings:i,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}}}),i.push(...Be),n.push({phase:"parse",durationMs:performance.now()-u}),{ops:[],trace:n,warnings:i,errors:r};m=v.program,i.push(...Be)}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()-u}),{ops:[],trace:n,warnings:i,errors:r}}n.push({phase:"parse",durationMs:performance.now()-u});let g=performance.now(),N={actionName:e.actionName,onceCounter:0,onceIntentCounter:0,whenCounter:0},S=m.domain.members.find(v=>v.kind==="action"&&v.name===he);if(!S)return r.push({severity:"error",code:"E_ANALYZE",message:`Synthetic patch action '${he}' 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()-g}),{ops:[],trace:n,warnings:i,errors:r};let O=o.length+3+2;if(S.location.end.line!==O)return r.push({severity:"error",code:"E_PATCH_WRAPPER",message:`Malformed synthetic patch wrapper for action '${he}'.`,location:s(S.location)}),n.push({phase:"analyze",durationMs:performance.now()-g}),{ops:[],trace:n,warnings:i,errors:r};let[U]=S.body;if(!U||U.kind!=="when"||!Xt(U.condition)||S.body.length!==1)return r.push({severity:"error",code:"E_PATCH_WRAPPER",message:`Malformed synthetic patch wrapper for action '${he}'.`,location:s(S.location)}),n.push({phase:"analyze",durationMs:performance.now()-g}),{ops:[],trace:n,warnings:i,errors:r};let E=new _e({mapLocation:s,toMelExpr:ie}).collect(U.body,r,N,void 0);if(r.length===0&&t.trim()!==""&&E.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(U.location)}),n.push({phase:"analyze",durationMs:performance.now()-g,details:{count:E.length}}),r.length>0)return{ops:[],trace:n,warnings:i,errors:r};let L=performance.now(),re={mode:"action",allowSysPaths:e.allowSysPaths??{prefixes:["meta","input"]},fnTableVersion:e.fnTableVersion??"1.0",actionName:e.actionName},z=[];for(let v of E)try{let R=Jt(v);z.push(Ce(R,re))}catch(R){R instanceof F?r.push({severity:"error",code:R.code,message:R.message,location:s(v.patch.location)}):R instanceof Error?r.push({severity:"error",code:"E_LOWER",message:R.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()-L,details:{count:z.length}}),r.length>0?{ops:[],trace:n,warnings:i,errors:r}:{ops:z,trace:n,warnings:i,errors:r}}function or(t,e){let n=t.split(`
|
|
10
|
-
`).map(i=>`${rr}${i}`).join(`
|
|
11
|
-
`);return[`domain ${ir} {`,` action ${e}() {`," when true {",n," }"," }","}"].join(`
|
|
12
|
-
`)}function ar(t,e){let n=[],i=[],r=[],o=performance.now(),a;try{let E=ye(t);a=E.tokens;let L=E.diagnostics.filter(z=>z.severity==="error");if(L.length>0)return r.push(...L),n.push({phase:"lex",durationMs:performance.now()-o,details:{tokenCount:a.length}}),{schema:null,trace:n,warnings:i,errors:r};let re=E.diagnostics.filter(z=>z.severity==="warning");i.push(...re)}catch(E){let L=E;return r.push({severity:"error",code:"E_LEX",message:L.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"lex",durationMs:performance.now()-o}),{schema:null,trace:n,warnings:i,errors:r}}n.push({phase:"lex",durationMs:performance.now()-o,details:{tokenCount:a.length}});let s=performance.now(),c;try{let E=ge(a),L=E.diagnostics.filter(re=>re.severity==="error");if(L.length>0)return r.push(...L),n.push({phase:"parse",durationMs:performance.now()-s}),{schema:null,trace:n,warnings:i,errors:on(r)};c=E.program}catch(E){let L=E;return r.push({severity:"error",code:"E_PARSE",message:L.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"parse",durationMs:performance.now()-s}),{schema:null,trace:n,warnings:i,errors:r}}n.push({phase:"parse",durationMs:performance.now()-s});let l=performance.now(),d=Qt(c),u=d.diagnostics.filter(E=>E.severity==="error"),m=d.diagnostics.filter(E=>E.severity==="warning"),g=bt(d.program),N=Ft(d.program),S=[...u,...g.diagnostics.filter(E=>E.severity==="error"),...N.diagnostics.filter(E=>E.severity==="error")],O=[...m,...g.diagnostics.filter(E=>E.severity==="warning"),...N.diagnostics.filter(E=>E.severity==="warning")];if(i.push(...O),n.push({phase:"analyze",durationMs:performance.now()-l}),S.length>0)return r.push(...S),{schema:null,trace:n,warnings:i,errors:r};let U=performance.now(),$e=qt(d.program);n.push({phase:"generate",durationMs:performance.now()-U});for(let E of $e.diagnostics)E.severity==="warning"?i.push(E):r.push(E);return{schema:$e.schema,trace:n,warnings:i,errors:on(r)}}var ht=10;function on(t){if(t.length<=ht)return t;let e=t.slice(0,ht);return e.push({severity:"error",code:"E_TOO_MANY",message:`... and ${t.length-ht} 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 sr(t,e){return rn(t,e)}export{Ge as a,an as b,cr as c,ft as d,yt as e,qe as f,gt as g,Et as h,dr as i,h as j,He as k,ye as l,kr as m,Tr as n,kt as o,Ve as p,Tt as q,br as r,Sr as s,Nt as t,ze as u,ge as v,Ee as w,Ke as x,bt as y,ke as z,St as A,Rr as B,sn as C,Lr as D,Fr as E,Je as F,Ft as G,Ze as H,et as I,tt as J,nt as K,Dn as L,F as M,ve as N,f as O,we as P,it as Q,Rn as R,rt as S,Ln as T,p as U,ti as V,ri as W,Ce as X,ki as Y,qt as Z,Qt as _,ar as $,sr as aa};
|