@manifesto-ai/compiler 3.6.0 → 3.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -216,7 +216,7 @@ type CompileOptions = {
216
216
  | [MEL Syntax](../../docs/mel/SYNTAX.md) | Grammar and syntax |
217
217
  | [MEL Examples](../../docs/mel/EXAMPLES.md) | Example library |
218
218
  | [MEL Error Guide](../../docs/mel/ERROR-GUIDE.md) | Error codes and fixes |
219
- | [Compiler Spec](docs/SPEC-v1.0.0.md) | Current full compiler and MEL spec |
219
+ | [Compiler Spec](docs/SPEC-v1.1.0.md) | Current full compiler and MEL spec |
220
220
  | [Compiler FDR](docs/FDR-v0.5.0.md) | Design rationale |
221
221
  | [Compiler Compliance Suite](docs/compiler-SPEC-compilance-test-suite.md) | CCTS structure, rule modes, and execution guide |
222
222
 
@@ -2,6 +2,7 @@ import { type Diagnostic } from "./diagnostics/types.js";
2
2
  import type { DomainSchema } from "./generator/ir.js";
3
3
  import type { ProgramNode } from "./parser/ast.js";
4
4
  import type { SchemaGraph } from "./schema-graph.js";
5
+ import type { SourceMapIndex } from "./source-map.js";
5
6
  export type JsonLiteral = string | number | boolean | null | readonly JsonLiteral[] | {
6
7
  readonly [key: string]: JsonLiteral;
7
8
  };
@@ -18,6 +19,7 @@ export interface DomainModule {
18
19
  readonly schema: DomainSchema;
19
20
  readonly graph: SchemaGraph;
20
21
  readonly annotations: AnnotationIndex;
22
+ readonly sourceMap: SourceMapIndex;
21
23
  }
22
24
  export interface AnnotationExtractionResult {
23
25
  annotations: AnnotationIndex;
@@ -70,6 +70,7 @@ export interface CompileMelModuleResult {
70
70
  errors: Diagnostic[];
71
71
  }
72
72
  export type { Annotation, AnnotationIndex, DomainModule, JsonLiteral, LocalTargetKey, } from "../annotations.js";
73
+ export type { SourceMapEmissionContext, SourceMapEntry, SourceMapIndex, SourceMapPath, SourcePoint, SourceSpan, } from "../source-map.js";
73
74
  /**
74
75
  * Patch compilation options.
75
76
  */
@@ -5,5 +5,5 @@
5
5
  *
6
6
  * @see SPEC v0.4.0 §19
7
7
  */
8
- export type { Annotation, AnnotationIndex, CompileTrace, CompileMelDomainOptions, CompileMelDomainResult, CompileMelModuleOptions, CompileMelModuleResult, CompileMelPatchOptions, CompileMelPatchResult, DomainModule, JsonLiteral, LocalTargetKey, } from "./compile-mel.js";
8
+ export type { Annotation, AnnotationIndex, CompileTrace, CompileMelDomainOptions, CompileMelDomainResult, CompileMelModuleOptions, CompileMelModuleResult, CompileMelPatchOptions, CompileMelPatchResult, DomainModule, JsonLiteral, LocalTargetKey, SourceMapEmissionContext, SourceMapEntry, SourceMapIndex, SourceMapPath, SourcePoint, SourceSpan, } from "./compile-mel.js";
9
9
  export { compileMelDomain, compileMelModule, compileMelPatch } from "./compile-mel.js";
@@ -1,3 +1,3 @@
1
- import{a as f,b as g}from"./chunk-BGYS7OOZ.js";import{ba as d}from"./chunk-JNATEPDW.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-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(`
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};
@@ -1,4 +1,4 @@
1
- import{ba as t}from"./chunk-JNATEPDW.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-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)};
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};
@@ -0,0 +1,12 @@
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};
package/dist/esbuild.js CHANGED
@@ -1 +1 @@
1
- import{a as e}from"./chunk-SCNQFUUN.js";import"./chunk-BGYS7OOZ.js";import"./chunk-JNATEPDW.js";var t=e.esbuild,n=t;export{n as default,t as melPlugin};
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};