@manifesto-ai/compiler 3.7.0 → 3.8.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.
@@ -1,4 +1,7 @@
1
1
  import type { ComputedNode, DomainNode, ExprNode, ParamNode, TypeDeclNode, TypeExprNode } from "../parser/ast.js";
2
+ import type { SpreadOperandClassification } from "./object-contribution-types.js";
3
+ export type { SpreadOperandClassification, } from "./object-contribution-types.js";
4
+ export { mayYieldArrayExpr } from "./object-contribution-types.js";
2
5
  export type TypeEnv = Map<string, TypeExprNode>;
3
6
  export type ComparableSurfaceClass = "primitive" | "nonprimitive" | "unknown";
4
7
  export interface DomainTypeSymbols {
@@ -19,3 +22,4 @@ export declare function getIndexType(typeExpr: TypeExprNode | null, symbols: Dom
19
22
  export declare function getArrayElementType(typeExpr: TypeExprNode | null, symbols: DomainTypeSymbols): TypeExprNode | null;
20
23
  export declare function isPrimitiveEntityIdType(typeExpr: TypeExprNode, symbols: DomainTypeSymbols): boolean;
21
24
  export declare function isNullType(typeExpr: TypeExprNode): boolean;
25
+ export declare function classifySpreadOperandType(typeExpr: TypeExprNode | null, symbols: DomainTypeSymbols): SpreadOperandClassification;
@@ -0,0 +1,19 @@
1
+ import type { ExprNode, TypeExprNode } from "../parser/ast.js";
2
+ export type SpreadOperandClassification = "object" | "nullable-object" | "invalid" | "unknown";
3
+ type InferExprType<Env, Symbols> = (expr: ExprNode, env: Env, symbols: Symbols) => TypeExprNode | null;
4
+ type ResolveType<Symbols> = (typeExpr: TypeExprNode | null, symbols: Symbols) => TypeExprNode | null;
5
+ type ExprTypeContext<Env, Symbols> = {
6
+ env: Env;
7
+ symbols: Symbols;
8
+ inferExprType: InferExprType<Env, Symbols>;
9
+ resolveType: ResolveType<Symbols>;
10
+ };
11
+ export declare function inferObjectLiteralContributionType<Env, Symbols>(expr: Extract<ExprNode, {
12
+ kind: "objectLiteral";
13
+ }>, env: Env, symbols: Symbols, inferExprType: InferExprType<Env, Symbols>, resolveType: ResolveType<Symbols>): TypeExprNode | null;
14
+ export declare function inferMergeContributionType<Env, Symbols>(expr: Extract<ExprNode, {
15
+ kind: "functionCall";
16
+ }>, env: Env, symbols: Symbols, inferExprType: InferExprType<Env, Symbols>, resolveType: ResolveType<Symbols>): TypeExprNode | null;
17
+ export declare function classifySpreadOperandType<Symbols>(typeExpr: TypeExprNode | null, symbols: Symbols, resolveType: ResolveType<Symbols>): SpreadOperandClassification;
18
+ export declare function mayYieldArrayExpr<Env, Symbols>(expr: ExprNode | undefined, context?: ExprTypeContext<Env, Symbols>): boolean;
19
+ export {};
@@ -64,6 +64,7 @@ export declare class SemanticValidator {
64
64
  private requireAssignable;
65
65
  private requireArrayCompatible;
66
66
  private requireLenCompatible;
67
+ private requireSpreadOperand;
67
68
  private validateCoalesceTypes;
68
69
  private validateMatchCall;
69
70
  private validateArgSelectionCall;
@@ -1,4 +1,4 @@
1
- import{da as t}from"./chunk-YIGJ5PGV.js";function i(o){let e=o.location;if(!e)return`[${o.code}] ${o.message}`;let{line:r,column:n}=e.start;return`[${o.code}] ${o.message} (${r}:${n})`}function s(o){return`export default ${JSON.stringify(o,null,2)};
1
+ import{da as t}from"./chunk-PEO2YZ2Y.js";function i(o){let e=o.location;if(!e)return`[${o.code}] ${o.message}`;let{line:r,column:n}=e.start;return`[${o.code}] ${o.message} (${r}:${n})`}function s(o){return`export default ${JSON.stringify(o,null,2)};
2
2
  `}function a(o,e){let r=t(o,{mode:"domain"});if(r.errors.length>0){let n=r.errors.map(i).join(`
3
3
  `);throw new Error(`MEL compilation failed for ${e}
4
4
  ${n}`)}if(!r.schema)throw new Error(`MEL compilation produced no schema for ${e}`);return s(r.schema)}export{i as a,s as b,a as c};
@@ -1,3 +1,3 @@
1
- import{a as f,b as g}from"./chunk-E4EHOM7R.js";import{da as d}from"./chunk-YIGJ5PGV.js";import{createHash as p}from"crypto";import*as i from"path";import{createUnplugin as h}from"unplugin";var M=new Set(["transform","build","both"]);function l(e){return e.split("?",1)[0]}function b(e,t){return e.lastIndex=0,e.test(t)}function y(e){let t=l(e).replace(/\\/g,"/");if(!t)return"domain.mel";if(!i.isAbsolute(e))return t.replace(/^\.\//,"");let n=i.relative(process.cwd(),e);return!n||n.startsWith("..")||i.isAbsolute(n)?w(t):n.split(i.sep).join("/")}function w(e){let t=i.posix.basename(e)||"domain.mel",n=i.posix.extname(t),o=t.slice(0,t.length-n.length)||"domain",r=p("sha256").update(e).digest("hex").slice(0,12);return`external/${x(o)}--${r}${n}`}function x(e){return e.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"domain"}function E(e){if(!e)return null;if(typeof e=="function")return{emit:e,timing:"transform"};if(typeof e=="object"&&typeof e.emit=="function"){let t=e.timing??"transform";if(!M.has(t))throw new TypeError(`manifesto:mel codegen timing must be one of "transform", "build", or "both" (received ${JSON.stringify(t)})`);return{emit:e.emit,timing:t}}throw new TypeError("manifesto:mel codegen must be a function or an object with a callable emit field")}var O=h((e={})=>{let t=e.include??/\.mel$/,n=new Map,o=E(e.codegen);return{name:"manifesto:mel",enforce:"pre",transformInclude(r){return b(t,l(r))},async transform(r,s){let m=l(s),a=d(r,{mode:"domain"});if(a.errors.length>0){let u=a.errors.map(f).join(`
1
+ import{a as f,b as g}from"./chunk-M3P5RIDR.js";import{da as d}from"./chunk-PEO2YZ2Y.js";import{createHash as p}from"crypto";import*as i from"path";import{createUnplugin as h}from"unplugin";var M=new Set(["transform","build","both"]);function l(e){return e.split("?",1)[0]}function b(e,t){return e.lastIndex=0,e.test(t)}function y(e){let t=l(e).replace(/\\/g,"/");if(!t)return"domain.mel";if(!i.isAbsolute(e))return t.replace(/^\.\//,"");let n=i.relative(process.cwd(),e);return!n||n.startsWith("..")||i.isAbsolute(n)?w(t):n.split(i.sep).join("/")}function w(e){let t=i.posix.basename(e)||"domain.mel",n=i.posix.extname(t),o=t.slice(0,t.length-n.length)||"domain",r=p("sha256").update(e).digest("hex").slice(0,12);return`external/${x(o)}--${r}${n}`}function x(e){return e.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"domain"}function E(e){if(!e)return null;if(typeof e=="function")return{emit:e,timing:"transform"};if(typeof e=="object"&&typeof e.emit=="function"){let t=e.timing??"transform";if(!M.has(t))throw new TypeError(`manifesto:mel codegen timing must be one of "transform", "build", or "both" (received ${JSON.stringify(t)})`);return{emit:e.emit,timing:t}}throw new TypeError("manifesto:mel codegen must be a function or an object with a callable emit field")}var O=h((e={})=>{let t=e.include??/\.mel$/,n=new Map,o=E(e.codegen);return{name:"manifesto:mel",enforce:"pre",transformInclude(r){return b(t,l(r))},async transform(r,s){let m=l(s),a=d(r,{mode:"domain"});if(a.errors.length>0){let u=a.errors.map(f).join(`
2
2
  `);throw new Error(`MEL compilation failed for ${m}
3
3
  ${u}`)}if(!a.schema)throw new Error(`MEL compilation produced no schema for ${m}`);let c=y(m);return o&&((o.timing==="transform"||o.timing==="both")&&await o.emit({schema:a.schema,sourceId:c}),(o.timing==="build"||o.timing==="both")&&n.set(c,a.schema)),g(a.schema)},async buildEnd(){if(!(!o||n.size===0))for(let[r,s]of n)await o.emit({schema:s,sourceId:r})}}});export{O as a};
@@ -0,0 +1,12 @@
1
+ var it={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"},gr=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 aa(e){return e in it}function Vt(e){return gr.has(e)}function Ht(e){return Object.hasOwn(it,e)?it[e]:void 0}function at(e,t,n,r){return{kind:e,lexeme:t,location:n,value:r}}function Kt(e,t,n){return{line:e,column:t,offset:n}}function Wt(e,t,n){return{start:e,end:t,source:n}}function ca(e,t){return{start:e,end:e,source:t}}function y(e,t){return{start:e.start.offset<t.start.offset?e.start:t.start,end:e.end.offset>t.end.offset?e.end:t.end,source:e.source??t.source}}var st=class{source;sourcePath;tokens=[];diagnostics=[];start=0;current=0;line=1;column=1;lineStart=0;constructor(t,n){this.source=t,this.sourcePath=n}tokenize(){for(;!this.isAtEnd();)this.start=this.current,this.scanToken();return this.tokens.push(at("EOF","",this.currentLocation())),{tokens:this.tokens,diagnostics:this.diagnostics}}scanToken(){let t=this.advance();switch(t){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.peek()==="."&&this.peekNext()==="."?(this.advance(),this.advance(),this.addToken("ELLIPSIS")):this.addToken("DOT");break;case"+":this.addToken("PLUS");break;case"-":this.addToken("MINUS");break;case"*":this.addToken("STAR");break;case"%":this.addToken("PERCENT");break;case":":this.addToken("COLON");break;case"@":this.addToken("AT");break;case"=":this.addToken(this.match("=")?"EQ_EQ":"EQ");break;case"!":this.addToken(this.match("=")?"BANG_EQ":"BANG");break;case"<":this.addToken(this.match("=")?"LT_EQ":"LT");break;case">":this.addToken(this.match("=")?"GT_EQ":"GT");break;case"&":this.match("&")?this.addToken("AMP_AMP"):this.error("Expected '&&' for logical AND");break;case"|":this.match("|")?this.addToken("PIPE_PIPE"):this.addToken("PIPE");break;case"?":this.addToken(this.match("?")?"QUESTION_QUESTION":"QUESTION");break;case"/":this.match("/")?this.lineComment():this.match("*")?this.blockComment():this.addToken("SLASH");break;case" ":case"\r":case" ":break;case`
2
+ `:this.newline();break;case'"':this.string('"');break;case"'":this.string("'");break;case"$":this.systemIdentifier();break;default:this.isDigit(t)?this.number():this.isAlpha(t)?this.identifier():this.error(`Unexpected character '${t}'`)}}lineComment(){for(;this.peek()!==`
3
+ `&&!this.isAtEnd();)this.advance()}blockComment(){let t=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 ${t}:${n}`)}string(t){let n=this.line,r=this.column-1,o="";for(;this.peek()!==t&&!this.isAtEnd();){if(this.peek()===`
5
+ `){this.error("Unterminated string literal");return}if(this.peek()==="\\"){this.advance();let i=this.advance();switch(i){case"n":o+=`
6
+ `;break;case"r":o+="\r";break;case"t":o+=" ";break;case"\\":o+="\\";break;case"'":o+="'";break;case'"':o+='"';break;case"0":o+="\0";break;default:this.error(`Invalid escape sequence '\\${i}'`),o+=i}}else o+=this.advance()}if(this.isAtEnd()){this.error(`Unterminated string starting at line ${n}:${r}`);return}this.advance(),this.addToken("STRING",o)}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),r=parseInt(n,16);this.addToken("NUMBER",r);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 t=parseFloat(this.source.slice(this.start,this.current));this.addToken("NUMBER",t)}identifier(){for(;this.isAlphaNumeric(this.peek());){if(this.peek()==="$"){this.advance(),this.error("'$' is forbidden in identifiers (MEL A17)","E004");continue}this.advance()}let t=this.source.slice(this.start,this.current);if(t.startsWith("__sys__")){this.error("'__sys__' prefix is reserved for compiler-generated identifiers (MEL A26)","E004"),this.addToken("ERROR");return}if(Vt(t)){this.error(`'${t}' is a reserved keyword and cannot be used`),this.addToken("ERROR");return}let n=Ht(t);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 t=this.source.slice(this.start,this.current);if(t==="$item"){this.addToken("ITEM");return}if(t==="$system"||t==="$meta"||t==="$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 '${t}'. Expected $system.*, $meta.*, $input.*, or $item`),this.addToken("ERROR")}isAtEnd(){return this.current>=this.source.length}advance(){let t=this.source[this.current];return this.current++,this.column++,t}peek(){return this.isAtEnd()?"\0":this.source[this.current]}peekNext(){return this.current+1>=this.source.length?"\0":this.source[this.current+1]}match(t){return this.isAtEnd()||this.source[this.current]!==t?!1:(this.current++,this.column++,!0)}newline(){this.line++,this.column=1,this.lineStart=this.current}isDigit(t){return t>="0"&&t<="9"}isHexDigit(t){return this.isDigit(t)||t>="a"&&t<="f"||t>="A"&&t<="F"}isAlpha(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"}isAlphaNumeric(t){return this.isAlpha(t)||this.isDigit(t)}currentLocation(){let t=this.positionAt(this.start),n=this.positionAt(this.current);return Wt(t,n,this.sourcePath)}positionAt(t){let n=1,r=0;for(let o=0;o<t;o++)this.source[o]===`
7
+ `&&(n++,r=o+1);return Kt(n,t-r+1,t)}addToken(t,n){let r=this.source.slice(this.start,this.current);this.tokens.push(at(t,r,this.currentLocation(),n))}error(t,n="MEL_LEXER"){let r=this.currentLocation();this.diagnostics.push({severity:"error",code:n,message:t,location:r,source:this.getSourceLine(r.start.line)})}getSourceLine(t){return this.source.split(`
8
+ `)[t-1]??""}};function Le(e,t){return new st(e,t).tokenize()}function ga(e){return["literal","identifier","systemIdent","iterationVar","propertyAccess","indexAccess","functionCall","unary","binary","ternary","objectLiteral","arrayLiteral"].includes(e.kind)}function Ea(e){return["when","once","onceIntent","patch","effect","fail","stop"].includes(e.kind)}var Yt=(f=>(f[f.NONE=0]="NONE",f[f.TERNARY=1]="TERNARY",f[f.NULLISH=2]="NULLISH",f[f.OR=3]="OR",f[f.AND=4]="AND",f[f.EQUALITY=5]="EQUALITY",f[f.COMPARISON=6]="COMPARISON",f[f.ADDITIVE=7]="ADDITIVE",f[f.MULTIPLICATIVE=8]="MULTIPLICATIVE",f[f.UNARY=9]="UNARY",f[f.CALL=10]="CALL",f[f.ACCESS=11]="ACCESS",f))(Yt||{});function ct(e){switch(e){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 Qt(e){switch(e){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 ka(e){return ct(e)!==0}function ba(e){return e==="BANG"||e==="MINUS"}function Jt(e){return e==="QUESTION"||e==="QUESTION_QUESTION"}var lt=class{tokens;current=0;diagnostics=[];constructor(t){this.tokens=t}parse(){try{return{program:this.parseProgram(),diagnostics:this.diagnostics}}catch{return{program:null,diagnostics:this.diagnostics}}}parseProgram(){let t=this.peek().location,n=[];for(;this.check("IMPORT");)n.push(this.parseImport());let r=this.parseAnnotationList();r.length>0&&!this.check("DOMAIN")&&this.reportUnsupportedAnnotations(r);let o=this.parseDomain(r);return{kind:"program",imports:n,domain:o,location:y(t,o.location)}}parseImport(){let t=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 r=this.consume("STRING","Expected string after 'from'");return{kind:"import",names:n,from:r.value,location:y(t,r.location)}}parseDomain(t=[]){let n=this.consume("DOMAIN","Expected 'domain'").location,r=this.consume("IDENTIFIER","Expected domain name").lexeme;this.consume("LBRACE","Expected '{' after domain name");let o=[],i=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let s=this.parseAnnotationList();if(s.length>0&&(this.check("RBRACE")||this.isAtEnd())){this.reportUnsupportedAnnotations(s);continue}if(this.check("TYPE"))o.push(this.parseTypeDecl(s));else{let c=this.parseDomainMember(s);c&&i.push(c)}}let a=this.consume("RBRACE","Expected '}' to close domain").location;return{kind:"domain",name:r,annotations:t.length>0?t:void 0,types:o,members:i,location:y(n,a)}}parseTypeDecl(t=[]){let n=this.consume("TYPE","Expected 'type'").location,r=this.consume("IDENTIFIER","Expected type name").lexeme;this.consume("EQ","Expected '=' after type name");let o=this.parseTypeExpr();return{kind:"typeDecl",name:r,annotations:t.length>0?t:void 0,typeExpr:o,location:y(n,o.location)}}parseDomainMember(t=[]){return this.check("STATE")?(this.reportUnsupportedAnnotations(t),this.parseState()):this.check("COMPUTED")?this.parseComputed(t):this.check("ACTION")?this.parseAction(t):this.isFlowDeclContext()?(this.reportUnsupportedAnnotations(t),this.parseFlowDecl()):(this.reportUnsupportedAnnotations(t),this.error(`Unexpected token '${this.peek().lexeme}'. Expected 'state', 'computed', 'action', or 'flow'.`),this.advance(),null)}parseState(){let t=this.consume("STATE","Expected 'state'").location;this.consume("LBRACE","Expected '{' after 'state'");let n=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let o=this.parseAnnotationList();if(o.length>0&&(this.check("RBRACE")||this.isAtEnd())){this.reportUnsupportedAnnotations(o);continue}n.push(this.parseStateField(o))}let r=this.consume("RBRACE","Expected '}' to close state block").location;return{kind:"state",fields:n,location:y(t,r)}}parseStateField(t=[]){let n=this.consume("IDENTIFIER","Expected field name");this.consume("COLON","Expected ':' after field name");let r=this.parseTypeExpr(),o;return this.match("EQ")&&(o=this.parseExpression()),{kind:"stateField",name:n.lexeme,annotations:t.length>0?t:void 0,typeExpr:r,initializer:o,location:y(n.location,o?.location??r.location)}}parseComputed(t=[]){let n=this.consume("COMPUTED","Expected 'computed'").location,r=this.consume("IDENTIFIER","Expected computed name").lexeme;this.consume("EQ","Expected '=' after computed name");let o=this.parseExpression();return{kind:"computed",name:r,annotations:t.length>0?t:void 0,expression:o,location:y(n,o.location)}}parseAction(t=[]){let n=this.consume("ACTION","Expected 'action'").location,r=this.consume("IDENTIFIER","Expected action name").lexeme;this.consume("LPAREN","Expected '(' after action name");let o=[];if(!this.check("RPAREN"))do{let l=this.parseAnnotationList();if(l.length>0&&(this.check("RPAREN")||this.isAtEnd())){this.reportUnsupportedAnnotations(l);break}o.push(this.parseParam(l))}while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after parameters");let i;this.match("AVAILABLE")&&(this.consume("WHEN","Expected 'when' after 'available'"),i=this.parseExpression());let a;if(this.match("DISPATCHABLE")&&(this.consume("WHEN","Expected 'when' after 'dispatchable'"),a=this.parseExpression()),this.check("AVAILABLE")){let l=a?"'available when' must appear before 'dispatchable when' in an action":"Action can declare 'available when' at most once";throw this.errorAtCurrent(l)}if(this.check("DISPATCHABLE"))throw this.errorAtCurrent("Action can declare 'dispatchable when' at most once");this.consume("LBRACE","Expected '{' to start action body");let s=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let l=this.parseGuardedStmt();l&&s.push(l)}let c=this.consume("RBRACE","Expected '}' to close action").location;return{kind:"action",name:r,annotations:t.length>0?t:void 0,params:o,available:i,dispatchable:a,body:s,location:y(n,c)}}parseFlowDecl(){let t=this.consume("IDENTIFIER","Expected 'flow'"),n=this.consume("IDENTIFIER","Expected flow name").lexeme;this.consume("LPAREN","Expected '(' after flow name");let r=[];if(!this.check("RPAREN"))do{let a=this.parseAnnotationList();if(this.reportUnsupportedAnnotations(a),a.length>0&&(this.check("RPAREN")||this.isAtEnd()))break;r.push(this.parseParam(a))}while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after parameters"),this.consume("LBRACE","Expected '{' to start flow body");let o=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let a=this.parseFlowStmt();a&&o.push(a)}let i=this.consume("RBRACE","Expected '}' to close flow").location;return{kind:"flow",name:n,params:r,body:o,location:y(t.location,i)}}parseParam(t=[]){let n=this.consume("IDENTIFIER","Expected parameter name");this.consume("COLON","Expected ':' after parameter name");let r=this.parseTypeExpr();return{kind:"param",name:n.lexeme,annotations:t.length>0?t:void 0,typeExpr:r,location:y(n.location,r.location)}}parseGuardedStmt(){let t=this.parseAnnotationList();if(this.reportUnsupportedAnnotations(t),this.check("WHEN"))return this.parseWhenStmt();if(this.check("ONCE"))return this.parseOnceStmt();if(this.isOnceIntentContext())return this.parseOnceIntentStmt();if(this.isIncludeContext())return this.parseIncludeStmt();if(this.check("FAIL"))return this.parseFailStmt();if(this.check("STOP"))return this.parseStopStmt();let n=this.peek();return n.kind==="PATCH"||n.lexeme==="patch"||n.kind==="EFFECT"||n.lexeme==="effect"?(this.error(`'${n.lexeme}' must be inside a guard block (when, once, or onceIntent). Wrap it: when true { ${n.lexeme} ... }`),this.skipToRecoveryPoint(),null):(this.error(`Unexpected token '${n.lexeme}'. Expected 'when', 'once', 'onceIntent', 'include', 'fail', or 'stop'.`),this.advance(),null)}parseFlowStmt(){let t=this.parseAnnotationList();return this.reportUnsupportedAnnotations(t),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 t=0;for(;!this.isAtEnd();){let n=this.peek();if(n.kind==="LBRACE"){t++,this.advance();continue}if(n.kind==="RBRACE"){if(t===0)return;t--,this.advance();continue}if(t===0&&(n.kind==="WHEN"||n.kind==="ONCE"||n.lexeme==="onceIntent"||this.isIncludeContext()||n.kind==="FAIL"||n.kind==="STOP"))return;this.advance()}}parseWhenStmt(){let t=this.consume("WHEN","Expected 'when'").location,n=this.parseExpression();this.consume("LBRACE","Expected '{' after when condition");let r=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let i=this.parseInnerStmt();i&&r.push(i)}let o=this.consume("RBRACE","Expected '}' to close when block").location;return{kind:"when",condition:n,body:r,location:y(t,o)}}parseOnceStmt(){let t=this.consume("ONCE","Expected 'once'").location;this.consume("LPAREN","Expected '(' after 'once'");let n=this.parsePath();this.consume("RPAREN","Expected ')' after marker");let r;this.match("WHEN")&&(r=this.parseExpression()),this.consume("LBRACE","Expected '{' to start once block");let o=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let a=this.parseInnerStmt();a&&o.push(a)}let i=this.consume("RBRACE","Expected '}' to close once block").location;return{kind:"once",marker:n,condition:r,body:o,location:y(t,i)}}parseOnceIntentStmt(){let t=this.consume("IDENTIFIER","Expected 'onceIntent'"),n;this.match("WHEN")&&(n=this.parseExpression()),this.consume("LBRACE","Expected '{' to start onceIntent block");let r=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let i=this.parseInnerStmt();i&&r.push(i)}let o=this.consume("RBRACE","Expected '}' to close onceIntent block").location;return{kind:"onceIntent",condition:n,body:r,location:y(t.location,o)}}parseInnerStmt(){let t=this.parseAnnotationList();return this.reportUnsupportedAnnotations(t),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 t=this.consume("IDENTIFIER","Expected 'include'"),n=this.consume("IDENTIFIER","Expected flow name after 'include'");this.consume("LPAREN","Expected '(' after flow name");let r=[];if(!this.check("RPAREN"))do r.push(this.parseExpression());while(this.match("COMMA"));let o=this.consume("RPAREN","Expected ')' after include arguments").location;return{kind:"include",flowName:n.lexeme,args:r,location:y(t.location,o)}}parsePatchStmt(){let t=this.consume("PATCH","Expected 'patch'").location,n=this.parsePath(),r,o,i;return this.match("UNSET")?(r="unset",i=this.previous().location):this.match("MERGE")?(r="merge",o=this.parseExpression(),i=o.location):(this.consume("EQ","Expected '=', 'unset', or 'merge' after path"),r="set",o=this.parseExpression(),i=o.location),{kind:"patch",path:n,op:r,value:o,location:y(t,i)}}parseEffectStmt(){let t=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 r=[];for(;!this.check("RBRACE")&&!this.isAtEnd();)r.push(this.parseEffectArg()),this.match("COMMA");this.consume("RBRACE","Expected '}' after effect arguments");let o=this.consume("RPAREN","Expected ')' to close effect").location;return{kind:"effect",effectType:n,args:r,location:y(t,o)}}parseEffectArg(){let t=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(t.lexeme),r=n?this.parsePath():this.parseExpression();return{kind:"effectArg",name:t.lexeme,value:r,isPath:n,location:y(t.location,r.location)}}parseFailStmt(){let t=this.consume("FAIL","Expected 'fail'").location,n=this.consume("STRING","Expected error code string after 'fail'"),r=n.value,o,i=n.location;return this.match("WITH")&&(o=this.parseExpression(),i=o.location),{kind:"fail",code:r,message:o,location:y(t,i)}}parseStopStmt(){let t=this.consume("STOP","Expected 'stop'").location,n=this.consume("STRING","Expected reason string after 'stop'");return{kind:"stop",reason:n.value,location:y(t,n.location)}}parseTypeExpr(){let t=this.parseBaseType();if(this.check("PIPE")){let n=[t];for(;this.match("PIPE");)n.push(this.parseBaseType());t={kind:"unionType",types:n,location:y(n[0].location,n[n.length-1].location)}}return t}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 t=this.consume("IDENTIFIER","Expected type name");if(this.match("LT"))if(t.lexeme==="Array"){let n=this.parseTypeExpr(),r=this.consume("GT","Expected '>' after array element type").location;return{kind:"arrayType",elementType:n,location:y(t.location,r)}}else if(t.lexeme==="Record"){let n=this.parseTypeExpr();this.consume("COMMA","Expected ',' between Record type parameters");let r=this.parseTypeExpr(),o=this.consume("GT","Expected '>' after Record value type").location;return{kind:"recordType",keyType:n,valueType:r,location:y(t.location,o)}}else{for(this.error(`Unknown generic type '${t.lexeme}'`);!this.check("GT")&&!this.isAtEnd();)this.advance();this.match("GT")}return{kind:"simpleType",name:t.lexeme,location:t.location}}parseObjectType(){let t=this.consume("LBRACE","Expected '{'").location,n=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let o=this.parseAnnotationList();if(o.length>0&&(this.check("RBRACE")||this.isAtEnd())){this.reportUnsupportedAnnotations(o);continue}let i=this.consume("IDENTIFIER","Expected field name"),a=this.match("QUESTION");this.consume("COLON","Expected ':' after field name");let s=this.parseTypeExpr();n.push({kind:"typeField",name:i.lexeme,annotations:o.length>0?o:void 0,typeExpr:s,optional:a,location:y(i.location,s.location)}),this.match("COMMA")}let r=this.consume("RBRACE","Expected '}' to close object type").location;return{kind:"objectType",fields:n,location:y(t,r)}}parseExpression(t=0){let n=this.parsePrimary();for(;;){if(this.check("QUESTION")&&this.peekNext().kind==="DOT")throw this.errorAtCurrent("Object spread is the only bounded JavaScript-like sugar admitted in current MEL. Optional chaining is not supported.");let r=ct(this.peek().kind);if(r<=t)break;if(this.peek().kind==="QUESTION"){n=this.parseTernary(n);continue}let o=Qt(this.peek().kind);if(!o)break;this.advance();let i=Jt(this.previous().kind)?r-1:r,a=this.parseExpression(i);n={kind:"binary",operator:o,left:n,right:a,location:y(n.location,a.location)}}return n}parseTernary(t){this.consume("QUESTION","Expected '?'");let n=this.parseExpression();this.consume("COLON","Expected ':' in ternary expression");let r=this.parseExpression(0);return{kind:"ternary",condition:t,consequent:n,alternate:r,location:y(t.location,r.location)}}parsePrimary(){if(this.check("BANG")||this.check("MINUS")&&this.isUnaryContext()){let t=this.advance(),n=this.parsePrimary();return{kind:"unary",operator:t.kind==="BANG"?"!":"-",operand:n,location:y(t.location,n.location)}}if(this.match("LPAREN")){let t=this.parseExpression();return this.consume("RPAREN","Expected ')' after expression"),t}if(this.check("LBRACE"))return this.parseObjectLiteral();if(this.check("LBRACKET"))return this.parseArrayLiteral();if(this.check("NUMBER")){let t=this.advance();return{kind:"literal",value:t.value,literalType:"number",location:t.location}}if(this.check("STRING")){let t=this.advance();return{kind:"literal",value:t.value,literalType:"string",location:t.location}}if(this.check("TRUE")||this.check("FALSE")){let t=this.advance();return{kind:"literal",value:t.kind==="TRUE",literalType:"boolean",location:t.location}}if(this.check("NULL"))return{kind:"literal",value:null,literalType:"null",location:this.advance().location};if(this.check("SYSTEM_IDENT")){let t=this.advance(),n=t.lexeme.slice(1).split(".");return this.parsePostfix({kind:"systemIdent",path:n,location:t.location})}if(this.check("ITEM")){let t=this.advance();return this.parsePostfix({kind:"iterationVar",name:"item",location:t.location})}if(this.check("MERGE")&&this.peekNext()?.kind==="LPAREN"){let t=this.advance();return this.parseFunctionCall(t)}if(this.check("IDENTIFIER")){let t=this.advance();return this.check("LPAREN")?this.parseFunctionCall(t):this.parsePostfix({kind:"identifier",name:t.lexeme,location:t.location})}return this.error(`Unexpected token '${this.peek().lexeme}'`),{kind:"literal",value:null,literalType:"null",location:this.peek().location}}parseFunctionCall(t){this.consume("LPAREN","Expected '(' for function call");let n=[];if(!this.check("RPAREN"))do n.push(this.parseExpression());while(this.match("COMMA"));let r=this.consume("RPAREN","Expected ')' after arguments").location;return this.parsePostfix({kind:"functionCall",name:t.lexeme,args:n,location:y(t.location,r)})}parsePostfix(t){for(;;)if(this.match("DOT")){let n=this.consume("IDENTIFIER","Expected property name after '.'");t={kind:"propertyAccess",object:t,property:n.lexeme,location:y(t.location,n.location)}}else if(this.match("LBRACKET")){let n=this.parseExpression(),r=this.consume("RBRACKET","Expected ']' after index").location;t={kind:"indexAccess",object:t,index:n,location:y(t.location,r)}}else break;return t}parseObjectLiteral(){let t=this.consume("LBRACE","Expected '{'").location,n=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){if(this.check("LBRACKET"))throw this.errorAtCurrent("Object spread is the only bounded JavaScript-like sugar admitted in current MEL. Computed object keys are not supported.");if(this.match("ELLIPSIS")){let o=this.previous().location,i=this.parseExpression();n.push({kind:"objectSpread",expr:i,location:y(o,i.location)})}else{let o=this.consume("IDENTIFIER","Expected property name");this.consume("COLON","Expected ':' after property name");let i=this.parseExpression();n.push({kind:"objectProperty",key:o.lexeme,value:i,location:y(o.location,i.location)})}this.check("RBRACE")||this.consume("COMMA","Expected ',' between properties")}let r=this.consume("RBRACE","Expected '}' to close object").location;return{kind:"objectLiteral",properties:n,location:y(t,r)}}parseArrayLiteral(){let t=this.consume("LBRACKET","Expected '['").location,n=[];for(;!this.check("RBRACKET")&&!this.isAtEnd();){if(this.check("ELLIPSIS"))throw this.errorAtCurrent("Object spread is the only bounded JavaScript-like sugar admitted in current MEL. Array spread is not supported.");n.push(this.parseExpression()),this.check("RBRACKET")||this.consume("COMMA","Expected ',' between elements")}let r=this.consume("RBRACKET","Expected ']' to close array").location;return{kind:"arrayLiteral",elements:n,location:y(t,r)}}parsePath(){let t=[],n=this.peek().location,r=this.consume("IDENTIFIER","Expected identifier");for(t.push({kind:"propertySegment",name:r.lexeme,location:r.location});;)if(this.match("DOT")){let i=this.consume("IDENTIFIER","Expected property name");t.push({kind:"propertySegment",name:i.lexeme,location:i.location})}else if(this.match("LBRACKET")){let i=this.parseExpression(),a=this.consume("RBRACKET","Expected ']'").location;t.push({kind:"indexSegment",index:i,location:y(i.location,a)})}else break;let o=t[t.length-1];return{kind:"path",segments:t,location:y(n,o.location)}}isUnaryContext(){if(this.current===0)return!0;let t=this.previous();return["LPAREN","LBRACKET","LBRACE","COMMA","COLON","EQ","PLUS","MINUS","STAR","SLASH","PERCENT","AT","EQ_EQ","BANG_EQ","LT","LT_EQ","GT","GT_EQ","AMP_AMP","PIPE_PIPE","BANG","QUESTION","QUESTION_QUESTION"].includes(t.kind)}peek(){return this.tokens[this.current]}peekNext(){return this.peekAt(1)}peekAt(t){return this.current+t>=this.tokens.length?this.tokens[this.tokens.length-1]:this.tokens[this.current+t]}previous(){return this.tokens[this.current-1]}isAtEnd(){return this.peek().kind==="EOF"}advance(){return this.isAtEnd()||this.current++,this.previous()}check(t){return this.isAtEnd()?!1:this.peek().kind===t}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(...t){for(let n of t)if(this.check(n))return this.advance(),!0;return!1}consume(t,n){if(this.check(t))return this.advance();throw this.errorAtCurrent(n)}parseAnnotationList(){let t=[];for(;this.check("AT");)t.push(this.parseAnnotation());return t}parseAnnotation(){let t=this.consume("AT","Expected '@'").location,n=this.consume("IDENTIFIER","Expected annotation name after '@'");if(n.lexeme!=="meta")throw this.errorAtToken(n,"Expected 'meta' after '@'");this.consume("LPAREN","Expected '(' after '@meta'");let r=this.consume("STRING","Expected string tag as first @meta argument"),o;this.match("COMMA")&&(o=this.parseExpression());let i=this.consume("RPAREN","Expected ')' after @meta arguments").location;return{kind:"annotation",tag:r.value,payload:o,location:y(t,i)}}reportUnsupportedAnnotations(t){for(let n of t)this.diagnostics.push({severity:"error",code:"E053",message:"@meta can attach only to domain, type, type field, state field, computed, or action declarations.",location:n.location})}error(t){this.diagnostics.push({severity:"error",code:"MEL_PARSER",message:t,location:this.previous().location})}errorAtCurrent(t){return this.diagnostics.push({severity:"error",code:"MEL_PARSER",message:t,location:this.peek().location}),new Error(t)}errorAtToken(t,n){return this.diagnostics.push({severity:"error",code:"MEL_PARSER",message:n,location:t.location}),new Error(n)}};function Re(e){return new lt(e).parse()}var je=class{parent;symbols=new Map;kind;constructor(t,n=null){this.kind=t,this.parent=n}define(t){this.symbols.set(t.name,t)}lookup(t){let n=this.symbols.get(t);return n||this.parent?.lookup(t)}isDefined(t){return this.symbols.has(t)}},dt=class{diagnostics=[];scopes=new Map;currentScope=null;domainScope=null;analyze(t){return this.diagnostics=[],this.scopes=new Map,this.currentScope=null,this.domainScope=null,this.analyzeDomain(t.domain),{scopes:this.scopes,diagnostics:this.diagnostics}}analyzeDomain(t){let n=new je("domain");this.domainScope=n,this.currentScope=n,this.scopes.set("domain",n);for(let r of t.members)if(r.kind==="state")for(let o of r.fields)this.defineSymbol({name:o.name,kind:"state",location:o.location});else r.kind==="computed"?this.defineSymbol({name:r.name,kind:"computed",location:r.location}):r.kind==="action"?this.defineSymbol({name:r.name,kind:"action",location:r.location}):r.kind;for(let r of t.members)r.kind==="computed"?this.analyzeComputedExpr(r):r.kind==="action"&&this.analyzeAction(r)}analyzeComputedExpr(t){this.analyzeExpr(t.expression,"computed")}analyzeAction(t){let n=new je("action",this.domainScope);this.currentScope=n,this.scopes.set(`action.${t.name}`,n);for(let r of t.params)n.define({name:r.name,kind:"param",location:r.location});for(let r of t.body)this.analyzeStmt(r);this.currentScope=this.domainScope}analyzeStmt(t){switch(t.kind){case"when":this.analyzeExpr(t.condition,"action");for(let n of t.body)this.analyzeStmt(n);break;case"onceIntent":t.condition&&this.analyzeExpr(t.condition,"action");for(let n of t.body)this.analyzeStmt(n);break;case"once":this.validatePath(t.marker),t.condition&&this.analyzeExpr(t.condition,"action");for(let n of t.body)this.analyzeStmt(n);break;case"patch":this.validatePath(t.path),t.value&&this.analyzeExpr(t.value,"action");break;case"effect":for(let n of t.args)n.isPath?this.validatePath(n.value):this.analyzeExpr(n.value,"action");break;case"include":case"fail":case"stop":break}}analyzeExpr(t,n){switch(t.kind){case"identifier":this.checkIdentifier(t.name,t.location,n);break;case"systemIdent":this.checkSystemIdent(t.path,t.location,n);break;case"propertyAccess":this.analyzeExpr(t.object,n);break;case"indexAccess":this.analyzeExpr(t.object,n),this.analyzeExpr(t.index,n);break;case"functionCall":for(let r of t.args)this.analyzeExpr(r,n);break;case"binary":this.analyzeExpr(t.left,n),this.analyzeExpr(t.right,n);break;case"unary":this.analyzeExpr(t.operand,n);break;case"ternary":this.analyzeExpr(t.condition,n),this.analyzeExpr(t.consequent,n),this.analyzeExpr(t.alternate,n);break;case"objectLiteral":for(let r of t.properties)this.analyzeExpr(r.kind==="objectProperty"?r.value:r.expr,n);break;case"arrayLiteral":for(let r of t.elements)this.analyzeExpr(r,n);break;case"iterationVar":break;case"literal":break}}checkIdentifier(t,n,r){let o=this.currentScope?.lookup(t);if(!o){this.error(`Undefined identifier '${t}'`,n,"E_UNDEFINED");return}r==="computed"&&o.kind==="param"&&this.error(`Cannot access parameter '${t}' in computed expression`,n,"E_INVALID_ACCESS")}checkSystemIdent(t,n,r){let[o,...i]=t;if(o==="system"&&r==="computed"&&this.error("Cannot use $system.* in computed expressions (non-deterministic)",n,"E001"),o==="system"){let a=["uuid","timestamp","time.now","random"],s=i.join(".");s&&!a.includes(s)&&this.error(`Invalid system value '$system.${s}'. Valid values: ${a.join(", ")}`,n,"E003")}if(o==="meta"){let a=["intentId","actionName","timestamp"],s=i.join(".");s&&!a.includes(s)&&this.error(`Invalid meta value '$meta.${s}'. Valid values: ${a.join(", ")}`,n,"E003")}}validatePath(t){if(!t||!t.segments)return;let n=t.segments[0];n?.kind==="propertySegment"&&(this.currentScope?.lookup(n.name)||this.error(`Undefined identifier '${n.name}' in path`,t.location,"E_UNDEFINED"))}defineSymbol(t){if(this.currentScope){if(this.currentScope.isDefined(t.name)){this.error(`Duplicate identifier '${t.name}'`,t.location,"E_DUPLICATE");return}this.currentScope.define(t)}}error(t,n,r){this.diagnostics.push({severity:"error",code:r,message:t,location:n})}};function Xt(e){return new dt().analyze(e)}function M(e,t,n,r){return{severity:"error",code:e,message:t,location:n,...r}}function Zt(e,t,n,r){return{severity:"warning",code:e,message:t,location:n,...r}}function Ma(e,t,n){return{severity:"info",code:e,message:t,location:n}}function Er(e){return e.severity==="error"}function Da(e){return e.some(Er)}function Oa(e,t){return e.filter(n=>n.severity===t)}function Fe(e,t,n,r,o){let i=[],a=[],s=()=>{a.length!==0&&(i.push({kind:"objectType",fields:a,location:e.location}),a=[])};for(let c of e.properties){if(c.kind==="objectProperty"){let d=r(c.value,t,n);if(!d)return null;a.push({kind:"typeField",name:c.key,typeExpr:d,optional:!1,location:c.location});continue}s();let l=r(c.expr,t,n);if(!l)return null;i.push(l)}return s(),i.length===0?{kind:"objectType",fields:[],location:e.location}:on(i,e.location,n,o)}function _e(e,t,n,r,o){let i=e.args.map(a=>r(a,t,n));return i.some(a=>a===null)?null:on(i,e.location,n,o)}function en(e,t,n){let r=n(e,t);if(!r)return"unknown";if(r.kind==="objectType")return"object";if(r.kind!=="unionType")return"invalid";let o=r.types.map(s=>n(s,t)).filter(s=>s!==null),i=o.filter(s=>!Z(s));return o.some(s=>Z(s))&&i.length===1&&i[0].kind==="objectType"?"nullable-object":"invalid"}function G(e,t){if(!e)return!1;if(tn(pt(e,t),t)||e.kind==="arrayLiteral")return!0;if(e.kind==="ternary")return G(e.consequent,t)||G(e.alternate,t);if(e.kind!=="functionCall")return!1;if(e.name==="coalesce"){for(let n of e.args)if(!ce(n,t)){if(G(n,t))return!0;if(le(n,t))return!1}return!1}return(e.name==="cond"||e.name==="if")&&e.args.length>=3?G(e.args[1],t)||G(e.args[2],t):!1}function ce(e,t){let n=pt(e,t);return n&&nn(n,t)?!0:e.kind==="literal"?e.value===null:e.kind==="ternary"?ce(e.consequent,t)&&ce(e.alternate,t):e.kind!=="functionCall"?!1:e.name==="coalesce"?e.args.length>0&&e.args.every(r=>ce(r,t)):(e.name==="cond"||e.name==="if")&&e.args.length>=3?ce(e.args[1],t)&&ce(e.args[2],t):!1}function le(e,t){let n=pt(e,t);return n&&rn(n,t)?!0:e.kind==="literal"?e.value!==null:e.kind==="arrayLiteral"||e.kind==="objectLiteral"?!0:e.kind==="ternary"?le(e.consequent,t)&&le(e.alternate,t):e.kind!=="functionCall"?!1:e.name==="coalesce"?e.args.some(r=>le(r,t)):e.name==="merge"?!0:(e.name==="cond"||e.name==="if")&&e.args.length>=3?le(e.args[1],t)&&le(e.args[2],t):!1}function pt(e,t){return t?t.resolveType(t.inferExprType(e,t.env,t.symbols),t.symbols):null}function tn(e,t){if(!e||!t)return!1;let n=t.resolveType(e,t.symbols);return n?n.kind==="arrayType"?!0:n.kind==="unionType"?n.types.some(r=>tn(r,t)):!1:!1}function nn(e,t){if(!t)return Z(e);let n=t.resolveType(e,t.symbols);return n?n.kind==="unionType"?n.types.length>0&&n.types.every(r=>nn(r,t)):Z(n):!1}function rn(e,t){if(!t)return!Z(e);let n=t.resolveType(e,t.symbols);return n?n.kind==="unionType"?n.types.length>0&&n.types.every(r=>rn(r,t)):!Z(n):!1}function on(e,t,n,r){let o=new Map;for(let i of e){let a=Tr(i,n,r);if(!a)return null;for(let s of a){let c=o.get(s.name);if(!c){o.set(s.name,s);continue}if(!s.optional){o.set(s.name,s);continue}let l=kr([c.typeExpr,s.typeExpr],s.location);if(!l)return null;o.set(s.name,{kind:"typeField",name:s.name,typeExpr:l,optional:c.optional,location:s.location})}}return{kind:"objectType",fields:[...o.values()],location:t}}function Tr(e,t,n){let r=n(e,t);if(!r)return null;if(r.kind==="objectType")return r.fields.map(c=>({...c,optional:c.optional}));if(r.kind!=="unionType")return null;let o=r.types.map(c=>n(c,t)).filter(c=>c!==null),i=o.filter(c=>!Z(c));if(!o.some(c=>Z(c))||i.length!==1)return null;let s=i[0];return s.kind!=="objectType"?null:s.fields.map(c=>({...c,optional:!0}))}function Z(e){return e.kind==="simpleType"&&e.name==="null"||e.kind==="literalType"&&e.value===null}function kr(e,t){let n=e.filter(i=>i!==null).flatMap(i=>i.kind==="unionType"?i.types:[i]);if(n.length===0)return null;if(n.length===1)return n[0];let r=[],o=new Set;for(let i of n){let a=JSON.stringify(i);o.has(a)||(o.add(a),r.push(i))}return r.length===1?r[0]:{kind:"unionType",types:r,location:t}}var sn=new Set(["eq","neq","gt","gte","lt","lte","and","or","not","isNull","isNotNull","hasKey","startsWith","endsWith","strIncludes","includes","every","some","existsById"]),cn=new Set(["add","sub","mul","div","mod","absDiff","abs","clamp","floor","ceil","round","sqrt","pow","len","strlen","indexOf","streak","sum","min","max","toNumber"]),ln=new Set(["trim","lower","upper","concat","typeof","toString","substring","substr","replace"]),br=new Set(["keys","values","entries","merge","filter","map","append","reverse","unique","flat","split","fromEntries"]),Nr=new Set(["updateById","removeById"]);function $e(e){let t=new Map,n=new Map,r=new Map;for(let o of e.types)r.set(o.name,o);for(let o of e.members){if(o.kind==="state"){for(let i of o.fields)t.set(i.name,i.typeExpr);continue}o.kind==="computed"&&n.set(o.name,o)}return{stateTypes:t,computedDecls:n,typeDefs:r,computedTypeCache:new Map,computedTypeInFlight:new Set}}function Ge(e){let t=new Map;for(let n of e)t.set(n.name,n.typeExpr);return t}function m(e,t,n){switch(e.kind){case"literal":return Fr(e.value,e.location);case"identifier":return t.get(e.name)??n.stateTypes.get(e.name)??Sr(e.name,n);case"propertyAccess":return te(m(e.object,t,n),e.property,n);case"indexAccess":return we(m(e.object,t,n),n);case"objectLiteral":return Fe(e,t,n,m,k);case"arrayLiteral":{let r=w(e.elements.map(o=>m(o,t,n)),e.location);return r?{kind:"arrayType",elementType:r,location:e.location}:null}case"unary":return vr(e);case"binary":return xr(e,t,n);case"ternary":return w([m(e.consequent,t,n),m(e.alternate,t,n)],e.location);case"functionCall":return Ar(e,t,n);case"systemIdent":return null;case"iterationVar":return t.get("$item")??null}}function B(e,t,n){let r=m(e,t,n);if(r)return dn(r,n);switch(e.kind){case"literal":return"primitive";case"objectLiteral":case"arrayLiteral":return"nonprimitive";case"binary":return e.operator==="??"?xe([B(e.left,t,n),B(e.right,t,n)]):e.operator==="=="||e.operator==="!="||e.operator==="+"||e.operator==="-"||e.operator==="*"||e.operator==="/"||e.operator==="%"||e.operator==="<"||e.operator==="<="||e.operator===">"||e.operator===">="||e.operator==="&&"||e.operator==="||"?"primitive":"unknown";case"unary":return"primitive";case"ternary":return xe([B(e.consequent,t,n),B(e.alternate,t,n)]);case"functionCall":return br.has(e.name)?"nonprimitive":sn.has(e.name)||cn.has(e.name)||ln.has(e.name)||e.name==="toBoolean"?"primitive":(e.name==="cond"||e.name==="if")&&e.args.length>=3?xe([B(e.args[1],t,n),B(e.args[2],t,n)]):e.name==="coalesce"?xe(e.args.map(o=>B(o,t,n))):"unknown";case"identifier":case"propertyAccess":case"indexAccess":case"systemIdent":case"iterationVar":return"unknown"}}function dn(e,t){let n=k(e,t);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 xe(n.types.map(r=>dn(r,t)))}}function k(e,t,n=new Set){return e?e.kind==="simpleType"&&t.typeDefs.has(e.name)?n.has(e.name)?null:(n.add(e.name),k(t.typeDefs.get(e.name).typeExpr,t,n)):e:null}function te(e,t,n){let r=k(e,n);if(!r)return null;if(r.kind==="objectType"){let o=r.fields.find(i=>i.name===t);return o?o.optional?w([o.typeExpr,P("null",o.location)],o.location):o.typeExpr:null}if(r.kind==="unionType"){let o=r.types.filter(i=>!q(i)).map(i=>te(i,t,n)).filter(i=>i!==null);return w(o,r.location)}return null}function we(e,t){let n=k(e,t);if(!n)return null;if(n.kind==="arrayType")return n.elementType;if(n.kind==="recordType")return n.valueType;if(n.kind==="unionType"){let r=n.types.filter(o=>!q(o)).map(o=>we(o,t)).filter(o=>o!==null);return w(r,n.location)}return null}function U(e,t){let n=k(e,t);if(!n)return null;if(n.kind==="arrayType")return n.elementType;if(n.kind==="unionType"){let r=n.types.filter(o=>!q(o)).map(o=>U(o,t)).filter(o=>o!==null);return w(r,n.location)}return null}function Be(e,t){let n=k(e,t);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(r=>Be(r,t));default:return!1}}function q(e){return e.kind==="simpleType"&&e.name==="null"||e.kind==="literalType"&&e.value===null}function Ue(e,t){return en(e,t,k)}function Sr(e,t){if(t.computedTypeCache.has(e))return t.computedTypeCache.get(e)??null;let n=t.computedDecls.get(e);if(!n||t.computedTypeInFlight.has(e))return null;t.computedTypeInFlight.add(e);let r=m(n.expression,new Map,t);return t.computedTypeInFlight.delete(e),t.computedTypeCache.set(e,r),r}function vr(e){return e.operator==="!"?P("boolean",e.location):P("number",e.location)}function xr(e,t,n){switch(e.operator){case"==":case"!=":case"<":case"<=":case">":case">=":case"&&":case"||":return P("boolean",e.location);case"+":case"-":case"*":case"/":case"%":return P("number",e.location);case"??":return w([m(e.left,t,n),m(e.right,t,n)],e.location)}}function Ar(e,t,n){if(sn.has(e.name))return P("boolean",e.location);if(cn.has(e.name))return P("number",e.location);if(e.name==="idiv")return w([P("number",e.location),P("null",e.location)],e.location);if(ln.has(e.name))return P("string",e.location);if(e.name==="toBoolean")return P("boolean",e.location);if(e.name==="findById"&&e.args.length>=1){let r=U(m(e.args[0],t,n),n);return r?w([r,P("null",e.location)],e.location):null}if(e.name==="find"&&e.args.length>=1){let r=U(m(e.args[0],t,n),n);return r?w([r,P("null",e.location)],e.location):null}if(e.name==="filter"&&e.args.length>=1)return m(e.args[0],t,n);if(e.name==="map"&&e.args.length>=2){let r=m(e.args[0],t,n),o=U(r,n);if(!o)return null;let i=m(e.args[1],$r(t,o),n);return i?{kind:"arrayType",elementType:i,location:e.location}:null}if((e.name==="first"||e.name==="last")&&e.args.length>=1)return U(m(e.args[0],t,n),n);if(e.name==="at"&&e.args.length>=1)return we(m(e.args[0],t,n),n);if(e.name==="field"&&e.args.length>=2){let r=_r(e.args[1]);return r?te(m(e.args[0],t,n),r,n):null}return Nr.has(e.name)&&e.args.length>=1?m(e.args[0],t,n):(e.name==="cond"||e.name==="if")&&e.args.length>=3?w([m(e.args[1],t,n),m(e.args[2],t,n)],e.location):e.name==="coalesce"?Rr(e,t,n):e.name==="match"?wr(e,t,n):e.name==="argmax"||e.name==="argmin"?Cr(e,t,n):e.name==="slice"&&e.args.length>=1?m(e.args[0],t,n):e.name==="split"?{kind:"arrayType",elementType:P("string",e.location),location:e.location}:e.name==="keys"?{kind:"arrayType",elementType:P("string",e.location),location:e.location}:e.name==="values"&&e.args.length>=1?jr(e,t,n):e.name==="merge"?_e(e,t,n,m,k):null}function xe(e){let t=!1;for(let n of e){if(n==="nonprimitive")return"nonprimitive";n==="unknown"&&(t=!0)}return t?"unknown":"primitive"}function w(e,t){let n=e.filter(i=>i!==null).flatMap(i=>i.kind==="unionType"?i.types:[i]);if(n.length===0)return null;if(n.length===1)return n[0];let r=[],o=new Set;for(let i of n){let a=JSON.stringify(i);o.has(a)||(o.add(a),r.push(i))}return r.length===1?r[0]:{kind:"unionType",types:r,location:t}}function wr(e,t,n){if(e.args.length<3)return null;let r=[];for(let o=1;o<e.args.length-1;o+=1){let i=e.args[o];if(i.kind!=="arrayLiteral"||i.elements.length!==2)return null;r.push(m(i.elements[1],t,n))}return r.push(m(e.args[e.args.length-1],t,n)),w(r,e.location)}function Cr(e,t,n){if(e.args.length<2)return null;let r=[];for(let i=0;i<e.args.length-1;i+=1){let a=e.args[i];if(a.kind!=="arrayLiteral"||a.elements.length!==3)return null;r.push(m(a.elements[0],t,n))}let o=w(r,e.location);return o?Mr(e,t,n)?o:w([o,P("null",e.location)],e.location):null}var Pr=Symbol("arg-selection:other-string"),Ir=Symbol("arg-selection:other-number");function Mr(e,t,n){let r=[];for(let c=0;c<e.args.length-1;c+=1){let l=e.args[c];if(l.kind!=="arrayLiteral"||l.elements.length!==3)return!1;r.push(l.elements[1])}let o=new Map;for(let c of r)if(!de(c,t,n,o))return!1;let i=[...o.values()].map(c=>({key:c.key,values:Or(c,n)}));if(i.some(c=>c.values===null||c.values.length===0))return!1;let a=1;for(let c of i)if(a*=c.values.length,a>256)return!1;let s=new Map;return pn(i,0,s,()=>r.some(c=>j(c,s)===!0))}function pn(e,t,n,r){if(t>=e.length)return r();let o=e[t];for(let i of o.values)if(n.set(o.key,i),!pn(e,t+1,n,r))return n.delete(o.key),!1;return n.delete(o.key),!0}function de(e,t,n,r){switch(e.kind){case"literal":return e.literalType==="boolean";case"identifier":case"iterationVar":case"propertyAccess":case"indexAccess":return Dr(e,t,n,r);case"unary":return e.operator==="!"&&de(e.operand,t,n,r);case"binary":return e.operator==="&&"||e.operator==="||"?de(e.left,t,n,r)&&de(e.right,t,n,r):e.operator==="=="||e.operator==="!="?an(e.left,e.right,t,n,r):!1;case"functionCall":switch(e.name){case"and":case"or":return e.args.every(o=>de(o,t,n,r));case"not":return e.args.length===1&&de(e.args[0],t,n,r);case"eq":case"neq":return e.args.length===2&&an(e.args[0],e.args[1],t,n,r);case"isNull":case"isNotNull":return e.args.length===1&&ut(e.args[0],t,n,r,null);default:return!1}default:return!1}}function Dr(e,t,n,r){let o=Ae(e),i=m(e,t,n);return!o||!i||!fn(i,n)||mt(e,t,n)?!1:(r.get(o)||r.set(o,{key:o,typeExpr:i,comparedLiterals:[]}),!0)}function an(e,t,n,r,o){let i=ft(e),a=ft(t);return i!==void 0&&a!==void 0?!0:a!==void 0?ut(e,n,r,o,a):i!==void 0?ut(t,n,r,o,i):!1}function ut(e,t,n,r,o){let i=Ae(e),a=m(e,t,n);if(!i||!a||!mn(a,n)||mt(e,t,n))return!1;let s=r.get(i);return s?(s.comparedLiterals.some(c=>Object.is(c,o))||s.comparedLiterals.push(o),!0):(r.set(i,{key:i,typeExpr:a,comparedLiterals:[o]}),!0)}function Or(e,t){let n=[],r=!1,o=a=>{n.some(s=>Object.is(s,a))||n.push(a)},i=a=>{let s=k(a,t);if(!s||r){r=!0;return}switch(s.kind){case"literalType":o(s.value);return;case"simpleType":switch(s.name){case"boolean":o(!0),o(!1);return;case"string":for(let c of e.comparedLiterals)typeof c=="string"&&o(c);o(Pr);return;case"number":for(let c of e.comparedLiterals)typeof c=="number"&&o(c);o(Ir);return;case"null":o(null);return;default:r=!0;return}case"unionType":for(let c of s.types)i(c);return;default:r=!0}};return i(e.typeExpr),r||n.length===0?null:n}function j(e,t){switch(e.kind){case"literal":return e.literalType==="null"?null:typeof e.value=="string"||typeof e.value=="number"||typeof e.value=="boolean"?e.value:void 0;case"identifier":case"iterationVar":case"propertyAccess":case"indexAccess":{let n=Ae(e);return n?t.get(n):void 0}case"unary":{let n=j(e.operand,t);return e.operator==="!"&&typeof n=="boolean"?!n:void 0}case"binary":{let n=j(e.left,t),r=j(e.right,t);switch(e.operator){case"&&":return typeof n=="boolean"&&typeof r=="boolean"?n&&r:void 0;case"||":return typeof n=="boolean"&&typeof r=="boolean"?n||r:void 0;case"==":return n!==void 0&&r!==void 0?Object.is(n,r):void 0;case"!=":return n!==void 0&&r!==void 0?!Object.is(n,r):void 0;default:return}}case"functionCall":switch(e.name){case"and":{let n=e.args.map(r=>j(r,t));return n.every(r=>typeof r=="boolean")?n.every(Boolean):void 0}case"or":{let n=e.args.map(r=>j(r,t));return n.every(r=>typeof r=="boolean")?n.some(Boolean):void 0}case"not":{let n=e.args.length===1?j(e.args[0],t):void 0;return typeof n=="boolean"?!n:void 0}case"eq":case"neq":{if(e.args.length!==2)return;let n=j(e.args[0],t),r=j(e.args[1],t);return n===void 0||r===void 0?void 0:e.name==="eq"?Object.is(n,r):!Object.is(n,r)}case"isNull":{if(e.args.length!==1)return;let n=j(e.args[0],t);return n===void 0?void 0:n===null}case"isNotNull":{if(e.args.length!==1)return;let n=j(e.args[0],t);return n===void 0?void 0:n!==null}case"cond":case"if":{if(e.args.length!==3)return;let n=j(e.args[0],t);return typeof n!="boolean"?void 0:j(n?e.args[1]:e.args[2],t)}default:return}default:return}}function Ae(e){switch(e.kind){case"identifier":return`id:${e.name}`;case"iterationVar":return"$item";case"propertyAccess":{let t=Ae(e.object);return t?`${t}.${e.property}`:null}case"indexAccess":{let t=Ae(e.object),n=ft(e.index);return t&&n!==void 0?`${t}[${JSON.stringify(n)}]`:null}default:return null}}function mt(e,t,n){switch(e.kind){case"propertyAccess":return ht(m(e.object,t,n),n)||Lr(e.object,e.property,t,n)||mt(e.object,t,n);case"indexAccess":return!0;default:return!1}}function Lr(e,t,n,r){return un(m(e,n,r),t,r)}function un(e,t,n){let r=k(e,n);if(!r)return!0;if(r.kind==="objectType"){let o=r.fields.find(i=>i.name===t);return!o||o.optional}if(r.kind==="unionType"){let o=r.types.filter(i=>!q(i));return o.length===0||o.some(i=>un(i,t,n))}return!0}function fn(e,t){let n=k(e,t);if(!n)return!1;switch(n.kind){case"simpleType":return n.name==="boolean";case"literalType":return typeof n.value=="boolean";case"unionType":return n.types.length>0&&n.types.every(r=>fn(r,t));default:return!1}}function mn(e,t){let n=k(e,t);if(!n)return!1;switch(n.kind){case"simpleType":return n.name==="string"||n.name==="number"||n.name==="boolean"||n.name==="null";case"literalType":return typeof n.value=="string"||typeof n.value=="number"||typeof n.value=="boolean"||n.value===null;case"unionType":return n.types.length>0&&n.types.every(r=>mn(r,t));default:return!1}}function ft(e){if(e.kind==="literal")return e.literalType==="null"?null:typeof e.value=="string"||typeof e.value=="number"||typeof e.value=="boolean"?e.value:void 0}function Rr(e,t,n){let r=e.args.map(a=>m(a,t,n));if(r.some(a=>a===null))return w(r,e.location);let o=r.map(a=>yn(a,n)).filter(a=>a!==null);if(o.length===0)return w(r,e.location);let i=[...o];return r.every(a=>a!==null&&ht(a,n))&&i.push(P("null",e.location)),w(i,e.location)}function jr(e,t,n){if(e.args.length<1)return null;let r=hn(m(e.args[0],t,n),n);return r?{kind:"arrayType",elementType:r,location:e.location}:null}function hn(e,t){let n=k(e,t);return n?n.kind==="recordType"?n.valueType:n.kind==="objectType"?w(n.fields.map(r=>r.typeExpr),n.location):n.kind==="unionType"?w(n.types.filter(r=>!q(r)).map(r=>hn(r,t)),n.location):null:null}function yn(e,t){let n=k(e,t);if(!n||q(n))return null;if(n.kind!=="unionType")return n;let r=n.types.map(o=>yn(o,t)).filter(o=>o!==null);return r.length===0?null:w(r,n.location)}function ht(e,t){let n=k(e,t);return!n||q(n)?!0:n.kind!=="unionType"?!1:n.types.some(r=>ht(r,t))}function Fr(e,t){return{kind:"literalType",value:e,location:t}}function P(e,t){return{kind:"simpleType",name:e,location:t}}function _r(e){return e.kind==="literal"&&typeof e.value=="string"?e.value:null}function $r(e,t){let n=new Map(e);return n.set("$item",t),n}var Gr=new Set(["findById","existsById"]),gt=new Set(["updateById","removeById"]),Br=new Set([...Gr,...gt]);function Y(e,t,n,r,o){let i=`${n}:${o.start.offset}:${o.end.offset}:${r}`;t.has(i)||(t.add(i),e.push(M(n,r,o)))}function gn(e){let t=[],n=new Set,r=$e(e.domain);Vr(e.domain,r,t,n);for(let o of e.domain.members)switch(o.kind){case"computed":N(o.expression,"computed",new Map,r,t,n,0);break;case"action":{let i=Ge(o.params);Ur(o,i,r,t,n);break}case"state":case"flow":break}return t}function Ur(e,t,n,r,o){e.available&&N(e.available,"available",t,n,r,o,0),e.dispatchable&&N(e.dispatchable,"dispatchable",t,n,r,o,0);for(let i of e.body)qr(i,t,n,r,o)}function qr(e,t,n,r,o){switch(e.kind){case"when":N(e.condition,"guard",t,n,r,o,0);for(let i of e.body)pe(i,t,n,r,o);break;case"once":e.condition&&N(e.condition,"guard",t,n,r,o,0);for(let i of e.body)pe(i,t,n,r,o);break;case"onceIntent":e.condition&&N(e.condition,"guard",t,n,r,o,0);for(let i of e.body)pe(i,t,n,r,o);break;case"include":break}}function pe(e,t,n,r,o){switch(e.kind){case"when":N(e.condition,"guard",t,n,r,o,0);for(let i of e.body)pe(i,t,n,r,o);break;case"once":e.condition&&N(e.condition,"guard",t,n,r,o,0);for(let i of e.body)pe(i,t,n,r,o);break;case"onceIntent":e.condition&&N(e.condition,"guard",t,n,r,o,0);for(let i of e.body)pe(i,t,n,r,o);break;case"patch":e.value&&N(e.value,"patch",t,n,r,o,0);break;case"effect":for(let i of e.args)i.isPath||N(i.value,"action",t,n,r,o,0);break;case"fail":e.message&&N(e.message,"action",t,n,r,o,0);break;case"include":case"stop":break}}function N(e,t,n,r,o,i,a){switch(e.kind){case"functionCall":{zr(e,t,n,r,o,i,a);let s=a+(gt.has(e.name)?1:0);for(let c of e.args)N(c,t,n,r,o,i,s);break}case"binary":N(e.left,t,n,r,o,i,a),N(e.right,t,n,r,o,i,a);break;case"unary":N(e.operand,t,n,r,o,i,a);break;case"ternary":N(e.condition,t,n,r,o,i,a),N(e.consequent,t,n,r,o,i,a),N(e.alternate,t,n,r,o,i,a);break;case"propertyAccess":N(e.object,t,n,r,o,i,a);break;case"indexAccess":N(e.object,t,n,r,o,i,a),N(e.index,t,n,r,o,i,a);break;case"objectLiteral":for(let s of e.properties)N(s.kind==="objectProperty"?s.value:s.expr,t,n,r,o,i,a);break;case"arrayLiteral":for(let s of e.elements)N(s,t,n,r,o,i,a);break;case"literal":case"identifier":case"systemIdent":case"iterationVar":break}}function zr(e,t,n,r,o,i,a){if(!Br.has(e.name)||e.args.length===0)return;gt.has(e.name)&&(t==="available"?Y(o,i,"E035","updateById/removeById are not allowed in available conditions.",e.location):t==="dispatchable"?Y(o,i,"E048","updateById/removeById are not allowed in dispatchable conditions.",e.location):t==="guard"?Y(o,i,"E034","updateById/removeById are not allowed in guard conditions.",e.location):t!=="patch"&&Y(o,i,"E031","updateById/removeById are only allowed in patch RHS.",e.location),a>0&&Y(o,i,"E032","Nested transform primitives are not allowed.",e.location),t==="patch"&&!yt(e.args[0],r)&&Y(o,i,"E033","Transform primitive collection argument must resolve to a state path.",e.args[0].location));let s=Kr(e.args[0],n,r);if(!s)return;let c=Tn(s,r);if(!c){Y(o,i,"E030","Collection element type must declare an 'id' field for entity primitives.",e.args[0].location);return}Be(c,r)||Y(o,i,"E030a","Entity 'id' field must be string or number.",e.args[0].location)}function Vr(e,t,n,r){for(let o of e.members)if(o.kind==="state")for(let i of o.fields)Hr(i,t,n,r)}function Hr(e,t,n,r){if(!e.initializer||e.initializer.kind!=="arrayLiteral")return;let o=U(e.typeExpr,t);if(!o)return;let i=Tn(o,t);if(!i||!Be(i,t))return;let a=new Map;for(let s of e.initializer.elements){if(s.kind!=="objectLiteral")continue;let c=En(s);if(c.kind!=="literal")continue;let l=`${typeof c.value}:${String(c.value)}`;if(a.get(l)){Y(n,r,"E030b","Duplicate '.id' values detected in state initializer.",c.location);continue}a.set(l,c.location)}}function En(e){if(e.kind!=="objectLiteral")return{kind:"unknown"};let t={kind:"absent"};for(let n of e.properties){if(n.kind==="objectProperty"){if(n.key!=="id")continue;if(n.value.kind==="literal"&&(typeof n.value.value=="string"||typeof n.value.value=="number")){t={kind:"literal",value:n.value.value,location:n.value.location};continue}t={kind:"unknown"};continue}let r=En(n.expr);r.kind!=="absent"&&(t=r)}return t}function Kr(e,t,n){return U(m(e,t,n),n)}function Tn(e,t){return te(e,"id",t)}function yt(e,t){switch(e.kind){case"identifier":return t.stateTypes.has(e.name);case"propertyAccess":return yt(e.object,t);case"indexAccess":return yt(e.object,t);default:return!1}}function kn(){return{inAction:!1,inGuard:!1,guardDepth:0,hasMarkerPatch:!1,currentActionParamTypes:new Map,diagnostics:[]}}var Wr=/\b(await(?:ing)?|wait(?:ing)?|pending)\b/i;function T(e,t){return{kind:"simpleType",name:e,location:t}}function z(e,t,n){let r=k(e,n),o=k(t,n);if(!r||!o)return null;if(o.kind==="unionType"){let i=r.kind==="unionType"?r.types:[r],a=!1;for(let s of i){let c=o.types.map(l=>z(s,l,n));if(!c.includes(!0)){if(c.every(l=>l===!1))return!1;a=!0}}return a?null:!0}if(r.kind==="unionType"){let i=!1;for(let a of r.types){let s=z(a,o,n);if(s===!1)return!1;s===null&&(i=!0)}return i?null:!0}if(o.kind==="simpleType"){if(r.kind==="simpleType")return r.name===o.name;if(r.kind==="literalType")return o.name==="null"?r.value===null:typeof r.value===o.name}if(o.kind==="literalType")return r.kind!=="literalType"?!1:r.value===o.value;if(o.kind==="arrayType")return r.kind!=="arrayType"?!1:z(r.elementType,o.elementType,n);if(o.kind==="objectType"){if(r.kind!=="objectType")return!1;for(let i of o.fields){let a=r.fields.find(c=>c.name===i.name);if(!a){if(i.optional)continue;return!1}if(a.optional&&!i.optional)return!1;let s=z(a.typeExpr,i.typeExpr,n);if(s!==!0)return s}return!0}return o.kind==="recordType"?r.kind!=="recordType"?null:z(r.valueType,o.valueType,n):null}function v(e,t){let n=k(e,t);if(!n)return"unknown";switch(n.kind){case"simpleType":return n.name;case"literalType":return JSON.stringify(n.value);case"arrayType":return`Array<${v(n.elementType,t)}>`;case"recordType":return`Record<${v(n.keyType,t)}, ${v(n.valueType,t)}>`;case"objectType":return`{ ${n.fields.map(r=>`${r.name}${r.optional?"?":""}: ${v(r.typeExpr,t)}`).join("; ")} }`;case"unionType":return n.types.map(r=>v(r,t)).join(" | ")}}function qe(e,t){let n=k(e,t);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 r=new Set;for(let o of n.types){let i=qe(o,t);if(i===null)return null;if(i==="nonprimitive")return"nonprimitive";for(let a of i)r.add(a)}return r}}}function Et(e,t){let n=qe(e,t);if(n===null)return null;if(n==="nonprimitive")return"invalid";let r=[...n].filter(o=>o!=="null");return r.length!==1||n.has("null")?"invalid":r[0]}function Nn(e,t,n){let r=qe(e,n),o=qe(t,n);if(r===null||o===null)return null;if(r==="nonprimitive"||o==="nonprimitive")return!1;if(!(r instanceof Set)||!(o instanceof Set))return null;let i=[...r].filter(s=>s!=="null"),a=[...o].filter(s=>s!=="null");return i.length===0||a.length===0?!0:i.some(s=>a.includes(s))}function Sn(e,t){let n=k(e,t);if(!n||q(n))return null;if(n.kind!=="unionType")return n;let r=n.types.map(a=>Sn(a,t)).filter(a=>a!==null);if(r.length===0)return null;let o=[],i=new Set;for(let a of r){let s=JSON.stringify(a);i.has(s)||(i.add(s),o.push(a))}return o.length===1?o[0]:{kind:"unionType",types:o,location:n.location}}function Tt(e,t,n){if(!e||!t)return null;let r=z(e,t,n);if(r===!0)return!0;let o=z(t,e,n);if(o===!0)return!0;let i=Nn(e,t,n);return i!==null?i:r===!1&&o===!1?!1:null}function kt(e,t,n){let r=k(e,n),o=k(t,n);if(!r||!o)return null;if(o.kind==="unionType"){let i=!1;for(let a of o.types){if(q(a))continue;let s=kt(r,a,n);if(s===!0)return!0;s===null&&(i=!0)}return i?null:!1}if(r.kind==="unionType"){let i=!1;for(let a of r.types){let s=kt(a,o,n);if(s===!1)return!1;s===null&&(i=!0)}return i?null:!0}if(o.kind!=="objectType"||r.kind!=="objectType")return!1;for(let i of r.fields){let a=o.fields.find(c=>c.name===i.name);if(!a)return!1;let s=z(i.typeExpr,a.typeExpr,n);if(s!==!0)return s}return!0}function vn(e,t){let n=k(e,t);if(!n)return null;if(n.kind==="unionType"){let r=n.types.map(o=>vn(o,t));return r.every(o=>o===!0)?!0:r.some(o=>o===!1)?!1:null}return n.kind==="arrayType"}function xn(e,t){let n=k(e,t);if(!n)return null;if(n.kind==="unionType"){let r=n.types.map(o=>xn(o,t));return r.every(o=>o===!0)?!0:r.some(o=>o===!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 Yr(e,t){let n=new Map(e);return n.set("$item",t),n}function bn(e){let t=ze(e);if(typeof t=="number")return t;if(e.kind==="literal")return e.literalType==="null"?null:typeof e.value=="string"||typeof e.value=="number"||typeof e.value=="boolean"?e.value:void 0}function ze(e){if(e.kind==="literal"&&e.literalType==="number"&&typeof e.value=="number")return e.value;if(e.kind==="unary"&&e.operator==="-"){let t=ze(e.operand);return typeof t=="number"?-t:void 0}}function Qr(e,t){let[n,...r]=e.segments;if(!n||n.kind!=="propertySegment")return null;let o=t.stateTypes.get(n.name)??null;for(let i of r){if(!o)return null;o=i.kind==="propertySegment"?te(o,i.name,t):we(o,t)}return o}function Jr(e){let t="";for(let[n,r]of e.segments.entries()){if(r.kind==="propertySegment"){t+=n===0?r.name:`.${r.name}`;continue}r.index.kind==="literal"?t+=`[${JSON.stringify(r.index.value)}]`:t+="[*]"}return t}var bt=class{ctx=kn();symbols=null;validate(t){return this.ctx=kn(),this.symbols=$e(t.domain),this.validateDomain(t.domain),this.symbols=null,{valid:!this.ctx.diagnostics.some(n=>n.severity==="error"),diagnostics:this.ctx.diagnostics}}validateDomain(t){t.name.startsWith("__")&&this.error("Domain name cannot start with '__' (reserved prefix)",t.location,"E_RESERVED_NAME");for(let n of t.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(t){let n=new Map;for(let r of t.fields){let o=n.get(r.name);o?this.error(`Duplicate state field '${r.name}'. First declared at line ${o.start.line}`,r.location,"E_DUPLICATE_FIELD"):n.set(r.name,r.location),this.validateStateField(r)}}validateStateField(t){this.checkAnonymousObjectType(t.typeExpr,t.location),t.initializer&&this.validateStateInitializer(t.initializer)}validateStateInitializer(t){switch(t.kind){case"literal":return;case"identifier":case"iterationVar":this.error("State initializers must be compile-time constants",t.location,"E042");return;case"systemIdent":t.path[0]==="system"?this.error("$system.* cannot be used in state initializers",t.location,"E002"):this.error("State initializers must be compile-time constants",t.location,"E042");return;case"objectLiteral":for(let n of t.properties){if(n.kind==="objectProperty"){this.validateStateInitializer(n.value);continue}let r=this.ctx.diagnostics.length;this.validateStateInitializer(n.expr),r===this.ctx.diagnostics.length&&this.requireSpreadOperand(this.inferType(n.expr,new Map),n.location,n.expr,new Map)}return;case"arrayLiteral":for(let n of t.elements)this.validateStateInitializer(n);return;case"functionCall":{let n=this.ctx.diagnostics.length;for(let r of t.args)this.validateStateInitializer(r);this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",t.location,"E042");return}case"binary":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(t.left),this.validateStateInitializer(t.right),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",t.location,"E042");return}case"unary":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(t.operand),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",t.location,"E042");return}case"ternary":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(t.condition),this.validateStateInitializer(t.consequent),this.validateStateInitializer(t.alternate),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",t.location,"E042");return}case"propertyAccess":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(t.object),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",t.location,"E042");return}case"indexAccess":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(t.object),this.validateStateInitializer(t.index),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",t.location,"E042");return}}}checkAnonymousObjectType(t,n){switch(t.kind){case"objectType":this.ctx.diagnostics.push(Zt("W012","Anonymous object type in state field. Use a named type declaration instead: type MyType = { ... }",t.location,{suggestion:"Define this type using 'type TypeName = { ... }' and reference it by name"}));for(let r of t.fields)this.checkAnonymousObjectType(r.typeExpr,n);break;case"arrayType":this.checkAnonymousObjectType(t.elementType,n);break;case"recordType":this.checkAnonymousObjectType(t.keyType,n),this.checkAnonymousObjectType(t.valueType,n);break;case"unionType":for(let r of t.types)this.checkAnonymousObjectType(r,n);break}}validateAction(t){this.ctx.inAction=!0,this.ctx.currentActionParamTypes=Ge(t.params),t.available&&this.validateAvailableExpr(t.available),t.dispatchable&&this.validateDispatchableExpr(t.dispatchable);for(let n of t.body)this.validateGuardedStmt(n);this.ctx.inAction=!1,this.ctx.currentActionParamTypes=new Map}validateAvailableExpr(t){switch(t.kind){case"identifier":this.ctx.currentActionParamTypes.has(t.name)&&this.error("Action parameters cannot be used in available condition",t.location,"E005");break;case"systemIdent":t.path[0]==="system"&&this.error("$system.* cannot be used in available condition (must be pure expression)",t.location,"E005"),t.path[0]==="input"&&this.error("$input.* cannot be used in available condition (parameters not available at availability check)",t.location,"E005"),t.path[0]==="meta"&&this.error("$meta.* cannot be used in available condition (availability is schema-context only)",t.location,"E005");break;case"functionCall":for(let n of t.args)this.validateAvailableExpr(n);break;case"binary":this.validateAvailableExpr(t.left),this.validateAvailableExpr(t.right);break;case"unary":this.validateAvailableExpr(t.operand);break;case"ternary":this.validateAvailableExpr(t.condition),this.validateAvailableExpr(t.consequent),this.validateAvailableExpr(t.alternate);break;case"propertyAccess":this.validateAvailableExpr(t.object);break;case"indexAccess":this.validateAvailableExpr(t.object),this.validateAvailableExpr(t.index);break;case"objectLiteral":for(let n of t.properties)this.validateAvailableExpr(n.kind==="objectProperty"?n.value:n.expr);break;case"arrayLiteral":for(let n of t.elements)this.validateAvailableExpr(n);break}}validateDispatchableExpr(t){switch(t.kind){case"systemIdent":t.path[0]==="system"&&this.error("$system.* cannot be used in dispatchable condition (must be pure expression)",t.location,"E047"),t.path[0]==="input"&&this.error("$input.* cannot be used in dispatchable condition (use bare action parameter names)",t.location,"E047"),t.path[0]==="meta"&&this.error("$meta.* cannot be used in dispatchable condition (dispatchability is snapshot + bound-input only)",t.location,"E047");break;case"functionCall":for(let n of t.args)this.validateDispatchableExpr(n);break;case"binary":this.validateDispatchableExpr(t.left),this.validateDispatchableExpr(t.right);break;case"unary":this.validateDispatchableExpr(t.operand);break;case"ternary":this.validateDispatchableExpr(t.condition),this.validateDispatchableExpr(t.consequent),this.validateDispatchableExpr(t.alternate);break;case"propertyAccess":this.validateDispatchableExpr(t.object);break;case"indexAccess":this.validateDispatchableExpr(t.object),this.validateDispatchableExpr(t.index);break;case"objectLiteral":for(let n of t.properties)this.validateDispatchableExpr(n.kind==="objectProperty"?n.value:n.expr);break;case"arrayLiteral":for(let n of t.elements)this.validateDispatchableExpr(n);break}}validateGuardedStmt(t){switch(t.kind){case"when":this.validateWhen(t);break;case"once":this.validateOnce(t);break;case"onceIntent":this.validateOnceIntent(t);break;case"patch":this.validatePatch(t);break;case"effect":this.validateEffect(t);break;case"include":break;case"fail":this.validateFail(t);break;case"stop":this.validateStop(t);break}}validateWhen(t){this.ctx.inGuard=!0,this.ctx.guardDepth++,this.validateCondition(t.condition,"when");for(let n of t.body)this.validateGuardedStmt(n);this.ctx.guardDepth--,this.ctx.guardDepth===0&&(this.ctx.inGuard=!1)}validateOnce(t){this.ctx.inGuard=!0,this.ctx.guardDepth++,this.ctx.hasMarkerPatch=!1,t.condition&&this.validateCondition(t.condition,"once");for(let n of t.body)this.validateGuardedStmt(n);this.ctx.guardDepth--,this.ctx.guardDepth===0&&(this.ctx.inGuard=!1)}validateOnceIntent(t){this.ctx.inGuard=!0,this.ctx.guardDepth++,t.condition&&this.validateCondition(t.condition,"onceIntent");for(let n of t.body)this.validateGuardedStmt(n);this.ctx.guardDepth--,this.ctx.guardDepth===0&&(this.ctx.inGuard=!1)}validatePatch(t){if(this.ctx.inGuard||this.error("Patch must be inside a guard (when, once, or onceIntent)",t.location,"E_UNGUARDED_PATCH"),t.value){let n=this.ctx.diagnostics.length,r=this.validateExpr(t.value,"action");if(!this.symbols||n!==this.ctx.diagnostics.length)return;let o=Qr(t.path,this.symbols);if(!o||!r)return;(t.op==="merge"?kt(r,o,this.symbols):z(r,o,this.symbols))===!1&&this.error(`Patch value for '${Jr(t.path)}' must be assignable to ${v(o,this.symbols)}, got ${v(r,this.symbols)}`,t.value.location,"E_TYPE_MISMATCH")}}validateEffect(t){this.ctx.inGuard||this.error("Effect must be inside a guard (when, once, or onceIntent)",t.location,"E_UNGUARDED_EFFECT");for(let n of t.args)n.isPath||this.validateExpr(n.value,"action")}validateFail(t){this.ctx.inGuard||this.error("fail must be inside a guard (when, once, or onceIntent)",t.location,"E006"),t.message&&this.validateExpr(t.message,"action")}validateStop(t){this.ctx.inGuard||this.error("stop must be inside a guard (when, once, or onceIntent)",t.location,"E007"),Wr.test(t.reason)&&this.error("stop message suggests waiting/pending - use 'Already processed' style instead",t.location,"E008")}validateCondition(t,n){let r=this.ctx.diagnostics.length,o=this.validateExpr(t,"action");r===this.ctx.diagnostics.length&&this.requireAssignable(o,T("boolean",t.location),t.location,`Condition in ${n} must evaluate to boolean`)}validateExpr(t,n,r=this.ctx.currentActionParamTypes){switch(t.kind){case"functionCall":return this.validateFunctionCall(t,n,r),this.inferType(t,r);case"binary":{let o=this.ctx.diagnostics.length,i=this.validateExpr(t.left,n,r),a=this.validateExpr(t.right,n,r);if(!(o!==this.ctx.diagnostics.length))switch(t.operator){case"==":case"!=":this.validatePrimitiveEquality(t.left,t.right,i,a,t.location);break;case"<":case"<=":case">":case">=":this.requireAssignable(i,T("number",t.left.location),t.left.location,`Operator '${t.operator}' requires a numeric left operand`),this.requireAssignable(a,T("number",t.right.location),t.right.location,`Operator '${t.operator}' requires a numeric right operand`);break;case"&&":case"||":this.requireAssignable(i,T("boolean",t.left.location),t.left.location,`Operator '${t.operator}' requires a boolean left operand`),this.requireAssignable(a,T("boolean",t.right.location),t.right.location,`Operator '${t.operator}' requires a boolean right operand`);break;case"+":case"-":case"*":case"/":case"%":this.requireAssignable(i,T("number",t.left.location),t.left.location,`Operator '${t.operator}' requires a numeric left operand`),this.requireAssignable(a,T("number",t.right.location),t.right.location,`Operator '${t.operator}' requires a numeric right operand`);break;case"??":this.validateCoalesceTypes([i,a],t.location);break}return this.inferType(t,r)}case"unary":{let o=this.ctx.diagnostics.length,i=this.validateExpr(t.operand,n,r);return o===this.ctx.diagnostics.length&&this.requireAssignable(i,T(t.operator==="!"?"boolean":"number",t.operand.location),t.operand.location,t.operator==="!"?"Unary '!' requires a boolean operand":"Unary '-' requires a numeric operand"),this.inferType(t,r)}case"ternary":{let o=this.ctx.diagnostics.length,i=this.validateExpr(t.condition,n,r);return this.validateExpr(t.consequent,n,r),this.validateExpr(t.alternate,n,r),o===this.ctx.diagnostics.length&&this.requireAssignable(i,T("boolean",t.condition.location),t.condition.location,"Ternary condition must evaluate to boolean"),this.inferType(t,r)}case"propertyAccess":return this.validateExpr(t.object,n,r),this.inferType(t,r);case"indexAccess":return this.validateExpr(t.object,n,r),this.validateExpr(t.index,n,r),this.inferType(t,r);case"objectLiteral":for(let o of t.properties){if(o.kind==="objectProperty"){this.validateExpr(o.value,n,r);continue}let i=this.validateExpr(o.expr,n,r);this.symbols&&this.requireSpreadOperand(i,o.location,o.expr,r)}return this.inferType(t,r);case"arrayLiteral":for(let o of t.elements)this.validateExpr(o,n,r);return this.inferType(t,r);case"systemIdent":return this.inferType(t,r);case"literal":case"identifier":case"iterationVar":return this.inferType(t,r)}}validateFunctionCall(t,n,r){let{name:o,args:i,location:a}=t;if(["reduce","fold","foldl","foldr","scan"].includes(o)&&this.error(`Function '${o}' is forbidden. Use sum(), min(), max() for aggregation instead`,a,"E011"),["sum","min","max"].includes(o)&&i.length===1){n==="action"&&this.error(`Primitive aggregation '${o}()' can only be used in computed expressions, not in actions`,a,"E009");let c=i[0];c.kind==="functionCall"&&this.error(`Primitive aggregation '${o}()' does not allow composition. Use a direct reference, not '${c.name}()'`,a,"E010")}switch(o){case"eq":case"neq":break;case"len":case"sum":i.length!==1&&this.error(`Function '${o}' expects 1 argument, got ${i.length}`,a,"E_ARG_COUNT");break;case"add":case"sub":case"mul":case"div":case"mod":case"absDiff":case"idiv":case"gt":case"gte":case"lt":case"lte":i.length!==2&&this.error(`Function '${o}' expects 2 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"not":case"neg":case"abs":case"floor":case"ceil":case"round":case"sqrt":case"isNull":case"isNotNull":case"trim":case"lower":case"upper":case"strlen":case"keys":case"values":case"entries":case"first":case"last":case"typeof":case"toString":case"toNumber":case"toBoolean":case"reverse":case"unique":case"flat":case"fromEntries":i.length!==1&&this.error(`Function '${o}' expects 1 argument, got ${i.length}`,a,"E_ARG_COUNT");break;case"pow":case"findById":case"existsById":case"filter":case"map":case"find":case"every":case"some":case"at":case"includes":case"field":case"hasKey":case"pick":case"omit":case"startsWith":case"endsWith":case"strIncludes":case"indexOf":i.length!==2&&this.error(`Function '${o}' expects 2 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"updateById":case"clamp":i.length!==3&&this.error(`Function '${o}' expects 3 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"removeById":case"streak":i.length!==2&&this.error(`Function '${o}' expects 2 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"slice":case"substring":case"substr":case"replace":(i.length<2||i.length>3)&&this.error(`Function '${o}' expects 2-3 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"split":i.length!==2&&this.error(`Function '${o}' expects 2 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"and":case"or":case"concat":case"min":case"max":case"merge":case"coalesce":case"append":i.length<1&&this.error(`Function '${o}' expects at least 1 argument`,a,"E_ARG_COUNT");break;case"match":i.length<3&&this.error("Function 'match' expects a selector, at least one [key, value] arm, and a default value",a,"E050");break;case"argmax":case"argmin":i.length<2&&this.error(`Function '${o}' expects at least one [label, eligible, score] candidate and a tie-break literal`,a,"E052");break;case"if":case"cond":i.length!==3&&this.error(`Function '${o}' expects 3 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;default:this.error(`Unknown function '${o}'. Check spelling or see MEL builtin function reference`,a,"E_UNKNOWN_FN");break}let s=[];if(["filter","map","find","every","some"].includes(o)&&i.length>0){let c=this.validateExpr(i[0],n,r);s.push(c);let l=r;if(this.symbols){let d=U(c,this.symbols);d&&(l=Yr(r,d))}for(let d=1;d<i.length;d+=1)s.push(this.validateExpr(i[d],n,d===1?l:r))}else for(let c of i)s.push(this.validateExpr(c,n,r));if(this.symbols)switch(o){case"eq":case"neq":i.length===2&&this.validatePrimitiveEquality(i[0],i[1],s[0],s[1],a);break;case"add":case"sub":case"mul":case"div":case"mod":case"absDiff":case"idiv":case"pow":i.length===2&&(this.requireAssignable(s[0],T("number",i[0].location),i[0].location,`Function '${o}' expects a numeric first argument`),this.requireAssignable(s[1],T("number",i[1].location),i[1].location,`Function '${o}' expects a numeric second argument`));break;case"gt":case"gte":case"lt":case"lte":i.length===2&&(this.requireAssignable(s[0],T("number",i[0].location),i[0].location,`Function '${o}' expects a numeric first argument`),this.requireAssignable(s[1],T("number",i[1].location),i[1].location,`Function '${o}' expects a numeric second argument`));break;case"and":case"or":for(let[c,l]of i.entries())this.requireAssignable(s[c],T("boolean",l.location),l.location,`Function '${o}' expects boolean arguments`);break;case"not":i.length===1&&this.requireAssignable(s[0],T("boolean",i[0].location),i[0].location,"Function 'not' expects a boolean argument");break;case"neg":case"abs":case"floor":case"ceil":case"round":case"sqrt":i.length===1&&this.requireAssignable(s[0],T("number",i[0].location),i[0].location,`Function '${o}' expects a numeric argument`);break;case"clamp":if(i.length===3){this.requireAssignable(s[0],T("number",i[0].location),i[0].location,"Function 'clamp' expects a numeric first argument"),this.requireAssignable(s[1],T("number",i[1].location),i[1].location,"Function 'clamp' expects a numeric second argument"),this.requireAssignable(s[2],T("number",i[2].location),i[2].location,"Function 'clamp' expects a numeric third argument");let c=ze(i[1]),l=ze(i[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":i.length===2&&(this.requireAssignable(s[0],T("number",i[0].location),i[0].location,"Function 'streak' expects a numeric first argument"),this.requireAssignable(s[1],T("boolean",i[1].location),i[1].location,"Function 'streak' expects a boolean second argument"));break;case"trim":case"lower":case"upper":case"strlen":i.length===1&&this.requireAssignable(s[0],T("string",i[0].location),i[0].location,`Function '${o}' expects a string argument`);break;case"startsWith":case"endsWith":case"strIncludes":case"indexOf":case"split":i.length===2&&(this.requireAssignable(s[0],T("string",i[0].location),i[0].location,`Function '${o}' expects a string first argument`),this.requireAssignable(s[1],T("string",i[1].location),i[1].location,`Function '${o}' expects a string second argument`));break;case"replace":i.length>=2&&(this.requireAssignable(s[0],T("string",i[0].location),i[0].location,"Function 'replace' expects a string first argument"),this.requireAssignable(s[1],T("string",i[1].location),i[1].location,"Function 'replace' expects a string second argument")),i.length===3&&this.requireAssignable(s[2],T("string",i[2].location),i[2].location,"Function 'replace' expects a string replacement argument");break;case"substring":case"substr":i.length>=2&&(this.requireAssignable(s[0],T("string",i[0].location),i[0].location,`Function '${o}' expects a string first argument`),this.requireAssignable(s[1],T("number",i[1].location),i[1].location,`Function '${o}' expects a numeric second argument`)),i.length===3&&this.requireAssignable(s[2],T("number",i[2].location),i[2].location,`Function '${o}' expects a numeric third argument`);break;case"len":i.length===1&&this.requireLenCompatible(s[0],i[0].location);break;case"filter":case"find":case"every":case"some":i.length===2&&(this.requireArrayCompatible(s[0],i[0].location,o),this.requireAssignable(s[1],T("boolean",i[1].location),i[1].location,`Function '${o}' requires a boolean-valued callback`));break;case"map":i.length===2&&this.requireArrayCompatible(s[0],i[0].location,o);break;case"merge":for(let[c,l]of i.entries())this.requireSpreadOperand(s[c],l.location,l,r);break;case"coalesce":this.validateCoalesceTypes(s,a);break;case"match":this.validateMatchCall(i,s,a,r);break;case"argmax":case"argmin":this.validateArgSelectionCall(o,i,a,r);break;case"if":case"cond":i.length===3&&this.requireAssignable(s[0],T("boolean",i[0].location),i[0].location,`Function '${o}' expects a boolean condition`);break}}validatePrimitiveEquality(t,n,r,o,i){if(!this.symbols)return;if(t.kind==="objectLiteral"||t.kind==="arrayLiteral"||n.kind==="objectLiteral"||n.kind==="arrayLiteral"){this.error("eq/neq operands must be compatible primitive types, not object or array literals",i,"E_TYPE_MISMATCH");return}Nn(r,o,this.symbols)===!1&&this.error(`eq/neq operands must be compatible primitive types, got ${v(r,this.symbols)} and ${v(o,this.symbols)}`,i,"E_TYPE_MISMATCH")}inferType(t,n){return this.symbols?m(t,n,this.symbols):null}requireAssignable(t,n,r,o){if(!this.symbols||!t)return;z(t,n,this.symbols)===!1&&this.error(`${o}, got ${v(t,this.symbols)}`,r,"E_TYPE_MISMATCH")}requireArrayCompatible(t,n,r){if(!this.symbols||!t)return;vn(t,this.symbols)===!1&&this.error(`Function '${r}' expects an array first argument, got ${v(t,this.symbols)}`,n,"E_TYPE_MISMATCH")}requireLenCompatible(t,n){if(!this.symbols||!t)return;xn(t,this.symbols)===!1&&this.error(`Function 'len' expects a string, array, object, or record argument, got ${v(t,this.symbols)}`,n,"E_TYPE_MISMATCH")}requireSpreadOperand(t,n,r,o=new Map){if(!this.symbols)return;let i=t===null?"unknown":Ue(t,this.symbols);(G(r,{env:o,symbols:this.symbols,inferExprType:m,resolveType:k})?"invalid":i)==="invalid"&&this.error(`Object spread operands must be object-shaped or T | null where T is object-shaped, got ${v(t,this.symbols)}`,n,"E_TYPE_MISMATCH")}validateCoalesceTypes(t,n){if(!this.symbols)return;let r=t.map(o=>Sn(o,this.symbols)).filter(o=>o!==null);for(let o=0;o<r.length;o+=1)for(let i=o+1;i<r.length;i+=1)if(Tt(r[o],r[i],this.symbols)===!1){this.error(`coalesce arguments must have compatible non-null types, got ${v(r[o],this.symbols)} and ${v(r[i],this.symbols)}`,n,"E_TYPE_MISMATCH");return}}validateMatchCall(t,n,r,o){if(!this.symbols||t.length<3)return;let i=n[0],a=Et(i,this.symbols);a==="invalid"&&this.error(`Function 'match' requires a selector of type string, number, or boolean, got ${v(i,this.symbols)}`,t[0].location,"E_TYPE_MISMATCH");let s=new Set,c=[];for(let l=1;l<t.length-1;l+=1){let d=t[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[p,f]=d.elements,h=bn(p);if(h==null)this.error("Function 'match' requires literal string, number, or boolean arm keys",p.location,"E050");else{let $=`${typeof h}:${String(h)}`;s.has($)?this.error(`Function 'match' has duplicate arm key ${JSON.stringify(h)}`,p.location,"E051"):s.add($)}let A=this.inferType(p,o),S=Et(A,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 ${v(i,this.symbols)} and ${v(A,this.symbols)}`,p.location,"E_TYPE_MISMATCH"),c.push(this.inferType(f,o))}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(Tt(c[l],c[d],this.symbols)===!1){this.error(`Function 'match' arm values and default must have compatible types, got ${v(c[l],this.symbols)} and ${v(c[d],this.symbols)}`,r,"E_TYPE_MISMATCH");return}}validateArgSelectionCall(t,n,r,o){if(!this.symbols||n.length<2)return;let i=n[n.length-1],a=bn(i);a!=="first"&&a!=="last"&&this.error(`Function '${t}' requires a final tie-break literal of "first" or "last"`,i.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 '${t}' requires inline [label, eligible, score] array literal candidates`,d.location,"E052");continue}let[p,f,h]=d.elements,A=this.inferType(p,o),S=Et(A,this.symbols);S==="invalid"?this.error(`Function '${t}' requires labels with exactly one primitive scalar type, got ${v(A,this.symbols)}`,p.location,"E_TYPE_MISMATCH"):c===null?c=S:S!==null&&S!==c&&this.error(`Function '${t}' candidate labels must share one primitive scalar type, got ${c} and ${S}`,p.location,"E_TYPE_MISMATCH"),this.requireAssignable(this.inferType(f,o),T("boolean",f.location),f.location,`Function '${t}' expects a boolean eligible value`),this.requireAssignable(this.inferType(h,o),T("number",h.location),h.location,`Function '${t}' expects a numeric score value`),s.push(A)}for(let l=0;l<s.length;l+=1)for(let d=l+1;d<s.length;d+=1)if(Tt(s[l],s[d],this.symbols)===!1){this.error(`Function '${t}' candidate labels must have compatible scalar types, got ${v(s[l],this.symbols)} and ${v(s[d],this.symbols)}`,r,"E_TYPE_MISMATCH");return}}error(t,n,r){this.ctx.diagnostics.push({severity:"error",code:r,message:t,location:n})}warn(t,n,r){this.ctx.diagnostics.push({severity:"warning",code:r,message:t,location:n})}};function An(e){let n=new bt().validate(e),r=gn(e),o=[...n.diagnostics,...r];return{valid:!o.some(i=>i.severity==="error"),diagnostics:o}}var Nt={mode:"schema",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!1},St={mode:"action",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!1},vt={mode:"action",allowSysPaths:{prefixes:["input"]},fnTableVersion:"1.0",allowItem:!1},xt={mode:"action",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!0},Xr={allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0"};var _=class extends Error{code;path;details;constructor(t,n,r){super(n),this.name="LoweringError",this.code=t,this.path=r?.path,this.details=r?.details}};function Ve(e,t,n){return new _("INVALID_KIND_FOR_CONTEXT",`Node kind '${e}' is not allowed in ${t} context`,{path:n,details:{kind:e,context:t}})}function g(e,t){return new _("UNKNOWN_CALL_FN",`Unknown function '${e}' in call expression`,{path:t,details:{fn:e}})}function He(e,t){return new _("INVALID_SYS_PATH",`System path '${e.join(".")}' is not allowed in Translator path`,{path:t,details:{sysPath:e}})}function At(e,t){return new _("UNSUPPORTED_BASE",`Unsupported base expression kind '${e}'. Only var(item) is supported.`,{path:t,details:{baseKind:e}})}function Zr(e,t){return new _("INVALID_SHAPE",`Invalid node shape: ${e}`,{path:t,details:{description:e}})}function wt(e,t){return new _("UNKNOWN_NODE_KIND",`Unknown expression node kind '${e}'`,{path:t,details:{kind:e}})}function eo(e,t){let n=Array.from(e),r=Array.from(t),o=Math.min(n.length,r.length);for(let i=0;i<o;i+=1){let a=n[i].codePointAt(0)??0,s=r[i].codePointAt(0)??0;if(a!==s)return a-s}return n.length-r.length}function wn(e){return e.map((t,n)=>({item:t,index:n})).sort((t,n)=>{let r=eo(t.item.key,n.item.key);return r!==0?r:t.index-n.index}).map(({item:t})=>t)}function u(e,t){switch(e.kind){case"lit":return to(e);case"var":return no(e,t);case"sys":return ro(e,t);case"get":return oo(e,t);case"field":return Cn(e,t);case"call":return io(e,t);case"obj":return ao(e,t);case"arr":return so(e,t);default:throw wt(e.kind)}}function to(e){return{kind:"lit",value:e.value}}function no(e,t){if(!t.allowItem)throw Ve("var",t.mode);return{kind:"get",path:"$item"}}function ro(e,t){if(e.path.length===0)throw He(e.path);let n=e.path[0];if(!(t.allowSysPaths?.prefixes??["meta","input"]).includes(n))throw He(e.path);return{kind:"get",path:e.path.join(".")}}function oo(e,t){let n=e.path.map(r=>r.name).join(".");if(e.base===void 0)return{kind:"get",path:n};if(e.base.kind==="var"&&e.base.name==="item"){if(!t.allowItem)throw Ve("var",t.mode);return{kind:"get",path:`$item.${n}`}}throw At(e.base.kind)}function Cn(e,t){if(e.object.kind==="get"&&e.object.base===void 0){let n=e.object.path.map(r=>r.name).join(".");return{kind:"get",path:n?`${n}.${e.property}`:e.property}}return{kind:"field",object:u(e.object,t),property:e.property}}function io(e,t){let{fn:n,args:r}=e;if(n==="absDiff"){if(r.length!==2)throw g(n);return{kind:"abs",arg:{kind:"sub",left:u(r[0],t),right:u(r[1],t)}}}if(n==="clamp"){if(r.length!==3)throw g(n);return{kind:"min",args:[{kind:"max",args:[u(r[0],t),u(r[1],t)]},u(r[2],t)]}}if(n==="idiv"){if(r.length!==2)throw g(n);return{kind:"floor",arg:{kind:"div",left:u(r[0],t),right:u(r[1],t)}}}if(n==="streak"){if(r.length!==2)throw g(n);return{kind:"if",cond:u(r[1],t),then:{kind:"add",left:u(r[0],t),right:{kind:"lit",value:1}},else:{kind:"lit",value:0}}}if(n==="match")return co(r,t);if(n==="argmax"||n==="argmin")return lo(n,r,t);if(ho(n)){if(r.length!==2)throw g(n);let[o,i]=r;return{kind:n,left:u(o,t),right:u(i,t)}}if(n==="isNotNull"){if(r.length!==1)throw g(n);return{kind:"not",arg:{kind:"isNull",arg:u(r[0],t)}}}if(Pn(n)){if(r.length!==1)throw g(n);return{kind:yo(n),arg:u(r[0],t)}}if(n==="trim"){if(r.length!==1)throw g(n);return{kind:"trim",str:u(r[0],t)}}if(n==="lower"||n==="toLowerCase"){if(r.length!==1)throw g(n);return{kind:"toLowerCase",str:u(r[0],t)}}if(n==="upper"||n==="toUpperCase"){if(r.length!==1)throw g(n);return{kind:"toUpperCase",str:u(r[0],t)}}if(n==="strlen"||n==="strLen"){if(r.length!==1)throw g(n);return{kind:"strLen",str:u(r[0],t)}}if(go(n))return r.length===1?{kind:n==="min"?"minArray":"maxArray",array:u(r[0],t)}:{kind:n,args:r.map(o=>u(o,t))};if(n==="sum"){if(r.length!==1)throw g(n);return{kind:"sumArray",array:u(r[0],t)}}if(n==="pow"){if(r.length!==2)throw g(n);return{kind:"pow",base:u(r[0],t),exponent:u(r[1],t)}}if(Eo(n))return{kind:n,args:r.map(o=>u(o,t))};if(n==="if"||n==="cond"){if(r.length!==3)throw g(n);return{kind:"if",cond:u(r[0],t),then:u(r[1],t),else:u(r[2],t)}}if(n==="field"){if(r.length!==2)throw g(n);let o=u(r[0],t),i=r[1];if(i.kind!=="lit"||typeof i.value!="string")throw g(n);return Cn({kind:"field",object:r[0],property:i.value},t)}if(To(n)){if(r.length!==1)throw g(n);return{kind:n,array:u(r[0],t)}}if(ko(n)){if(r.length!==1)throw g(n);return{kind:n,obj:u(r[0],t)}}if(n==="at"){if(r.length!==2)throw g(n);return{kind:"at",array:u(r[0],t),index:u(r[1],t)}}if(n==="includes"){if(r.length!==2)throw g(n);return{kind:"includes",array:u(r[0],t),item:u(r[1],t)}}if(bo(n)){if(r.length!==2)throw g(n);let o={...t,allowItem:!0};return n==="map"?{kind:"map",array:u(r[0],t),mapper:u(r[1],o)}:{kind:n,array:u(r[0],t),predicate:u(r[1],o)}}if(n==="slice"){if(r.length<2||r.length>3)throw g(n);let o={kind:"slice",array:u(r[0],t),start:u(r[1],t)};return r.length===3&&(o.end=u(r[2],t)),o}if(n==="substring"||n==="substr"){if(r.length<2||r.length>3)throw g(n);let o={kind:"substring",str:u(r[0],t),start:u(r[1],t)};return r.length===3&&(o.end=u(r[2],t)),o}if(n==="append"){if(r.length<1)throw g(n);return{kind:"append",array:u(r[0],t),items:r.slice(1).map(o=>u(o,t))}}if(n==="merge")return{kind:"merge",objects:r.map(o=>u(o,t))};throw g(n)}function ao(e,t){let n={};for(let r of wn(e.fields))n[r.key]=u(r.value,t);return{kind:"object",fields:n}}function so(e,t){if(e.elements.every(o=>o.kind==="lit"))return{kind:"lit",value:e.elements.map(i=>i.value)};let r=e.elements.map(o=>u(o,t));return r.length===0?{kind:"lit",value:[]}:{kind:"append",array:{kind:"lit",value:[]},items:r}}function co(e,t){if(e.length<3)throw g("match");let n=u(e[0],t),r=u(e[e.length-1],t);for(let o=e.length-2;o>=1;o-=1){let i=e[o];if(i.kind!=="arr"||i.elements.length!==2)throw g("match");r={kind:"if",cond:{kind:"eq",left:n,right:u(i.elements[0],t)},then:u(i.elements[1],t),else:r}}return r}function lo(e,t,n){if(t.length<2)throw g(e);let r=t[t.length-1];if(r.kind!=="lit"||r.value!=="first"&&r.value!=="last")throw g(e);let o=t.slice(0,-1).map(i=>po(i,n,e));if(o.length===0)throw g(e);return uo(e,o,r.value)}function po(e,t,n){if(e.kind!=="arr"||e.elements.length!==3)throw g(n);return{label:u(e.elements[0],t),eligible:u(e.elements[1],t),score:u(e.elements[2],t)}}function uo(e,t,n){let r={kind:"lit",value:null};for(let o=t.length-1;o>=0;o-=1)r={kind:"if",cond:fo(e,t,n,o),then:t[o].label,else:r};return r}function fo(e,t,n,r){let o=t[r],i=[];for(let a=0;a<t.length;a+=1){if(a===r)continue;let s=t[a];i.push({kind:"or",args:[{kind:"not",arg:s.eligible},{kind:mo(e,n,r,a),left:o.score,right:s.score}]})}return i.length===0?o.eligible:{kind:"and",args:[o.eligible,...i]}}function mo(e,t,n,r){let o=t==="first"?n<r:n>r;return e==="argmax"?o?"gte":"gt":o?"lte":"lt"}function ho(e){return["eq","neq","gt","gte","lt","lte","add","sub","mul","div","mod"].includes(e)}function Pn(e){return["not","neg","abs","floor","ceil","round","sqrt","len","typeof","isNull","toString"].includes(e)}function yo(e){if(e==="isNotNull")throw g(e);if(!Pn(e))throw g(e);return e}function go(e){return e==="min"||e==="max"}function Eo(e){return["and","or","concat","coalesce"].includes(e)}function To(e){return["first","last"].includes(e)}function ko(e){return["keys","values","entries"].includes(e)}function bo(e){return["filter","find","every","some","map"].includes(e)}function No(e,t){return e.map(n=>So(n,t))}function So(e,t){let n=e.condition?u(e.condition,Ke(t,"action")):void 0,r=vo(e.op,t);return{fragmentId:e.fragmentId,condition:n,op:r,confidence:e.confidence}}function vo(e,t){switch(e.kind){case"addType":return{kind:"addType",typeName:e.typeName,typeExpr:ue(e.typeExpr)};case"addField":return{kind:"addField",typeName:e.typeName,field:{name:e.field.name,type:ue(e.field.type),optional:e.field.optional,defaultValue:e.field.defaultValue}};case"setFieldType":return{kind:"setFieldType",path:e.path,typeExpr:ue(e.typeExpr)};case"setDefaultValue":return{kind:"setDefaultValue",path:e.path,value:e.value};case"addConstraint":return{kind:"addConstraint",targetPath:e.targetPath,rule:u(e.rule,Ke(t,"schema")),message:e.message};case"addComputed":return{kind:"addComputed",name:e.name,expr:u(e.expr,Ke(t,"schema")),deps:e.deps};case"addActionAvailable":return{kind:"addActionAvailable",actionName:e.actionName,expr:u(e.expr,Ke(t,"schema"))}}}function ue(e){switch(e.kind){case"primitive":return{kind:"primitive",name:e.name};case"array":return{kind:"array",element:ue(e.element)};case"object":return{kind:"object",fields:e.fields.map(t=>({name:t.name,type:ue(t.type),optional:t.optional}))};case"union":return{kind:"union",members:e.members.map(ue)};case"literal":return{kind:"literal",value:e.value};case"ref":return{kind:"ref",name:e.name}}}function Ke(e,t){return{mode:t,allowSysPaths:e.allowSysPaths,fnTableVersion:e.fnTableVersion,actionName:e.actionName,allowItem:!1}}function xo(e,t){return e.map(n=>We(n,t))}function We(e,t){let n=e.condition?u(e.condition,t):void 0,r=e.value?u(e.value,t):void 0;return{condition:n,op:e.op,path:Ao(e.path,t),value:r}}function Ao(e,t){return e.map(n=>n.kind==="prop"?n:{kind:"expr",expr:u(n.expr,t)})}function C(e,t={}){switch(e.kind){case"literal":return{kind:"lit",value:Io(e.value,e.literalType)};case"identifier":return t.resolveIdentifier?.(e.name)??V(e.name);case"systemIdent":return Co(e,t);case"iterationVar":return{kind:"var",name:e.name};case"propertyAccess":return Po(e.object,e.property,t);case"indexAccess":return{kind:"call",fn:"at",args:[C(e.object,t),C(e.index,t)]};case"functionCall":return{kind:"call",fn:e.name,args:e.args.map(n=>C(n,t))};case"unary":return{kind:"call",fn:e.operator==="!"?"not":"neg",args:[C(e.operand,t)]};case"binary":return{kind:"call",fn:Mo(e.operator),args:[C(e.left,t),C(e.right,t)]};case"ternary":return{kind:"call",fn:"cond",args:[C(e.condition,t),C(e.consequent,t),C(e.alternate,t)]};case"objectLiteral":return wo(e,t);case"arrayLiteral":return{kind:"arr",elements:e.elements.map(n=>C(n,t))}}}function wo(e,t){if(!e.properties.some(a=>a.kind==="objectSpread"))return{kind:"obj",fields:e.properties.map(a=>{if(a.kind!=="objectProperty")throw new Error("Unexpected non-property in non-spread object literal");return{key:a.key,value:C(a.value,t)}})};let r=[],o=[],i=()=>{o.length!==0&&(r.push({kind:"obj",fields:o}),o=[])};for(let a of e.properties){if(a.kind==="objectProperty"){o.push({key:a.key,value:C(a.value,t)});continue}i(),r.push(C(a.expr,t))}return i(),{kind:"call",fn:"merge",args:r}}function V(...e){return{kind:"get",path:In(...e)}}function Ct(e,...t){return{kind:"get",base:e,path:In(...t)}}function Ce(...e){return{kind:"sys",path:e}}function Ye(e){return{kind:"obj",fields:Object.entries(e).map(([t,n])=>({key:t,value:n}))}}function In(...e){return e.map(t=>({kind:"prop",name:t}))}function Co(e,t){return t.resolveSystemIdent?.(e.path)??Ce(...e.path)}function Po(e,t,n){let r=C(e,n);return r.kind==="get"?{kind:"get",...r.base?{base:r.base}:void 0,path:[...r.path,{kind:"prop",name:t}]}:r.kind==="var"&&r.name==="item"?Ct(r,t):{kind:"field",object:r,property:t}}function Io(e,t){if(t==="null")return null;if(t==="number"){if(typeof e=="number")return e;if(typeof e=="bigint")return Number(e);if(typeof e=="string"&&e.length>0){let n=Number(e);if(!Number.isNaN(n))return n}throw new Error("Invalid number literal")}if(t==="string"){if(typeof e=="string")return e;throw new Error("Invalid string literal")}if(t==="boolean"){if(typeof e=="boolean")return e;throw new Error("Invalid boolean literal")}throw new Error("Unsupported literal type")}function Mo(e){switch(e){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 Fo,semanticPathToPatchPath as _o,sha256Sync as $o}from"@manifesto-ai/core";var Do=new Set(["findById","existsById","updateById","removeById"]);function Mn(e){return{...e,computed:{fields:Object.fromEntries(Object.entries(e.computed.fields).map(([t,n])=>[t,Oo(n)]))},actions:Object.fromEntries(Object.entries(e.actions).map(([t,n])=>[t,Lo(n)]))}}function Oo(e){return{...e,expr:Dn(e.expr)}}function Lo(e){return{...e,flow:Qe(e.flow),available:e.available?Dn(e.available):void 0,dispatchable:e.dispatchable?Ro(e.dispatchable):void 0}}function Qe(e){switch(e.kind){case"seq":return{kind:"seq",steps:e.steps.map(t=>Qe(t))};case"if":return{kind:"if",cond:Pt(e.cond),then:Qe(e.then),else:e.else?Qe(e.else):void 0};case"patch":return{kind:"patch",op:e.op,path:e.path,value:e.value?Pt(e.value):void 0};case"effect":return{kind:"effect",type:e.type,params:Object.fromEntries(Object.entries(e.params).map(([t,n])=>[t,jo(n)]))};case"fail":return{kind:"fail",code:e.code,message:e.message?Pt(e.message):void 0};case"call":case"halt":return e}}function Dn(e){return u(L(e),Nt)}function Pt(e){return u(L(e),St)}function Ro(e){return u(L(e),vt)}function jo(e){return u(L(e),xt)}function L(e){switch(e.kind){case"lit":case"var":return e;case"sys":return e.path[0]==="system"?V("$system",...e.path.slice(1)):e;case"get":return{kind:"get",...e.base?{base:L(e.base)}:void 0,path:e.path};case"field":return{kind:"field",object:L(e.object),property:e.property};case"obj":return{kind:"obj",fields:e.fields.map(t=>({key:t.key,value:L(t.value)}))};case"arr":return{kind:"arr",elements:e.elements.map(t=>L(t))};case"call":return Do.has(e.fn)?L(On(e.fn,e.args)):{kind:"call",fn:e.fn,args:e.args.map(t=>L(t))}}}function On(e,t){let[n,r,o]=t,i=L(n),a=r?L(r):{kind:"lit",value:null},s={kind:"var",name:"item"},c=Ct(s,"id");switch(e){case"findById":return{kind:"call",fn:"find",args:[i,{kind:"call",fn:"eq",args:[c,a]}]};case"existsById":return{kind:"call",fn:"not",args:[{kind:"call",fn:"isNull",args:[On("findById",t)]}]};case"updateById":{let l=o?L(o):Ye({});return{kind:"call",fn:"map",args:[i,{kind:"call",fn:"cond",args:[{kind:"call",fn:"eq",args:[c,a]},{kind:"call",fn:"merge",args:[s,l]},s]}]}}case"removeById":return{kind:"call",fn:"filter",args:[i,{kind:"call",fn:"not",args:[{kind:"call",fn:"eq",args:[c,a]}]}]};default:return{kind:"call",fn:e,args:t.map(l=>L(l))}}}function Go(e){return{domainName:e,stateFields:new Set,computedFields:new Set,actionParams:new Map,onceIntentCounters:new Map,currentAction:null,diagnostics:[],typeDefs:new Map,typeDefinitions:new Map,stateFieldSpecs:new Map,stateFieldTypes:new Map}}function Bo(e){let t=Go(e.domain.name);Uo(e.domain,t);let n=qo(e.domain,t),r=zo(e.domain,t),o=Yo(e.domain,t),i=ei(e.domain,t);if(t.diagnostics.some(l=>l.severity==="error"))return{schema:null,diagnostics:t.diagnostics};let a={id:`mel:${e.domain.name.toLowerCase()}`,version:"1.0.0",types:n,state:r,computed:o,actions:i,meta:{name:e.domain.name}},s=ui(a);return{schema:{...a,hash:s},diagnostics:t.diagnostics}}function Ln(e){let t=Bo(e);return t.schema?{schema:Mn(t.schema),diagnostics:t.diagnostics}:{schema:null,diagnostics:t.diagnostics}}function Uo(e,t){for(let n of e.types)t.typeDefs.set(n.name,n);for(let n of e.members)if(n.kind==="state")for(let r of n.fields)t.stateFields.add(r.name);else n.kind==="computed"?t.computedFields.add(n.name):n.kind}function qo(e,t){let n={};for(let r of e.types){let o=Q(r.typeExpr);t.typeDefinitions.set(r.name,o),n[r.name]={name:r.name,definition:o}}return n}function Q(e){switch(e.kind){case"simpleType":return["string","number","boolean","null","object","array"].includes(e.name)?{kind:"primitive",type:e.name}:{kind:"ref",name:e.name};case"arrayType":return{kind:"array",element:Q(e.elementType)};case"recordType":return{kind:"record",key:Q(e.keyType),value:Q(e.valueType)};case"objectType":let t={};for(let r of e.fields)t[r.name]={type:Q(r.typeExpr),optional:r.optional};return{kind:"object",fields:t};case"unionType":return{kind:"union",types:e.types.map(Q)};case"literalType":return{kind:"literal",value:e.value};default:let n=e;throw new Error(`Unknown type expression kind: ${e.kind}`)}}function zo(e,t){let n={},r={};for(let o of e.members)if(o.kind==="state")for(let i of o.fields){let a=Q(i.typeExpr);r[i.name]=a,t.stateFieldTypes.set(i.name,a);let s=re(i.typeExpr,t);s&&t.stateFieldSpecs.set(i.name,s);let c=Vo(i,t);c&&(n[i.name]=c)}return{fields:n,fieldTypes:r}}function Vo(e,t){let n=re(e.typeExpr,t);if(!n)return null;let r=e.initializer?Me(e.initializer,t):void 0;return r!==void 0&&Ie(r,Q(e.typeExpr),e.name,e.location,t),{...n,required:!0,default:r}}function re(e,t,n=[]){switch(e.kind){case"simpleType":switch(e.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 r=t.typeDefs.get(e.name);return r?n.includes(e.name)?(It(t,"E044",`Recursive type '${e.name}' cannot be lowered to FieldSpec in a schema position`,e.location),null):re(r.typeExpr,t,[...n,e.name]):{type:"object",required:!0}}}case"unionType":{let r=e.types.filter(s=>!Ho(s,t,n)),o=r.length!==e.types.length,i=[],a=!o;for(let s of r){if(s.kind!=="literalType"){a=!1;break}i.push(s.value)}return a&&i.length>0?{type:{enum:i},required:!0}:o&&r.length===1?re(r[0],t,n):(It(t,"E043",`Union type '${fe(e)}' cannot be soundly lowered to FieldSpec`,e.location),null)}case"arrayType":{let r=re(e.elementType,t,n);return r?{type:"array",required:!0,items:r}:null}case"recordType":return{type:"object",required:!0};case"literalType":return typeof e.value=="string"?{type:"string",required:!0}:typeof e.value=="number"?{type:"number",required:!0}:typeof e.value=="boolean"?{type:"boolean",required:!0}:{type:"null",required:!0};case"objectType":{let r={};for(let o of e.fields){let i=re(o.typeExpr,t,n);if(!i)return null;r[o.name]={...i,required:!o.optional}}return{type:"object",required:!0,fields:r}}}}function Rn(e,t,n=[]){if(e.kind!=="simpleType")return e;let r=t.typeDefs.get(e.name);return r?n.includes(e.name)?null:Rn(r.typeExpr,t,[...n,e.name]):e}function Ho(e,t,n=[]){let r=Rn(e,t,n);return r?.kind==="simpleType"&&r.name==="null"||r?.kind==="literalType"&&r.value===null}function It(e,t,n,r){e.diagnostics.push({severity:"error",code:t,message:n,location:r})}function fe(e){switch(e.kind){case"simpleType":return e.name;case"unionType":return e.types.map(t=>fe(t)).join(" | ");case"arrayType":return`Array<${fe(e.elementType)}>`;case"recordType":return`Record<${fe(e.keyType)}, ${fe(e.valueType)}>`;case"literalType":return JSON.stringify(e.value);case"objectType":return`{ ${e.fields.map(t=>`${t.name}${t.optional?"?":""}: ${fe(t.typeExpr)}`).join("; ")} }`}}function oe(e,t,n=[]){if(e.kind!=="ref")return e;if(n.includes(e.name))return null;let r=t.typeDefinitions.get(e.name);return r?oe(r,t,[...n,e.name]):null}function Ko(e){return e?.kind==="primitive"&&e.type==="null"||e?.kind==="literal"&&e.value===null}function jn(e,t){let n=oe(e,t);if(!n||n.kind!=="union")return null;let r=n.types.filter(o=>{let i=oe(o,t);return!Ko(i)});return r.length===1?r[0]:null}function Wo(e,t,n){if(t===null||Array.isArray(t)||typeof t!="object")return e;let r=jn(e,n);return r&&oe(r,n)?.kind==="object"?r:e}function J(e){switch(e.kind){case"primitive":return e.type;case"array":return`Array<${J(e.element)}>`;case"record":return`Record<${J(e.key)}, ${J(e.value)}>`;case"object":return`{ ${Object.entries(e.fields).map(([t,n])=>`${t}${n.optional?"?":""}: ${J(n.type)}`).join("; ")} }`;case"union":return e.types.map(t=>J(t)).join(" | ");case"literal":return JSON.stringify(e.value);case"ref":return e.name}}function Pe(e,t,n){let r=oe(t,n);if(!r)return!1;switch(r.kind){case"primitive":switch(r.type){case"null":return e===null;case"string":return typeof e=="string";case"number":return typeof e=="number";case"boolean":return typeof e=="boolean";case"object":return e!==null&&!Array.isArray(e)&&typeof e=="object";case"array":return Array.isArray(e);default:return!1}case"literal":return Object.is(e,r.value);case"array":return Array.isArray(e)&&e.every(o=>Pe(o,r.element,n));case"record":return e!==null&&!Array.isArray(e)&&typeof e=="object"&&Object.values(e).every(o=>Pe(o,r.value,n));case"object":if(e===null||Array.isArray(e)||typeof e!="object")return!1;for(let o of Object.keys(e))if(!(o in r.fields))return!1;for(let[o,i]of Object.entries(r.fields)){if(!(o in e)){if(!i.optional)return!1;continue}if(!Pe(e[o],i.type,n))return!1}return!0;case"union":return r.types.some(o=>Pe(e,o,n));case"ref":return!1}}function Ie(e,t,n,r,o){if(e===void 0)return;let i=oe(t,o);if(!i){o.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${J(t)}, got ${JSON.stringify(e)}`,location:r});return}if(i.kind==="union"){if(Pe(e,i,o))return;o.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${J(i)}, got ${JSON.stringify(e)}`,location:r});return}switch(i.kind){case"primitive":{let a=Array.isArray(e)?"array":e===null?"null":typeof e;switch(i.type){case"null":e!==null&&ne(o,n,"null",a,r);return;case"string":case"number":case"boolean":typeof e!==i.type&&ne(o,n,i.type,a,r);return;case"object":(e===null||Array.isArray(e)||typeof e!="object")&&ne(o,n,"object",a,r);return;case"array":Array.isArray(e)||ne(o,n,"array",a,r);return}return}case"literal":Object.is(e,i.value)||o.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects literal ${JSON.stringify(i.value)}, got ${JSON.stringify(e)}`,location:r});return;case"array":if(!Array.isArray(e)){ne(o,n,"array",e===null?"null":typeof e=="object"?"object":typeof e,r);return}for(let a=0;a<e.length;a+=1)Ie(e[a],i.element,`${n}[${a}]`,r,o);return;case"record":if(e===null||Array.isArray(e)||typeof e!="object"){let a=Array.isArray(e)?"array":e===null?"null":typeof e;ne(o,n,"object",a,r);return}for(let[a,s]of Object.entries(e))Ie(s,i.value,`${n}.${a}`,r,o);return;case"object":if(e===null||Array.isArray(e)||typeof e!="object"){let a=Array.isArray(e)?"array":e===null?"null":typeof e;ne(o,n,"object",a,r);return}for(let a of Object.keys(e))a in i.fields||o.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}.${a}' is not declared in ${J(i)}`,location:r});for(let[a,s]of Object.entries(i.fields)){if(!(a in e)){s.optional||o.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}.${a}' is required`,location:r});continue}Ie(e[a],s.type,`${n}.${a}`,r,o)}return;case"ref":o.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${J(t)}, got ${JSON.stringify(e)}`,location:r});return}}function ne(e,t,n,r,o){e.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${t}' expects ${n}, got ${r}`,location:o})}function Me(e,t){switch(e.kind){case"literal":return e.value;case"arrayLiteral":return e.elements.map(n=>Me(n,t));case"objectLiteral":{let n={};for(let r of e.properties){if(r.kind==="objectProperty"){n[r.key]=Me(r.value,t);continue}let o=Me(r.expr,t);o!==null&&!Array.isArray(o)&&typeof o=="object"&&Object.assign(n,o)}return n}default:return}}function Yo(e,t){let n=[],r=0;for(let i of e.members)if(i.kind==="computed"){let a=H(i.expression,t),s=Zo(a);n.push({name:i.name,deps:s,expr:a,location:i.location,order:r}),r+=1}let o={};for(let i of Qo(n,t))o[i.name]={deps:i.deps,expr:i.expr};return{fields:o}}function Qo(e,t){if(e.length<=1)return[...e];let n=new Map(e.map(c=>[c.name,c])),r=new Map,o=new Map,i=new Map;for(let c of e)o.set(c.name,[]),i.set(c.name,0);for(let c of e){let l=Array.from(new Set(c.deps.filter(d=>n.has(d))));r.set(c.name,l),i.set(c.name,l.length);for(let d of l)o.get(d).push(c.name)}let a=e.filter(c=>(i.get(c.name)??0)===0).map(c=>c.name),s=[];for(;a.length>0;){let c=a.shift();s.push(n.get(c));for(let l of o.get(c)??[]){let d=(i.get(l)??0)-1;i.set(l,d),d===0&&Jo(a,l,n)}}if(s.length!==e.length){let c=new Set(s.map(f=>f.name)),l=e.filter(f=>!c.has(f.name)),d=Xo(l[0].name,r),p=d?d.join(" -> "):l.map(f=>f.name).join(", ");return It(t,"E040",`Circular computed dependency: ${p}`,(d?n.get(d[0]):l[0]).location),[...e]}return s}function Jo(e,t,n){let r=n.get(t)?.order??Number.MAX_SAFE_INTEGER,o=e.length;for(let i=0;i<e.length;i+=1){let a=n.get(e[i])?.order??Number.MAX_SAFE_INTEGER;if(r<a){o=i;break}}e.splice(o,0,t)}function Xo(e,t){let n=new Set,r=[],o=new Set;function i(a){n.add(a),r.push(a),o.add(a);for(let s of t.get(a)??[])if(n.has(s)){if(o.has(s)){let c=r.indexOf(s);return[...r.slice(c),s]}}else{let c=i(s);if(c)return c}return r.pop(),o.delete(a),null}return i(e)}function Zo(e){let t=new Set;function n(r){switch(r.kind){case"lit":case"sys":case"var":return;case"get":r.base===void 0?t.add(r.path.map(o=>o.name).join(".")):n(r.base);return;case"field":n(r.object);return;case"call":for(let o of r.args)n(o);return;case"obj":for(let o of r.fields)n(o.value);return;case"arr":for(let o of r.elements)n(o);return}}return n(e),Array.from(t)}function ei(e,t){let n={};for(let r of e.members)if(r.kind==="action"){t.currentAction=r.name,t.onceIntentCounters.set(r.name,0);let o=new Set;for(let p of r.params)o.add(p.name);t.actionParams.set(r.name,o);let i=r.params.map(p=>p.name),a=Fn(r.body,t),s,c;if(r.params.length>0){let p={},f={};for(let h of r.params){let A=re(h.typeExpr,t);A&&(p[h.name]=structuredClone(A),f[h.name]={type:Q(h.typeExpr),optional:!1})}s={type:"object",required:!0,fields:p},c={kind:"object",fields:f}}let l;r.available&&(l=H(r.available,t));let d;r.dispatchable&&(d=H(r.dispatchable,t,{preferActionParams:!0})),n[r.name]={flow:a,input:s,inputType:c,params:i,available:l,dispatchable:d},t.currentAction=null}return n}function Fn(e,t){return e.length===0?{kind:"seq",steps:[]}:e.length===1?Xe(e[0],t):{kind:"seq",steps:e.map(n=>Xe(n,t))}}function Xe(e,t){switch(e.kind){case"when":return ti(e,t);case"once":return ni(e,t);case"onceIntent":return ri(e,t);case"patch":return oi(e,t);case"effect":return ii(e,t);case"fail":return si(e,t);case"stop":return ci(e,t);case"include":return{kind:"seq",steps:[]}}}function ti(e,t){let n=H(e.condition,t),r=Fn(e.body,t);return{kind:"if",cond:n,then:r}}function ni(e,t){let n=Mt(e.marker,t),r=Ce("meta","intentId"),o=Ze("neq",[V(..._n(n)),r]);if(e.condition){let s=H(e.condition,t);o=Ze("and",[o,s])}let i={kind:"patch",op:"set",path:Dt(n),value:r},a=e.body.map(s=>Xe(s,t));return{kind:"if",cond:o,then:{kind:"seq",steps:[i,...a]}}}function ri(e,t){let n=t.currentAction??"unknown",r=t.onceIntentCounters.get(n)??0;t.onceIntentCounters.set(n,r+1);let o=$o(`${n}:${r}:intent`),i=`$mel.guards.intent.${o}`,a=Ce("meta","intentId"),s=Ze("neq",[V(..._n(i)),a]);if(e.condition){let d=H(e.condition,t);s=Ze("and",[s,d])}let c={kind:"patch",op:"merge",path:Dt("$mel.guards.intent"),value:Ye({[o]:a})},l=e.body.map(d=>Xe(d,t));return{kind:"if",cond:s,then:{kind:"seq",steps:[c,...l]}}}function oi(e,t){let n=Mt(e.path,t),r={kind:"patch",op:e.op,path:Dt(n)};if(e.value){let o=H(e.value,t);if(r.value=o,e.op==="set"){let i=e.path.segments[0];if(i.kind==="propertySegment"){let a=t.stateFieldTypes.get(i.name);if(a){let s=a,c=e.path.segments;for(let l=1;l<c.length;l++){let d=c[l],p=s?oe(s,t):null;if(!p){s=null;break}if(p.kind==="union"){let f=jn(s,t);if(!f){s=null;break}s=f,l-=1;continue}if(d.kind==="propertySegment"&&p.kind==="object"&&p.fields[d.name])s=p.fields[d.name].type;else if(d.kind==="propertySegment"&&p.kind==="record")s=p.value;else if(d.kind==="indexSegment"&&p.kind==="array")s=p.element;else{s=null;break}}if(s){let l=ai(e.value,t);if(l!==void 0){let d=e.path.segments.map(f=>f.kind==="propertySegment"?f.name:"[*]").join("."),p=Wo(s,l,t);Ie(l,p,d,e.location,t)}}}}}}return r}function ii(e,t){let n={};for(let r of e.args)r.isPath?n[r.name]={kind:"lit",value:Mt(r.value,t)}:n[r.name]=H(r.value,t);return{kind:"effect",type:e.effectType,params:n}}function ai(e,t){return Me(e,t)}function si(e,t){let n={kind:"fail",code:e.code};return e.message&&(n.message=H(e.message,t)),n}function ci(e,t){return{kind:"halt",reason:e.reason}}function li(e){return e.replaceAll("\\","\\\\").replaceAll(".","\\.")}function Je(...e){return e.map(li).join(".")}function Mt(e,t){let n=[];for(let o of e.segments)if(o.kind==="propertySegment")n.push(o.name);else{let i=H(o.index,t);i.kind==="lit"?n.push(String(i.value)):n.push("*")}let r=n[0];return t.stateFields.has(r)?Je(...n):t.computedFields.has(r)?Je(...n):t.currentAction&&t.actionParams.get(t.currentAction)?.has(r)?`input.${Je(...n)}`:Je(...n)}function Dt(e){return _o(e)}function Ze(e,t){return{kind:"call",fn:e,args:t}}function _n(e){return e.split(/(?<!\\)\./g).map(t=>t.replaceAll("\\.",".").replaceAll("\\\\","\\"))}function H(e,t,n={}){return C(e,{resolveIdentifier:r=>di(r,t,n),resolveSystemIdent:r=>pi(r,t)})}function di(e,t,n={}){return n.preferActionParams&&t.currentAction&&t.actionParams.get(t.currentAction)?.has(e)?V("input",e):t.stateFields.has(e)||t.computedFields.has(e)?V(e):t.currentAction&&t.actionParams.get(t.currentAction)?.has(e)?V("input",e):(t.diagnostics.push({severity:"error",code:"E_UNKNOWN_IDENT",message:`Unknown identifier '${e}'`,location:{start:{line:0,column:0,offset:0},end:{line:0,column:0,offset:0}}}),V(e))}function pi(e,t){let[n,...r]=e;switch(n){case"system":case"meta":case"input":return Ce(n,...r);default:return t.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(e){return Fo(e)}var fi="@meta can attach only to domain, type, type field, state field, computed, or action declarations.",mi="Action-parameter annotations are not part of the current MEL syntax.",Ot="Annotation payloads must be JSON-like literals. MEL expressions are not allowed in @meta payloads.",$n="Annotation payload nesting exceeds the current MEL limit of 2 levels.",hi="Annotation target does not map to the emitted DomainSchema.",Gn=2;function Bn(e,t){let n=[],r=new Map,o=e.domain;me(o.annotations,`domain:${o.name}`,n,r);for(let a of o.types)me(a.annotations,`type:${a.name}`,n,r),he(a.typeExpr,a.name,0,n,r);for(let a of o.members)switch(a.kind){case"state":for(let s of a.fields)me(s.annotations,`state_field:${s.name}`,n,r),ie(s.typeExpr,n);break;case"computed":me(a.annotations,`computed:${a.name}`,n,r);break;case"action":me(a.annotations,`action:${a.name}`,n,r),yi(a,n);for(let s of a.params)ie(s.typeExpr,n);break;case"flow":break}let i={};for(let a of[...r.keys()].sort()){if(!Ti(t,a)){n.push(M("E057",hi,ki(e,a)??o.location));continue}let s=r.get(a);s&&s.length>0&&(i[a]=Object.freeze(s.map(c=>Ei(c))))}return{annotations:Object.freeze({schemaHash:t.hash,entries:Object.freeze(i)}),diagnostics:n}}function me(e,t,n,r){if(!e||e.length===0)return;let o=[];for(let a of e){let s=a.payload===void 0?{ok:!0,value:void 0}:Lt(a.payload,0,n);s.ok&&o.push({tag:a.tag,...s.value===void 0?{}:{payload:s.value}})}if(o.length===0)return;let i=r.get(t);if(i){i.push(...o);return}r.set(t,o)}function he(e,t,n,r,o){switch(e.kind){case"objectType":for(let i of e.fields)i.annotations?.length&&(n===0?me(i.annotations,`type_field:${t}.${i.name}`,r,o):Un(i.annotations,r)),he(i.typeExpr,t,n+1,r,o);return;case"arrayType":he(e.elementType,t,n,r,o);return;case"recordType":he(e.keyType,t,n,r,o),he(e.valueType,t,n,r,o);return;case"unionType":for(let i of e.types)he(i,t,n,r,o);return;case"simpleType":case"literalType":return}}function ie(e,t){switch(e.kind){case"objectType":for(let n of e.fields)Un(n.annotations,t),ie(n.typeExpr,t);return;case"arrayType":ie(e.elementType,t);return;case"recordType":ie(e.keyType,t),ie(e.valueType,t);return;case"unionType":for(let n of e.types)ie(n,t);return;case"simpleType":case"literalType":return}}function yi(e,t){for(let n of e.params)gi(n,t)}function gi(e,t){if(e.annotations)for(let n of e.annotations)t.push(M("E054",mi,n.location))}function Un(e,t){if(e)for(let n of e)t.push(M("E053",fi,n.location))}function Lt(e,t,n){switch(e.kind){case"literal":return e.literalType==="string"||e.literalType==="number"||e.literalType==="boolean"||e.literalType==="null"?{ok:!0,value:e.value}:(n.push(M("E055",Ot,e.location)),{ok:!1});case"arrayLiteral":{if(t+1>Gn)return n.push(M("E056",$n,e.location)),{ok:!1};let r=[];for(let o of e.elements){let i=Lt(o,t+1,n);if(!i.ok)return{ok:!1};r.push(i.value)}return{ok:!0,value:r}}case"objectLiteral":{if(t+1>Gn)return n.push(M("E056",$n,e.location)),{ok:!1};let r={};for(let o of e.properties){if(o.kind!=="objectProperty")return n.push(M("E055",Ot,o.location)),{ok:!1};let i=Lt(o.value,t+1,n);if(!i.ok)return{ok:!1};r[o.key]=i.value}return{ok:!0,value:r}}default:return n.push(M("E055",Ot,e.location)),{ok:!1}}}function Ei(e){return e.payload===void 0?Object.freeze({tag:e.tag}):Object.freeze({tag:e.tag,payload:Rt(e.payload)})}function Rt(e){if(Array.isArray(e))return Object.freeze(e.map(t=>Rt(t)));if(e!==null&&typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=Rt(r);return Object.freeze(t)}return e}function Ti(e,t){let n=t.indexOf(":");if(n<0)return!1;let r=t.slice(0,n),o=t.slice(n+1);switch(r){case"domain":return e.meta?.name===o||e.id===`mel:${o.toLowerCase()}`;case"type":return Object.hasOwn(e.types,o);case"type_field":{let i=o.indexOf(".");if(i<=0||i!==o.lastIndexOf("."))return!1;let a=o.slice(0,i),s=o.slice(i+1),c=e.types[a];return!c||c.definition.kind!=="object"?!1:Object.hasOwn(c.definition.fields,s)}case"state_field":return Object.hasOwn(e.state.fields,o);case"computed":return Object.hasOwn(e.computed.fields,o);case"action":return Object.hasOwn(e.actions,o);default:return!1}}function ki(e,t){let n=t.indexOf(":");if(n<0)return null;let r=t.slice(0,n),o=t.slice(n+1),i=e.domain;if(r==="domain"&&i.name===o)return i.location;if(r==="type")return i.types.find(a=>a.name===o)?.location??null;if(r==="type_field"){let a=o.indexOf(".");if(a<=0)return null;let s=o.slice(0,a),c=o.slice(a+1),l=i.types.find(d=>d.name===s);return!l||l.typeExpr.kind!=="objectType"?l?.location??null:l.typeExpr.fields.find(d=>d.name===c)?.location??l.location}if(r==="state_field"){for(let a of i.members){if(a.kind!=="state")continue;let s=a.fields.find(c=>c.name===o);if(s)return s.location}return null}return r==="computed"?i.members.find(a=>a.kind==="computed"&&a.name===o)?.location??null:r==="action"?i.members.find(a=>a.kind==="action"&&a.name===o)?.location??null:null}var jt=16;function b(e){return structuredClone(e)}function I(e,t,n,r,o){let i=`${n}:${o.start.offset}:${o.end.offset}:${r}`;t.has(i)||(t.add(i),e.push(M(n,r,o)))}function bi(e){let t=new Map,n=new Set,r=new Map,o=new Set,i=new Map;for(let a of e.types)r.set(a.name,a);for(let a of e.members)switch(a.kind){case"state":for(let s of a.fields)t.set(s.name,s.typeExpr);break;case"computed":n.add(a.name);break;case"action":o.add(a.name);break;case"flow":i.has(a.name)||i.set(a.name,a);break}return{stateTypes:t,computedNames:n,typeDefs:r,actionNames:o,flows:i}}function Ni(e){let t=new Map;for(let n of e.params)t.set(n.name,n.typeExpr);return t}function Si(e){let t=new Map;for(let n of e.params)t.set(n.name,n.typeExpr);return t}function vi(e,t,n,r){let o=new Map;for(let i of t.flows.values()){o.set(i.name,[]),t.actionNames.has(i.name)&&I(n,r,"E022",`Flow '${i.name}' conflicts with action '${i.name}'.`,i.location);for(let s of i.params)(t.stateTypes.has(s.name)||t.computedNames.has(s.name)||t.typeDefs.has(s.name))&&I(n,r,"E021",`Flow parameter '${s.name}' conflicts with a top-level identifier.`,s.location);let a=Ni(i);for(let s of i.body)Ai(s,i.name,a,t,n,r,o.get(i.name))}for(let i of e.members)if(i.kind==="action"){let a=Si(i);for(let s of i.body)xi(s,a,t,n,r)}return o}function xi(e,t,n,r,o){switch(e.kind){case"include":tt(e,t,n,r,o);break;case"when":for(let i of e.body)Ee(i,t,n,r,o);break;case"once":for(let i of e.body)Ee(i,t,n,r,o);break;case"onceIntent":for(let i of e.body)Ee(i,t,n,r,o);break;case"fail":case"stop":break}}function Ee(e,t,n,r,o){switch(e.kind){case"include":I(r,o,"E016","include is only allowed at action or flow body top-level.",e.location),tt(e,t,n,r,o);break;case"when":for(let i of e.body)Ee(i,t,n,r,o);break;case"once":for(let i of e.body)Ee(i,t,n,r,o);break;case"onceIntent":for(let i of e.body)Ee(i,t,n,r,o);break;case"patch":case"effect":case"fail":case"stop":break}}function Ai(e,t,n,r,o,i,a){switch(e.kind){case"include":tt(e,n,r,o,i)&&a.push({target:e.flowName,location:e.location});break;case"when":for(let s of e.body)et(s,t,n,r,o,i);break;case"once":I(o,i,"E017","once() is not allowed in flow bodies.",e.location);break;case"onceIntent":I(o,i,"E018","onceIntent is not allowed in flow bodies.",e.location);break;case"patch":I(o,i,"E019","patch is not allowed in flow bodies.",e.location);break;case"effect":I(o,i,"E020","effect is not allowed in flow bodies.",e.location);break}}function et(e,t,n,r,o,i){switch(e.kind){case"include":I(o,i,"E016","include is only allowed at action or flow body top-level.",e.location),tt(e,n,r,o,i);break;case"when":for(let a of e.body)et(a,t,n,r,o,i);break;case"once":I(o,i,"E017","once() is not allowed in flow bodies.",e.location);for(let a of e.body)et(a,t,n,r,o,i);break;case"onceIntent":I(o,i,"E018","onceIntent is not allowed in flow bodies.",e.location);for(let a of e.body)et(a,t,n,r,o,i);break;case"patch":I(o,i,"E019","patch is not allowed in flow bodies.",e.location);break;case"effect":I(o,i,"E020","effect is not allowed in flow bodies.",e.location);break;case"fail":case"stop":break}}function tt(e,t,n,r,o){let i=n.flows.get(e.flowName);if(!i)return I(r,o,"E015",`'${e.flowName}' is not a declared flow.`,e.location),!1;if(e.args.length!==i.params.length)return I(r,o,"E023",`include '${e.flowName}' expected ${i.params.length} argument(s), got ${e.args.length}.`,e.location),!0;for(let a=0;a<e.args.length;a+=1){let s=e.args[a],c=i.params[a],l=ye(s,t,n);if(!l)continue;ge(l,c.typeExpr,n)===!1&&I(r,o,"E024",`include '${e.flowName}' argument ${a+1} is not assignable to parameter '${c.name}'.`,s.location)}return!0}function wi(e,t,n,r){function o(i,a,s){s.add(i);for(let c of e.get(i)??[]){if(a+1>jt){I(n,r,"E014",`Include expansion depth exceeds limit (${jt}).`,c.location);continue}if(s.has(c.target)){I(n,r,"E013","Circular include detected.",c.location);continue}o(c.target,a+1,new Set(s))}}for(let i of t.flows.keys())o(i,1,new Set)}function D(e,t){switch(e.kind){case"identifier":return t.has(e.name)?b(t.get(e.name)):b(e);case"systemIdent":case"literal":case"iterationVar":return b(e);case"functionCall":return{...b(e),args:e.args.map(n=>D(n,t))};case"binary":return{...b(e),left:D(e.left,t),right:D(e.right,t)};case"unary":return{...b(e),operand:D(e.operand,t)};case"ternary":return{...b(e),condition:D(e.condition,t),consequent:D(e.consequent,t),alternate:D(e.alternate,t)};case"propertyAccess":return{...b(e),object:D(e.object,t)};case"indexAccess":return{...b(e),object:D(e.object,t),index:D(e.index,t)};case"objectLiteral":return{...b(e),properties:e.properties.map(n=>({...b(n),...n.kind==="objectProperty"?{value:D(n.value,t)}:{expr:D(n.expr,t)}}))};case"arrayLiteral":return{...b(e),elements:e.elements.map(n=>D(n,t))}}}function Ci(e,t){switch(e.kind){case"when":return[qn(e,t)];case"fail":return[{...b(e),message:e.message?D(e.message,t):void 0}];case"stop":return[b(e)];case"patch":case"effect":case"once":case"onceIntent":case"include":return[]}}function qn(e,t){return{...b(e),condition:D(e.condition,t),body:e.body.flatMap(n=>Ci(n,t))}}function Pi(e,t,n){let r=new Map;for(let o=0;o<e.params.length;o+=1)r.set(e.params[o].name,D(t.args[o],n));return r}function Ii(e,t,n,r,o){switch(e.kind){case"when":return[qn(e,n)];case"include":return zn(e,t,n,r,o);case"once":case"onceIntent":case"patch":case"effect":return[]}}function zn(e,t,n,r,o){let i=t.flows.get(e.flowName);if(!i||e.args.length!==i.params.length||r>jt||o.includes(e.flowName))return[];let a=Pi(i,e,n),s=[...o,e.flowName];return i.body.flatMap(c=>Ii(c,t,a,r+1,s))}function Te(e){switch(e.kind){case"when":return[{...b(e),body:e.body.flatMap(t=>Te(t))}];case"once":return[{...b(e),body:e.body.flatMap(t=>Te(t))}];case"onceIntent":return[{...b(e),body:e.body.flatMap(t=>Te(t))}];case"include":return[];case"patch":case"effect":case"fail":case"stop":return[b(e)]}}function Mi(e,t,n){switch(e.kind){case"include":return zn(e,t,new Map,n,[]);case"when":return[{...b(e),body:e.body.flatMap(r=>Te(r))}];case"once":return[{...b(e),body:e.body.flatMap(r=>Te(r))}];case"onceIntent":return[{...b(e),body:e.body.flatMap(r=>Te(r))}];case"fail":case"stop":return[b(e)]}}function Di(e,t){let n=[];for(let r of e.domain.members)switch(r.kind){case"state":case"computed":n.push(b(r));break;case"action":n.push({...b(r),body:r.body.flatMap(o=>Mi(o,t,1))});break;case"flow":break}return{...b(e),domain:{...b(e.domain),types:e.domain.types.map(r=>b(r)),members:n}}}function ye(e,t,n){switch(e.kind){case"literal":return{kind:"literalType",value:e.value,location:e.location};case"identifier":return t.get(e.name)??n.stateTypes.get(e.name)??null;case"propertyAccess":{let r=ye(e.object,t,n);return Vn(r,e.property,n)}case"indexAccess":{let r=ye(e.object,t,n);return Hn(r,n)}case"objectLiteral":return Fe(e,t,n,ye,ae);case"arrayLiteral":{if(e.elements.length===0)return null;let r=ye(e.elements[0],t,n);return r?{kind:"arrayType",elementType:r,location:e.location}:null}case"functionCall":return e.name==="merge"?_e(e,t,n,ye,ae):null;case"systemIdent":case"binary":case"unary":case"ternary":case"iterationVar":return null}}function ae(e,t,n=new Set){return e?e.kind==="simpleType"&&t.typeDefs.has(e.name)?n.has(e.name)?null:(n.add(e.name),ae(t.typeDefs.get(e.name).typeExpr,t,n)):e:null}function Vn(e,t,n){let r=ae(e,n);if(!r)return null;if(r.kind==="objectType"){let o=r.fields.find(i=>i.name===t);return o?o.optional?Ft([o.typeExpr,{kind:"simpleType",name:"null",location:o.location}],o.location):o.typeExpr:null}if(r.kind==="unionType"){let o=r.types.filter(i=>!Kn(i)).map(i=>Vn(i,t,n)).filter(i=>i!==null);return Ft(o,r.location)}return null}function Hn(e,t){let n=ae(e,t);if(!n)return null;if(n.kind==="arrayType")return n.elementType;if(n.kind==="recordType")return n.valueType;if(n.kind==="unionType"){let r=n.types.filter(o=>!Kn(o)).map(o=>Hn(o,t)).filter(o=>o!==null);return Ft(r,n.location)}return null}function ge(e,t,n){let r=ae(e,n),o=ae(t,n);if(!r||!o)return null;if(o.kind==="unionType"){let i=o.types.map(a=>ge(r,a,n));return i.includes(!0)?!0:i.every(a=>a===!1)?!1:null}if(r.kind==="unionType"){let i=r.types.map(a=>ge(a,o,n));return i.every(a=>a===!0)?!0:i.some(a=>a===!1)?!1:null}if(o.kind==="simpleType"){if(r.kind==="simpleType")return r.name===o.name;if(r.kind==="literalType")return o.name==="null"?r.value===null:typeof r.value===o.name}if(o.kind==="literalType")return r.kind!=="literalType"?!1:r.value===o.value;if(o.kind==="arrayType")return r.kind!=="arrayType"?!1:ge(r.elementType,o.elementType,n);if(o.kind==="objectType"){if(r.kind!=="objectType")return!1;for(let i of o.fields){let a=r.fields.find(c=>c.name===i.name);if(!a){if(i.optional)continue;return!1}if(a.optional&&!i.optional)return!1;let s=ge(a.typeExpr,i.typeExpr,n);if(s!==!0)return s}return!0}return o.kind==="recordType"?r.kind!=="recordType"?null:ge(r.valueType,o.valueType,n):null}function Kn(e){return e.kind==="simpleType"&&e.name==="null"||e.kind==="literalType"&&e.value===null}function Ft(e,t){let n=e.filter(i=>i!==null).flatMap(i=>i.kind==="unionType"?i.types:[i]);if(n.length===0)return null;if(n.length===1)return n[0];let r=[],o=new Set;for(let i of n){let a=JSON.stringify(i);o.has(a)||(o.add(a),r.push(i))}return r.length===1?r[0]:{kind:"unionType",types:r,location:t}}function Wn(e){let t=bi(e.domain),n=[],r=new Set,o=vi(e.domain,t,n,r);return wi(o,t,n,r),{program:Di(e,t),diagnostics:n}}var Oi=new Set(["$item","$index","$array"]);function Jn(e){let t=Object.keys(e.state.fields).filter(d=>!d.startsWith("$")),n=Li(e),r=new Set(n),o=new Set(t),i=Object.keys(e.actions),a=[...t.map(d=>({id:_t(d),kind:"state",name:d})),...n.map(d=>({id:$t(d),kind:"computed",name:d})),...i.map(d=>({id:Qn(d),kind:"action",name:d}))],s=new Set,c=[],l=(d,p,f)=>{if(!d||!p)return;let h=`${d}|${f}|${p}`;s.has(h)||(s.add(h),c.push({from:d,to:p,relation:f}))};for(let d of n){let p=e.computed.fields[d];if(p)for(let f of p.deps)l(Yn(f,e,r,o),$t(d),"feeds")}for(let d of i){let p=e.actions[d],f=Qn(d);for(let h of Ri(p.flow,e))o.has(h)&&l(f,_t(h),"mutates");if(p.available)for(let h of nr(p.available))l(Yn(h,e,r,o),f,"unlocks")}return _i({nodes:a,edges:c})}function Li(e){let t=e.computed.fields,n=new Map,r=(o,i)=>{let a=n.get(o);if(a!==void 0)return a;if(i.has(o))return!1;i.add(o);let s=t[o];if(!s)return i.delete(o),n.set(o,!0),!0;for(let c of nr(s.expr)){if(tr(c))return i.delete(o),n.set(o,!1),!1;let l=Xn(c,t);if(l!==null&&!r(l,i))return i.delete(o),n.set(o,!1),!1}return i.delete(o),n.set(o,!0),!0};return Object.keys(t).filter(o=>r(o,new Set))}function Ri(e,t){let n=new Set,r=(o,i)=>{if(o)switch(o.kind){case"seq":o.steps.forEach(a=>r(a,i));return;case"if":r(o.then,i),r(o.else,i);return;case"patch":{let a=ji(o.path);a&&n.add(a);return}case"effect":{let a=Fi(o.params.into);a&&n.add(a);return}case"call":{if(i.has(o.flow))return;let a=t.actions[o.flow];if(!a)return;let s=new Set(i);s.add(o.flow),r(a.flow,s);return}case"halt":case"fail":return}};return r(e,new Set),[...n]}function ji(e){let[t]=e;return!t||t.kind!=="prop"||t.name.startsWith("$")?null:t.name}function Fi(e){return typeof e!="object"||e===null||e.kind!=="lit"||typeof e.value!="string"?null:Zn(e.value)}function Yn(e,t,n,r){let o=Xn(e,t.computed.fields);if(o!==null&&n.has(o))return $t(o);if(tr(e))return null;let i=Zn(e);return!i||!r.has(i)?null:_t(i)}function Xn(e,t){if(Object.prototype.hasOwnProperty.call(t,e))return e;if(!e.startsWith("computed."))return null;let n=e.slice(9);return Object.prototype.hasOwnProperty.call(t,n)?n:null}function Zn(e){let t=er(e),n=t.startsWith("data.")?t.slice(5):t,r=/^([^.[\]]+)/.exec(n);if(!r)return null;let[o]=r.slice(1);return!o||o.startsWith("$")?null:o}function er(e){return e.startsWith("/")?e.slice(1).replace(/\//g,"."):e}function tr(e){let t=er(e),n=t.startsWith("data.")?t.slice(5):t,o=/^([^.[\]]+)/.exec(n)?.[1]??"";return o.startsWith("$")?!Oi.has(o):!1}function nr(e){let t=[],n=new WeakSet,r=o=>{if(o==null)return;if(Array.isArray(o)){o.forEach(r);return}if(typeof o!="object")return;let i=o;if(!n.has(i)&&(n.add(i),i.kind!=="lit")){if(i.kind==="get"&&typeof i.path=="string"){t.push(i.path);return}for(let a of Object.values(i))r(a)}};return r(e),t}function _t(e){return`state:${e}`}function $t(e){return`computed:${e}`}function Qn(e){return`action:${e}`}function _i(e){return Object.freeze({nodes:Object.freeze(e.nodes.map(t=>Object.freeze(t))),edges:Object.freeze([...e.edges].sort($i).map(t=>Object.freeze(t)))})}function $i(e,t){return e.from.localeCompare(t.from)||e.to.localeCompare(t.to)||e.relation.localeCompare(t.relation)}var Gi="Source-map target does not map to the emitted DomainSchema.",Bi="Source-map entry missing for emitted DomainSchema target.",Ui=new TextEncoder;function sr(e){return Object.freeze({coordinateUnit:"utf16",compilerVersion:e,emissionOptionsFingerprint:"default"})}function cr(e,t,n,r){let o=[],i=new Map,a=e.domain,s=Vi(t,r.coordinateUnit);i.set(`domain:${a.name}`,Ne({target:{kind:"domain",domain:{name:a.name}},span:s(a.location)}));for(let l of a.types)i.set(`type:${l.name}`,Ne({target:{kind:"type",type:{name:l.name}},span:s(l.location)})),ke(l.typeExpr,l.name,0,i,s);for(let l of a.members)switch(l.kind){case"state":for(let d of l.fields)i.set(`state_field:${d.name}`,Ne({target:{kind:"state_field",field:{name:d.name}},span:s(d.location)}));break;case"computed":i.set(`computed:${l.name}`,Ne({target:{kind:"computed",computed:{name:l.name}},span:s(l.location)}));break;case"action":i.set(`action:${l.name}`,Ne({target:{kind:"action",action:{name:l.name}},span:s(l.location)}));break;case"flow":break}let c={};for(let l of[...i.keys()].sort()){if(!zi(n,l)){o.push(M("E058",Gi,rr(e,l)??a.location));continue}let d=i.get(l);d&&(c[l]=d)}for(let l of qi(e,n))Object.hasOwn(c,l)||o.push(M("E058",Bi,rr(e,l)??a.location));return{sourceMap:Object.freeze({schemaHash:n.hash,sourceHash:ir(t),format:"manifesto/source-map-v1",coordinateUnit:r.coordinateUnit,emissionFingerprint:ir(`${r.coordinateUnit}\0${r.compilerVersion}\0${r.emissionOptionsFingerprint}`),entries:Object.freeze(c)}),diagnostics:o}}function ke(e,t,n,r,o){switch(e.kind){case"objectType":for(let i of e.fields)n===0&&r.set(`type_field:${t}.${i.name}`,Ne({target:{kind:"type_field",type:{name:t},field:{name:i.name}},span:o(i.location)})),ke(i.typeExpr,t,n+1,r,o);return;case"arrayType":ke(e.elementType,t,n+1,r,o);return;case"recordType":ke(e.keyType,t,n+1,r,o),ke(e.valueType,t,n+1,r,o);return;case"unionType":for(let i of e.types)ke(i,t,n+1,r,o);return;case"simpleType":case"literalType":return}}function qi(e,t){let n=new Set;n.add(`domain:${e.domain.name}`);for(let[r,o]of Object.entries(t.types))if(n.add(`type:${r}`),o.definition.kind==="object")for(let i of Object.keys(o.definition.fields))n.add(`type_field:${r}.${i}`);for(let r of Object.keys(t.state.fields))n.add(`state_field:${r}`);for(let r of Object.keys(t.computed.fields))n.add(`computed:${r}`);for(let r of Object.keys(t.actions))n.add(`action:${r}`);return[...n].sort()}function zi(e,t){let n=t.indexOf(":");if(n<0)return!1;let r=t.slice(0,n),o=t.slice(n+1);switch(r){case"domain":return e.meta?.name===o||e.id===`mel:${o.toLowerCase()}`;case"type":return Object.hasOwn(e.types,o);case"type_field":{let i=o.indexOf(".");if(i<=0||i!==o.lastIndexOf("."))return!1;let a=o.slice(0,i),s=o.slice(i+1),c=e.types[a];return!c||c.definition.kind!=="object"?!1:Object.hasOwn(c.definition.fields,s)}case"state_field":return Object.hasOwn(e.state.fields,o);case"computed":return Object.hasOwn(e.computed.fields,o);case"action":return Object.hasOwn(e.actions,o);default:return!1}}function rr(e,t){let n=t.indexOf(":");if(n<0)return null;let r=t.slice(0,n),o=t.slice(n+1);switch(r){case"domain":return e.domain.name===o?e.domain.location:null;case"type":return e.domain.types.find(i=>i.name===o)?.location??null;case"type_field":{let i=o.indexOf(".");if(i<=0||i!==o.lastIndexOf("."))return null;let a=o.slice(0,i),s=o.slice(i+1),c=e.domain.types.find(l=>l.name===a);return c?be(c.typeExpr,s,0):null}case"state_field":for(let i of e.domain.members){if(i.kind!=="state")continue;let a=i.fields.find(s=>s.name===o);if(a)return a.location}return null;case"computed":return e.domain.members.find(i=>i.kind==="computed"&&i.name===o)?.location??null;case"action":return e.domain.members.find(i=>i.kind==="action"&&i.name===o)?.location??null;default:return null}}function be(e,t,n){switch(e.kind){case"objectType":for(let r of e.fields){if(n===0&&r.name===t)return r.location;let o=be(r.typeExpr,t,n+1);if(o)return o}return null;case"arrayType":return be(e.elementType,t,n+1);case"recordType":return be(e.keyType,t,n+1)??be(e.valueType,t,n+1);case"unionType":for(let r of e.types){let o=be(r,t,n+1);if(o)return o}return null;case"simpleType":case"literalType":return null}}function Vi(e,t){return t==="utf16"?n=>Hi(n):n=>Ki(n,e)}function Hi(e){return Object.freeze({start:Object.freeze({line:e.start.line,column:e.start.column}),end:Object.freeze({line:e.end.line,column:e.end.column})})}function Ki(e,t){return Object.freeze({start:or(e.start,t),end:or(e.end,t)})}function or(e,t){let n=ar(t.slice(0,e.offset)),r=e.offset-(e.column-1),o=ar(t.slice(0,r));return Object.freeze({line:e.line,column:n-o+1})}function Ne(e){return Object.freeze({target:Wi(e.target),span:Object.freeze({start:Object.freeze({...e.span.start}),end:Object.freeze({...e.span.end})})})}function Wi(e){switch(e.kind){case"domain":return Object.freeze({kind:e.kind,domain:Object.freeze({...e.domain})});case"type":return Object.freeze({kind:e.kind,type:Object.freeze({...e.type})});case"type_field":return Object.freeze({kind:e.kind,type:Object.freeze({...e.type}),field:Object.freeze({...e.field})});case"state_field":return Object.freeze({kind:e.kind,field:Object.freeze({...e.field})});case"computed":return Object.freeze({kind:e.kind,computed:Object.freeze({...e.computed})});case"action":return Object.freeze({kind:e.kind,action:Object.freeze({...e.action})})}}function ir(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return`fnv1a32:${t.toString(16).padStart(8,"0")}`}function ar(e){return Ui.encode(e).length}import{sha256Sync as nt}from"@manifesto-ai/core";function lr(e){return e.kind==="literal"&&e.literalType==="boolean"&&e.value===!0}function Se(e){return C(e)}var rt=class{constructor(t){this.deps=t;this.exprValidator=new Bt(t.mapLocation)}conditionComposer=new Gt;exprValidator;collect(t,n,r,o){return this.collectPatchStatements(t,n,r,o)}collectPatchStatements(t,n,r,o){let i=[];for(let a of t){if(a.kind==="patch"){this.exprValidator.validatePath(a.path,n),a.value&&this.exprValidator.validateExpr(a.value,n),i.push({patch:a,condition:o});continue}if(a.kind==="when"){this.exprValidator.validateExpr(a.condition,n);let s=o;try{s=this.conditionComposer.and(o,this.deps.toMelExpr(a.condition))}catch(f){n.push({severity:"error",code:"E_LOWER",message:f.message,location:this.deps.mapLocation(a.condition.location)})}let c=nt(`${r.actionName}:${r.whenCounter}:when`);r.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=De(l),p=this.collectPatchStatements(a.body,n,r,void 0).map(f=>({patch:f.patch,condition:this.conditionComposer.and(d,f.condition)}));i.push({patch:{kind:"patch",op:"set",path:l,value:{kind:"literal",literalType:"boolean",value:!0,location:a.location},location:a.location},condition:s},...p,{patch:{kind:"patch",op:"unset",path:l,location:a.location}});continue}if(a.kind==="once"){this.exprValidator.validatePath(a.marker,n);let s=o,c=De(a.marker),l=a.marker,d=a.location,p={kind:"call",fn:"neq",args:[c,{kind:"sys",path:["meta","intentId"]}]};if(a.condition){this.exprValidator.validateExpr(a.condition,n);try{p=this.conditionComposer.and(p,this.deps.toMelExpr(a.condition))??p}catch($){n.push({severity:"error",code:"E_LOWER",message:$.message,location:this.deps.mapLocation(a.condition.location)})}}s=this.conditionComposer.and(o,p);let f=nt(`${r.actionName}:${r.onceCounter}:once`);r.onceCounter+=1;let h={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:d},{kind:"propertySegment",name:"__onceScopeGuards",location:d},{kind:"propertySegment",name:f,location:d}],location:d},A=De(h),S=this.collectPatchStatements(a.body,n,r,A);i.push({patch:{kind:"patch",op:"set",path:h,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:A},...S,{patch:{kind:"patch",op:"unset",path:h,location:d},condition:s});continue}if(a.kind==="onceIntent"){let s=nt(`${r.actionName}:${r.onceCounter}:onceIntent`);r.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=De(c),d=nt(`${r.actionName}:${r.onceIntentCounter}:intent`);r.onceIntentCounter+=1;let p=a.location,h={kind:"call",fn:"neq",args:[De({kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:p},{kind:"propertySegment",name:"guards",location:p},{kind:"propertySegment",name:"intent",location:p},{kind:"propertySegment",name:d,location:p}],location:p}),{kind:"sys",path:["meta","intentId"]}]};if(a.condition){this.exprValidator.validateExpr(a.condition,n);try{h=this.conditionComposer.and(h,this.deps.toMelExpr(a.condition))??h}catch(K){n.push({severity:"error",code:"E_LOWER",message:K.message,location:this.deps.mapLocation(a.condition.location)})}}let A=this.conditionComposer.and(o,h),S={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:p},{kind:"propertySegment",name:"guards",location:p},{kind:"propertySegment",name:"intent",location:p}],location:p},$=this.collectPatchStatements(a.body,n,r,l);i.push({patch:{kind:"patch",op:"set",path:c,value:{kind:"literal",literalType:"boolean",value:!0,location:p},location:p},condition:A},{patch:{kind:"patch",op:"merge",path:S,value:{kind:"objectLiteral",properties:[{kind:"objectProperty",key:d,value:{kind:"systemIdent",path:["meta","intentId"],location:p},location:p}],location:p},location:p},condition:l},...$,{patch:{kind:"patch",op:"unset",path:c,location:p},condition:A});continue}n.push({severity:"error",code:"E_UNSUPPORTED_STMT",message:`Unsupported statement '${a.kind}' in patch text. Only patch statements are allowed.`,location:this.deps.mapLocation(a.location)})}return i}};function dr(e){return{op:e.patch.op,path:Yi(e.patch.path),...e.condition?{condition:e.condition}:void 0,...e.patch.value?{value:Se(e.patch.value)}:void 0}}function De(e){let t=e.segments,n;for(let r of t){if(r.kind==="propertySegment"){let o={kind:"prop",name:r.name};n?n={kind:"call",fn:"field",args:[n,{kind:"lit",value:r.name}]}:n={kind:"get",path:[o]};continue}if(!n)throw new Error("Path cannot start with index access in compileMelPatch guard.");n={kind:"call",fn:"at",args:[n,Se(r.index)]}}if(!n)throw new Error("Empty patch guard path.");return n}function Yi(e){return e.segments.map(t=>t.kind==="propertySegment"?{kind:"prop",name:t.name}:{kind:"expr",expr:Se(t.index)})}var Gt=class{and(t,n){return t?n?{kind:"call",fn:"and",args:[t,n]}:t:n}},Bt=class{constructor(t){this.mapLocation=t}symbols={stateTypes:new Map,computedDecls:new Map,typeDefs:new Map,computedTypeCache:new Map,computedTypeInFlight:new Set};validatePath(t,n){for(let r of t.segments)r.kind==="indexSegment"&&this.validateExpr(r.index,n)}validateExpr(t,n){switch(t.kind){case"functionCall":(t.name==="eq"||t.name==="neq")&&t.args.length>=2&&this.validatePrimitiveEquality(t.args[0],t.args[1],t.location,n);for(let r of t.args)this.validateExpr(r,n);if(t.name==="merge")for(let r of t.args)this.validateSpreadOperand(r,r.location,n);return;case"binary":(t.operator==="=="||t.operator==="!=")&&this.validatePrimitiveEquality(t.left,t.right,t.location,n),this.validateExpr(t.left,n),this.validateExpr(t.right,n);return;case"unary":this.validateExpr(t.operand,n);return;case"ternary":this.validateExpr(t.condition,n),this.validateExpr(t.consequent,n),this.validateExpr(t.alternate,n);return;case"propertyAccess":this.validateExpr(t.object,n);return;case"indexAccess":this.validateExpr(t.object,n),this.validateExpr(t.index,n);return;case"objectLiteral":for(let r of t.properties){if(r.kind==="objectProperty"){this.validateExpr(r.value,n);continue}this.validateExpr(r.expr,n),this.validateSpreadOperand(r.expr,r.location,n)}return;case"arrayLiteral":for(let r of t.elements)this.validateExpr(r,n);return;case"literal":case"identifier":case"systemIdent":case"iterationVar":return}}validatePrimitiveEquality(t,n,r,o){let i=B(t,new Map,this.symbols),a=B(n,new Map,this.symbols);i!=="nonprimitive"&&a!=="nonprimitive"||o.push({severity:"error",code:"E_TYPE_MISMATCH",message:"eq/neq operands must be primitive types (null, boolean, number, string)",location:this.mapLocation(r)})}validateSpreadOperand(t,n,r){let o=m(t,new Map,this.symbols),i=G(t,{env:new Map,symbols:this.symbols,inferExprType:m,resolveType:k});!o&&!i||(i?"invalid":o?Ue(o,this.symbols):"unknown")!=="invalid"||r.push({severity:"error",code:"E_TYPE_MISMATCH",message:"Object spread operands must be object-shaped or T | null where T is object-shaped",location:this.mapLocation(n)})}};function ur(e){let t=[],n=0;for(let r of e)t.push(n),n+=r.length+1;return t}function fr(e,t){return n=>mr(n,e,t)}function Ut(e,t,n){return e.map(r=>Qi(r,t,n))}function Qi(e,t,n){return{...e,location:mr(e.location,t,n)}}function mr(e,t,n){return{...e,start:pr(e.start,t,n),end:pr(e.end,t,n)}}function pr(e,t,n){let r=e.line-3,o=t.length,i=Math.min(Math.max(r,1),o),a=n[i-1]??0,s=t[i-1]??"",c=Math.max(s.length+1,1),l=Math.min(Math.max(e.column-6,1),c);return{line:i,column:l,offset:Math.max(a+l-1,0)}}var Oe="__compileMelPatch",Xi="__patchDomain",Zi=" ";function hr(e,t){let n=[],r=[],o=[],i=e.split(`
9
+ `),a=ur(i),s=fr(i,a),c=ea(e,Oe),l=performance.now(),d;try{let x=Le(c);d=x.tokens;let O=Ut(x.diagnostics.filter(ee=>ee.severity==="error"),i,a);if(O.length>0)return o.push(...O),n.push({phase:"lex",durationMs:performance.now()-l,details:{tokenCount:d.length}}),{ops:[],trace:n,warnings:r,errors:o}}catch(x){return o.push({severity:"error",code:"E_LEX",message:x.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:r,errors:o}}n.push({phase:"lex",durationMs:performance.now()-l,details:{tokenCount:d.length}});let p=performance.now(),f;try{let x=Re(d),O=Ut(x.diagnostics,i,a),ee=O.filter(ot=>ot.severity==="error"),F=O.filter(ot=>ot.severity!=="error");if(ee.length>0)return o.push(...ee),r.push(...F),n.push({phase:"parse",durationMs:performance.now()-p}),{ops:[],trace:n,warnings:r,errors:o};if(!x.program)return o.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}}}),r.push(...F),n.push({phase:"parse",durationMs:performance.now()-p}),{ops:[],trace:n,warnings:r,errors:o};f=x.program,r.push(...F)}catch(x){return o.push({severity:"error",code:"E_PARSE",message:x.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"parse",durationMs:performance.now()-p}),{ops:[],trace:n,warnings:r,errors:o}}n.push({phase:"parse",durationMs:performance.now()-p});let h=performance.now(),A={actionName:t.actionName,onceCounter:0,onceIntentCounter:0,whenCounter:0},S=f.domain.members.find(x=>x.kind==="action"&&x.name===Oe);if(!S)return o.push({severity:"error",code:"E_ANALYZE",message:`Synthetic patch action '${Oe}' 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()-h}),{ops:[],trace:n,warnings:r,errors:o};let $=i.length+3+2;if(S.location.end.line!==$)return o.push({severity:"error",code:"E_PATCH_WRAPPER",message:`Malformed synthetic patch wrapper for action '${Oe}'.`,location:s(S.location)}),n.push({phase:"analyze",durationMs:performance.now()-h}),{ops:[],trace:n,warnings:r,errors:o};let[K]=S.body;if(!K||K.kind!=="when"||!lr(K.condition)||S.body.length!==1)return o.push({severity:"error",code:"E_PATCH_WRAPPER",message:`Malformed synthetic patch wrapper for action '${Oe}'.`,location:s(S.location)}),n.push({phase:"analyze",durationMs:performance.now()-h}),{ops:[],trace:n,warnings:r,errors:o};let E=new rt({mapLocation:s,toMelExpr:Se}).collect(K.body,o,A,void 0);if(o.length===0&&e.trim()!==""&&E.length===0&&o.push({severity:"error",code:"E_PATCH_WRAPPER",message:"Patch wrapper parsing produced no patch statements. The patch source may be malformed.",location:s(K.location)}),n.push({phase:"analyze",durationMs:performance.now()-h,details:{count:E.length}}),o.length>0)return{ops:[],trace:n,warnings:r,errors:o};let R=performance.now(),X={mode:"action",allowSysPaths:t.allowSysPaths??{prefixes:["meta","input"]},fnTableVersion:t.fnTableVersion??"1.0",actionName:t.actionName},W=[];for(let x of E)try{let O=dr(x);W.push(We(O,X))}catch(O){O instanceof _?o.push({severity:"error",code:O.code,message:O.message,location:s(x.patch.location)}):O instanceof Error?o.push({severity:"error",code:"E_LOWER",message:O.message,location:s(x.patch.location)}):o.push({severity:"error",code:"E_LOWER",message:"Unknown lowering failure",location:s(x.patch.location)})}return n.push({phase:"lower",durationMs:performance.now()-R,details:{count:W.length}}),o.length>0?{ops:[],trace:n,warnings:r,errors:o}:{ops:W,trace:n,warnings:r,errors:o}}function ea(e,t){let n=e.split(`
10
+ `).map(r=>`${Zi}${r}`).join(`
11
+ `);return[`domain ${Xi} {`,` action ${t}() {`," when true {",n," }"," }","}"].join(`
12
+ `)}var ta="3.5.0";function na(e,t){let n=yr(e,t);return{schema:n.schema,trace:n.trace,warnings:n.warnings,errors:n.errors}}function ra(e,t){let n=yr(e,t);return n.errors.length>0||!n.schema||!n.annotations||!n.sourceMap?{module:null,trace:n.trace,warnings:n.warnings,errors:n.errors}:{module:oa(n.schema,n.annotations,n.sourceMap),trace:n.trace,warnings:n.warnings,errors:n.errors}}function yr(e,t){let n=[],r=[],o=[],i=performance.now(),a;try{let E=Le(e);a=E.tokens;let R=E.diagnostics.filter(W=>W.severity==="error");if(R.length>0)return o.push(...R),n.push({phase:"lex",durationMs:performance.now()-i,details:{tokenCount:a.length}}),{program:null,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:o};let X=E.diagnostics.filter(W=>W.severity==="warning");r.push(...X)}catch(E){let R=E;return o.push({severity:"error",code:"E_LEX",message:R.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"lex",durationMs:performance.now()-i}),{program:null,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:o}}n.push({phase:"lex",durationMs:performance.now()-i,details:{tokenCount:a.length}});let s=performance.now(),c;try{let E=Re(a),R=E.diagnostics.filter(X=>X.severity==="error");if(R.length>0)return o.push(...R),n.push({phase:"parse",durationMs:performance.now()-s}),{program:null,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:ve(o)};c=E.program}catch(E){let R=E;return o.push({severity:"error",code:"E_PARSE",message:R.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"parse",durationMs:performance.now()-s}),{program:null,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:o}}n.push({phase:"parse",durationMs:performance.now()-s});let l=performance.now(),d=Wn(c),p=d.diagnostics.filter(E=>E.severity==="error"),f=d.diagnostics.filter(E=>E.severity==="warning"),h=Xt(d.program),A=An(d.program),S=[...p,...h.diagnostics.filter(E=>E.severity==="error"),...A.diagnostics.filter(E=>E.severity==="error")],$=[...f,...h.diagnostics.filter(E=>E.severity==="warning"),...A.diagnostics.filter(E=>E.severity==="warning")];if(r.push(...$),n.push({phase:"analyze",durationMs:performance.now()-l}),S.length>0)return o.push(...S),{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:ve(o)};let K=performance.now(),se=Ln(d.program);n.push({phase:"generate",durationMs:performance.now()-K});for(let E of se.diagnostics)E.severity==="warning"?r.push(E):o.push(E);if(se.schema){let E=Bn(d.program,se.schema),R=E.diagnostics.filter(F=>F.severity==="warning"),X=E.diagnostics.filter(F=>F.severity==="error");if(r.push(...R),o.push(...X),X.length>0)return{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:ve(o)};let W=sr(ta),x=cr(d.program,e,se.schema,W),O=x.diagnostics.filter(F=>F.severity==="warning"),ee=x.diagnostics.filter(F=>F.severity==="error");return r.push(...O),o.push(...ee),ee.length>0?{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:ve(o)}:{program:d.program,schema:se.schema,annotations:E.annotations,sourceMap:x.sourceMap,trace:n,warnings:r,errors:ve(o)}}return{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:ve(o)}}function oa(e,t,n){return Object.freeze({schema:e,graph:zt(Jn(e)),annotations:t,sourceMap:n})}function zt(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e)){for(let t of e)zt(t);return Object.freeze(e)}for(let t of Object.values(e))zt(t);return Object.freeze(e)}var qt=10;function ve(e){if(e.length<=qt)return e;let t=e.slice(0,qt);return t.push({severity:"error",code:"E_TOO_MANY",message:`... and ${e.length-qt} more error(s). Fix the errors above first.`,location:{start:{line:0,column:0,offset:0},end:{line:0,column:0,offset:0}}}),t}function ia(e,t){return hr(e,t)}export{it as a,gr as b,aa as c,Vt as d,Ht as e,at as f,Kt as g,Wt as h,ca as i,y as j,st as k,Le as l,ga as m,Ea as n,Yt as o,ct as p,Qt as q,ka as r,ba as s,Jt as t,lt as u,Re as v,je as w,dt as x,Xt as y,M as z,Zt as A,Ma as B,Er as C,Da as D,Oa as E,bt as F,An as G,Nt as H,St as I,vt as J,xt as K,Xr as L,_ as M,Ve as N,g as O,He as P,At as Q,Zr as R,wt as S,eo as T,u as U,No as V,xo as W,We as X,Bo as Y,Ln as Z,Bn as _,Wn as $,Jn as aa,sr as ba,cr as ca,na as da,ra as ea,ia as fa};
package/dist/esbuild.js CHANGED
@@ -1 +1 @@
1
- import{a as e}from"./chunk-7BIJ7ZQJ.js";import"./chunk-E4EHOM7R.js";import"./chunk-YIGJ5PGV.js";var t=e.esbuild,n=t;export{n as default,t as melPlugin};
1
+ import{a as e}from"./chunk-MB43CHXV.js";import"./chunk-M3P5RIDR.js";import"./chunk-PEO2YZ2Y.js";var t=e.esbuild,n=t;export{n as default,t as melPlugin};
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{$ as H,A as kt,B as vt,C as bt,D as w,E as Nt,F as Ct,G as z,H as Pt,I as $t,J as At,K as St,L as xt,M as wt,N as Rt,O as Ot,P as Ft,Q as jt,R as Tt,S as Dt,T as S,U as It,V as _t,W as Mt,X as qt,Y as Lt,Z as B,_ as K,a as Xn,aa as Ut,b as Yn,ba as J,c as Qn,ca as X,d as Zn,da as Vt,e as et,ea as Wt,f as nt,fa as Gt,g as tt,h as rt,i as at,j as ot,k as it,l as _,m as st,n as ut,o as ct,p as lt,q as dt,r as pt,s as ft,t as mt,u as gt,v as M,w as yt,x as ht,y as G,z as Et}from"./chunk-YIGJ5PGV.js";var Y={E001:{code:"E001",message:"$system.* cannot be used in computed expressions (non-deterministic)",category:"semantic"},E002:{code:"E002",message:"$system.* cannot be used in state initializers",category:"semantic"},E003:{code:"E003",message:"Invalid $system reference",category:"semantic"},E004:{code:"E004",message:"Identifier starts with reserved prefix '__sys__'",category:"syntax"},E005:{code:"E005",message:"available expression must be pure (no Effects, no $system.*)",category:"semantic"},E006:{code:"E006",message:"fail must be inside a guard (when, once, or onceIntent)",category:"semantic"},E007:{code:"E007",message:"stop must be inside a guard (when, once, or onceIntent)",category:"semantic"},E008:{code:"E008",message:"stop message suggests waiting/pending - use 'Already processed' style instead",category:"semantic"},E009:{code:"E009",message:"Primitive aggregation (sum, min, max) only allowed in computed",category:"semantic"},E010:{code:"E010",message:"Primitive aggregation does not allow composition - use direct reference only",category:"semantic"},E011:{code:"E011",message:"reduce/fold/scan is forbidden - use sum, min, max for aggregation",category:"semantic"},E013:{code:"E013",message:"Circular include detected",category:"semantic"},E014:{code:"E014",message:"Include expansion depth exceeds limit",category:"semantic"},E015:{code:"E015",message:"Include target is not a declared flow",category:"semantic"},E016:{code:"E016",message:"Include not allowed in InnerStmt position",category:"semantic"},E017:{code:"E017",message:"once() not allowed in flow",category:"semantic"},E018:{code:"E018",message:"onceIntent not allowed in flow",category:"semantic"},E019:{code:"E019",message:"patch not allowed in flow",category:"semantic"},E020:{code:"E020",message:"effect not allowed in flow",category:"semantic"},E021:{code:"E021",message:"Flow parameter name conflicts with top-level identifier",category:"semantic"},E022:{code:"E022",message:"Flow and action share the same name",category:"semantic"},E023:{code:"E023",message:"Wrong number of arguments for included flow",category:"semantic"},E024:{code:"E024",message:"Include argument type mismatch",category:"type"},E030:{code:"E030",message:"Collection element type does not have an 'id' field",category:"type"},E030a:{code:"E030a",message:"Collection element 'id' field is not a primitive type",category:"type"},E030b:{code:"E030b",message:"Duplicate '.id' values detected in state initializer",category:"type"},E031:{code:"E031",message:"updateById/removeById not allowed in this context",category:"semantic"},E032:{code:"E032",message:"Nested transform primitive",category:"semantic"},E033:{code:"E033",message:"Transform primitive collection argument is not a state path",category:"semantic"},E034:{code:"E034",message:"Transform primitive in guard condition",category:"semantic"},E035:{code:"E035",message:"Transform primitive in available condition",category:"semantic"},E040:{code:"E040",message:"Circular computed dependency",category:"semantic"},E041:{code:"E041",message:"Computed references undeclared identifier",category:"semantic"},E042:{code:"E042",message:"State initializer references non-constant value",category:"semantic"},E043:{code:"E043",message:"Non-trivial union type cannot be lowered to FieldSpec",category:"type"},E044:{code:"E044",message:"Recursive named type cannot be lowered to FieldSpec",category:"type"},E045:{code:"E045",message:"Nullable type cannot be lowered to FieldSpec",category:"type"},E046:{code:"E046",message:"Record type cannot be lowered to FieldSpec",category:"type"},E047:{code:"E047",message:"dispatchable expression must be pure (state/computed/action parameters only)",category:"semantic"},E048:{code:"E048",message:"Transform primitive in dispatchable condition",category:"semantic"},E049:{code:"E049",message:"Invalid literal clamp bounds",category:"semantic"},E050:{code:"E050",message:"Invalid match() form",category:"semantic"},E051:{code:"E051",message:"Duplicate match() key",category:"semantic"},E052:{code:"E052",message:"Invalid argmax()/argmin() form",category:"semantic"},E053:{code:"E053",message:"@meta can attach only to domain, type, type field, state field, computed, or action declarations",category:"syntax"},E054:{code:"E054",message:"Action-parameter annotations are not part of the current MEL syntax",category:"syntax"},E055:{code:"E055",message:"Annotation payloads must be JSON-like literals",category:"semantic"},E056:{code:"E056",message:"Annotation payload nesting exceeds the current MEL limit of 2 levels",category:"semantic"},E057:{code:"E057",message:"Annotation target does not map to the emitted DomainSchema",category:"semantic"},E_UNDEFINED:{code:"E_UNDEFINED",message:"Undefined identifier",category:"semantic"},E_DUPLICATE:{code:"E_DUPLICATE",message:"Duplicate identifier",category:"semantic"},E_INVALID_ACCESS:{code:"E_INVALID_ACCESS",message:"Invalid access to identifier in this context",category:"semantic"},E_UNGUARDED_STMT:{code:"E_UNGUARDED_STMT",message:"Statement must be inside a guard (when or once)",category:"semantic"},E_UNGUARDED_PATCH:{code:"E_UNGUARDED_PATCH",message:"Patch must be inside a guard",category:"semantic"},E_UNGUARDED_EFFECT:{code:"E_UNGUARDED_EFFECT",message:"Effect must be inside a guard",category:"semantic"},E_ARG_COUNT:{code:"E_ARG_COUNT",message:"Wrong number of arguments",category:"type"},E_TYPE_MISMATCH:{code:"E_TYPE_MISMATCH",message:"Type mismatch",category:"type"},W_NON_BOOL_COND:{code:"W_NON_BOOL_COND",message:"Condition may not be boolean",category:"semantic"},W_UNUSED:{code:"W_UNUSED",message:"Unused identifier",category:"semantic"},W012:{code:"W012",message:"Anonymous object type in state field - use named type declaration instead",category:"type"},MEL_LEXER:{code:"MEL_LEXER",message:"Lexer error",category:"syntax"},MEL_PARSER:{code:"MEL_PARSER",message:"Parser error",category:"syntax"}};function Ht(e){return Y[e]}function Jt(e){let n=Y[e];return n?`${e}: ${n.message}`:e}function Q(e,n){let{code:t,message:r,location:a}=e;if(!a||a.start.line===0&&a.start.column===0)return`[${t}] ${r}`;let{line:o,column:s}=a.start,l=`[${t}] ${r} (${o}:${s})`;if(!n)return l;let y=n.split(`
1
+ import{$ as H,A as kt,B as vt,C as bt,D as w,E as Nt,F as Ct,G as z,H as Pt,I as $t,J as At,K as St,L as xt,M as wt,N as Rt,O as Ot,P as Ft,Q as jt,R as Tt,S as Dt,T as S,U as It,V as _t,W as Mt,X as qt,Y as Lt,Z as B,_ as K,a as Xn,aa as Ut,b as Yn,ba as J,c as Qn,ca as X,d as Zn,da as Vt,e as et,ea as Wt,f as nt,fa as Gt,g as tt,h as rt,i as at,j as ot,k as it,l as _,m as st,n as ut,o as ct,p as lt,q as dt,r as pt,s as ft,t as mt,u as gt,v as M,w as yt,x as ht,y as G,z as Et}from"./chunk-PEO2YZ2Y.js";var Y={E001:{code:"E001",message:"$system.* cannot be used in computed expressions (non-deterministic)",category:"semantic"},E002:{code:"E002",message:"$system.* cannot be used in state initializers",category:"semantic"},E003:{code:"E003",message:"Invalid $system reference",category:"semantic"},E004:{code:"E004",message:"Identifier starts with reserved prefix '__sys__'",category:"syntax"},E005:{code:"E005",message:"available expression must be pure (no Effects, no $system.*)",category:"semantic"},E006:{code:"E006",message:"fail must be inside a guard (when, once, or onceIntent)",category:"semantic"},E007:{code:"E007",message:"stop must be inside a guard (when, once, or onceIntent)",category:"semantic"},E008:{code:"E008",message:"stop message suggests waiting/pending - use 'Already processed' style instead",category:"semantic"},E009:{code:"E009",message:"Primitive aggregation (sum, min, max) only allowed in computed",category:"semantic"},E010:{code:"E010",message:"Primitive aggregation does not allow composition - use direct reference only",category:"semantic"},E011:{code:"E011",message:"reduce/fold/scan is forbidden - use sum, min, max for aggregation",category:"semantic"},E013:{code:"E013",message:"Circular include detected",category:"semantic"},E014:{code:"E014",message:"Include expansion depth exceeds limit",category:"semantic"},E015:{code:"E015",message:"Include target is not a declared flow",category:"semantic"},E016:{code:"E016",message:"Include not allowed in InnerStmt position",category:"semantic"},E017:{code:"E017",message:"once() not allowed in flow",category:"semantic"},E018:{code:"E018",message:"onceIntent not allowed in flow",category:"semantic"},E019:{code:"E019",message:"patch not allowed in flow",category:"semantic"},E020:{code:"E020",message:"effect not allowed in flow",category:"semantic"},E021:{code:"E021",message:"Flow parameter name conflicts with top-level identifier",category:"semantic"},E022:{code:"E022",message:"Flow and action share the same name",category:"semantic"},E023:{code:"E023",message:"Wrong number of arguments for included flow",category:"semantic"},E024:{code:"E024",message:"Include argument type mismatch",category:"type"},E030:{code:"E030",message:"Collection element type does not have an 'id' field",category:"type"},E030a:{code:"E030a",message:"Collection element 'id' field is not a primitive type",category:"type"},E030b:{code:"E030b",message:"Duplicate '.id' values detected in state initializer",category:"type"},E031:{code:"E031",message:"updateById/removeById not allowed in this context",category:"semantic"},E032:{code:"E032",message:"Nested transform primitive",category:"semantic"},E033:{code:"E033",message:"Transform primitive collection argument is not a state path",category:"semantic"},E034:{code:"E034",message:"Transform primitive in guard condition",category:"semantic"},E035:{code:"E035",message:"Transform primitive in available condition",category:"semantic"},E040:{code:"E040",message:"Circular computed dependency",category:"semantic"},E041:{code:"E041",message:"Computed references undeclared identifier",category:"semantic"},E042:{code:"E042",message:"State initializer references non-constant value",category:"semantic"},E043:{code:"E043",message:"Non-trivial union type cannot be lowered to FieldSpec",category:"type"},E044:{code:"E044",message:"Recursive named type cannot be lowered to FieldSpec",category:"type"},E045:{code:"E045",message:"Nullable type cannot be lowered to FieldSpec",category:"type"},E046:{code:"E046",message:"Record type cannot be lowered to FieldSpec",category:"type"},E047:{code:"E047",message:"dispatchable expression must be pure (state/computed/action parameters only)",category:"semantic"},E048:{code:"E048",message:"Transform primitive in dispatchable condition",category:"semantic"},E049:{code:"E049",message:"Invalid literal clamp bounds",category:"semantic"},E050:{code:"E050",message:"Invalid match() form",category:"semantic"},E051:{code:"E051",message:"Duplicate match() key",category:"semantic"},E052:{code:"E052",message:"Invalid argmax()/argmin() form",category:"semantic"},E053:{code:"E053",message:"@meta can attach only to domain, type, type field, state field, computed, or action declarations",category:"syntax"},E054:{code:"E054",message:"Action-parameter annotations are not part of the current MEL syntax",category:"syntax"},E055:{code:"E055",message:"Annotation payloads must be JSON-like literals",category:"semantic"},E056:{code:"E056",message:"Annotation payload nesting exceeds the current MEL limit of 2 levels",category:"semantic"},E057:{code:"E057",message:"Annotation target does not map to the emitted DomainSchema",category:"semantic"},E_UNDEFINED:{code:"E_UNDEFINED",message:"Undefined identifier",category:"semantic"},E_DUPLICATE:{code:"E_DUPLICATE",message:"Duplicate identifier",category:"semantic"},E_INVALID_ACCESS:{code:"E_INVALID_ACCESS",message:"Invalid access to identifier in this context",category:"semantic"},E_UNGUARDED_STMT:{code:"E_UNGUARDED_STMT",message:"Statement must be inside a guard (when or once)",category:"semantic"},E_UNGUARDED_PATCH:{code:"E_UNGUARDED_PATCH",message:"Patch must be inside a guard",category:"semantic"},E_UNGUARDED_EFFECT:{code:"E_UNGUARDED_EFFECT",message:"Effect must be inside a guard",category:"semantic"},E_ARG_COUNT:{code:"E_ARG_COUNT",message:"Wrong number of arguments",category:"type"},E_TYPE_MISMATCH:{code:"E_TYPE_MISMATCH",message:"Type mismatch",category:"type"},W_NON_BOOL_COND:{code:"W_NON_BOOL_COND",message:"Condition may not be boolean",category:"semantic"},W_UNUSED:{code:"W_UNUSED",message:"Unused identifier",category:"semantic"},W012:{code:"W012",message:"Anonymous object type in state field - use named type declaration instead",category:"type"},MEL_LEXER:{code:"MEL_LEXER",message:"Lexer error",category:"syntax"},MEL_PARSER:{code:"MEL_PARSER",message:"Parser error",category:"syntax"}};function Ht(e){return Y[e]}function Jt(e){let n=Y[e];return n?`${e}: ${n.message}`:e}function Q(e,n){let{code:t,message:r,location:a}=e;if(!a||a.start.line===0&&a.start.column===0)return`[${t}] ${r}`;let{line:o,column:s}=a.start,l=`[${t}] ${r} (${o}:${s})`;if(!n)return l;let y=n.split(`
2
2
  `)[o-1];if(!y)return l;let h=String(o).padStart(4," "),f=`${h} | ${y}`,p=Math.max(1,a.end.line===a.start.line?Math.min(a.end.column-s,y.length-s+1):1),E=`${" ".repeat(h.length+3+s-1)}${"^".repeat(p)}`;return`${l}
3
3
  ${f}
4
4
  ${E}`}function me(e,n){return e.map(t=>Q(t,n)).join(`
@@ -6,7 +6,7 @@ import type { SourceLocation } from "./source-location.js";
6
6
  /**
7
7
  * All token kinds in MEL
8
8
  */
9
- export type TokenKind = "DOMAIN" | "STATE" | "COMPUTED" | "ACTION" | "EFFECT" | "WHEN" | "ONCE" | "PATCH" | "UNSET" | "MERGE" | "TRUE" | "FALSE" | "NULL" | "AS" | "AVAILABLE" | "DISPATCHABLE" | "FAIL" | "STOP" | "WITH" | "TYPE" | "IMPORT" | "FROM" | "EXPORT" | "PLUS" | "MINUS" | "STAR" | "SLASH" | "PERCENT" | "EQ_EQ" | "BANG_EQ" | "LT" | "LT_EQ" | "GT" | "GT_EQ" | "AMP_AMP" | "PIPE_PIPE" | "BANG" | "QUESTION_QUESTION" | "QUESTION" | "COLON" | "EQ" | "AT" | "LPAREN" | "RPAREN" | "LBRACE" | "RBRACE" | "LBRACKET" | "RBRACKET" | "COMMA" | "SEMICOLON" | "DOT" | "PIPE" | "NUMBER" | "STRING" | "IDENTIFIER" | "SYSTEM_IDENT" | "ITEM" | "EOF" | "ERROR";
9
+ export type TokenKind = "DOMAIN" | "STATE" | "COMPUTED" | "ACTION" | "EFFECT" | "WHEN" | "ONCE" | "PATCH" | "UNSET" | "MERGE" | "TRUE" | "FALSE" | "NULL" | "AS" | "AVAILABLE" | "DISPATCHABLE" | "FAIL" | "STOP" | "WITH" | "TYPE" | "IMPORT" | "FROM" | "EXPORT" | "PLUS" | "MINUS" | "STAR" | "SLASH" | "PERCENT" | "EQ_EQ" | "BANG_EQ" | "LT" | "LT_EQ" | "GT" | "GT_EQ" | "AMP_AMP" | "PIPE_PIPE" | "BANG" | "QUESTION_QUESTION" | "QUESTION" | "COLON" | "EQ" | "AT" | "LPAREN" | "RPAREN" | "LBRACE" | "RBRACE" | "LBRACKET" | "RBRACKET" | "COMMA" | "SEMICOLON" | "DOT" | "ELLIPSIS" | "PIPE" | "NUMBER" | "STRING" | "IDENTIFIER" | "SYSTEM_IDENT" | "ITEM" | "EOF" | "ERROR";
10
10
  /**
11
11
  * A token produced by the lexer
12
12
  */
@@ -1 +1 @@
1
- import{c as n}from"./chunk-E4EHOM7R.js";import"./chunk-YIGJ5PGV.js";import{readFile as i}from"fs/promises";import{fileURLToPath as c}from"url";function u(o){let[t]=o.split("?",1),[r]=t.split("#",1);return r}function s(o){return u(o).endsWith(".mel")}function a(o){try{return c(o)}catch{return o}}var h=async(o,t,r)=>s(o)?{...await r(o,t),shortCircuit:!0}:r(o,t),p=async(o,t,r)=>{if(!s(o))return r(o,t);let e=await i(new URL(o),"utf8");return{format:"module",source:n(e,a(o)),shortCircuit:!0}};export{p as load,h as resolve};
1
+ import{c as n}from"./chunk-M3P5RIDR.js";import"./chunk-PEO2YZ2Y.js";import{readFile as i}from"fs/promises";import{fileURLToPath as c}from"url";function u(o){let[t]=o.split("?",1),[r]=t.split("#",1);return r}function s(o){return u(o).endsWith(".mel")}function a(o){try{return c(o)}catch{return o}}var h=async(o,t,r)=>s(o)?{...await r(o,t),shortCircuit:!0}:r(o,t),p=async(o,t,r)=>{if(!s(o))return r(o,t);let e=await i(new URL(o),"utf8");return{format:"module",source:n(e,a(o)),shortCircuit:!0}};export{p as load,h as resolve};
@@ -344,13 +344,18 @@ export interface TernaryExprNode extends ASTNode {
344
344
  */
345
345
  export interface ObjectLiteralExprNode extends ASTNode {
346
346
  kind: "objectLiteral";
347
- properties: ObjectPropertyNode[];
347
+ properties: ObjectLiteralEntryNode[];
348
348
  }
349
+ export type ObjectLiteralEntryNode = ObjectPropertyNode | ObjectSpreadNode;
349
350
  export interface ObjectPropertyNode extends ASTNode {
350
351
  kind: "objectProperty";
351
352
  key: string;
352
353
  value: ExprNode;
353
354
  }
355
+ export interface ObjectSpreadNode extends ASTNode {
356
+ kind: "objectSpread";
357
+ expr: ExprNode;
358
+ }
354
359
  /**
355
360
  * Array literal expression ([1, 2, 3])
356
361
  */
package/dist/rollup.js CHANGED
@@ -1 +1 @@
1
- import{a as e}from"./chunk-7BIJ7ZQJ.js";import"./chunk-E4EHOM7R.js";import"./chunk-YIGJ5PGV.js";var l=e.rollup,t=l;export{t as default,l as melPlugin};
1
+ import{a as e}from"./chunk-MB43CHXV.js";import"./chunk-M3P5RIDR.js";import"./chunk-PEO2YZ2Y.js";var l=e.rollup,t=l;export{t as default,l as melPlugin};
package/dist/rspack.js CHANGED
@@ -1 +1 @@
1
- import{a as e}from"./chunk-7BIJ7ZQJ.js";import"./chunk-E4EHOM7R.js";import"./chunk-YIGJ5PGV.js";var t=e.rspack,o=t;export{o as default,t as melPlugin};
1
+ import{a as e}from"./chunk-MB43CHXV.js";import"./chunk-M3P5RIDR.js";import"./chunk-PEO2YZ2Y.js";var t=e.rspack,o=t;export{o as default,t as melPlugin};
package/dist/vite.js CHANGED
@@ -1 +1 @@
1
- import{a as e}from"./chunk-7BIJ7ZQJ.js";import"./chunk-E4EHOM7R.js";import"./chunk-YIGJ5PGV.js";var t=e.vite,o=t;export{o as default,t as melPlugin};
1
+ import{a as e}from"./chunk-MB43CHXV.js";import"./chunk-M3P5RIDR.js";import"./chunk-PEO2YZ2Y.js";var t=e.vite,o=t;export{o as default,t as melPlugin};
package/dist/webpack.js CHANGED
@@ -1 +1 @@
1
- import{a as e}from"./chunk-7BIJ7ZQJ.js";import"./chunk-E4EHOM7R.js";import"./chunk-YIGJ5PGV.js";var t=e.webpack,o=t;export{o as default,t as melPlugin};
1
+ import{a as e}from"./chunk-MB43CHXV.js";import"./chunk-M3P5RIDR.js";import"./chunk-PEO2YZ2Y.js";var t=e.webpack,o=t;export{o as default,t as melPlugin};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@manifesto-ai/compiler",
3
- "version": "3.7.0",
3
+ "version": "3.8.0",
4
4
  "description": "Manifesto Compiler - MEL (Manifesto Expression Language) to DomainSchema compiler",
5
5
  "author": "eggplantiny <eggplantiny@gmail.com>",
6
6
  "license": "MIT",
@@ -61,7 +61,7 @@
61
61
  },
62
62
  "peerDependencies": {
63
63
  "@anthropic-ai/sdk": "^0.26.0",
64
- "@manifesto-ai/core": "^2.12.0",
64
+ "@manifesto-ai/core": "^2.13.0",
65
65
  "openai": "^4.0.0",
66
66
  "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0",
67
67
  "zod": "^4.3.6"
@@ -97,7 +97,7 @@
97
97
  "vitest": "^4.1.2",
98
98
  "webpack": "^5.106.1",
99
99
  "zod": "^4.3.6",
100
- "@manifesto-ai/core": "2.12.0"
100
+ "@manifesto-ai/core": "2.13.0"
101
101
  },
102
102
  "files": [
103
103
  "dist"
@@ -1,12 +0,0 @@
1
- var Ye={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"},jn=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 mi(t){return t in Ye}function wt(t){return jn.has(t)}function Ct(t){return Object.hasOwn(Ye,t)?Ye[t]:void 0}function Qe(t,e,n,o){return{kind:t,lexeme:e,location:n,value:o}}function Pt(t,e,n){return{line:t,column:e,offset:n}}function It(t,e,n){return{start:t,end:e,source:n}}function hi(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 Xe=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("AT");break;case"=":this.addToken(this.match("=")?"EQ_EQ":"EQ");break;case"!":this.addToken(this.match("=")?"BANG_EQ":"BANG");break;case"<":this.addToken(this.match("=")?"LT_EQ":"LT");break;case">":this.addToken(this.match("=")?"GT_EQ":"GT");break;case"&":this.match("&")?this.addToken("AMP_AMP"):this.error("Expected '&&' for logical AND");break;case"|":this.match("|")?this.addToken("PIPE_PIPE"):this.addToken("PIPE");break;case"?":this.addToken(this.match("?")?"QUESTION_QUESTION":"QUESTION");break;case"/":this.match("/")?this.lineComment():this.match("*")?this.blockComment():this.addToken("SLASH");break;case" ":case"\r":case" ":break;case`
2
- `:this.newline();break;case'"':this.string('"');break;case"'":this.string("'");break;case"$":this.systemIdentifier();break;default:this.isDigit(e)?this.number():this.isAlpha(e)?this.identifier():this.error(`Unexpected character '${e}'`)}}lineComment(){for(;this.peek()!==`
3
- `&&!this.isAtEnd();)this.advance()}blockComment(){let e=this.line,n=this.column-2;for(;!this.isAtEnd();){if(this.peek()==="*"&&this.peekNext()==="/"){this.advance(),this.advance();return}this.peek()===`
4
- `&&this.newline(),this.advance()}this.error(`Unterminated block comment starting at line ${e}:${n}`)}string(e){let n=this.line,o=this.column-1,r="";for(;this.peek()!==e&&!this.isAtEnd();){if(this.peek()===`
5
- `){this.error("Unterminated string literal");return}if(this.peek()==="\\"){this.advance();let i=this.advance();switch(i){case"n":r+=`
6
- `;break;case"r":r+="\r";break;case"t":r+=" ";break;case"\\":r+="\\";break;case"'":r+="'";break;case'"':r+='"';break;case"0":r+="\0";break;default:this.error(`Invalid escape sequence '\\${i}'`),r+=i}}else r+=this.advance()}if(this.isAtEnd()){this.error(`Unterminated string starting at line ${n}:${o}`);return}this.advance(),this.addToken("STRING",r)}number(){if(this.source[this.start]==="0"&&(this.peek()==="x"||this.peek()==="X")){for(this.advance();this.isHexDigit(this.peek());)this.advance();let n=this.source.slice(this.start+2,this.current),o=parseInt(n,16);this.addToken("NUMBER",o);return}for(;this.isDigit(this.peek());)this.advance();if(this.peek()==="."&&this.isDigit(this.peekNext()))for(this.advance();this.isDigit(this.peek());)this.advance();if(this.peek()==="e"||this.peek()==="E"){if(this.advance(),(this.peek()==="+"||this.peek()==="-")&&this.advance(),!this.isDigit(this.peek())){this.error("Invalid number: expected digits after exponent");return}for(;this.isDigit(this.peek());)this.advance()}let e=parseFloat(this.source.slice(this.start,this.current));this.addToken("NUMBER",e)}identifier(){for(;this.isAlphaNumeric(this.peek());){if(this.peek()==="$"){this.advance(),this.error("'$' is forbidden in identifiers (MEL A17)","E004");continue}this.advance()}let e=this.source.slice(this.start,this.current);if(e.startsWith("__sys__")){this.error("'__sys__' prefix is reserved for compiler-generated identifiers (MEL A26)","E004"),this.addToken("ERROR");return}if(wt(e)){this.error(`'${e}' is a reserved keyword and cannot be used`),this.addToken("ERROR");return}let n=Ct(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 It(e,n,this.sourcePath)}positionAt(e){let n=1,o=0;for(let r=0;r<e;r++)this.source[r]===`
7
- `&&(n++,o=r+1);return Pt(n,e-o+1,e)}addToken(e,n){let o=this.source.slice(this.start,this.current);this.tokens.push(Qe(e,o,this.currentLocation(),n))}error(e,n="MEL_LEXER"){let o=this.currentLocation();this.diagnostics.push({severity:"error",code:n,message:e,location:o,source:this.getSourceLine(o.start.line)})}getSourceLine(e){return this.source.split(`
8
- `)[e-1]??""}};function Ae(t,e){return new Xe(t,e).tokenize()}function xi(t){return["literal","identifier","systemIdent","iterationVar","propertyAccess","indexAccess","functionCall","unary","binary","ternary","objectLiteral","arrayLiteral"].includes(t.kind)}function vi(t){return["when","once","onceIntent","patch","effect","fail","stop"].includes(t.kind)}var Mt=(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))(Mt||{});function Je(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 Dt(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 wi(t){return Je(t)!==0}function Ci(t){return t==="BANG"||t==="MINUS"}function Rt(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 o=this.parseAnnotationList();o.length>0&&!this.check("DOMAIN")&&this.reportUnsupportedAnnotations(o);let r=this.parseDomain(o);return{kind:"program",imports:n,domain:r,location:h(e,r.location)}}parseImport(){let e=this.consume("IMPORT","Expected 'import'").location;this.consume("LBRACE","Expected '{' after 'import'");let n=[];do n.push(this.consume("IDENTIFIER","Expected identifier").lexeme);while(this.match("COMMA"));this.consume("RBRACE","Expected '}' after import names"),this.consume("FROM","Expected 'from' after import names");let o=this.consume("STRING","Expected string after 'from'");return{kind:"import",names:n,from:o.value,location:h(e,o.location)}}parseDomain(e=[]){let n=this.consume("DOMAIN","Expected 'domain'").location,o=this.consume("IDENTIFIER","Expected domain name").lexeme;this.consume("LBRACE","Expected '{' after domain name");let r=[],i=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let s=this.parseAnnotationList();if(s.length>0&&(this.check("RBRACE")||this.isAtEnd())){this.reportUnsupportedAnnotations(s);continue}if(this.check("TYPE"))r.push(this.parseTypeDecl(s));else{let c=this.parseDomainMember(s);c&&i.push(c)}}let a=this.consume("RBRACE","Expected '}' to close domain").location;return{kind:"domain",name:o,annotations:e.length>0?e:void 0,types:r,members:i,location:h(n,a)}}parseTypeDecl(e=[]){let n=this.consume("TYPE","Expected 'type'").location,o=this.consume("IDENTIFIER","Expected type name").lexeme;this.consume("EQ","Expected '=' after type name");let r=this.parseTypeExpr();return{kind:"typeDecl",name:o,annotations:e.length>0?e:void 0,typeExpr:r,location:h(n,r.location)}}parseDomainMember(e=[]){return this.check("STATE")?(this.reportUnsupportedAnnotations(e),this.parseState()):this.check("COMPUTED")?this.parseComputed(e):this.check("ACTION")?this.parseAction(e):this.isFlowDeclContext()?(this.reportUnsupportedAnnotations(e),this.parseFlowDecl()):(this.reportUnsupportedAnnotations(e),this.error(`Unexpected token '${this.peek().lexeme}'. Expected 'state', 'computed', 'action', or 'flow'.`),this.advance(),null)}parseState(){let e=this.consume("STATE","Expected 'state'").location;this.consume("LBRACE","Expected '{' after 'state'");let n=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let r=this.parseAnnotationList();if(r.length>0&&(this.check("RBRACE")||this.isAtEnd())){this.reportUnsupportedAnnotations(r);continue}n.push(this.parseStateField(r))}let o=this.consume("RBRACE","Expected '}' to close state block").location;return{kind:"state",fields:n,location:h(e,o)}}parseStateField(e=[]){let n=this.consume("IDENTIFIER","Expected field name");this.consume("COLON","Expected ':' after field name");let o=this.parseTypeExpr(),r;return this.match("EQ")&&(r=this.parseExpression()),{kind:"stateField",name:n.lexeme,annotations:e.length>0?e:void 0,typeExpr:o,initializer:r,location:h(n.location,r?.location??o.location)}}parseComputed(e=[]){let n=this.consume("COMPUTED","Expected 'computed'").location,o=this.consume("IDENTIFIER","Expected computed name").lexeme;this.consume("EQ","Expected '=' after computed name");let r=this.parseExpression();return{kind:"computed",name:o,annotations:e.length>0?e:void 0,expression:r,location:h(n,r.location)}}parseAction(e=[]){let n=this.consume("ACTION","Expected 'action'").location,o=this.consume("IDENTIFIER","Expected action name").lexeme;this.consume("LPAREN","Expected '(' after action name");let r=[];if(!this.check("RPAREN"))do{let l=this.parseAnnotationList();if(l.length>0&&(this.check("RPAREN")||this.isAtEnd())){this.reportUnsupportedAnnotations(l);break}r.push(this.parseParam(l))}while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after parameters");let i;this.match("AVAILABLE")&&(this.consume("WHEN","Expected 'when' after 'available'"),i=this.parseExpression());let a;if(this.match("DISPATCHABLE")&&(this.consume("WHEN","Expected 'when' after 'dispatchable'"),a=this.parseExpression()),this.check("AVAILABLE")){let l=a?"'available when' must appear before 'dispatchable when' in an action":"Action can declare 'available when' at most once";throw this.errorAtCurrent(l)}if(this.check("DISPATCHABLE"))throw this.errorAtCurrent("Action can declare 'dispatchable when' at most once");this.consume("LBRACE","Expected '{' to start action body");let s=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let l=this.parseGuardedStmt();l&&s.push(l)}let c=this.consume("RBRACE","Expected '}' to close action").location;return{kind:"action",name:o,annotations:e.length>0?e:void 0,params:r,available:i,dispatchable:a,body:s,location:h(n,c)}}parseFlowDecl(){let e=this.consume("IDENTIFIER","Expected 'flow'"),n=this.consume("IDENTIFIER","Expected flow name").lexeme;this.consume("LPAREN","Expected '(' after flow name");let o=[];if(!this.check("RPAREN"))do{let a=this.parseAnnotationList();if(this.reportUnsupportedAnnotations(a),a.length>0&&(this.check("RPAREN")||this.isAtEnd()))break;o.push(this.parseParam(a))}while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after parameters"),this.consume("LBRACE","Expected '{' to start flow body");let r=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let a=this.parseFlowStmt();a&&r.push(a)}let i=this.consume("RBRACE","Expected '}' to close flow").location;return{kind:"flow",name:n,params:o,body:r,location:h(e.location,i)}}parseParam(e=[]){let n=this.consume("IDENTIFIER","Expected parameter name");this.consume("COLON","Expected ':' after parameter name");let o=this.parseTypeExpr();return{kind:"param",name:n.lexeme,annotations:e.length>0?e:void 0,typeExpr:o,location:h(n.location,o.location)}}parseGuardedStmt(){let e=this.parseAnnotationList();if(this.reportUnsupportedAnnotations(e),this.check("WHEN"))return this.parseWhenStmt();if(this.check("ONCE"))return this.parseOnceStmt();if(this.isOnceIntentContext())return this.parseOnceIntentStmt();if(this.isIncludeContext())return this.parseIncludeStmt();if(this.check("FAIL"))return this.parseFailStmt();if(this.check("STOP"))return this.parseStopStmt();let n=this.peek();return n.kind==="PATCH"||n.lexeme==="patch"||n.kind==="EFFECT"||n.lexeme==="effect"?(this.error(`'${n.lexeme}' must be inside a guard block (when, once, or onceIntent). Wrap it: when true { ${n.lexeme} ... }`),this.skipToRecoveryPoint(),null):(this.error(`Unexpected token '${n.lexeme}'. Expected 'when', 'once', 'onceIntent', 'include', 'fail', or 'stop'.`),this.advance(),null)}parseFlowStmt(){let e=this.parseAnnotationList();return this.reportUnsupportedAnnotations(e),this.check("WHEN")?this.parseWhenStmt():this.isIncludeContext()?this.parseIncludeStmt():this.check("ONCE")?this.parseOnceStmt():this.isOnceIntentContext()?this.parseOnceIntentStmt():this.check("PATCH")?this.parsePatchStmt():this.check("EFFECT")?this.parseEffectStmt():(this.error(`Unexpected token '${this.peek().lexeme}'. Expected 'when', 'include', 'once', 'onceIntent', 'patch', or 'effect'.`),this.advance(),null)}skipToRecoveryPoint(){let e=0;for(;!this.isAtEnd();){let n=this.peek();if(n.kind==="LBRACE"){e++,this.advance();continue}if(n.kind==="RBRACE"){if(e===0)return;e--,this.advance();continue}if(e===0&&(n.kind==="WHEN"||n.kind==="ONCE"||n.lexeme==="onceIntent"||this.isIncludeContext()||n.kind==="FAIL"||n.kind==="STOP"))return;this.advance()}}parseWhenStmt(){let e=this.consume("WHEN","Expected 'when'").location,n=this.parseExpression();this.consume("LBRACE","Expected '{' after when condition");let o=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let i=this.parseInnerStmt();i&&o.push(i)}let r=this.consume("RBRACE","Expected '}' to close when block").location;return{kind:"when",condition:n,body:o,location:h(e,r)}}parseOnceStmt(){let e=this.consume("ONCE","Expected 'once'").location;this.consume("LPAREN","Expected '(' after 'once'");let n=this.parsePath();this.consume("RPAREN","Expected ')' after marker");let o;this.match("WHEN")&&(o=this.parseExpression()),this.consume("LBRACE","Expected '{' to start once block");let r=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let a=this.parseInnerStmt();a&&r.push(a)}let i=this.consume("RBRACE","Expected '}' to close once block").location;return{kind:"once",marker:n,condition:o,body:r,location:h(e,i)}}parseOnceIntentStmt(){let e=this.consume("IDENTIFIER","Expected 'onceIntent'"),n;this.match("WHEN")&&(n=this.parseExpression()),this.consume("LBRACE","Expected '{' to start onceIntent block");let o=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let i=this.parseInnerStmt();i&&o.push(i)}let r=this.consume("RBRACE","Expected '}' to close onceIntent block").location;return{kind:"onceIntent",condition:n,body:o,location:h(e.location,r)}}parseInnerStmt(){let e=this.parseAnnotationList();return this.reportUnsupportedAnnotations(e),this.check("PATCH")?this.parsePatchStmt():this.check("EFFECT")?this.parseEffectStmt():this.check("WHEN")?this.parseWhenStmt():this.check("ONCE")?this.parseOnceStmt():this.isOnceIntentContext()?this.parseOnceIntentStmt():this.isIncludeContext()?this.parseIncludeStmt():this.check("FAIL")?this.parseFailStmt():this.check("STOP")?this.parseStopStmt():(this.error(`Unexpected token '${this.peek().lexeme}'. Expected 'patch', 'effect', 'when', 'once', 'onceIntent', 'include', 'fail', or 'stop'.`),this.advance(),null)}parseIncludeStmt(){let e=this.consume("IDENTIFIER","Expected 'include'"),n=this.consume("IDENTIFIER","Expected flow name after 'include'");this.consume("LPAREN","Expected '(' after flow name");let o=[];if(!this.check("RPAREN"))do o.push(this.parseExpression());while(this.match("COMMA"));let r=this.consume("RPAREN","Expected ')' after include arguments").location;return{kind:"include",flowName:n.lexeme,args:o,location:h(e.location,r)}}parsePatchStmt(){let e=this.consume("PATCH","Expected 'patch'").location,n=this.parsePath(),o,r,i;return this.match("UNSET")?(o="unset",i=this.previous().location):this.match("MERGE")?(o="merge",r=this.parseExpression(),i=r.location):(this.consume("EQ","Expected '=', 'unset', or 'merge' after path"),o="set",r=this.parseExpression(),i=r.location),{kind:"patch",path:n,op:o,value:r,location:h(e,i)}}parseEffectStmt(){let e=this.consume("EFFECT","Expected 'effect'").location,n=this.consume("IDENTIFIER","Expected effect type").lexeme;for(;this.match("DOT");)n+="."+this.consume("IDENTIFIER","Expected identifier after '.'").lexeme;this.consume("LPAREN","Expected '(' after effect type"),this.consume("LBRACE","Expected '{' for effect arguments");let o=[];for(;!this.check("RBRACE")&&!this.isAtEnd();)o.push(this.parseEffectArg()),this.match("COMMA");this.consume("RBRACE","Expected '}' after effect arguments");let r=this.consume("RPAREN","Expected ')' to close effect").location;return{kind:"effect",effectType:n,args:o,location:h(e,r)}}parseEffectArg(){let e=this.match("IDENTIFIER","FAIL")?this.previous():this.consume("IDENTIFIER","Expected argument name");this.consume("COLON","Expected ':' after argument name");let n=["into","pass","fail"].includes(e.lexeme),o=n?this.parsePath():this.parseExpression();return{kind:"effectArg",name:e.lexeme,value:o,isPath:n,location:h(e.location,o.location)}}parseFailStmt(){let e=this.consume("FAIL","Expected 'fail'").location,n=this.consume("STRING","Expected error code string after 'fail'"),o=n.value,r,i=n.location;return this.match("WITH")&&(r=this.parseExpression(),i=r.location),{kind:"fail",code:o,message:r,location:h(e,i)}}parseStopStmt(){let e=this.consume("STOP","Expected 'stop'").location,n=this.consume("STRING","Expected reason string after 'stop'");return{kind:"stop",reason:n.value,location:h(e,n.location)}}parseTypeExpr(){let e=this.parseBaseType();if(this.check("PIPE")){let n=[e];for(;this.match("PIPE");)n.push(this.parseBaseType());e={kind:"unionType",types:n,location:h(n[0].location,n[n.length-1].location)}}return e}parseBaseType(){if(this.check("LBRACE"))return this.parseObjectType();if(this.check("STRING")){let n=this.advance();return{kind:"literalType",value:n.value,location:n.location}}if(this.check("NUMBER")){let n=this.advance();return{kind:"literalType",value:n.value,location:n.location}}if(this.check("TRUE")||this.check("FALSE")){let n=this.advance();return{kind:"literalType",value:n.kind==="TRUE",location:n.location}}if(this.check("NULL"))return{kind:"literalType",value:null,location:this.advance().location};let e=this.consume("IDENTIFIER","Expected type name");if(this.match("LT"))if(e.lexeme==="Array"){let n=this.parseTypeExpr(),o=this.consume("GT","Expected '>' after array element type").location;return{kind:"arrayType",elementType:n,location:h(e.location,o)}}else if(e.lexeme==="Record"){let n=this.parseTypeExpr();this.consume("COMMA","Expected ',' between Record type parameters");let o=this.parseTypeExpr(),r=this.consume("GT","Expected '>' after Record value type").location;return{kind:"recordType",keyType:n,valueType:o,location:h(e.location,r)}}else{for(this.error(`Unknown generic type '${e.lexeme}'`);!this.check("GT")&&!this.isAtEnd();)this.advance();this.match("GT")}return{kind:"simpleType",name:e.lexeme,location:e.location}}parseObjectType(){let e=this.consume("LBRACE","Expected '{'").location,n=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let r=this.parseAnnotationList();if(r.length>0&&(this.check("RBRACE")||this.isAtEnd())){this.reportUnsupportedAnnotations(r);continue}let i=this.consume("IDENTIFIER","Expected field name"),a=this.match("QUESTION");this.consume("COLON","Expected ':' after field name");let s=this.parseTypeExpr();n.push({kind:"typeField",name:i.lexeme,annotations:r.length>0?r:void 0,typeExpr:s,optional:a,location:h(i.location,s.location)}),this.match("COMMA")}let o=this.consume("RBRACE","Expected '}' to close object type").location;return{kind:"objectType",fields:n,location:h(e,o)}}parseExpression(e=0){let n=this.parsePrimary();for(;;){let o=Je(this.peek().kind);if(o<=e)break;if(this.peek().kind==="QUESTION"){n=this.parseTernary(n);continue}let r=Dt(this.peek().kind);if(!r)break;this.advance();let i=Rt(this.previous().kind)?o-1:o,a=this.parseExpression(i);n={kind:"binary",operator:r,left:n,right:a,location:h(n.location,a.location)}}return n}parseTernary(e){this.consume("QUESTION","Expected '?'");let n=this.parseExpression();this.consume("COLON","Expected ':' in ternary expression");let o=this.parseExpression(0);return{kind:"ternary",condition:e,consequent:n,alternate:o,location:h(e.location,o.location)}}parsePrimary(){if(this.check("BANG")||this.check("MINUS")&&this.isUnaryContext()){let e=this.advance(),n=this.parsePrimary();return{kind:"unary",operator:e.kind==="BANG"?"!":"-",operand:n,location:h(e.location,n.location)}}if(this.match("LPAREN")){let e=this.parseExpression();return this.consume("RPAREN","Expected ')' after expression"),e}if(this.check("LBRACE"))return this.parseObjectLiteral();if(this.check("LBRACKET"))return this.parseArrayLiteral();if(this.check("NUMBER")){let e=this.advance();return{kind:"literal",value:e.value,literalType:"number",location:e.location}}if(this.check("STRING")){let e=this.advance();return{kind:"literal",value:e.value,literalType:"string",location:e.location}}if(this.check("TRUE")||this.check("FALSE")){let e=this.advance();return{kind:"literal",value:e.kind==="TRUE",literalType:"boolean",location:e.location}}if(this.check("NULL"))return{kind:"literal",value:null,literalType:"null",location:this.advance().location};if(this.check("SYSTEM_IDENT")){let e=this.advance(),n=e.lexeme.slice(1).split(".");return this.parsePostfix({kind:"systemIdent",path:n,location:e.location})}if(this.check("ITEM")){let e=this.advance();return this.parsePostfix({kind:"iterationVar",name:"item",location:e.location})}if(this.check("MERGE")&&this.peekNext()?.kind==="LPAREN"){let e=this.advance();return this.parseFunctionCall(e)}if(this.check("IDENTIFIER")){let e=this.advance();return this.check("LPAREN")?this.parseFunctionCall(e):this.parsePostfix({kind:"identifier",name:e.lexeme,location:e.location})}return this.error(`Unexpected token '${this.peek().lexeme}'`),{kind:"literal",value:null,literalType:"null",location:this.peek().location}}parseFunctionCall(e){this.consume("LPAREN","Expected '(' for function call");let n=[];if(!this.check("RPAREN"))do n.push(this.parseExpression());while(this.match("COMMA"));let o=this.consume("RPAREN","Expected ')' after arguments").location;return this.parsePostfix({kind:"functionCall",name:e.lexeme,args:n,location:h(e.location,o)})}parsePostfix(e){for(;;)if(this.match("DOT")){let n=this.consume("IDENTIFIER","Expected property name after '.'");e={kind:"propertyAccess",object:e,property:n.lexeme,location:h(e.location,n.location)}}else if(this.match("LBRACKET")){let n=this.parseExpression(),o=this.consume("RBRACKET","Expected ']' after index").location;e={kind:"indexAccess",object:e,index:n,location:h(e.location,o)}}else break;return e}parseObjectLiteral(){let e=this.consume("LBRACE","Expected '{'").location,n=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let r=this.consume("IDENTIFIER","Expected property name");this.consume("COLON","Expected ':' after property name");let i=this.parseExpression();n.push({kind:"objectProperty",key:r.lexeme,value:i,location:h(r.location,i.location)}),this.check("RBRACE")||this.consume("COMMA","Expected ',' between properties")}let o=this.consume("RBRACE","Expected '}' to close object").location;return{kind:"objectLiteral",properties:n,location:h(e,o)}}parseArrayLiteral(){let e=this.consume("LBRACKET","Expected '['").location,n=[];for(;!this.check("RBRACKET")&&!this.isAtEnd();)n.push(this.parseExpression()),this.check("RBRACKET")||this.consume("COMMA","Expected ',' between elements");let o=this.consume("RBRACKET","Expected ']' to close array").location;return{kind:"arrayLiteral",elements:n,location:h(e,o)}}parsePath(){let e=[],n=this.peek().location,o=this.consume("IDENTIFIER","Expected identifier");for(e.push({kind:"propertySegment",name:o.lexeme,location:o.location});;)if(this.match("DOT")){let i=this.consume("IDENTIFIER","Expected property name");e.push({kind:"propertySegment",name:i.lexeme,location:i.location})}else if(this.match("LBRACKET")){let i=this.parseExpression(),a=this.consume("RBRACKET","Expected ']'").location;e.push({kind:"indexSegment",index:i,location:h(i.location,a)})}else break;let r=e[e.length-1];return{kind:"path",segments:e,location:h(n,r.location)}}isUnaryContext(){if(this.current===0)return!0;let e=this.previous();return["LPAREN","LBRACKET","LBRACE","COMMA","COLON","EQ","PLUS","MINUS","STAR","SLASH","PERCENT","AT","EQ_EQ","BANG_EQ","LT","LT_EQ","GT","GT_EQ","AMP_AMP","PIPE_PIPE","BANG","QUESTION","QUESTION_QUESTION"].includes(e.kind)}peek(){return this.tokens[this.current]}peekNext(){return this.peekAt(1)}peekAt(e){return this.current+e>=this.tokens.length?this.tokens[this.tokens.length-1]:this.tokens[this.current+e]}previous(){return this.tokens[this.current-1]}isAtEnd(){return this.peek().kind==="EOF"}advance(){return this.isAtEnd()||this.current++,this.previous()}check(e){return this.isAtEnd()?!1:this.peek().kind===e}isOnceIntentContext(){if(!this.check("IDENTIFIER")||this.peek().lexeme!=="onceIntent")return!1;let n=this.peekNext();return n.kind==="LBRACE"||n.kind==="WHEN"}isFlowDeclContext(){return!this.check("IDENTIFIER")||this.peek().lexeme!=="flow"?!1:this.peekNext().kind==="IDENTIFIER"&&this.peekAt(2).kind==="LPAREN"}isIncludeContext(){return!this.check("IDENTIFIER")||this.peek().lexeme!=="include"?!1:this.peekNext().kind==="IDENTIFIER"&&this.peekAt(2).kind==="LPAREN"}match(...e){for(let n of e)if(this.check(n))return this.advance(),!0;return!1}consume(e,n){if(this.check(e))return this.advance();throw this.errorAtCurrent(n)}parseAnnotationList(){let e=[];for(;this.check("AT");)e.push(this.parseAnnotation());return e}parseAnnotation(){let e=this.consume("AT","Expected '@'").location,n=this.consume("IDENTIFIER","Expected annotation name after '@'");if(n.lexeme!=="meta")throw this.errorAtToken(n,"Expected 'meta' after '@'");this.consume("LPAREN","Expected '(' after '@meta'");let o=this.consume("STRING","Expected string tag as first @meta argument"),r;this.match("COMMA")&&(r=this.parseExpression());let i=this.consume("RPAREN","Expected ')' after @meta arguments").location;return{kind:"annotation",tag:o.value,payload:r,location:h(e,i)}}reportUnsupportedAnnotations(e){for(let n of e)this.diagnostics.push({severity:"error",code:"E053",message:"@meta can attach only to domain, type, type field, state field, computed, or action declarations.",location:n.location})}error(e){this.diagnostics.push({severity:"error",code:"MEL_PARSER",message:e,location:this.previous().location})}errorAtCurrent(e){return this.diagnostics.push({severity:"error",code:"MEL_PARSER",message:e,location:this.peek().location}),new Error(e)}errorAtToken(e,n){return this.diagnostics.push({severity:"error",code:"MEL_PARSER",message:n,location:e.location}),new Error(n)}};function we(t){return new Ze(t).parse()}var Ce=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)}},et=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 Ce("domain");this.domainScope=n,this.currentScope=n,this.scopes.set("domain",n);for(let o of e.members)if(o.kind==="state")for(let r of o.fields)this.defineSymbol({name:r.name,kind:"state",location:r.location});else o.kind==="computed"?this.defineSymbol({name:o.name,kind:"computed",location:o.location}):o.kind==="action"?this.defineSymbol({name:o.name,kind:"action",location:o.location}):o.kind;for(let o of e.members)o.kind==="computed"?this.analyzeComputedExpr(o):o.kind==="action"&&this.analyzeAction(o)}analyzeComputedExpr(e){this.analyzeExpr(e.expression,"computed")}analyzeAction(e){let n=new Ce("action",this.domainScope);this.currentScope=n,this.scopes.set(`action.${e.name}`,n);for(let o of e.params)n.define({name:o.name,kind:"param",location:o.location});for(let o of e.body)this.analyzeStmt(o);this.currentScope=this.domainScope}analyzeStmt(e){switch(e.kind){case"when":this.analyzeExpr(e.condition,"action");for(let n of e.body)this.analyzeStmt(n);break;case"onceIntent":e.condition&&this.analyzeExpr(e.condition,"action");for(let n of e.body)this.analyzeStmt(n);break;case"once":this.validatePath(e.marker),e.condition&&this.analyzeExpr(e.condition,"action");for(let n of e.body)this.analyzeStmt(n);break;case"patch":this.validatePath(e.path),e.value&&this.analyzeExpr(e.value,"action");break;case"effect":for(let n of e.args)n.isPath?this.validatePath(n.value):this.analyzeExpr(n.value,"action");break;case"include":case"fail":case"stop":break}}analyzeExpr(e,n){switch(e.kind){case"identifier":this.checkIdentifier(e.name,e.location,n);break;case"systemIdent":this.checkSystemIdent(e.path,e.location,n);break;case"propertyAccess":this.analyzeExpr(e.object,n);break;case"indexAccess":this.analyzeExpr(e.object,n),this.analyzeExpr(e.index,n);break;case"functionCall":for(let o of e.args)this.analyzeExpr(o,n);break;case"binary":this.analyzeExpr(e.left,n),this.analyzeExpr(e.right,n);break;case"unary":this.analyzeExpr(e.operand,n);break;case"ternary":this.analyzeExpr(e.condition,n),this.analyzeExpr(e.consequent,n),this.analyzeExpr(e.alternate,n);break;case"objectLiteral":for(let o of e.properties)this.analyzeExpr(o.value,n);break;case"arrayLiteral":for(let o of e.elements)this.analyzeExpr(o,n);break;case"iterationVar":break;case"literal":break}}checkIdentifier(e,n,o){let r=this.currentScope?.lookup(e);if(!r){this.error(`Undefined identifier '${e}'`,n,"E_UNDEFINED");return}o==="computed"&&r.kind==="param"&&this.error(`Cannot access parameter '${e}' in computed expression`,n,"E_INVALID_ACCESS")}checkSystemIdent(e,n,o){let[r,...i]=e;if(r==="system"&&o==="computed"&&this.error("Cannot use $system.* in computed expressions (non-deterministic)",n,"E001"),r==="system"){let a=["uuid","timestamp","time.now","random"],s=i.join(".");s&&!a.includes(s)&&this.error(`Invalid system value '$system.${s}'. Valid values: ${a.join(", ")}`,n,"E003")}if(r==="meta"){let a=["intentId","actionName","timestamp"],s=i.join(".");s&&!a.includes(s)&&this.error(`Invalid meta value '$meta.${s}'. Valid values: ${a.join(", ")}`,n,"E003")}}validatePath(e){if(!e||!e.segments)return;let n=e.segments[0];n?.kind==="propertySegment"&&(this.currentScope?.lookup(n.name)||this.error(`Undefined identifier '${n.name}' in path`,e.location,"E_UNDEFINED"))}defineSymbol(e){if(this.currentScope){if(this.currentScope.isDefined(e.name)){this.error(`Duplicate identifier '${e.name}'`,e.location,"E_DUPLICATE");return}this.currentScope.define(e)}}error(e,n,o){this.diagnostics.push({severity:"error",code:o,message:e,location:n})}};function Ot(t){return new et().analyze(t)}function P(t,e,n,o){return{severity:"error",code:t,message:e,location:n,...o}}function Lt(t,e,n,o){return{severity:"warning",code:t,message:e,location:n,...o}}function _i(t,e,n){return{severity:"info",code:t,message:e,location:n}}function _n(t){return t.severity==="error"}function $i(t){return t.some(_n)}function Gi(t,e){return t.filter(n=>n.severity===e)}var Ft=new Set(["eq","neq","gt","gte","lt","lte","and","or","not","isNull","isNotNull","hasKey","startsWith","endsWith","strIncludes","includes","every","some","existsById"]),jt=new Set(["add","sub","mul","div","mod","absDiff","abs","clamp","floor","ceil","round","sqrt","pow","len","strlen","indexOf","streak","sum","min","max","toNumber"]),_t=new Set(["trim","lower","upper","concat","typeof","toString","substring","substr","replace"]),$n=new Set(["keys","values","entries","merge","filter","map","append","reverse","unique","flat","split","fromEntries"]),Gn=new Set(["updateById","removeById"]);function Pe(t){let e=new Map,n=new Map,o=new Map;for(let r of t.types)o.set(r.name,r);for(let r of t.members){if(r.kind==="state"){for(let i of r.fields)e.set(i.name,i.typeExpr);continue}r.kind==="computed"&&n.set(r.name,r)}return{stateTypes:e,computedDecls:n,typeDefs:o,computedTypeCache:new Map,computedTypeInFlight:new Set}}function Ie(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 Vn(t.value,t.location);case"identifier":return e.get(t.name)??n.stateTypes.get(t.name)??Un(t.name,n);case"propertyAccess":return X(k(t.object,e,n),t.property,n);case"indexAccess":return ge(k(t.object,e,n),n);case"objectLiteral":return{kind:"objectType",fields:t.properties.map(o=>{let r=k(o.value,e,n);return r?{kind:"typeField",name:o.key,typeExpr:r,optional:!1,location:o.location}:null}).filter(o=>o!==null),location:t.location};case"arrayLiteral":{let o=D(t.elements.map(r=>k(r,e,n)),t.location);return o?{kind:"arrayType",elementType:o,location:t.location}:null}case"unary":return Bn(t);case"binary":return zn(t,e,n);case"ternary":return D([k(t.consequent,e,n),k(t.alternate,e,n)],t.location);case"functionCall":return qn(t,e,n);case"systemIdent":return null;case"iterationVar":return e.get("$item")??null}}function $(t,e,n){let o=k(t,e,n);if(o)return $t(o,n);switch(t.kind){case"literal":return"primitive";case"objectLiteral":case"arrayLiteral":return"nonprimitive";case"binary":return t.operator==="??"?ye([$(t.left,e,n),$(t.right,e,n)]):t.operator==="=="||t.operator==="!="||t.operator==="+"||t.operator==="-"||t.operator==="*"||t.operator==="/"||t.operator==="%"||t.operator==="<"||t.operator==="<="||t.operator===">"||t.operator===">="||t.operator==="&&"||t.operator==="||"?"primitive":"unknown";case"unary":return"primitive";case"ternary":return ye([$(t.consequent,e,n),$(t.alternate,e,n)]);case"functionCall":return $n.has(t.name)?"nonprimitive":Ft.has(t.name)||jt.has(t.name)||_t.has(t.name)||t.name==="toBoolean"?"primitive":(t.name==="cond"||t.name==="if")&&t.args.length>=3?ye([$(t.args[1],e,n),$(t.args[2],e,n)]):t.name==="coalesce"?ye(t.args.map(r=>$(r,e,n))):"unknown";case"identifier":case"propertyAccess":case"indexAccess":case"systemIdent":case"iterationVar":return"unknown"}}function $t(t,e){let n=R(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 ye(n.types.map(o=>$t(o,e)))}}function R(t,e,n=new Set){return t?t.kind==="simpleType"&&e.typeDefs.has(t.name)?n.has(t.name)?null:(n.add(t.name),R(e.typeDefs.get(t.name).typeExpr,e,n)):t:null}function X(t,e,n){let o=R(t,n);if(!o)return null;if(o.kind==="objectType")return o.fields.find(i=>i.name===e)?.typeExpr??null;if(o.kind==="unionType"){let r=o.types.filter(i=>!ne(i)).map(i=>X(i,e,n)).filter(i=>i!==null);return D(r,o.location)}return null}function ge(t,e){let n=R(t,e);if(!n)return null;if(n.kind==="arrayType")return n.elementType;if(n.kind==="recordType")return n.valueType;if(n.kind==="unionType"){let o=n.types.filter(r=>!ne(r)).map(r=>ge(r,e)).filter(r=>r!==null);return D(o,n.location)}return null}function G(t,e){let n=R(t,e);if(!n)return null;if(n.kind==="arrayType")return n.elementType;if(n.kind==="unionType"){let o=n.types.filter(r=>!ne(r)).map(r=>G(r,e)).filter(r=>r!==null);return D(o,n.location)}return null}function Me(t,e){let n=R(t,e);if(!n)return!1;switch(n.kind){case"simpleType":return n.name==="string"||n.name==="number";case"literalType":return typeof n.value=="string"||typeof n.value=="number";case"unionType":return n.types.length>0&&n.types.every(o=>Me(o,e));default:return!1}}function ne(t){return t.kind==="simpleType"&&t.name==="null"||t.kind==="literalType"&&t.value===null}function Un(t,e){if(e.computedTypeCache.has(t))return e.computedTypeCache.get(t)??null;let n=e.computedDecls.get(t);if(!n||e.computedTypeInFlight.has(t))return null;e.computedTypeInFlight.add(t);let o=k(n.expression,new Map,e);return e.computedTypeInFlight.delete(t),e.computedTypeCache.set(t,o),o}function Bn(t){return t.operator==="!"?I("boolean",t.location):I("number",t.location)}function zn(t,e,n){switch(t.operator){case"==":case"!=":case"<":case"<=":case">":case">=":case"&&":case"||":return I("boolean",t.location);case"+":case"-":case"*":case"/":case"%":return I("number",t.location);case"??":return D([k(t.left,e,n),k(t.right,e,n)],t.location)}}function qn(t,e,n){if(Ft.has(t.name))return I("boolean",t.location);if(jt.has(t.name))return I("number",t.location);if(t.name==="idiv")return D([I("number",t.location),I("null",t.location)],t.location);if(_t.has(t.name))return I("string",t.location);if(t.name==="toBoolean")return I("boolean",t.location);if(t.name==="findById"&&t.args.length>=1){let o=G(k(t.args[0],e,n),n);return o?D([o,I("null",t.location)],t.location):null}if(t.name==="find"&&t.args.length>=1){let o=G(k(t.args[0],e,n),n);return o?D([o,I("null",t.location)],t.location):null}if(t.name==="filter"&&t.args.length>=1)return k(t.args[0],e,n);if(t.name==="map"&&t.args.length>=2){let o=k(t.args[0],e,n),r=G(o,n);if(!r)return null;let i=k(t.args[1],Yn(e,r),n);return i?{kind:"arrayType",elementType:i,location:t.location}:null}if((t.name==="first"||t.name==="last")&&t.args.length>=1)return G(k(t.args[0],e,n),n);if(t.name==="at"&&t.args.length>=1)return ge(k(t.args[0],e,n),n);if(t.name==="field"&&t.args.length>=2){let o=Wn(t.args[1]);return o?X(k(t.args[0],e,n),o,n):null}return Gn.has(t.name)&&t.args.length>=1?k(t.args[0],e,n):(t.name==="cond"||t.name==="if")&&t.args.length>=3?D([k(t.args[1],e,n),k(t.args[2],e,n)],t.location):t.name==="coalesce"?D(t.args.map(o=>k(o,e,n)),t.location):t.name==="match"?Hn(t,e,n):t.name==="argmax"||t.name==="argmin"?Kn(t,e,n):t.name==="slice"&&t.args.length>=1?k(t.args[0],e,n):t.name==="split"?{kind:"arrayType",elementType:I("string",t.location),location:t.location}:t.name==="keys"?{kind:"arrayType",elementType:I("string",t.location),location:t.location}:null}function ye(t){let e=!1;for(let n of t){if(n==="nonprimitive")return"nonprimitive";n==="unknown"&&(e=!0)}return e?"unknown":"primitive"}function D(t,e){let n=t.filter(i=>i!==null);if(n.length===0)return null;if(n.length===1)return n[0];let o=[],r=new Set;for(let i of n){let a=JSON.stringify(i);r.has(a)||(r.add(a),o.push(i))}return o.length===1?o[0]:{kind:"unionType",types:o,location:e}}function Hn(t,e,n){if(t.args.length<3)return null;let o=[];for(let r=1;r<t.args.length-1;r+=1){let i=t.args[r];if(i.kind!=="arrayLiteral"||i.elements.length!==2)return null;o.push(k(i.elements[1],e,n))}return o.push(k(t.args[t.args.length-1],e,n)),D(o,t.location)}function Kn(t,e,n){if(t.args.length<2)return null;let o=[];for(let i=0;i<t.args.length-1;i+=1){let a=t.args[i];if(a.kind!=="arrayLiteral"||a.elements.length!==3)return null;o.push(k(a.elements[0],e,n))}let r=D(o,t.location);return r?D([r,I("null",t.location)],t.location):null}function Vn(t,e){return{kind:"literalType",value:t,location:e}}function I(t,e){return{kind:"simpleType",name:t,location:e}}function Wn(t){return t.kind==="literal"&&typeof t.value=="string"?t.value:null}function Yn(t,e){let n=new Map(t);return n.set("$item",e),n}var Qn=new Set(["findById","existsById"]),nt=new Set(["updateById","removeById"]),Xn=new Set([...Qn,...nt]);function H(t,e,n,o,r){let i=`${n}:${r.start.offset}:${r.end.offset}:${o}`;e.has(i)||(e.add(i),t.push(P(n,o,r)))}function Gt(t){let e=[],n=new Set,o=Pe(t.domain);to(t.domain,o,e,n);for(let r of t.domain.members)switch(r.kind){case"computed":b(r.expression,"computed",new Map,o,e,n,0);break;case"action":{let i=Ie(r.params);Jn(r,i,o,e,n);break}case"state":case"flow":break}return e}function Jn(t,e,n,o,r){t.available&&b(t.available,"available",e,n,o,r,0),t.dispatchable&&b(t.dispatchable,"dispatchable",e,n,o,r,0);for(let i of t.body)Zn(i,e,n,o,r)}function Zn(t,e,n,o,r){switch(t.kind){case"when":b(t.condition,"guard",e,n,o,r,0);for(let i of t.body)oe(i,e,n,o,r);break;case"once":t.condition&&b(t.condition,"guard",e,n,o,r,0);for(let i of t.body)oe(i,e,n,o,r);break;case"onceIntent":t.condition&&b(t.condition,"guard",e,n,o,r,0);for(let i of t.body)oe(i,e,n,o,r);break;case"include":break}}function oe(t,e,n,o,r){switch(t.kind){case"when":b(t.condition,"guard",e,n,o,r,0);for(let i of t.body)oe(i,e,n,o,r);break;case"once":t.condition&&b(t.condition,"guard",e,n,o,r,0);for(let i of t.body)oe(i,e,n,o,r);break;case"onceIntent":t.condition&&b(t.condition,"guard",e,n,o,r,0);for(let i of t.body)oe(i,e,n,o,r);break;case"patch":t.value&&b(t.value,"patch",e,n,o,r,0);break;case"effect":for(let i of t.args)i.isPath||b(i.value,"action",e,n,o,r,0);break;case"fail":t.message&&b(t.message,"action",e,n,o,r,0);break;case"include":case"stop":break}}function b(t,e,n,o,r,i,a){switch(t.kind){case"functionCall":{eo(t,e,n,o,r,i,a);let s=a+(nt.has(t.name)?1:0);for(let c of t.args)b(c,e,n,o,r,i,s);break}case"binary":b(t.left,e,n,o,r,i,a),b(t.right,e,n,o,r,i,a);break;case"unary":b(t.operand,e,n,o,r,i,a);break;case"ternary":b(t.condition,e,n,o,r,i,a),b(t.consequent,e,n,o,r,i,a),b(t.alternate,e,n,o,r,i,a);break;case"propertyAccess":b(t.object,e,n,o,r,i,a);break;case"indexAccess":b(t.object,e,n,o,r,i,a),b(t.index,e,n,o,r,i,a);break;case"objectLiteral":for(let s of t.properties)b(s.value,e,n,o,r,i,a);break;case"arrayLiteral":for(let s of t.elements)b(s,e,n,o,r,i,a);break;case"literal":case"identifier":case"systemIdent":case"iterationVar":break}}function eo(t,e,n,o,r,i,a){if(!Xn.has(t.name)||t.args.length===0)return;nt.has(t.name)&&(e==="available"?H(r,i,"E035","updateById/removeById are not allowed in available conditions.",t.location):e==="dispatchable"?H(r,i,"E048","updateById/removeById are not allowed in dispatchable conditions.",t.location):e==="guard"?H(r,i,"E034","updateById/removeById are not allowed in guard conditions.",t.location):e!=="patch"&&H(r,i,"E031","updateById/removeById are only allowed in patch RHS.",t.location),a>0&&H(r,i,"E032","Nested transform primitives are not allowed.",t.location),e==="patch"&&!tt(t.args[0],o)&&H(r,i,"E033","Transform primitive collection argument must resolve to a state path.",t.args[0].location));let s=oo(t.args[0],n,o);if(!s)return;let c=Ut(s,o);if(!c){H(r,i,"E030","Collection element type must declare an 'id' field for entity primitives.",t.args[0].location);return}Me(c,o)||H(r,i,"E030a","Entity 'id' field must be string or number.",t.args[0].location)}function to(t,e,n,o){for(let r of t.members)if(r.kind==="state")for(let i of r.fields)no(i,e,n,o)}function no(t,e,n,o){if(!t.initializer||t.initializer.kind!=="arrayLiteral")return;let r=G(t.typeExpr,e);if(!r)return;let i=Ut(r,e);if(!i||!Me(i,e))return;let a=new Map;for(let s of t.initializer.elements){if(s.kind!=="objectLiteral")continue;let c=s.properties.find(p=>p.key==="id");if(!c||c.value.kind!=="literal"||typeof c.value.value!="string"&&typeof c.value.value!="number")continue;let l=`${typeof c.value.value}:${String(c.value.value)}`;if(a.get(l)){H(n,o,"E030b","Duplicate '.id' values detected in state initializer.",c.value.location);continue}a.set(l,c.value.location)}}function oo(t,e,n){return G(k(t,e,n),n)}function Ut(t,e){return X(t,"id",e)}function tt(t,e){switch(t.kind){case"identifier":return e.stateTypes.has(t.name);case"propertyAccess":return tt(t.object,e);case"indexAccess":return tt(t.object,e);default:return!1}}function Bt(){return{inAction:!1,inGuard:!1,guardDepth:0,hasMarkerPatch:!1,currentActionParamTypes:new Map,diagnostics:[]}}var ro=/\b(await(?:ing)?|wait(?:ing)?|pending)\b/i;function E(t,e){return{kind:"simpleType",name:t,location:e}}function K(t,e,n){let o=R(t,n),r=R(e,n);if(!o||!r)return null;if(r.kind==="unionType"){let i=o.kind==="unionType"?o.types:[o],a=!1;for(let s of i){let c=r.types.map(l=>K(s,l,n));if(!c.includes(!0)){if(c.every(l=>l===!1))return!1;a=!0}}return a?null:!0}if(o.kind==="unionType"){let i=!1;for(let a of o.types){let s=K(a,r,n);if(s===!1)return!1;s===null&&(i=!0)}return i?null:!0}if(r.kind==="simpleType"){if(o.kind==="simpleType")return o.name===r.name;if(o.kind==="literalType")return r.name==="null"?o.value===null:typeof o.value===r.name}if(r.kind==="literalType")return o.kind!=="literalType"?!1:o.value===r.value;if(r.kind==="arrayType")return o.kind!=="arrayType"?!1:K(o.elementType,r.elementType,n);if(r.kind==="objectType"){if(o.kind!=="objectType")return!1;for(let i of r.fields){let a=o.fields.find(c=>c.name===i.name);if(!a){if(i.optional)continue;return!1}let s=K(a.typeExpr,i.typeExpr,n);if(s!==!0)return s}return!0}return r.kind==="recordType"?o.kind!=="recordType"?null:K(o.valueType,r.valueType,n):null}function v(t,e){let n=R(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<${v(n.elementType,e)}>`;case"recordType":return`Record<${v(n.keyType,e)}, ${v(n.valueType,e)}>`;case"objectType":return`{ ${n.fields.map(o=>`${o.name}${o.optional?"?":""}: ${v(o.typeExpr,e)}`).join("; ")} }`;case"unionType":return n.types.map(o=>v(o,e)).join(" | ")}}function De(t,e){let n=R(t,e);if(!n)return null;switch(n.kind){case"simpleType":return n.name==="string"||n.name==="number"||n.name==="boolean"||n.name==="null"?new Set([n.name]):n.name==="object"?"nonprimitive":null;case"literalType":return new Set([n.value===null?"null":typeof n.value]);case"arrayType":case"recordType":case"objectType":return"nonprimitive";case"unionType":{let o=new Set;for(let r of n.types){let i=De(r,e);if(i===null)return null;if(i==="nonprimitive")return"nonprimitive";for(let a of i)o.add(a)}return o}}}function ot(t,e){let n=De(t,e);if(n===null)return null;if(n==="nonprimitive")return"invalid";let o=[...n].filter(r=>r!=="null");return o.length!==1||n.has("null")?"invalid":o[0]}function qt(t,e,n){let o=De(t,n),r=De(e,n);if(o===null||r===null)return null;if(o==="nonprimitive"||r==="nonprimitive")return!1;if(!(o instanceof Set)||!(r instanceof Set))return null;let i=[...o].filter(s=>s!=="null"),a=[...r].filter(s=>s!=="null");return i.length===0||a.length===0?!0:i.some(s=>a.includes(s))}function io(t,e){let n=R(t,e);if(!n||ne(n))return null;if(n.kind!=="unionType")return n;let o=n.types.filter(r=>!ne(r));return o.length===0?null:o.length===1?o[0]:{kind:"unionType",types:o,location:n.location}}function rt(t,e,n){if(!t||!e)return null;let o=K(t,e,n);if(o===!0)return!0;let r=K(e,t,n);if(r===!0)return!0;let i=qt(t,e,n);return i!==null?i:o===!1&&r===!1?!1:null}function Ht(t,e){let n=R(t,e);if(!n)return null;if(n.kind==="unionType"){let o=n.types.map(r=>Ht(r,e));return o.every(r=>r===!0)?!0:o.some(r=>r===!1)?!1:null}return n.kind==="arrayType"}function Kt(t,e){let n=R(t,e);if(!n)return null;if(n.kind==="unionType"){let o=n.types.map(r=>Kt(r,e));return o.every(r=>r===!0)?!0:o.some(r=>r===!1)?!1:null}return n.kind==="arrayType"||n.kind==="recordType"||n.kind==="objectType"?!0:n.kind==="literalType"?typeof n.value=="string":n.kind==="simpleType"?n.name==="string"||n.name==="object":!1}function ao(t,e){let n=new Map(t);return n.set("$item",e),n}function zt(t){let e=Re(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 Re(t){if(t.kind==="literal"&&t.literalType==="number"&&typeof t.value=="number")return t.value;if(t.kind==="unary"&&t.operator==="-"){let e=Re(t.operand);return typeof e=="number"?-e:void 0}}function so(t,e){let[n,...o]=t.segments;if(!n||n.kind!=="propertySegment")return null;let r=e.stateTypes.get(n.name)??null;for(let i of o){if(!r)return null;r=i.kind==="propertySegment"?X(r,i.name,e):ge(r,e)}return r}function co(t){let e="";for(let[n,o]of t.segments.entries()){if(o.kind==="propertySegment"){e+=n===0?o.name:`.${o.name}`;continue}o.index.kind==="literal"?e+=`[${JSON.stringify(o.index.value)}]`:e+="[*]"}return e}var it=class{ctx=Bt();symbols=null;validate(e){return this.ctx=Bt(),this.symbols=Pe(e.domain),this.validateDomain(e.domain),this.symbols=null,{valid:!this.ctx.diagnostics.some(n=>n.severity==="error"),diagnostics:this.ctx.diagnostics}}validateDomain(e){e.name.startsWith("__")&&this.error("Domain name cannot start with '__' (reserved prefix)",e.location,"E_RESERVED_NAME");for(let n of e.members)switch(n.kind){case"state":this.validateState(n);break;case"computed":this.validateExpr(n.expression,"computed");break;case"action":this.validateAction(n);break;case"flow":break}}validateState(e){let n=new Map;for(let o of e.fields){let r=n.get(o.name);r?this.error(`Duplicate state field '${o.name}'. First declared at line ${r.start.line}`,o.location,"E_DUPLICATE_FIELD"):n.set(o.name,o.location),this.validateStateField(o)}}validateStateField(e){this.checkAnonymousObjectType(e.typeExpr,e.location),e.initializer&&this.validateStateInitializer(e.initializer)}validateStateInitializer(e){switch(e.kind){case"literal":return;case"identifier":case"iterationVar":this.error("State initializers must be compile-time constants",e.location,"E042");return;case"systemIdent":e.path[0]==="system"?this.error("$system.* cannot be used in state initializers",e.location,"E002"):this.error("State initializers must be compile-time constants",e.location,"E042");return;case"objectLiteral":for(let n of e.properties)this.validateStateInitializer(n.value);return;case"arrayLiteral":for(let n of e.elements)this.validateStateInitializer(n);return;case"functionCall":{let n=this.ctx.diagnostics.length;for(let o of e.args)this.validateStateInitializer(o);this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}case"binary":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(e.left),this.validateStateInitializer(e.right),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}case"unary":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(e.operand),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}case"ternary":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(e.condition),this.validateStateInitializer(e.consequent),this.validateStateInitializer(e.alternate),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}case"propertyAccess":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(e.object),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}case"indexAccess":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(e.object),this.validateStateInitializer(e.index),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}}}checkAnonymousObjectType(e,n){switch(e.kind){case"objectType":this.ctx.diagnostics.push(Lt("W012","Anonymous object type in state field. Use a named type declaration instead: type MyType = { ... }",e.location,{suggestion:"Define this type using 'type TypeName = { ... }' and reference it by name"}));for(let o of e.fields)this.checkAnonymousObjectType(o.typeExpr,n);break;case"arrayType":this.checkAnonymousObjectType(e.elementType,n);break;case"recordType":this.checkAnonymousObjectType(e.keyType,n),this.checkAnonymousObjectType(e.valueType,n);break;case"unionType":for(let o of e.types)this.checkAnonymousObjectType(o,n);break}}validateAction(e){this.ctx.inAction=!0,this.ctx.currentActionParamTypes=Ie(e.params),e.available&&this.validateAvailableExpr(e.available),e.dispatchable&&this.validateDispatchableExpr(e.dispatchable);for(let n of e.body)this.validateGuardedStmt(n);this.ctx.inAction=!1,this.ctx.currentActionParamTypes=new Map}validateAvailableExpr(e){switch(e.kind){case"identifier":this.ctx.currentActionParamTypes.has(e.name)&&this.error("Action parameters cannot be used in available condition",e.location,"E005");break;case"systemIdent":e.path[0]==="system"&&this.error("$system.* cannot be used in available condition (must be pure expression)",e.location,"E005"),e.path[0]==="input"&&this.error("$input.* cannot be used in available condition (parameters not available at availability check)",e.location,"E005"),e.path[0]==="meta"&&this.error("$meta.* cannot be used in available condition (availability is schema-context only)",e.location,"E005");break;case"functionCall":for(let n of e.args)this.validateAvailableExpr(n);break;case"binary":this.validateAvailableExpr(e.left),this.validateAvailableExpr(e.right);break;case"unary":this.validateAvailableExpr(e.operand);break;case"ternary":this.validateAvailableExpr(e.condition),this.validateAvailableExpr(e.consequent),this.validateAvailableExpr(e.alternate);break;case"propertyAccess":this.validateAvailableExpr(e.object);break;case"indexAccess":this.validateAvailableExpr(e.object),this.validateAvailableExpr(e.index);break;case"objectLiteral":for(let n of e.properties)this.validateAvailableExpr(n.value);break;case"arrayLiteral":for(let n of e.elements)this.validateAvailableExpr(n);break}}validateDispatchableExpr(e){switch(e.kind){case"systemIdent":e.path[0]==="system"&&this.error("$system.* cannot be used in dispatchable condition (must be pure expression)",e.location,"E047"),e.path[0]==="input"&&this.error("$input.* cannot be used in dispatchable condition (use bare action parameter names)",e.location,"E047"),e.path[0]==="meta"&&this.error("$meta.* cannot be used in dispatchable condition (dispatchability is snapshot + bound-input only)",e.location,"E047");break;case"functionCall":for(let n of e.args)this.validateDispatchableExpr(n);break;case"binary":this.validateDispatchableExpr(e.left),this.validateDispatchableExpr(e.right);break;case"unary":this.validateDispatchableExpr(e.operand);break;case"ternary":this.validateDispatchableExpr(e.condition),this.validateDispatchableExpr(e.consequent),this.validateDispatchableExpr(e.alternate);break;case"propertyAccess":this.validateDispatchableExpr(e.object);break;case"indexAccess":this.validateDispatchableExpr(e.object),this.validateDispatchableExpr(e.index);break;case"objectLiteral":for(let n of e.properties)this.validateDispatchableExpr(n.value);break;case"arrayLiteral":for(let n of e.elements)this.validateDispatchableExpr(n);break}}validateGuardedStmt(e){switch(e.kind){case"when":this.validateWhen(e);break;case"once":this.validateOnce(e);break;case"onceIntent":this.validateOnceIntent(e);break;case"patch":this.validatePatch(e);break;case"effect":this.validateEffect(e);break;case"include":break;case"fail":this.validateFail(e);break;case"stop":this.validateStop(e);break}}validateWhen(e){this.ctx.inGuard=!0,this.ctx.guardDepth++,this.validateCondition(e.condition,"when");for(let n of e.body)this.validateGuardedStmt(n);this.ctx.guardDepth--,this.ctx.guardDepth===0&&(this.ctx.inGuard=!1)}validateOnce(e){this.ctx.inGuard=!0,this.ctx.guardDepth++,this.ctx.hasMarkerPatch=!1,e.condition&&this.validateCondition(e.condition,"once");for(let n of e.body)this.validateGuardedStmt(n);this.ctx.guardDepth--,this.ctx.guardDepth===0&&(this.ctx.inGuard=!1)}validateOnceIntent(e){this.ctx.inGuard=!0,this.ctx.guardDepth++,e.condition&&this.validateCondition(e.condition,"onceIntent");for(let n of e.body)this.validateGuardedStmt(n);this.ctx.guardDepth--,this.ctx.guardDepth===0&&(this.ctx.inGuard=!1)}validatePatch(e){if(this.ctx.inGuard||this.error("Patch must be inside a guard (when, once, or onceIntent)",e.location,"E_UNGUARDED_PATCH"),e.value){let n=this.ctx.diagnostics.length,o=this.validateExpr(e.value,"action");if(!this.symbols||n!==this.ctx.diagnostics.length)return;let r=so(e.path,this.symbols);if(!r||!o)return;K(o,r,this.symbols)===!1&&this.error(`Patch value for '${co(e.path)}' must be assignable to ${v(r,this.symbols)}, got ${v(o,this.symbols)}`,e.value.location,"E_TYPE_MISMATCH")}}validateEffect(e){this.ctx.inGuard||this.error("Effect must be inside a guard (when, once, or onceIntent)",e.location,"E_UNGUARDED_EFFECT");for(let n of e.args)n.isPath||this.validateExpr(n.value,"action")}validateFail(e){this.ctx.inGuard||this.error("fail must be inside a guard (when, once, or onceIntent)",e.location,"E006"),e.message&&this.validateExpr(e.message,"action")}validateStop(e){this.ctx.inGuard||this.error("stop must be inside a guard (when, once, or onceIntent)",e.location,"E007"),ro.test(e.reason)&&this.error("stop message suggests waiting/pending - use 'Already processed' style instead",e.location,"E008")}validateCondition(e,n){let o=this.ctx.diagnostics.length,r=this.validateExpr(e,"action");o===this.ctx.diagnostics.length&&this.requireAssignable(r,E("boolean",e.location),e.location,`Condition in ${n} must evaluate to boolean`)}validateExpr(e,n,o=this.ctx.currentActionParamTypes){switch(e.kind){case"functionCall":return this.validateFunctionCall(e,n,o),this.inferType(e,o);case"binary":{let r=this.ctx.diagnostics.length,i=this.validateExpr(e.left,n,o),a=this.validateExpr(e.right,n,o);if(!(r!==this.ctx.diagnostics.length))switch(e.operator){case"==":case"!=":this.validatePrimitiveEquality(e.left,e.right,i,a,e.location);break;case"<":case"<=":case">":case">=":this.requireAssignable(i,E("number",e.left.location),e.left.location,`Operator '${e.operator}' requires a numeric left operand`),this.requireAssignable(a,E("number",e.right.location),e.right.location,`Operator '${e.operator}' requires a numeric right operand`);break;case"&&":case"||":this.requireAssignable(i,E("boolean",e.left.location),e.left.location,`Operator '${e.operator}' requires a boolean left operand`),this.requireAssignable(a,E("boolean",e.right.location),e.right.location,`Operator '${e.operator}' requires a boolean right operand`);break;case"+":case"-":case"*":case"/":case"%":this.requireAssignable(i,E("number",e.left.location),e.left.location,`Operator '${e.operator}' requires a numeric left operand`),this.requireAssignable(a,E("number",e.right.location),e.right.location,`Operator '${e.operator}' requires a numeric right operand`);break;case"??":this.validateCoalesceTypes([i,a],e.location);break}return this.inferType(e,o)}case"unary":{let r=this.ctx.diagnostics.length,i=this.validateExpr(e.operand,n,o);return r===this.ctx.diagnostics.length&&this.requireAssignable(i,E(e.operator==="!"?"boolean":"number",e.operand.location),e.operand.location,e.operator==="!"?"Unary '!' requires a boolean operand":"Unary '-' requires a numeric operand"),this.inferType(e,o)}case"ternary":{let r=this.ctx.diagnostics.length,i=this.validateExpr(e.condition,n,o);return this.validateExpr(e.consequent,n,o),this.validateExpr(e.alternate,n,o),r===this.ctx.diagnostics.length&&this.requireAssignable(i,E("boolean",e.condition.location),e.condition.location,"Ternary condition must evaluate to boolean"),this.inferType(e,o)}case"propertyAccess":return this.validateExpr(e.object,n,o),this.inferType(e,o);case"indexAccess":return this.validateExpr(e.object,n,o),this.validateExpr(e.index,n,o),this.inferType(e,o);case"objectLiteral":for(let r of e.properties)this.validateExpr(r.value,n,o);return this.inferType(e,o);case"arrayLiteral":for(let r of e.elements)this.validateExpr(r,n,o);return this.inferType(e,o);case"systemIdent":return this.inferType(e,o);case"literal":case"identifier":case"iterationVar":return this.inferType(e,o)}}validateFunctionCall(e,n,o){let{name:r,args:i,location:a}=e;if(["reduce","fold","foldl","foldr","scan"].includes(r)&&this.error(`Function '${r}' is forbidden. Use sum(), min(), max() for aggregation instead`,a,"E011"),["sum","min","max"].includes(r)&&i.length===1){n==="action"&&this.error(`Primitive aggregation '${r}()' can only be used in computed expressions, not in actions`,a,"E009");let c=i[0];c.kind==="functionCall"&&this.error(`Primitive aggregation '${r}()' does not allow composition. Use a direct reference, not '${c.name}()'`,a,"E010")}switch(r){case"eq":case"neq":break;case"len":case"sum":i.length!==1&&this.error(`Function '${r}' expects 1 argument, got ${i.length}`,a,"E_ARG_COUNT");break;case"add":case"sub":case"mul":case"div":case"mod":case"absDiff":case"idiv":case"gt":case"gte":case"lt":case"lte":i.length!==2&&this.error(`Function '${r}' expects 2 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"not":case"neg":case"abs":case"floor":case"ceil":case"round":case"sqrt":case"isNull":case"isNotNull":case"trim":case"lower":case"upper":case"strlen":case"keys":case"values":case"entries":case"first":case"last":case"typeof":case"toString":case"toNumber":case"toBoolean":case"reverse":case"unique":case"flat":case"fromEntries":i.length!==1&&this.error(`Function '${r}' expects 1 argument, got ${i.length}`,a,"E_ARG_COUNT");break;case"pow":case"findById":case"existsById":case"filter":case"map":case"find":case"every":case"some":case"at":case"includes":case"field":case"hasKey":case"pick":case"omit":case"startsWith":case"endsWith":case"strIncludes":case"indexOf":i.length!==2&&this.error(`Function '${r}' expects 2 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"updateById":case"clamp":i.length!==3&&this.error(`Function '${r}' expects 3 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"removeById":case"streak":i.length!==2&&this.error(`Function '${r}' expects 2 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"slice":case"substring":case"substr":case"replace":(i.length<2||i.length>3)&&this.error(`Function '${r}' expects 2-3 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"split":i.length!==2&&this.error(`Function '${r}' expects 2 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"and":case"or":case"concat":case"min":case"max":case"merge":case"coalesce":case"append":i.length<1&&this.error(`Function '${r}' expects at least 1 argument`,a,"E_ARG_COUNT");break;case"match":i.length<3&&this.error("Function 'match' expects a selector, at least one [key, value] arm, and a default value",a,"E050");break;case"argmax":case"argmin":i.length<2&&this.error(`Function '${r}' expects at least one [label, eligible, score] candidate and a tie-break literal`,a,"E052");break;case"if":case"cond":i.length!==3&&this.error(`Function '${r}' expects 3 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;default:this.error(`Unknown function '${r}'. Check spelling or see MEL builtin function reference`,a,"E_UNKNOWN_FN");break}let s=[];if(["filter","map","find","every","some"].includes(r)&&i.length>0){let c=this.validateExpr(i[0],n,o);s.push(c);let l=o;if(this.symbols){let d=G(c,this.symbols);d&&(l=ao(o,d))}for(let d=1;d<i.length;d+=1)s.push(this.validateExpr(i[d],n,d===1?l:o))}else for(let c of i)s.push(this.validateExpr(c,n,o));if(this.symbols)switch(r){case"eq":case"neq":i.length===2&&this.validatePrimitiveEquality(i[0],i[1],s[0],s[1],a);break;case"add":case"sub":case"mul":case"div":case"mod":case"absDiff":case"idiv":case"pow":i.length===2&&(this.requireAssignable(s[0],E("number",i[0].location),i[0].location,`Function '${r}' expects a numeric first argument`),this.requireAssignable(s[1],E("number",i[1].location),i[1].location,`Function '${r}' expects a numeric second argument`));break;case"gt":case"gte":case"lt":case"lte":i.length===2&&(this.requireAssignable(s[0],E("number",i[0].location),i[0].location,`Function '${r}' expects a numeric first argument`),this.requireAssignable(s[1],E("number",i[1].location),i[1].location,`Function '${r}' expects a numeric second argument`));break;case"and":case"or":for(let[c,l]of i.entries())this.requireAssignable(s[c],E("boolean",l.location),l.location,`Function '${r}' expects boolean arguments`);break;case"not":i.length===1&&this.requireAssignable(s[0],E("boolean",i[0].location),i[0].location,"Function 'not' expects a boolean argument");break;case"neg":case"abs":case"floor":case"ceil":case"round":case"sqrt":i.length===1&&this.requireAssignable(s[0],E("number",i[0].location),i[0].location,`Function '${r}' expects a numeric argument`);break;case"clamp":if(i.length===3){this.requireAssignable(s[0],E("number",i[0].location),i[0].location,"Function 'clamp' expects a numeric first argument"),this.requireAssignable(s[1],E("number",i[1].location),i[1].location,"Function 'clamp' expects a numeric second argument"),this.requireAssignable(s[2],E("number",i[2].location),i[2].location,"Function 'clamp' expects a numeric third argument");let c=Re(i[1]),l=Re(i[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":i.length===2&&(this.requireAssignable(s[0],E("number",i[0].location),i[0].location,"Function 'streak' expects a numeric first argument"),this.requireAssignable(s[1],E("boolean",i[1].location),i[1].location,"Function 'streak' expects a boolean second argument"));break;case"trim":case"lower":case"upper":case"strlen":i.length===1&&this.requireAssignable(s[0],E("string",i[0].location),i[0].location,`Function '${r}' expects a string argument`);break;case"startsWith":case"endsWith":case"strIncludes":case"indexOf":case"split":i.length===2&&(this.requireAssignable(s[0],E("string",i[0].location),i[0].location,`Function '${r}' expects a string first argument`),this.requireAssignable(s[1],E("string",i[1].location),i[1].location,`Function '${r}' expects a string second argument`));break;case"replace":i.length>=2&&(this.requireAssignable(s[0],E("string",i[0].location),i[0].location,"Function 'replace' expects a string first argument"),this.requireAssignable(s[1],E("string",i[1].location),i[1].location,"Function 'replace' expects a string second argument")),i.length===3&&this.requireAssignable(s[2],E("string",i[2].location),i[2].location,"Function 'replace' expects a string replacement argument");break;case"substring":case"substr":i.length>=2&&(this.requireAssignable(s[0],E("string",i[0].location),i[0].location,`Function '${r}' expects a string first argument`),this.requireAssignable(s[1],E("number",i[1].location),i[1].location,`Function '${r}' expects a numeric second argument`)),i.length===3&&this.requireAssignable(s[2],E("number",i[2].location),i[2].location,`Function '${r}' expects a numeric third argument`);break;case"len":i.length===1&&this.requireLenCompatible(s[0],i[0].location);break;case"filter":case"find":case"every":case"some":i.length===2&&(this.requireArrayCompatible(s[0],i[0].location,r),this.requireAssignable(s[1],E("boolean",i[1].location),i[1].location,`Function '${r}' requires a boolean-valued callback`));break;case"map":i.length===2&&this.requireArrayCompatible(s[0],i[0].location,r);break;case"coalesce":this.validateCoalesceTypes(s,a);break;case"match":this.validateMatchCall(i,s,a,o);break;case"argmax":case"argmin":this.validateArgSelectionCall(r,i,a,o);break;case"if":case"cond":i.length===3&&this.requireAssignable(s[0],E("boolean",i[0].location),i[0].location,`Function '${r}' expects a boolean condition`);break}}validatePrimitiveEquality(e,n,o,r,i){if(!this.symbols)return;if(e.kind==="objectLiteral"||e.kind==="arrayLiteral"||n.kind==="objectLiteral"||n.kind==="arrayLiteral"){this.error("eq/neq operands must be compatible primitive types, not object or array literals",i,"E_TYPE_MISMATCH");return}qt(o,r,this.symbols)===!1&&this.error(`eq/neq operands must be compatible primitive types, got ${v(o,this.symbols)} and ${v(r,this.symbols)}`,i,"E_TYPE_MISMATCH")}inferType(e,n){return this.symbols?k(e,n,this.symbols):null}requireAssignable(e,n,o,r){if(!this.symbols||!e)return;K(e,n,this.symbols)===!1&&this.error(`${r}, got ${v(e,this.symbols)}`,o,"E_TYPE_MISMATCH")}requireArrayCompatible(e,n,o){if(!this.symbols||!e)return;Ht(e,this.symbols)===!1&&this.error(`Function '${o}' expects an array first argument, got ${v(e,this.symbols)}`,n,"E_TYPE_MISMATCH")}requireLenCompatible(e,n){if(!this.symbols||!e)return;Kt(e,this.symbols)===!1&&this.error(`Function 'len' expects a string, array, object, or record argument, got ${v(e,this.symbols)}`,n,"E_TYPE_MISMATCH")}validateCoalesceTypes(e,n){if(!this.symbols)return;let o=e.map(r=>io(r,this.symbols)).filter(r=>r!==null);for(let r=0;r<o.length;r+=1)for(let i=r+1;i<o.length;i+=1)if(rt(o[r],o[i],this.symbols)===!1){this.error(`coalesce arguments must have compatible non-null types, got ${v(o[r],this.symbols)} and ${v(o[i],this.symbols)}`,n,"E_TYPE_MISMATCH");return}}validateMatchCall(e,n,o,r){if(!this.symbols||e.length<3)return;let i=n[0],a=ot(i,this.symbols);a==="invalid"&&this.error(`Function 'match' requires a selector of type string, number, or boolean, got ${v(i,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[p,m]=d.elements,f=zt(p);if(f==null)this.error("Function 'match' requires literal string, number, or boolean arm keys",p.location,"E050");else{let _=`${typeof f}:${String(f)}`;s.has(_)?this.error(`Function 'match' has duplicate arm key ${JSON.stringify(f)}`,p.location,"E051"):s.add(_)}let N=this.inferType(p,r),S=ot(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 ${v(i,this.symbols)} and ${v(N,this.symbols)}`,p.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(rt(c[l],c[d],this.symbols)===!1){this.error(`Function 'match' arm values and default must have compatible types, got ${v(c[l],this.symbols)} and ${v(c[d],this.symbols)}`,o,"E_TYPE_MISMATCH");return}}validateArgSelectionCall(e,n,o,r){if(!this.symbols||n.length<2)return;let i=n[n.length-1],a=zt(i);a!=="first"&&a!=="last"&&this.error(`Function '${e}' requires a final tie-break literal of "first" or "last"`,i.location,"E052");let s=[],c=null;for(let 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[p,m,f]=d.elements,N=this.inferType(p,r),S=ot(N,this.symbols);S==="invalid"?this.error(`Function '${e}' requires labels with exactly one primitive scalar type, got ${v(N,this.symbols)}`,p.location,"E_TYPE_MISMATCH"):c===null?c=S:S!==null&&S!==c&&this.error(`Function '${e}' candidate labels must share one primitive scalar type, got ${c} and ${S}`,p.location,"E_TYPE_MISMATCH"),this.requireAssignable(this.inferType(m,r),E("boolean",m.location),m.location,`Function '${e}' expects a boolean eligible value`),this.requireAssignable(this.inferType(f,r),E("number",f.location),f.location,`Function '${e}' expects a numeric score value`),s.push(N)}for(let l=0;l<s.length;l+=1)for(let d=l+1;d<s.length;d+=1)if(rt(s[l],s[d],this.symbols)===!1){this.error(`Function '${e}' candidate labels must have compatible scalar types, got ${v(s[l],this.symbols)} and ${v(s[d],this.symbols)}`,o,"E_TYPE_MISMATCH");return}}error(e,n,o){this.ctx.diagnostics.push({severity:"error",code:o,message:e,location:n})}warn(e,n,o){this.ctx.diagnostics.push({severity:"warning",code:o,message:e,location:n})}};function Vt(t){let n=new it().validate(t),o=Gt(t),r=[...n.diagnostics,...o];return{valid:!r.some(i=>i.severity==="error"),diagnostics:r}}var at={mode:"schema",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!1},st={mode:"action",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!1},ct={mode:"action",allowSysPaths:{prefixes:["input"]},fnTableVersion:"1.0",allowItem:!1},lt={mode:"action",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!0},lo={allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0"};var j=class extends Error{code;path;details;constructor(e,n,o){super(n),this.name="LoweringError",this.code=e,this.path=o?.path,this.details=o?.details}};function Oe(t,e,n){return new j("INVALID_KIND_FOR_CONTEXT",`Node kind '${t}' is not allowed in ${e} context`,{path:n,details:{kind:t,context:e}})}function y(t,e){return new j("UNKNOWN_CALL_FN",`Unknown function '${t}' in call expression`,{path:e,details:{fn:t}})}function Le(t,e){return new j("INVALID_SYS_PATH",`System path '${t.join(".")}' is not allowed in Translator path`,{path:e,details:{sysPath:t}})}function dt(t,e){return new j("UNSUPPORTED_BASE",`Unsupported base expression kind '${t}'. Only var(item) is supported.`,{path:e,details:{baseKind:t}})}function po(t,e){return new j("INVALID_SHAPE",`Invalid node shape: ${t}`,{path:e,details:{description:t}})}function pt(t,e){return new j("UNKNOWN_NODE_KIND",`Unknown expression node kind '${t}'`,{path:e,details:{kind:t}})}function uo(t,e){let n=Array.from(t),o=Array.from(e),r=Math.min(n.length,o.length);for(let i=0;i<r;i+=1){let a=n[i].codePointAt(0)??0,s=o[i].codePointAt(0)??0;if(a!==s)return a-s}return n.length-o.length}function Wt(t){return t.map((e,n)=>({item:e,index:n})).sort((e,n)=>{let o=uo(e.item.key,n.item.key);return o!==0?o:e.index-n.index}).map(({item:e})=>e)}function u(t,e){switch(t.kind){case"lit":return mo(t);case"var":return fo(t,e);case"sys":return ho(t,e);case"get":return yo(t,e);case"field":return Yt(t,e);case"call":return go(t,e);case"obj":return Eo(t,e);case"arr":return ko(t,e);default:throw pt(t.kind)}}function mo(t){return{kind:"lit",value:t.value}}function fo(t,e){if(!e.allowItem)throw Oe("var",e.mode);return{kind:"get",path:"$item"}}function ho(t,e){if(t.path.length===0)throw Le(t.path);let n=t.path[0];if(!(e.allowSysPaths?.prefixes??["meta","input"]).includes(n))throw Le(t.path);return{kind:"get",path:t.path.join(".")}}function yo(t,e){let n=t.path.map(o=>o.name).join(".");if(t.base===void 0)return{kind:"get",path:n};if(t.base.kind==="var"&&t.base.name==="item"){if(!e.allowItem)throw Oe("var",e.mode);return{kind:"get",path:`$item.${n}`}}throw dt(t.base.kind)}function Yt(t,e){if(t.object.kind==="get"&&t.object.base===void 0){let n=t.object.path.map(o=>o.name).join(".");return{kind:"get",path:n?`${n}.${t.property}`:t.property}}return{kind:"field",object:u(t.object,e),property:t.property}}function go(t,e){let{fn:n,args:o}=t;if(n==="absDiff"){if(o.length!==2)throw y(n);return{kind:"abs",arg:{kind:"sub",left:u(o[0],e),right:u(o[1],e)}}}if(n==="clamp"){if(o.length!==3)throw y(n);return{kind:"min",args:[{kind:"max",args:[u(o[0],e),u(o[1],e)]},u(o[2],e)]}}if(n==="idiv"){if(o.length!==2)throw y(n);return{kind:"floor",arg:{kind:"div",left:u(o[0],e),right:u(o[1],e)}}}if(n==="streak"){if(o.length!==2)throw y(n);return{kind:"if",cond:u(o[1],e),then:{kind:"add",left:u(o[0],e),right:{kind:"lit",value:1}},else:{kind:"lit",value:0}}}if(n==="match")return To(o,e);if(n==="argmax"||n==="argmin")return No(n,o,e);if(Ao(n)){if(o.length!==2)throw y(n);let[r,i]=o;return{kind:n,left:u(r,e),right:u(i,e)}}if(n==="isNotNull"){if(o.length!==1)throw y(n);return{kind:"not",arg:{kind:"isNull",arg:u(o[0],e)}}}if(Qt(n)){if(o.length!==1)throw y(n);return{kind:wo(n),arg:u(o[0],e)}}if(n==="trim"){if(o.length!==1)throw y(n);return{kind:"trim",str:u(o[0],e)}}if(n==="lower"||n==="toLowerCase"){if(o.length!==1)throw y(n);return{kind:"toLowerCase",str:u(o[0],e)}}if(n==="upper"||n==="toUpperCase"){if(o.length!==1)throw y(n);return{kind:"toUpperCase",str:u(o[0],e)}}if(n==="strlen"||n==="strLen"){if(o.length!==1)throw y(n);return{kind:"strLen",str:u(o[0],e)}}if(Co(n))return o.length===1?{kind:n==="min"?"minArray":"maxArray",array:u(o[0],e)}:{kind:n,args:o.map(r=>u(r,e))};if(n==="sum"){if(o.length!==1)throw y(n);return{kind:"sumArray",array:u(o[0],e)}}if(n==="pow"){if(o.length!==2)throw y(n);return{kind:"pow",base:u(o[0],e),exponent:u(o[1],e)}}if(Po(n))return{kind:n,args:o.map(r=>u(r,e))};if(n==="if"||n==="cond"){if(o.length!==3)throw y(n);return{kind:"if",cond:u(o[0],e),then:u(o[1],e),else:u(o[2],e)}}if(n==="field"){if(o.length!==2)throw y(n);let r=u(o[0],e),i=o[1];if(i.kind!=="lit"||typeof i.value!="string")throw y(n);return Yt({kind:"field",object:o[0],property:i.value},e)}if(Io(n)){if(o.length!==1)throw y(n);return{kind:n,array:u(o[0],e)}}if(Mo(n)){if(o.length!==1)throw y(n);return{kind:n,obj:u(o[0],e)}}if(n==="at"){if(o.length!==2)throw y(n);return{kind:"at",array:u(o[0],e),index:u(o[1],e)}}if(n==="includes"){if(o.length!==2)throw y(n);return{kind:"includes",array:u(o[0],e),item:u(o[1],e)}}if(Do(n)){if(o.length!==2)throw y(n);let r={...e,allowItem:!0};return n==="map"?{kind:"map",array:u(o[0],e),mapper:u(o[1],r)}:{kind:n,array:u(o[0],e),predicate:u(o[1],r)}}if(n==="slice"){if(o.length<2||o.length>3)throw y(n);let r={kind:"slice",array:u(o[0],e),start:u(o[1],e)};return o.length===3&&(r.end=u(o[2],e)),r}if(n==="substring"||n==="substr"){if(o.length<2||o.length>3)throw y(n);let r={kind:"substring",str:u(o[0],e),start:u(o[1],e)};return o.length===3&&(r.end=u(o[2],e)),r}if(n==="append"){if(o.length<1)throw y(n);return{kind:"append",array:u(o[0],e),items:o.slice(1).map(r=>u(r,e))}}if(n==="merge")return{kind:"merge",objects:o.map(r=>u(r,e))};throw y(n)}function Eo(t,e){let n={};for(let o of Wt(t.fields))n[o.key]=u(o.value,e);return{kind:"object",fields:n}}function ko(t,e){if(t.elements.every(r=>r.kind==="lit"))return{kind:"lit",value:t.elements.map(i=>i.value)};let o=t.elements.map(r=>u(r,e));return o.length===0?{kind:"lit",value:[]}:{kind:"append",array:{kind:"lit",value:[]},items:o}}function To(t,e){if(t.length<3)throw y("match");let n=u(t[0],e),o=u(t[t.length-1],e);for(let r=t.length-2;r>=1;r-=1){let i=t[r];if(i.kind!=="arr"||i.elements.length!==2)throw y("match");o={kind:"if",cond:{kind:"eq",left:n,right:u(i.elements[0],e)},then:u(i.elements[1],e),else:o}}return o}function No(t,e,n){if(e.length<2)throw y(t);let o=e[e.length-1];if(o.kind!=="lit"||o.value!=="first"&&o.value!=="last")throw y(t);let r=e.slice(0,-1).map(i=>bo(i,n,t));if(r.length===0)throw y(t);return So(t,r,o.value)}function bo(t,e,n){if(t.kind!=="arr"||t.elements.length!==3)throw y(n);return{label:u(t.elements[0],e),eligible:u(t.elements[1],e),score:u(t.elements[2],e)}}function So(t,e,n){let o={kind:"lit",value:null};for(let r=e.length-1;r>=0;r-=1)o={kind:"if",cond:xo(t,e,n,r),then:e[r].label,else:o};return o}function xo(t,e,n,o){let r=e[o],i=[];for(let a=0;a<e.length;a+=1){if(a===o)continue;let s=e[a];i.push({kind:"or",args:[{kind:"not",arg:s.eligible},{kind:vo(t,n,o,a),left:r.score,right:s.score}]})}return i.length===0?r.eligible:{kind:"and",args:[r.eligible,...i]}}function vo(t,e,n,o){let r=e==="first"?n<o:n>o;return t==="argmax"?r?"gte":"gt":r?"lte":"lt"}function Ao(t){return["eq","neq","gt","gte","lt","lte","add","sub","mul","div","mod"].includes(t)}function Qt(t){return["not","neg","abs","floor","ceil","round","sqrt","len","typeof","isNull","toString"].includes(t)}function wo(t){if(t==="isNotNull")throw y(t);if(!Qt(t))throw y(t);return t}function Co(t){return t==="min"||t==="max"}function Po(t){return["and","or","concat","coalesce"].includes(t)}function Io(t){return["first","last"].includes(t)}function Mo(t){return["keys","values","entries"].includes(t)}function Do(t){return["filter","find","every","some","map"].includes(t)}function Ro(t,e){return t.map(n=>Oo(n,e))}function Oo(t,e){let n=t.condition?u(t.condition,Fe(e,"action")):void 0,o=Lo(t.op,e);return{fragmentId:t.fragmentId,condition:n,op:o,confidence:t.confidence}}function Lo(t,e){switch(t.kind){case"addType":return{kind:"addType",typeName:t.typeName,typeExpr:re(t.typeExpr)};case"addField":return{kind:"addField",typeName:t.typeName,field:{name:t.field.name,type:re(t.field.type),optional:t.field.optional,defaultValue:t.field.defaultValue}};case"setFieldType":return{kind:"setFieldType",path:t.path,typeExpr:re(t.typeExpr)};case"setDefaultValue":return{kind:"setDefaultValue",path:t.path,value:t.value};case"addConstraint":return{kind:"addConstraint",targetPath:t.targetPath,rule:u(t.rule,Fe(e,"schema")),message:t.message};case"addComputed":return{kind:"addComputed",name:t.name,expr:u(t.expr,Fe(e,"schema")),deps:t.deps};case"addActionAvailable":return{kind:"addActionAvailable",actionName:t.actionName,expr:u(t.expr,Fe(e,"schema"))}}}function re(t){switch(t.kind){case"primitive":return{kind:"primitive",name:t.name};case"array":return{kind:"array",element:re(t.element)};case"object":return{kind:"object",fields:t.fields.map(e=>({name:e.name,type:re(e.type),optional:e.optional}))};case"union":return{kind:"union",members:t.members.map(re)};case"literal":return{kind:"literal",value:t.value};case"ref":return{kind:"ref",name:t.name}}}function Fe(t,e){return{mode:e,allowSysPaths:t.allowSysPaths,fnTableVersion:t.fnTableVersion,actionName:t.actionName,allowItem:!1}}function Fo(t,e){return t.map(n=>je(n,e))}function je(t,e){let n=t.condition?u(t.condition,e):void 0,o=t.value?u(t.value,e):void 0;return{condition:n,op:t.op,path:jo(t.path,e),value:o}}function jo(t,e){return t.map(n=>n.kind==="prop"?n:{kind:"expr",expr:u(n.expr,e)})}function w(t,e={}){switch(t.kind){case"literal":return{kind:"lit",value:Go(t.value,t.literalType)};case"identifier":return e.resolveIdentifier?.(t.name)??U(t.name);case"systemIdent":return _o(t,e);case"iterationVar":return{kind:"var",name:t.name};case"propertyAccess":return $o(t.object,t.property,e);case"indexAccess":return{kind:"call",fn:"at",args:[w(t.object,e),w(t.index,e)]};case"functionCall":return{kind:"call",fn:t.name,args:t.args.map(n=>w(n,e))};case"unary":return{kind:"call",fn:t.operator==="!"?"not":"neg",args:[w(t.operand,e)]};case"binary":return{kind:"call",fn:Uo(t.operator),args:[w(t.left,e),w(t.right,e)]};case"ternary":return{kind:"call",fn:"cond",args:[w(t.condition,e),w(t.consequent,e),w(t.alternate,e)]};case"objectLiteral":return{kind:"obj",fields:t.properties.map(n=>({key:n.key,value:w(n.value,e)}))};case"arrayLiteral":return{kind:"arr",elements:t.elements.map(n=>w(n,e))}}}function U(...t){return{kind:"get",path:Xt(...t)}}function ut(t,...e){return{kind:"get",base:t,path:Xt(...e)}}function Ee(...t){return{kind:"sys",path:t}}function _e(t){return{kind:"obj",fields:Object.entries(t).map(([e,n])=>({key:e,value:n}))}}function Xt(...t){return t.map(e=>({kind:"prop",name:e}))}function _o(t,e){return e.resolveSystemIdent?.(t.path)??Ee(...t.path)}function $o(t,e,n){let o=w(t,n);return o.kind==="get"?{kind:"get",...o.base?{base:o.base}:void 0,path:[...o.path,{kind:"prop",name:e}]}:o.kind==="var"&&o.name==="item"?ut(o,e):{kind:"field",object:o,property:e}}function Go(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 Uo(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 Vo,semanticPathToPatchPath as Wo,sha256Sync as Yo}from"@manifesto-ai/core";var Bo=new Set(["findById","existsById","updateById","removeById"]);function Jt(t){return{...t,computed:{fields:Object.fromEntries(Object.entries(t.computed.fields).map(([e,n])=>[e,zo(n)]))},actions:Object.fromEntries(Object.entries(t.actions).map(([e,n])=>[e,qo(n)]))}}function zo(t){return{...t,expr:Zt(t.expr)}}function qo(t){return{...t,flow:$e(t.flow),available:t.available?Zt(t.available):void 0,dispatchable:t.dispatchable?Ho(t.dispatchable):void 0}}function $e(t){switch(t.kind){case"seq":return{kind:"seq",steps:t.steps.map(e=>$e(e))};case"if":return{kind:"if",cond:mt(t.cond),then:$e(t.then),else:t.else?$e(t.else):void 0};case"patch":return{kind:"patch",op:t.op,path:t.path,value:t.value?mt(t.value):void 0};case"effect":return{kind:"effect",type:t.type,params:Object.fromEntries(Object.entries(t.params).map(([e,n])=>[e,Ko(n)]))};case"fail":return{kind:"fail",code:t.code,message:t.message?mt(t.message):void 0};case"call":case"halt":return t}}function Zt(t){return u(O(t),at)}function mt(t){return u(O(t),st)}function Ho(t){return u(O(t),ct)}function Ko(t){return u(O(t),lt)}function O(t){switch(t.kind){case"lit":case"var":return t;case"sys":return t.path[0]==="system"?U("$system",...t.path.slice(1)):t;case"get":return{kind:"get",...t.base?{base:O(t.base)}:void 0,path:t.path};case"field":return{kind:"field",object:O(t.object),property:t.property};case"obj":return{kind:"obj",fields:t.fields.map(e=>({key:e.key,value:O(e.value)}))};case"arr":return{kind:"arr",elements:t.elements.map(e=>O(e))};case"call":return Bo.has(t.fn)?O(en(t.fn,t.args)):{kind:"call",fn:t.fn,args:t.args.map(e=>O(e))}}}function en(t,e){let[n,o,r]=e,i=O(n),a=o?O(o):{kind:"lit",value:null},s={kind:"var",name:"item"},c=ut(s,"id");switch(t){case"findById":return{kind:"call",fn:"find",args:[i,{kind:"call",fn:"eq",args:[c,a]}]};case"existsById":return{kind:"call",fn:"not",args:[{kind:"call",fn:"isNull",args:[en("findById",e)]}]};case"updateById":{let l=r?O(r):_e({});return{kind:"call",fn:"map",args:[i,{kind:"call",fn:"cond",args:[{kind:"call",fn:"eq",args:[c,a]},{kind:"call",fn:"merge",args:[s,l]},s]}]}}case"removeById":return{kind:"call",fn:"filter",args:[i,{kind:"call",fn:"not",args:[{kind:"call",fn:"eq",args:[c,a]}]}]};default:return{kind:"call",fn:t,args:e.map(l=>O(l))}}}function Qo(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 Xo(t){let e=Qo(t.domain.name);Jo(t.domain,e);let n=Zo(t.domain,e),o=er(t.domain,e),r=nr(t.domain,e),i=sr(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:o,computed:r,actions:i,meta:{name:t.domain.name}},s=kr(a);return{schema:{...a,hash:s},diagnostics:e.diagnostics}}function tn(t){let e=Xo(t);return e.schema?{schema:Jt(e.schema),diagnostics:e.diagnostics}:{schema:null,diagnostics:e.diagnostics}}function Jo(t,e){for(let n of t.types)e.typeDefs.set(n.name,n);for(let n of t.members)if(n.kind==="state")for(let o of n.fields)e.stateFields.add(o.name);else n.kind==="computed"?e.computedFields.add(n.name):n.kind}function Zo(t,e){let n={};for(let o of t.types){let r=V(o.typeExpr);e.typeDefinitions.set(o.name,r),n[o.name]={name:o.name,definition:r}}return n}function V(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:V(t.elementType)};case"recordType":return{kind:"record",key:V(t.keyType),value:V(t.valueType)};case"objectType":let e={};for(let o of t.fields)e[o.name]={type:V(o.typeExpr),optional:o.optional};return{kind:"object",fields:e};case"unionType":return{kind:"union",types:t.types.map(V)};case"literalType":return{kind:"literal",value:t.value};default:let n=t;throw new Error(`Unknown type expression kind: ${t.kind}`)}}function er(t,e){let n={},o={};for(let r of t.members)if(r.kind==="state")for(let i of r.fields){let a=V(i.typeExpr);o[i.name]=a,e.stateFieldTypes.set(i.name,a);let s=Z(i.typeExpr,e);s&&e.stateFieldSpecs.set(i.name,s);let c=tr(i,e);c&&(n[i.name]=c)}return{fields:n,fieldTypes:o}}function tr(t,e){let n=Z(t.typeExpr,e);if(!n)return null;let o=t.initializer?Ue(t.initializer,e):void 0;return o!==void 0&&Te(o,V(t.typeExpr),t.name,t.location,e),{...n,required:!0,default:o}}function Z(t,e,n=[]){switch(t.kind){case"simpleType":switch(t.name){case"string":return{type:"string",required:!0};case"number":return{type:"number",required:!0};case"boolean":return{type:"boolean",required:!0};case"null":return{type:"null",required:!0};default:{let o=e.typeDefs.get(t.name);return o?n.includes(t.name)?(ft(e,"E044",`Recursive type '${t.name}' cannot be lowered to FieldSpec in a schema position`,t.location),null):Z(o.typeExpr,e,[...n,t.name]):{type:"object",required:!0}}}case"unionType":{let o=t.types.filter(s=>!(s.kind==="simpleType"&&s.name==="null")&&!(s.kind==="literalType"&&s.value===null)),r=o.length!==t.types.length,i=[],a=!r;for(let s of o){if(s.kind!=="literalType"){a=!1;break}i.push(s.value)}return a&&i.length>0?{type:{enum:i},required:!0}:r&&o.length===1?Z(o[0],e,n):(ft(e,"E043",`Union type '${ie(t)}' cannot be soundly lowered to FieldSpec`,t.location),null)}case"arrayType":{let o=Z(t.elementType,e,n);return o?{type:"array",required:!0,items:o}:null}case"recordType":return{type:"object",required:!0};case"literalType":return typeof t.value=="string"?{type:"string",required:!0}:typeof t.value=="number"?{type:"number",required:!0}:typeof t.value=="boolean"?{type:"boolean",required:!0}:{type:"null",required:!0};case"objectType":{let o={};for(let r of t.fields){let i=Z(r.typeExpr,e,n);if(!i)return null;o[r.name]={...i,required:!r.optional}}return{type:"object",required:!0,fields:o}}}}function ft(t,e,n,o){t.diagnostics.push({severity:"error",code:e,message:n,location:o})}function ie(t){switch(t.kind){case"simpleType":return t.name;case"unionType":return t.types.map(e=>ie(e)).join(" | ");case"arrayType":return`Array<${ie(t.elementType)}>`;case"recordType":return`Record<${ie(t.keyType)}, ${ie(t.valueType)}>`;case"literalType":return JSON.stringify(t.value);case"objectType":return`{ ${t.fields.map(e=>`${e.name}${e.optional?"?":""}: ${ie(e.typeExpr)}`).join("; ")} }`}}function Ne(t,e,n=[]){if(t.kind!=="ref")return t;if(n.includes(t.name))return null;let o=e.typeDefinitions.get(t.name);return o?Ne(o,e,[...n,t.name]):null}function W(t){switch(t.kind){case"primitive":return t.type;case"array":return`Array<${W(t.element)}>`;case"record":return`Record<${W(t.key)}, ${W(t.value)}>`;case"object":return`{ ${Object.entries(t.fields).map(([e,n])=>`${e}${n.optional?"?":""}: ${W(n.type)}`).join("; ")} }`;case"union":return t.types.map(e=>W(e)).join(" | ");case"literal":return JSON.stringify(t.value);case"ref":return t.name}}function ke(t,e,n){let o=Ne(e,n);if(!o)return!1;switch(o.kind){case"primitive":switch(o.type){case"null":return t===null;case"string":return typeof t=="string";case"number":return typeof t=="number";case"boolean":return typeof t=="boolean";case"object":return t!==null&&!Array.isArray(t)&&typeof t=="object";case"array":return Array.isArray(t);default:return!1}case"literal":return Object.is(t,o.value);case"array":return Array.isArray(t)&&t.every(r=>ke(r,o.element,n));case"record":return t!==null&&!Array.isArray(t)&&typeof t=="object"&&Object.values(t).every(r=>ke(r,o.value,n));case"object":if(t===null||Array.isArray(t)||typeof t!="object")return!1;for(let r of Object.keys(t))if(!(r in o.fields))return!1;for(let[r,i]of Object.entries(o.fields)){if(!(r in t)){if(!i.optional)return!1;continue}if(!ke(t[r],i.type,n))return!1}return!0;case"union":return o.types.some(r=>ke(t,r,n));case"ref":return!1}}function Te(t,e,n,o,r){if(t===void 0)return;let i=Ne(e,r);if(!i){r.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${W(e)}, got ${JSON.stringify(t)}`,location:o});return}if(i.kind==="union"){if(ke(t,i,r))return;r.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${W(i)}, got ${JSON.stringify(t)}`,location:o});return}switch(i.kind){case"primitive":{let a=Array.isArray(t)?"array":t===null?"null":typeof t;switch(i.type){case"null":t!==null&&J(r,n,"null",a,o);return;case"string":case"number":case"boolean":typeof t!==i.type&&J(r,n,i.type,a,o);return;case"object":(t===null||Array.isArray(t)||typeof t!="object")&&J(r,n,"object",a,o);return;case"array":Array.isArray(t)||J(r,n,"array",a,o);return}return}case"literal":Object.is(t,i.value)||r.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects literal ${JSON.stringify(i.value)}, got ${JSON.stringify(t)}`,location:o});return;case"array":if(!Array.isArray(t)){J(r,n,"array",t===null?"null":typeof t=="object"?"object":typeof t,o);return}for(let a=0;a<t.length;a+=1)Te(t[a],i.element,`${n}[${a}]`,o,r);return;case"record":if(t===null||Array.isArray(t)||typeof t!="object"){let a=Array.isArray(t)?"array":t===null?"null":typeof t;J(r,n,"object",a,o);return}for(let[a,s]of Object.entries(t))Te(s,i.value,`${n}.${a}`,o,r);return;case"object":if(t===null||Array.isArray(t)||typeof t!="object"){let a=Array.isArray(t)?"array":t===null?"null":typeof t;J(r,n,"object",a,o);return}for(let a of Object.keys(t))a in i.fields||r.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}.${a}' is not declared in ${W(i)}`,location:o});for(let[a,s]of Object.entries(i.fields)){if(!(a in t)){s.optional||r.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}.${a}' is required`,location:o});continue}Te(t[a],s.type,`${n}.${a}`,o,r)}return;case"ref":r.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${W(e)}, got ${JSON.stringify(t)}`,location:o});return}}function J(t,e,n,o,r){t.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${e}' expects ${n}, got ${o}`,location:r})}function Ue(t,e){switch(t.kind){case"literal":return t.value;case"arrayLiteral":return t.elements.map(n=>Ue(n,e));case"objectLiteral":{let n={};for(let o of t.properties)n[o.key]=Ue(o.value,e);return n}default:return}}function nr(t,e){let n=[],o=0;for(let i of t.members)if(i.kind==="computed"){let a=B(i.expression,e),s=ar(a);n.push({name:i.name,deps:s,expr:a,location:i.location,order:o}),o+=1}let r={};for(let i of or(n,e))r[i.name]={deps:i.deps,expr:i.expr};return{fields:r}}function or(t,e){if(t.length<=1)return[...t];let n=new Map(t.map(c=>[c.name,c])),o=new Map,r=new Map,i=new Map;for(let c of t)r.set(c.name,[]),i.set(c.name,0);for(let c of t){let l=Array.from(new Set(c.deps.filter(d=>n.has(d))));o.set(c.name,l),i.set(c.name,l.length);for(let d of l)r.get(d).push(c.name)}let a=t.filter(c=>(i.get(c.name)??0)===0).map(c=>c.name),s=[];for(;a.length>0;){let c=a.shift();s.push(n.get(c));for(let l of r.get(c)??[]){let d=(i.get(l)??0)-1;i.set(l,d),d===0&&rr(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=ir(l[0].name,o),p=d?d.join(" -> "):l.map(m=>m.name).join(", ");return ft(e,"E040",`Circular computed dependency: ${p}`,(d?n.get(d[0]):l[0]).location),[...t]}return s}function rr(t,e,n){let o=n.get(e)?.order??Number.MAX_SAFE_INTEGER,r=t.length;for(let i=0;i<t.length;i+=1){let a=n.get(t[i])?.order??Number.MAX_SAFE_INTEGER;if(o<a){r=i;break}}t.splice(r,0,e)}function ir(t,e){let n=new Set,o=[],r=new Set;function i(a){n.add(a),o.push(a),r.add(a);for(let s of e.get(a)??[])if(n.has(s)){if(r.has(s)){let c=o.indexOf(s);return[...o.slice(c),s]}}else{let c=i(s);if(c)return c}return o.pop(),r.delete(a),null}return i(t)}function ar(t){let e=new Set;function n(o){switch(o.kind){case"lit":case"sys":case"var":return;case"get":o.base===void 0?e.add(o.path.map(r=>r.name).join(".")):n(o.base);return;case"field":n(o.object);return;case"call":for(let r of o.args)n(r);return;case"obj":for(let r of o.fields)n(r.value);return;case"arr":for(let r of o.elements)n(r);return}}return n(t),Array.from(e)}function sr(t,e){let n={};for(let o of t.members)if(o.kind==="action"){e.currentAction=o.name,e.onceIntentCounters.set(o.name,0);let r=new Set;for(let p of o.params)r.add(p.name);e.actionParams.set(o.name,r);let i=o.params.map(p=>p.name),a=nn(o.body,e),s,c;if(o.params.length>0){let p={},m={};for(let f of o.params){let N=Z(f.typeExpr,e);N&&(p[f.name]=structuredClone(N),m[f.name]={type:V(f.typeExpr),optional:!1})}s={type:"object",required:!0,fields:p},c={kind:"object",fields:m}}let l;o.available&&(l=B(o.available,e));let d;o.dispatchable&&(d=B(o.dispatchable,e,{preferActionParams:!0})),n[o.name]={flow:a,input:s,inputType:c,params:i,available:l,dispatchable:d},e.currentAction=null}return n}function nn(t,e){return t.length===0?{kind:"seq",steps:[]}:t.length===1?Be(t[0],e):{kind:"seq",steps:t.map(n=>Be(n,e))}}function Be(t,e){switch(t.kind){case"when":return cr(t,e);case"once":return lr(t,e);case"onceIntent":return dr(t,e);case"patch":return pr(t,e);case"effect":return ur(t,e);case"fail":return fr(t,e);case"stop":return hr(t,e);case"include":return{kind:"seq",steps:[]}}}function cr(t,e){let n=B(t.condition,e),o=nn(t.body,e);return{kind:"if",cond:n,then:o}}function lr(t,e){let n=ht(t.marker,e),o=Ee("meta","intentId"),r=ze("neq",[U(...on(n)),o]);if(t.condition){let s=B(t.condition,e);r=ze("and",[r,s])}let i={kind:"patch",op:"set",path:yt(n),value:o},a=t.body.map(s=>Be(s,e));return{kind:"if",cond:r,then:{kind:"seq",steps:[i,...a]}}}function dr(t,e){let n=e.currentAction??"unknown",o=e.onceIntentCounters.get(n)??0;e.onceIntentCounters.set(n,o+1);let r=Yo(`${n}:${o}:intent`),i=`$mel.guards.intent.${r}`,a=Ee("meta","intentId"),s=ze("neq",[U(...on(i)),a]);if(t.condition){let d=B(t.condition,e);s=ze("and",[s,d])}let c={kind:"patch",op:"merge",path:yt("$mel.guards.intent"),value:_e({[r]:a})},l=t.body.map(d=>Be(d,e));return{kind:"if",cond:s,then:{kind:"seq",steps:[c,...l]}}}function pr(t,e){let n=ht(t.path,e),o={kind:"patch",op:t.op,path:yt(n)};if(t.value){let r=B(t.value,e);if(o.value=r,t.op==="set"){let i=t.path.segments[0];if(i.kind==="propertySegment"){let a=e.stateFieldTypes.get(i.name);if(a){let s=a,c=t.path.segments;for(let l=1;l<c.length;l++){let d=c[l],p=s?Ne(s,e):null;if(!p){s=null;break}if(p.kind==="union"){let m=p.types.filter(f=>{let N=Ne(f,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"&&p.kind==="object"&&p.fields[d.name])s=p.fields[d.name].type;else if(d.kind==="propertySegment"&&p.kind==="record")s=p.value;else if(d.kind==="indexSegment"&&p.kind==="array")s=p.element;else{s=null;break}}if(s){let l=mr(t.value,e);if(l!==void 0){let d=t.path.segments.map(p=>p.kind==="propertySegment"?p.name:"[*]").join(".");Te(l,s,d,t.location,e)}}}}}}return o}function ur(t,e){let n={};for(let o of t.args)o.isPath?n[o.name]={kind:"lit",value:ht(o.value,e)}:n[o.name]=B(o.value,e);return{kind:"effect",type:t.effectType,params:n}}function mr(t,e){return Ue(t,e)}function fr(t,e){let n={kind:"fail",code:t.code};return t.message&&(n.message=B(t.message,e)),n}function hr(t,e){return{kind:"halt",reason:t.reason}}function yr(t){return t.replaceAll("\\","\\\\").replaceAll(".","\\.")}function Ge(...t){return t.map(yr).join(".")}function ht(t,e){let n=[];for(let r of t.segments)if(r.kind==="propertySegment")n.push(r.name);else{let i=B(r.index,e);i.kind==="lit"?n.push(String(i.value)):n.push("*")}let o=n[0];return e.stateFields.has(o)?Ge(...n):e.computedFields.has(o)?Ge(...n):e.currentAction&&e.actionParams.get(e.currentAction)?.has(o)?`input.${Ge(...n)}`:Ge(...n)}function yt(t){return Wo(t)}function ze(t,e){return{kind:"call",fn:t,args:e}}function on(t){return t.split(/(?<!\\)\./g).map(e=>e.replaceAll("\\.",".").replaceAll("\\\\","\\"))}function B(t,e,n={}){return w(t,{resolveIdentifier:o=>gr(o,e,n),resolveSystemIdent:o=>Er(o,e)})}function gr(t,e,n={}){return n.preferActionParams&&e.currentAction&&e.actionParams.get(e.currentAction)?.has(t)?U("input",t):e.stateFields.has(t)||e.computedFields.has(t)?U(t):e.currentAction&&e.actionParams.get(e.currentAction)?.has(t)?U("input",t):(e.diagnostics.push({severity:"error",code:"E_UNKNOWN_IDENT",message:`Unknown identifier '${t}'`,location:{start:{line:0,column:0,offset:0},end:{line:0,column:0,offset:0}}}),U(t))}function Er(t,e){let[n,...o]=t;switch(n){case"system":case"meta":case"input":return Ee(n,...o);default:return e.diagnostics.push({severity:"error",code:"E_INVALID_SYSTEM",message:`Invalid system identifier namespace '$${n}'`,location:{start:{line:0,column:0,offset:0},end:{line:0,column:0,offset:0}}}),{kind:"lit",value:null}}}function kr(t){return Vo(t)}var Tr="@meta can attach only to domain, type, type field, state field, computed, or action declarations.",Nr="Action-parameter annotations are not part of the current MEL syntax.",rn="Annotation payloads must be JSON-like literals. MEL expressions are not allowed in @meta payloads.",an="Annotation payload nesting exceeds the current MEL limit of 2 levels.",br="Annotation target does not map to the emitted DomainSchema.",sn=2;function cn(t,e){let n=[],o=new Map,r=t.domain;ae(r.annotations,`domain:${r.name}`,n,o);for(let a of r.types)ae(a.annotations,`type:${a.name}`,n,o),se(a.typeExpr,a.name,0,n,o);for(let a of r.members)switch(a.kind){case"state":for(let s of a.fields)ae(s.annotations,`state_field:${s.name}`,n,o),ee(s.typeExpr,n);break;case"computed":ae(a.annotations,`computed:${a.name}`,n,o);break;case"action":ae(a.annotations,`action:${a.name}`,n,o),Sr(a,n);for(let s of a.params)ee(s.typeExpr,n);break;case"flow":break}let i={};for(let a of[...o.keys()].sort()){if(!Ar(e,a)){n.push(P("E057",br,wr(t,a)??r.location));continue}let s=o.get(a);s&&s.length>0&&(i[a]=Object.freeze(s.map(c=>vr(c))))}return{annotations:Object.freeze({schemaHash:e.hash,entries:Object.freeze(i)}),diagnostics:n}}function ae(t,e,n,o){if(!t||t.length===0)return;let r=[];for(let a of t){let s=a.payload===void 0?{ok:!0,value:void 0}:gt(a.payload,0,n);s.ok&&r.push({tag:a.tag,...s.value===void 0?{}:{payload:s.value}})}if(r.length===0)return;let i=o.get(e);if(i){i.push(...r);return}o.set(e,r)}function se(t,e,n,o,r){switch(t.kind){case"objectType":for(let i of t.fields)i.annotations?.length&&(n===0?ae(i.annotations,`type_field:${e}.${i.name}`,o,r):ln(i.annotations,o)),se(i.typeExpr,e,n+1,o,r);return;case"arrayType":se(t.elementType,e,n,o,r);return;case"recordType":se(t.keyType,e,n,o,r),se(t.valueType,e,n,o,r);return;case"unionType":for(let i of t.types)se(i,e,n,o,r);return;case"simpleType":case"literalType":return}}function ee(t,e){switch(t.kind){case"objectType":for(let n of t.fields)ln(n.annotations,e),ee(n.typeExpr,e);return;case"arrayType":ee(t.elementType,e);return;case"recordType":ee(t.keyType,e),ee(t.valueType,e);return;case"unionType":for(let n of t.types)ee(n,e);return;case"simpleType":case"literalType":return}}function Sr(t,e){for(let n of t.params)xr(n,e)}function xr(t,e){if(t.annotations)for(let n of t.annotations)e.push(P("E054",Nr,n.location))}function ln(t,e){if(t)for(let n of t)e.push(P("E053",Tr,n.location))}function gt(t,e,n){switch(t.kind){case"literal":return t.literalType==="string"||t.literalType==="number"||t.literalType==="boolean"||t.literalType==="null"?{ok:!0,value:t.value}:(n.push(P("E055",rn,t.location)),{ok:!1});case"arrayLiteral":{if(e+1>sn)return n.push(P("E056",an,t.location)),{ok:!1};let o=[];for(let r of t.elements){let i=gt(r,e+1,n);if(!i.ok)return{ok:!1};o.push(i.value)}return{ok:!0,value:o}}case"objectLiteral":{if(e+1>sn)return n.push(P("E056",an,t.location)),{ok:!1};let o={};for(let r of t.properties){let i=gt(r.value,e+1,n);if(!i.ok)return{ok:!1};o[r.key]=i.value}return{ok:!0,value:o}}default:return n.push(P("E055",rn,t.location)),{ok:!1}}}function vr(t){return t.payload===void 0?Object.freeze({tag:t.tag}):Object.freeze({tag:t.tag,payload:Et(t.payload)})}function Et(t){if(Array.isArray(t))return Object.freeze(t.map(e=>Et(e)));if(t!==null&&typeof t=="object"){let e={};for(let[n,o]of Object.entries(t))e[n]=Et(o);return Object.freeze(e)}return t}function Ar(t,e){let n=e.indexOf(":");if(n<0)return!1;let o=e.slice(0,n),r=e.slice(n+1);switch(o){case"domain":return t.meta?.name===r||t.id===`mel:${r.toLowerCase()}`;case"type":return Object.hasOwn(t.types,r);case"type_field":{let i=r.indexOf(".");if(i<=0||i!==r.lastIndexOf("."))return!1;let a=r.slice(0,i),s=r.slice(i+1),c=t.types[a];return!c||c.definition.kind!=="object"?!1:Object.hasOwn(c.definition.fields,s)}case"state_field":return Object.hasOwn(t.state.fields,r);case"computed":return Object.hasOwn(t.computed.fields,r);case"action":return Object.hasOwn(t.actions,r);default:return!1}}function wr(t,e){let n=e.indexOf(":");if(n<0)return null;let o=e.slice(0,n),r=e.slice(n+1),i=t.domain;if(o==="domain"&&i.name===r)return i.location;if(o==="type")return i.types.find(a=>a.name===r)?.location??null;if(o==="type_field"){let a=r.indexOf(".");if(a<=0)return null;let s=r.slice(0,a),c=r.slice(a+1),l=i.types.find(d=>d.name===s);return!l||l.typeExpr.kind!=="objectType"?l?.location??null:l.typeExpr.fields.find(d=>d.name===c)?.location??l.location}if(o==="state_field"){for(let a of i.members){if(a.kind!=="state")continue;let s=a.fields.find(c=>c.name===r);if(s)return s.location}return null}return o==="computed"?i.members.find(a=>a.kind==="computed"&&a.name===r)?.location??null:o==="action"?i.members.find(a=>a.kind==="action"&&a.name===r)?.location??null:null}var kt=16;function T(t){return structuredClone(t)}function A(t,e,n,o,r){let i=`${n}:${r.start.offset}:${r.end.offset}:${o}`;e.has(i)||(e.add(i),t.push(P(n,o,r)))}function Cr(t){let e=new Map,n=new Set,o=new Map,r=new Set,i=new Map;for(let a of t.types)o.set(a.name,a);for(let a of t.members)switch(a.kind){case"state":for(let s of a.fields)e.set(s.name,s.typeExpr);break;case"computed":n.add(a.name);break;case"action":r.add(a.name);break;case"flow":i.has(a.name)||i.set(a.name,a);break}return{stateTypes:e,computedNames:n,typeDefs:o,actionNames:r,flows:i}}function Pr(t){let e=new Map;for(let n of t.params)e.set(n.name,n.typeExpr);return e}function Ir(t){let e=new Map;for(let n of t.params)e.set(n.name,n.typeExpr);return e}function Mr(t,e,n,o){let r=new Map;for(let i of e.flows.values()){r.set(i.name,[]),e.actionNames.has(i.name)&&A(n,o,"E022",`Flow '${i.name}' conflicts with action '${i.name}'.`,i.location);for(let s of i.params)(e.stateTypes.has(s.name)||e.computedNames.has(s.name)||e.typeDefs.has(s.name))&&A(n,o,"E021",`Flow parameter '${s.name}' conflicts with a top-level identifier.`,s.location);let a=Pr(i);for(let s of i.body)Rr(s,i.name,a,e,n,o,r.get(i.name))}for(let i of t.members)if(i.kind==="action"){let a=Ir(i);for(let s of i.body)Dr(s,a,e,n,o)}return r}function Dr(t,e,n,o,r){switch(t.kind){case"include":He(t,e,n,o,r);break;case"when":for(let i of t.body)le(i,e,n,o,r);break;case"once":for(let i of t.body)le(i,e,n,o,r);break;case"onceIntent":for(let i of t.body)le(i,e,n,o,r);break;case"fail":case"stop":break}}function le(t,e,n,o,r){switch(t.kind){case"include":A(o,r,"E016","include is only allowed at action or flow body top-level.",t.location),He(t,e,n,o,r);break;case"when":for(let i of t.body)le(i,e,n,o,r);break;case"once":for(let i of t.body)le(i,e,n,o,r);break;case"onceIntent":for(let i of t.body)le(i,e,n,o,r);break;case"patch":case"effect":case"fail":case"stop":break}}function Rr(t,e,n,o,r,i,a){switch(t.kind){case"include":He(t,n,o,r,i)&&a.push({target:t.flowName,location:t.location});break;case"when":for(let s of t.body)qe(s,e,n,o,r,i);break;case"once":A(r,i,"E017","once() is not allowed in flow bodies.",t.location);break;case"onceIntent":A(r,i,"E018","onceIntent is not allowed in flow bodies.",t.location);break;case"patch":A(r,i,"E019","patch is not allowed in flow bodies.",t.location);break;case"effect":A(r,i,"E020","effect is not allowed in flow bodies.",t.location);break}}function qe(t,e,n,o,r,i){switch(t.kind){case"include":A(r,i,"E016","include is only allowed at action or flow body top-level.",t.location),He(t,n,o,r,i);break;case"when":for(let a of t.body)qe(a,e,n,o,r,i);break;case"once":A(r,i,"E017","once() is not allowed in flow bodies.",t.location);for(let a of t.body)qe(a,e,n,o,r,i);break;case"onceIntent":A(r,i,"E018","onceIntent is not allowed in flow bodies.",t.location);for(let a of t.body)qe(a,e,n,o,r,i);break;case"patch":A(r,i,"E019","patch is not allowed in flow bodies.",t.location);break;case"effect":A(r,i,"E020","effect is not allowed in flow bodies.",t.location);break;case"fail":case"stop":break}}function He(t,e,n,o,r){let i=n.flows.get(t.flowName);if(!i)return A(o,r,"E015",`'${t.flowName}' is not a declared flow.`,t.location),!1;if(t.args.length!==i.params.length)return A(o,r,"E023",`include '${t.flowName}' expected ${i.params.length} argument(s), got ${t.args.length}.`,t.location),!0;for(let a=0;a<t.args.length;a+=1){let s=t.args[a],c=i.params[a],l=be(s,e,n);if(!l)continue;ce(l,c.typeExpr,n)===!1&&A(o,r,"E024",`include '${t.flowName}' argument ${a+1} is not assignable to parameter '${c.name}'.`,s.location)}return!0}function Or(t,e,n,o){function r(i,a,s){s.add(i);for(let c of t.get(i)??[]){if(a+1>kt){A(n,o,"E014",`Include expansion depth exceeds limit (${kt}).`,c.location);continue}if(s.has(c.target)){A(n,o,"E013","Circular include detected.",c.location);continue}r(c.target,a+1,new Set(s))}}for(let i of e.flows.keys())r(i,1,new Set)}function M(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=>M(n,e))};case"binary":return{...T(t),left:M(t.left,e),right:M(t.right,e)};case"unary":return{...T(t),operand:M(t.operand,e)};case"ternary":return{...T(t),condition:M(t.condition,e),consequent:M(t.consequent,e),alternate:M(t.alternate,e)};case"propertyAccess":return{...T(t),object:M(t.object,e)};case"indexAccess":return{...T(t),object:M(t.object,e),index:M(t.index,e)};case"objectLiteral":return{...T(t),properties:t.properties.map(n=>({...T(n),value:M(n.value,e)}))};case"arrayLiteral":return{...T(t),elements:t.elements.map(n=>M(n,e))}}}function Lr(t,e){switch(t.kind){case"when":return[dn(t,e)];case"fail":return[{...T(t),message:t.message?M(t.message,e):void 0}];case"stop":return[T(t)];case"patch":case"effect":case"once":case"onceIntent":case"include":return[]}}function dn(t,e){return{...T(t),condition:M(t.condition,e),body:t.body.flatMap(n=>Lr(n,e))}}function Fr(t,e,n){let o=new Map;for(let r=0;r<t.params.length;r+=1)o.set(t.params[r].name,M(e.args[r],n));return o}function jr(t,e,n,o,r){switch(t.kind){case"when":return[dn(t,n)];case"include":return pn(t,e,n,o,r);case"once":case"onceIntent":case"patch":case"effect":return[]}}function pn(t,e,n,o,r){let i=e.flows.get(t.flowName);if(!i||t.args.length!==i.params.length||o>kt||r.includes(t.flowName))return[];let a=Fr(i,t,n),s=[...r,t.flowName];return i.body.flatMap(c=>jr(c,e,a,o+1,s))}function de(t){switch(t.kind){case"when":return[{...T(t),body:t.body.flatMap(e=>de(e))}];case"once":return[{...T(t),body:t.body.flatMap(e=>de(e))}];case"onceIntent":return[{...T(t),body:t.body.flatMap(e=>de(e))}];case"include":return[];case"patch":case"effect":case"fail":case"stop":return[T(t)]}}function _r(t,e,n){switch(t.kind){case"include":return pn(t,e,new Map,n,[]);case"when":return[{...T(t),body:t.body.flatMap(o=>de(o))}];case"once":return[{...T(t),body:t.body.flatMap(o=>de(o))}];case"onceIntent":return[{...T(t),body:t.body.flatMap(o=>de(o))}];case"fail":case"stop":return[T(t)]}}function $r(t,e){let n=[];for(let o of t.domain.members)switch(o.kind){case"state":case"computed":n.push(T(o));break;case"action":n.push({...T(o),body:o.body.flatMap(r=>_r(r,e,1))});break;case"flow":break}return{...T(t),domain:{...T(t.domain),types:t.domain.types.map(o=>T(o)),members:n}}}function be(t,e,n){switch(t.kind){case"literal":return{kind:"literalType",value:t.value,location:t.location};case"identifier":return e.get(t.name)??n.stateTypes.get(t.name)??null;case"propertyAccess":{let o=be(t.object,e,n);return un(o,t.property,n)}case"indexAccess":{let o=be(t.object,e,n);return mn(o,n)}case"objectLiteral":return{kind:"objectType",fields:t.properties.map(o=>{let r=be(o.value,e,n);return r?{kind:"typeField",name:o.key,typeExpr:r,optional:!1,location:o.location}:null}).filter(o=>o!==null),location:t.location};case"arrayLiteral":{if(t.elements.length===0)return null;let o=be(t.elements[0],e,n);return o?{kind:"arrayType",elementType:o,location:t.location}:null}case"systemIdent":case"functionCall":case"binary":case"unary":case"ternary":case"iterationVar":return null}}function Se(t,e,n=new Set){return t?t.kind==="simpleType"&&e.typeDefs.has(t.name)?n.has(t.name)?null:(n.add(t.name),Se(e.typeDefs.get(t.name).typeExpr,e,n)):t:null}function un(t,e,n){let o=Se(t,n);if(!o)return null;if(o.kind==="objectType")return o.fields.find(i=>i.name===e)?.typeExpr??null;if(o.kind==="unionType")for(let r of o.types){if(r.kind==="simpleType"&&r.name==="null")continue;let i=un(r,e,n);if(i)return i}return null}function mn(t,e){let n=Se(t,e);if(!n)return null;if(n.kind==="arrayType")return n.elementType;if(n.kind==="recordType")return n.valueType;if(n.kind==="unionType")for(let o of n.types){if(o.kind==="simpleType"&&o.name==="null")continue;let r=mn(o,e);if(r)return r}return null}function ce(t,e,n){let o=Se(t,n),r=Se(e,n);if(!o||!r)return null;if(r.kind==="unionType"){let i=r.types.map(a=>ce(o,a,n));return i.includes(!0)?!0:i.every(a=>a===!1)?!1:null}if(o.kind==="unionType"){let i=o.types.map(a=>ce(a,r,n));return i.every(a=>a===!0)?!0:i.some(a=>a===!1)?!1:null}if(r.kind==="simpleType"){if(o.kind==="simpleType")return o.name===r.name;if(o.kind==="literalType")return r.name==="null"?o.value===null:typeof o.value===r.name}if(r.kind==="literalType")return o.kind!=="literalType"?!1:o.value===r.value;if(r.kind==="arrayType")return o.kind!=="arrayType"?!1:ce(o.elementType,r.elementType,n);if(r.kind==="objectType"){if(o.kind!=="objectType")return!1;for(let i of r.fields){let a=o.fields.find(c=>c.name===i.name);if(!a){if(i.optional)continue;return!1}let s=ce(a.typeExpr,i.typeExpr,n);if(s!==!0)return s}return!0}return r.kind==="recordType"?o.kind!=="recordType"?null:ce(o.valueType,r.valueType,n):null}function fn(t){let e=Cr(t.domain),n=[],o=new Set,r=Mr(t.domain,e,n,o);return Or(r,e,n,o),{program:$r(t,e),diagnostics:n}}var Gr=new Set(["$item","$index","$array"]);function gn(t){let e=Object.keys(t.state.fields).filter(d=>!d.startsWith("$")),n=Ur(t),o=new Set(n),r=new Set(e),i=Object.keys(t.actions),a=[...e.map(d=>({id:Tt(d),kind:"state",name:d})),...n.map(d=>({id:Nt(d),kind:"computed",name:d})),...i.map(d=>({id:yn(d),kind:"action",name:d}))],s=new Set,c=[],l=(d,p,m)=>{if(!d||!p)return;let f=`${d}|${m}|${p}`;s.has(f)||(s.add(f),c.push({from:d,to:p,relation:m}))};for(let d of n){let p=t.computed.fields[d];if(p)for(let m of p.deps)l(hn(m,t,o,r),Nt(d),"feeds")}for(let d of i){let p=t.actions[d],m=yn(d);for(let f of Br(p.flow,t))r.has(f)&&l(m,Tt(f),"mutates");if(p.available)for(let f of bn(p.available))l(hn(f,t,o,r),m,"unlocks")}return Hr({nodes:a,edges:c})}function Ur(t){let e=t.computed.fields,n=new Map,o=(r,i)=>{let a=n.get(r);if(a!==void 0)return a;if(i.has(r))return!1;i.add(r);let s=e[r];if(!s)return i.delete(r),n.set(r,!0),!0;for(let c of bn(s.expr)){if(Nn(c))return i.delete(r),n.set(r,!1),!1;let l=En(c,e);if(l!==null&&!o(l,i))return i.delete(r),n.set(r,!1),!1}return i.delete(r),n.set(r,!0),!0};return Object.keys(e).filter(r=>o(r,new Set))}function Br(t,e){let n=new Set,o=(r,i)=>{if(r)switch(r.kind){case"seq":r.steps.forEach(a=>o(a,i));return;case"if":o(r.then,i),o(r.else,i);return;case"patch":{let a=zr(r.path);a&&n.add(a);return}case"effect":{let a=qr(r.params.into);a&&n.add(a);return}case"call":{if(i.has(r.flow))return;let a=e.actions[r.flow];if(!a)return;let s=new Set(i);s.add(r.flow),o(a.flow,s);return}case"halt":case"fail":return}};return o(t,new Set),[...n]}function zr(t){let[e]=t;return!e||e.kind!=="prop"||e.name.startsWith("$")?null:e.name}function qr(t){return typeof t!="object"||t===null||t.kind!=="lit"||typeof t.value!="string"?null:kn(t.value)}function hn(t,e,n,o){let r=En(t,e.computed.fields);if(r!==null&&n.has(r))return Nt(r);if(Nn(t))return null;let i=kn(t);return!i||!o.has(i)?null:Tt(i)}function En(t,e){if(Object.prototype.hasOwnProperty.call(e,t))return t;if(!t.startsWith("computed."))return null;let n=t.slice(9);return Object.prototype.hasOwnProperty.call(e,n)?n:null}function kn(t){let e=Tn(t),n=e.startsWith("data.")?e.slice(5):e,o=/^([^.[\]]+)/.exec(n);if(!o)return null;let[r]=o.slice(1);return!r||r.startsWith("$")?null:r}function Tn(t){return t.startsWith("/")?t.slice(1).replace(/\//g,"."):t}function Nn(t){let e=Tn(t),n=e.startsWith("data.")?e.slice(5):e,r=/^([^.[\]]+)/.exec(n)?.[1]??"";return r.startsWith("$")?!Gr.has(r):!1}function bn(t){let e=[],n=new WeakSet,o=r=>{if(r==null)return;if(Array.isArray(r)){r.forEach(o);return}if(typeof r!="object")return;let i=r;if(!n.has(i)&&(n.add(i),i.kind!=="lit")){if(i.kind==="get"&&typeof i.path=="string"){e.push(i.path);return}for(let a of Object.values(i))o(a)}};return o(t),e}function Tt(t){return`state:${t}`}function Nt(t){return`computed:${t}`}function yn(t){return`action:${t}`}function Hr(t){return Object.freeze({nodes:Object.freeze(t.nodes.map(e=>Object.freeze(e))),edges:Object.freeze([...t.edges].sort(Kr).map(e=>Object.freeze(e)))})}function Kr(t,e){return t.from.localeCompare(e.from)||t.to.localeCompare(e.to)||t.relation.localeCompare(e.relation)}var Vr="Source-map target does not map to the emitted DomainSchema.",Wr="Source-map entry missing for emitted DomainSchema target.",Yr=new TextEncoder;function wn(t){return Object.freeze({coordinateUnit:"utf16",compilerVersion:t,emissionOptionsFingerprint:"default"})}function Cn(t,e,n,o){let r=[],i=new Map,a=t.domain,s=Jr(e,o.coordinateUnit);i.set(`domain:${a.name}`,me({target:{kind:"domain",domain:{name:a.name}},span:s(a.location)}));for(let l of a.types)i.set(`type:${l.name}`,me({target:{kind:"type",type:{name:l.name}},span:s(l.location)})),pe(l.typeExpr,l.name,0,i,s);for(let l of a.members)switch(l.kind){case"state":for(let d of l.fields)i.set(`state_field:${d.name}`,me({target:{kind:"state_field",field:{name:d.name}},span:s(d.location)}));break;case"computed":i.set(`computed:${l.name}`,me({target:{kind:"computed",computed:{name:l.name}},span:s(l.location)}));break;case"action":i.set(`action:${l.name}`,me({target:{kind:"action",action:{name:l.name}},span:s(l.location)}));break;case"flow":break}let c={};for(let l of[...i.keys()].sort()){if(!Xr(n,l)){r.push(P("E058",Vr,Sn(t,l)??a.location));continue}let d=i.get(l);d&&(c[l]=d)}for(let l of Qr(t,n))Object.hasOwn(c,l)||r.push(P("E058",Wr,Sn(t,l)??a.location));return{sourceMap:Object.freeze({schemaHash:n.hash,sourceHash:vn(e),format:"manifesto/source-map-v1",coordinateUnit:o.coordinateUnit,emissionFingerprint:vn(`${o.coordinateUnit}\0${o.compilerVersion}\0${o.emissionOptionsFingerprint}`),entries:Object.freeze(c)}),diagnostics:r}}function pe(t,e,n,o,r){switch(t.kind){case"objectType":for(let i of t.fields)n===0&&o.set(`type_field:${e}.${i.name}`,me({target:{kind:"type_field",type:{name:e},field:{name:i.name}},span:r(i.location)})),pe(i.typeExpr,e,n+1,o,r);return;case"arrayType":pe(t.elementType,e,n+1,o,r);return;case"recordType":pe(t.keyType,e,n+1,o,r),pe(t.valueType,e,n+1,o,r);return;case"unionType":for(let i of t.types)pe(i,e,n+1,o,r);return;case"simpleType":case"literalType":return}}function Qr(t,e){let n=new Set;n.add(`domain:${t.domain.name}`);for(let[o,r]of Object.entries(e.types))if(n.add(`type:${o}`),r.definition.kind==="object")for(let i of Object.keys(r.definition.fields))n.add(`type_field:${o}.${i}`);for(let o of Object.keys(e.state.fields))n.add(`state_field:${o}`);for(let o of Object.keys(e.computed.fields))n.add(`computed:${o}`);for(let o of Object.keys(e.actions))n.add(`action:${o}`);return[...n].sort()}function Xr(t,e){let n=e.indexOf(":");if(n<0)return!1;let o=e.slice(0,n),r=e.slice(n+1);switch(o){case"domain":return t.meta?.name===r||t.id===`mel:${r.toLowerCase()}`;case"type":return Object.hasOwn(t.types,r);case"type_field":{let i=r.indexOf(".");if(i<=0||i!==r.lastIndexOf("."))return!1;let a=r.slice(0,i),s=r.slice(i+1),c=t.types[a];return!c||c.definition.kind!=="object"?!1:Object.hasOwn(c.definition.fields,s)}case"state_field":return Object.hasOwn(t.state.fields,r);case"computed":return Object.hasOwn(t.computed.fields,r);case"action":return Object.hasOwn(t.actions,r);default:return!1}}function Sn(t,e){let n=e.indexOf(":");if(n<0)return null;let o=e.slice(0,n),r=e.slice(n+1);switch(o){case"domain":return t.domain.name===r?t.domain.location:null;case"type":return t.domain.types.find(i=>i.name===r)?.location??null;case"type_field":{let i=r.indexOf(".");if(i<=0||i!==r.lastIndexOf("."))return null;let a=r.slice(0,i),s=r.slice(i+1),c=t.domain.types.find(l=>l.name===a);return c?ue(c.typeExpr,s,0):null}case"state_field":for(let i of t.domain.members){if(i.kind!=="state")continue;let a=i.fields.find(s=>s.name===r);if(a)return a.location}return null;case"computed":return t.domain.members.find(i=>i.kind==="computed"&&i.name===r)?.location??null;case"action":return t.domain.members.find(i=>i.kind==="action"&&i.name===r)?.location??null;default:return null}}function ue(t,e,n){switch(t.kind){case"objectType":for(let o of t.fields){if(n===0&&o.name===e)return o.location;let r=ue(o.typeExpr,e,n+1);if(r)return r}return null;case"arrayType":return ue(t.elementType,e,n+1);case"recordType":return ue(t.keyType,e,n+1)??ue(t.valueType,e,n+1);case"unionType":for(let o of t.types){let r=ue(o,e,n+1);if(r)return r}return null;case"simpleType":case"literalType":return null}}function Jr(t,e){return e==="utf16"?n=>Zr(n):n=>ei(n,t)}function Zr(t){return Object.freeze({start:Object.freeze({line:t.start.line,column:t.start.column}),end:Object.freeze({line:t.end.line,column:t.end.column})})}function ei(t,e){return Object.freeze({start:xn(t.start,e),end:xn(t.end,e)})}function xn(t,e){let n=An(e.slice(0,t.offset)),o=t.offset-(t.column-1),r=An(e.slice(0,o));return Object.freeze({line:t.line,column:n-r+1})}function me(t){return Object.freeze({target:ti(t.target),span:Object.freeze({start:Object.freeze({...t.span.start}),end:Object.freeze({...t.span.end})})})}function ti(t){switch(t.kind){case"domain":return Object.freeze({kind:t.kind,domain:Object.freeze({...t.domain})});case"type":return Object.freeze({kind:t.kind,type:Object.freeze({...t.type})});case"type_field":return Object.freeze({kind:t.kind,type:Object.freeze({...t.type}),field:Object.freeze({...t.field})});case"state_field":return Object.freeze({kind:t.kind,field:Object.freeze({...t.field})});case"computed":return Object.freeze({kind:t.kind,computed:Object.freeze({...t.computed})});case"action":return Object.freeze({kind:t.kind,action:Object.freeze({...t.action})})}}function vn(t){let e=2166136261;for(let n=0;n<t.length;n+=1)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return`fnv1a32:${e.toString(16).padStart(8,"0")}`}function An(t){return Yr.encode(t).length}import{sha256Sync as Ke}from"@manifesto-ai/core";function Pn(t){return t.kind==="literal"&&t.literalType==="boolean"&&t.value===!0}function fe(t){return w(t)}var Ve=class{constructor(e){this.deps=e;this.exprValidator=new St(e.mapLocation)}conditionComposer=new bt;exprValidator;collect(e,n,o,r){return this.collectPatchStatements(e,n,o,r)}collectPatchStatements(e,n,o,r){let i=[];for(let a of e){if(a.kind==="patch"){this.exprValidator.validatePath(a.path,n),a.value&&this.exprValidator.validateExpr(a.value,n),i.push({patch:a,condition:r});continue}if(a.kind==="when"){this.exprValidator.validateExpr(a.condition,n);let s=r;try{s=this.conditionComposer.and(r,this.deps.toMelExpr(a.condition))}catch(m){n.push({severity:"error",code:"E_LOWER",message:m.message,location:this.deps.mapLocation(a.condition.location)})}let c=Ke(`${o.actionName}:${o.whenCounter}:when`);o.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=xe(l),p=this.collectPatchStatements(a.body,n,o,void 0).map(m=>({patch:m.patch,condition:this.conditionComposer.and(d,m.condition)}));i.push({patch:{kind:"patch",op:"set",path:l,value:{kind:"literal",literalType:"boolean",value:!0,location:a.location},location:a.location},condition:s},...p,{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=xe(a.marker),l=a.marker,d=a.location,p={kind:"call",fn:"neq",args:[c,{kind:"sys",path:["meta","intentId"]}]};if(a.condition){this.exprValidator.validateExpr(a.condition,n);try{p=this.conditionComposer.and(p,this.deps.toMelExpr(a.condition))??p}catch(_){n.push({severity:"error",code:"E_LOWER",message:_.message,location:this.deps.mapLocation(a.condition.location)})}}s=this.conditionComposer.and(r,p);let m=Ke(`${o.actionName}:${o.onceCounter}:once`);o.onceCounter+=1;let f={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:d},{kind:"propertySegment",name:"__onceScopeGuards",location:d},{kind:"propertySegment",name:m,location:d}],location:d},N=xe(f),S=this.collectPatchStatements(a.body,n,o,N);i.push({patch:{kind:"patch",op:"set",path:f,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:f,location:d},condition:s});continue}if(a.kind==="onceIntent"){let s=Ke(`${o.actionName}:${o.onceCounter}:onceIntent`);o.onceCounter+=1;let c={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:a.location},{kind:"propertySegment",name:"__onceScopeGuards",location:a.location},{kind:"propertySegment",name:s,location:a.location}],location:a.location},l=xe(c),d=Ke(`${o.actionName}:${o.onceIntentCounter}:intent`);o.onceIntentCounter+=1;let p=a.location,f={kind:"call",fn:"neq",args:[xe({kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:p},{kind:"propertySegment",name:"guards",location:p},{kind:"propertySegment",name:"intent",location:p},{kind:"propertySegment",name:d,location:p}],location:p}),{kind:"sys",path:["meta","intentId"]}]};if(a.condition){this.exprValidator.validateExpr(a.condition,n);try{f=this.conditionComposer.and(f,this.deps.toMelExpr(a.condition))??f}catch(z){n.push({severity:"error",code:"E_LOWER",message:z.message,location:this.deps.mapLocation(a.condition.location)})}}let N=this.conditionComposer.and(r,f),S={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:p},{kind:"propertySegment",name:"guards",location:p},{kind:"propertySegment",name:"intent",location:p}],location:p},_=this.collectPatchStatements(a.body,n,o,l);i.push({patch:{kind:"patch",op:"set",path:c,value:{kind:"literal",literalType:"boolean",value:!0,location:p},location:p},condition:N},{patch:{kind:"patch",op:"merge",path:S,value:{kind:"objectLiteral",properties:[{kind:"objectProperty",key:d,value:{kind:"systemIdent",path:["meta","intentId"],location:p},location:p}],location:p},location:p},condition:l},..._,{patch:{kind:"patch",op:"unset",path:c,location:p},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 i}};function In(t){return{op:t.patch.op,path:ni(t.patch.path),...t.condition?{condition:t.condition}:void 0,...t.patch.value?{value:fe(t.patch.value)}:void 0}}function xe(t){let e=t.segments,n;for(let o of e){if(o.kind==="propertySegment"){let r={kind:"prop",name:o.name};n?n={kind:"call",fn:"field",args:[n,{kind:"lit",value:o.name}]}:n={kind:"get",path:[r]};continue}if(!n)throw new Error("Path cannot start with index access in compileMelPatch guard.");n={kind:"call",fn:"at",args:[n,fe(o.index)]}}if(!n)throw new Error("Empty patch guard path.");return n}function ni(t){return t.segments.map(e=>e.kind==="propertySegment"?{kind:"prop",name:e.name}:{kind:"expr",expr:fe(e.index)})}var bt=class{and(e,n){return e?n?{kind:"call",fn:"and",args:[e,n]}:e:n}},St=class{constructor(e){this.mapLocation=e}symbols={stateTypes:new Map,computedDecls:new Map,typeDefs:new Map,computedTypeCache:new Map,computedTypeInFlight:new Set};validatePath(e,n){for(let o of e.segments)o.kind==="indexSegment"&&this.validateExpr(o.index,n)}validateExpr(e,n){switch(e.kind){case"functionCall":(e.name==="eq"||e.name==="neq")&&e.args.length>=2&&this.validatePrimitiveEquality(e.args[0],e.args[1],e.location,n);for(let o of e.args)this.validateExpr(o,n);return;case"binary":(e.operator==="=="||e.operator==="!=")&&this.validatePrimitiveEquality(e.left,e.right,e.location,n),this.validateExpr(e.left,n),this.validateExpr(e.right,n);return;case"unary":this.validateExpr(e.operand,n);return;case"ternary":this.validateExpr(e.condition,n),this.validateExpr(e.consequent,n),this.validateExpr(e.alternate,n);return;case"propertyAccess":this.validateExpr(e.object,n);return;case"indexAccess":this.validateExpr(e.object,n),this.validateExpr(e.index,n);return;case"objectLiteral":for(let o of e.properties)this.validateExpr(o.value,n);return;case"arrayLiteral":for(let o of e.elements)this.validateExpr(o,n);return;case"literal":case"identifier":case"systemIdent":case"iterationVar":return}}validatePrimitiveEquality(e,n,o,r){let i=$(e,new Map,this.symbols),a=$(n,new Map,this.symbols);i!=="nonprimitive"&&a!=="nonprimitive"||r.push({severity:"error",code:"E_TYPE_MISMATCH",message:"eq/neq operands must be primitive types (null, boolean, number, string)",location:this.mapLocation(o)})}};function Dn(t){let e=[],n=0;for(let o of t)e.push(n),n+=o.length+1;return e}function Rn(t,e){return n=>On(n,t,e)}function xt(t,e,n){return t.map(o=>oi(o,e,n))}function oi(t,e,n){return{...t,location:On(t.location,e,n)}}function On(t,e,n){return{...t,start:Mn(t.start,e,n),end:Mn(t.end,e,n)}}function Mn(t,e,n){let o=t.line-3,r=e.length,i=Math.min(Math.max(o,1),r),a=n[i-1]??0,s=e[i-1]??"",c=Math.max(s.length+1,1),l=Math.min(Math.max(t.column-6,1),c);return{line:i,column:l,offset:Math.max(a+l-1,0)}}var ve="__compileMelPatch",ii="__patchDomain",ai=" ";function Ln(t,e){let n=[],o=[],r=[],i=t.split(`
9
- `),a=Dn(i),s=Rn(i,a),c=si(t,ve),l=performance.now(),d;try{let x=Ae(c);d=x.tokens;let C=xt(x.diagnostics.filter(Q=>Q.severity==="error"),i,a);if(C.length>0)return r.push(...C),n.push({phase:"lex",durationMs:performance.now()-l,details:{tokenCount:d.length}}),{ops:[],trace:n,warnings:o,errors:r}}catch(x){return r.push({severity:"error",code:"E_LEX",message:x.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:o,errors:r}}n.push({phase:"lex",durationMs:performance.now()-l,details:{tokenCount:d.length}});let p=performance.now(),m;try{let x=we(d),C=xt(x.diagnostics,i,a),Q=C.filter(We=>We.severity==="error"),F=C.filter(We=>We.severity!=="error");if(Q.length>0)return r.push(...Q),o.push(...F),n.push({phase:"parse",durationMs:performance.now()-p}),{ops:[],trace:n,warnings:o,errors:r};if(!x.program)return r.push({severity:"error",code:"E_PARSE",message:"Failed to parse MEL patch program",location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),o.push(...F),n.push({phase:"parse",durationMs:performance.now()-p}),{ops:[],trace:n,warnings:o,errors:r};m=x.program,o.push(...F)}catch(x){return r.push({severity:"error",code:"E_PARSE",message:x.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"parse",durationMs:performance.now()-p}),{ops:[],trace:n,warnings:o,errors:r}}n.push({phase:"parse",durationMs:performance.now()-p});let f=performance.now(),N={actionName:e.actionName,onceCounter:0,onceIntentCounter:0,whenCounter:0},S=m.domain.members.find(x=>x.kind==="action"&&x.name===ve);if(!S)return r.push({severity:"error",code:"E_ANALYZE",message:`Synthetic patch action '${ve}' not found during parsing`,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"analyze",durationMs:performance.now()-f}),{ops:[],trace:n,warnings:o,errors:r};let _=i.length+3+2;if(S.location.end.line!==_)return r.push({severity:"error",code:"E_PATCH_WRAPPER",message:`Malformed synthetic patch wrapper for action '${ve}'.`,location:s(S.location)}),n.push({phase:"analyze",durationMs:performance.now()-f}),{ops:[],trace:n,warnings:o,errors:r};let[z]=S.body;if(!z||z.kind!=="when"||!Pn(z.condition)||S.body.length!==1)return r.push({severity:"error",code:"E_PATCH_WRAPPER",message:`Malformed synthetic patch wrapper for action '${ve}'.`,location:s(S.location)}),n.push({phase:"analyze",durationMs:performance.now()-f}),{ops:[],trace:n,warnings:o,errors:r};let g=new Ve({mapLocation:s,toMelExpr:fe}).collect(z.body,r,N,void 0);if(r.length===0&&t.trim()!==""&&g.length===0&&r.push({severity:"error",code:"E_PATCH_WRAPPER",message:"Patch wrapper parsing produced no patch statements. The patch source may be malformed.",location:s(z.location)}),n.push({phase:"analyze",durationMs:performance.now()-f,details:{count:g.length}}),r.length>0)return{ops:[],trace:n,warnings:o,errors:r};let L=performance.now(),Y={mode:"action",allowSysPaths:e.allowSysPaths??{prefixes:["meta","input"]},fnTableVersion:e.fnTableVersion??"1.0",actionName:e.actionName},q=[];for(let x of g)try{let C=In(x);q.push(je(C,Y))}catch(C){C instanceof j?r.push({severity:"error",code:C.code,message:C.message,location:s(x.patch.location)}):C instanceof Error?r.push({severity:"error",code:"E_LOWER",message:C.message,location:s(x.patch.location)}):r.push({severity:"error",code:"E_LOWER",message:"Unknown lowering failure",location:s(x.patch.location)})}return n.push({phase:"lower",durationMs:performance.now()-L,details:{count:q.length}}),r.length>0?{ops:[],trace:n,warnings:o,errors:r}:{ops:q,trace:n,warnings:o,errors:r}}function si(t,e){let n=t.split(`
10
- `).map(o=>`${ai}${o}`).join(`
11
- `);return[`domain ${ii} {`,` action ${e}() {`," when true {",n," }"," }","}"].join(`
12
- `)}var ci="3.5.0";function li(t,e){let n=Fn(t,e);return{schema:n.schema,trace:n.trace,warnings:n.warnings,errors:n.errors}}function di(t,e){let n=Fn(t,e);return n.errors.length>0||!n.schema||!n.annotations||!n.sourceMap?{module:null,trace:n.trace,warnings:n.warnings,errors:n.errors}:{module:pi(n.schema,n.annotations,n.sourceMap),trace:n.trace,warnings:n.warnings,errors:n.errors}}function Fn(t,e){let n=[],o=[],r=[],i=performance.now(),a;try{let g=Ae(t);a=g.tokens;let L=g.diagnostics.filter(q=>q.severity==="error");if(L.length>0)return r.push(...L),n.push({phase:"lex",durationMs:performance.now()-i,details:{tokenCount:a.length}}),{program:null,schema:null,annotations:null,sourceMap:null,trace:n,warnings:o,errors:r};let Y=g.diagnostics.filter(q=>q.severity==="warning");o.push(...Y)}catch(g){let L=g;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()-i}),{program:null,schema:null,annotations:null,sourceMap:null,trace:n,warnings:o,errors:r}}n.push({phase:"lex",durationMs:performance.now()-i,details:{tokenCount:a.length}});let s=performance.now(),c;try{let g=we(a),L=g.diagnostics.filter(Y=>Y.severity==="error");if(L.length>0)return r.push(...L),n.push({phase:"parse",durationMs:performance.now()-s}),{program:null,schema:null,annotations:null,sourceMap:null,trace:n,warnings:o,errors:he(r)};c=g.program}catch(g){let L=g;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}),{program:null,schema:null,annotations:null,sourceMap:null,trace:n,warnings:o,errors:r}}n.push({phase:"parse",durationMs:performance.now()-s});let l=performance.now(),d=fn(c),p=d.diagnostics.filter(g=>g.severity==="error"),m=d.diagnostics.filter(g=>g.severity==="warning"),f=Ot(d.program),N=Vt(d.program),S=[...p,...f.diagnostics.filter(g=>g.severity==="error"),...N.diagnostics.filter(g=>g.severity==="error")],_=[...m,...f.diagnostics.filter(g=>g.severity==="warning"),...N.diagnostics.filter(g=>g.severity==="warning")];if(o.push(..._),n.push({phase:"analyze",durationMs:performance.now()-l}),S.length>0)return r.push(...S),{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:o,errors:he(r)};let z=performance.now(),te=tn(d.program);n.push({phase:"generate",durationMs:performance.now()-z});for(let g of te.diagnostics)g.severity==="warning"?o.push(g):r.push(g);if(te.schema){let g=cn(d.program,te.schema),L=g.diagnostics.filter(F=>F.severity==="warning"),Y=g.diagnostics.filter(F=>F.severity==="error");if(o.push(...L),r.push(...Y),Y.length>0)return{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:o,errors:he(r)};let q=wn(ci),x=Cn(d.program,t,te.schema,q),C=x.diagnostics.filter(F=>F.severity==="warning"),Q=x.diagnostics.filter(F=>F.severity==="error");return o.push(...C),r.push(...Q),Q.length>0?{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:o,errors:he(r)}:{program:d.program,schema:te.schema,annotations:g.annotations,sourceMap:x.sourceMap,trace:n,warnings:o,errors:he(r)}}return{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:o,errors:he(r)}}function pi(t,e,n){return Object.freeze({schema:t,graph:At(gn(t)),annotations:e,sourceMap:n})}function At(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){for(let e of t)At(e);return Object.freeze(t)}for(let e of Object.values(t))At(e);return Object.freeze(t)}var vt=10;function he(t){if(t.length<=vt)return t;let e=t.slice(0,vt);return e.push({severity:"error",code:"E_TOO_MANY",message:`... and ${t.length-vt} 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 ui(t,e){return Ln(t,e)}export{Ye as a,jn as b,mi as c,wt as d,Ct as e,Qe as f,Pt as g,It as h,hi as i,h as j,Xe as k,Ae as l,xi as m,vi as n,Mt as o,Je as p,Dt as q,wi as r,Ci as s,Rt as t,Ze as u,we as v,Ce as w,et as x,Ot as y,P as z,Lt as A,_i as B,_n as C,$i as D,Gi as E,it as F,Vt as G,at as H,st as I,ct as J,lt as K,lo as L,j as M,Oe as N,y as O,Le as P,dt as Q,po as R,pt as S,uo as T,u as U,Ro as V,Fo as W,je as X,Xo as Y,tn as Z,cn as _,fn as $,gn as aa,wn as ba,Cn as ca,li as da,di as ea,ui as fa};