@lokascript/semantic 2.6.0 → 2.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.
Files changed (40) hide show
  1. package/dist/browser-ar.ar.global.js +5 -5
  2. package/dist/browser-bn.bn.global.js +4 -4
  3. package/dist/browser-de.de.global.js +4 -4
  4. package/dist/browser-east-asian.east-asian.global.js +3 -3
  5. package/dist/browser-en-tr.en-tr.global.js +4 -4
  6. package/dist/browser-es.es.global.js +4 -4
  7. package/dist/browser-fr.fr.global.js +3 -3
  8. package/dist/browser-hi.hi.global.js +3 -3
  9. package/dist/browser-id.id.global.js +4 -4
  10. package/dist/browser-it.it.global.js +3 -3
  11. package/dist/browser-ja.ja.global.js +4 -4
  12. package/dist/browser-ko.ko.global.js +5 -5
  13. package/dist/browser-lazy.lazy.global.js +1 -1
  14. package/dist/browser-ms.ms.global.js +4 -4
  15. package/dist/browser-pl.pl.global.js +4 -4
  16. package/dist/browser-priority.priority.global.js +1 -1
  17. package/dist/browser-qu.qu.global.js +5 -5
  18. package/dist/browser-ru.ru.global.js +5 -5
  19. package/dist/browser-sw.sw.global.js +4 -4
  20. package/dist/browser-th.th.global.js +3 -3
  21. package/dist/browser-tl.tl.global.js +4 -4
  22. package/dist/browser-tr.tr.global.js +4 -4
  23. package/dist/browser-uk.uk.global.js +5 -5
  24. package/dist/browser-vi.vi.global.js +3 -3
  25. package/dist/browser.global.js +22 -22
  26. package/dist/browser.global.js.map +1 -1
  27. package/dist/generators/index.d.ts +1 -0
  28. package/dist/generators/index.d.ts.map +1 -1
  29. package/dist/generators/profile-queries.d.ts +32 -0
  30. package/dist/generators/profile-queries.d.ts.map +1 -0
  31. package/dist/index.cjs +19 -0
  32. package/dist/index.cjs.map +1 -1
  33. package/dist/index.d.ts +1 -1
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +17 -0
  36. package/dist/index.js.map +1 -1
  37. package/package.json +3 -3
  38. package/src/generators/index.ts +3 -0
  39. package/src/generators/profile-queries.ts +53 -0
  40. package/src/index.ts +4 -0
@@ -1,6 +1,6 @@
1
- "use strict";var LokaScriptSemanticAr=(()=>{var kt=Object.defineProperty;var Ur=Object.getOwnPropertyDescriptor;var Hr=Object.getOwnPropertyNames;var Gr=Object.prototype.hasOwnProperty;var Yr=(o,e)=>{for(var t in e)kt(o,t,{get:e[t],enumerable:!0})},Zr=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Hr(e))!Gr.call(o,n)&&n!==t&&kt(o,n,{get:()=>e[n],enumerable:!(r=Ur(e,n))||r.enumerable});return o};var Jr=o=>Zr(kt({},"__esModule",{value:!0}),o);var ka={};Yr(ka,{ASTBuilder:()=>ze,DEFAULT_CONFIDENCE_THRESHOLD:()=>Yt,HIGH_CONFIDENCE_THRESHOLD:()=>Zt,VERSION:()=>ha,arabicProfile:()=>xe,arabicTokenizer:()=>mt,buildAST:()=>Qt,canParse:()=>Ft,createCommandNode:()=>G,createEventHandler:()=>fe,createLiteral:()=>$,createPropertyPath:()=>se,createReference:()=>J,createSelector:()=>re,fromExplicit:()=>Ht,getCommandMapper:()=>Oe,getPatternsForLanguage:()=>Kr,getPatternsForLanguageAndCommand:()=>xa,getProfile:()=>Qe,getSupportedLanguages:()=>ga,getTokenizer:()=>Xe,isExplicitSyntax:()=>me,isLanguageSupported:()=>Pt,parse:()=>Me,parseAny:()=>Gt,parseExplicit:()=>Re,registerCommandMapper:()=>wt,render:()=>Ge,renderExplicit:()=>Ye,toExplicit:()=>Ut,tokenize:()=>va,tryGetProfile:()=>V});var Yt=.5,Zt=.8;var Xr=new Set(["me","my","myself","you","your","yourself","it","its","result","event","target","body","detail","window","document"]),Qr=new Set(["and","or","not","no"]),en=new Set(["true","false","null","undefined"]),tn=new Set(["is","matches","match","contains","in"]),rn=new Set(["next","previous","closest","first","last"]),nn=new Set(["ms","s","seconds","second","milliseconds","millisecond","minutes","minute","hours","hour"]);function Jt(o){let e=[],t=0,r=1,n=1;function i(){if(e.length===0)return!0;let p=e[e.length-1];return p.type==="IDENTIFIER"&&tn.has(p.value.toLowerCase())||p.type==="IDENTIFIER"&&rn.has(p.value.toLowerCase())?!0:["OPERATOR","COMPARISON","LOGICAL","LPAREN","LBRACKET","LBRACE","COMMA","COLON"].includes(p.type)}function s(p=0){return o[t+p]??""}function a(){let p=o[t];return t++,p===`
2
- `?(r++,n=1):n++,p}function l(){for(;t<o.length&&/\s/.test(o[t]);)a()}function c(p){let h="";for(;t<o.length&&p(o[t]);)h+=a();return h}function d(p){let h=p;for(a();t<o.length&&o[t]!==p;)o[t]==="\\"&&t+1<o.length&&(h+=a()),h+=a();return t<o.length&&(h+=a()),h}function u(){let p="`";for(a();t<o.length&&o[t]!=="`";)o[t]==="\\"&&t+1<o.length&&(p+=a()),p+=a();return t<o.length&&(p+=a()),p}function f(){let p="<";for(a();t<o.length&&(p+=a(),!p.endsWith("/>")););return p}function m(p,h,y){return{type:p,value:h,start:y,end:t,line:r,column:n-h.length}}for(;t<o.length&&(l(),!(t>=o.length));){let p=t,h=s();if(h==="'"&&s(1)==="s"&&!/\w/.test(s(2))){a(),a(),e.push(m("POSSESSIVE","'s",p));continue}if(h==='"'||h==="'"){let y=d(h);e.push(m("STRING",y,p));continue}if(h==="`"){let y=u();e.push(m("TEMPLATE_LITERAL",y,p));continue}if(h==="<"&&/[a-zA-Z.#\[]/.test(s(1))){let y=f();e.push(m("QUERY_SELECTOR",y,p));continue}if(h==="#"&&i()){a();let y=c(g=>/[\w-]/.test(g));e.push(m("ID_SELECTOR","#"+y,p));continue}if(h==="."&&/[a-zA-Z_-]/.test(s(1))&&i()){a();let y=c(g=>/[\w-]/.test(g));e.push(m("CLASS_SELECTOR","."+y,p));continue}if(h==="@"&&/[a-zA-Z_]/.test(s(1))){a();let y=c(g=>/[\w-]/.test(g));e.push(m("ATTRIBUTE_REF","@"+y,p));continue}if(h==="["&&i()){let y=s(1);if(y==="@"||/[a-zA-Z]/.test(y)){let g="";for(g+=a();t<o.length&&o[t]!=="]";)o[t]==='"'||o[t]==="'"?g+=d(o[t]):g+=a();t<o.length&&(g+=a()),e.push(m("ATTRIBUTE_SELECTOR",g,p));continue}}if(h==="["){a(),e.push(m("LBRACKET","[",p));continue}if(h==="]"){a(),e.push(m("RBRACKET","]",p));continue}if(/\d/.test(h)){let y=c(E=>/[\d.]/.test(E)),g=t,S=c(E=>/[a-zA-Z]/.test(E));nn.has(S)?e.push(m("TIME_EXPRESSION",y+S,p)):(t=g,e.push(m("NUMBER",y,p)));continue}if(h==="("){a(),e.push(m("LPAREN","(",p));continue}if(h===")"){a(),e.push(m("RPAREN",")",p));continue}if(h==="{"){a(),e.push(m("LBRACE","{",p));continue}if(h==="}"){a(),e.push(m("RBRACE","}",p));continue}if(h===","){a(),e.push(m("COMMA",",",p));continue}if(h===":"){a(),e.push(m("COLON",":",p));continue}if(h==="."){a(),e.push(m("DOT",".",p));continue}if(h==="+"||h==="-"||h==="*"||h==="/"||h==="%"){a(),e.push(m("OPERATOR",h,p));continue}if(h==="="||h==="!"||h==="<"||h===">"){let y=a();s()==="="&&(y+=a()),e.push(m("COMPARISON",y,p));continue}if(/[a-zA-Z_$]/.test(h)){let y=c(S=>/[\w$]/.test(S)),g=y.toLowerCase();Xr.has(g)?e.push(m("CONTEXT_VAR",y,p)):Qr.has(g)?e.push(m("LOGICAL",y,p)):en.has(g)?e.push(m("BOOLEAN",y,p)):e.push(m("IDENTIFIER",y,p));continue}a()}return e.push(m("EOF","",t)),e}var on=new Set(["my","its","your"]),an=new Set(["is","matches","match","contains","in","exists","does"]),sn=new Set(["next","previous","closest","first","last"]),Je=class{constructor(){this.tokens=[];this.current=0}parse(e){try{return this.tokens=Jt(e),this.current=0,this.isAtEnd()?{success:!1,error:"Empty expression"}:{success:!0,node:this.parseExpression(),consumed:this.current}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Parse error"}}}peek(){return this.tokens[this.current]??{type:"EOF",value:"",start:0,end:0}}peekAt(e){return this.tokens[this.current+e]??{type:"EOF",value:"",start:0,end:0}}previous(){return this.tokens[this.current-1]??{type:"EOF",value:"",start:0,end:0}}isAtEnd(){return this.peek().type==="EOF"}advance(){return this.isAtEnd()||this.current++,this.previous()}check(e){return this.peek().type===e}checkValue(e){return this.peek().value.toLowerCase()===e.toLowerCase()}match(...e){for(let t of e)if(this.check(t))return this.advance(),!0;return!1}parseExpression(){return this.parseOr()}parseOr(){let e=this.parseAnd();for(;this.checkValue("or");){let t=this.advance().value,r=this.parseAnd();e=this.createBinaryExpression(t,e,r)}return e}parseAnd(){let e=this.parseEquality();for(;this.checkValue("and");){let t=this.advance().value,r=this.parseEquality();e=this.createBinaryExpression(t,e,r)}return e}parseEquality(){let e=this.parseComparison();for(;;){let t;if(this.match("COMPARISON"))t=this.previous().value;else if(this.checkValue("is")||this.checkValue("matches")||this.checkValue("match")||this.checkValue("contains")||this.checkValue("in")){let n=this.advance().value;t=n.toLowerCase()==="match"?"matches":n}else break;if(t.toLowerCase()==="is"){if(this.checkValue("empty")){this.advance(),e=this.createPostfixUnary("is empty",e);continue}if(this.checkValue("not")&&this.peekAt(1).value.toLowerCase()==="empty"){this.advance(),this.advance(),e=this.createPostfixUnary("is not empty",e);continue}}let r=this.parseComparison();e=this.createBinaryExpression(t,e,r)}return e}parseComparison(){let e=this.parseAddition();for(;this.check("COMPARISON");){let t=this.advance().value,r=this.parseAddition();e=this.createBinaryExpression(t,e,r)}return e}parseAddition(){let e=this.parseMultiplication();for(;this.peek().value==="+"||this.peek().value==="-";){let t=this.advance().value,r=this.parseMultiplication();e=this.createBinaryExpression(t,e,r)}return e}parseMultiplication(){let e=this.parseUnary();for(;this.peek().value==="*"||this.peek().value==="/"||this.peek().value==="%";){let t=this.advance().value,r=this.parseUnary();e=this.createBinaryExpression(t,e,r)}return e}parseUnary(){if(this.checkValue("not")||this.checkValue("no")||this.peek().value==="-"){let e=this.advance().value,t=this.parseUnary();return this.createUnaryExpression(e,t)}return this.parsePostfix()}parsePostfix(){let e=this.parsePrimary();for(;;)if(this.match("DOT"))if(this.check("IDENTIFIER")||this.check("CONTEXT_VAR")){let t=this.advance().value;e=this.createPropertyAccess(e,t)}else break;else if(this.match("POSSESSIVE"))if(this.check("IDENTIFIER")||this.check("CONTEXT_VAR")){let t=this.advance().value;e=this.createPossessiveExpression(e,t)}else break;else if(this.match("LPAREN")){let t=this.parseArguments();e=this.createCallExpression(e,t)}else if(this.match("LBRACKET")){let t=this.parseExpression();if(!this.match("RBRACKET"))throw new Error("Expected ] after index");e=this.createPropertyAccess(e,t)}else if(e.type==="contextReference"&&on.has(e.contextType??"")&&this.check("IDENTIFIER")&&!an.has(this.peek().value.toLowerCase())){let t=this.advance().value;e=this.createPropertyAccess(e,t)}else if(this.checkValue("exists")&&this.peekAt(1).type!=="LPAREN")this.advance(),e=this.createPostfixUnary("exists",e);else break;return e}parsePrimary(){let e=this.peek();if(this.match("NUMBER"))return this.createLiteral(parseFloat(e.value),"number",e);if(this.match("STRING")){let t=e.value.slice(1,-1);return this.createLiteral(t,"string",e)}if(this.match("BOOLEAN")){let t=e.value==="true"?!0:e.value==="false"?!1:e.value==="null"?null:void 0,r={true:"boolean",false:"boolean",null:"null",undefined:"undefined"};return this.createLiteral(t,r[e.value]??"string",e)}if(this.match("TEMPLATE_LITERAL"))return{type:"templateLiteral",value:e.value,start:e.start,end:e.end,line:e.line,column:e.column};if(this.match("TIME_EXPRESSION"))return this.parseTimeExpression(e);if(this.match("ID_SELECTOR"))return this.createSelector(e.value,"id",e);if(this.match("CLASS_SELECTOR"))return this.createSelector(e.value,"class",e);if(this.match("ATTRIBUTE_SELECTOR"))return this.createSelector(e.value,"attribute",e);if(this.match("ATTRIBUTE_REF"))return{type:"attributeAccess",attributeName:e.value.slice(1),start:e.start,end:e.end};if(this.match("QUERY_SELECTOR")){let t=e.value.slice(1,-2);return this.createSelector(t,"query",e)}if(this.match("CONTEXT_VAR"))return this.createContextReference(e.value,e);if(this.match("IDENTIFIER")){if(sn.has(e.value.toLowerCase())&&(this.check("CLASS_SELECTOR")||this.check("ID_SELECTOR")||this.check("QUERY_SELECTOR"))){let t=this.advance(),r=t.type==="QUERY_SELECTOR"?t.value.slice(1,-2):t.value,n=t.type==="CLASS_SELECTOR"?"class":t.type==="ID_SELECTOR"?"id":"query";return{type:"callExpression",callee:this.createIdentifier(e.value,e),arguments:[this.createSelector(r,n,t)],start:e.start,end:t.end}}return this.createIdentifier(e.value,e)}if(this.match("LPAREN")){let t=this.parseExpression();if(!this.match("RPAREN"))throw new Error("Expected ) after expression");return t}if(this.match("LBRACKET"))return this.parseArrayLiteral();if(this.match("LBRACE"))return this.parseObjectLiteral();throw new Error(`Unexpected token: ${e.value}`)}parseArguments(){let e=[];if(!this.check("RPAREN"))do e.push(this.parseExpression());while(this.match("COMMA"));if(!this.match("RPAREN"))throw new Error("Expected ) after arguments");return e}parseArrayLiteral(){let e=[],t=this.previous().start;if(!this.check("RBRACKET"))do e.push(this.parseExpression());while(this.match("COMMA"));if(!this.match("RBRACKET"))throw new Error("Expected ] after array elements");return{type:"arrayLiteral",elements:e,start:t,end:this.previous().end}}parseObjectLiteral(){let e=[],t=this.previous().start;if(!this.check("RBRACE"))do{let r;if(this.check("STRING"))r=this.advance().value.slice(1,-1);else if(this.check("IDENTIFIER"))r=this.advance().value;else throw new Error("Expected property name");if(!this.match("COLON"))throw new Error("Expected : after property name");let n=this.parseExpression();e.push({key:r,value:n})}while(this.match("COMMA"));if(!this.match("RBRACE"))throw new Error("Expected } after object properties");return{type:"objectLiteral",properties:e.map(r=>({type:"objectProperty",key:r.key,value:r.value})),start:t,end:this.previous().end}}parseTimeExpression(e){let t=e.value.match(/^(\d+(?:\.\d+)?)(ms|s|seconds?|milliseconds?|minutes?|hours?)$/i);if(!t)throw new Error(`Invalid time expression: ${e.value}`);let r=parseFloat(t[1]),n=t[2].toLowerCase();return{type:"timeExpression",value:r,unit:n,raw:e.value,start:e.start,end:e.end,line:e.line,column:e.column}}createLiteral(e,t,r){return{type:"literal",value:e,dataType:t,raw:r.value,start:r.start,end:r.end,line:r.line,column:r.column}}createSelector(e,t,r){return{type:"selector",value:e,selector:e,selectorType:t,start:r.start,end:r.end,line:r.line,column:r.column}}createContextReference(e,t){return{type:"contextReference",contextType:e,name:t.value,start:t.start,end:t.end,line:t.line,column:t.column}}createIdentifier(e,t){return{type:"identifier",name:e,start:t.start,end:t.end,line:t.line,column:t.column}}createPropertyAccess(e,t){return{type:"propertyAccess",object:e,property:typeof t=="string"?t:t.type==="identifier"?t.name:"",start:e.start,end:this.previous().end}}createPossessiveExpression(e,t){return{type:"possessiveExpression",object:e,property:t,start:e.start,end:this.previous().end}}createBinaryExpression(e,t,r){return{type:"binaryExpression",operator:e,left:t,right:r,start:t.start,end:r.end}}createUnaryExpression(e,t){return{type:"unaryExpression",operator:e,operand:t,prefix:!0,start:this.previous().start,end:t.end}}createPostfixUnary(e,t){return{type:"unaryExpression",operator:e,operand:t,prefix:!1,start:t.start,end:this.previous().end}}createCallExpression(e,t){return{type:"callExpression",callee:e,arguments:t,start:e.start,end:this.previous().end}}};function St(o){return new Je().parse(o)}function Z(o,e){switch(o.type){case"literal":return ln(o);case"selector":return cn(o,e);case"reference":return un(o);case"property-path":return dn(o,e);case"expression":return pn(o);case"flag":return{type:"literal",value:o.enabled};default:let t=o;throw new Error(`Unknown semantic value type: ${t.type}`)}}function ln(o){let e={type:"literal",value:o.value};return o.dataType?{...e,dataType:o.dataType}:e}function cn(o,e){return o.value.startsWith("@")&&/^[a-zA-Z_]/.test(o.value.slice(1))?{type:"attributeAccess",attributeName:o.value.slice(1)}:(e&&o.value.startsWith("*")&&/^[a-zA-Z-]/.test(o.value.slice(1))&&e.push(`Converted '${o.value}' to a CSS selector, but it looks like a CSS property name. CSS properties in commands like 'transition' should be literal strings, not selectors. Consider using expectedTypes: ['literal'] instead of ['literal', 'selector'] in the command schema.`),o.value.startsWith("<")?{type:"selector",value:o.value,selector:o.value,selectorType:o.selectorKind,raw:o.value}:{type:"selector",value:o.value,selector:o.value,selectorType:o.selectorKind})}function un(o){return{type:"contextReference",contextType:o.value,name:o.value}}function dn(o,e){return{type:"propertyAccess",object:Z(o.object,e),property:o.property}}function pn(o){let e=St(o.raw);return!e.success||!e.node?{type:"identifier",name:o.raw}:e.node}function bt(o,e){return o.roles.get(e)}function w(o,e,t){let r=bt(o,e);return r?Z(r,t):void 0}function R(o,e=[],t,r={}){let n={type:"command",name:o,args:e};return t&&Object.keys(t).length>0&&(n.modifiers=t),r.isBlocking&&(n.isBlocking=r.isBlocking),r.implicitTarget&&(n.implicitTarget=r.implicitTarget),r.semanticRoles&&Object.keys(r.semanticRoles).length>0&&(n.semanticRoles=r.semanticRoles),n}var mn={action:"toggle",toAST(o,e){let t=w(o,"patient"),r=w(o,"destination"),n=w(o,"duration"),i=t?[t]:[],s={};return r&&(s.on=r),n&&(s.for=n),R("toggle",i,s)}},fn={action:"add",toAST(o,e){let t=w(o,"patient"),r=w(o,"destination"),n=t?[t]:[],i={};return r&&(i.to=r),R("add",n,i)}},hn={action:"remove",toAST(o,e){let t=w(o,"patient"),r=w(o,"source"),n=t?[t]:[],i={};return r&&(i.from=r),R("remove",n,i)}},yn={action:"set",toAST(o,e){let t=w(o,"destination"),r=w(o,"patient"),n=w(o,"scope"),i=[],s={};return t&&i.push(t),r&&(s.to=r),n&&(s.on=n),R("set",i,s)}},gn={action:"show",toAST(o,e){let t=w(o,"destination"),r=w(o,"patient"),n=w(o,"duration"),i=[],s={},a=t??r;return a&&i.push(a),n&&(s.with=n),R("show",i,s)}},vn={action:"hide",toAST(o,e){let t=w(o,"destination"),r=w(o,"patient"),n=w(o,"duration"),i=[],s={},a=t??r;return a&&i.push(a),n&&(s.with=n),R("hide",i,s)}},xn={action:"increment",toAST(o,e){let t=w(o,"destination"),r=w(o,"patient"),n=w(o,"quantity"),i=[],s={},a=t??r;return a&&i.push(a),n&&(s.by=n),R("increment",i,s)}},kn={action:"decrement",toAST(o,e){let t=w(o,"destination"),r=w(o,"patient"),n=w(o,"quantity"),i=[],s={},a=t??r;return a&&i.push(a),n&&(s.by=n),R("decrement",i,s)}},Sn={action:"wait",toAST(o,e){let t=w(o,"event");if(t){let i={for:t},s=w(o,"source");return s&&(i.from=s),R("wait",[],i,{isBlocking:!0})}let r=w(o,"duration");return R("wait",r?[r]:[],void 0,{isBlocking:!0})}},bn={action:"log",toAST(o,e){let t=w(o,"patient"),r=[];return t&&r.push(t),R("log",r)}},wn={action:"put",toAST(o,e){let t=w(o,"patient"),r=w(o,"destination"),n=bt(o,"manner")??bt(o,"method"),i=t?[t]:[],s={};if(r){let a=n?.type==="literal"?String(n.value):"into";s[a]=r}return R("put",i,s)}},En={action:"fetch",toAST(o,e){let t=w(o,"source"),r=w(o,"method"),n=w(o,"responseType"),i=w(o,"patient"),s=t?[t]:[],a={};return r&&(a.with=r),n&&(a.as=n),i&&(a.body=i),R("fetch",s,a,{isBlocking:!0})}},Tn={action:"append",toAST(o,e){let t=w(o,"patient"),r=w(o,"destination"),n=t?[t]:[],i={};return r&&(i.to=r),R("append",n,i)}},Cn={action:"prepend",toAST(o,e){let t=w(o,"patient"),r=w(o,"destination"),n=t?[t]:[],i={};return r&&(i.to=r),R("prepend",n,i)}},Pn={action:"trigger",toAST(o,e){let t=w(o,"event"),r=w(o,"destination"),n=t?[t]:[],i={};return r&&(i.on=r),R("trigger",n,i)}},Nn={action:"send",toAST(o,e){let t=w(o,"event"),r=w(o,"destination"),n=w(o,"patient"),i=t?[t]:[],s={};return r&&(s.to=r),n&&(s.detail=n),R("send",i,s)}},Rn={action:"go",toAST(o,e){let t=w(o,"source"),r=w(o,"destination"),n=[],i={};return t&&n.push(t),r&&(i.to=r),R("go",n,i)}},Ln={action:"transition",toAST(o,e){let t=w(o,"patient"),r=w(o,"goal"),n=w(o,"duration"),i=w(o,"destination"),s=t?[t]:[],a={};return r&&(a.to=r),n&&(a.over=n),i&&(a.on=i),R("transition",s,a)}},An={action:"focus",toAST(o,e){let t=w(o,"destination"),r=w(o,"patient"),n=[],i={},s=t??r;return s&&n.push(s),R("focus",n,i)}},Mn={action:"blur",toAST(o,e){let t=w(o,"destination"),r=w(o,"patient"),n=[],i=t??r;return i&&n.push(i),R("blur",n)}},On={action:"get",toAST(o,e){let t=w(o,"source"),r=w(o,"patient"),n=[],i=t??r;return i&&n.push(i),R("get",n)}},zn={action:"take",toAST(o,e){let t=w(o,"patient"),r=w(o,"source"),n=t?[t]:[],i={};return r&&(i.from=r),R("take",n,i)}},Vn={action:"call",toAST(o,e){let t=w(o,"patient");return R("call",t?[t]:[])}},In={action:"return",toAST(o,e){let t=w(o,"patient");return R("return",t?[t]:[])}},_n={action:"halt",toAST(o,e){let t=o.roles.get("patient");return t?R("halt",[Z(t)]):R("halt",[])}},Bn={action:"throw",toAST(o,e){let t=w(o,"patient");return R("throw",t?[t]:[])}},Dn={action:"settle",toAST(o,e){let t=w(o,"destination"),r=w(o,"patient"),n=[],i=t??r;return i&&n.push(i),R("settle",n,void 0,{isBlocking:!0})}},$n={action:"swap",toAST(o,e){let t=w(o,"patient"),r=w(o,"source"),n=w(o,"destination"),i=w(o,"style"),s=[],a={};return t&&s.push(t),r&&s.push(r),n&&(a.on=n),i&&(a.with=i),R("swap",s,a)}},Wn={action:"morph",toAST(o,e){let t=w(o,"source"),r=w(o,"destination"),n=w(o,"patient"),i=[],s={},a=t??r;return a&&i.push(a),n&&(s.on=n),R("morph",i,s)}},jn={action:"clone",toAST(o,e){let t=w(o,"source"),r=w(o,"destination"),n=w(o,"patient"),i=[],s={},a=t??n;return a&&i.push(a),r&&(s.into=r),R("clone",i,s)}},qn={action:"make",toAST(o,e){let t=w(o,"patient");return R("make",t?[t]:[])}},Kn={action:"measure",toAST(o,e){let t=w(o,"patient"),r=w(o,"destination"),n=w(o,"source"),i=[],s={};t&&i.push(t);let a=r??n;return a&&(s.of=a),R("measure",i,s)}},Fn={action:"tell",toAST(o,e){let t=w(o,"destination"),r=w(o,"patient"),n=[],i=t??r;return i&&n.push(i),R("tell",n)}},Un={action:"js",toAST(o,e){let t=w(o,"patient");return R("js",t?[t]:[])}},Hn={action:"async",toAST(o,e){return R("async",[])}},Gn={action:"if",toAST(o,e){let t=w(o,"condition");return R("if",t?[t]:[])}},Yn={action:"unless",toAST(o,e){let t=w(o,"condition");return R("unless",t?[t]:[])}},Zn={action:"repeat",toAST(o,e){let t=w(o,"quantity"),r=w(o,"patient"),n=[],i=t??r;return i&&n.push(i),R("repeat",n)}},Jn={action:"for",toAST(o,e){let t=w(o,"patient"),r=w(o,"source"),n=t?[t]:[],i={};return r&&(i.in=r),R("for",n,i)}},Xn={action:"while",toAST(o,e){let t=w(o,"condition");return R("while",t?[t]:[])}},Qn={action:"continue",toAST(o,e){return R("continue",[])}},eo={action:"default",toAST(o,e){let t=w(o,"patient"),r=w(o,"source"),n=t?[t]:[],i={};return r&&(i.to=r),R("default",n,i)}},to={action:"init",toAST(o,e){return R("init",[])}},ro={action:"behavior",toAST(o,e){let t=w(o,"patient");return R("behavior",t?[t]:[])}},no={action:"install",toAST(o,e){let t=w(o,"patient"),r=w(o,"destination"),n=t?[t]:[],i={};return r&&(i.on=r),R("install",n,i)}},oo={action:"on",toAST(o,e){let t=w(o,"event"),r=w(o,"source"),n=t?[t]:[],i={};return r&&(i.from=r),R("on",n,i)}},Xt=new Map([["toggle",mn],["add",fn],["remove",hn],["set",yn],["show",gn],["hide",vn],["increment",xn],["decrement",kn],["wait",Sn],["log",bn],["put",wn],["fetch",En],["append",Tn],["prepend",Cn],["get",On],["take",zn],["trigger",Pn],["send",Nn],["on",oo],["go",Rn],["transition",Ln],["focus",An],["blur",Mn],["call",Vn],["return",In],["halt",_n],["throw",Bn],["settle",Dn],["swap",$n],["morph",Wn],["clone",jn],["measure",Kn],["make",qn],["tell",Fn],["default",eo],["js",Un],["async",Hn],["if",Gn],["unless",Yn],["repeat",Zn],["for",Jn],["while",Xn],["continue",Qn],["init",to],["behavior",ro],["install",no]]);function Oe(o){return Xt.get(o)}function wt(o){Xt.set(o.action,o)}var ze=class{constructor(e={}){this.warnings=[]}build(e){switch(e.kind){case"command":return this.buildCommand(e);case"event-handler":return this.buildEventHandler(e);case"conditional":return this.buildConditional(e);case"compound":return this.buildCompound(e);case"loop":return this.buildLoop(e);case"behavior":return this.buildBehavior(e);case"def":return this.buildDef(e);default:throw new Error(`Unknown semantic node kind: ${e.kind}`)}}buildBehavior(e){let t=e.eventHandlers.map(n=>this.buildEventHandler(n)),r={type:"behavior",name:e.name,parameters:[...e.parameters],eventHandlers:t};return e.initBlock&&e.initBlock.length>0&&(r.initBlock={type:"initBlock",commands:e.initBlock.map(n=>this.build(n))}),r}buildDef(e){return{type:"def",name:e.name,params:[...e.parameters],body:e.body.map(t=>this.build(t))}}buildCommand(e){let t=Oe(e.action),r;if(t){let n=t.toAST(e,this);if("ast"in n&&"warnings"in n){let i=n;this.warnings.push(...i.warnings),r=i.ast}else r=n}else r=this.buildGenericCommand(e);if(e.roles&&e.roles.size>0){let n={};for(let[i,s]of e.roles)n[i]=Z(s);Object.keys(n).length>0&&(r.semanticRoles=n)}return r}buildGenericCommand(e){let t=[],r={},n=["patient","source","quantity"],i=["destination","duration","method","style"];for(let a of n){let l=e.roles.get(a);l&&t.push(Z(l))}for(let a of i){let l=e.roles.get(a);if(l){let c=this.roleToModifierKey(a);r[c]=Z(l)}}let s={type:"command",name:e.action,args:t};return Object.keys(r).length>0?{...s,modifiers:r}:s}roleToModifierKey(e){return{destination:"on",duration:"for",source:"from",condition:"if",method:"via",style:"with"}[e]??e}buildEventHandler(e){let t=e.roles.get("event"),r="click",n,i=t?.type==="literal"?String(t.value):t?.type==="expression"?t.raw:t?.type==="reference"?t.value:void 0;i!==void 0&&(i.includes("|")||i.includes(" or ")?(n=i.split(/\s+or\s+|\|/).map(g=>g.trim()),r=n[0]):r=i);let s=e.body.map(g=>this.build(g)),a=e.roles.get("source"),l,c;a?.type==="selector"?(l=a.value,c=a.value):a?.type==="reference"?c=a.value:a?.type==="literal"&&(c=String(a.value));let d=e.roles.get("condition"),u=d?Z(d):void 0,f=e.roles.get("destination"),m=f?Z(f):void 0,p=e.eventModifiers,h=l;if(p?.from){let g=p.from;g.type==="selector"&&!l&&(h=g.value)}let y=e.parameterNames?[...e.parameterNames]:void 0;return{type:"eventHandler",event:r,commands:s,...n&&n.length>1?{events:n}:{},...h?{selector:h}:{},...c?{target:c}:{},...u?{condition:u}:{},...m?{watchTarget:m}:{},...y&&y.length>0?{args:y,params:y}:{}}}buildConditional(e){let t=e.roles.get("condition");if(!t)throw new Error("Conditional node missing condition");let r=Z(t),n=e.thenBranch.map(a=>this.build(a)),i=e.elseBranch?.map(a=>this.build(a)),s=[r,{type:"block",commands:n}];return i&&i.length>0&&s.push({type:"block",commands:i}),{type:"command",name:"if",args:s}}buildCompound(e){let t=e.statements.map(n=>this.build(n));return t.length===1?t[0]:t.length===0?{type:"block",commands:[]}:t.every(n=>n.type==="eventHandler")?{type:"Program",statements:t}:{type:"CommandSequence",commands:t}}buildLoop(e){let t=e.body.map(n=>this.build(n)),r=[{type:"identifier",name:e.loopVariant}];switch(e.loopVariant){case"times":{let n=e.roles.get("quantity");n&&r.push(Z(n));break}case"for":{e.loopVariable&&r.push({type:"string",value:e.loopVariable});let n=e.roles.get("source");n&&r.push(Z(n));break}case"while":case"until":{let n=e.roles.get("condition");n&&r.push(Z(n));break}case"forever":break}return r.push({type:"block",commands:t}),{type:"command",name:"repeat",args:r}}buildBlock(e){return{type:"block",commands:e.map(r=>this.build(r))}}};function Qt(o){let e=new ze;return{ast:e.build(o),warnings:e.warnings}}var ge=new Map,ve=new Map,Ve=new Map;var er=null;function rr(o,e){let t={...o};for(let r of Object.keys(e)){let n=e[r],i=o[r];n!==void 0&&(typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof i=="object"&&i!==null&&!Array.isArray(i)?t[r]=rr(i,n):t[r]=n)}return t}function nr(o,e){return rr(o,e)}function Et(o){if(!o.extends)return o;let e=ve.get(o.extends);if(!e)return console.warn(`[Registry] Profile '${o.code}' extends '${o.extends}' but base is not registered. Make sure to import the base language before the variant.`),o;let t=Et(e);return nr(t,o)}function Tt(o,e,t){ge.set(o,e),ve.set(o,t),Ve.delete(o)}var tr=new Map;function we(o){return o.split("-")[0]}function Ee(o){return o.includes("-")}function Xe(o){let e=ge.get(o);if(!e&&Ee(o)){let t=we(o);e=ge.get(t)}if(!e){let t=Array.from(ge.keys()).join(", ");throw new Error(`Language '${o}' is not registered. Registered languages: ${t||"none"}. Import the language module first: import '@lokascript/semantic/languages/${o}';`)}return e}function Qe(o){let e=ve.get(o);if(!e&&Ee(o)){let t=we(o);e=ve.get(t)}if(!e){let t=Array.from(ve.keys()).join(", ");throw new Error(`Language profile '${o}' is not registered. Registered languages: ${t||"none"}. Import the language module first: import '@lokascript/semantic/languages/${o}';`)}return Et(e)}function V(o){let e=ve.get(o);return!e&&Ee(o)&&(e=ve.get(we(o))),e?Et(e):void 0}function Ct(){return Array.from(ge.keys())}function Pt(o){return ge.has(o)?!0:Ee(o)?ge.has(we(o)):!1}function or(o,e){return Xe(e).tokenize(o)}function Q(o){let e=Ve.get(o);if(!e&&Ee(o)&&(e=Ve.get(we(o))),e)return e;let t=tr.get(o);if(!t&&Ee(o)&&(t=tr.get(we(o))),t)return Ve.set(o,t),t;if(!er)throw new Error(`No patterns registered for language '${o}'. Either import the language module or set a pattern generator.`);let r=Qe(o),n=er(r);return Ve.set(o,n),n}function Nt(o,e){return Q(o).filter(t=>t.command===e).sort((t,r)=>r.priority-t.priority)}var xe={code:"ar",name:"Arabic",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629",regions:["priority"],direction:"rtl",script:"arabic",wordOrder:"VSO",markingStrategy:"preposition",usesSpaces:!0,verb:{position:"start",subjectDrop:!0},references:{me:"\u0623\u0646\u0627",it:"\u0647\u0648",you:"\u0623\u0646\u062A",result:"\u0627\u0644\u0646\u062A\u064A\u062C\u0629",event:"\u0627\u0644\u062D\u062F\u062B",target:"\u0627\u0644\u0647\u062F\u0641",body:"\u062C\u0633\u0645"},possessive:{marker:"",markerPosition:"after-object",usePossessiveAdjectives:!0,specialForms:{me:"\u0644\u064A",it:"\u0644\u0647",you:"\u0644\u0643"},keywords:{\u0644\u064A:"me",\u0644\u0643:"you",\u0644\u0647:"it",\u0644\u0647\u0627:"it"}},roleMarkers:{destination:{primary:"\u0639\u0644\u0649",alternatives:["\u0641\u064A","\u0625\u0644\u0649","\u0628","\u0642\u0628\u0644","\u0628\u0639\u062F"],position:"before"},source:{primary:"\u0645\u0646",position:"before"},patient:{primary:"",position:"before"},style:{primary:"\u0628\u0640",alternatives:["\u0628\u0627\u0633\u062A\u062E\u062F\u0627\u0645"],position:"before"}},keywords:{toggle:{primary:"\u0628\u062F\u0651\u0644",alternatives:["\u0628\u062F\u0644","\u063A\u064A\u0651\u0631","\u063A\u064A\u0631"],normalized:"toggle"},add:{primary:"\u0623\u0636\u0641",alternatives:["\u0627\u0636\u0641"],normalized:"add"},remove:{primary:"\u0627\u062D\u0630\u0641",alternatives:["\u0623\u0632\u0644","\u0627\u0645\u0633\u062D"],normalized:"remove"},put:{primary:"\u0636\u0639",alternatives:["\u0627\u062C\u0639\u0644"],normalized:"put"},append:{primary:"\u0623\u0644\u062D\u0642",normalized:"append"},prepend:{primary:"\u0633\u0628\u0642",normalized:"prepend"},take:{primary:"\u062E\u0630",normalized:"take"},make:{primary:"\u0627\u0635\u0646\u0639",alternatives:["\u0623\u0646\u0634\u0626"],normalized:"make"},clone:{primary:"\u0627\u0633\u062A\u0646\u0633\u062E",normalized:"clone"},swap:{primary:"\u0627\u0633\u062A\u0628\u062F\u0644",alternatives:["\u062A\u0628\u0627\u062F\u0644"],normalized:"swap"},morph:{primary:"\u062D\u0648\u0651\u0644",normalized:"morph"},set:{primary:"\u0627\u0636\u0628\u0637",alternatives:["\u0639\u064A\u0651\u0646","\u062D\u062F\u062F"],normalized:"set"},get:{primary:"\u0627\u062D\u0635\u0644",normalized:"get"},increment:{primary:"\u0632\u0650\u062F",alternatives:["\u0632\u062F","\u0627\u0631\u0641\u0639"],normalized:"increment"},decrement:{primary:"\u0623\u0646\u0642\u0635",alternatives:["\u0627\u0646\u0642\u0635","\u0642\u0644\u0644"],normalized:"decrement"},log:{primary:"\u0633\u062C\u0644",normalized:"log"},show:{primary:"\u0627\u0638\u0647\u0631",alternatives:["\u0623\u0638\u0647\u0631","\u0627\u0639\u0631\u0636"],normalized:"show"},hide:{primary:"\u0627\u062E\u0641",alternatives:["\u0623\u062E\u0641\u0650","\u0627\u062E\u0641\u064A","\u0623\u062E\u0641"],normalized:"hide"},transition:{primary:"\u0627\u0646\u062A\u0642\u0627\u0644",alternatives:["\u0627\u0646\u062A\u0642\u0644"],normalized:"transition"},on:{primary:"\u0639\u0644\u0649",alternatives:["\u0639\u0646\u062F","\u0644\u062F\u0649","\u062D\u064A\u0646"],normalized:"on"},trigger:{primary:"\u062A\u0634\u063A\u064A\u0644",alternatives:["\u0623\u0637\u0644\u0642","\u0641\u0639\u0651\u0644"],normalized:"trigger"},send:{primary:"\u0623\u0631\u0633\u0644",normalized:"send"},focus:{primary:"\u062A\u0631\u0643\u064A\u0632",alternatives:["\u0631\u0643\u0632"],normalized:"focus"},blur:{primary:"\u0636\u0628\u0627\u0628\u064A\u0629",alternatives:["\u0634\u0648\u0634"],normalized:"blur"},empty:{primary:"\u0625\u0641\u0631\u0627\u063A",alternatives:["\u0641\u0627\u0631\u063A"],normalized:"empty"},open:{primary:"\u0627\u0641\u062A\u062D",normalized:"open"},close:{primary:"\u0623\u063A\u0644\u0642",normalized:"close"},select:{primary:"\u0638\u0644\u0644",normalized:"select"},clear:{primary:"\u0646\u0638\u0651\u0641",normalized:"clear"},reset:{primary:"\u0625\u0639\u0627\u062F\u0629-\u0636\u0628\u0637",alternatives:["\u0623\u0639\u062F-\u062A\u0639\u064A\u064A\u0646"],normalized:"reset"},breakpoint:{primary:"\u0646\u0642\u0637\u0629-\u062A\u0648\u0642\u0641",normalized:"breakpoint"},go:{primary:"\u0627\u0630\u0647\u0628",normalized:"go"},scroll:{primary:"\u0645\u0631\u0631",alternatives:["\u062A\u0645\u0631\u064A\u0631"],normalized:"scroll"},push:{primary:"\u0627\u062F\u0641\u0639",alternatives:["\u062F\u0641\u0639"],normalized:"push"},replace:{primary:"\u0627\u0633\u062A\u0628\u062F\u0644_\u0639\u0646\u0648\u0627\u0646",alternatives:["\u0623\u0639\u062F_\u062A\u0639\u064A\u064A\u0646_\u0639\u0646\u0648\u0627\u0646"],normalized:"replace"},process:{primary:"\u0639\u0627\u0644\u062C",alternatives:["\u0645\u0639\u0627\u0644\u062C\u0629"],normalized:"process"},wait:{primary:"\u0627\u0646\u062A\u0638\u0631",normalized:"wait"},fetch:{primary:"\u0627\u062D\u0636\u0631",alternatives:["\u062C\u0644\u0628"],normalized:"fetch"},settle:{primary:"\u0627\u0633\u062A\u0642\u0631",normalized:"settle"},if:{primary:"\u0625\u0630\u0627",normalized:"if"},unless:{primary:"\u0625\u0644\u0627",normalized:"unless"},when:{primary:"\u0639\u0646\u062F\u0645\u0627",normalized:"when"},where:{primary:"\u0623\u064A\u0646",normalized:"where"},else:{primary:"\u0648\u0625\u0644\u0627",alternatives:["\u062E\u0644\u0627\u0641 \u0630\u0644\u0643"],normalized:"else"},repeat:{primary:"\u0643\u0631\u0631",normalized:"repeat"},for:{primary:"\u0644\u0643\u0644",normalized:"for"},while:{primary:"\u0628\u064A\u0646\u0645\u0627",normalized:"while"},forever:{primary:"forever",normalized:"forever"},continue:{primary:"\u0648\u0627\u0635\u0644",normalized:"continue"},halt:{primary:"\u0623\u0648\u0642\u0641",normalized:"halt"},throw:{primary:"\u0627\u0631\u0645",alternatives:["\u0627\u0631\u0645\u0650"],normalized:"throw"},call:{primary:"\u0627\u0633\u062A\u062F\u0639",alternatives:["\u0646\u0627\u062F\u0650"],normalized:"call"},return:{primary:"\u0627\u0631\u062C\u0639",alternatives:["\u0639\u064F\u062F"],normalized:"return"},then:{primary:"\u062B\u0645",alternatives:["\u0628\u0639\u062F\u0647\u0627","\u062B\u0645\u0651"],normalized:"then"},and:{primary:"\u0648\u0623\u064A\u0636\u0627\u064B",alternatives:["\u0623\u064A\u0636\u0627\u064B"],normalized:"and"},end:{primary:"\u0646\u0647\u0627\u064A\u0629",alternatives:["\u0627\u0646\u062A\u0647\u0649","\u0627\u0644\u0646\u0647\u0627\u064A\u0629"],normalized:"end"},js:{primary:"\u062C\u0627\u0641\u0627\u0633\u0643\u0631\u0628\u062A",alternatives:["js"],normalized:"js"},async:{primary:"\u0645\u062A\u0632\u0627\u0645\u0646",normalized:"async"},tell:{primary:"\u0623\u062E\u0628\u0631",normalized:"tell"},default:{primary:"\u0627\u0641\u062A\u0631\u0627\u0636\u064A",normalized:"default"},init:{primary:"\u062A\u0647\u064A\u0626\u0629",alternatives:["\u0628\u062F\u0621"],normalized:"init"},behavior:{primary:"\u0633\u0644\u0648\u0643",normalized:"behavior"},install:{primary:"\u062A\u062B\u0628\u064A\u062A",alternatives:["\u062B\u0628\u0651\u062A"],normalized:"install"},measure:{primary:"\u0642\u064A\u0627\u0633",alternatives:["\u0642\u0650\u0633","\u0642\u0633"],normalized:"measure"},beep:{primary:"\u0635\u0641\u0651\u0631",normalized:"beep"},break:{primary:"\u062A\u0648\u0642\u0641",normalized:"break"},copy:{primary:"\u0627\u0646\u0633\u062E",normalized:"copy"},exit:{primary:"\u0627\u062E\u0631\u062C",normalized:"exit"},pick:{primary:"\u0627\u062E\u062A\u0631",normalized:"pick"},render:{primary:"\u0627\u0631\u0633\u0645",normalized:"render"},into:{primary:"\u0641\u064A",alternatives:["\u0625\u0644\u0649"],normalized:"into"},before:{primary:"\u0642\u0628\u0644",normalized:"before"},after:{primary:"\u0628\u0639\u062F",normalized:"after"},until:{primary:"\u062D\u062A\u0649",normalized:"until"},event:{primary:"\u062D\u062F\u062B",normalized:"event"},from:{primary:"\u0645\u0646",normalized:"from"},connect:{primary:"\u0627\u062A\u0635\u0644",alternatives:["\u0627\u062A\u0635\u0627\u0644"],normalized:"connect"},stream:{primary:"\u062A\u062F\u0641\u0642",alternatives:["\u0628\u062B"],normalized:"stream"},live:{primary:"\u0645\u0628\u0627\u0634\u0631",alternatives:["\u062D\u064A"],normalized:"live"},socket:{primary:"\u0645\u0642\u0628\u0633",alternatives:["websocket"],normalized:"socket"},bind:{primary:"\u0627\u0631\u0628\u0637",alternatives:["\u0631\u0628\u0637","bind"],normalized:"bind"},intercept:{primary:"\u0627\u0639\u062A\u0631\u0636",alternatives:["\u0627\u0639\u062A\u0631\u0627\u0636","intercept"],normalized:"intercept"},worker:{primary:"\u0639\u0627\u0645\u0644",alternatives:["worker"],normalized:"worker"},eventsource:{primary:"eventsource",alternatives:["\u0645\u0635\u062F\u0631-\u0627\u0644\u0623\u062D\u062F\u0627\u062B"],normalized:"eventsource"}},tokenization:{prefixes:["\u0627\u0644","\u0648","\u0641","\u0628","\u0643","\u0644"]},eventHandler:{eventMarker:{primary:"\u0639\u0646\u062F",alternatives:["\u0641\u064A","\u0644\u062F\u0649","\u0639\u0646\u062F\u0645\u0627","\u062D\u064A\u0646","\u062D\u064A\u0646\u0645\u0627","\u0644\u0645\u0651\u0627","\u0644\u0645\u0627"],position:"before"},temporalMarkers:["\u0639\u0646\u062F\u0645\u0627","\u062D\u064A\u0646","\u0644\u0645\u0651\u0627"],negationMarker:{primary:"\u0639\u062F\u0645",alternatives:["\u0639\u062F\u0645"],position:"before"}}};function F(o,e){return e?{type:"literal",value:o,dataType:e}:{type:"literal",value:o}}function Ie(o,e){return e?{type:"selector",value:o,selectorKind:e}:{type:"selector",value:o}}function Te(o){return{type:"reference",value:o}}function tt(o,e){return{type:"property-path",object:o,property:e}}function Rt(o,e=!0){return{type:"flag",name:o,enabled:e}}function ar(o,e,t){let r=e instanceof Map?e:new Map(Object.entries(e)),n={kind:"command",action:o,roles:r};return t?{...n,metadata:t}:n}function Lt(o,e,t,r,n){let i=e instanceof Map?e:new Map(Object.entries(e));return{kind:"event-handler",action:o,roles:i,body:t,...n&&{eventModifiers:n},...r&&{metadata:r}}}function sr(o,e,t,r,n){let i=e instanceof Map?e:new Map(Object.entries(e));return{kind:"conditional",action:o,roles:i,thenBranch:t,...r&&{elseBranch:r},...n&&{metadata:n}}}function lr(o,e,t,r,n,i,s){let a=e instanceof Map?e:new Map(Object.entries(e));return{kind:"loop",action:o,roles:a,loopVariant:t,body:r,...n&&{loopVariable:n},...i&&{indexVariable:i},...s&&{metadata:s}}}var At=new Set(["me","you","it","result","event","target","body"]);function rt(o,e=At){return e.has(o)}var ir=new Set(["body","then","else","condition","loop-body","variable","catch","finally"]);function io(o){let e=o.slice(1,-1),t=0;for(let r of e)if(r==="[")t++;else if(r==="]")t--;else if(t===0&&(r===" "||r===":"))return!0;return!1}function nt(o,e={}){let t=o.trim(),r=e.collectDiagnostics===!0,n=[];if(!t.startsWith("[")||!t.endsWith("]"))throw new Error("Explicit syntax must be wrapped in brackets: [command role:value ...]");let i=t.slice(1,-1).trim();if(!i)throw new Error("Empty explicit statement");let s=so(i);if(s.length===0)throw new Error("No command specified in explicit statement");let a=s[0].toLowerCase(),l=new Map,c=e.referenceSet??At,d=e.schemaLookup?.getSchema(a),u=d?new Set(d.roles.map(m=>m.role)):null;for(let m=1;m<s.length;m++){let p=s[m];if(p.startsWith("+")||p.startsWith("~")){let C=p.startsWith("+"),k=p.slice(1);if(!k){if(r){n.push({severity:"error",code:"EMPTY_FLAG",message:`Empty flag name: "${p}"`,source:"schema"});continue}throw new Error(`Empty flag name: "${p}"`)}if(u&&!u.has(k)){if(r){n.push({severity:"error",code:"UNKNOWN_FLAG",message:`Unknown flag "${k}" for command "${a}"`,source:"schema",suggestions:[...u].map(x=>`+${x}`)}),l.set(k,Rt(k,C));continue}throw new Error(`Unknown flag "${k}" for command "${a}". Valid roles: ${[...u].join(", ")}`)}l.set(k,Rt(k,C));continue}let h=p.indexOf(":");if(h===-1){if(r){n.push({severity:"error",code:"INVALID_ROLE_FORMAT",message:`Invalid role format: "${p}". Expected role:value or +flag`,source:"schema"});continue}throw new Error(`Invalid role format: "${p}". Expected role:value or +flag`)}let y=p.slice(0,h);if(u&&!ir.has(y)&&!u.has(y))if(r)n.push({severity:"error",code:"UNKNOWN_ROLE",message:`Unknown role "${y}" for command "${a}"`,source:"schema",suggestions:[...u]});else throw new Error(`Unknown role "${y}" for command "${a}". Valid roles: ${[...u].join(", ")}`);let g=y,S=p.slice(h+1);if(ir.has(y)&&S.startsWith("[")&&io(S)){let C=co(p,h+1),k=p.slice(h+1,C+1);l.set(g,{type:"expression",raw:k});continue}let E=lo(S,c);l.set(g,E)}if(d&&a!=="on"){for(let m of d.roles)if(m.required&&!l.has(m.role)&&!m.default)if(r)n.push({severity:"error",code:"MISSING_REQUIRED_ROLE",message:`Missing required role "${m.role}" for command "${a}": ${m.description}`,source:"schema"});else throw new Error(`Missing required role "${m.role}" for command "${a}": ${m.description}`)}let f=m=>n.length===0?m:{...m,diagnostics:n};switch(a){case"on":{if(!l.get("event")){if(r)return n.push({severity:"error",code:"MISSING_EVENT_ROLE",message:"Event handler requires event role: [on event:click ...]",source:"schema"}),f(Lt("on",l,[],{sourceLanguage:"explicit"}));throw new Error("Event handler requires event role: [on event:click ...]")}let p=et(l,"body",e);return l.delete("body"),f(Lt("on",l,p,{sourceLanguage:"explicit"}))}case"if":{let m=et(l,"then",e),p=et(l,"else",e);return l.delete("then"),l.delete("else"),f(sr(a,l,m,p.length>0?p:void 0,{sourceLanguage:"explicit"}))}case"repeat":{let m=et(l,"loop-body",e),p=l.get("loop-variant"),h=l.get("variable"),y=l.get("index-variable");l.delete("loop-body"),l.delete("loop-variant"),l.delete("variable"),l.delete("index-variable");let g;p&&p.type==="literal"&&typeof p.value=="string"?g=p.value:l.has("quantity")?g="times":l.has("source")?g="for":l.has("condition")?g="while":g="forever";let S=h?.type==="literal"&&typeof h.value=="string"?h.value:h?.type==="expression"?h.raw:void 0,E=y?.type==="literal"&&typeof y.value=="string"?y.value:void 0;return f(lr(a,l,g,m,S,E,{sourceLanguage:"explicit"}))}default:return f(ar(a,l,{sourceLanguage:"explicit"}))}}function me(o){let e=o.trim();return e.startsWith("[")&&e.endsWith("]")}function et(o,e,t){let r=o.get(e);return r?r.type==="expression"?[nt(r.raw,t)]:[]:[]}function ao(o){if(o){if(o.startsWith("#"))return"id";if(o.startsWith("."))return"class";if(o.startsWith("["))return"attribute";if(o.startsWith("<")||o.startsWith("*"))return"element";if(/[>+~ ]/.test(o)&&o.length>1)return"complex"}}function so(o){let e=[],t="",r=!1,n="",i=0;for(let s=0;s<o.length;s++){let a=o[s];if(r){t+=a,a===n&&o[s-1]!=="\\"&&(r=!1);continue}if(a==='"'||a==="'"){r=!0,n=a,t+=a;continue}if(a==="["){i++,t+=a;continue}if(a==="]"){i--,t+=a;continue}if(a===" "&&i===0){t&&(e.push(t),t="");continue}t+=a}return t&&e.push(t),e}function lo(o,e){if(o.startsWith("#")||o.startsWith(".")||o.startsWith("[")||o.startsWith("@")||o.startsWith("*"))return Ie(o,ao(o));if(o.startsWith('"')||o.startsWith("'"))return F(o.slice(1,-1),"string");if(o==="true")return F(!0,"boolean");if(o==="false")return F(!1,"boolean");let t=o.toLowerCase();if(rt(t,e))return Te(t);let r=o.match(/^(-?\d+(?:\.\d+)?)(ms|s|m|h)?$/);if(r){let n=parseFloat(r[1]);return r[2]?F(o,"duration"):F(n,"number")}return F(o)}function co(o,e){let t=0;for(let r=e;r<o.length;r++)if(o[r]==="[")t++;else if(o[r]==="]"&&(t--,t===0))return r;return o.length-1}function ee(o){let e;if(o.kind==="compound"){let t=o;e=t.statements.map(r=>ee(r)).join(` ${t.chainType} `)}else e=uo(o);return o.annotations&&o.annotations.length>0?o.annotations.map(r=>r.value!==void 0?`@${r.name}(${r.value})`:`@${r.name}`).join(" ")+" "+e:e}function uo(o){let e=[o.action];for(let[t,r]of o.roles)r.type==="flag"?e.push(r.enabled?`+${r.name}`:`~${r.name}`):e.push(`${t}:${cr(r)}`);if(o.kind==="event-handler"){let t=o;t.body&&t.body.length>0&&e.push(`body:${t.body.map(r=>ee(r)).join(" ")}`)}if(o.kind==="conditional"){let t=o;t.thenBranch&&t.thenBranch.length>0&&e.push(`then:${t.thenBranch.map(r=>ee(r)).join(" ")}`),t.elseBranch&&t.elseBranch.length>0&&e.push(`else:${t.elseBranch.map(r=>ee(r)).join(" ")}`)}if(o.kind==="loop"){let t=o;t.loopVariant&&e.push(`loop-variant:${t.loopVariant}`),t.loopVariable&&e.push(`variable:${t.loopVariable}`),t.indexVariable&&e.push(`index-variable:${t.indexVariable}`),t.body&&t.body.length>0&&e.push(`loop-body:${t.body.map(r=>ee(r)).join(" ")}`)}if(o.kind==="command"){let t=o;t.body&&t.body.length>0&&e.push(`body:${t.body.map(r=>ee(r)).join(" ")}`),t.catchBranch&&t.catchBranch.length>0&&e.push(`catch:${t.catchBranch.map(r=>ee(r)).join(" ")}`),t.finallyBranch&&t.finallyBranch.length>0&&e.push(`finally:${t.finallyBranch.map(r=>ee(r)).join(" ")}`),t.asyncVariant&&e.push(`async-variant:${t.asyncVariant}`),t.asyncBody&&t.asyncBody.length>0&&e.push(`async-body:${t.asyncBody.map(r=>ee(r)).join(" ")}`)}return`[${e.join(" ")}]`}function cr(o){switch(o.type){case"literal":return typeof o.value=="string"?o.dataType==="string"||/\s/.test(o.value)?`"${o.value}"`:o.value:String(o.value);case"selector":return o.value;case"reference":return o.value;case"property-path":return`${cr(o.object)}'s ${o.property}`;case"expression":return o.raw;case"flag":return o.name}}var po=class{constructor(o){this.namespace=o,this.enabled=this.checkEnabled()}checkEnabled(){if(typeof process<"u"&&process.env){let o=process.env.DEBUG||"";return o==="*"||o.includes("framework:*")||o.includes(`framework:${this.namespace}`)}return!1}log(o,e,...t){if(!this.enabled)return;let r=`[framework:${this.namespace}]`,n=new Date().toISOString();switch(o){case"debug":console.debug(`${n} ${r} DEBUG:`,e,...t);break;case"info":console.info(`${n} ${r} INFO:`,e,...t);break;case"warn":console.warn(`${n} ${r} WARN:`,e,...t);break;case"error":console.error(`${n} ${r} ERROR:`,e,...t);break}}debug(o,...e){this.log("debug",o,...e)}info(o,...e){this.log("info",o,...e)}warn(o,...e){this.log("warn",o,...e)}error(o,...e){this.log("error",o,...e)}isEnabled(){return this.enabled}enable(){this.enabled=!0}disable(){this.enabled=!1}};function mo(o){return new po(o)}function Ce(o,e){return!e||e.length===0||e.includes(o)||e.includes("expression")?!0:o==="property-path"?e.some(t=>["selector","reference","expression"].includes(t)):!1}function fo(o,e){return o?.possessive?.keywords?.[e]}function ur(o){return!1}var _e=class Pe{constructor(){this.logger=mo("pattern-matcher"),this.stemMatchCount=0,this.totalKeywordMatches=0}safeToLowerCase(e){return typeof e=="string"?e.toLowerCase():e==null?"":String(e).toLowerCase()}matchPattern(e,t,r){let n=e.mark(),i=new Map;if(this.logger.debug("========================================"),this.logger.debug("matchPattern ENTRY"),this.logger.debug("Pattern ID:",t.id),this.logger.debug("Pattern command:",t.command),this.logger.debug("Pattern language:",t.language),this.logger.debug("Pattern template:",JSON.stringify(t.template,null,2)),this.logger.isEnabled()){let l=[];for(let c=0;c<10;c++){let d=e.peek(c);if(d)l.push({type:d.type,value:d.value,kind:d.kind});else break}this.logger.debug("Input tokens (first 10):",l),this.logger.debug("Profile code:",r?.code)}this.currentProfile=r,this.stemMatchCount=0,this.totalKeywordMatches=0,this.logger.debug("--- Calling matchTokenSequence ---"),this.logger.debug("Pattern tokens to match:",JSON.stringify(t.template.tokens,null,2));let s=this.matchTokenSequence(e,t.template.tokens,i);if(this.logger.debug("matchTokenSequence returned:",s),this.logger.debug("Captured roles:",Array.from(i.entries()).map(([l,c])=>[l,JSON.stringify(c)])),!s)return this.logger.debug(">>> MATCH FAILED - resetting token position"),e.reset(n),null;let a=this.calculateConfidence(t,i);return this.applyExtractionRules(t,i),{pattern:t,captured:i,consumedTokens:e.position()-n.position,confidence:a}}matchBest(e,t,r){let n=[];for(let s of t){let a=e.mark(),l=this.matchPattern(e,s,r);l&&n.push(l),e.reset(a)}if(n.length===0)return null;n.sort((s,a)=>{let l=a.pattern.priority-s.pattern.priority;if(l!==0)return l;let c=a.confidence-s.confidence;return Math.abs(c)>.001?c:a.consumedTokens-s.consumedTokens});let i=n[0];return this.matchPattern(e,i.pattern),i}matchTokenSequence(e,t,r,n){let i=t[0],s=i?.type==="literal"&&(i.value==="and"||i.value==="then"||i.alternatives?.includes("and")||i.alternatives?.includes("then"));if(this.currentProfile?.code==="ar"&&!s)for(;e.peek()?.kind==="conjunction";)e.advance();let a=null,l=null;for(let c=0;c<t.length;c++){let d=t[c];this.logger.debug(" >> Matching pattern token:",JSON.stringify(d,null,2));let u=e.peek();if(this.logger.debug(" >> Current input token:",u?JSON.stringify({type:u.type,value:u.value,kind:u.kind}):"EOF"),d.type==="role"&&d.greedy){let y=this.collectStopMarkers(t,c+1);if(n)for(let S of n)y.add(S);let g=[];for(;!e.isAtEnd();){let S=e.peek();if(!S||this.isStopMarker(S,y))break;g.push(S.value),e.advance()}if(g.length>0){r.set(d.role,{type:"expression",raw:g.join(" ")}),a=null,l=null;continue}else{if(d.optional)continue;return!1}}if(d.type==="group"){let y=this.collectStopMarkers(t,c+1);if(n)for(let S of n)y.add(S);if(this.matchGroupToken(e,d,r,y)){a=null,l=null;continue}if(this.isOptional(d))continue;return!1}let f=d.type==="role"&&d.optional===!0,m=f?e.mark():null;if(d.type==="role"&&!f){let y=c+1<t.length?t[c+1]:null;if(y?.type==="literal"){let g=e.peek();if(g&&this.getMatchType(g,y.value)!=="none"){if(this.logger.debug(" >> MARKER-STEAL GUARD: current token matches next literal, skipping role"),this.logger.debug(" >> Token match FAILED"),this.isOptional(d))continue;if(a&&l){this.logger.debug(" >> BACKTRACKING: undoing optional role",l),e.reset(a),r.delete(l),a=null,l=null;let S=this.matchPatternToken(e,d,r);if(this.logger.debug(" >> Backtrack retry result:",S),S)continue}return!1}}}let h=this.matchPatternToken(e,d,r);if(this.logger.debug(" >> Match result:",h),h){f?(a=m,l=d.role):(a=null,l=null);continue}if(this.logger.debug(" >> Token match FAILED"),!this.isOptional(d)){if(a&&l){this.logger.debug(" >> BACKTRACKING: undoing optional role",l),e.reset(a),r.delete(l),a=null,l=null;let y=this.matchPatternToken(e,d,r);if(this.logger.debug(" >> Backtrack retry result:",y),y)continue}return!1}}return!0}matchPatternToken(e,t,r){switch(t.type){case"literal":return this.matchLiteralToken(e,t);case"role":return this.matchRoleToken(e,t,r);case"group":return this.matchGroupToken(e,t,r);default:return!1}}matchLiteralToken(e,t){let r=e.peek();if(this.logger.debug(" >>> matchLiteralToken: expecting",t.value),this.logger.debug(" >>> matchLiteralToken: got token",r?JSON.stringify({type:r.type,value:r.value,kind:r.kind}):"null"),!r)return this.logger.debug(" >>> matchLiteralToken: FAIL - no token"),!1;let n=this.getMatchType(r,t.value);if(this.logger.debug(" >>> matchType for",r.value,"vs",t.value,":",n),n!=="none")return this.totalKeywordMatches++,n==="stem"&&this.stemMatchCount++,e.advance(),!0;if(t.alternatives)for(let i of t.alternatives){let s=this.getMatchType(r,i);if(s!=="none")return this.totalKeywordMatches++,s==="stem"&&this.stemMatchCount++,e.advance(),!0}return!1}matchRoleToken(e,t,r){this.logger.debug(" >>> matchRoleToken ENTRY: capturing role",t.role),this.logger.debug(" >>> matchRoleToken: expected types",t.expectedTypes),this.logger.debug(" >>> matchRoleToken: optional?",t.optional),this.skipNoiseWords(e);let n=e.peek();if(this.logger.debug(" >>> After skipNoiseWords, current token:",n?JSON.stringify({value:n.value,kind:n.kind}):"null"),!n)return t.optional||!1;let i=this.tryMatchPossessiveExpression(e);if(i)return t.expectedTypes&&t.expectedTypes.length>0&&!Ce(i.type,t.expectedTypes)?t.optional||!1:(r.set(t.role,i),!0);let s=this.tryMatchMethodCallExpression(e);if(s)return t.expectedTypes&&t.expectedTypes.length>0&&!Ce(s.type,t.expectedTypes)?t.optional||!1:(r.set(t.role,s),!0);let a=this.tryMatchPossessiveSelectorExpression(e);if(a)return t.expectedTypes&&t.expectedTypes.length>0&&!Ce(a.type,t.expectedTypes)?t.optional||!1:(r.set(t.role,a),!0);let l=this.tryMatchPropertyAccessExpression(e);if(l)return t.expectedTypes&&t.expectedTypes.length>0&&!Ce(l.type,t.expectedTypes)?t.optional||!1:(r.set(t.role,l),!0);let c=this.tryMatchSelectorPropertyExpression(e);if(c)return t.expectedTypes&&t.expectedTypes.length>0&&!Ce(c.type,t.expectedTypes)?t.optional||!1:(r.set(t.role,c),!0);this.logger.debug(" >>> Trying tokenToSemanticValue for token:",n?JSON.stringify({value:n.value,kind:n.kind}):"null");let d=this.tokenToSemanticValue(n);return this.logger.debug(" >>> tokenToSemanticValue returned:",d?JSON.stringify(d):"null"),d?(this.logger.debug(" >>> Validating type:",d.type,"against expected:",t.expectedTypes),t.expectedTypes&&t.expectedTypes.length>0&&!Ce(d.type,t.expectedTypes)?(this.logger.debug(" >>> TYPE MISMATCH - returning",t.optional||!1),t.optional||!1):(this.logger.debug(" >>> Type validation PASSED"),r.set(t.role,d),e.advance(),!0)):t.optional||!1}tryMatchPossessiveExpression(e){let t=e.peek();if(!t||!this.currentProfile)return null;let r=t.normalized||t.value,n=this.safeToLowerCase(r),i=fo(this.currentProfile,n);if(!i)return null;let s=e.mark();e.advance();let a=e.peek();if(!a)return e.reset(s),null;if(a.kind==="identifier"||a.kind==="keyword"&&!this.isStructuralKeyword(a.value)||a.kind==="selector"&&a.value.startsWith("*")||a.kind==="selector"&&a.value.startsWith("@")||a.kind==="selector"&&a.value.startsWith(".")&&/^\.[a-zA-Z_]\w*/.test(a.value)){e.advance();let l=a.value;a.kind==="selector"&&l.startsWith(".")&&/^\.[a-zA-Z_]\w*/.test(l)&&(l=l.substring(1));let c=l;for(;e.peek()?.kind==="selector"&&e.peek().value.startsWith(".")&&/^\.[a-zA-Z_]\w*/.test(e.peek().value);)c+=e.peek().value,e.advance();let d=e.peek();return d?.kind==="literal"&&d.value.startsWith("(")&&(c+=d.value,e.advance()),tt(Te(i),c)}return e.reset(s),null}isStructuralKeyword(e){return new Set(["into","in","to","from","at","by","with","without","before","after","of","as","on","then","end","else","if","repeat","while","for","toggle","add","remove","put","set","show","hide","increment","decrement","send","trigger","call"]).has(e.toLowerCase())}tryMatchMethodCallExpression(e){let t=e.peek();if(!t||t.kind!=="selector")return null;let r=e.mark();e.advance();let n=e.peek();if(!n||n.kind!=="operator"||n.value!==".")return e.reset(r),null;e.advance();let i=e.peek();if(!i||i.kind!=="identifier")return e.reset(r),null;e.advance();let s=e.peek();if(!s||s.kind!=="punctuation"||s.value!=="(")return e.reset(r),null;e.advance();let a=[];for(;!e.isAtEnd()&&a.length<Pe.MAX_METHOD_ARGS;){let c=e.peek();if(!c)break;if(c.kind==="punctuation"&&c.value===")"){e.advance();break}if(c.kind==="punctuation"&&c.value===","){e.advance();continue}a.push(c.value),e.advance()}return{type:"expression",raw:`${t.value}.${i.value}(${a.join(", ")})`}}tryMatchPropertyAccessExpression(e){let t=e.peek();if(!t||t.kind!=="identifier"&&t.kind!=="keyword")return null;let r=e.mark();e.advance();let n=e.peek();if(!n||n.kind!=="operator"||n.value!==".")return e.reset(r),null;e.advance();let i=e.peek();if(!i||i.kind!=="identifier")return e.reset(r),null;e.advance();let s=`${t.value}.${i.value}`,a=1;for(;!e.isAtEnd()&&a<Pe.MAX_PROPERTY_DEPTH;){let c=e.peek();if(!c||c.kind!=="operator"||c.value!==".")break;e.advance();let d=e.peek();if(!d||d.kind!=="identifier")break;e.advance(),s+=`.${d.value}`,a++}let l=e.peek();if(l&&l.kind==="punctuation"&&l.value==="("){e.advance();let c=[],d=0;for(;!e.isAtEnd()&&c.length<Pe.MAX_METHOD_ARGS;){let f=e.peek();if(!f)break;if(f.kind==="punctuation"&&f.value===")"){if(d===0){e.advance();break}d--}if(f.kind==="punctuation"&&f.value==="("&&d++,f.kind==="punctuation"&&f.value===","){e.advance();continue}c.push(f.value),e.advance()}return{type:"expression",raw:`${s}(${c.join(", ")})`}}return{type:"expression",raw:s}}tryMatchPossessiveSelectorExpression(e){let t=e.peek();if(!t||t.kind!=="selector")return null;let r=e.mark();e.advance();let n=e.peek();if(!n||n.kind!=="punctuation"||n.value!=="'s")return e.reset(r),null;e.advance();let i=e.peek();return!i||i.kind!=="selector"&&i.kind!=="identifier"?(e.reset(r),null):(e.advance(),tt(Ie(t.value),i.value))}tryMatchSelectorPropertyExpression(e){let t=e.peek();if(!t||t.kind!=="selector"||typeof t.value!="string"||!t.value.startsWith("#"))return null;let r=e.mark();e.advance();let n=e.peek();if(!n||n.kind!=="selector"||!n.value.startsWith("."))return e.reset(r),null;let i=e.peek(1);i&&i.kind,e.advance();let s=n.value.slice(1);return tt(Ie(t.value),s)}matchGroupToken(e,t,r,n){let i=e.mark(),s=new Set(r.keys());if(this.matchTokenSequence(e,t.tokens,r,n))return!0;e.reset(i);for(let c of r.keys())s.has(c)||r.delete(c);if(!t.optional)return!1;let l=this.getGroupLeadingMarker(t);if(l)for(let c=1;c<=Pe.MAX_MARKER_SCAN;c++){let d=e.peek(c);if(!d)break;if((d.normalized||d.value).toLowerCase()===l){this.logger.debug(" >> MARKER SCAN: found",l,"at offset",c,"- skipping intervening tokens");for(let m=0;m<c;m++)e.advance();if(this.matchTokenSequence(e,t.tokens,r,n))return!0;e.reset(i);for(let m of r.keys())s.has(m)||r.delete(m);break}}return!0}getGroupLeadingMarker(e){let t=e.tokens[0];return t?.type==="literal"?t.value.toLowerCase():null}getMatchType(e,t){return e.value===t?"exact":e.normalized===t?"normalized":e.stem===t&&e.stemConfidence!==void 0&&e.stemConfidence>=.7?"stem":e.kind==="keyword"&&this.safeToLowerCase(e.value)===t.toLowerCase()?"case-insensitive":"none"}collectStopMarkers(e,t){let r=new Set;for(let n=t;n<e.length;n++){let i=e[n];if(i.type==="literal"){if(r.add(i.value.toLowerCase()),i.alternatives)for(let s of i.alternatives)r.add(s.toLowerCase());break}if(i.type==="group"){for(let s of i.tokens)if(s.type==="literal"){if(r.add(s.value.toLowerCase()),s.alternatives)for(let a of s.alternatives)r.add(a.toLowerCase());break}if(!i.optional)break}}return r}isStopMarker(e,t){return t.size===0?!1:!!(t.has(e.value.toLowerCase())||e.normalized&&t.has(e.normalized.toLowerCase()))}tokenToSemanticValue(e){switch(e.kind){case"selector":return Ie(e.value);case"literal":return this.parseLiteralValue(e.value);case"keyword":let t=e.normalized||e.value,r=this.safeToLowerCase(t);return ur(r)?Te(r):F(e.normalized||e.value);case"identifier":if(typeof e.value=="string"&&e.value.startsWith(":"))return Te(e.value);let n=this.safeToLowerCase(e.value);return ur(n)?Te(n):{type:"expression",raw:e.value};case"url":return F(e.value,"string");default:return null}}parseLiteralValue(e){if(e.startsWith('"')||e.startsWith("'")||e.startsWith("`")||e.startsWith("\u300C")){let n=e.slice(1,-1);return F(n,"string")}if(e==="true")return F(!0,"boolean");if(e==="false")return F(!1,"boolean");let t=e.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/);if(t){let n=parseFloat(t[1]);return t[2]?F(e,"duration"):F(n,"number")}let r=parseFloat(e);return isNaN(r)?F(e,"string"):F(r,"number")}applyExtractionRules(e,t){for(let[r,n]of Object.entries(e.extraction))t.has(r)||(n.value!==void 0?t.set(r,{type:"literal",value:n.value}):n.default&&t.set(r,n.default))}isOptional(e){return e.type!=="literal"&&e.optional===!0}calculateConfidence(e,t){let r=0,n=0,i=c=>e.extraction?.[c]?.default!==void 0;for(let c of e.template.tokens)if(c.type==="role")n+=1,t.has(c.role)&&(r+=1);else if(c.type==="group"){for(let d of c.tokens)if(d.type==="role"){let u=i(d.role),f=.8;n+=f,t.has(d.role)?r+=f:u&&(r+=f*.6)}}let s=n>0?r/n:1;if(this.stemMatchCount>0&&this.totalKeywordMatches>0){let c=this.stemMatchCount/this.totalKeywordMatches*.15;s=Math.max(.5,s-c)}let a=this.calculateVSOConfidenceBoost(e);s=Math.min(1,s+a);let l=this.arabicPrepositionDisambiguation(e,t);return s=Math.max(0,Math.min(1,s+l)),s}calculateVSOConfidenceBoost(e){if(e.language!=="ar")return 0;let t=e.template.tokens[0];if(!t||t.type!=="literal")return 0;let r=new Set(["\u0628\u062F\u0644","\u063A\u064A\u0631","\u0623\u0636\u0641","\u0623\u0632\u0644","\u0636\u0639","\u0627\u062C\u0639\u0644","\u0639\u064A\u0646","\u0632\u062F","\u0627\u0646\u0642\u0635","\u0633\u062C\u0644","\u0623\u0638\u0647\u0631","\u0623\u062E\u0641","\u0634\u063A\u0644","\u0623\u0631\u0633\u0644","\u0631\u0643\u0632","\u0634\u0648\u0634","\u062A\u0648\u0642\u0641","\u0627\u0646\u0633\u062E","\u0627\u062D\u0630\u0641","\u0627\u0635\u0646\u0639","\u0627\u0646\u062A\u0638\u0631","\u0627\u0646\u062A\u0642\u0627\u0644","\u0623\u0648"]);if(r.has(t.value))return .15;if(t.alternatives){for(let n of t.alternatives)if(r.has(n))return .15}return 0}arabicPrepositionDisambiguation(e,t){if(e.language!=="ar")return 0;let r=0,n={patient:["\u0639\u0644\u0649"],destination:["\u0625\u0644\u0649","\u0627\u0644\u0649"],source:["\u0645\u0646"],agent:["\u0645\u0646"],manner:["\u0628"],style:["\u0628"],goal:["\u0625\u0644\u0649","\u0627\u0644\u0649"],method:["\u0628"]};for(let[i,s]of t.entries()){let a=n[i];if(!a||a.length===0)continue;let l="metadata"in s?s.metadata:void 0;if(l&&typeof l.prepositionValue=="string"){let c=l.prepositionValue;a.includes(c)?r+=.1:r-=.1}}return Math.max(-.1,Math.min(.1,r))}skipNoiseWords(e){let t=e.peek();if(!t)return;let r=this.safeToLowerCase(t.value);if(Pe.ENGLISH_NOISE_WORDS.has(r)){let n=e.mark();e.advance();let i=e.peek();if(i&&i.kind==="selector")return;e.reset(n)}r==="class"&&e.advance()}extractEventModifiers(e){let t={},r=!1;for(;!e.isAtEnd();){let n=e.peek();if(!n||n.kind!=="event-modifier")break;let i=n.metadata;if(!i)break;switch(r=!0,i.modifierName){case"once":t.once=!0;break;case"debounce":typeof i.value=="number"&&(t.debounce=i.value);break;case"throttle":typeof i.value=="number"&&(t.throttle=i.value);break;case"queue":(i.value==="first"||i.value==="last"||i.value==="all"||i.value==="none")&&(t.queue=i.value);break}e.advance()}return r?t:void 0}};_e.MAX_MARKER_SCAN=3;_e.MAX_PROPERTY_DEPTH=10;_e.MAX_METHOD_ARGS=20;_e.ENGLISH_NOISE_WORDS=new Set(["the","a","an"]);var ho=_e,rs=new ho;var Mt=class{constructor(){this.name="string-literal"}canExtract(o,e){let t=o[e];return t==='"'||t==="'"||t==="`"||t==="\u201C"||t==="\u2018"}extract(o,e){let t=o[e];if(t==="\u201C"){let i=1;for(;e+i<o.length;){if(o[e+i]==="\u201D")return i++,{value:o.substring(e,e+i),length:i};i++}return null}if(t==="\u2018"){let i=1;for(;e+i<o.length;){if(o[e+i]==="\u2019")return i++,{value:o.substring(e,e+i),length:i};i++}return null}let r=1,n=!1;for(;e+r<o.length;){let i=o[e+r];if(n){n=!1,r++;continue}if(i==="\\"){n=!0,r++;continue}if(i===t)return r++,{value:o.substring(e,e+r),length:r};r++}return null}},Ot=class{constructor(){this.name="number"}canExtract(o,e){return/\d/.test(o[e])}extract(o,e){let t=0,r=!1;for(;e+t<o.length;){let s=o[e+t];if(/\d/.test(s))t++;else if(s==="."&&!r)r=!0,t++;else break}if(t===0)return null;let n=o.substring(e,e+t),i=e+t;if(i<o.length){let s=o.slice(i),a=[{pattern:"\u6BEB\u79D2",suffix:"ms"},{pattern:"\u5206\u949F",suffix:"m"},{pattern:"\u5C0F\u65F6",suffix:"h"},{pattern:"\u30DF\u30EA\u79D2",suffix:"ms"},{pattern:"\u6642\u9593",suffix:"h"}];for(let c of a)if(s.startsWith(c.pattern))return{value:n+c.suffix,length:t+c.pattern.length,metadata:{hasTimeUnit:!0}};if(s.startsWith("ms"))return{value:n+"ms",length:t+2,metadata:{hasTimeUnit:!0}};let l=[{pattern:"\u79D2",suffix:"s"},{pattern:"\u5206",suffix:"m"}];for(let c of l)if(s.startsWith(c.pattern))return{value:n+c.suffix,length:t+1,metadata:{hasTimeUnit:!0}};if(/^[smh](?![a-zA-Z])/.test(s))return{value:n+s[0],length:t+1,metadata:{hasTimeUnit:!0}}}return{value:n,length:t}}};function yo(o){return"setContext"in o&&typeof o.setContext=="function"}function go(o){let e={language:o.language,direction:o.direction,lookupKeyword:o.lookupKeyword.bind(o),isKeyword:o.isKeyword.bind(o),isKeywordStart:o.isKeywordStart.bind(o),...o.isKeywordStartAtBoundary?{isKeywordStartAtBoundary:o.isKeywordStartAtBoundary.bind(o)}:{}};return o.normalizer?{...e,normalizer:o.normalizer}:e}var H=class{constructor(o,e){this.pos=0,this.tokens=o,this.language=e}peek(o=0){let e=this.pos+o;return e<0||e>=this.tokens.length?null:this.tokens[e]}advance(){if(this.isAtEnd())throw new Error("Unexpected end of token stream");return this.tokens[this.pos++]}isAtEnd(){return this.pos>=this.tokens.length}mark(){return{position:this.pos}}reset(o){this.pos=o.position}position(){return this.pos}remaining(){return this.tokens.slice(this.pos)}takeWhile(o){let e=[];for(;!this.isAtEnd()&&o(this.peek());)e.push(this.advance());return e}skipWhile(o){for(;!this.isAtEnd()&&o(this.peek());)this.advance()}};function _(o,e){return{start:o,end:e}}function B(o,e,t,r){if(typeof o=="object"){let{value:i,kind:s,position:a,normalized:l,stem:c,stemConfidence:d,metadata:u}=o;return{value:i,kind:s,position:a,...l!==void 0&&{normalized:l},...c!==void 0&&{stem:c},...d!==void 0&&{stemConfidence:d},...u!==void 0&&{metadata:u}}}let n=o;if(!e||!t)throw new Error("createToken requires kind and position parameters");if(typeof r=="string")return{value:n,kind:e,position:t,normalized:r};if(r){let{normalized:i,stem:s,stemConfidence:a,metadata:l}=r;return{value:n,kind:e,position:t,...i!==void 0&&{normalized:i},...s!==void 0&&{stem:s},...a!==void 0&&{stemConfidence:a},...l!==void 0&&{metadata:l}}}return{value:n,kind:e,position:t}}function ae(o){return/\s/.test(o)}function ot(o){return o==="#"||o==="."||o==="["||o==="@"||o==="*"||o==="<"}function it(o){return o==='"'||o==="'"||o==="`"||o==="\u300C"||o==="\u300D"}function ie(o){return/\d/.test(o)}function at(o){return/[a-zA-Z]/.test(o)}function q(o){return/[a-zA-Z0-9_-]/.test(o)}function dr(o,e){if(e>=o.length)return null;let t=o[e];if(!ot(t))return null;let r=e,n="";if(t==="#"||t==="."){for(n+=o[r++];r<o.length&&q(o[r]);)n+=o[r++];if(n.length<=1)return null;if(r<o.length&&o[r]==="."&&t==="#"){let s=r+1;for(;s<o.length&&q(o[s]);)s++;if(s<o.length&&o[s]==="(")return n}}else if(t==="["){let i=1,s=!1,a=null,l=!1;for(n+=o[r++];r<o.length&&i>0;){let c=o[r];n+=c,l?l=!1:c==="\\"?l=!0:s?c===a&&(s=!1,a=null):c==='"'||c==="'"||c==="`"?(s=!0,a=c):c==="["?i++:c==="]"&&i--,r++}if(i!==0)return null}else if(t==="@"){for(n+=o[r++];r<o.length&&q(o[r]);)n+=o[r++];if(n.length<=1)return null}else if(t==="*"){for(n+=o[r++];r<o.length&&q(o[r]);)n+=o[r++];if(n.length<=1)return null}else if(t==="<"){if(n+=o[r++],r>=o.length||!at(o[r]))return null;for(;r<o.length&&q(o[r]);)n+=o[r++];for(;r<o.length;){let i=o[r];if(i==="."){if(n+=o[r++],r>=o.length||!q(o[r]))return null;for(;r<o.length&&q(o[r]);)n+=o[r++]}else if(i==="#"){if(n+=o[r++],r>=o.length||!q(o[r]))return null;for(;r<o.length&&q(o[r]);)n+=o[r++]}else if(i==="["){let s=1,a=!1,l=null,c=!1;for(n+=o[r++];r<o.length&&s>0;){let d=o[r];n+=d,c?c=!1:d==="\\"?c=!0:a?d===l&&(a=!1,l=null):d==='"'||d==="'"||d==="`"?(a=!0,l=d):d==="["?s++:d==="]"&&s--,r++}if(s!==0)return null}else break}for(;r<o.length&&ae(o[r]);)n+=o[r++];if(r<o.length&&o[r]==="/")for(n+=o[r++];r<o.length&&ae(o[r]);)n+=o[r++];if(r>=o.length||o[r]!==">")return null;n+=o[r++]}return n||null}function vo(o,e){if(e>=o.length||o[e]!=="'"||e+1>=o.length||o[e+1].toLowerCase()!=="s")return!1;if(e+2>=o.length)return!0;let r=o[e+2];return ae(r)||r==="*"||!q(r)}function pr(o,e){if(e>=o.length)return null;let t=o[e];if(!it(t)||t==="'"&&vo(o,e))return null;let n={'"':'"',"'":"'","`":"`","\u300C":"\u300D"}[t];if(!n)return null;let i=e+1,s=t,a=!1;for(;i<o.length;){let l=o[i];if(s+=l,a)a=!1;else if(l==="\\")a=!0;else if(l===n)return s;i++}return s}function mr(o,e){if(e>=o.length)return!1;let t=o[e],r=o[e+1]||"",n=o[e+2]||"";if(t==="/"&&r!=="/"&&/[a-zA-Z0-9._-]/.test(r)||t==="/"&&r==="/"&&/[a-zA-Z]/.test(n)||t==="."&&(r==="/"||r==="."&&n==="/"))return!0;let i=o.slice(e,e+8).toLowerCase();return!!(i.startsWith("http://")||i.startsWith("https://"))}function fr(o,e){if(!mr(o,e))return null;let t=e,r="",n=/[a-zA-Z0-9/:._\-?&=%@+~!$'()*,;[\]]/;for(;t<o.length;){let i=o[t];if(i==="#"){if(r.length>0&&/[a-zA-Z0-9/.]$/.test(r))for(r+=i,t++;t<o.length&&/[a-zA-Z0-9_-]/.test(o[t]);)r+=o[t++];break}if(n.test(i))r+=i,t++;else break}return r.length<2?null:r}function hr(o,e){if(e>=o.length)return null;let t=o[e];if(!ie(t)&&t!=="-"&&t!=="+")return null;let r=e,n="";if((o[r]==="-"||o[r]==="+")&&(n+=o[r++]),r>=o.length||!ie(o[r]))return null;for(;r<o.length&&ie(o[r]);)n+=o[r++];if(r<o.length&&o[r]===".")for(n+=o[r++];r<o.length&&ie(o[r]);)n+=o[r++];return r<o.length&&(o.slice(r,r+2)==="ms"?n+="ms":(o[r]==="s"||o[r]==="m"||o[r]==="h")&&(n+=o[r])),n}var xo=["===","!==","->","==","!=","<=",">=","&&","||","**","+=","-=","*=","/=","+","-","*","/","=",">","<","!","&","|","%","^","~"];function ue(o){return e=>{let t=e.charCodeAt(0);return o.some(([r,n])=>t>=r&&t<=n)}}var ss=new Set(xo),ko=new Set(["patient","destination","source","style","event","eventMarker","agent","goal","manner","into","from","to","with","at","of","as","by","in","on","over","under","between","through","without"]),So=["click","dblclick","input","change","submit","keydown","keyup","keypress","mousedown","mouseup","mouseover","mouseout","mouseenter","mouseleave","mousemove","pointerdown","pointerup","pointermove","focus","blur","load","resize","scroll"],yr=class gr{constructor(){this.profileKeywords=[],this.multiWordKeywords=[],this.profileKeywordMap=new Map,this.rawExtraEntries=[],this.extractors=[]}getExtraKeywordEntries(){return this.rawExtraEntries}tokenize(e){if(this.isUsingExtractors())return this.tokenizeWithExtractors(e);throw new Error(`${this.constructor.name}: tokenize() not implemented and no extractors registered. Either register extractors or override tokenize() method.`)}registerExtractor(e){yo(e)&&e.setContext(go(this)),this.extractors.push(e)}registerExtractors(e){for(let t of e)this.registerExtractor(t)}clearExtractors(){this.extractors=[]}isUsingExtractors(){return this.extractors.length>0}tokenizeWithExtractors(e){let t=[],r=0;for(;r<e.length;){for(;r<e.length&&ae(e[r]);)r++;if(r>=e.length)break;let n=this.tryMultiWordKeyword(e,r);if(n){t.push(n),r=n.position.end;continue}let i=!1;for(let s of this.extractors)if(s.canExtract(e,r)){let a=s.extract(e,r);if(a){let l=a.metadata?.normalized,c=a.metadata?.stem,d=a.metadata?.stemConfidence,u={};if(a.metadata)for(let[m,p]of Object.entries(a.metadata))m!=="normalized"&&m!=="stem"&&m!=="stemConfidence"&&(u[m]=p);let f={};l&&(f.normalized=l),c&&(f.stem=c),d!==void 0&&(f.stemConfidence=d),Object.keys(u).length>0&&(f.metadata=u),t.push(B(a.value,this.classifyToken(a.value),_(r,r+a.length),Object.keys(f).length>0?f:void 0)),r+=a.length,i=!0;break}}if(!i){let s=e[r],a=this.classifyUnknownChar(s);t.push(B(s,a,_(r,r+1))),r++}}return new H(t,this.language)}classifyUnknownChar(e){return"()[]{},:;".includes(e)?"punctuation":"+-*/<>=!&|".includes(e)?"operator":"identifier"}tryPropertyAccess(e,t,r){if(e[t]!==".")return!1;let n=r[r.length-1],i=n&&n.position.end<t;if(n&&!i&&(n.kind==="identifier"||n.kind==="keyword"||n.kind==="selector"))return r.push(B(".","operator",_(t,t+1))),!0;let l=t+1;for(;l<e.length&&q(e[l]);)l++;return l<e.length&&e[l]==="("?(r.push(B(".","operator",_(t,t+1))),!0):!1}initializeKeywordsFromProfile(e,t=[]){let r=new Map;if(this.rawExtraEntries=t,e.keywords){for(let[n,i]of Object.entries(e.keywords))if(r.set(i.primary,{native:i.primary,normalized:i.normalized||n}),i.alternatives)for(let s of i.alternatives)r.set(s,{native:s,normalized:i.normalized||n})}if(e.references){for(let[n,i]of Object.entries(e.references))r.set(i,{native:i,normalized:n});for(let n of Object.keys(e.references))r.has(n)||r.set(n,{native:n,normalized:n})}if(e.roleMarkers){for(let[n,i]of Object.entries(e.roleMarkers))if(i.primary&&r.set(i.primary,{native:i.primary,normalized:n}),i.alternatives)for(let s of i.alternatives)r.set(s,{native:s,normalized:n})}if(e.possessive?.keywords)for(let[n,i]of Object.entries(e.possessive.keywords))r.set(n,{native:n,normalized:i});for(let n of So)r.has(n)||r.set(n,{native:n,normalized:n});for(let n of t)r.set(n.native,n);this.profileKeywords=Array.from(r.values()).sort((n,i)=>i.native.length-n.native.length),this.multiWordKeywords=this.profileKeywords.filter(n=>n.native.includes(" ")&&!ko.has(n.normalized)),this.profileKeywordMap=new Map;for(let n of this.profileKeywords){this.profileKeywordMap.set(n.native.toLowerCase(),n);let i=this.removeDiacritics(n.native);i!==n.native&&!this.profileKeywordMap.has(i.toLowerCase())&&this.profileKeywordMap.set(i.toLowerCase(),n)}}removeDiacritics(e){return e.replace(/[\u064B-\u0652\u0670]/g,"")}tryProfileKeyword(e,t){for(let r of this.profileKeywords)if(e.slice(t).startsWith(r.native))return B(r.native,"keyword",_(t,t+r.native.length),r.normalized);return null}tryMultiWordKeyword(e,t,r=n=>/[\p{L}\p{N}_]/u.test(n)){if(this.multiWordKeywords.length===0)return null;let n=e.slice(t);for(let i of this.multiWordKeywords){if(!n.startsWith(i.native))continue;let s=e[t+i.native.length];if(!(s!==void 0&&r(s)))return B(i.native,"keyword",_(t,t+i.native.length),i.normalized)}return null}isKeywordStart(e,t){let r=e.slice(t);return this.profileKeywords.some(n=>r.startsWith(n.native))}isKeywordStartAtBoundary(e,t,r=n=>/[\p{L}\p{N}_]/u.test(n)){let n=e.slice(t);return this.profileKeywords.some(i=>{if(!n.startsWith(i.native))return!1;let s=e[t+i.native.length];return s===void 0||!r(s)})}lookupKeyword(e){return this.profileKeywordMap.get(e.toLowerCase())}isKeyword(e){return this.profileKeywordMap.has(e.toLowerCase())}setNormalizer(e){this.normalizer=e}tryNormalize(e){if(!this.normalizer)return null;let t=this.normalizer.normalize(e);return t.stem!==e&&t.confidence>=.7?t:null}tryMorphKeywordMatch(e,t,r){let n=this.tryNormalize(e);if(!n)return null;let i=this.lookupKeyword(n.stem);if(!i)return null;let s={normalized:i.normalized,stem:n.stem,stemConfidence:n.confidence};return B(e,"keyword",_(t,r),s)}trySelector(e,t){let r=dr(e,t);return r?B(r,"selector",_(t,t+r.length)):null}tryEventModifier(e,t){if(e[t]!==".")return null;let r=e.slice(t).match(/^\.(?:once|debounce|throttle|queue)(?:\(([^)]+)\))?(?:\s|$|\.)/);if(!r)return null;let n=r[0].replace(/(\s|\.)$/,""),i=n.slice(1).split("(")[0],s=r[1];return{...B(n,"event-modifier",_(t,t+n.length)),metadata:{modifierName:i,value:s?i==="queue"?s:parseInt(s,10):void 0}}}tryString(e,t){let r=pr(e,t);return r?B(r,"literal",_(t,t+r.length)):null}tryNumber(e,t){let r=hr(e,t);return r?B(r,"literal",_(t,t+r.length)):null}tryMatchTimeUnit(e,t,r,n=!1){let i=t;if(n)for(;i<e.length&&ae(e[i]);)i++;let s=e.slice(i);for(let a of r){let l=s.slice(0,a.length);if(a.caseInsensitive?l.toLowerCase()===a.pattern.toLowerCase():l===a.pattern){if(a.notFollowedBy&&(s[a.length]||"")===a.notFollowedBy)continue;if(a.checkBoundary){let d=s[a.length]||"";if(q(d))continue}return{suffix:a.suffix,endPos:i+a.length}}}return null}parseBaseNumber(e,t,r=!0){let n=t,i="";if(r&&(e[n]==="-"||e[n]==="+")&&(i+=e[n++]),n>=e.length||!ie(e[n]))return null;for(;n<e.length&&ie(e[n]);)i+=e[n++];if(n<e.length&&e[n]===".")for(i+=e[n++];n<e.length&&ie(e[n]);)i+=e[n++];return!i||i==="-"||i==="+"?null:{number:i,endPos:n}}tryNumberWithTimeUnits(e,t,r,n={}){let{allowSign:i=!0,skipWhitespace:s=!1}=n,a=this.parseBaseNumber(e,t,i);if(!a)return null;let{number:l,endPos:c}=a,d=[...r,...gr.STANDARD_TIME_UNITS],u=this.tryMatchTimeUnit(e,c,d,s);return u&&(l+=u.suffix,c=u.endPos),B(l,"literal",_(t,c))}tryUrl(e,t){let r=fr(e,t);return r?B(r,"url",_(t,t+r.length)):null}tryVariableRef(e,t){if(e[t]!==":"||t+1>=e.length||!q(e[t+1]))return null;let r=t+1;for(;r<e.length&&q(e[r]);)r++;let n=e.slice(t,r);return B(n,"identifier",_(t,r))}tryOperator(e,t){let r=e.slice(t,t+2);if(["==","!=","<=",">=","&&","||","->"].includes(r))return B(r,"operator",_(t,t+2));let n=e[t];return["<",">","!","+","-","*","/","="].includes(n)?B(n,"operator",_(t,t+1)):["(",")","{","}",",",";",":"].includes(n)?B(n,"punctuation",_(t,t+1)):null}tryMultiCharParticle(e,t,r){for(let n of r)if(e.slice(t,t+n.length)===n)return B(n,"particle",_(t,t+n.length));return null}};yr.STANDARD_TIME_UNITS=[{pattern:"ms",suffix:"ms",length:2},{pattern:"s",suffix:"s",length:1,checkBoundary:!0},{pattern:"m",suffix:"m",length:1,checkBoundary:!0,notFollowedBy:"s"},{pattern:"h",suffix:"h",length:1,checkBoundary:!0}];var Be=yr;function zt(o){return{stem:o,confidence:1}}function Vt(o,e,t){return t?{stem:o,confidence:e,metadata:t}:{stem:o,confidence:e}}function re(o){let e="complex";return o.startsWith("#")&&!o.includes(" ")?e="id":o.startsWith(".")&&!o.includes(" ")?e="class":o.startsWith("[")&&o.endsWith("]")?e="attribute":/^[a-z][a-z0-9]*$/i.test(o)&&(e="element"),{type:"selector",value:o,selectorKind:e}}function $(o,e){let t={type:"literal",value:o};return e!==void 0?{type:"literal",value:o,dataType:e}:t}function ke(o){return rt(o)}function J(o){return{type:"reference",value:o}}function se(o,e){return{type:"property-path",object:o,property:e}}function G(o,e,t){let r={kind:"command",action:o,roles:new Map(Object.entries(e))};return t!==void 0?{...r,metadata:t}:r}function fe(o,e,t,r,n,i){let s=new Map;s.set("event",o);let a={kind:"event-handler",action:"on",roles:s,body:e};return t!==void 0&&(a.eventModifiers=t),r!==void 0&&(a.metadata=r),n!==void 0&&n.length>0&&(a.parameterNames=n),i!==void 0&&i.length>0&&(a.additionalEvents=i),a}function vr(o,e,t,r,n){let i={kind:"behavior",action:"behavior",roles:new Map,name:o,parameters:e,eventHandlers:t};return r!==void 0&&r.length>0&&(i.initBlock=r),n!==void 0&&(i.metadata=n),i}function xr(o,e,t,r){let n={kind:"def",action:"def",roles:new Map,name:o,parameters:e,body:t};return r!==void 0&&(n.metadata=r),n}function De(o,e="then",t){let r={kind:"compound",action:"compound",roles:new Map,statements:o,chainType:e};return t!==void 0&&(r.metadata=t),r}function kr(o,e,t,r){let n=new Map;n.set("condition",o);let i={kind:"conditional",action:"if",roles:n,thenBranch:e};return t!==void 0&&(i.elseBranch=t),r!==void 0&&(i.metadata=r),i}function $e(o,e){return!e||e.length===0||e.includes(o)||e.includes("expression")?!0:o==="property-path"?e.some(t=>["selector","reference","expression"].includes(t)):o==="expression"?e.some(t=>["selector","reference","expression"].includes(t)):!1}var bo={action:"toggle",description:"Toggle a class or attribute on/off",category:"dom-class",primaryRole:"patient",roles:[{role:"patient",description:"The class or attribute to toggle",required:!0,expectedTypes:["selector"],selectorKinds:["class","attribute"],svoPosition:1,sovPosition:2},{role:"destination",description:"The target element (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:1,markerVariants:{ko:["\uC5D0\uC11C"]}}],errorCodes:["MISSING_ARGUMENT","NO_VALID_CLASS_NAMES","INVALID_CSS_PROPERTY"],preconditions:[{condition:"Command has at least one argument",errorCode:"MISSING_ARGUMENT",message:"toggle command requires an argument"},{condition:"Class names are valid CSS identifiers",errorCode:"NO_VALID_CLASS_NAMES",message:"toggle command: no valid class names found"}],recoveryHints:{MISSING_ARGUMENT:"Add a class selector (.classname) or attribute to toggle",NO_VALID_CLASS_NAMES:"Ensure class names start with a dot (.) and are valid CSS identifiers",INVALID_CSS_PROPERTY:"Check CSS property name syntax (use kebab-case)"}},wo={action:"add",description:"Add a class or attribute to an element",category:"dom-class",primaryRole:"patient",roles:[{role:"patient",description:"The class or attribute to add",required:!0,expectedTypes:["selector","literal"],svoPosition:1,sovPosition:2},{role:"destination",description:"The target element (defaults to me)",required:!1,expectedTypes:["selector","reference","expression"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:1,markerOverride:{en:"to"}}],errorCodes:["MISSING_ARGUMENT","NO_VALID_CLASS_NAMES","PROPERTY_REQUIRES_VALUE"],preconditions:[{condition:"Command has at least one argument",errorCode:"MISSING_ARGUMENT",message:"add command requires an argument"}],recoveryHints:{MISSING_ARGUMENT:"Add a class selector (.classname) or attribute to add",NO_VALID_CLASS_NAMES:"Ensure class names start with a dot (.) and are valid CSS identifiers",PROPERTY_REQUIRES_VALUE:"When adding a property (*prop), provide a value argument"}},Eo={action:"remove",description:"Remove a class or attribute from an element",category:"dom-class",primaryRole:"patient",targetRole:"source",roles:[{role:"patient",description:"The class/attribute to remove, or the element to remove",required:!0,expectedTypes:["selector","reference"],svoPosition:1,sovPosition:2},{role:"source",description:"The element to remove from (defaults to me)",required:!1,expectedTypes:["selector","reference","expression"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:1}],errorCodes:["MISSING_ARGUMENT","NO_VALID_CLASS_NAMES"],preconditions:[{condition:"Command has at least one argument",errorCode:"MISSING_ARGUMENT",message:"remove command requires an argument"}],recoveryHints:{MISSING_ARGUMENT:"Add a class selector (.classname) or attribute to remove",NO_VALID_CLASS_NAMES:"Ensure class names start with a dot (.) and are valid CSS identifiers"}},To={action:"put",description:"Put content into a target element or variable",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The content to put",required:!0,expectedTypes:["literal","selector","reference","expression"],svoPosition:1,sovPosition:1},{role:"destination",description:"Where to put the content",required:!0,expectedTypes:["selector","reference"],svoPosition:2,sovPosition:2,markerOverride:{en:"into"},markerVariants:{en:["before","after"]},methodCarrier:"method"}],errorCodes:["MISSING_ARGUMENTS","MISSING_CONTENT","MISSING_POSITION","INVALID_POSITION","NO_TARGET","NO_ELEMENTS"],preconditions:[{condition:"Command has content and position arguments",errorCode:"MISSING_ARGUMENTS",message:"put requires arguments"},{condition:"Content to put is specified",errorCode:"MISSING_CONTENT",message:"put requires content"},{condition:"Position keyword is specified (into, before, after, etc.)",errorCode:"MISSING_POSITION",message:"put requires position keyword"}],recoveryHints:{MISSING_ARGUMENTS:"Use syntax: put <content> into/before/after <target>",MISSING_CONTENT:"Add content to put (string, element, or expression)",MISSING_POSITION:"Add position keyword: into, before, after, at start of, at end of",INVALID_POSITION:"Valid positions: into, before, after, at start of, at end of",NO_TARGET:'Ensure target element exists or use "me" reference',NO_ELEMENTS:"Check that the selector matches existing elements"}},Co={action:"set",description:"Set a property or variable to a value",category:"variable",primaryRole:"destination",roles:[{role:"destination",description:"The property or variable to set",required:!0,expectedTypes:["selector","reference","expression","property-path"],svoPosition:1,sovPosition:1,markerOverride:{en:"",ja:"\u3092",ko:"\uB97C",tr:"i",ar:"",sw:"",tl:"",bn:"\u0995\u09C7",qu:"ta",hi:"\u0915\u094B"}},{role:"patient",description:"The value to set",required:!0,expectedTypes:["literal","expression","reference"],svoPosition:2,sovPosition:2,markerOverride:{en:"to",es:"a",pt:"para",fr:"\xE0",de:"auf",id:"ke",ja:"\u306B",ko:"\uC5D0",tr:"e",ar:"\u0625\u0644\u0649",sw:"kwenye",tl:"sa",bn:"\u09A4\u09C7",qu:"man",hi:"\u092E\u0947\u0902"},markerVariants:{tr:["e","a","ye","ya"]}},{role:"scope",description:"The element(s) the attribute/property is set on (defaults to me)",required:!1,expectedTypes:["selector","reference"],svoPosition:3,sovPosition:3,markerOverride:{en:"on",es:"on",pt:"on",fr:"on",de:"on",it:"on",id:"on",ms:"on",sw:"on",tl:"on",zh:"on",vi:"on",ru:"on",uk:"on",pl:"on",th:"on",he:"on",ar:"on",ja:"on",ko:"on",tr:"on",hi:"on",bn:"on",qu:"on"}}],errorCodes:["MISSING_TARGET","INVALID_TARGET","MISSING_VALUE","INVALID_SYNTAX"],preconditions:[{condition:"Command has a target variable or property",errorCode:"MISSING_TARGET",message:"set command requires a target"},{condition:"Target is a valid variable or property reference",errorCode:"INVALID_TARGET",message:"set command target must be a string or object literal"},{condition:'Value is specified with "to" keyword',errorCode:"MISSING_VALUE",message:'set command requires a value (use "to" keyword)'}],recoveryHints:{MISSING_TARGET:"Add a target: set :variable to value OR set element.property to value",INVALID_TARGET:'Use local variable (:name), element property (el.prop), or "the X of Y" syntax',MISSING_VALUE:'Add "to <value>" to specify what to set',INVALID_SYNTAX:"Use syntax: set <target> to <value>"}},Po={action:"bind",description:"Reactively bind a variable to an element or property value",category:"variable",primaryRole:"destination",roles:[{role:"destination",description:"The variable to bind",required:!0,expectedTypes:["reference","expression"],svoPosition:1,sovPosition:1,markerOverride:{en:"",es:"",pt:"",fr:"",de:"",it:"",id:"",ms:"",vi:"",ru:"",uk:"",pl:"",th:"",zh:"",he:"",ar:"",sw:"",tl:"",ja:"\u3092",ko:"\uB97C",tr:"i",bn:"\u0995\u09C7",qu:"ta",hi:"\u0915\u094B"}},{role:"source",description:"The element or property to bind to",required:!0,expectedTypes:["selector","reference","expression"],svoPosition:2,sovPosition:2,markerOverride:{en:"to",es:"a",pt:"para",fr:"\xE0",de:"zu",it:"in",id:"ke",ms:"ke",vi:"v\xE0o",ru:"\u0432",uk:"\u0432",pl:"do",ja:"\u306B",ko:"\uC5D0",tr:"e",ar:"\u0625\u0644\u0649",zh:"\u5230",he:"\u05DC",sw:"kwa",th:"\u0E43\u0E19",tl:"sa",bn:"\u09A4\u09C7",qu:"man",hi:"\u092E\u0947\u0902"}}],errorCodes:["MISSING_TARGET","MISSING_VALUE","INVALID_SYNTAX"],recoveryHints:{MISSING_TARGET:"Add a variable to bind: bind $name to #input",MISSING_VALUE:'Add "to <element>" to specify the binding source',INVALID_SYNTAX:"Use syntax: bind <variable> to <element>"}},No={action:"live",description:"Reactive block: re-run the body when its dependencies change",category:"control-flow",primaryRole:"patient",hasBody:!0,bareKeyword:!0,roles:[]},Ro={action:"eventsource",description:"Open a Server-Sent Events stream and handle its events",category:"async",primaryRole:"patient",hasBody:!0,bareKeyword:!0,roles:[]},Lo={action:"socket",description:"Open a WebSocket and handle its messages",category:"async",primaryRole:"patient",hasBody:!0,bareKeyword:!0,roles:[]},Ao={action:"worker",description:"Define a Web Worker with inline methods",category:"async",primaryRole:"patient",hasBody:!0,bareKeyword:!0,roles:[]},Mo={action:"intercept",description:"Service-worker fetch interception / caching strategies",category:"async",primaryRole:"patient",hasBody:!0,bareKeyword:!0,roles:[]},Oo={action:"show",description:"Make an element visible",category:"dom-visibility",primaryRole:"patient",roles:[{role:"patient",description:"The element to show",required:!0,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:1,sovPosition:1},{role:"style",description:"Animation style (fade, slide, etc.)",required:!1,expectedTypes:["literal"],svoPosition:2,sovPosition:2}]},zo={action:"hide",description:"Make an element invisible",category:"dom-visibility",primaryRole:"patient",roles:[{role:"patient",description:"The element to hide",required:!0,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:1,sovPosition:1},{role:"style",description:"Animation style (fade, slide, etc.)",required:!1,expectedTypes:["literal"],svoPosition:2,sovPosition:2}]},Vo={action:"on",description:"Handle an event",category:"event",primaryRole:"event",hasBody:!0,roles:[{role:"event",description:"The event to handle",required:!0,expectedTypes:["literal"],svoPosition:1,sovPosition:2},{role:"source",description:"The element to listen on (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:1}]},Io={action:"trigger",description:"Trigger/dispatch an event",category:"event",primaryRole:"event",roles:[{role:"event",description:"The event to trigger (supports namespaced events like draggable:start)",required:!0,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:2},{role:"destination",description:"The target element (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:1}]},_o={action:"wait",description:"Wait for a duration or event",category:"async",primaryRole:"duration",roles:[{role:"duration",description:"Duration or event to wait for",required:!0,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:1}]},Bo={action:"fetch",description:"Fetch data from a URL",category:"async",primaryRole:"source",roles:[{role:"source",description:"The URL to fetch from",required:!0,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:1,renderOverride:{en:""}},{role:"responseType",description:"Response format (json, text, html, blob, etc.)",required:!1,expectedTypes:["literal","expression"],svoPosition:2,sovPosition:2,markerOverride:{en:"as"}},{role:"method",description:"HTTP method (GET, POST, etc.)",required:!1,expectedTypes:["literal"],svoPosition:3,sovPosition:3},{role:"destination",description:"Where to store the result",required:!1,expectedTypes:["selector","reference"],svoPosition:4,sovPosition:4}]},Do={action:"increment",description:"Increment a numeric value",category:"variable",primaryRole:"patient",roles:[{role:"patient",description:"The value to increment",required:!0,expectedTypes:["selector","reference","expression"],svoPosition:1,sovPosition:1},{role:"quantity",description:"Amount to increment by (defaults to 1)",required:!1,expectedTypes:["literal"],default:{type:"literal",value:1,dataType:"number"},svoPosition:2,sovPosition:2,markerOverride:{en:"by",es:"por",pt:"por",fr:"par",de:"um"}}]},$o={action:"decrement",description:"Decrement a numeric value",category:"variable",primaryRole:"patient",roles:[{role:"patient",description:"The value to decrement",required:!0,expectedTypes:["selector","reference","expression"],svoPosition:1,sovPosition:1},{role:"quantity",description:"Amount to decrement by (defaults to 1)",required:!1,expectedTypes:["literal"],default:{type:"literal",value:1,dataType:"number"},svoPosition:2,sovPosition:2,markerOverride:{en:"by",es:"por",pt:"por",fr:"par",de:"um"}}]},Wo={action:"append",description:"Append content to an element",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The content to append",required:!0,expectedTypes:["literal","selector","expression"],svoPosition:1,sovPosition:2},{role:"destination",description:"The element to append to",required:!0,expectedTypes:["selector","reference"],svoPosition:2,sovPosition:1,markerOverride:{en:"to"}}]},jo={action:"prepend",description:"Prepend content to an element",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The content to prepend",required:!0,expectedTypes:["literal","selector","expression"],svoPosition:1,sovPosition:2},{role:"destination",description:"The element to prepend to",required:!0,expectedTypes:["selector","reference"],svoPosition:2,sovPosition:1,markerOverride:{en:"to"}}]},qo={action:"log",description:"Log a value to the console",category:"variable",primaryRole:"patient",roles:[{role:"patient",description:"The value to log",required:!0,expectedTypes:["literal","selector","reference","expression"],svoPosition:1,sovPosition:1}]},Ko={action:"get",description:"Get a value from a source",category:"variable",primaryRole:"source",roles:[{role:"source",description:"The source to get from",required:!0,expectedTypes:["selector","reference","expression"],svoPosition:1,sovPosition:2,markerOverride:{en:"",es:"",pt:"",fr:"",de:"",ja:"\u3092",zh:"",ko:"\uB97C",ar:"\u0639\u0644\u0649",tr:"i",id:"",he:"\u05D0\u05EA",sw:"",tl:"",bn:"\u0995\u09C7",qu:"ta"}},{role:"destination",description:"Where to store the result (optional)",required:!1,expectedTypes:["reference"],svoPosition:2,sovPosition:1}]},Fo={action:"take",description:"Take content from a source element",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The class or element to take",required:!0,expectedTypes:["selector"],svoPosition:1,sovPosition:2},{role:"source",description:"The element to take from (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:1}]},Uo={action:"make",description:"Create a new element",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The element type or selector to create",required:!0,expectedTypes:["literal","selector"],svoPosition:1,sovPosition:1}]},Ho={action:"halt",description:"Halt/stop execution or event propagation",category:"control-flow",primaryRole:"patient",roles:[{role:"patient",description:"What to halt (event, default, bubbling, etc.)",required:!1,expectedTypes:["literal","reference","expression"],svoPosition:1,sovPosition:1}]},Go={action:"settle",description:"Wait for animations/transitions to settle",category:"async",primaryRole:"patient",roles:[{role:"patient",description:"The element to settle (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:1,sovPosition:1}]},Yo={action:"throw",description:"Throw an error",category:"control-flow",primaryRole:"patient",roles:[{role:"patient",description:"The error message or object to throw",required:!0,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:1}]},Zo={action:"send",description:"Send an event to an element",category:"event",primaryRole:"event",roles:[{role:"event",description:"The event to send",required:!0,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:2},{role:"destination",description:"The target element (defaults to me)",required:!1,expectedTypes:["selector","reference","expression"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:1,markerOverride:{en:"to",ja:"\u306B",ar:"\u0625\u0644\u0649",es:"a",ko:"\uC5D0\uAC8C",zh:"\u5230",tr:"-e",pt:"para",fr:"\xE0",de:"an",id:"ke",qu:"-man",sw:"kwa"}}]},Jo={action:"if",description:"Conditional execution",category:"control-flow",primaryRole:"condition",hasBody:!0,roles:[{role:"condition",description:"The condition to evaluate",required:!0,expectedTypes:["expression","reference","selector"],svoPosition:1,sovPosition:1}]},Xo={action:"unless",description:"Negated conditional execution (executes when condition is false)",category:"control-flow",primaryRole:"condition",hasBody:!0,roles:[{role:"condition",description:"The condition to evaluate (body executes when false)",required:!0,expectedTypes:["expression","reference","selector"],svoPosition:1,sovPosition:1}]},Qo={action:"else",description:"Else branch of conditional",category:"control-flow",primaryRole:"patient",hasBody:!0,roles:[]},ei={action:"repeat",description:"Repeat a block of commands",category:"control-flow",primaryRole:"loopType",hasBody:!0,roles:[{role:"loopType",description:"Loop variant: forever, times, for, while, until, until-event",required:!0,expectedTypes:["literal"],svoPosition:0,sovPosition:0},{role:"quantity",description:"Number of times to repeat",required:!1,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:1},{role:"event",description:"Event to wait for (terminates loop)",required:!1,expectedTypes:["literal","expression"],svoPosition:2,sovPosition:2},{role:"source",description:"Element to listen for event on",required:!1,expectedTypes:["selector","reference"],svoPosition:3,sovPosition:3}],notes:'Can also use "repeat forever", "repeat until condition", or "repeat until event X from Y"'},ti={action:"for",description:"Iterate over a collection",category:"control-flow",primaryRole:"patient",hasBody:!0,roles:[{role:"patient",description:"The iteration variable",required:!0,expectedTypes:["reference","expression"],svoPosition:1,sovPosition:2},{role:"source",description:"The collection to iterate over",required:!0,expectedTypes:["selector","reference","expression"],svoPosition:2,sovPosition:1,markerOverride:{en:"in",es:"en",fr:"en",de:"in",it:"in",pt:"dentro",id:"dalam",ms:"dalam",pl:"w",ru:"\u0432",uk:"\u0443",sw:"ndani",th:"\u0E43\u0E19",vi:"trong",ar:"\u0641\u064A",tl:"sa_loob",he:"in",zh:"\u5728"}}]},ri={action:"while",description:"Loop while condition is true",category:"control-flow",primaryRole:"condition",hasBody:!0,roles:[{role:"condition",description:"The condition to check",required:!0,expectedTypes:["expression"],svoPosition:1,sovPosition:1}]},ni={action:"continue",description:"Continue to next loop iteration",category:"control-flow",primaryRole:"patient",roles:[]},oi={action:"go",description:"Navigate to a URL",category:"navigation",primaryRole:"destination",roles:[{role:"destination",description:"The URL to navigate to",required:!0,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:1,markerOverride:{en:"to"},renderOverride:{en:""},markerOptional:{en:!0},markerVariants:{he:["\u05D0\u05EA"],zh:["\u628A"]}}]},ii={action:"transition",description:"Transition an element with animation",category:"dom-visibility",primaryRole:"patient",omitRoleVariants:["goal"],roles:[{role:"patient",description:"The property to transition (opacity, *background-color, etc.)",required:!0,expectedTypes:["literal","expression","selector"],svoPosition:1,sovPosition:2,markerOverride:{en:"",ar:"",tl:"",sw:""}},{role:"goal",description:"The target value to transition to",required:!0,expectedTypes:["literal","expression"],svoPosition:2,sovPosition:3,markerOverride:{en:"to",ar:"\u0625\u0644\u0649",tl:"sa",sw:"kwa",bn:"\u09A4\u09C7",qu:"man",es:"a",pt:"para",fr:"\xE0",de:"zu",he:"\u05E2\u05DC",it:"in",ja:"\u306B",ko:"\uC5D0",ms:"ke",pl:"do",ru:"\u0432",th:"\u0E43\u0E19",tr:"e",uk:"\u0432",vi:"v\xE0o",zh:"\u5230",id:"ke"}},{role:"destination",description:"The target element (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:3,sovPosition:1},{role:"duration",description:"Transition duration (over 500ms, for 2 seconds)",required:!1,expectedTypes:["literal"],svoPosition:4,sovPosition:4,markerOverride:{en:"over"}},{role:"style",description:"Easing function (ease-in, linear, etc.)",required:!1,expectedTypes:["literal"],svoPosition:5,sovPosition:5}]},ai={action:"clone",description:"Clone an element",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The element to clone",required:!0,expectedTypes:["selector","reference"],svoPosition:1,sovPosition:2},{role:"destination",description:"Where to put the clone",required:!1,expectedTypes:["selector","reference"],svoPosition:2,sovPosition:1,markerOverride:{en:"into"}}]},si={action:"focus",description:"Focus an element",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The element to focus (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:1,sovPosition:1}]},li={action:"blur",description:"Remove focus from an element",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The element to blur (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:1,sovPosition:1}]},ci={action:"empty",description:"Remove all children from an element (sets innerHTML to empty)",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The element to empty (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:1,sovPosition:1}]},ui={action:"open",description:"Open a dialog, details element, or popover",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The element to open (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:2},{role:"style",description:"Open-mode variant (modal / non-modal) for <dialog>",required:!1,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:1,markerOverride:{en:"as"}}]},di={action:"close",description:"Close a dialog, details element, or popover",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The element to close (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:1,sovPosition:1}]},pi={action:"select",description:"Select the contents of a text field or DOM element",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The element whose contents to select (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:1,sovPosition:1}]},mi={action:"clear",description:"Clear a variable, local, or input element",category:"variable",primaryRole:"patient",roles:[{role:"patient",description:"The variable or element to clear (defaults to me)",required:!1,expectedTypes:["selector","reference","expression"],default:{type:"reference",value:"me"},svoPosition:1,sovPosition:1}]},fi={action:"reset",description:"Reset a <form> element to its default values",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The form element to reset (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:1,sovPosition:1}]},hi={action:"breakpoint",description:"Drop into the debugger",category:"control-flow",primaryRole:"patient",roles:[],bareKeyword:!0},yi={action:"call",description:"Call a function",category:"control-flow",primaryRole:"patient",roles:[{role:"patient",description:"The function to call",required:!0,expectedTypes:["expression","reference"],markerOptional:{he:!0,zh:!0},svoPosition:1,sovPosition:1}]},gi={action:"return",description:"Return a value from a function",category:"control-flow",primaryRole:"patient",roles:[{role:"patient",description:"The value to return",required:!1,expectedTypes:["literal","expression","reference"],svoPosition:1,sovPosition:1}]},vi={action:"js",description:"Execute raw JavaScript code",category:"control-flow",primaryRole:"patient",hasBody:!0,roles:[{role:"patient",description:"The JavaScript code to execute",required:!1,expectedTypes:["expression"],svoPosition:1,sovPosition:1}]},xi={action:"async",description:"Execute commands asynchronously",category:"async",primaryRole:"patient",hasBody:!0,roles:[]},ki={action:"tell",description:"Execute commands in context of another element",category:"control-flow",primaryRole:"destination",hasBody:!0,roles:[{role:"destination",description:"The element to tell",required:!0,expectedTypes:["selector","reference"],svoPosition:1,sovPosition:1,markerOverride:{en:"",he:"\u05D0\u05EA",zh:"\u628A"}}]},Si={action:"default",description:"Set a default value for a variable",category:"variable",primaryRole:"destination",roles:[{role:"destination",description:"The variable to set default for",required:!0,expectedTypes:["selector","reference","expression","property-path"],svoPosition:1,sovPosition:1,markerOverride:{en:"",ar:"",tl:"",sw:"",bn:"\u0995\u09C7",qu:"ta",ja:"\u3092",ko:"\uB97C",tr:"i",hi:"\u0915\u094B",de:"",es:"",fr:"",it:"",pt:"",pl:"",ru:"",uk:"",vi:"",id:"",ms:"",th:"",zh:"\u628A",he:"\u05D0\u05EA"}},{role:"patient",description:"The default value",required:!0,expectedTypes:["literal","expression"],svoPosition:2,sovPosition:2,markerOverride:{en:"to",ar:"\u0625\u0644\u0649",tl:"sa",sw:"kwa",bn:"\u09A4\u09C7",qu:"man",ja:"\u306B",ko:"\uC5D0",tr:"e",hi:"\u092E\u0947\u0902",de:"zu",es:"a",fr:"\xE0",it:"in",pt:"para",pl:"do",ru:"\u0432",uk:"\u0432",vi:"v\xE0o",id:"ke",ms:"ke",th:"\u0E43\u0E19",zh:"\u5230",he:"\u05E2\u05DC"}}]},bi={action:"init",description:"Initialization block that runs once",category:"control-flow",primaryRole:"patient",hasBody:!0,roles:[]},wi={action:"behavior",description:"Define a reusable behavior",category:"control-flow",primaryRole:"patient",hasBody:!0,roles:[{role:"patient",description:"The behavior name (PascalCase identifier)",required:!0,expectedTypes:["literal","reference","expression"],svoPosition:1,sovPosition:1}]},Ei={action:"install",description:"Install a behavior on an element",category:"control-flow",primaryRole:"patient",roles:[{role:"patient",description:"The behavior name to install",required:!0,expectedTypes:["literal","reference","expression"],svoPosition:1,sovPosition:2},{role:"destination",description:"Element to install on (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:1}]},Ti={action:"measure",description:"Measure element dimensions (x, y, width, height, etc.)",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"Property to measure (x, y, width, height, top, left, etc.)",required:!1,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:1},{role:"source",description:"Element to measure (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:2,markerOverride:{en:"of"}}]},Ci={action:"swap",description:"Swap DOM content using various strategies (innerHTML, outerHTML, delete, etc.)",category:"dom-content",primaryRole:"destination",roles:[{role:"method",description:"The swap strategy (innerHTML, outerHTML, beforebegin, afterend, delete)",required:!1,expectedTypes:["literal"],svoPosition:1,sovPosition:3,markerOverride:{en:""}},{role:"destination",description:"The element to swap content in/for",required:!0,expectedTypes:["selector","reference"],svoPosition:2,sovPosition:1,markerOverride:{en:"of",es:"",fr:"",pt:"",it:"",de:"",pl:"",ru:"",uk:"",id:"",ms:"",sw:"",th:"",vi:"",he:"\u05D0\u05EA",zh:"\u628A"}},{role:"patient",description:"The content to swap in (optional for delete)",required:!1,expectedTypes:["literal","expression","selector"],svoPosition:3,sovPosition:2,markerOverride:{en:"with",es:"con",fr:"avec",pt:"com",it:"con",de:"mit",pl:"z",ru:"\u0441",uk:"\u0437",id:"dengan",ms:"dengan",sw:"na",th:"\u0E14\u0E49\u0E27\u0E22",vi:"v\u1EDBi",he:"\u05E2\u05DD",zh:"\u7528"}}]},Pi={action:"morph",description:"Morph an element into another using DOM diffing",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The element to morph",required:!0,expectedTypes:["selector","reference"],svoPosition:1,sovPosition:1,markerOverride:{en:""}},{role:"destination",description:"The target content/element to morph into",required:!0,expectedTypes:["literal","expression","selector","reference"],svoPosition:2,sovPosition:2,markerOverride:{en:"to"}}]},Ni={action:"beep",description:"Debug output for expressions with type information",category:"variable",primaryRole:"patient",roles:[{role:"patient",description:"The expression(s) to debug",required:!1,expectedTypes:["literal","selector","reference","expression"],svoPosition:1,sovPosition:1}]},Ri={action:"break",description:"Exit from the current loop",category:"control-flow",primaryRole:"patient",roles:[]},Li={action:"copy",description:"Copy text or element content to the clipboard",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The text or element to copy",required:!0,expectedTypes:["literal","selector","reference","expression"],svoPosition:1,sovPosition:1}]},Ai={action:"exit",description:"Exit from the current event handler",category:"control-flow",primaryRole:"patient",roles:[],bareKeyword:!0},Mi={action:"pick",description:"Select a random element from a collection",category:"variable",primaryRole:"patient",roles:[{role:"patient",description:"The items to pick from",required:!0,expectedTypes:["literal","expression","reference"],svoPosition:1,sovPosition:1},{role:"source",description:'The array to pick from (with "from" keyword)',required:!1,expectedTypes:["reference","expression"],svoPosition:2,sovPosition:2}]},Oi={action:"scroll",description:"Scroll the viewport to a target element",category:"navigation",primaryRole:"destination",argSkipTokens:["of","the","top","bottom","middle","center","nearest","left","right","smoothly","instantly"],roles:[{role:"destination",description:"The element to scroll to",required:!0,expectedTypes:["selector","reference","expression"],svoPosition:1,sovPosition:1,markerOverride:{en:"to"}}]},Sr={en:"url",es:"url",pt:"url",fr:"url",de:"url",it:"url",ja:"url",ko:"url",zh:"url",ar:"url",he:"url",hi:"url",bn:"url",tr:"url",ru:"url",uk:"url",pl:"url",id:"url",vi:"url",th:"url",ms:"url",tl:"url",sw:"url",qu:"url"},zi={en:"partials in",es:"partials in",pt:"partials in",fr:"partials in",de:"partials in",it:"partials in",ja:"partials in",ko:"partials in",zh:"partials in",ar:"partials in",he:"partials in",hi:"partials in",bn:"partials in",tr:"partials in",ru:"partials in",uk:"partials in",pl:"partials in",id:"partials in",vi:"partials in",th:"partials in",ms:"partials in",tl:"partials in",sw:"partials in",qu:"partials in"},Vi={action:"push",description:"Push a URL onto the browser history",category:"navigation",primaryRole:"patient",roles:[{role:"patient",description:"The URL to push (after the `url` keyword)",required:!0,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:1,markerOverride:Sr}]},Ii={action:"replace",description:"Replace the current browser history entry with a URL",category:"navigation",primaryRole:"patient",roles:[{role:"patient",description:"The URL to replace with (after the `url` keyword)",required:!0,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:1,markerOverride:Sr}]},_i={action:"process",description:"Process hx-partial markup in HTML content",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The HTML content (string, element, or response) to process",required:!0,expectedTypes:["literal","reference","expression"],svoPosition:1,sovPosition:1,markerOverride:zi}]},Bi={action:"render",description:"Render a template with optional variables",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The template to render",required:!0,expectedTypes:["selector","reference","expression"],svoPosition:1,sovPosition:2},{role:"style",description:"Variables to pass to the template (with keyword)",required:!1,expectedTypes:["expression","reference"],svoPosition:2,sovPosition:1}]},Ne={toggle:bo,add:wo,remove:Eo,put:To,set:Co,show:Oo,hide:zo,on:Vo,trigger:Io,wait:_o,fetch:Bo,increment:Do,decrement:$o,append:Wo,prepend:jo,log:qo,get:Ko,take:Fo,make:Uo,halt:Ho,settle:Go,throw:Yo,send:Zo,if:Jo,unless:Xo,else:Qo,repeat:ei,for:ti,while:ri,continue:ni,go:oi,scroll:Oi,push:Vi,replace:Ii,process:_i,transition:ii,clone:ai,focus:si,blur:li,empty:ci,open:ui,close:di,select:pi,clear:mi,reset:fi,breakpoint:hi,call:yi,return:gi,js:vi,async:xi,tell:ki,default:Si,init:bi,behavior:wi,install:Ei,measure:Ti,swap:Ci,morph:Pi,beep:Ni,break:Ri,copy:Li,exit:Ai,pick:Mi,render:Bi,bind:Po,live:No,eventsource:Ro,socket:Lo,worker:Ao,intercept:Mo,compound:{action:"compound",description:"A compound node representing chained statements",primaryRole:"patient",category:"control-flow",hasBody:!0,roles:[]}};function ne(o){return Ne[o]}function de(o,e){let t=o.possessive?.keywords?.[e];if(t)return t;let r=o.possessive?.specialForms;if(r){for(let[n,i]of Object.entries(r))if(i===e)return n}}var br=[{lang:"es",verb:"poner",verbAlts:["pon","colocar","put"],at:"en",end:"fin",of:"de"},{lang:"fr",verb:"mettre",at:"\xE0",end:"fin",of:"de"},{lang:"pt",verb:"colocar",at:"em",end:"fim",of:"de"},{lang:"it",verb:"mettere",at:"a",end:"fine",of:"di"},{lang:"de",verb:"setzen",at:"bei",end:"ende",of:"von"},{lang:"sw",verb:"weka",at:"katika",end:"mwisho",of:"ya"},{lang:"id",verb:"taruh",verbAlts:["letakkan","masukkan","tempatkan"],at:"di",end:"akhir",of:"dari"},{lang:"ms",verb:"letak",at:"di",end:"tamat",of:"daripada"},{lang:"vi",verb:"\u0111\u1EB7t",at:"t\u1EA1i",end:"k\u1EBFt th\xFAc",of:"c\u1EE7a"},{lang:"pl",verb:"umie\u015B\u0107",at:"przy",end:"koniec",of:"z"},{lang:"ru",verb:"\u043F\u043E\u043B\u043E\u0436\u0438\u0442\u044C",at:"\u0443",end:"\u043A\u043E\u043D\u0435\u0446",of:"\u0438\u0437"},{lang:"uk",verb:"\u043F\u043E\u043A\u043B\u0430\u0441\u0442\u0438",at:"\u0432",end:"\u043A\u0456\u043D\u0435\u0446\u044C",of:"\u0437"},{lang:"th",verb:"\u0E43\u0E2A\u0E48",at:"\u0E17\u0E35\u0E48",end:"\u0E08\u0E1A",of:"\u0E02\u0E2D\u0E07"},{lang:"tl",verb:"ilagay",at:"sa",end:"wakas",of:"ng"},{lang:"ar",verb:"\u0636\u0639",at:"\u0639\u0646\u062F",end:"\u0627\u0644\u0646\u0647\u0627\u064A\u0629",of:"\u0645\u0646"},{lang:"zh",verb:"\u653E\u7F6E",verbAlts:["\u653E","\u653E\u5165"],patientPrefix:"\u628A",at:"\u5728",end:"\u7ED3\u675F",of:"\u7684"},{lang:"he",verb:"\u05E9\u05D9\u05DD",patientPrefix:"\u05D0\u05EA",at:"at",end:"\u05E1\u05D5\u05E3",of:"of"},{lang:"tr",verb:"koy",sov:!0,objMarker:"i",at:"de",end:"son",of:"nin"},{lang:"ja",verb:"\u7F6E\u304F",sov:!0,objMarker:"\u3092",at:"\u3067",end:"\u7D42\u308F\u308A",of:"\u306E"},{lang:"ko",verb:"\uB123\uB2E4",sov:!0,objMarker:"\uB97C",at:"\uC5D0",end:"\uB05D",of:"\uC758"},{lang:"hi",verb:"\u0930\u0916\u0947\u0902",verbAlts:["\u0930\u0916","\u0921\u093E\u0932\u0947\u0902","\u0921\u093E\u0932"],sov:!0,objMarker:"\u0915\u094B",at:"\u092A\u0930",end:"\u0938\u092E\u093E\u092A\u094D\u0924",of:"\u0915\u093E"},{lang:"bn",verb:"\u09B0\u09BE\u0996\u09C1\u09A8",verbAlts:["\u09B0\u09BE\u0996"],sov:!0,objMarker:"\u0995\u09C7",at:"\u098F",end:"\u09B6\u09C7\u09B7",of:"\u09B0"},{lang:"qu",verb:"churay",sov:!0,objMarker:"ta",at:"pi",end:"tukuy",of:"pa"}];function It(o,e,t,r){let n=br.find(s=>s.lang===o);if(!n)return!1;let i=(s,a)=>(s??"").toLowerCase()===a.toLowerCase();return i(e,n.end)&&i(t,n.at)&&i(r,n.of)}function wr(o,e){let t=br.find(n=>n.lang===o);if(!t)return!1;let r=e.toLowerCase();return r===t.at.toLowerCase()||r===t.of.toLowerCase()||r===t.end.toLowerCase()}var Er=new Set(["\u0628\u062F\u0644","\u063A\u064A\u0631","\u0623\u0636\u0641","\u0623\u0632\u0644","\u0636\u0639","\u0627\u062C\u0639\u0644","\u0639\u064A\u0646","\u0632\u062F","\u0627\u0646\u0642\u0635","\u0633\u062C\u0644","\u0623\u0638\u0647\u0631","\u0623\u062E\u0641","\u0634\u063A\u0644","\u0623\u0631\u0633\u0644","\u0631\u0643\u0632","\u0634\u0648\u0634","\u062A\u0648\u0642\u0641","\u0627\u0646\u0633\u062E","\u0627\u062D\u0630\u0641","\u0627\u0635\u0646\u0639","\u0627\u0646\u062A\u0638\u0631","\u0627\u0646\u062A\u0642\u0627\u0644","\u0623\u0648"]),Di={patient:["\u0639\u0644\u0649"],destination:["\u0625\u0644\u0649","\u0627\u0644\u0649"],source:["\u0645\u0646"],agent:["\u0645\u0646"],manner:["\u0628"],style:["\u0628"],goal:["\u0625\u0644\u0649","\u0627\u0644\u0649"],method:["\u0628"]},_t=class{calculate(e){return this.calculateWithBreakdown(e).final}calculateWithBreakdown(e){let t=this.scoreRoleCoverage(e),r=this.scoreStemPenalty(e),n=this.scoreLanguageBoost(e),i=this.scoreLanguageAdjustment(e),s=t;return s=Math.max(.5,s+r),s=Math.min(1,s+n),s=Math.max(0,Math.min(1,s+i)),{roleCoverage:t,stemPenalty:r,languageBoost:n,languageAdjustment:i,final:s}}scoreRoleCoverage(e){let{pattern:t,captured:r}=e,n=0,i=0,s=a=>t.extraction?.[a]?.default!==void 0;for(let a of t.template.tokens)if(a.type==="role")i+=1,r.has(a.role)&&(n+=1);else if(a.type==="group")for(let l of a.tokens)l.type==="role"&&(i+=.8,r.has(l.role)?n+=.8:s(l.role)&&(n+=.8*.6));return i>0?n/i:1}scoreStemPenalty(e){let{stemMatchCount:t,totalKeywordMatches:r}=e;return t<=0||r<=0?0:-(t/r)*.15}scoreLanguageBoost(e){let{pattern:t}=e;if(t.language!=="ar")return 0;let r=t.template.tokens[0];return!r||r.type!=="literal"?0:Er.has(r.value)||r.alternatives?.some(n=>Er.has(n))?.15:0}scoreLanguageAdjustment(e){let{pattern:t,captured:r}=e;if(t.language!=="ar")return 0;let n=0;for(let[i,s]of r.entries()){let a=Di[i];if(!a||a.length===0)continue;let l="metadata"in s?s.metadata:void 0;l&&typeof l.prepositionValue=="string"&&(a.includes(l.prepositionValue)?n+=.1:n-=.1)}return Math.max(-.1,Math.min(.1,n))}},Tr=new _t;var $i=new Set(Object.values(Ne).filter(o=>o.bareKeyword===!0).map(o=>o.action)),A=class A{constructor(e){this.matchCache=new Map;this.stemMatchCount=0;this.totalKeywordMatches=0;this.confidenceModel=e??Tr}matchPattern(e,t){let r=e.mark(),n=new Map;if(this.currentProfile=V(t.language),this.currentPatternCommand=t.command,this.stemMatchCount=0,this.totalKeywordMatches=0,!this.matchTokenSequence(e,t.template.tokens,n))return e.reset(r),null;let s=this.confidenceModel.calculate({pattern:t,captured:n,stemMatchCount:this.stemMatchCount,totalKeywordMatches:this.totalKeywordMatches});return this.applyExtractionRules(t,n),{pattern:t,captured:n,consumedTokens:e.position()-r.position,confidence:s}}matchBest(e,t){this.matchCache.clear();let r=[],n=e.position();for(let s of t){let a=e.mark(),l=`${n}:${s.id}`,c;this.matchCache.has(l)?c=this.matchCache.get(l):(c=this.matchPattern(e,s),this.matchCache.set(l,c)),c&&r.push(c),e.reset(a)}if(r.length===0)return null;r.sort((s,a)=>{let l=a.pattern.priority-s.pattern.priority;return l!==0?l:a.confidence-s.confidence});let i=r[0];return this.matchPattern(e,i.pattern),i}matchTokenSequence(e,t,r,n){let i=t[0],s=i?.type==="literal"&&(i.value==="and"||i.value==="then"||i.alternatives?.includes("and")||i.alternatives?.includes("then"));if(this.currentProfile?.code==="ar"&&!s)for(;e.peek()?.kind==="conjunction";)e.advance();let a=0;for(let l=0;l<t.length;l++){let c=t[l];a>0&&c.type==="literal"&&this.tryConsumeEventSourceClause(e,r,c);let d=this.matchPatternToken(e,c,r,t[l+1]??n);if(a=c.type==="role"&&c.role==="event"?2:Math.max(0,a-1),!d){if(this.isOptional(c))continue;return!1}}return!0}tryConsumeEventSourceClause(e,t,r){if(t.has("source"))return;let n=e.peek(),i=e.peek(1);if(!n||!i||this.patternTokenWouldMatch(r,n))return;let s=this.currentProfile?.roleMarkers?.source,a=c=>{if(c.kind!=="particle"&&c.kind!=="keyword")return!1;if((c.normalized??"").toLowerCase()==="source")return!0;if(!s)return!1;let d=c.value.toLowerCase();return s.primary?.toLowerCase()===d?!0:!!s.alternatives?.some(u=>u.toLowerCase()===d)},l=s?.position;if(l!=="after"&&a(n)&&i.kind==="selector"){e.advance();let c=this.tokenToSemanticValue(e.advance());c&&t.set("source",c);return}if(l==="after"&&n.kind==="selector"&&a(i)){let c=this.tokenToSemanticValue(n);e.advance(),e.advance(),c&&t.set("source",c)}}matchPatternToken(e,t,r,n){switch(t.type){case"literal":return this.matchLiteralToken(e,t);case"role":return this.matchRoleToken(e,t,r,n);case"group":return this.matchGroupToken(e,t,r,n);default:return!1}}matchLiteralToken(e,t){let r=e.peek();if(!r)return!1;let n=this.getMatchType(r,t.value);if(n!=="none")return this.totalKeywordMatches++,n==="stem"&&this.stemMatchCount++,e.advance(),!0;if(t.alternatives)for(let i of t.alternatives){let s=this.getMatchType(r,i);if(s!=="none")return this.totalKeywordMatches++,s==="stem"&&this.stemMatchCount++,e.advance(),!0}for(let i of[t.value,...t.alternatives??[]])for(let s of["-","_"])if(i.includes(s)&&this.tryMatchShatteredCompound(e,i,s))return this.totalKeywordMatches++,!0;return!1}tryFoldHyphenActionKeyword(e){let t=this.currentProfile;if(!t)return null;let r=e.mark(),n=[];for(;;){let s=e.peek();if(!s||s.kind!=="identifier"&&s.kind!=="keyword")break;n.push(s.value),e.advance();let a=e.peek();if(!a||a.value!=="-")break;e.advance(),n.push("-")}if(n.length<3||n[n.length-1]==="-")return e.reset(r),null;let i=n.join("").toLowerCase();for(let[s,a]of Object.entries(t.keywords))if(a.primary.toLowerCase()===i||a.alternatives?.some(l=>l.toLowerCase()===i))return $(s);return e.reset(r),null}tryMatchShatteredCompound(e,t,r){let n=t.split(r);if(n.length<2||n.some(s=>s.length===0))return!1;let i=e.mark();for(let s=0;s<n.length;s++){if(s>0){let l=e.peek();if(!l||l.value!==r)return e.reset(i),!1;e.advance()}let a=e.peek();if(!a||a.kind!=="identifier"&&a.kind!=="keyword"&&a.kind!=="particle"||a.value.toLowerCase()!==n[s].toLowerCase())return e.reset(i),!1;e.advance()}return!0}matchRoleToken(e,t,r,n){this.skipNoiseWords(e);let i=e.peek();if(!i)return t.optional||!1;if(t.role==="action"&&this.currentProfile&&e.peek(1)?.value==="-"){let g=this.tryFoldHyphenActionKeyword(e);if(g)return r.set(t.role,g),!0}if(t.role==="event"&&this.currentPatternCommand==="on"){if(!A.tokenLooksLikeEvent(i))return t.optional||!1;let g=(i.normalized??i.value).toLowerCase();if(A.POSITIONAL_OR_SCOPE_KEYWORDS.has(g)||this.currentProfile&&(de(this.currentProfile,i.value)??de(this.currentProfile,g))!==void 0||i.value.includes("?."))return t.optional||!1}if(t.role==="event"){let g=(i.normalized??i.value).toLowerCase();if(A.STRUCTURAL_NEVER_EVENT.has(g))return t.optional||!1}if(t.role==="duration"){let g=(i.normalized??i.value).toLowerCase();if(A.POSITIONAL_OR_SCOPE_KEYWORDS.has(g))return t.optional||!1}if(t.optional&&n===void 0&&t.role!=="event"&&t.role!=="action"&&i.kind==="keyword"&&(i.normalized??i.value).toLowerCase()in Ne)return!0;let s=this.tryMatchPositionalExpression(e);if(s)return t.expectedTypes&&t.expectedTypes.length>0&&!$e(s.type,t.expectedTypes)?t.optional||!1:(r.set(t.role,s),!0);let a=this.tryMatchCaretScopeExpression(e);if(a)return t.expectedTypes&&t.expectedTypes.length>0&&!$e(a.type,t.expectedTypes)?t.optional||!1:(r.set(t.role,a),!0);if(t.role!=="event"&&(!t.expectedTypes||t.expectedTypes.includes("expression"))){let g=this.tryMatchOperatorRunExpression(e);if(g)return r.set(t.role,g),!0}if(t.expectedTypes?.includes("property-path")){let g=this.tryMatchOfPossessiveExpression(e);if(g)return r.set(t.role,g),!0;let S=this.tryMatchPostNominalPossessiveExpression(e);if(S)return r.set(t.role,S),!0}let l=this.tryMatchPossessiveExpression(e);if(l)return t.expectedTypes&&t.expectedTypes.length>0&&!t.expectedTypes.includes(l.type)&&!t.expectedTypes.includes("expression")?t.optional||!1:(r.set(t.role,l),!0);let c=this.tryMatchMethodCallExpression(e);if(c)return t.expectedTypes&&t.expectedTypes.length>0&&!t.expectedTypes.includes(c.type)&&!t.expectedTypes.includes("expression")?t.optional||!1:(r.set(t.role,c),!0);let u=t.role==="event"&&this.currentPatternCommand==="on"||A.DECLARATION_COMMANDS.has(this.currentPatternCommand??"")?null:this.tryMatchBareCallExpression(e);if(u)return t.expectedTypes&&t.expectedTypes.length>0&&!t.expectedTypes.includes(u.type)&&!t.expectedTypes.includes("expression")?t.optional||!1:(r.set(t.role,u),!0);let f=this.tryMatchPossessiveSelectorExpression(e);if(f)return t.expectedTypes&&t.expectedTypes.length>0&&!$e(f.type,t.expectedTypes)?t.optional||!1:(r.set(t.role,f),!0);let m=t.role!=="condition",p=this.tryMatchPropertyAccessExpression(e,m);if(p)return t.expectedTypes&&t.expectedTypes.length>0&&!t.expectedTypes.includes(p.type)&&!t.expectedTypes.includes("expression")?t.optional||!1:(r.set(t.role,p),!0);let h=this.tryMatchSelectorPropertyExpression(e);if(h)return t.expectedTypes&&t.expectedTypes.length>0&&!$e(h.type,t.expectedTypes)?t.optional||!1:(r.set(t.role,h),!0);if(i.kind==="identifier"&&i.value==="{"&&(!t.expectedTypes?.length||t.expectedTypes.includes("literal"))){let g=this.tryMatchBraceRunLiteral(e);if(g)return r.set(t.role,g),!0}let y=this.tokenToSemanticValue(i);if(!y)return t.optional||!1;if(t.expectedTypes&&t.expectedTypes.length>0&&!t.expectedTypes.includes(y.type)){let g=y.type==="selector"&&String(y.value).startsWith("@"),S=t.expectedTypes.some(E=>E==="expression"||E==="reference");if(!(g&&S))return t.optional||!1}if(r.set(t.role,y),e.advance(),t.role==="event"){let g=e.peek();g&&g.kind==="selector"&&g.value.startsWith("[")&&"value"in y&&(r.set(t.role,$(`${String(y.value)}${g.value}`)),e.advance());let S=e.peek();if(S&&(S.kind==="particle"||S.kind==="keyword")&&(S.normalized??"").toLowerCase()==="source"&&!this.patternTokenWouldMatch(n,S)){let E=e.peek(1);if(E&&(E.kind==="selector"||E.kind==="identifier")){e.advance();let C=this.tokenToSemanticValue(e.advance());C&&!r.has("source")&&r.set("source",C)}}}return!0}patternTokenWouldMatch(e,t){return e?e.type==="literal"?this.getMatchType(t,e.value)!=="none"?!0:!!e.alternatives?.some(r=>this.getMatchType(t,r)!=="none"):e.type==="group"?this.patternTokenWouldMatch(e.tokens?.[0],t):!1:!1}tryMatchPositionalExpression(e){let t=e.peek();if(!t)return null;let r=(t.normalized??t.value).toLowerCase();if(!A.POSITIONAL_KEYWORDS.has(r)&&!A.POSITIONAL_KEYWORDS.has(t.value.toLowerCase()))return null;let n=e.mark(),i=[t.normalized??t.value];e.advance();let s=e.peek();if(!s||s.kind!=="selector")return e.reset(n),null;i.push(s.value),e.advance();let a=0;for(;a++<8;){let d=e.peek();if(d&&d.kind==="selector"&&d.value.startsWith("."))i.push(d.value),e.advance();else break}let l=e.peek(),c=e.peek(1);return l&&c&&c.kind==="selector"&&(l.kind==="keyword"||l.kind==="particle"||l.kind==="identifier")&&!A.POSITIONAL_KEYWORDS.has((l.normalized??l.value).toLowerCase())&&!A.COMMAND_ACTION_KEYWORDS.has((l.normalized??l.value).toLowerCase())&&(i.push(l.normalized??l.value,c.value),e.advance(),e.advance()),{type:"expression",raw:i.join(" ")}}tryMatchCaretScopeExpression(e){let t=e.peek();if(!t||t.kind!=="identifier"||!t.value.startsWith("^"))return null;let r=e.peek(1),n=e.peek(2),i=(r?.normalized??"").toLowerCase(),s=!!r&&(r.value.toLowerCase()==="on"||i==="destination"||i==="on");return!r||!n||n.kind!=="selector"||!s?null:(e.advance(),e.advance(),e.advance(),{type:"expression",raw:`${t.value} on ${n.value}`})}isOfPossessiveMarker(e){let t=e.value.toLowerCase(),r=(e.normalized??"").toLowerCase();if(t==="of"||t==="ng"||r==="of"||r==="source")return!0;let n=this.currentProfile?.code?A.OF_POSSESSIVE_MARKERS[this.currentProfile.code]:void 0;return!!n&&n.has(t)}tryMatchOperatorRunExpression(e){let t=e.mark(),r=e.position();if(!this.tryConsumeRunOperand(e))return e.reset(t),null;let n=1;for(;;){let s=e.peek();if(!s||!A.RUN_OPERATORS.has(s.value))break;let a=e.mark();if(e.advance(),!this.tryConsumeRunOperand(e)){e.reset(a);break}n++}if(n<2)return e.reset(t),null;let i=e.tokens.slice(r,e.position()).map(s=>s.value).join(" ");return{type:"expression",raw:i,value:i}}tryConsumeRunOperand(e){let t=e.peek();if(!t)return!1;if(t.value==="("){let r=e.mark(),n=0;for(;!e.isAtEnd();){let i=e.advance();if(i.value==="(")n++;else if(i.value===")"&&(n--,n===0))return!0}return e.reset(r),!1}return this.tryMatchPossessiveExpression(e)?!0:(t.kind==="literal"||t.kind==="identifier"||t.kind==="selector"||t.kind==="keyword")&&!A.RUN_OPERATORS.has(t.value)&&t.value!==")"?(e.advance(),!0):!1}tryMatchOfPossessiveExpression(e){let t=e.peek();if(!t||t.kind!=="selector")return null;let r=e.mark();e.advance();let n=e.peek();if(!n||!this.isOfPossessiveMarker(n))return e.reset(r),null;e.advance();let i=e.peek();return!i||i.kind!=="selector"?(e.reset(r),null):(e.advance(),se(re(i.value),t.value))}tryMatchPossessiveExpression(e){let t=e.peek();if(!t||!this.currentProfile)return null;let r=[t.value,t.normalized].filter(Boolean),n;for(let l of r)if(n=de(this.currentProfile,l)??de(this.currentProfile,l.toLowerCase()),n)break;if(!n)return null;let i=e.mark();e.advance();let s=this.currentProfile.possessive?.connectors;if(s&&s.length>0){let l=e.peek();if(l){let c=l.value.toLowerCase(),d=(l.normalized??"").toLowerCase();s.some(u=>u.toLowerCase()===c||u.toLowerCase()===d)&&e.advance()}}let a=e.peek();if(!a||wr(this.currentProfile.code,a.value))return e.reset(i),null;if(a.kind==="identifier"||a.kind==="keyword"&&!this.isStructuralKeyword(a.value)&&!(a.normalized&&this.isStructuralKeyword(a.normalized))&&!(a.normalized&&this.isRoleMarkerConcept(a.normalized))||a.kind==="selector"&&a.value.startsWith("*")||a.kind==="selector"&&a.value.startsWith("@")||a.kind==="selector"&&a.value.startsWith(".")&&/^\.[a-zA-Z_]\w*/.test(a.value)){e.advance();let l=a.value;a.kind==="selector"&&l.startsWith(".")&&/^\.[a-zA-Z_]\w*/.test(l)&&(l=l.substring(1));let c=l;for(;e.peek()?.kind==="selector"&&e.peek().value.startsWith(".")&&/^\.[a-zA-Z_]\w*/.test(e.peek().value);)c+=e.peek().value,e.advance();let d=e.peek();if(d&&d.value.startsWith("(")){let u="",f=0,m=0;for(;!e.isAtEnd()&&m++<A.MAX_METHOD_ARGS+2;){let p=e.peek();if(!p)break;u+=p.value,e.advance();for(let h of p.value)h==="("?f++:h===")"&&f--;if(f<=0)break}c+=u}return se(J(n),c)}return e.reset(i),null}tryMatchPostNominalPossessiveExpression(e){if(!this.currentProfile||this.currentProfile.possessive?.markerPosition!=="after-object")return null;let t=u=>{for(let f of[u.value,u.normalized].filter(Boolean))if(de(this.currentProfile,f)??de(this.currentProfile,f.toLowerCase()))return!0;return!1},r=e.peek();if(!r)return null;let n=r.kind==="selector"&&r.value.startsWith(".")&&/^\.[a-zA-Z_]\w*/.test(r.value);if(!(r.kind==="identifier"&&!this.isStructuralKeyword(r.value)&&!(r.normalized&&this.isStructuralKeyword(r.normalized))&&!(r.normalized&&this.isRoleMarkerConcept(r.normalized))||r.kind==="selector"&&(r.value.startsWith("*")||r.value.startsWith("@"))||n)||t(r))return null;let s=e.mark(),a=r.value;n&&(a=a.substring(1)),e.advance();let l=a;for(;e.peek()?.kind==="selector"&&e.peek().value.startsWith(".")&&/^\.[a-zA-Z_]\w*/.test(e.peek().value);)l+=e.peek().value,e.advance();let c=e.peek();if(!c)return e.reset(s),null;let d;for(let u of[c.value,c.normalized].filter(Boolean))if(d=de(this.currentProfile,u)??de(this.currentProfile,u.toLowerCase()),d)break;return d?(e.advance(),se(J(d),l)):(e.reset(s),null)}isStructuralKeyword(e){return new Set(["into","in","to","from","at","by","with","without","before","after","of","as","on","then","end","else","if","repeat","while","for","toggle","add","remove","put","set","show","hide","increment","decrement","send","trigger","call"]).has(e.toLowerCase())}isRoleMarkerConcept(e){return new Set(["destination","source","patient","object","event","eventmarker","manner","instrument"]).has(e.toLowerCase())}static tokenLooksLikeEvent(e){if(e.kind==="selector"||e.kind==="url"||e.kind==="literal")return!1;let t=e.value;if(/[/#@*]/.test(t)||t.startsWith('"')||t.startsWith("'")||t.startsWith("`"))return!1;let r=e.normalized?.toLowerCase();return!(r&&$i.has(r))}tryMatchBraceRunLiteral(e){let t=e.peek();if(!t||t.kind!=="identifier"||t.value!=="{")return null;let r=e.mark();e.advance();let n=["{"],i=1,s=0;for(;!e.isAtEnd()&&s++<A.MAX_BRACE_RUN_TOKENS;){let a=e.advance();if(!a)break;if(a.value==="{")i++;else if(a.value==="}"&&(i--,i===0))return n.push("}"),$(n.join(" "));n.push(a.value)}return e.reset(r),null}tryMatchBareCallExpression(e){let t=e.peek();if(!t||t.kind!=="identifier"||!/^[A-Za-z_][\w$]*$/.test(t.value))return null;let r=e.peek(1);if(!r||r.value!=="(")return null;let n=e.mark();e.advance(),e.advance();let i=[],s=!1,a=0;for(;!e.isAtEnd()&&a++<A.MAX_METHOD_ARGS+2;){let l=e.peek();if(!l)break;if(l.value===")"){e.advance(),s=!0;break}if(l.value===","){e.advance();continue}i.push(l.value),e.advance()}return s?{type:"expression",raw:`${t.value}(${i.join(", ")})`}:(e.reset(n),null)}tryMatchMethodCallExpression(e){let t=e.peek();if(!t||t.kind!=="selector")return null;let r=e.mark();e.advance();let n=e.peek();if(!n||n.kind!=="operator"||n.value!==".")return e.reset(r),null;e.advance();let i=e.peek();if(!i||i.kind!=="identifier")return e.reset(r),null;e.advance();let s=e.peek();if(!s||s.kind!=="punctuation"||s.value!=="(")return e.reset(r),null;e.advance();let a=[];for(;!e.isAtEnd()&&a.length<A.MAX_METHOD_ARGS;){let c=e.peek();if(!c)break;if(c.kind==="punctuation"&&c.value===")"){e.advance();break}if(c.kind==="punctuation"&&c.value===","){e.advance();continue}a.push(c.value),e.advance()}return{type:"expression",raw:`${t.value}.${i.value}(${a.join(", ")})`}}tryMatchPropertyAccessExpression(e,t=!0){let r=e.peek();if(!r||r.kind!=="identifier"&&r.kind!=="keyword")return null;let n=e.mark();e.advance();let i=r.value.toLowerCase(),s=e.peek();if((r.kind==="identifier"||A.PROPERTY_ACCESS_BASES.has(i))&&s&&s.kind==="selector"&&/^\.[a-zA-Z_]/.test(s.value)){let m=r.value,p=[],h=0;for(;h<A.MAX_PROPERTY_DEPTH;){let S=e.peek();if(S&&S.kind==="selector"&&/^\.[a-zA-Z_]/.test(S.value))m+=`.${S.value.slice(1)}`,p.push(S.value.slice(1)),e.advance(),h++;else break}let y=e.peek(),g=!!y&&y.value.startsWith("(");if(t&&!g&&p.length>0&&ke(i))return se(J(i),p.join("."));if(g){let S=e.mark(),E=[],C=0,k=!1;for(;!e.isAtEnd();){let x=e.peek();if(!x)break;if(x.value==="(")C++;else if(x.value===")"){if(E.push(x.value),e.advance(),C--,C===0&&(k=!0),k)break;continue}E.push(x.value),e.advance()}k?m+=E.join(""):e.reset(S)}return{type:"expression",raw:m}}let a=e.peek();if(!a||a.kind!=="operator"||a.value!==".")return e.reset(n),null;e.advance();let l=e.peek();if(!l||l.kind!=="identifier")return e.reset(n),null;e.advance();let c=`${r.value}.${l.value}`,d=1;for(;!e.isAtEnd()&&d<A.MAX_PROPERTY_DEPTH;){let m=e.peek();if(!m||m.kind!=="operator"||m.value!==".")break;e.advance();let p=e.peek();if(!p||p.kind!=="identifier")break;e.advance(),c+=`.${p.value}`,d++}let u=e.peek();if(u&&u.kind==="punctuation"&&u.value==="("){e.advance();let m=[],p=0;for(;!e.isAtEnd()&&m.length<A.MAX_METHOD_ARGS;){let y=e.peek();if(!y)break;if(y.kind==="punctuation"&&y.value===")"){if(p===0){e.advance();break}p--}if(y.kind==="punctuation"&&y.value==="("&&p++,y.kind==="punctuation"&&y.value===","){e.advance();continue}m.push(y.value),e.advance()}return{type:"expression",raw:`${c}(${m.join(", ")})`}}let f=r.value.toLowerCase();if(t&&ke(f)){let m=c.split(".").slice(1).join(".");return se(J(f),m)}return{type:"expression",raw:c}}tryMatchPossessiveSelectorExpression(e){let t=e.peek();if(!t||t.kind!=="selector")return null;let r=e.mark();e.advance();let n=e.peek(),i=this.currentProfile?.possessive?.marker?.replace(/^-/,""),s=!!n&&n.kind==="punctuation"&&n.value==="'s",a=!!n&&n.value==="'"&&(e.peek(1)?.value??"").toLowerCase()==="s",l=(()=>{if(!this.currentPatternCommand||(n?.normalized??"").toLowerCase()!=="source")return!1;let f=Ne[this.currentPatternCommand];return!!f&&f.roles.some(m=>m.role==="source")})(),c=!!n&&!!i&&i!=="'s"&&n.value===i&&(n.kind==="particle"||n.kind==="punctuation")&&!l;if(!s&&!c&&!a)return e.reset(r),null;e.advance(),a&&e.advance();let d=e.peek();return!d||!(d.kind==="identifier"||(s||a)&&(d.kind==="selector"||d.kind==="keyword"))?(e.reset(r),null):(e.advance(),se(re(t.value),d.value))}tryMatchSelectorPropertyExpression(e){let t=e.peek();if(!t||t.kind!=="selector"||!t.value.startsWith("#"))return null;let r=e.mark();e.advance();let n=e.peek();if(!n||n.kind!=="selector"||!n.value.startsWith("."))return e.reset(r),null;let i=e.peek(1);i&&i.kind,e.advance();let s=n.value.slice(1);return se(re(t.value),s)}matchGroupToken(e,t,r,n){let i=e.mark(),s=new Set(r.keys());if(!this.matchTokenSequence(e,t.tokens,r,n)){e.reset(i);for(let l of r.keys())s.has(l)||r.delete(l);return t.optional||!1}return!0}getMatchType(e,t){return e.value===t?"exact":e.normalized===t?"normalized":e.stem===t&&e.stemConfidence!==void 0&&e.stemConfidence>=.7?"stem":e.kind==="keyword"&&e.value.toLowerCase()===t.toLowerCase()?"case-insensitive":"none"}tokenToSemanticValue(e){switch(e.kind){case"selector":return re(e.value);case"literal":return this.parseLiteralValue(e.value);case"keyword":let t=(e.normalized||e.value).toLowerCase();return ke(t)?J(t):$(e.normalized||e.value);case"identifier":if(e.value.startsWith("@"))return re(e.value);if(e.value.startsWith(":")||e.value.startsWith("$"))return J(e.value);let r=e.value.toLowerCase();return ke(r)?J(r):{type:"expression",raw:e.value};case"url":return $(e.value,"string");default:return null}}parseLiteralValue(e){if(e.startsWith('"')||e.startsWith("'")||e.startsWith("`")||e.startsWith("\u300C")){let n=e.slice(1,-1);return $(n,"string")}if(e==="true")return $(!0,"boolean");if(e==="false")return $(!1,"boolean");let t=e.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/);if(t){let n=parseFloat(t[1]);return t[2]?$(e,"duration"):$(n,"number")}let r=parseFloat(e);return isNaN(r)?$(e,"string"):$(r,"number")}applyExtractionRules(e,t){for(let[r,n]of Object.entries(e.extraction))t.has(r)||(n.value!==void 0?t.set(r,{type:"literal",value:n.value}):n.default&&t.set(r,n.default))}isOptional(e){return e.type!=="literal"&&e.optional===!0}skipNoiseWords(e){let t=e.peek();if(!t)return;let r=t.value.toLowerCase();if(A.ENGLISH_NOISE_WORDS.has(r)){let n=e.mark();e.advance();let i=e.peek();if(i&&(i.kind==="selector"||i.kind==="identifier"))return;let s=e.peek(1);if(i&&i.kind==="keyword"&&s&&s.kind==="selector"&&/^\.[a-zA-Z_]/.test(s.value))return;let a=i?(i.normalized??i.value).toLowerCase():"";if(i&&A.POSITIONAL_OR_SCOPE_KEYWORDS.has(a))return;let l=e.peek(1),c=l?(l.normalized??l.value).toLowerCase():"",d=this.currentProfile?.wordOrder!=="SOV"&&A.COMMAND_ACTION_KEYWORDS.has(c),u=!l||l.kind==="particle"||A.CLAUSE_BOUNDARY_KEYWORDS.has(c)||d;if(i&&i.kind==="keyword"&&this.currentProfile?.code!=="en"&&ke(a)&&u||i&&i.kind==="keyword"&&this.currentProfile?.code==="en"&&ke(a))return;e.reset(n)}r==="class"&&e.advance()}extractEventModifiers(e){let t={},r=!1;for(;!e.isAtEnd();){let n=e.peek();if(!n||n.kind!=="event-modifier")break;let i=n.metadata;if(!i)break;switch(r=!0,i.modifierName){case"once":t.once=!0;break;case"debounce":typeof i.value=="number"&&(t.debounce=i.value);break;case"throttle":typeof i.value=="number"&&(t.throttle=i.value);break;case"queue":(i.value==="first"||i.value==="last"||i.value==="all"||i.value==="none")&&(t.queue=i.value);break}e.advance()}return r?t:void 0}};A.POSITIONAL_KEYWORDS=new Set(["first","last","next","previous","random","closest"]),A.POSITIONAL_OR_SCOPE_KEYWORDS=new Set(["first","last","next","previous","random","closest","parent"]),A.STRUCTURAL_NEVER_EVENT=new Set(["if","unless","else","end","then"]),A.PROPERTY_ACCESS_BASES=new Set(["it","me","you","my","its","your","event","result","target","detail","body","window","document","self","this"]),A.COMMAND_ACTION_KEYWORDS=new Set(Object.keys(Ne).map(e=>e.toLowerCase())),A.CLAUSE_BOUNDARY_KEYWORDS=new Set(["then","and","or","end","else"]),A.OF_POSSESSIVE_MARKERS={ms:new Set(["daripada"]),sw:new Set(["ya"]),vi:new Set(["c\u1EE7a"]),zh:new Set(["\u7684"]),it:new Set(["di"]),pl:new Set(["z"]),uk:new Set(["\u0437"]),th:new Set(["\u0E02\u0E2D\u0E07"]),ja:new Set(["\u306E"]),ko:new Set(["\uC758"]),bn:new Set(["\u09B0"]),hi:new Set(["\u0915\u093E"]),qu:new Set(["pa"]),tr:new Set(["nin"])},A.RUN_OPERATORS=new Set(["+","-","*","/"]),A.MAX_BRACE_RUN_TOKENS=64,A.MAX_PROPERTY_DEPTH=10,A.MAX_METHOD_ARGS=20,A.DECLARATION_COMMANDS=new Set(["behavior","def","install"]),A.ENGLISH_NOISE_WORDS=new Set(["the","a","an"]);var Bt=A,le=new Bt;var Wi=["===","!==","->","==","!=","<=",">=","&&","||","**","+=","-=","*=","/=","+","-","*","/","=",">","<","!","&","|","%","^","~"],st=class{constructor(e=Wi){this.name="operator";this.operators=[...e].sort((t,r)=>r.length-t.length)}canExtract(e,t){return this.operators.some(r=>e.startsWith(r,t))}extract(e,t){for(let r of this.operators)if(e.startsWith(r,t))return{value:r,length:r.length};return null}},ji="()[]{},:;",lt=class{constructor(e=ji){this.punctuation=e;this.name="punctuation"}canExtract(e,t){return this.punctuation.includes(e[t])}extract(e,t){let r=e[t];return this.punctuation.includes(r)?{value:r,length:1}:null}};function Dt(o,e){let t=o[e];if(t==="#"){let r=o.slice(e).match(/^#[a-zA-Z_][\w-]*/);return r?r[0]:null}if(t==="."){let r=o.slice(e).match(/^\.\{[a-zA-Z_$][\w$]*\}/);if(r)return r[0];let n=o.slice(e).match(/^\.[a-zA-Z_][\w-]*/);return n?n[0]:null}if(t==="@"){let r=o.slice(e).match(/^@[a-zA-Z_][\w-]*/);return r?r[0]:null}if(t==="*"){let r=o.slice(e).match(/^\*(?:--)?[a-zA-Z_][\w-]*/);return r?r[0]:null}if(t==="["){let r=0,n=e;for(;n<o.length;){if(o[n]==="["&&r++,o[n]==="]"&&(r--,r===0))return o.slice(e,n+1);n++}return null}if(t==="<"){let r=o.slice(e).match(/^<(?=[\w.#[])[\w-]*(?:[#.][\w-]+|\[[^\]]+\])*\s*\/>/);return r?r[0]:null}return null}var We=class{constructor(){this.name="css-selector"}canExtract(e,t){let r=e[t];return r==="#"||r==="."||r==="["||r==="<"?!0:r==="@"||r==="*"?Dt(e,t)!==null:!1}extract(e,t){let r=Dt(e,t);return r?{value:r,length:r.length,metadata:{type:"css-selector"}}:null}};var je=class{constructor(){this.name="event-modifier"}canExtract(e,t){if(e[t]!==".")return!1;let r=e.slice(t);return/^\.(once|prevent|stop|debounce|throttle|queue)/.test(r)}extract(e,t){let r=e.slice(t).match(/^\.(?:once|prevent|stop|debounce|throttle|queue)(?:\(([^)]+)\))?/);if(!r)return null;let n=r[0],i=n.slice(1).split("(")[0],s=r[1];return{value:n,length:n.length,metadata:{modifierName:i,value:s?i==="queue"?s:parseInt(s,10):void 0}}}};function Nr(o,e){let t=o.slice(e);if(t.startsWith("http://")||t.startsWith("https://")){let r=t.match(/^https?:\/\/[^\s]*/);return r?r[0]:null}if(t.startsWith("//")){let r=t.match(/^\/\/[^\s]*/);return r?r[0]:null}if(t.startsWith("./")||t.startsWith("../")){let r=t.match(/^\.\.?\/[^\s]*/);return r?r[0]:null}if(t.startsWith("/")){let r=t.match(/^\/[^\s]*/);return r?r[0]:null}return null}var qe=class{constructor(){this.name="url"}canExtract(e,t){let r=e.slice(t);return r.startsWith("http://")||r.startsWith("https://")||r.startsWith("//")||r.startsWith("./")||r.startsWith("../")||r.startsWith("/")}extract(e,t){let r=Nr(e,t);return r?{value:r,length:r.length,metadata:{type:"url"}}:null}};var Ke=class{constructor(){this.name="variable-ref"}canExtract(e,t){let r=e[t];return(r===":"||r==="$"||r==="^")&&t+1<e.length&&/[a-zA-Z_]/.test(e[t+1])}extract(e,t){if(!this.canExtract(e,t))return null;let r=1;for(;t+r<e.length&&/[a-zA-Z0-9_]/.test(e[t+r]);)r++;return{value:e.substring(t,t+r),length:r,metadata:{type:"variable-reference"}}}};var Rr=ue([[1536,1791],[1872,1919],[2208,2303],[64336,65023],[65136,65279]]),qi=new Set(["\u0641\u064A","\u0639\u0644\u0649","\u0645\u0646","\u0625\u0644\u0649","\u0627\u0644\u0649","\u0645\u0639","\u0639\u0646","\u0642\u0628\u0644","\u0628\u0639\u062F","\u0628\u064A\u0646"]),ct=class{constructor(){this.name="arabic-keyword"}setContext(e){this.context=e}canExtract(e,t){return Rr(e[t])}extract(e,t){if(!this.context)throw new Error("ArabicKeywordExtractor: context not set");let r=t;this.context.isKeywordStart(e,t);let n="",i=t;for(;i<e.length&&(Rr(e[i])||e[i]==="\u0640");)n+=e[i],i++;if(!n)return null;let s=this.context.lookupKeyword(n),a=s&&s.normalized!==s.native?s.normalized:void 0;if(qi.has(n))return{value:n,length:i-r,metadata:{prepositionValue:n,normalized:a}};let l,c,d;if(!s&&this.context.normalizer){let u=this.context.normalizer.normalize(n);if(u.stem!==n&&u.confidence>=.7){let f=this.context.lookupKeyword(u.stem);f&&(l=f.normalized,c=u.stem,d=u.confidence)}}return{value:n,length:i-r,metadata:{normalized:a||l,stem:c,stemConfidence:d}}}};var Fe=ue([[1536,1791],[1872,1919],[2208,2303],[64336,65023],[65136,65279]]),Ue=new Map([["\u0648",{normalized:"and",type:"conjunction"}],["\u0641",{normalized:"then",type:"conjunction"}],["\u0628",{normalized:"with",type:"preposition"}],["\u0644",{normalized:"to",type:"preposition"}],["\u0643",{normalized:"like",type:"preposition"}],["\u0648\u0644",{normalized:"and-to",type:"conjunction"}],["\u0648\u0628",{normalized:"and-with",type:"conjunction"}],["\u0648\u0643",{normalized:"and-like",type:"conjunction"}],["\u0641\u0644",{normalized:"then-to",type:"conjunction"}],["\u0641\u0628",{normalized:"then-with",type:"conjunction"}],["\u0641\u0643",{normalized:"then-like",type:"conjunction"}]]),Ki=new Set(["\u0648\u062B\u064A\u0642\u0629"]),ut=class{constructor(){this.name="arabic-proclitic"}setContext(e){this.context=e}canExtract(e,t){let r=e[t];return Ue.has(r)||t+1<e.length&&Ue.has(e.slice(t,t+2))}extract(e,t){if(!this.context)throw new Error("ArabicProcliticExtractor: context not set");let r=t;for(;r<e.length&&(Fe(e[r])||e[r]==="\u0640");)r++;let n=e.slice(t,r);if(this.context.isKeyword(n)||Ki.has(n))return null;if(t+2<=e.length){let d=e.slice(t,t+2),u=Ue.get(d);if(u){let f=t+2;if(f<e.length&&Fe(e[f])){let m=0,p=f;for(;p<e.length&&Fe(e[p]);)m++,p++;if(m>=2)if(Ue.get(e[t])){let y=e.slice(t+1,r);if(!this.context.isKeyword(y))return{value:d,length:2,metadata:{procliticType:u.type,normalized:u.normalized}}}else return{value:d,length:2,metadata:{procliticType:u.type,normalized:u.normalized}}}}}let i=e[t],s=Ue.get(i);if(!s)return null;let a=t+1;if(a>=e.length||!Fe(e[a]))return null;let l=0,c=a;for(;c<e.length&&Fe(e[c]);)l++,c++;return l<2?null:{value:i,length:1,metadata:{procliticType:s.type,normalized:s.normalized}}}};var Fi=ue([[1536,1791],[1872,1919],[2208,2303],[64336,65023],[65136,65279]]),Lr=new Map([["\u0639\u0646\u062F\u0645\u0627",{normalized:"on",formality:"formal",confidence:.95,description:"when (formal MSA)"}],["\u062D\u064A\u0646\u0645\u0627",{normalized:"on",formality:"formal",confidence:.93,description:"when/whenever (formal)"}],["\u0639\u0646\u062F",{normalized:"on",formality:"neutral",confidence:.88,description:"at/when (neutral)"}],["\u062D\u064A\u0646",{normalized:"on",formality:"neutral",confidence:.85,description:"when/time (neutral)"}],["\u0644\u0645\u0651\u0627",{normalized:"on",formality:"dialectal",confidence:.7,description:"when (dialectal, with shadda)"}],["\u0644\u0645\u0627",{normalized:"on",formality:"dialectal",confidence:.68,description:"when (dialectal, no diacritic)"}],["\u0644\u062F\u0649",{normalized:"on",formality:"neutral",confidence:.82,description:"at/with (temporal)"}]]),dt=class{constructor(){this.name="arabic-temporal"}setContext(e){this._context=e,this._context}canExtract(e,t){for(let[r]of Lr)if(e.startsWith(r,t))return!0;return!1}extract(e,t){let r=Array.from(Lr.entries()).sort(([n],[i])=>i.length-n.length);for(let[n,i]of r)if(e.startsWith(n,t)){let s=t+n.length;if(s>=e.length||/\s/.test(e[s])||!Fi(e[s]))return{value:n,length:n.length,metadata:{temporalFormality:i.formality,temporalConfidence:i.confidence,normalized:i.normalized,description:i.description}}}return null}};function Ui(o){let e=o.charCodeAt(0);return e>=65&&e<=90||e>=97&&e<=122||e===95||e===36}function Hi(o){let e=o.charCodeAt(0);return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===95||e===36}var pt=class{constructor(){this.name="ascii-identifier"}setContext(e){this.context=e}canExtract(e,t){return Ui(e[t])}extract(e,t){if(!this.context)throw new Error("AsciiIdentifierExtractor: context not set");let r=t,n="",i=t;for(;i<e.length&&Hi(e[i]);)n+=e[i],i++;if(!n)return null;let s=this.context.lookupKeyword(n),a=s&&s.normalized!==s.native?s.normalized:void 0;return{value:n,length:i-r,metadata:{normalized:a}}}};function Ar(){return[new qe,new je,new Ke,new We]}function Gi(o){let e=o.charCodeAt(0);return e>=1536&&e<=1791||e>=1872&&e<=1919||e>=2208&&e<=2303||e>=64336&&e<=65023||e>=65136&&e<=65279}function Yi(o){for(let e of o)if(Gi(e))return!0;return!1}function Zi(o){return o.replace(/[\u064B-\u0652\u0670]/g,"")}var Ji=[{pattern:"\u0648\u0627\u0644",confidencePenalty:.15,prefixType:"conjunction"},{pattern:"\u0641\u0627\u0644",confidencePenalty:.15,prefixType:"conjunction"},{pattern:"\u0628\u0627\u0644",confidencePenalty:.15,prefixType:"preposition"},{pattern:"\u0643\u0627\u0644",confidencePenalty:.15,prefixType:"preposition"},{pattern:"\u0644\u0644",confidencePenalty:.12,prefixType:"preposition"}],Xi=[{pattern:"\u0627\u0644",confidencePenalty:.08,prefixType:"article",minRemaining:2},{pattern:"\u0648",confidencePenalty:.08,prefixType:"conjunction",minRemaining:3},{pattern:"\u0641",confidencePenalty:.08,prefixType:"conjunction",minRemaining:3},{pattern:"\u0628",confidencePenalty:.1,prefixType:"preposition",minRemaining:3},{pattern:"\u0644",confidencePenalty:.1,prefixType:"preposition",minRemaining:3},{pattern:"\u0643",confidencePenalty:.1,prefixType:"preposition",minRemaining:3}],Qi=[{pattern:"\u064A",confidencePenalty:.12,prefixType:"verb-marker",minRemaining:3},{pattern:"\u062A",confidencePenalty:.12,prefixType:"verb-marker",minRemaining:3},{pattern:"\u0646",confidencePenalty:.12,prefixType:"verb-marker",minRemaining:3},{pattern:"\u0623",confidencePenalty:.12,prefixType:"verb-marker",minRemaining:3},{pattern:"\u0627",confidencePenalty:.12,prefixType:"verb-marker",minRemaining:3}],ea=[{pattern:"\u0648\u0646",confidencePenalty:.1,type:"masculine-plural"},{pattern:"\u064A\u0646",confidencePenalty:.1,type:"masculine-plural-accusative"},{pattern:"\u0627\u062A",confidencePenalty:.1,type:"feminine-plural"},{pattern:"\u0627\u0646",confidencePenalty:.1,type:"dual-nominative"},{pattern:"\u064A\u0646",confidencePenalty:.1,type:"dual-accusative"},{pattern:"\u0647\u0627",confidencePenalty:.1,type:"pronoun-her"},{pattern:"\u0647\u0645",confidencePenalty:.1,type:"pronoun-them"},{pattern:"\u0647\u0646",confidencePenalty:.1,type:"pronoun-them-f"},{pattern:"\u0646\u0627",confidencePenalty:.1,type:"pronoun-us"},{pattern:"\u0643\u0645",confidencePenalty:.1,type:"pronoun-you-pl"},{pattern:"\u0643",confidencePenalty:.08,type:"pronoun-you"},{pattern:"\u0647",confidencePenalty:.08,type:"pronoun-him"},{pattern:"\u064A",confidencePenalty:.08,type:"pronoun-me"},{pattern:"\u0629",confidencePenalty:.08,type:"feminine"}],He=class{constructor(){this.language="ar"}isNormalizable(e){return!(!Yi(e)||e.length<2)}normalize(e){let t=Zi(e),r=1,n=[],i=[];for(let a of Ji)if(t.startsWith(a.pattern)){let l=t.slice(a.pattern.length);if(l.length>=2){t=l,r-=a.confidencePenalty,n.push(a.pattern);break}}if(n.length===0){for(let a of Xi)if(t.startsWith(a.pattern)){let l=t.slice(a.pattern.length),c=a.minRemaining??2;if(l.length>=c){t=l,r-=a.confidencePenalty,n.push(a.pattern);break}}}if(!(t.endsWith("\u0627\u062A")||t.endsWith("\u0629")||t.endsWith("\u0648\u0646")||t.endsWith("\u064A\u0646")||t.endsWith("\u0647\u0627")||t.endsWith("\u0647\u0645")||t.endsWith("\u0647\u0646")||t.endsWith("\u0646\u0627")||t.endsWith("\u0643\u0645"))&&(n.length===0||n[0]==="\u0648"||n[0]==="\u0641")){for(let a of Qi)if(t.startsWith(a.pattern)){let l=t.slice(a.pattern.length),c=a.minRemaining??3;if(l.length>=c){t=l,r-=a.confidencePenalty,n.push(a.pattern);break}}}for(let a of ea)if(t.endsWith(a.pattern)){let l=t.slice(0,-a.pattern.length);l.length>=2&&(t=l,r-=a.confidencePenalty,i.push(a.pattern))}return r=Math.max(.5,r),n.length===0&&i.length===0?zt(e):Vt(t,r,{removedPrefixes:n,removedSuffixes:i})}},cl=new He;var ta=new Set(["\u0648\u0644","\u0648\u0628","\u0648\u0643","\u0641\u0644","\u0641\u0628","\u0641\u0643"]),ra=new Set(["\u0641\u064A","\u0639\u0644\u0649","\u0645\u0646","\u0625\u0644\u0649","\u0627\u0644\u0649","\u0645\u0639","\u0639\u0646","\u0642\u0628\u0644","\u0628\u0639\u062F","\u0628\u064A\u0646","\u0628","\u0644","\u0643"]),na=[{native:"\u0635\u062D\u064A\u062D",normalized:"true"},{native:"\u062E\u0637\u0623",normalized:"false"},{native:"null",normalized:"null"},{native:"\u0641\u0627\u0631\u063A",normalized:"null"},{native:"\u063A\u064A\u0631 \u0645\u0639\u0631\u0641",normalized:"undefined"},{native:"\u0627\u0644\u0623\u0648\u0644",normalized:"first"},{native:"\u0623\u0648\u0644",normalized:"first"},{native:"\u0627\u0644\u0623\u062E\u064A\u0631",normalized:"last"},{native:"\u0622\u062E\u0631",normalized:"last"},{native:"\u0627\u0644\u062A\u0627\u0644\u064A",normalized:"next"},{native:"\u0627\u0644\u0633\u0627\u0628\u0642",normalized:"previous"},{native:"\u0627\u0644\u0623\u0642\u0631\u0628",normalized:"closest"},{native:"\u0627\u0644\u0623\u0628",normalized:"parent"},{native:"\u0627\u0644\u0646\u0642\u0631",normalized:"click"},{native:"\u0646\u0642\u0631",normalized:"click"},{native:"\u0627\u0644\u0625\u062F\u062E\u0627\u0644",normalized:"input"},{native:"\u0625\u062F\u062E\u0627\u0644",normalized:"input"},{native:"\u0627\u0644\u062A\u063A\u064A\u064A\u0631",normalized:"change"},{native:"\u062A\u063A\u064A\u064A\u0631",normalized:"change"},{native:"\u0627\u0644\u0625\u0631\u0633\u0627\u0644",normalized:"submit"},{native:"\u0625\u0631\u0633\u0627\u0644",normalized:"submit"},{native:"\u0627\u0644\u062A\u0631\u0643\u064A\u0632",normalized:"focus"},{native:"\u0641\u0642\u062F\u0627\u0646 \u0627\u0644\u062A\u0631\u0643\u064A\u0632",normalized:"blur"},{native:"\u0636\u063A\u0637",normalized:"keydown"},{native:"\u0631\u0641\u0639",normalized:"keyup"},{native:"\u062A\u0645\u0631\u064A\u0631 \u0627\u0644\u0641\u0623\u0631\u0629",normalized:"mouseover"},{native:"\u0645\u063A\u0627\u062F\u0631\u0629 \u0627\u0644\u0641\u0623\u0631\u0629",normalized:"mouseout"},{native:"\u062A\u062D\u0645\u064A\u0644",normalized:"load"},{native:"\u062A\u0645\u0631\u064A\u0631",normalized:"scroll"},{native:"\u0641\u0623\u0631\u0629 \u0623\u0633\u0641\u0644",normalized:"mousedown"},{native:"\u0641\u0623\u0631\u0629 \u0623\u0639\u0644\u0649",normalized:"mouseup"},{native:"\u0641\u0623\u0631\u0629 \u062F\u062E\u0648\u0644",normalized:"mouseenter"},{native:"\u0641\u0623\u0631\u0629 \u062E\u0631\u0648\u062C",normalized:"mouseleave"},{native:"\u0641\u0623\u0631\u0629 \u0641\u0648\u0642",normalized:"mouseover"},{native:"\u0641\u0623\u0631\u0629 \u062E\u0627\u0631\u062C",normalized:"mouseout"},{native:"\u0641\u0623\u0631\u0629 \u062A\u062D\u0631\u0643",normalized:"mousemove"},{native:"\u0645\u0641\u062A\u0627\u062D \u0623\u0633\u0641\u0644",normalized:"keydown"},{native:"\u0645\u0641\u062A\u0627\u062D \u0623\u0639\u0644\u0649",normalized:"keyup"},{native:"\u0647\u064A",normalized:"it"},{native:"\u062B\u0627\u0646\u064A\u0629",normalized:"s"},{native:"\u062B\u0648\u0627\u0646\u064A",normalized:"s"},{native:"\u0645\u0644\u064A \u062B\u0627\u0646\u064A\u0629",normalized:"ms"},{native:"\u062F\u0642\u064A\u0642\u0629",normalized:"m"},{native:"\u062F\u0642\u0627\u0626\u0642",normalized:"m"},{native:"\u0633\u0627\u0639\u0629",normalized:"h"},{native:"\u0633\u0627\u0639\u0627\u062A",normalized:"h"},{native:"\u0639\u0646\u062F\u0645\u0627",normalized:"on"},{native:"\u062D\u064A\u0646\u0645\u0627",normalized:"on"},{native:"\u0639\u0646\u062F",normalized:"on"},{native:"\u062D\u064A\u0646",normalized:"on"},{native:"\u0644\u0645\u0651\u0627",normalized:"on"},{native:"\u0644\u0645\u0627",normalized:"on"},{native:"\u0644\u062F\u0649",normalized:"on"}],$t=class extends Be{constructor(){super();this.language="ar";this.direction="rtl";this.initializeKeywordsFromProfile(xe,na),this.normalizer=new He,this.registerExtractors(Ar()),this.registerExtractor(new Mt),this.registerExtractor(new Ot),this.registerExtractor(new pt),this.registerExtractor(new dt),this.registerExtractor(new ut),this.registerExtractor(new ct),this.registerExtractor(new st),this.registerExtractor(new lt)}tokenizeWithExtractors(t){let r=[],n=0;for(;n<t.length;){for(;n<t.length&&ae(t[n]);)n++;if(n>=t.length)break;let i=this.tryMultiWordKeyword(t,n);if(i){r.push(i),n=i.position.end;continue}let s=!1;for(let a of this.extractors)if(a.canExtract(t,n)){let l=a.extract(t,n);if(l){let c=l.metadata?.normalized,d=l.metadata?.stem,u=l.metadata?.stemConfidence,f={};if(l.metadata)for(let[h,y]of Object.entries(l.metadata))h!=="normalized"&&h!=="stem"&&h!=="stemConfidence"&&(f[h]=y);let m;f.procliticType==="conjunction"?m="conjunction":f.procliticType==="preposition"?m="particle":m=this.classifyToken(l.value);let p={};c&&(p.normalized=c),d&&(p.stem=d),u!==void 0&&(p.stemConfidence=u),Object.keys(f).length>0&&(p.metadata=f),r.push(B(l.value,m,_(n,n+l.length),Object.keys(p).length>0?p:void 0)),n+=l.length,s=!0;break}}if(!s){let a=t[n],l=this.classifyUnknownChar(a);r.push(B(a,l,_(n,n+1))),n++}}return new H(r,this.language)}classifyToken(t){return ta.has(t)?"conjunction":ra.has(t)?"particle":this.isKeyword(t)?"keyword":t.startsWith("/")||t.startsWith("./")||t.startsWith("../")||t.startsWith("http")?"url":/^\.(once|prevent|stop|debounce|throttle|queue)(\(.*\))?$/.test(t)?"event-modifier":t.startsWith("#")||t.startsWith(".")||t.startsWith("[")||t.startsWith("*")||t.startsWith("<")?"selector":t.startsWith('"')||t.startsWith("'")||/^\d/.test(t)?"literal":"identifier"}},mt=new $t;function Y(o,e){return or(o,e)}function ft(){return Ct()}var yt=["if","unless","repeat","for","while"];function ce(o,e){let t=new Set([e]),n=V(o)?.keywords?.[e];if(n){n.primary&&t.add(n.primary.toLowerCase());for(let i of n.alternatives??[])t.add(i.toLowerCase())}return t}function te(o,e){return e.has(o.value.toLowerCase())?!0:o.normalized?e.has(o.normalized.toLowerCase()):!1}var ia=new Set(yt);function jt(o,e){let t=o.normalized?.toLowerCase();return t?ia.has(t):e.some(r=>te(o,r))}var Mr=new Set(["me","it","you","the","body","window","document","its","event","result","target","self","this","them","parent","next","previous","closest","first","last"]),aa=new Set(["destination","source","style","patient","on","from","to"]);function sa(o){if(!o||o.kind==="selector")return!1;let e=(o.normalized??o.value).toLowerCase(),t=o.value.toLowerCase();return!(Mr.has(e)||Mr.has(t)||aa.has(e))}var Or=new Set(["ja","ko"]);function Wt(o){let e=new Set;o?.primary&&e.add(o.primary.toLowerCase());for(let t of o?.alternatives??[])e.add(t.toLowerCase());return e}function Vr(o,e){let t=[],r=e.position.end,n=o.slice(e.position.end).match(/^\s*\(([^)]*)\)/);if(n){r=e.position.end+n[0].length;for(let i of n[1].split(/[,،、]/)){let s=i.trim();s&&t.push(s)}}return{parameters:t,headerEnd:r}}function Ir(o,e,t){let r=e+1;if(r>=o.length)return-1;let n=Wt(V(t)?.roleMarkers?.patient);return n.size>0&&te(o[r],n)&&r++,r<o.length?r:-1}function _r(o,e,t){if(!V(e))return null;let r=ce(e,"behavior"),n=ce(e,"def"),i=o.toLowerCase(),s=[...r].some(d=>i.includes(d)),a=/\bdef\b/.test(i)||[...n].some(d=>d!=="def"&&i.includes(d));if(!s&&!a)return null;let l=Y(o,e).tokens;if(l.length<2)return null;if(te(l[0],r))return zr(o,e,l,t,0);let c=l.findIndex((d,u)=>u>0&&te(d,r));return c>0&&/^[A-Z][A-Za-z0-9_]*$/.test(l[0].value)?zr(o,e,l,t,c):te(l[0],n)?la(o,e,l,t):null}function Br(o,e,t){let r=V(e);if(!r)return null;let n=r.wordOrder!=="SOV",i=Or.has(e)?Wt(r.roleMarkers?.event):new Set,s=Or.has(e)?Wt(r.keywords?.on):new Set,a=i.size>0&&s.size>0,l=ce(e,"end"),c=ce(e,"on"),d=o.toLowerCase(),u=[...l].some(x=>d.includes(x)),f=(n||a)&&(()=>{let x=0;for(let T of c)if(T){for(let v=d.indexOf(T);v>=0;v=d.indexOf(T,v+T.length))if(++x>=2)return!0}return!1})();if(!u&&!f)return null;let m=Y(o,e).tokens;if(m.length<2)return null;let p=yt.map(x=>ce(e,x)),h=x=>jt(x,p),y=x=>te(x,l),g=[],S=0,E=0;for(let x=0;x<m.length;x++){let T=m[x];if(y(T)){if(S>0){S--;continue}let v=o.slice(m[E].position.start,T.position.start).trim();v&&g.push(v),E=x+1}else if(h(T))S++;else if(n&&S===0&&x>E&&te(T,c)&&sa(m[x+1])){let v=o.slice(m[E].position.start,T.position.start).trim();v&&g.push(v),E=x}else if(a&&S===0&&x-1>E&&te(T,i)&&m[x+1]!==void 0&&te(m[x+1],s)){let v=m[x-1],b=o.slice(m[E].position.start,v.position.start).trim();b&&g.push(b),E=x-1}}if(E<m.length){let x=o.slice(m[E].position.start).trim();x&&g.push(x)}if(g.length<2)return null;let C=[],k=[];for(let x of g){let T;try{T=t.statement(x,e)}catch{return null}if(!T||T.kind!=="event-handler")return null;let v=T;C.push(v);let b=!v.body||v.body.length===0;k.push(b?.2:v.metadata?.confidence??.75)}return De(C,"then",{sourceLanguage:e,confidence:ht(k),sourceText:o})}function ht(o){return o.length>0?o.reduce((e,t)=>e+t,0)/o.length:0}function Dr(o){let e=[];for(let t of o){let r=t.statements;t.kind==="compound"&&Array.isArray(r)?e.push(...r):e.push(t)}return e}function zr(o,e,t,r,n){let i=n>0,s=i?0:Ir(t,n,e);if(s<0)return null;let a=t[s],l=a.value;if(!/^[A-Z][A-Za-z0-9_]*$/.test(l))return null;let{parameters:c,headerEnd:d}=Vr(o,a),u=i?n+1:t.findIndex(v=>v.position.start>=d);u<=s&&(u=s+1);let f=ce(e,"init"),m=ce(e,"end"),p=yt.map(v=>ce(e,v)),h=v=>jt(v,p),y=v=>te(v,m),g=[],S=[],E=[],C=!1,k=0,x=u;for(let v=u;v<t.length;v++){let b=t[v];if(y(b)){if(k>0){k--;continue}if(v===x){C=!0;break}if(te(t[x],f)){let N=o.slice(t[x].position.end,b.position.start).trim();if(N)try{let P=Dr(r.body(N,e));S.push(...P),E.push(ht(P.map(z=>z.metadata?.confidence??.75)))}catch{E.push(0)}}else{let N=o.slice(t[x].position.start,b.position.start).trim();try{let P=r.statement(N,e);if(P&&P.kind==="event-handler"){let z=P;g.push(z);let M=!z.body||z.body.length===0;E.push(M?.2:z.metadata?.confidence??.75)}else E.push(0)}catch{E.push(0)}}x=v+1}else h(b)&&k++}if(g.length===0&&S.length===0)return null;let T=(C?1:.8)*ht(E);return vr(l,c,g,S.length>0?S:void 0,{sourceLanguage:e,confidence:T,sourceText:o})}function la(o,e,t,r){let n=Ir(t,0,e);if(n<0)return null;let i=t[n],s=i.value;if(!/^[a-zA-Z_$][\w$]*(?:\.[a-zA-Z_$][\w$]*)*$/.test(s))return null;let{parameters:a,headerEnd:l}=Vr(o,i),c=t.findIndex(k=>k.position.start>=l);c<=n&&(c=n+1);let d=ce(e,"end"),u=yt.map(k=>ce(e,k)),f=k=>jt(k,u),m=k=>te(k,d),p=0,h=-1;for(let k=c;k<t.length;k++)if(m(t[k])){if(p===0){h=k;break}p--}else f(t[k])&&p++;let y=t[c]?.position.start??l,g=h>=0?t[h].position.start:o.length,S=o.slice(y,g).trim();if(!S)return null;let E;try{E=Dr(r.body(S,e))}catch{return null}if(E.length===0)return null;let C=ht(E.map(k=>k.metadata?.confidence??.75));return h<0&&(C*=.8),xr(s,a,E,{sourceLanguage:e,confidence:C,sourceText:o})}var Se={ko:{\uD074\uB9AD:"click",\uC785\uB825:"input",\uBCC0\uACBD:"change",\uC81C\uCD9C:"submit",\uD0A4\uB2E4\uC6B4:"keydown",\uD0A4\uC5C5:"keyup",\uB9C8\uC6B0\uC2A4\uC624\uBC84:"mouseover",\uB9C8\uC6B0\uC2A4\uC544\uC6C3:"mouseout",\uB9C8\uC6B0\uC2A4\uB2E4\uC6B4:"mousedown",\uB9C8\uC6B0\uC2A4\uC5C5:"mouseup",\uD3EC\uCEE4\uC2A4:"focus",\uBE14\uB7EC:"blur",\uB85C\uB4DC:"load",\uB9AC\uC0AC\uC774\uC988:"resize",\uC2A4\uD06C\uB864:"scroll"},ja:{\u30AF\u30EA\u30C3\u30AF:"click",\u5165\u529B:"input",\u5909\u66F4:"change",\u9001\u4FE1:"submit",\u30AD\u30FC\u30C0\u30A6\u30F3:"keydown",\u30AD\u30FC\u30A2\u30C3\u30D7:"keyup",\u30AD\u30FC\u30D7\u30EC\u30B9:"keypress",\u30DE\u30A6\u30B9\u30AA\u30FC\u30D0\u30FC:"mouseover",\u30DE\u30A6\u30B9\u30A2\u30A6\u30C8:"mouseout",\u30DE\u30A6\u30B9\u62BC\u4E0B:"mousedown",\u30DE\u30A6\u30B9\u89E3\u653E:"mouseup",\u30D5\u30A9\u30FC\u30AB\u30B9:"focus",\u30D6\u30E9\u30FC:"blur",\u30ED\u30FC\u30C9:"load",\u8AAD\u307F\u8FBC\u307F:"load",\u30B5\u30A4\u30BA\u5909\u66F4:"resize",\u30B9\u30AF\u30ED\u30FC\u30EB:"scroll"},ar:{\u0627\u0644\u0646\u0642\u0631:"click",\u0646\u0642\u0631:"click",\u0627\u0644\u0625\u062F\u062E\u0627\u0644:"input",\u0625\u062F\u062E\u0627\u0644:"input",\u0627\u0644\u062A\u063A\u064A\u064A\u0631:"change",\u062A\u063A\u064A\u064A\u0631:"change",\u0627\u0644\u0625\u0631\u0633\u0627\u0644:"submit",\u0625\u0631\u0633\u0627\u0644:"submit","\u0636\u063A\u0637 \u0627\u0644\u0645\u0641\u062A\u0627\u062D":"keydown","\u0631\u0641\u0639 \u0627\u0644\u0645\u0641\u062A\u0627\u062D":"keyup","\u062A\u0645\u0631\u064A\u0631 \u0627\u0644\u0645\u0627\u0648\u0633":"mouseover",\u0627\u0644\u062A\u0631\u0643\u064A\u0632:"focus",\u062A\u062D\u0645\u064A\u0644:"load",\u062A\u0645\u0631\u064A\u0631:"scroll"},es:{clic:"click",click:"click",entrada:"input",cambio:"change",env\u00EDo:"submit",enviar:"submit","tecla abajo":"keydown","tecla arriba":"keyup","rat\xF3n encima":"mouseover","rat\xF3n fuera":"mouseout",enfoque:"focus",desenfoque:"blur",carga:"load",desplazamiento:"scroll"},tr:{t\u0131klama:"click",t\u0131kla:"click",t\u0131k:"click",giri\u015F:"input",girdi:"input",de\u011Fi\u015Fiklik:"change",de\u011Fi\u015Fim:"change",g\u00F6nderme:"submit",g\u00F6nder:"submit",tu\u015Fbasma:"keydown",tu\u015Fb\u0131rakma:"keyup",fare_bas:"mousedown",fare_b\u0131rak:"mouseup",farei\u00E7inde:"mouseover",fared\u0131\u015F\u0131nda:"mouseout",odaklanma:"focus",odak:"focus",bulan\u0131kl\u0131k:"blur",y\u00FCkleme:"load",y\u00FCkle:"load",boyutland\u0131rma:"resize",boyutland\u0131r:"resize",kayd\u0131rma:"scroll"},pt:{clique:"click",clicar:"click",click:"click",entrada:"input",inserir:"input",mudan\u00E7a:"change",mudanca:"change",alterar:"change",envio:"submit",enviar:"submit","tecla baixo":"keydown","tecla cima":"keyup","pressionar tecla":"keydown","soltar tecla":"keyup","mouse sobre":"mouseover","mouse fora":"mouseout",foco:"focus",focar:"focus",desfoque:"blur",desfocar:"blur",carregar:"load",carregamento:"load",rolagem:"scroll",rolar:"scroll"},zh:{\u70B9\u51FB:"click",\u5355\u51FB:"click",\u53CC\u51FB:"dblclick",\u8F93\u5165:"input",\u6539\u53D8:"change",\u53D8\u5316:"change",\u53D8\u66F4:"change",\u63D0\u4EA4:"submit",\u53D1\u9001:"submit",\u6309\u952E:"keydown",\u952E\u5165:"keydown",\u677E\u952E:"keyup",\u9F20\u6807\u8FDB\u5165:"mouseover",\u9F20\u6807\u79FB\u5165:"mouseover",\u9F20\u6807\u79BB\u5F00:"mouseout",\u9F20\u6807\u79FB\u51FA:"mouseout",\u7126\u70B9:"focus",\u805A\u7126:"focus",\u5931\u7126:"blur",\u6A21\u7CCA:"blur",\u52A0\u8F7D:"load",\u8F7D\u5165:"load",\u6EDA\u52A8:"scroll"},fr:{clic:"click",cliquer:"click",click:"click",saisie:"input",entr\u00E9e:"input",changement:"change",changer:"change",soumettre:"submit",soumission:"submit",envoi:"submit","touche bas":"keydown","touche haut":"keyup","souris dessus":"mouseover","souris dehors":"mouseout",focus:"focus",focaliser:"focus",d\u00E9focus:"blur",d\u00E9focaliser:"blur",chargement:"load",charger:"load",d\u00E9filement:"scroll",d\u00E9filer:"scroll"},de:{klick:"click",klicken:"click",click:"click",eingabe:"input",eingeben:"input",\u00E4nderung:"change",\u00E4ndern:"change",absenden:"submit",einreichen:"submit","taste runter":"keydown","taste hoch":"keyup","maus \xFCber":"mouseover","maus raus":"mouseout",fokus:"focus",fokussieren:"focus",defokussieren:"blur",unsch\u00E4rfe:"blur",laden:"load",ladung:"load",scrollen:"scroll",bl\u00E4ttern:"scroll"},id:{klik:"click",click:"click",masukan:"input",input:"input",ubah:"change",perubahan:"change",kirim:"submit","tekan tombol":"keydown","lepas tombol":"keyup","mouse masuk":"mouseover","mouse keluar":"mouseout",fokus:"focus",blur:"blur",muat:"load",memuat:"load",gulir:"scroll",menggulir:"scroll"},bn:{\u0995\u09CD\u09B2\u09BF\u0995:"click",\u0987\u09A8\u09AA\u09C1\u099F:"input",\u099C\u09AE\u09BE:"submit",\u09B2\u09CB\u09A1:"load",\u09B8\u09CD\u0995\u09CD\u09B0\u09CB\u09B2:"scroll",\u09B0\u09BF\u09B8\u09BE\u0987\u099C:"resize",\u099D\u09BE\u09AA\u09B8\u09BE:"blur",\u09AB\u09CB\u0995\u09BE\u09B8:"focus",\u09AA\u09B0\u09BF\u09AC\u09B0\u09CD\u09A4\u09A8:"change"},qu:{click:"click","\xF1it'iy":"click",\u00F1itiy:"click",yaykuchiy:"input",yaykuy:"input",tikray:"change","t'ikray":"change",apachiy:"submit",kachay:"submit","llave uray":"keydown","llave hawa":"keyup","q'away":"focus",qhaway:"focus",paqariy:"blur","mana q'away":"blur",cargay:"load",apakuy:"load",apamuy:"load",kunray:"scroll",muyuy:"scroll",hatun_kay:"resize"},sw:{bofya:"click",click:"click",kubofya:"click",ingiza:"input",kubadilisha:"change",mabadiliko:"change",tuma:"submit",kutuma:"submit","bonyeza chini":"keydown","bonyeza juu":"keyup","panya juu":"mouseover","panya nje":"mouseout",lenga:"focus",kulenga:"focus",blur:"blur",pakia:"load",kupakia:"load",sogeza:"scroll",kusogeza:"scroll"}};var ca=Object.fromEntries(Object.entries(Se).map(([o,e])=>{let t={};for(let[r,n]of Object.entries(e))n in t||(t[n]=r);return[o,t]})),ua={ar:new Set(["mouseover"]),bn:new Set(["resize"]),de:new Set(["keydown","keyup","load","mouseout","mouseover"]),fr:new Set(["blur"]),id:new Set(["input","keyup","mouseout","mouseover"]),ja:new Set(["keypress","mousedown","mouseup","resize"]),qu:new Set(["change","focus","load","resize","submit"]),sw:new Set(["change","click","input","keydown","keyup","mouseout","mouseover","submit"]),tr:new Set(["keydown","keyup","load","mousedown","mouseout","mouseover","mouseup","resize","scroll"]),zh:new Set(["focus","keyup","mouseout","mouseover"])};function $r(o,e){return ua[e]?.has(o)?o:ca[e]?.[o]??o}var gt=class{render(e,t){if(e.kind==="compound")return this.renderCompound(e,t);if(e.kind==="behavior")return this.renderBehavior(e,t);if(e.kind==="def")return this.renderDef(e,t);let r=Nt(t,e.action);if(r.length===0)return this.renderExplicit(e);let n=this.findBestPattern(e,r);return n?this.renderWithPattern(e,n):this.renderExplicit(e)}renderCompound(e,t){if(e.statements.length>1&&e.statements.every(i=>i.kind==="event-handler")){let i=this.keyword(t,"end"),s=[];for(let a of e.statements)s.push(this.render(a,t),i);return s.join(`
3
- `)}let r=e.statements.map(i=>this.render(i,t)),n=this.getChainWord(e.chainType,t);return r.join(` ${n} `)}keyword(e,t){return V(e)?.keywords?.[t]?.primary??t}renderBlockHeader(e,t,r){return r.length>0?`${e} ${t}(${r.join(", ")})`:`${e} ${t}`}renderBehavior(e,t){let r=this.keyword(t,"end"),n=[this.renderBlockHeader(this.keyword(t,"behavior"),e.name,e.parameters)];for(let i of e.eventHandlers)n.push(` ${this.render(i,t)}`,` ${r}`);if(e.initBlock&&e.initBlock.length>0){n.push(` ${this.keyword(t,"init")}`);for(let i of e.initBlock)n.push(` ${this.render(i,t)}`);n.push(` ${r}`)}return n.push(r),n.join(`
1
+ "use strict";var LokaScriptSemanticAr=(()=>{var xt=Object.defineProperty;var Ur=Object.getOwnPropertyDescriptor;var Hr=Object.getOwnPropertyNames;var Gr=Object.prototype.hasOwnProperty;var Yr=(o,e)=>{for(var t in e)xt(o,t,{get:e[t],enumerable:!0})},Zr=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Hr(e))!Gr.call(o,n)&&n!==t&&xt(o,n,{get:()=>e[n],enumerable:!(r=Ur(e,n))||r.enumerable});return o};var Jr=o=>Zr(xt({},"__esModule",{value:!0}),o);var xa={};Yr(xa,{ASTBuilder:()=>ze,DEFAULT_CONFIDENCE_THRESHOLD:()=>Yt,HIGH_CONFIDENCE_THRESHOLD:()=>Zt,VERSION:()=>ha,arabicProfile:()=>ke,arabicTokenizer:()=>mt,buildAST:()=>Qt,canParse:()=>Ft,createCommandNode:()=>G,createEventHandler:()=>fe,createLiteral:()=>$,createPropertyPath:()=>se,createReference:()=>J,createSelector:()=>re,fromExplicit:()=>Ht,getCommandMapper:()=>Oe,getPatternsForLanguage:()=>Kr,getPatternsForLanguageAndCommand:()=>ka,getProfile:()=>Qe,getSupportedLanguages:()=>ga,getTokenizer:()=>Xe,isExplicitSyntax:()=>me,isLanguageSupported:()=>Pt,parse:()=>Me,parseAny:()=>Gt,parseExplicit:()=>Re,registerCommandMapper:()=>wt,render:()=>Ge,renderExplicit:()=>Ye,toExplicit:()=>Ut,tokenize:()=>va,tryGetProfile:()=>I});var Yt=.5,Zt=.8;var Xr=new Set(["me","my","myself","you","your","yourself","it","its","result","event","target","body","detail","window","document"]),Qr=new Set(["and","or","not","no"]),en=new Set(["true","false","null","undefined"]),tn=new Set(["is","matches","match","contains","in"]),rn=new Set(["next","previous","closest","first","last"]),nn=new Set(["ms","s","seconds","second","milliseconds","millisecond","minutes","minute","hours","hour"]);function Jt(o){let e=[],t=0,r=1,n=1;function i(){if(e.length===0)return!0;let p=e[e.length-1];return p.type==="IDENTIFIER"&&tn.has(p.value.toLowerCase())||p.type==="IDENTIFIER"&&rn.has(p.value.toLowerCase())?!0:["OPERATOR","COMPARISON","LOGICAL","LPAREN","LBRACKET","LBRACE","COMMA","COLON"].includes(p.type)}function s(p=0){return o[t+p]??""}function a(){let p=o[t];return t++,p===`
2
+ `?(r++,n=1):n++,p}function l(){for(;t<o.length&&/\s/.test(o[t]);)a()}function c(p){let h="";for(;t<o.length&&p(o[t]);)h+=a();return h}function d(p){let h=p;for(a();t<o.length&&o[t]!==p;)o[t]==="\\"&&t+1<o.length&&(h+=a()),h+=a();return t<o.length&&(h+=a()),h}function u(){let p="`";for(a();t<o.length&&o[t]!=="`";)o[t]==="\\"&&t+1<o.length&&(p+=a()),p+=a();return t<o.length&&(p+=a()),p}function f(){let p="<";for(a();t<o.length&&(p+=a(),!p.endsWith("/>")););return p}function m(p,h,y){return{type:p,value:h,start:y,end:t,line:r,column:n-h.length}}for(;t<o.length&&(l(),!(t>=o.length));){let p=t,h=s();if(h==="'"&&s(1)==="s"&&!/\w/.test(s(2))){a(),a(),e.push(m("POSSESSIVE","'s",p));continue}if(h==='"'||h==="'"){let y=d(h);e.push(m("STRING",y,p));continue}if(h==="`"){let y=u();e.push(m("TEMPLATE_LITERAL",y,p));continue}if(h==="<"&&/[a-zA-Z.#\[]/.test(s(1))){let y=f();e.push(m("QUERY_SELECTOR",y,p));continue}if(h==="#"&&i()){a();let y=c(g=>/[\w-]/.test(g));e.push(m("ID_SELECTOR","#"+y,p));continue}if(h==="."&&/[a-zA-Z_-]/.test(s(1))&&i()){a();let y=c(g=>/[\w-]/.test(g));e.push(m("CLASS_SELECTOR","."+y,p));continue}if(h==="@"&&/[a-zA-Z_]/.test(s(1))){a();let y=c(g=>/[\w-]/.test(g));e.push(m("ATTRIBUTE_REF","@"+y,p));continue}if(h==="["&&i()){let y=s(1);if(y==="@"||/[a-zA-Z]/.test(y)){let g="";for(g+=a();t<o.length&&o[t]!=="]";)o[t]==='"'||o[t]==="'"?g+=d(o[t]):g+=a();t<o.length&&(g+=a()),e.push(m("ATTRIBUTE_SELECTOR",g,p));continue}}if(h==="["){a(),e.push(m("LBRACKET","[",p));continue}if(h==="]"){a(),e.push(m("RBRACKET","]",p));continue}if(/\d/.test(h)){let y=c(E=>/[\d.]/.test(E)),g=t,S=c(E=>/[a-zA-Z]/.test(E));nn.has(S)?e.push(m("TIME_EXPRESSION",y+S,p)):(t=g,e.push(m("NUMBER",y,p)));continue}if(h==="("){a(),e.push(m("LPAREN","(",p));continue}if(h===")"){a(),e.push(m("RPAREN",")",p));continue}if(h==="{"){a(),e.push(m("LBRACE","{",p));continue}if(h==="}"){a(),e.push(m("RBRACE","}",p));continue}if(h===","){a(),e.push(m("COMMA",",",p));continue}if(h===":"){a(),e.push(m("COLON",":",p));continue}if(h==="."){a(),e.push(m("DOT",".",p));continue}if(h==="+"||h==="-"||h==="*"||h==="/"||h==="%"){a(),e.push(m("OPERATOR",h,p));continue}if(h==="="||h==="!"||h==="<"||h===">"){let y=a();s()==="="&&(y+=a()),e.push(m("COMPARISON",y,p));continue}if(/[a-zA-Z_$]/.test(h)){let y=c(S=>/[\w$]/.test(S)),g=y.toLowerCase();Xr.has(g)?e.push(m("CONTEXT_VAR",y,p)):Qr.has(g)?e.push(m("LOGICAL",y,p)):en.has(g)?e.push(m("BOOLEAN",y,p)):e.push(m("IDENTIFIER",y,p));continue}a()}return e.push(m("EOF","",t)),e}var on=new Set(["my","its","your"]),an=new Set(["is","matches","match","contains","in","exists","does"]),sn=new Set(["next","previous","closest","first","last"]),Je=class{constructor(){this.tokens=[];this.current=0}parse(e){try{return this.tokens=Jt(e),this.current=0,this.isAtEnd()?{success:!1,error:"Empty expression"}:{success:!0,node:this.parseExpression(),consumed:this.current}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Parse error"}}}peek(){return this.tokens[this.current]??{type:"EOF",value:"",start:0,end:0}}peekAt(e){return this.tokens[this.current+e]??{type:"EOF",value:"",start:0,end:0}}previous(){return this.tokens[this.current-1]??{type:"EOF",value:"",start:0,end:0}}isAtEnd(){return this.peek().type==="EOF"}advance(){return this.isAtEnd()||this.current++,this.previous()}check(e){return this.peek().type===e}checkValue(e){return this.peek().value.toLowerCase()===e.toLowerCase()}match(...e){for(let t of e)if(this.check(t))return this.advance(),!0;return!1}parseExpression(){return this.parseOr()}parseOr(){let e=this.parseAnd();for(;this.checkValue("or");){let t=this.advance().value,r=this.parseAnd();e=this.createBinaryExpression(t,e,r)}return e}parseAnd(){let e=this.parseEquality();for(;this.checkValue("and");){let t=this.advance().value,r=this.parseEquality();e=this.createBinaryExpression(t,e,r)}return e}parseEquality(){let e=this.parseComparison();for(;;){let t;if(this.match("COMPARISON"))t=this.previous().value;else if(this.checkValue("is")||this.checkValue("matches")||this.checkValue("match")||this.checkValue("contains")||this.checkValue("in")){let n=this.advance().value;t=n.toLowerCase()==="match"?"matches":n}else break;if(t.toLowerCase()==="is"){if(this.checkValue("empty")){this.advance(),e=this.createPostfixUnary("is empty",e);continue}if(this.checkValue("not")&&this.peekAt(1).value.toLowerCase()==="empty"){this.advance(),this.advance(),e=this.createPostfixUnary("is not empty",e);continue}}let r=this.parseComparison();e=this.createBinaryExpression(t,e,r)}return e}parseComparison(){let e=this.parseAddition();for(;this.check("COMPARISON");){let t=this.advance().value,r=this.parseAddition();e=this.createBinaryExpression(t,e,r)}return e}parseAddition(){let e=this.parseMultiplication();for(;this.peek().value==="+"||this.peek().value==="-";){let t=this.advance().value,r=this.parseMultiplication();e=this.createBinaryExpression(t,e,r)}return e}parseMultiplication(){let e=this.parseUnary();for(;this.peek().value==="*"||this.peek().value==="/"||this.peek().value==="%";){let t=this.advance().value,r=this.parseUnary();e=this.createBinaryExpression(t,e,r)}return e}parseUnary(){if(this.checkValue("not")||this.checkValue("no")||this.peek().value==="-"){let e=this.advance().value,t=this.parseUnary();return this.createUnaryExpression(e,t)}return this.parsePostfix()}parsePostfix(){let e=this.parsePrimary();for(;;)if(this.match("DOT"))if(this.check("IDENTIFIER")||this.check("CONTEXT_VAR")){let t=this.advance().value;e=this.createPropertyAccess(e,t)}else break;else if(this.match("POSSESSIVE"))if(this.check("IDENTIFIER")||this.check("CONTEXT_VAR")){let t=this.advance().value;e=this.createPossessiveExpression(e,t)}else break;else if(this.match("LPAREN")){let t=this.parseArguments();e=this.createCallExpression(e,t)}else if(this.match("LBRACKET")){let t=this.parseExpression();if(!this.match("RBRACKET"))throw new Error("Expected ] after index");e=this.createPropertyAccess(e,t)}else if(e.type==="contextReference"&&on.has(e.contextType??"")&&this.check("IDENTIFIER")&&!an.has(this.peek().value.toLowerCase())){let t=this.advance().value;e=this.createPropertyAccess(e,t)}else if(this.checkValue("exists")&&this.peekAt(1).type!=="LPAREN")this.advance(),e=this.createPostfixUnary("exists",e);else break;return e}parsePrimary(){let e=this.peek();if(this.match("NUMBER"))return this.createLiteral(parseFloat(e.value),"number",e);if(this.match("STRING")){let t=e.value.slice(1,-1);return this.createLiteral(t,"string",e)}if(this.match("BOOLEAN")){let t=e.value==="true"?!0:e.value==="false"?!1:e.value==="null"?null:void 0,r={true:"boolean",false:"boolean",null:"null",undefined:"undefined"};return this.createLiteral(t,r[e.value]??"string",e)}if(this.match("TEMPLATE_LITERAL"))return{type:"templateLiteral",value:e.value,start:e.start,end:e.end,line:e.line,column:e.column};if(this.match("TIME_EXPRESSION"))return this.parseTimeExpression(e);if(this.match("ID_SELECTOR"))return this.createSelector(e.value,"id",e);if(this.match("CLASS_SELECTOR"))return this.createSelector(e.value,"class",e);if(this.match("ATTRIBUTE_SELECTOR"))return this.createSelector(e.value,"attribute",e);if(this.match("ATTRIBUTE_REF"))return{type:"attributeAccess",attributeName:e.value.slice(1),start:e.start,end:e.end};if(this.match("QUERY_SELECTOR")){let t=e.value.slice(1,-2);return this.createSelector(t,"query",e)}if(this.match("CONTEXT_VAR"))return this.createContextReference(e.value,e);if(this.match("IDENTIFIER")){if(sn.has(e.value.toLowerCase())&&(this.check("CLASS_SELECTOR")||this.check("ID_SELECTOR")||this.check("QUERY_SELECTOR"))){let t=this.advance(),r=t.type==="QUERY_SELECTOR"?t.value.slice(1,-2):t.value,n=t.type==="CLASS_SELECTOR"?"class":t.type==="ID_SELECTOR"?"id":"query";return{type:"callExpression",callee:this.createIdentifier(e.value,e),arguments:[this.createSelector(r,n,t)],start:e.start,end:t.end}}return this.createIdentifier(e.value,e)}if(this.match("LPAREN")){let t=this.parseExpression();if(!this.match("RPAREN"))throw new Error("Expected ) after expression");return t}if(this.match("LBRACKET"))return this.parseArrayLiteral();if(this.match("LBRACE"))return this.parseObjectLiteral();throw new Error(`Unexpected token: ${e.value}`)}parseArguments(){let e=[];if(!this.check("RPAREN"))do e.push(this.parseExpression());while(this.match("COMMA"));if(!this.match("RPAREN"))throw new Error("Expected ) after arguments");return e}parseArrayLiteral(){let e=[],t=this.previous().start;if(!this.check("RBRACKET"))do e.push(this.parseExpression());while(this.match("COMMA"));if(!this.match("RBRACKET"))throw new Error("Expected ] after array elements");return{type:"arrayLiteral",elements:e,start:t,end:this.previous().end}}parseObjectLiteral(){let e=[],t=this.previous().start;if(!this.check("RBRACE"))do{let r;if(this.check("STRING"))r=this.advance().value.slice(1,-1);else if(this.check("IDENTIFIER"))r=this.advance().value;else throw new Error("Expected property name");if(!this.match("COLON"))throw new Error("Expected : after property name");let n=this.parseExpression();e.push({key:r,value:n})}while(this.match("COMMA"));if(!this.match("RBRACE"))throw new Error("Expected } after object properties");return{type:"objectLiteral",properties:e.map(r=>({type:"objectProperty",key:r.key,value:r.value})),start:t,end:this.previous().end}}parseTimeExpression(e){let t=e.value.match(/^(\d+(?:\.\d+)?)(ms|s|seconds?|milliseconds?|minutes?|hours?)$/i);if(!t)throw new Error(`Invalid time expression: ${e.value}`);let r=parseFloat(t[1]),n=t[2].toLowerCase();return{type:"timeExpression",value:r,unit:n,raw:e.value,start:e.start,end:e.end,line:e.line,column:e.column}}createLiteral(e,t,r){return{type:"literal",value:e,dataType:t,raw:r.value,start:r.start,end:r.end,line:r.line,column:r.column}}createSelector(e,t,r){return{type:"selector",value:e,selector:e,selectorType:t,start:r.start,end:r.end,line:r.line,column:r.column}}createContextReference(e,t){return{type:"contextReference",contextType:e,name:t.value,start:t.start,end:t.end,line:t.line,column:t.column}}createIdentifier(e,t){return{type:"identifier",name:e,start:t.start,end:t.end,line:t.line,column:t.column}}createPropertyAccess(e,t){return{type:"propertyAccess",object:e,property:typeof t=="string"?t:t.type==="identifier"?t.name:"",start:e.start,end:this.previous().end}}createPossessiveExpression(e,t){return{type:"possessiveExpression",object:e,property:t,start:e.start,end:this.previous().end}}createBinaryExpression(e,t,r){return{type:"binaryExpression",operator:e,left:t,right:r,start:t.start,end:r.end}}createUnaryExpression(e,t){return{type:"unaryExpression",operator:e,operand:t,prefix:!0,start:this.previous().start,end:t.end}}createPostfixUnary(e,t){return{type:"unaryExpression",operator:e,operand:t,prefix:!1,start:t.start,end:this.previous().end}}createCallExpression(e,t){return{type:"callExpression",callee:e,arguments:t,start:e.start,end:this.previous().end}}};function St(o){return new Je().parse(o)}function Z(o,e){switch(o.type){case"literal":return ln(o);case"selector":return cn(o,e);case"reference":return un(o);case"property-path":return dn(o,e);case"expression":return pn(o);case"flag":return{type:"literal",value:o.enabled};default:let t=o;throw new Error(`Unknown semantic value type: ${t.type}`)}}function ln(o){let e={type:"literal",value:o.value};return o.dataType?{...e,dataType:o.dataType}:e}function cn(o,e){return o.value.startsWith("@")&&/^[a-zA-Z_]/.test(o.value.slice(1))?{type:"attributeAccess",attributeName:o.value.slice(1)}:(e&&o.value.startsWith("*")&&/^[a-zA-Z-]/.test(o.value.slice(1))&&e.push(`Converted '${o.value}' to a CSS selector, but it looks like a CSS property name. CSS properties in commands like 'transition' should be literal strings, not selectors. Consider using expectedTypes: ['literal'] instead of ['literal', 'selector'] in the command schema.`),o.value.startsWith("<")?{type:"selector",value:o.value,selector:o.value,selectorType:o.selectorKind,raw:o.value}:{type:"selector",value:o.value,selector:o.value,selectorType:o.selectorKind})}function un(o){return{type:"contextReference",contextType:o.value,name:o.value}}function dn(o,e){return{type:"propertyAccess",object:Z(o.object,e),property:o.property}}function pn(o){let e=St(o.raw);return!e.success||!e.node?{type:"identifier",name:o.raw}:e.node}function bt(o,e){return o.roles.get(e)}function w(o,e,t){let r=bt(o,e);return r?Z(r,t):void 0}function R(o,e=[],t,r={}){let n={type:"command",name:o,args:e};return t&&Object.keys(t).length>0&&(n.modifiers=t),r.isBlocking&&(n.isBlocking=r.isBlocking),r.implicitTarget&&(n.implicitTarget=r.implicitTarget),r.semanticRoles&&Object.keys(r.semanticRoles).length>0&&(n.semanticRoles=r.semanticRoles),n}var mn={action:"toggle",toAST(o,e){let t=w(o,"patient"),r=w(o,"destination"),n=w(o,"duration"),i=t?[t]:[],s={};return r&&(s.on=r),n&&(s.for=n),R("toggle",i,s)}},fn={action:"add",toAST(o,e){let t=w(o,"patient"),r=w(o,"destination"),n=t?[t]:[],i={};return r&&(i.to=r),R("add",n,i)}},hn={action:"remove",toAST(o,e){let t=w(o,"patient"),r=w(o,"source"),n=t?[t]:[],i={};return r&&(i.from=r),R("remove",n,i)}},yn={action:"set",toAST(o,e){let t=w(o,"destination"),r=w(o,"patient"),n=w(o,"scope"),i=[],s={};return t&&i.push(t),r&&(s.to=r),n&&(s.on=n),R("set",i,s)}},gn={action:"show",toAST(o,e){let t=w(o,"destination"),r=w(o,"patient"),n=w(o,"duration"),i=[],s={},a=t??r;return a&&i.push(a),n&&(s.with=n),R("show",i,s)}},vn={action:"hide",toAST(o,e){let t=w(o,"destination"),r=w(o,"patient"),n=w(o,"duration"),i=[],s={},a=t??r;return a&&i.push(a),n&&(s.with=n),R("hide",i,s)}},kn={action:"increment",toAST(o,e){let t=w(o,"destination"),r=w(o,"patient"),n=w(o,"quantity"),i=[],s={},a=t??r;return a&&i.push(a),n&&(s.by=n),R("increment",i,s)}},xn={action:"decrement",toAST(o,e){let t=w(o,"destination"),r=w(o,"patient"),n=w(o,"quantity"),i=[],s={},a=t??r;return a&&i.push(a),n&&(s.by=n),R("decrement",i,s)}},Sn={action:"wait",toAST(o,e){let t=w(o,"event");if(t){let i={for:t},s=w(o,"source");return s&&(i.from=s),R("wait",[],i,{isBlocking:!0})}let r=w(o,"duration");return R("wait",r?[r]:[],void 0,{isBlocking:!0})}},bn={action:"log",toAST(o,e){let t=w(o,"patient"),r=[];return t&&r.push(t),R("log",r)}},wn={action:"put",toAST(o,e){let t=w(o,"patient"),r=w(o,"destination"),n=bt(o,"manner")??bt(o,"method"),i=t?[t]:[],s={};if(r){let a=n?.type==="literal"?String(n.value):"into";s[a]=r}return R("put",i,s)}},En={action:"fetch",toAST(o,e){let t=w(o,"source"),r=w(o,"method"),n=w(o,"responseType"),i=w(o,"patient"),s=t?[t]:[],a={};return r&&(a.with=r),n&&(a.as=n),i&&(a.body=i),R("fetch",s,a,{isBlocking:!0})}},Tn={action:"append",toAST(o,e){let t=w(o,"patient"),r=w(o,"destination"),n=t?[t]:[],i={};return r&&(i.to=r),R("append",n,i)}},Cn={action:"prepend",toAST(o,e){let t=w(o,"patient"),r=w(o,"destination"),n=t?[t]:[],i={};return r&&(i.to=r),R("prepend",n,i)}},Pn={action:"trigger",toAST(o,e){let t=w(o,"event"),r=w(o,"destination"),n=t?[t]:[],i={};return r&&(i.on=r),R("trigger",n,i)}},Nn={action:"send",toAST(o,e){let t=w(o,"event"),r=w(o,"destination"),n=w(o,"patient"),i=t?[t]:[],s={};return r&&(s.to=r),n&&(s.detail=n),R("send",i,s)}},Rn={action:"go",toAST(o,e){let t=w(o,"source"),r=w(o,"destination"),n=[],i={};return t&&n.push(t),r&&(i.to=r),R("go",n,i)}},Ln={action:"transition",toAST(o,e){let t=w(o,"patient"),r=w(o,"goal"),n=w(o,"duration"),i=w(o,"destination"),s=t?[t]:[],a={};return r&&(a.to=r),n&&(a.over=n),i&&(a.on=i),R("transition",s,a)}},An={action:"focus",toAST(o,e){let t=w(o,"destination"),r=w(o,"patient"),n=[],i={},s=t??r;return s&&n.push(s),R("focus",n,i)}},Mn={action:"blur",toAST(o,e){let t=w(o,"destination"),r=w(o,"patient"),n=[],i=t??r;return i&&n.push(i),R("blur",n)}},On={action:"get",toAST(o,e){let t=w(o,"source"),r=w(o,"patient"),n=[],i=t??r;return i&&n.push(i),R("get",n)}},zn={action:"take",toAST(o,e){let t=w(o,"patient"),r=w(o,"source"),n=t?[t]:[],i={};return r&&(i.from=r),R("take",n,i)}},In={action:"call",toAST(o,e){let t=w(o,"patient");return R("call",t?[t]:[])}},Vn={action:"return",toAST(o,e){let t=w(o,"patient");return R("return",t?[t]:[])}},_n={action:"halt",toAST(o,e){let t=o.roles.get("patient");return t?R("halt",[Z(t)]):R("halt",[])}},Bn={action:"throw",toAST(o,e){let t=w(o,"patient");return R("throw",t?[t]:[])}},Dn={action:"settle",toAST(o,e){let t=w(o,"destination"),r=w(o,"patient"),n=[],i=t??r;return i&&n.push(i),R("settle",n,void 0,{isBlocking:!0})}},$n={action:"swap",toAST(o,e){let t=w(o,"patient"),r=w(o,"source"),n=w(o,"destination"),i=w(o,"style"),s=[],a={};return t&&s.push(t),r&&s.push(r),n&&(a.on=n),i&&(a.with=i),R("swap",s,a)}},Wn={action:"morph",toAST(o,e){let t=w(o,"source"),r=w(o,"destination"),n=w(o,"patient"),i=[],s={},a=t??r;return a&&i.push(a),n&&(s.on=n),R("morph",i,s)}},jn={action:"clone",toAST(o,e){let t=w(o,"source"),r=w(o,"destination"),n=w(o,"patient"),i=[],s={},a=t??n;return a&&i.push(a),r&&(s.into=r),R("clone",i,s)}},qn={action:"make",toAST(o,e){let t=w(o,"patient");return R("make",t?[t]:[])}},Kn={action:"measure",toAST(o,e){let t=w(o,"patient"),r=w(o,"destination"),n=w(o,"source"),i=[],s={};t&&i.push(t);let a=r??n;return a&&(s.of=a),R("measure",i,s)}},Fn={action:"tell",toAST(o,e){let t=w(o,"destination"),r=w(o,"patient"),n=[],i=t??r;return i&&n.push(i),R("tell",n)}},Un={action:"js",toAST(o,e){let t=w(o,"patient");return R("js",t?[t]:[])}},Hn={action:"async",toAST(o,e){return R("async",[])}},Gn={action:"if",toAST(o,e){let t=w(o,"condition");return R("if",t?[t]:[])}},Yn={action:"unless",toAST(o,e){let t=w(o,"condition");return R("unless",t?[t]:[])}},Zn={action:"repeat",toAST(o,e){let t=w(o,"quantity"),r=w(o,"patient"),n=[],i=t??r;return i&&n.push(i),R("repeat",n)}},Jn={action:"for",toAST(o,e){let t=w(o,"patient"),r=w(o,"source"),n=t?[t]:[],i={};return r&&(i.in=r),R("for",n,i)}},Xn={action:"while",toAST(o,e){let t=w(o,"condition");return R("while",t?[t]:[])}},Qn={action:"continue",toAST(o,e){return R("continue",[])}},eo={action:"default",toAST(o,e){let t=w(o,"patient"),r=w(o,"source"),n=t?[t]:[],i={};return r&&(i.to=r),R("default",n,i)}},to={action:"init",toAST(o,e){return R("init",[])}},ro={action:"behavior",toAST(o,e){let t=w(o,"patient");return R("behavior",t?[t]:[])}},no={action:"install",toAST(o,e){let t=w(o,"patient"),r=w(o,"destination"),n=t?[t]:[],i={};return r&&(i.on=r),R("install",n,i)}},oo={action:"on",toAST(o,e){let t=w(o,"event"),r=w(o,"source"),n=t?[t]:[],i={};return r&&(i.from=r),R("on",n,i)}},Xt=new Map([["toggle",mn],["add",fn],["remove",hn],["set",yn],["show",gn],["hide",vn],["increment",kn],["decrement",xn],["wait",Sn],["log",bn],["put",wn],["fetch",En],["append",Tn],["prepend",Cn],["get",On],["take",zn],["trigger",Pn],["send",Nn],["on",oo],["go",Rn],["transition",Ln],["focus",An],["blur",Mn],["call",In],["return",Vn],["halt",_n],["throw",Bn],["settle",Dn],["swap",$n],["morph",Wn],["clone",jn],["measure",Kn],["make",qn],["tell",Fn],["default",eo],["js",Un],["async",Hn],["if",Gn],["unless",Yn],["repeat",Zn],["for",Jn],["while",Xn],["continue",Qn],["init",to],["behavior",ro],["install",no]]);function Oe(o){return Xt.get(o)}function wt(o){Xt.set(o.action,o)}var ze=class{constructor(e={}){this.warnings=[]}build(e){switch(e.kind){case"command":return this.buildCommand(e);case"event-handler":return this.buildEventHandler(e);case"conditional":return this.buildConditional(e);case"compound":return this.buildCompound(e);case"loop":return this.buildLoop(e);case"behavior":return this.buildBehavior(e);case"def":return this.buildDef(e);default:throw new Error(`Unknown semantic node kind: ${e.kind}`)}}buildBehavior(e){let t=e.eventHandlers.map(n=>this.buildEventHandler(n)),r={type:"behavior",name:e.name,parameters:[...e.parameters],eventHandlers:t};return e.initBlock&&e.initBlock.length>0&&(r.initBlock={type:"initBlock",commands:e.initBlock.map(n=>this.build(n))}),r}buildDef(e){return{type:"def",name:e.name,params:[...e.parameters],body:e.body.map(t=>this.build(t))}}buildCommand(e){let t=Oe(e.action),r;if(t){let n=t.toAST(e,this);if("ast"in n&&"warnings"in n){let i=n;this.warnings.push(...i.warnings),r=i.ast}else r=n}else r=this.buildGenericCommand(e);if(e.roles&&e.roles.size>0){let n={};for(let[i,s]of e.roles)n[i]=Z(s);Object.keys(n).length>0&&(r.semanticRoles=n)}return r}buildGenericCommand(e){let t=[],r={},n=["patient","source","quantity"],i=["destination","duration","method","style"];for(let a of n){let l=e.roles.get(a);l&&t.push(Z(l))}for(let a of i){let l=e.roles.get(a);if(l){let c=this.roleToModifierKey(a);r[c]=Z(l)}}let s={type:"command",name:e.action,args:t};return Object.keys(r).length>0?{...s,modifiers:r}:s}roleToModifierKey(e){return{destination:"on",duration:"for",source:"from",condition:"if",method:"via",style:"with"}[e]??e}buildEventHandler(e){let t=e.roles.get("event"),r="click",n,i=t?.type==="literal"?String(t.value):t?.type==="expression"?t.raw:t?.type==="reference"?t.value:void 0;i!==void 0&&(i.includes("|")||i.includes(" or ")?(n=i.split(/\s+or\s+|\|/).map(g=>g.trim()),r=n[0]):r=i);let s=e.body.map(g=>this.build(g)),a=e.roles.get("source"),l,c;a?.type==="selector"?(l=a.value,c=a.value):a?.type==="reference"?c=a.value:a?.type==="literal"&&(c=String(a.value));let d=e.roles.get("condition"),u=d?Z(d):void 0,f=e.roles.get("destination"),m=f?Z(f):void 0,p=e.eventModifiers,h=l;if(p?.from){let g=p.from;g.type==="selector"&&!l&&(h=g.value)}let y=e.parameterNames?[...e.parameterNames]:void 0;return{type:"eventHandler",event:r,commands:s,...n&&n.length>1?{events:n}:{},...h?{selector:h}:{},...c?{target:c}:{},...u?{condition:u}:{},...m?{watchTarget:m}:{},...y&&y.length>0?{args:y,params:y}:{}}}buildConditional(e){let t=e.roles.get("condition");if(!t)throw new Error("Conditional node missing condition");let r=Z(t),n=e.thenBranch.map(a=>this.build(a)),i=e.elseBranch?.map(a=>this.build(a)),s=[r,{type:"block",commands:n}];return i&&i.length>0&&s.push({type:"block",commands:i}),{type:"command",name:"if",args:s}}buildCompound(e){let t=e.statements.map(n=>this.build(n));return t.length===1?t[0]:t.length===0?{type:"block",commands:[]}:t.every(n=>n.type==="eventHandler")?{type:"Program",statements:t}:{type:"CommandSequence",commands:t}}buildLoop(e){let t=e.body.map(n=>this.build(n)),r=[{type:"identifier",name:e.loopVariant}];switch(e.loopVariant){case"times":{let n=e.roles.get("quantity");n&&r.push(Z(n));break}case"for":{e.loopVariable&&r.push({type:"string",value:e.loopVariable});let n=e.roles.get("source");n&&r.push(Z(n));break}case"while":case"until":{let n=e.roles.get("condition");n&&r.push(Z(n));break}case"forever":break}return r.push({type:"block",commands:t}),{type:"command",name:"repeat",args:r}}buildBlock(e){return{type:"block",commands:e.map(r=>this.build(r))}}};function Qt(o){let e=new ze;return{ast:e.build(o),warnings:e.warnings}}var ge=new Map,ve=new Map,Ie=new Map;var er=null;function rr(o,e){let t={...o};for(let r of Object.keys(e)){let n=e[r],i=o[r];n!==void 0&&(typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof i=="object"&&i!==null&&!Array.isArray(i)?t[r]=rr(i,n):t[r]=n)}return t}function nr(o,e){return rr(o,e)}function Et(o){if(!o.extends)return o;let e=ve.get(o.extends);if(!e)return console.warn(`[Registry] Profile '${o.code}' extends '${o.extends}' but base is not registered. Make sure to import the base language before the variant.`),o;let t=Et(e);return nr(t,o)}function Tt(o,e,t){ge.set(o,e),ve.set(o,t),Ie.delete(o)}var tr=new Map;function we(o){return o.split("-")[0]}function Ee(o){return o.includes("-")}function Xe(o){let e=ge.get(o);if(!e&&Ee(o)){let t=we(o);e=ge.get(t)}if(!e){let t=Array.from(ge.keys()).join(", ");throw new Error(`Language '${o}' is not registered. Registered languages: ${t||"none"}. Import the language module first: import '@lokascript/semantic/languages/${o}';`)}return e}function Qe(o){let e=ve.get(o);if(!e&&Ee(o)){let t=we(o);e=ve.get(t)}if(!e){let t=Array.from(ve.keys()).join(", ");throw new Error(`Language profile '${o}' is not registered. Registered languages: ${t||"none"}. Import the language module first: import '@lokascript/semantic/languages/${o}';`)}return Et(e)}function I(o){let e=ve.get(o);return!e&&Ee(o)&&(e=ve.get(we(o))),e?Et(e):void 0}function Ct(){return Array.from(ge.keys())}function Pt(o){return ge.has(o)?!0:Ee(o)?ge.has(we(o)):!1}function or(o,e){return Xe(e).tokenize(o)}function Q(o){let e=Ie.get(o);if(!e&&Ee(o)&&(e=Ie.get(we(o))),e)return e;let t=tr.get(o);if(!t&&Ee(o)&&(t=tr.get(we(o))),t)return Ie.set(o,t),t;if(!er)throw new Error(`No patterns registered for language '${o}'. Either import the language module or set a pattern generator.`);let r=Qe(o),n=er(r);return Ie.set(o,n),n}function Nt(o,e){return Q(o).filter(t=>t.command===e).sort((t,r)=>r.priority-t.priority)}var ke={code:"ar",name:"Arabic",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629",regions:["priority"],direction:"rtl",script:"arabic",wordOrder:"VSO",markingStrategy:"preposition",usesSpaces:!0,verb:{position:"start",subjectDrop:!0},references:{me:"\u0623\u0646\u0627",it:"\u0647\u0648",you:"\u0623\u0646\u062A",result:"\u0627\u0644\u0646\u062A\u064A\u062C\u0629",event:"\u0627\u0644\u062D\u062F\u062B",target:"\u0627\u0644\u0647\u062F\u0641",body:"\u062C\u0633\u0645"},possessive:{marker:"",markerPosition:"after-object",usePossessiveAdjectives:!0,specialForms:{me:"\u0644\u064A",it:"\u0644\u0647",you:"\u0644\u0643"},keywords:{\u0644\u064A:"me",\u0644\u0643:"you",\u0644\u0647:"it",\u0644\u0647\u0627:"it"}},roleMarkers:{destination:{primary:"\u0639\u0644\u0649",alternatives:["\u0641\u064A","\u0625\u0644\u0649","\u0628","\u0642\u0628\u0644","\u0628\u0639\u062F"],position:"before"},source:{primary:"\u0645\u0646",position:"before"},patient:{primary:"",position:"before"},style:{primary:"\u0628\u0640",alternatives:["\u0628\u0627\u0633\u062A\u062E\u062F\u0627\u0645"],position:"before"}},keywords:{toggle:{primary:"\u0628\u062F\u0651\u0644",alternatives:["\u0628\u062F\u0644","\u063A\u064A\u0651\u0631","\u063A\u064A\u0631"],normalized:"toggle"},add:{primary:"\u0623\u0636\u0641",alternatives:["\u0627\u0636\u0641"],normalized:"add"},remove:{primary:"\u0627\u062D\u0630\u0641",alternatives:["\u0623\u0632\u0644","\u0627\u0645\u0633\u062D"],normalized:"remove"},put:{primary:"\u0636\u0639",alternatives:["\u0627\u062C\u0639\u0644"],normalized:"put"},append:{primary:"\u0623\u0644\u062D\u0642",normalized:"append"},prepend:{primary:"\u0633\u0628\u0642",normalized:"prepend"},take:{primary:"\u062E\u0630",normalized:"take"},make:{primary:"\u0627\u0635\u0646\u0639",alternatives:["\u0623\u0646\u0634\u0626"],normalized:"make"},clone:{primary:"\u0627\u0633\u062A\u0646\u0633\u062E",normalized:"clone"},swap:{primary:"\u0627\u0633\u062A\u0628\u062F\u0644",alternatives:["\u062A\u0628\u0627\u062F\u0644"],normalized:"swap"},morph:{primary:"\u062D\u0648\u0651\u0644",normalized:"morph"},set:{primary:"\u0627\u0636\u0628\u0637",alternatives:["\u0639\u064A\u0651\u0646","\u062D\u062F\u062F"],normalized:"set"},get:{primary:"\u0627\u062D\u0635\u0644",normalized:"get"},increment:{primary:"\u0632\u0650\u062F",alternatives:["\u0632\u062F","\u0627\u0631\u0641\u0639"],normalized:"increment"},decrement:{primary:"\u0623\u0646\u0642\u0635",alternatives:["\u0627\u0646\u0642\u0635","\u0642\u0644\u0644"],normalized:"decrement"},log:{primary:"\u0633\u062C\u0644",normalized:"log"},show:{primary:"\u0627\u0638\u0647\u0631",alternatives:["\u0623\u0638\u0647\u0631","\u0627\u0639\u0631\u0636"],normalized:"show"},hide:{primary:"\u0627\u062E\u0641",alternatives:["\u0623\u062E\u0641\u0650","\u0627\u062E\u0641\u064A","\u0623\u062E\u0641"],normalized:"hide"},transition:{primary:"\u0627\u0646\u062A\u0642\u0627\u0644",alternatives:["\u0627\u0646\u062A\u0642\u0644"],normalized:"transition"},on:{primary:"\u0639\u0644\u0649",alternatives:["\u0639\u0646\u062F","\u0644\u062F\u0649","\u062D\u064A\u0646"],normalized:"on"},trigger:{primary:"\u062A\u0634\u063A\u064A\u0644",alternatives:["\u0623\u0637\u0644\u0642","\u0641\u0639\u0651\u0644"],normalized:"trigger"},send:{primary:"\u0623\u0631\u0633\u0644",normalized:"send"},focus:{primary:"\u062A\u0631\u0643\u064A\u0632",alternatives:["\u0631\u0643\u0632"],normalized:"focus"},blur:{primary:"\u0636\u0628\u0627\u0628\u064A\u0629",alternatives:["\u0634\u0648\u0634"],normalized:"blur"},empty:{primary:"\u0625\u0641\u0631\u0627\u063A",alternatives:["\u0641\u0627\u0631\u063A"],normalized:"empty"},open:{primary:"\u0627\u0641\u062A\u062D",normalized:"open"},close:{primary:"\u0623\u063A\u0644\u0642",normalized:"close"},select:{primary:"\u0638\u0644\u0644",normalized:"select"},clear:{primary:"\u0646\u0638\u0651\u0641",normalized:"clear"},reset:{primary:"\u0625\u0639\u0627\u062F\u0629-\u0636\u0628\u0637",alternatives:["\u0623\u0639\u062F-\u062A\u0639\u064A\u064A\u0646"],normalized:"reset"},breakpoint:{primary:"\u0646\u0642\u0637\u0629-\u062A\u0648\u0642\u0641",normalized:"breakpoint"},go:{primary:"\u0627\u0630\u0647\u0628",normalized:"go"},scroll:{primary:"\u0645\u0631\u0631",alternatives:["\u062A\u0645\u0631\u064A\u0631"],normalized:"scroll"},push:{primary:"\u0627\u062F\u0641\u0639",alternatives:["\u062F\u0641\u0639"],normalized:"push"},replace:{primary:"\u0627\u0633\u062A\u0628\u062F\u0644_\u0639\u0646\u0648\u0627\u0646",alternatives:["\u0623\u0639\u062F_\u062A\u0639\u064A\u064A\u0646_\u0639\u0646\u0648\u0627\u0646"],normalized:"replace"},process:{primary:"\u0639\u0627\u0644\u062C",alternatives:["\u0645\u0639\u0627\u0644\u062C\u0629"],normalized:"process"},wait:{primary:"\u0627\u0646\u062A\u0638\u0631",normalized:"wait"},fetch:{primary:"\u0627\u062D\u0636\u0631",alternatives:["\u062C\u0644\u0628"],normalized:"fetch"},settle:{primary:"\u0627\u0633\u062A\u0642\u0631",normalized:"settle"},if:{primary:"\u0625\u0630\u0627",normalized:"if"},unless:{primary:"\u0625\u0644\u0627",normalized:"unless"},when:{primary:"\u0639\u0646\u062F\u0645\u0627",normalized:"when"},where:{primary:"\u0623\u064A\u0646",normalized:"where"},else:{primary:"\u0648\u0625\u0644\u0627",alternatives:["\u062E\u0644\u0627\u0641 \u0630\u0644\u0643"],normalized:"else"},repeat:{primary:"\u0643\u0631\u0631",normalized:"repeat"},for:{primary:"\u0644\u0643\u0644",normalized:"for"},while:{primary:"\u0628\u064A\u0646\u0645\u0627",normalized:"while"},forever:{primary:"forever",normalized:"forever"},continue:{primary:"\u0648\u0627\u0635\u0644",normalized:"continue"},halt:{primary:"\u0623\u0648\u0642\u0641",normalized:"halt"},throw:{primary:"\u0627\u0631\u0645",alternatives:["\u0627\u0631\u0645\u0650"],normalized:"throw"},call:{primary:"\u0627\u0633\u062A\u062F\u0639",alternatives:["\u0646\u0627\u062F\u0650"],normalized:"call"},return:{primary:"\u0627\u0631\u062C\u0639",alternatives:["\u0639\u064F\u062F"],normalized:"return"},then:{primary:"\u062B\u0645",alternatives:["\u0628\u0639\u062F\u0647\u0627","\u062B\u0645\u0651"],normalized:"then"},and:{primary:"\u0648\u0623\u064A\u0636\u0627\u064B",alternatives:["\u0623\u064A\u0636\u0627\u064B"],normalized:"and"},end:{primary:"\u0646\u0647\u0627\u064A\u0629",alternatives:["\u0627\u0646\u062A\u0647\u0649","\u0627\u0644\u0646\u0647\u0627\u064A\u0629"],normalized:"end"},js:{primary:"\u062C\u0627\u0641\u0627\u0633\u0643\u0631\u0628\u062A",alternatives:["js"],normalized:"js"},async:{primary:"\u0645\u062A\u0632\u0627\u0645\u0646",normalized:"async"},tell:{primary:"\u0623\u062E\u0628\u0631",normalized:"tell"},default:{primary:"\u0627\u0641\u062A\u0631\u0627\u0636\u064A",normalized:"default"},init:{primary:"\u062A\u0647\u064A\u0626\u0629",alternatives:["\u0628\u062F\u0621"],normalized:"init"},behavior:{primary:"\u0633\u0644\u0648\u0643",normalized:"behavior"},install:{primary:"\u062A\u062B\u0628\u064A\u062A",alternatives:["\u062B\u0628\u0651\u062A"],normalized:"install"},measure:{primary:"\u0642\u064A\u0627\u0633",alternatives:["\u0642\u0650\u0633","\u0642\u0633"],normalized:"measure"},beep:{primary:"\u0635\u0641\u0651\u0631",normalized:"beep"},break:{primary:"\u062A\u0648\u0642\u0641",normalized:"break"},copy:{primary:"\u0627\u0646\u0633\u062E",normalized:"copy"},exit:{primary:"\u0627\u062E\u0631\u062C",normalized:"exit"},pick:{primary:"\u0627\u062E\u062A\u0631",normalized:"pick"},render:{primary:"\u0627\u0631\u0633\u0645",normalized:"render"},into:{primary:"\u0641\u064A",alternatives:["\u0625\u0644\u0649"],normalized:"into"},before:{primary:"\u0642\u0628\u0644",normalized:"before"},after:{primary:"\u0628\u0639\u062F",normalized:"after"},until:{primary:"\u062D\u062A\u0649",normalized:"until"},event:{primary:"\u062D\u062F\u062B",normalized:"event"},from:{primary:"\u0645\u0646",normalized:"from"},connect:{primary:"\u0627\u062A\u0635\u0644",alternatives:["\u0627\u062A\u0635\u0627\u0644"],normalized:"connect"},stream:{primary:"\u062A\u062F\u0641\u0642",alternatives:["\u0628\u062B"],normalized:"stream"},live:{primary:"\u0645\u0628\u0627\u0634\u0631",alternatives:["\u062D\u064A"],normalized:"live"},socket:{primary:"\u0645\u0642\u0628\u0633",alternatives:["websocket"],normalized:"socket"},bind:{primary:"\u0627\u0631\u0628\u0637",alternatives:["\u0631\u0628\u0637","bind"],normalized:"bind"},intercept:{primary:"\u0627\u0639\u062A\u0631\u0636",alternatives:["\u0627\u0639\u062A\u0631\u0627\u0636","intercept"],normalized:"intercept"},worker:{primary:"\u0639\u0627\u0645\u0644",alternatives:["worker"],normalized:"worker"},eventsource:{primary:"eventsource",alternatives:["\u0645\u0635\u062F\u0631-\u0627\u0644\u0623\u062D\u062F\u0627\u062B"],normalized:"eventsource"}},tokenization:{prefixes:["\u0627\u0644","\u0648","\u0641","\u0628","\u0643","\u0644"]},eventHandler:{eventMarker:{primary:"\u0639\u0646\u062F",alternatives:["\u0641\u064A","\u0644\u062F\u0649","\u0639\u0646\u062F\u0645\u0627","\u062D\u064A\u0646","\u062D\u064A\u0646\u0645\u0627","\u0644\u0645\u0651\u0627","\u0644\u0645\u0627"],position:"before"},temporalMarkers:["\u0639\u0646\u062F\u0645\u0627","\u062D\u064A\u0646","\u0644\u0645\u0651\u0627"],negationMarker:{primary:"\u0639\u062F\u0645",alternatives:["\u0639\u062F\u0645"],position:"before"}}};function F(o,e){return e?{type:"literal",value:o,dataType:e}:{type:"literal",value:o}}function Ve(o,e){return e?{type:"selector",value:o,selectorKind:e}:{type:"selector",value:o}}function Te(o){return{type:"reference",value:o}}function tt(o,e){return{type:"property-path",object:o,property:e}}function Rt(o,e=!0){return{type:"flag",name:o,enabled:e}}function ar(o,e,t){let r=e instanceof Map?e:new Map(Object.entries(e)),n={kind:"command",action:o,roles:r};return t?{...n,metadata:t}:n}function Lt(o,e,t,r,n){let i=e instanceof Map?e:new Map(Object.entries(e));return{kind:"event-handler",action:o,roles:i,body:t,...n&&{eventModifiers:n},...r&&{metadata:r}}}function sr(o,e,t,r,n){let i=e instanceof Map?e:new Map(Object.entries(e));return{kind:"conditional",action:o,roles:i,thenBranch:t,...r&&{elseBranch:r},...n&&{metadata:n}}}function lr(o,e,t,r,n,i,s){let a=e instanceof Map?e:new Map(Object.entries(e));return{kind:"loop",action:o,roles:a,loopVariant:t,body:r,...n&&{loopVariable:n},...i&&{indexVariable:i},...s&&{metadata:s}}}var At=new Set(["me","you","it","result","event","target","body"]);function rt(o,e=At){return e.has(o)}var ir=new Set(["body","then","else","condition","loop-body","variable","catch","finally"]);function io(o){let e=o.slice(1,-1),t=0;for(let r of e)if(r==="[")t++;else if(r==="]")t--;else if(t===0&&(r===" "||r===":"))return!0;return!1}function nt(o,e={}){let t=o.trim(),r=e.collectDiagnostics===!0,n=[];if(!t.startsWith("[")||!t.endsWith("]"))throw new Error("Explicit syntax must be wrapped in brackets: [command role:value ...]");let i=t.slice(1,-1).trim();if(!i)throw new Error("Empty explicit statement");let s=so(i);if(s.length===0)throw new Error("No command specified in explicit statement");let a=s[0].toLowerCase(),l=new Map,c=e.referenceSet??At,d=e.schemaLookup?.getSchema(a),u=d?new Set(d.roles.map(m=>m.role)):null;for(let m=1;m<s.length;m++){let p=s[m];if(p.startsWith("+")||p.startsWith("~")){let C=p.startsWith("+"),x=p.slice(1);if(!x){if(r){n.push({severity:"error",code:"EMPTY_FLAG",message:`Empty flag name: "${p}"`,source:"schema"});continue}throw new Error(`Empty flag name: "${p}"`)}if(u&&!u.has(x)){if(r){n.push({severity:"error",code:"UNKNOWN_FLAG",message:`Unknown flag "${x}" for command "${a}"`,source:"schema",suggestions:[...u].map(k=>`+${k}`)}),l.set(x,Rt(x,C));continue}throw new Error(`Unknown flag "${x}" for command "${a}". Valid roles: ${[...u].join(", ")}`)}l.set(x,Rt(x,C));continue}let h=p.indexOf(":");if(h===-1){if(r){n.push({severity:"error",code:"INVALID_ROLE_FORMAT",message:`Invalid role format: "${p}". Expected role:value or +flag`,source:"schema"});continue}throw new Error(`Invalid role format: "${p}". Expected role:value or +flag`)}let y=p.slice(0,h);if(u&&!ir.has(y)&&!u.has(y))if(r)n.push({severity:"error",code:"UNKNOWN_ROLE",message:`Unknown role "${y}" for command "${a}"`,source:"schema",suggestions:[...u]});else throw new Error(`Unknown role "${y}" for command "${a}". Valid roles: ${[...u].join(", ")}`);let g=y,S=p.slice(h+1);if(ir.has(y)&&S.startsWith("[")&&io(S)){let C=co(p,h+1),x=p.slice(h+1,C+1);l.set(g,{type:"expression",raw:x});continue}let E=lo(S,c);l.set(g,E)}if(d&&a!=="on"){for(let m of d.roles)if(m.required&&!l.has(m.role)&&!m.default)if(r)n.push({severity:"error",code:"MISSING_REQUIRED_ROLE",message:`Missing required role "${m.role}" for command "${a}": ${m.description}`,source:"schema"});else throw new Error(`Missing required role "${m.role}" for command "${a}": ${m.description}`)}let f=m=>n.length===0?m:{...m,diagnostics:n};switch(a){case"on":{if(!l.get("event")){if(r)return n.push({severity:"error",code:"MISSING_EVENT_ROLE",message:"Event handler requires event role: [on event:click ...]",source:"schema"}),f(Lt("on",l,[],{sourceLanguage:"explicit"}));throw new Error("Event handler requires event role: [on event:click ...]")}let p=et(l,"body",e);return l.delete("body"),f(Lt("on",l,p,{sourceLanguage:"explicit"}))}case"if":{let m=et(l,"then",e),p=et(l,"else",e);return l.delete("then"),l.delete("else"),f(sr(a,l,m,p.length>0?p:void 0,{sourceLanguage:"explicit"}))}case"repeat":{let m=et(l,"loop-body",e),p=l.get("loop-variant"),h=l.get("variable"),y=l.get("index-variable");l.delete("loop-body"),l.delete("loop-variant"),l.delete("variable"),l.delete("index-variable");let g;p&&p.type==="literal"&&typeof p.value=="string"?g=p.value:l.has("quantity")?g="times":l.has("source")?g="for":l.has("condition")?g="while":g="forever";let S=h?.type==="literal"&&typeof h.value=="string"?h.value:h?.type==="expression"?h.raw:void 0,E=y?.type==="literal"&&typeof y.value=="string"?y.value:void 0;return f(lr(a,l,g,m,S,E,{sourceLanguage:"explicit"}))}default:return f(ar(a,l,{sourceLanguage:"explicit"}))}}function me(o){let e=o.trim();return e.startsWith("[")&&e.endsWith("]")}function et(o,e,t){let r=o.get(e);return r?r.type==="expression"?[nt(r.raw,t)]:[]:[]}function ao(o){if(o){if(o.startsWith("#"))return"id";if(o.startsWith("."))return"class";if(o.startsWith("["))return"attribute";if(o.startsWith("<")||o.startsWith("*"))return"element";if(/[>+~ ]/.test(o)&&o.length>1)return"complex"}}function so(o){let e=[],t="",r=!1,n="",i=0;for(let s=0;s<o.length;s++){let a=o[s];if(r){t+=a,a===n&&o[s-1]!=="\\"&&(r=!1);continue}if(a==='"'||a==="'"){r=!0,n=a,t+=a;continue}if(a==="["){i++,t+=a;continue}if(a==="]"){i--,t+=a;continue}if(a===" "&&i===0){t&&(e.push(t),t="");continue}t+=a}return t&&e.push(t),e}function lo(o,e){if(o.startsWith("#")||o.startsWith(".")||o.startsWith("[")||o.startsWith("@")||o.startsWith("*"))return Ve(o,ao(o));if(o.startsWith('"')||o.startsWith("'"))return F(o.slice(1,-1),"string");if(o==="true")return F(!0,"boolean");if(o==="false")return F(!1,"boolean");let t=o.toLowerCase();if(rt(t,e))return Te(t);let r=o.match(/^(-?\d+(?:\.\d+)?)(ms|s|m|h)?$/);if(r){let n=parseFloat(r[1]);return r[2]?F(o,"duration"):F(n,"number")}return F(o)}function co(o,e){let t=0;for(let r=e;r<o.length;r++)if(o[r]==="[")t++;else if(o[r]==="]"&&(t--,t===0))return r;return o.length-1}function ee(o){let e;if(o.kind==="compound"){let t=o;e=t.statements.map(r=>ee(r)).join(` ${t.chainType} `)}else e=uo(o);return o.annotations&&o.annotations.length>0?o.annotations.map(r=>r.value!==void 0?`@${r.name}(${r.value})`:`@${r.name}`).join(" ")+" "+e:e}function uo(o){let e=[o.action];for(let[t,r]of o.roles)r.type==="flag"?e.push(r.enabled?`+${r.name}`:`~${r.name}`):e.push(`${t}:${cr(r)}`);if(o.kind==="event-handler"){let t=o;t.body&&t.body.length>0&&e.push(`body:${t.body.map(r=>ee(r)).join(" ")}`)}if(o.kind==="conditional"){let t=o;t.thenBranch&&t.thenBranch.length>0&&e.push(`then:${t.thenBranch.map(r=>ee(r)).join(" ")}`),t.elseBranch&&t.elseBranch.length>0&&e.push(`else:${t.elseBranch.map(r=>ee(r)).join(" ")}`)}if(o.kind==="loop"){let t=o;t.loopVariant&&e.push(`loop-variant:${t.loopVariant}`),t.loopVariable&&e.push(`variable:${t.loopVariable}`),t.indexVariable&&e.push(`index-variable:${t.indexVariable}`),t.body&&t.body.length>0&&e.push(`loop-body:${t.body.map(r=>ee(r)).join(" ")}`)}if(o.kind==="command"){let t=o;t.body&&t.body.length>0&&e.push(`body:${t.body.map(r=>ee(r)).join(" ")}`),t.catchBranch&&t.catchBranch.length>0&&e.push(`catch:${t.catchBranch.map(r=>ee(r)).join(" ")}`),t.finallyBranch&&t.finallyBranch.length>0&&e.push(`finally:${t.finallyBranch.map(r=>ee(r)).join(" ")}`),t.asyncVariant&&e.push(`async-variant:${t.asyncVariant}`),t.asyncBody&&t.asyncBody.length>0&&e.push(`async-body:${t.asyncBody.map(r=>ee(r)).join(" ")}`)}return`[${e.join(" ")}]`}function cr(o){switch(o.type){case"literal":return typeof o.value=="string"?o.dataType==="string"||/\s/.test(o.value)?`"${o.value}"`:o.value:String(o.value);case"selector":return o.value;case"reference":return o.value;case"property-path":return`${cr(o.object)}'s ${o.property}`;case"expression":return o.raw;case"flag":return o.name}}var po=class{constructor(o){this.namespace=o,this.enabled=this.checkEnabled()}checkEnabled(){if(typeof process<"u"&&process.env){let o=process.env.DEBUG||"";return o==="*"||o.includes("framework:*")||o.includes(`framework:${this.namespace}`)}return!1}log(o,e,...t){if(!this.enabled)return;let r=`[framework:${this.namespace}]`,n=new Date().toISOString();switch(o){case"debug":console.debug(`${n} ${r} DEBUG:`,e,...t);break;case"info":console.info(`${n} ${r} INFO:`,e,...t);break;case"warn":console.warn(`${n} ${r} WARN:`,e,...t);break;case"error":console.error(`${n} ${r} ERROR:`,e,...t);break}}debug(o,...e){this.log("debug",o,...e)}info(o,...e){this.log("info",o,...e)}warn(o,...e){this.log("warn",o,...e)}error(o,...e){this.log("error",o,...e)}isEnabled(){return this.enabled}enable(){this.enabled=!0}disable(){this.enabled=!1}};function mo(o){return new po(o)}function Ce(o,e){return!e||e.length===0||e.includes(o)||e.includes("expression")?!0:o==="property-path"?e.some(t=>["selector","reference","expression"].includes(t)):!1}function fo(o,e){return o?.possessive?.keywords?.[e]}function ur(o){return!1}var _e=class Pe{constructor(){this.logger=mo("pattern-matcher"),this.stemMatchCount=0,this.totalKeywordMatches=0}safeToLowerCase(e){return typeof e=="string"?e.toLowerCase():e==null?"":String(e).toLowerCase()}matchPattern(e,t,r){let n=e.mark(),i=new Map;if(this.logger.debug("========================================"),this.logger.debug("matchPattern ENTRY"),this.logger.debug("Pattern ID:",t.id),this.logger.debug("Pattern command:",t.command),this.logger.debug("Pattern language:",t.language),this.logger.debug("Pattern template:",JSON.stringify(t.template,null,2)),this.logger.isEnabled()){let l=[];for(let c=0;c<10;c++){let d=e.peek(c);if(d)l.push({type:d.type,value:d.value,kind:d.kind});else break}this.logger.debug("Input tokens (first 10):",l),this.logger.debug("Profile code:",r?.code)}this.currentProfile=r,this.stemMatchCount=0,this.totalKeywordMatches=0,this.logger.debug("--- Calling matchTokenSequence ---"),this.logger.debug("Pattern tokens to match:",JSON.stringify(t.template.tokens,null,2));let s=this.matchTokenSequence(e,t.template.tokens,i);if(this.logger.debug("matchTokenSequence returned:",s),this.logger.debug("Captured roles:",Array.from(i.entries()).map(([l,c])=>[l,JSON.stringify(c)])),!s)return this.logger.debug(">>> MATCH FAILED - resetting token position"),e.reset(n),null;let a=this.calculateConfidence(t,i);return this.applyExtractionRules(t,i),{pattern:t,captured:i,consumedTokens:e.position()-n.position,confidence:a}}matchBest(e,t,r){let n=[];for(let s of t){let a=e.mark(),l=this.matchPattern(e,s,r);l&&n.push(l),e.reset(a)}if(n.length===0)return null;n.sort((s,a)=>{let l=a.pattern.priority-s.pattern.priority;if(l!==0)return l;let c=a.confidence-s.confidence;return Math.abs(c)>.001?c:a.consumedTokens-s.consumedTokens});let i=n[0];return this.matchPattern(e,i.pattern),i}matchTokenSequence(e,t,r,n){let i=t[0],s=i?.type==="literal"&&(i.value==="and"||i.value==="then"||i.alternatives?.includes("and")||i.alternatives?.includes("then"));if(this.currentProfile?.code==="ar"&&!s)for(;e.peek()?.kind==="conjunction";)e.advance();let a=null,l=null;for(let c=0;c<t.length;c++){let d=t[c];this.logger.debug(" >> Matching pattern token:",JSON.stringify(d,null,2));let u=e.peek();if(this.logger.debug(" >> Current input token:",u?JSON.stringify({type:u.type,value:u.value,kind:u.kind}):"EOF"),d.type==="role"&&d.greedy){let y=this.collectStopMarkers(t,c+1);if(n)for(let S of n)y.add(S);let g=[];for(;!e.isAtEnd();){let S=e.peek();if(!S||this.isStopMarker(S,y))break;g.push(S.value),e.advance()}if(g.length>0){r.set(d.role,{type:"expression",raw:g.join(" ")}),a=null,l=null;continue}else{if(d.optional)continue;return!1}}if(d.type==="group"){let y=this.collectStopMarkers(t,c+1);if(n)for(let S of n)y.add(S);if(this.matchGroupToken(e,d,r,y)){a=null,l=null;continue}if(this.isOptional(d))continue;return!1}let f=d.type==="role"&&d.optional===!0,m=f?e.mark():null;if(d.type==="role"&&!f){let y=c+1<t.length?t[c+1]:null;if(y?.type==="literal"){let g=e.peek();if(g&&this.getMatchType(g,y.value)!=="none"){if(this.logger.debug(" >> MARKER-STEAL GUARD: current token matches next literal, skipping role"),this.logger.debug(" >> Token match FAILED"),this.isOptional(d))continue;if(a&&l){this.logger.debug(" >> BACKTRACKING: undoing optional role",l),e.reset(a),r.delete(l),a=null,l=null;let S=this.matchPatternToken(e,d,r);if(this.logger.debug(" >> Backtrack retry result:",S),S)continue}return!1}}}let h=this.matchPatternToken(e,d,r);if(this.logger.debug(" >> Match result:",h),h){f?(a=m,l=d.role):(a=null,l=null);continue}if(this.logger.debug(" >> Token match FAILED"),!this.isOptional(d)){if(a&&l){this.logger.debug(" >> BACKTRACKING: undoing optional role",l),e.reset(a),r.delete(l),a=null,l=null;let y=this.matchPatternToken(e,d,r);if(this.logger.debug(" >> Backtrack retry result:",y),y)continue}return!1}}return!0}matchPatternToken(e,t,r){switch(t.type){case"literal":return this.matchLiteralToken(e,t);case"role":return this.matchRoleToken(e,t,r);case"group":return this.matchGroupToken(e,t,r);default:return!1}}matchLiteralToken(e,t){let r=e.peek();if(this.logger.debug(" >>> matchLiteralToken: expecting",t.value),this.logger.debug(" >>> matchLiteralToken: got token",r?JSON.stringify({type:r.type,value:r.value,kind:r.kind}):"null"),!r)return this.logger.debug(" >>> matchLiteralToken: FAIL - no token"),!1;let n=this.getMatchType(r,t.value);if(this.logger.debug(" >>> matchType for",r.value,"vs",t.value,":",n),n!=="none")return this.totalKeywordMatches++,n==="stem"&&this.stemMatchCount++,e.advance(),!0;if(t.alternatives)for(let i of t.alternatives){let s=this.getMatchType(r,i);if(s!=="none")return this.totalKeywordMatches++,s==="stem"&&this.stemMatchCount++,e.advance(),!0}return!1}matchRoleToken(e,t,r){this.logger.debug(" >>> matchRoleToken ENTRY: capturing role",t.role),this.logger.debug(" >>> matchRoleToken: expected types",t.expectedTypes),this.logger.debug(" >>> matchRoleToken: optional?",t.optional),this.skipNoiseWords(e);let n=e.peek();if(this.logger.debug(" >>> After skipNoiseWords, current token:",n?JSON.stringify({value:n.value,kind:n.kind}):"null"),!n)return t.optional||!1;let i=this.tryMatchPossessiveExpression(e);if(i)return t.expectedTypes&&t.expectedTypes.length>0&&!Ce(i.type,t.expectedTypes)?t.optional||!1:(r.set(t.role,i),!0);let s=this.tryMatchMethodCallExpression(e);if(s)return t.expectedTypes&&t.expectedTypes.length>0&&!Ce(s.type,t.expectedTypes)?t.optional||!1:(r.set(t.role,s),!0);let a=this.tryMatchPossessiveSelectorExpression(e);if(a)return t.expectedTypes&&t.expectedTypes.length>0&&!Ce(a.type,t.expectedTypes)?t.optional||!1:(r.set(t.role,a),!0);let l=this.tryMatchPropertyAccessExpression(e);if(l)return t.expectedTypes&&t.expectedTypes.length>0&&!Ce(l.type,t.expectedTypes)?t.optional||!1:(r.set(t.role,l),!0);let c=this.tryMatchSelectorPropertyExpression(e);if(c)return t.expectedTypes&&t.expectedTypes.length>0&&!Ce(c.type,t.expectedTypes)?t.optional||!1:(r.set(t.role,c),!0);this.logger.debug(" >>> Trying tokenToSemanticValue for token:",n?JSON.stringify({value:n.value,kind:n.kind}):"null");let d=this.tokenToSemanticValue(n);return this.logger.debug(" >>> tokenToSemanticValue returned:",d?JSON.stringify(d):"null"),d?(this.logger.debug(" >>> Validating type:",d.type,"against expected:",t.expectedTypes),t.expectedTypes&&t.expectedTypes.length>0&&!Ce(d.type,t.expectedTypes)?(this.logger.debug(" >>> TYPE MISMATCH - returning",t.optional||!1),t.optional||!1):(this.logger.debug(" >>> Type validation PASSED"),r.set(t.role,d),e.advance(),!0)):t.optional||!1}tryMatchPossessiveExpression(e){let t=e.peek();if(!t||!this.currentProfile)return null;let r=t.normalized||t.value,n=this.safeToLowerCase(r),i=fo(this.currentProfile,n);if(!i)return null;let s=e.mark();e.advance();let a=e.peek();if(!a)return e.reset(s),null;if(a.kind==="identifier"||a.kind==="keyword"&&!this.isStructuralKeyword(a.value)||a.kind==="selector"&&a.value.startsWith("*")||a.kind==="selector"&&a.value.startsWith("@")||a.kind==="selector"&&a.value.startsWith(".")&&/^\.[a-zA-Z_]\w*/.test(a.value)){e.advance();let l=a.value;a.kind==="selector"&&l.startsWith(".")&&/^\.[a-zA-Z_]\w*/.test(l)&&(l=l.substring(1));let c=l;for(;e.peek()?.kind==="selector"&&e.peek().value.startsWith(".")&&/^\.[a-zA-Z_]\w*/.test(e.peek().value);)c+=e.peek().value,e.advance();let d=e.peek();return d?.kind==="literal"&&d.value.startsWith("(")&&(c+=d.value,e.advance()),tt(Te(i),c)}return e.reset(s),null}isStructuralKeyword(e){return new Set(["into","in","to","from","at","by","with","without","before","after","of","as","on","then","end","else","if","repeat","while","for","toggle","add","remove","put","set","show","hide","increment","decrement","send","trigger","call"]).has(e.toLowerCase())}tryMatchMethodCallExpression(e){let t=e.peek();if(!t||t.kind!=="selector")return null;let r=e.mark();e.advance();let n=e.peek();if(!n||n.kind!=="operator"||n.value!==".")return e.reset(r),null;e.advance();let i=e.peek();if(!i||i.kind!=="identifier")return e.reset(r),null;e.advance();let s=e.peek();if(!s||s.kind!=="punctuation"||s.value!=="(")return e.reset(r),null;e.advance();let a=[];for(;!e.isAtEnd()&&a.length<Pe.MAX_METHOD_ARGS;){let c=e.peek();if(!c)break;if(c.kind==="punctuation"&&c.value===")"){e.advance();break}if(c.kind==="punctuation"&&c.value===","){e.advance();continue}a.push(c.value),e.advance()}return{type:"expression",raw:`${t.value}.${i.value}(${a.join(", ")})`}}tryMatchPropertyAccessExpression(e){let t=e.peek();if(!t||t.kind!=="identifier"&&t.kind!=="keyword")return null;let r=e.mark();e.advance();let n=e.peek();if(!n||n.kind!=="operator"||n.value!==".")return e.reset(r),null;e.advance();let i=e.peek();if(!i||i.kind!=="identifier")return e.reset(r),null;e.advance();let s=`${t.value}.${i.value}`,a=1;for(;!e.isAtEnd()&&a<Pe.MAX_PROPERTY_DEPTH;){let c=e.peek();if(!c||c.kind!=="operator"||c.value!==".")break;e.advance();let d=e.peek();if(!d||d.kind!=="identifier")break;e.advance(),s+=`.${d.value}`,a++}let l=e.peek();if(l&&l.kind==="punctuation"&&l.value==="("){e.advance();let c=[],d=0;for(;!e.isAtEnd()&&c.length<Pe.MAX_METHOD_ARGS;){let f=e.peek();if(!f)break;if(f.kind==="punctuation"&&f.value===")"){if(d===0){e.advance();break}d--}if(f.kind==="punctuation"&&f.value==="("&&d++,f.kind==="punctuation"&&f.value===","){e.advance();continue}c.push(f.value),e.advance()}return{type:"expression",raw:`${s}(${c.join(", ")})`}}return{type:"expression",raw:s}}tryMatchPossessiveSelectorExpression(e){let t=e.peek();if(!t||t.kind!=="selector")return null;let r=e.mark();e.advance();let n=e.peek();if(!n||n.kind!=="punctuation"||n.value!=="'s")return e.reset(r),null;e.advance();let i=e.peek();return!i||i.kind!=="selector"&&i.kind!=="identifier"?(e.reset(r),null):(e.advance(),tt(Ve(t.value),i.value))}tryMatchSelectorPropertyExpression(e){let t=e.peek();if(!t||t.kind!=="selector"||typeof t.value!="string"||!t.value.startsWith("#"))return null;let r=e.mark();e.advance();let n=e.peek();if(!n||n.kind!=="selector"||!n.value.startsWith("."))return e.reset(r),null;let i=e.peek(1);i&&i.kind,e.advance();let s=n.value.slice(1);return tt(Ve(t.value),s)}matchGroupToken(e,t,r,n){let i=e.mark(),s=new Set(r.keys());if(this.matchTokenSequence(e,t.tokens,r,n))return!0;e.reset(i);for(let c of r.keys())s.has(c)||r.delete(c);if(!t.optional)return!1;let l=this.getGroupLeadingMarker(t);if(l)for(let c=1;c<=Pe.MAX_MARKER_SCAN;c++){let d=e.peek(c);if(!d)break;if((d.normalized||d.value).toLowerCase()===l){this.logger.debug(" >> MARKER SCAN: found",l,"at offset",c,"- skipping intervening tokens");for(let m=0;m<c;m++)e.advance();if(this.matchTokenSequence(e,t.tokens,r,n))return!0;e.reset(i);for(let m of r.keys())s.has(m)||r.delete(m);break}}return!0}getGroupLeadingMarker(e){let t=e.tokens[0];return t?.type==="literal"?t.value.toLowerCase():null}getMatchType(e,t){return e.value===t?"exact":e.normalized===t?"normalized":e.stem===t&&e.stemConfidence!==void 0&&e.stemConfidence>=.7?"stem":e.kind==="keyword"&&this.safeToLowerCase(e.value)===t.toLowerCase()?"case-insensitive":"none"}collectStopMarkers(e,t){let r=new Set;for(let n=t;n<e.length;n++){let i=e[n];if(i.type==="literal"){if(r.add(i.value.toLowerCase()),i.alternatives)for(let s of i.alternatives)r.add(s.toLowerCase());break}if(i.type==="group"){for(let s of i.tokens)if(s.type==="literal"){if(r.add(s.value.toLowerCase()),s.alternatives)for(let a of s.alternatives)r.add(a.toLowerCase());break}if(!i.optional)break}}return r}isStopMarker(e,t){return t.size===0?!1:!!(t.has(e.value.toLowerCase())||e.normalized&&t.has(e.normalized.toLowerCase()))}tokenToSemanticValue(e){switch(e.kind){case"selector":return Ve(e.value);case"literal":return this.parseLiteralValue(e.value);case"keyword":let t=e.normalized||e.value,r=this.safeToLowerCase(t);return ur(r)?Te(r):F(e.normalized||e.value);case"identifier":if(typeof e.value=="string"&&e.value.startsWith(":"))return Te(e.value);let n=this.safeToLowerCase(e.value);return ur(n)?Te(n):{type:"expression",raw:e.value};case"url":return F(e.value,"string");default:return null}}parseLiteralValue(e){if(e.startsWith('"')||e.startsWith("'")||e.startsWith("`")||e.startsWith("\u300C")){let n=e.slice(1,-1);return F(n,"string")}if(e==="true")return F(!0,"boolean");if(e==="false")return F(!1,"boolean");let t=e.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/);if(t){let n=parseFloat(t[1]);return t[2]?F(e,"duration"):F(n,"number")}let r=parseFloat(e);return isNaN(r)?F(e,"string"):F(r,"number")}applyExtractionRules(e,t){for(let[r,n]of Object.entries(e.extraction))t.has(r)||(n.value!==void 0?t.set(r,{type:"literal",value:n.value}):n.default&&t.set(r,n.default))}isOptional(e){return e.type!=="literal"&&e.optional===!0}calculateConfidence(e,t){let r=0,n=0,i=c=>e.extraction?.[c]?.default!==void 0;for(let c of e.template.tokens)if(c.type==="role")n+=1,t.has(c.role)&&(r+=1);else if(c.type==="group"){for(let d of c.tokens)if(d.type==="role"){let u=i(d.role),f=.8;n+=f,t.has(d.role)?r+=f:u&&(r+=f*.6)}}let s=n>0?r/n:1;if(this.stemMatchCount>0&&this.totalKeywordMatches>0){let c=this.stemMatchCount/this.totalKeywordMatches*.15;s=Math.max(.5,s-c)}let a=this.calculateVSOConfidenceBoost(e);s=Math.min(1,s+a);let l=this.arabicPrepositionDisambiguation(e,t);return s=Math.max(0,Math.min(1,s+l)),s}calculateVSOConfidenceBoost(e){if(e.language!=="ar")return 0;let t=e.template.tokens[0];if(!t||t.type!=="literal")return 0;let r=new Set(["\u0628\u062F\u0644","\u063A\u064A\u0631","\u0623\u0636\u0641","\u0623\u0632\u0644","\u0636\u0639","\u0627\u062C\u0639\u0644","\u0639\u064A\u0646","\u0632\u062F","\u0627\u0646\u0642\u0635","\u0633\u062C\u0644","\u0623\u0638\u0647\u0631","\u0623\u062E\u0641","\u0634\u063A\u0644","\u0623\u0631\u0633\u0644","\u0631\u0643\u0632","\u0634\u0648\u0634","\u062A\u0648\u0642\u0641","\u0627\u0646\u0633\u062E","\u0627\u062D\u0630\u0641","\u0627\u0635\u0646\u0639","\u0627\u0646\u062A\u0638\u0631","\u0627\u0646\u062A\u0642\u0627\u0644","\u0623\u0648"]);if(r.has(t.value))return .15;if(t.alternatives){for(let n of t.alternatives)if(r.has(n))return .15}return 0}arabicPrepositionDisambiguation(e,t){if(e.language!=="ar")return 0;let r=0,n={patient:["\u0639\u0644\u0649"],destination:["\u0625\u0644\u0649","\u0627\u0644\u0649"],source:["\u0645\u0646"],agent:["\u0645\u0646"],manner:["\u0628"],style:["\u0628"],goal:["\u0625\u0644\u0649","\u0627\u0644\u0649"],method:["\u0628"]};for(let[i,s]of t.entries()){let a=n[i];if(!a||a.length===0)continue;let l="metadata"in s?s.metadata:void 0;if(l&&typeof l.prepositionValue=="string"){let c=l.prepositionValue;a.includes(c)?r+=.1:r-=.1}}return Math.max(-.1,Math.min(.1,r))}skipNoiseWords(e){let t=e.peek();if(!t)return;let r=this.safeToLowerCase(t.value);if(Pe.ENGLISH_NOISE_WORDS.has(r)){let n=e.mark();e.advance();let i=e.peek();if(i&&i.kind==="selector")return;e.reset(n)}r==="class"&&e.advance()}extractEventModifiers(e){let t={},r=!1;for(;!e.isAtEnd();){let n=e.peek();if(!n||n.kind!=="event-modifier")break;let i=n.metadata;if(!i)break;switch(r=!0,i.modifierName){case"once":t.once=!0;break;case"debounce":typeof i.value=="number"&&(t.debounce=i.value);break;case"throttle":typeof i.value=="number"&&(t.throttle=i.value);break;case"queue":(i.value==="first"||i.value==="last"||i.value==="all"||i.value==="none")&&(t.queue=i.value);break}e.advance()}return r?t:void 0}};_e.MAX_MARKER_SCAN=3;_e.MAX_PROPERTY_DEPTH=10;_e.MAX_METHOD_ARGS=20;_e.ENGLISH_NOISE_WORDS=new Set(["the","a","an"]);var ho=_e,rs=new ho;var Mt=class{constructor(){this.name="string-literal"}canExtract(o,e){let t=o[e];return t==='"'||t==="'"||t==="`"||t==="\u201C"||t==="\u2018"}extract(o,e){let t=o[e];if(t==="\u201C"){let i=1;for(;e+i<o.length;){if(o[e+i]==="\u201D")return i++,{value:o.substring(e,e+i),length:i};i++}return null}if(t==="\u2018"){let i=1;for(;e+i<o.length;){if(o[e+i]==="\u2019")return i++,{value:o.substring(e,e+i),length:i};i++}return null}let r=1,n=!1;for(;e+r<o.length;){let i=o[e+r];if(n){n=!1,r++;continue}if(i==="\\"){n=!0,r++;continue}if(i===t)return r++,{value:o.substring(e,e+r),length:r};r++}return null}},Ot=class{constructor(){this.name="number"}canExtract(o,e){return/\d/.test(o[e])}extract(o,e){let t=0,r=!1;for(;e+t<o.length;){let s=o[e+t];if(/\d/.test(s))t++;else if(s==="."&&!r)r=!0,t++;else break}if(t===0)return null;let n=o.substring(e,e+t),i=e+t;if(i<o.length){let s=o.slice(i),a=[{pattern:"\u6BEB\u79D2",suffix:"ms"},{pattern:"\u5206\u949F",suffix:"m"},{pattern:"\u5C0F\u65F6",suffix:"h"},{pattern:"\u30DF\u30EA\u79D2",suffix:"ms"},{pattern:"\u6642\u9593",suffix:"h"}];for(let c of a)if(s.startsWith(c.pattern))return{value:n+c.suffix,length:t+c.pattern.length,metadata:{hasTimeUnit:!0}};if(s.startsWith("ms"))return{value:n+"ms",length:t+2,metadata:{hasTimeUnit:!0}};let l=[{pattern:"\u79D2",suffix:"s"},{pattern:"\u5206",suffix:"m"}];for(let c of l)if(s.startsWith(c.pattern))return{value:n+c.suffix,length:t+1,metadata:{hasTimeUnit:!0}};if(/^[smh](?![a-zA-Z])/.test(s))return{value:n+s[0],length:t+1,metadata:{hasTimeUnit:!0}}}return{value:n,length:t}}};function yo(o){return"setContext"in o&&typeof o.setContext=="function"}function go(o){let e={language:o.language,direction:o.direction,lookupKeyword:o.lookupKeyword.bind(o),isKeyword:o.isKeyword.bind(o),isKeywordStart:o.isKeywordStart.bind(o),...o.isKeywordStartAtBoundary?{isKeywordStartAtBoundary:o.isKeywordStartAtBoundary.bind(o)}:{}};return o.normalizer?{...e,normalizer:o.normalizer}:e}var H=class{constructor(o,e){this.pos=0,this.tokens=o,this.language=e}peek(o=0){let e=this.pos+o;return e<0||e>=this.tokens.length?null:this.tokens[e]}advance(){if(this.isAtEnd())throw new Error("Unexpected end of token stream");return this.tokens[this.pos++]}isAtEnd(){return this.pos>=this.tokens.length}mark(){return{position:this.pos}}reset(o){this.pos=o.position}position(){return this.pos}remaining(){return this.tokens.slice(this.pos)}takeWhile(o){let e=[];for(;!this.isAtEnd()&&o(this.peek());)e.push(this.advance());return e}skipWhile(o){for(;!this.isAtEnd()&&o(this.peek());)this.advance()}};function _(o,e){return{start:o,end:e}}function B(o,e,t,r){if(typeof o=="object"){let{value:i,kind:s,position:a,normalized:l,stem:c,stemConfidence:d,metadata:u}=o;return{value:i,kind:s,position:a,...l!==void 0&&{normalized:l},...c!==void 0&&{stem:c},...d!==void 0&&{stemConfidence:d},...u!==void 0&&{metadata:u}}}let n=o;if(!e||!t)throw new Error("createToken requires kind and position parameters");if(typeof r=="string")return{value:n,kind:e,position:t,normalized:r};if(r){let{normalized:i,stem:s,stemConfidence:a,metadata:l}=r;return{value:n,kind:e,position:t,...i!==void 0&&{normalized:i},...s!==void 0&&{stem:s},...a!==void 0&&{stemConfidence:a},...l!==void 0&&{metadata:l}}}return{value:n,kind:e,position:t}}function ae(o){return/\s/.test(o)}function ot(o){return o==="#"||o==="."||o==="["||o==="@"||o==="*"||o==="<"}function it(o){return o==='"'||o==="'"||o==="`"||o==="\u300C"||o==="\u300D"}function ie(o){return/\d/.test(o)}function at(o){return/[a-zA-Z]/.test(o)}function q(o){return/[a-zA-Z0-9_-]/.test(o)}function dr(o,e){if(e>=o.length)return null;let t=o[e];if(!ot(t))return null;let r=e,n="";if(t==="#"||t==="."){for(n+=o[r++];r<o.length&&q(o[r]);)n+=o[r++];if(n.length<=1)return null;if(r<o.length&&o[r]==="."&&t==="#"){let s=r+1;for(;s<o.length&&q(o[s]);)s++;if(s<o.length&&o[s]==="(")return n}}else if(t==="["){let i=1,s=!1,a=null,l=!1;for(n+=o[r++];r<o.length&&i>0;){let c=o[r];n+=c,l?l=!1:c==="\\"?l=!0:s?c===a&&(s=!1,a=null):c==='"'||c==="'"||c==="`"?(s=!0,a=c):c==="["?i++:c==="]"&&i--,r++}if(i!==0)return null}else if(t==="@"){for(n+=o[r++];r<o.length&&q(o[r]);)n+=o[r++];if(n.length<=1)return null}else if(t==="*"){for(n+=o[r++];r<o.length&&q(o[r]);)n+=o[r++];if(n.length<=1)return null}else if(t==="<"){if(n+=o[r++],r>=o.length||!at(o[r]))return null;for(;r<o.length&&q(o[r]);)n+=o[r++];for(;r<o.length;){let i=o[r];if(i==="."){if(n+=o[r++],r>=o.length||!q(o[r]))return null;for(;r<o.length&&q(o[r]);)n+=o[r++]}else if(i==="#"){if(n+=o[r++],r>=o.length||!q(o[r]))return null;for(;r<o.length&&q(o[r]);)n+=o[r++]}else if(i==="["){let s=1,a=!1,l=null,c=!1;for(n+=o[r++];r<o.length&&s>0;){let d=o[r];n+=d,c?c=!1:d==="\\"?c=!0:a?d===l&&(a=!1,l=null):d==='"'||d==="'"||d==="`"?(a=!0,l=d):d==="["?s++:d==="]"&&s--,r++}if(s!==0)return null}else break}for(;r<o.length&&ae(o[r]);)n+=o[r++];if(r<o.length&&o[r]==="/")for(n+=o[r++];r<o.length&&ae(o[r]);)n+=o[r++];if(r>=o.length||o[r]!==">")return null;n+=o[r++]}return n||null}function vo(o,e){if(e>=o.length||o[e]!=="'"||e+1>=o.length||o[e+1].toLowerCase()!=="s")return!1;if(e+2>=o.length)return!0;let r=o[e+2];return ae(r)||r==="*"||!q(r)}function pr(o,e){if(e>=o.length)return null;let t=o[e];if(!it(t)||t==="'"&&vo(o,e))return null;let n={'"':'"',"'":"'","`":"`","\u300C":"\u300D"}[t];if(!n)return null;let i=e+1,s=t,a=!1;for(;i<o.length;){let l=o[i];if(s+=l,a)a=!1;else if(l==="\\")a=!0;else if(l===n)return s;i++}return s}function mr(o,e){if(e>=o.length)return!1;let t=o[e],r=o[e+1]||"",n=o[e+2]||"";if(t==="/"&&r!=="/"&&/[a-zA-Z0-9._-]/.test(r)||t==="/"&&r==="/"&&/[a-zA-Z]/.test(n)||t==="."&&(r==="/"||r==="."&&n==="/"))return!0;let i=o.slice(e,e+8).toLowerCase();return!!(i.startsWith("http://")||i.startsWith("https://"))}function fr(o,e){if(!mr(o,e))return null;let t=e,r="",n=/[a-zA-Z0-9/:._\-?&=%@+~!$'()*,;[\]]/;for(;t<o.length;){let i=o[t];if(i==="#"){if(r.length>0&&/[a-zA-Z0-9/.]$/.test(r))for(r+=i,t++;t<o.length&&/[a-zA-Z0-9_-]/.test(o[t]);)r+=o[t++];break}if(n.test(i))r+=i,t++;else break}return r.length<2?null:r}function hr(o,e){if(e>=o.length)return null;let t=o[e];if(!ie(t)&&t!=="-"&&t!=="+")return null;let r=e,n="";if((o[r]==="-"||o[r]==="+")&&(n+=o[r++]),r>=o.length||!ie(o[r]))return null;for(;r<o.length&&ie(o[r]);)n+=o[r++];if(r<o.length&&o[r]===".")for(n+=o[r++];r<o.length&&ie(o[r]);)n+=o[r++];return r<o.length&&(o.slice(r,r+2)==="ms"?n+="ms":(o[r]==="s"||o[r]==="m"||o[r]==="h")&&(n+=o[r])),n}var ko=["===","!==","->","==","!=","<=",">=","&&","||","**","+=","-=","*=","/=","+","-","*","/","=",">","<","!","&","|","%","^","~"];var ss=new Set(ko),xo=new Set(["patient","destination","source","style","event","eventMarker","agent","goal","manner","into","from","to","with","at","of","as","by","in","on","over","under","between","through","without"]),So=["click","dblclick","input","change","submit","keydown","keyup","keypress","mousedown","mouseup","mouseover","mouseout","mouseenter","mouseleave","mousemove","pointerdown","pointerup","pointermove","focus","blur","load","resize","scroll"],yr=class gr{constructor(){this.profileKeywords=[],this.multiWordKeywords=[],this.profileKeywordMap=new Map,this.rawExtraEntries=[],this.extractors=[]}getExtraKeywordEntries(){return this.rawExtraEntries}tokenize(e){if(this.isUsingExtractors())return this.tokenizeWithExtractors(e);throw new Error(`${this.constructor.name}: tokenize() not implemented and no extractors registered. Either register extractors or override tokenize() method.`)}registerExtractor(e){yo(e)&&e.setContext(go(this)),this.extractors.push(e)}registerExtractors(e){for(let t of e)this.registerExtractor(t)}clearExtractors(){this.extractors=[]}isUsingExtractors(){return this.extractors.length>0}tokenizeWithExtractors(e){let t=[],r=0;for(;r<e.length;){for(;r<e.length&&ae(e[r]);)r++;if(r>=e.length)break;let n=this.tryMultiWordKeyword(e,r);if(n){t.push(n),r=n.position.end;continue}let i=!1;for(let s of this.extractors)if(s.canExtract(e,r)){let a=s.extract(e,r);if(a){let l=a.metadata?.normalized,c=a.metadata?.stem,d=a.metadata?.stemConfidence,u={};if(a.metadata)for(let[m,p]of Object.entries(a.metadata))m!=="normalized"&&m!=="stem"&&m!=="stemConfidence"&&(u[m]=p);let f={};l&&(f.normalized=l),c&&(f.stem=c),d!==void 0&&(f.stemConfidence=d),Object.keys(u).length>0&&(f.metadata=u),t.push(B(a.value,this.classifyToken(a.value),_(r,r+a.length),Object.keys(f).length>0?f:void 0)),r+=a.length,i=!0;break}}if(!i){let s=e[r],a=this.classifyUnknownChar(s);t.push(B(s,a,_(r,r+1))),r++}}return new H(t,this.language)}classifyUnknownChar(e){return"()[]{},:;".includes(e)?"punctuation":"+-*/<>=!&|".includes(e)?"operator":"identifier"}tryPropertyAccess(e,t,r){if(e[t]!==".")return!1;let n=r[r.length-1],i=n&&n.position.end<t;if(n&&!i&&(n.kind==="identifier"||n.kind==="keyword"||n.kind==="selector"))return r.push(B(".","operator",_(t,t+1))),!0;let l=t+1;for(;l<e.length&&q(e[l]);)l++;return l<e.length&&e[l]==="("?(r.push(B(".","operator",_(t,t+1))),!0):!1}initializeKeywordsFromProfile(e,t=[]){let r=new Map;if(this.rawExtraEntries=t,e.keywords){for(let[n,i]of Object.entries(e.keywords))if(r.set(i.primary,{native:i.primary,normalized:i.normalized||n}),i.alternatives)for(let s of i.alternatives)r.set(s,{native:s,normalized:i.normalized||n})}if(e.references){for(let[n,i]of Object.entries(e.references))r.set(i,{native:i,normalized:n});for(let n of Object.keys(e.references))r.has(n)||r.set(n,{native:n,normalized:n})}if(e.roleMarkers){for(let[n,i]of Object.entries(e.roleMarkers))if(i.primary&&r.set(i.primary,{native:i.primary,normalized:n}),i.alternatives)for(let s of i.alternatives)r.set(s,{native:s,normalized:n})}if(e.possessive?.keywords)for(let[n,i]of Object.entries(e.possessive.keywords))r.set(n,{native:n,normalized:i});for(let n of So)r.has(n)||r.set(n,{native:n,normalized:n});for(let n of t)r.set(n.native,n);this.profileKeywords=Array.from(r.values()).sort((n,i)=>i.native.length-n.native.length),this.multiWordKeywords=this.profileKeywords.filter(n=>n.native.includes(" ")&&!xo.has(n.normalized)),this.profileKeywordMap=new Map;for(let n of this.profileKeywords){this.profileKeywordMap.set(n.native.toLowerCase(),n);let i=this.removeDiacritics(n.native);i!==n.native&&!this.profileKeywordMap.has(i.toLowerCase())&&this.profileKeywordMap.set(i.toLowerCase(),n)}}removeDiacritics(e){return e.replace(/[\u064B-\u0652\u0670]/g,"")}tryProfileKeyword(e,t){for(let r of this.profileKeywords)if(e.slice(t).startsWith(r.native))return B(r.native,"keyword",_(t,t+r.native.length),r.normalized);return null}tryMultiWordKeyword(e,t,r=n=>/[\p{L}\p{N}_]/u.test(n)){if(this.multiWordKeywords.length===0)return null;let n=e.slice(t);for(let i of this.multiWordKeywords){if(!n.startsWith(i.native))continue;let s=e[t+i.native.length];if(!(s!==void 0&&r(s)))return B(i.native,"keyword",_(t,t+i.native.length),i.normalized)}return null}isKeywordStart(e,t){let r=e.slice(t);return this.profileKeywords.some(n=>r.startsWith(n.native))}isKeywordStartAtBoundary(e,t,r=n=>/[\p{L}\p{N}_]/u.test(n)){let n=e.slice(t);return this.profileKeywords.some(i=>{if(!n.startsWith(i.native))return!1;let s=e[t+i.native.length];return s===void 0||!r(s)})}lookupKeyword(e){return this.profileKeywordMap.get(e.toLowerCase())}isKeyword(e){return this.profileKeywordMap.has(e.toLowerCase())}setNormalizer(e){this.normalizer=e}tryNormalize(e){if(!this.normalizer)return null;let t=this.normalizer.normalize(e);return t.stem!==e&&t.confidence>=.7?t:null}tryMorphKeywordMatch(e,t,r){let n=this.tryNormalize(e);if(!n)return null;let i=this.lookupKeyword(n.stem);if(!i)return null;let s={normalized:i.normalized,stem:n.stem,stemConfidence:n.confidence};return B(e,"keyword",_(t,r),s)}trySelector(e,t){let r=dr(e,t);return r?B(r,"selector",_(t,t+r.length)):null}tryEventModifier(e,t){if(e[t]!==".")return null;let r=e.slice(t).match(/^\.(?:once|debounce|throttle|queue)(?:\(([^)]+)\))?(?:\s|$|\.)/);if(!r)return null;let n=r[0].replace(/(\s|\.)$/,""),i=n.slice(1).split("(")[0],s=r[1];return{...B(n,"event-modifier",_(t,t+n.length)),metadata:{modifierName:i,value:s?i==="queue"?s:parseInt(s,10):void 0}}}tryString(e,t){let r=pr(e,t);return r?B(r,"literal",_(t,t+r.length)):null}tryNumber(e,t){let r=hr(e,t);return r?B(r,"literal",_(t,t+r.length)):null}tryMatchTimeUnit(e,t,r,n=!1){let i=t;if(n)for(;i<e.length&&ae(e[i]);)i++;let s=e.slice(i);for(let a of r){let l=s.slice(0,a.length);if(a.caseInsensitive?l.toLowerCase()===a.pattern.toLowerCase():l===a.pattern){if(a.notFollowedBy&&(s[a.length]||"")===a.notFollowedBy)continue;if(a.checkBoundary){let d=s[a.length]||"";if(q(d))continue}return{suffix:a.suffix,endPos:i+a.length}}}return null}parseBaseNumber(e,t,r=!0){let n=t,i="";if(r&&(e[n]==="-"||e[n]==="+")&&(i+=e[n++]),n>=e.length||!ie(e[n]))return null;for(;n<e.length&&ie(e[n]);)i+=e[n++];if(n<e.length&&e[n]===".")for(i+=e[n++];n<e.length&&ie(e[n]);)i+=e[n++];return!i||i==="-"||i==="+"?null:{number:i,endPos:n}}tryNumberWithTimeUnits(e,t,r,n={}){let{allowSign:i=!0,skipWhitespace:s=!1}=n,a=this.parseBaseNumber(e,t,i);if(!a)return null;let{number:l,endPos:c}=a,d=[...r,...gr.STANDARD_TIME_UNITS],u=this.tryMatchTimeUnit(e,c,d,s);return u&&(l+=u.suffix,c=u.endPos),B(l,"literal",_(t,c))}tryUrl(e,t){let r=fr(e,t);return r?B(r,"url",_(t,t+r.length)):null}tryVariableRef(e,t){if(e[t]!==":"||t+1>=e.length||!q(e[t+1]))return null;let r=t+1;for(;r<e.length&&q(e[r]);)r++;let n=e.slice(t,r);return B(n,"identifier",_(t,r))}tryOperator(e,t){let r=e.slice(t,t+2);if(["==","!=","<=",">=","&&","||","->"].includes(r))return B(r,"operator",_(t,t+2));let n=e[t];return["<",">","!","+","-","*","/","="].includes(n)?B(n,"operator",_(t,t+1)):["(",")","{","}",",",";",":"].includes(n)?B(n,"punctuation",_(t,t+1)):null}tryMultiCharParticle(e,t,r){for(let n of r)if(e.slice(t,t+n.length)===n)return B(n,"particle",_(t,t+n.length));return null}};yr.STANDARD_TIME_UNITS=[{pattern:"ms",suffix:"ms",length:2},{pattern:"s",suffix:"s",length:1,checkBoundary:!0},{pattern:"m",suffix:"m",length:1,checkBoundary:!0,notFollowedBy:"s"},{pattern:"h",suffix:"h",length:1,checkBoundary:!0}];var Be=yr;function ue(o){return e=>{let t=e.charCodeAt(0);return o.some(([r,n])=>t>=r&&t<=n)}}function zt(o){return{stem:o,confidence:1}}function It(o,e,t){return t?{stem:o,confidence:e,metadata:t}:{stem:o,confidence:e}}function re(o){let e="complex";return o.startsWith("#")&&!o.includes(" ")?e="id":o.startsWith(".")&&!o.includes(" ")?e="class":o.startsWith("[")&&o.endsWith("]")?e="attribute":/^[a-z][a-z0-9]*$/i.test(o)&&(e="element"),{type:"selector",value:o,selectorKind:e}}function $(o,e){let t={type:"literal",value:o};return e!==void 0?{type:"literal",value:o,dataType:e}:t}function xe(o){return rt(o)}function J(o){return{type:"reference",value:o}}function se(o,e){return{type:"property-path",object:o,property:e}}function G(o,e,t){let r={kind:"command",action:o,roles:new Map(Object.entries(e))};return t!==void 0?{...r,metadata:t}:r}function fe(o,e,t,r,n,i){let s=new Map;s.set("event",o);let a={kind:"event-handler",action:"on",roles:s,body:e};return t!==void 0&&(a.eventModifiers=t),r!==void 0&&(a.metadata=r),n!==void 0&&n.length>0&&(a.parameterNames=n),i!==void 0&&i.length>0&&(a.additionalEvents=i),a}function vr(o,e,t,r,n){let i={kind:"behavior",action:"behavior",roles:new Map,name:o,parameters:e,eventHandlers:t};return r!==void 0&&r.length>0&&(i.initBlock=r),n!==void 0&&(i.metadata=n),i}function kr(o,e,t,r){let n={kind:"def",action:"def",roles:new Map,name:o,parameters:e,body:t};return r!==void 0&&(n.metadata=r),n}function De(o,e="then",t){let r={kind:"compound",action:"compound",roles:new Map,statements:o,chainType:e};return t!==void 0&&(r.metadata=t),r}function xr(o,e,t,r){let n=new Map;n.set("condition",o);let i={kind:"conditional",action:"if",roles:n,thenBranch:e};return t!==void 0&&(i.elseBranch=t),r!==void 0&&(i.metadata=r),i}function $e(o,e){return!e||e.length===0||e.includes(o)||e.includes("expression")?!0:o==="property-path"?e.some(t=>["selector","reference","expression"].includes(t)):o==="expression"?e.some(t=>["selector","reference","expression"].includes(t)):!1}var bo={action:"toggle",description:"Toggle a class or attribute on/off",category:"dom-class",primaryRole:"patient",roles:[{role:"patient",description:"The class or attribute to toggle",required:!0,expectedTypes:["selector"],selectorKinds:["class","attribute"],svoPosition:1,sovPosition:2},{role:"destination",description:"The target element (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:1,markerVariants:{ko:["\uC5D0\uC11C"]}}],errorCodes:["MISSING_ARGUMENT","NO_VALID_CLASS_NAMES","INVALID_CSS_PROPERTY"],preconditions:[{condition:"Command has at least one argument",errorCode:"MISSING_ARGUMENT",message:"toggle command requires an argument"},{condition:"Class names are valid CSS identifiers",errorCode:"NO_VALID_CLASS_NAMES",message:"toggle command: no valid class names found"}],recoveryHints:{MISSING_ARGUMENT:"Add a class selector (.classname) or attribute to toggle",NO_VALID_CLASS_NAMES:"Ensure class names start with a dot (.) and are valid CSS identifiers",INVALID_CSS_PROPERTY:"Check CSS property name syntax (use kebab-case)"}},wo={action:"add",description:"Add a class or attribute to an element",category:"dom-class",primaryRole:"patient",roles:[{role:"patient",description:"The class or attribute to add",required:!0,expectedTypes:["selector","literal"],svoPosition:1,sovPosition:2},{role:"destination",description:"The target element (defaults to me)",required:!1,expectedTypes:["selector","reference","expression"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:1,markerOverride:{en:"to"}}],errorCodes:["MISSING_ARGUMENT","NO_VALID_CLASS_NAMES","PROPERTY_REQUIRES_VALUE"],preconditions:[{condition:"Command has at least one argument",errorCode:"MISSING_ARGUMENT",message:"add command requires an argument"}],recoveryHints:{MISSING_ARGUMENT:"Add a class selector (.classname) or attribute to add",NO_VALID_CLASS_NAMES:"Ensure class names start with a dot (.) and are valid CSS identifiers",PROPERTY_REQUIRES_VALUE:"When adding a property (*prop), provide a value argument"}},Eo={action:"remove",description:"Remove a class or attribute from an element",category:"dom-class",primaryRole:"patient",targetRole:"source",roles:[{role:"patient",description:"The class/attribute to remove, or the element to remove",required:!0,expectedTypes:["selector","reference"],svoPosition:1,sovPosition:2},{role:"source",description:"The element to remove from (defaults to me)",required:!1,expectedTypes:["selector","reference","expression"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:1}],errorCodes:["MISSING_ARGUMENT","NO_VALID_CLASS_NAMES"],preconditions:[{condition:"Command has at least one argument",errorCode:"MISSING_ARGUMENT",message:"remove command requires an argument"}],recoveryHints:{MISSING_ARGUMENT:"Add a class selector (.classname) or attribute to remove",NO_VALID_CLASS_NAMES:"Ensure class names start with a dot (.) and are valid CSS identifiers"}},To={action:"put",description:"Put content into a target element or variable",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The content to put",required:!0,expectedTypes:["literal","selector","reference","expression"],svoPosition:1,sovPosition:1},{role:"destination",description:"Where to put the content",required:!0,expectedTypes:["selector","reference"],svoPosition:2,sovPosition:2,markerOverride:{en:"into"},markerVariants:{en:["before","after"]},methodCarrier:"method"}],errorCodes:["MISSING_ARGUMENTS","MISSING_CONTENT","MISSING_POSITION","INVALID_POSITION","NO_TARGET","NO_ELEMENTS"],preconditions:[{condition:"Command has content and position arguments",errorCode:"MISSING_ARGUMENTS",message:"put requires arguments"},{condition:"Content to put is specified",errorCode:"MISSING_CONTENT",message:"put requires content"},{condition:"Position keyword is specified (into, before, after, etc.)",errorCode:"MISSING_POSITION",message:"put requires position keyword"}],recoveryHints:{MISSING_ARGUMENTS:"Use syntax: put <content> into/before/after <target>",MISSING_CONTENT:"Add content to put (string, element, or expression)",MISSING_POSITION:"Add position keyword: into, before, after, at start of, at end of",INVALID_POSITION:"Valid positions: into, before, after, at start of, at end of",NO_TARGET:'Ensure target element exists or use "me" reference',NO_ELEMENTS:"Check that the selector matches existing elements"}},Co={action:"set",description:"Set a property or variable to a value",category:"variable",primaryRole:"destination",roles:[{role:"destination",description:"The property or variable to set",required:!0,expectedTypes:["selector","reference","expression","property-path"],svoPosition:1,sovPosition:1,markerOverride:{en:"",ja:"\u3092",ko:"\uB97C",tr:"i",ar:"",sw:"",tl:"",bn:"\u0995\u09C7",qu:"ta",hi:"\u0915\u094B"}},{role:"patient",description:"The value to set",required:!0,expectedTypes:["literal","expression","reference"],svoPosition:2,sovPosition:2,markerOverride:{en:"to",es:"a",pt:"para",fr:"\xE0",de:"auf",id:"ke",ja:"\u306B",ko:"\uC5D0",tr:"e",ar:"\u0625\u0644\u0649",sw:"kwenye",tl:"sa",bn:"\u09A4\u09C7",qu:"man",hi:"\u092E\u0947\u0902"},markerVariants:{tr:["e","a","ye","ya"]}},{role:"scope",description:"The element(s) the attribute/property is set on (defaults to me)",required:!1,expectedTypes:["selector","reference"],svoPosition:3,sovPosition:3,markerOverride:{en:"on",es:"on",pt:"on",fr:"on",de:"on",it:"on",id:"on",ms:"on",sw:"on",tl:"on",zh:"on",vi:"on",ru:"on",uk:"on",pl:"on",th:"on",he:"on",ar:"on",ja:"on",ko:"on",tr:"on",hi:"on",bn:"on",qu:"on"}}],errorCodes:["MISSING_TARGET","INVALID_TARGET","MISSING_VALUE","INVALID_SYNTAX"],preconditions:[{condition:"Command has a target variable or property",errorCode:"MISSING_TARGET",message:"set command requires a target"},{condition:"Target is a valid variable or property reference",errorCode:"INVALID_TARGET",message:"set command target must be a string or object literal"},{condition:'Value is specified with "to" keyword',errorCode:"MISSING_VALUE",message:'set command requires a value (use "to" keyword)'}],recoveryHints:{MISSING_TARGET:"Add a target: set :variable to value OR set element.property to value",INVALID_TARGET:'Use local variable (:name), element property (el.prop), or "the X of Y" syntax',MISSING_VALUE:'Add "to <value>" to specify what to set',INVALID_SYNTAX:"Use syntax: set <target> to <value>"}},Po={action:"bind",description:"Reactively bind a variable to an element or property value",category:"variable",primaryRole:"destination",roles:[{role:"destination",description:"The variable to bind",required:!0,expectedTypes:["reference","expression"],svoPosition:1,sovPosition:1,markerOverride:{en:"",es:"",pt:"",fr:"",de:"",it:"",id:"",ms:"",vi:"",ru:"",uk:"",pl:"",th:"",zh:"",he:"",ar:"",sw:"",tl:"",ja:"\u3092",ko:"\uB97C",tr:"i",bn:"\u0995\u09C7",qu:"ta",hi:"\u0915\u094B"}},{role:"source",description:"The element or property to bind to",required:!0,expectedTypes:["selector","reference","expression"],svoPosition:2,sovPosition:2,markerOverride:{en:"to",es:"a",pt:"para",fr:"\xE0",de:"zu",it:"in",id:"ke",ms:"ke",vi:"v\xE0o",ru:"\u0432",uk:"\u0432",pl:"do",ja:"\u306B",ko:"\uC5D0",tr:"e",ar:"\u0625\u0644\u0649",zh:"\u5230",he:"\u05DC",sw:"kwa",th:"\u0E43\u0E19",tl:"sa",bn:"\u09A4\u09C7",qu:"man",hi:"\u092E\u0947\u0902"}}],errorCodes:["MISSING_TARGET","MISSING_VALUE","INVALID_SYNTAX"],recoveryHints:{MISSING_TARGET:"Add a variable to bind: bind $name to #input",MISSING_VALUE:'Add "to <element>" to specify the binding source',INVALID_SYNTAX:"Use syntax: bind <variable> to <element>"}},No={action:"live",description:"Reactive block: re-run the body when its dependencies change",category:"control-flow",primaryRole:"patient",hasBody:!0,bareKeyword:!0,roles:[]},Ro={action:"eventsource",description:"Open a Server-Sent Events stream and handle its events",category:"async",primaryRole:"patient",hasBody:!0,bareKeyword:!0,roles:[]},Lo={action:"socket",description:"Open a WebSocket and handle its messages",category:"async",primaryRole:"patient",hasBody:!0,bareKeyword:!0,roles:[]},Ao={action:"worker",description:"Define a Web Worker with inline methods",category:"async",primaryRole:"patient",hasBody:!0,bareKeyword:!0,roles:[]},Mo={action:"intercept",description:"Service-worker fetch interception / caching strategies",category:"async",primaryRole:"patient",hasBody:!0,bareKeyword:!0,roles:[]},Oo={action:"show",description:"Make an element visible",category:"dom-visibility",primaryRole:"patient",roles:[{role:"patient",description:"The element to show",required:!0,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:1,sovPosition:1},{role:"style",description:"Animation style (fade, slide, etc.)",required:!1,expectedTypes:["literal"],svoPosition:2,sovPosition:2}]},zo={action:"hide",description:"Make an element invisible",category:"dom-visibility",primaryRole:"patient",roles:[{role:"patient",description:"The element to hide",required:!0,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:1,sovPosition:1},{role:"style",description:"Animation style (fade, slide, etc.)",required:!1,expectedTypes:["literal"],svoPosition:2,sovPosition:2}]},Io={action:"on",description:"Handle an event",category:"event",primaryRole:"event",hasBody:!0,roles:[{role:"event",description:"The event to handle",required:!0,expectedTypes:["literal"],svoPosition:1,sovPosition:2},{role:"source",description:"The element to listen on (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:1}]},Vo={action:"trigger",description:"Trigger/dispatch an event",category:"event",primaryRole:"event",roles:[{role:"event",description:"The event to trigger (supports namespaced events like draggable:start)",required:!0,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:2},{role:"destination",description:"The target element (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:1}]},_o={action:"wait",description:"Wait for a duration or event",category:"async",primaryRole:"duration",roles:[{role:"duration",description:"Duration or event to wait for",required:!0,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:1}]},Bo={action:"fetch",description:"Fetch data from a URL",category:"async",primaryRole:"source",roles:[{role:"source",description:"The URL to fetch from",required:!0,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:1,renderOverride:{en:""}},{role:"responseType",description:"Response format (json, text, html, blob, etc.)",required:!1,expectedTypes:["literal","expression"],svoPosition:2,sovPosition:2,markerOverride:{en:"as"}},{role:"method",description:"HTTP method (GET, POST, etc.)",required:!1,expectedTypes:["literal"],svoPosition:3,sovPosition:3},{role:"destination",description:"Where to store the result",required:!1,expectedTypes:["selector","reference"],svoPosition:4,sovPosition:4}]},Do={action:"increment",description:"Increment a numeric value",category:"variable",primaryRole:"patient",roles:[{role:"patient",description:"The value to increment",required:!0,expectedTypes:["selector","reference","expression"],svoPosition:1,sovPosition:1},{role:"quantity",description:"Amount to increment by (defaults to 1)",required:!1,expectedTypes:["literal"],default:{type:"literal",value:1,dataType:"number"},svoPosition:2,sovPosition:2,markerOverride:{en:"by",es:"por",pt:"por",fr:"par",de:"um"}}]},$o={action:"decrement",description:"Decrement a numeric value",category:"variable",primaryRole:"patient",roles:[{role:"patient",description:"The value to decrement",required:!0,expectedTypes:["selector","reference","expression"],svoPosition:1,sovPosition:1},{role:"quantity",description:"Amount to decrement by (defaults to 1)",required:!1,expectedTypes:["literal"],default:{type:"literal",value:1,dataType:"number"},svoPosition:2,sovPosition:2,markerOverride:{en:"by",es:"por",pt:"por",fr:"par",de:"um"}}]},Wo={action:"append",description:"Append content to an element",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The content to append",required:!0,expectedTypes:["literal","selector","expression"],svoPosition:1,sovPosition:2},{role:"destination",description:"The element to append to",required:!0,expectedTypes:["selector","reference"],svoPosition:2,sovPosition:1,markerOverride:{en:"to"}}]},jo={action:"prepend",description:"Prepend content to an element",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The content to prepend",required:!0,expectedTypes:["literal","selector","expression"],svoPosition:1,sovPosition:2},{role:"destination",description:"The element to prepend to",required:!0,expectedTypes:["selector","reference"],svoPosition:2,sovPosition:1,markerOverride:{en:"to"}}]},qo={action:"log",description:"Log a value to the console",category:"variable",primaryRole:"patient",roles:[{role:"patient",description:"The value to log",required:!0,expectedTypes:["literal","selector","reference","expression"],svoPosition:1,sovPosition:1}]},Ko={action:"get",description:"Get a value from a source",category:"variable",primaryRole:"source",roles:[{role:"source",description:"The source to get from",required:!0,expectedTypes:["selector","reference","expression"],svoPosition:1,sovPosition:2,markerOverride:{en:"",es:"",pt:"",fr:"",de:"",ja:"\u3092",zh:"",ko:"\uB97C",ar:"\u0639\u0644\u0649",tr:"i",id:"",he:"\u05D0\u05EA",sw:"",tl:"",bn:"\u0995\u09C7",qu:"ta"}},{role:"destination",description:"Where to store the result (optional)",required:!1,expectedTypes:["reference"],svoPosition:2,sovPosition:1}]},Fo={action:"take",description:"Take content from a source element",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The class or element to take",required:!0,expectedTypes:["selector"],svoPosition:1,sovPosition:2},{role:"source",description:"The element to take from (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:1}]},Uo={action:"make",description:"Create a new element",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The element type or selector to create",required:!0,expectedTypes:["literal","selector"],svoPosition:1,sovPosition:1}]},Ho={action:"halt",description:"Halt/stop execution or event propagation",category:"control-flow",primaryRole:"patient",roles:[{role:"patient",description:"What to halt (event, default, bubbling, etc.)",required:!1,expectedTypes:["literal","reference","expression"],svoPosition:1,sovPosition:1}]},Go={action:"settle",description:"Wait for animations/transitions to settle",category:"async",primaryRole:"patient",roles:[{role:"patient",description:"The element to settle (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:1,sovPosition:1}]},Yo={action:"throw",description:"Throw an error",category:"control-flow",primaryRole:"patient",roles:[{role:"patient",description:"The error message or object to throw",required:!0,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:1}]},Zo={action:"send",description:"Send an event to an element",category:"event",primaryRole:"event",roles:[{role:"event",description:"The event to send",required:!0,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:2},{role:"destination",description:"The target element (defaults to me)",required:!1,expectedTypes:["selector","reference","expression"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:1,markerOverride:{en:"to",ja:"\u306B",ar:"\u0625\u0644\u0649",es:"a",ko:"\uC5D0\uAC8C",zh:"\u5230",tr:"-e",pt:"para",fr:"\xE0",de:"an",id:"ke",qu:"-man",sw:"kwa"}}]},Jo={action:"if",description:"Conditional execution",category:"control-flow",primaryRole:"condition",hasBody:!0,roles:[{role:"condition",description:"The condition to evaluate",required:!0,expectedTypes:["expression","reference","selector"],svoPosition:1,sovPosition:1}]},Xo={action:"unless",description:"Negated conditional execution (executes when condition is false)",category:"control-flow",primaryRole:"condition",hasBody:!0,roles:[{role:"condition",description:"The condition to evaluate (body executes when false)",required:!0,expectedTypes:["expression","reference","selector"],svoPosition:1,sovPosition:1}]},Qo={action:"else",description:"Else branch of conditional",category:"control-flow",primaryRole:"patient",hasBody:!0,roles:[]},ei={action:"repeat",description:"Repeat a block of commands",category:"control-flow",primaryRole:"loopType",hasBody:!0,roles:[{role:"loopType",description:"Loop variant: forever, times, for, while, until, until-event",required:!0,expectedTypes:["literal"],svoPosition:0,sovPosition:0},{role:"quantity",description:"Number of times to repeat",required:!1,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:1},{role:"event",description:"Event to wait for (terminates loop)",required:!1,expectedTypes:["literal","expression"],svoPosition:2,sovPosition:2},{role:"source",description:"Element to listen for event on",required:!1,expectedTypes:["selector","reference"],svoPosition:3,sovPosition:3}],notes:'Can also use "repeat forever", "repeat until condition", or "repeat until event X from Y"'},ti={action:"for",description:"Iterate over a collection",category:"control-flow",primaryRole:"patient",hasBody:!0,roles:[{role:"patient",description:"The iteration variable",required:!0,expectedTypes:["reference","expression"],svoPosition:1,sovPosition:2},{role:"source",description:"The collection to iterate over",required:!0,expectedTypes:["selector","reference","expression"],svoPosition:2,sovPosition:1,markerOverride:{en:"in",es:"en",fr:"en",de:"in",it:"in",pt:"dentro",id:"dalam",ms:"dalam",pl:"w",ru:"\u0432",uk:"\u0443",sw:"ndani",th:"\u0E43\u0E19",vi:"trong",ar:"\u0641\u064A",tl:"sa_loob",he:"in",zh:"\u5728"}}]},ri={action:"while",description:"Loop while condition is true",category:"control-flow",primaryRole:"condition",hasBody:!0,roles:[{role:"condition",description:"The condition to check",required:!0,expectedTypes:["expression"],svoPosition:1,sovPosition:1}]},ni={action:"continue",description:"Continue to next loop iteration",category:"control-flow",primaryRole:"patient",roles:[]},oi={action:"go",description:"Navigate to a URL",category:"navigation",primaryRole:"destination",roles:[{role:"destination",description:"The URL to navigate to",required:!0,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:1,markerOverride:{en:"to"},renderOverride:{en:""},markerOptional:{en:!0},markerVariants:{he:["\u05D0\u05EA"],zh:["\u628A"]}}]},ii={action:"transition",description:"Transition an element with animation",category:"dom-visibility",primaryRole:"patient",omitRoleVariants:["goal"],roles:[{role:"patient",description:"The property to transition (opacity, *background-color, etc.)",required:!0,expectedTypes:["literal","expression","selector"],svoPosition:1,sovPosition:2,markerOverride:{en:"",ar:"",tl:"",sw:""}},{role:"goal",description:"The target value to transition to",required:!0,expectedTypes:["literal","expression"],svoPosition:2,sovPosition:3,markerOverride:{en:"to",ar:"\u0625\u0644\u0649",tl:"sa",sw:"kwa",bn:"\u09A4\u09C7",qu:"man",es:"a",pt:"para",fr:"\xE0",de:"zu",he:"\u05E2\u05DC",it:"in",ja:"\u306B",ko:"\uC5D0",ms:"ke",pl:"do",ru:"\u0432",th:"\u0E43\u0E19",tr:"e",uk:"\u0432",vi:"v\xE0o",zh:"\u5230",id:"ke"}},{role:"destination",description:"The target element (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:3,sovPosition:1},{role:"duration",description:"Transition duration (over 500ms, for 2 seconds)",required:!1,expectedTypes:["literal"],svoPosition:4,sovPosition:4,markerOverride:{en:"over"}},{role:"style",description:"Easing function (ease-in, linear, etc.)",required:!1,expectedTypes:["literal"],svoPosition:5,sovPosition:5}]},ai={action:"clone",description:"Clone an element",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The element to clone",required:!0,expectedTypes:["selector","reference"],svoPosition:1,sovPosition:2},{role:"destination",description:"Where to put the clone",required:!1,expectedTypes:["selector","reference"],svoPosition:2,sovPosition:1,markerOverride:{en:"into"}}]},si={action:"focus",description:"Focus an element",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The element to focus (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:1,sovPosition:1}]},li={action:"blur",description:"Remove focus from an element",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The element to blur (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:1,sovPosition:1}]},ci={action:"empty",description:"Remove all children from an element (sets innerHTML to empty)",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The element to empty (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:1,sovPosition:1}]},ui={action:"open",description:"Open a dialog, details element, or popover",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The element to open (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:2},{role:"style",description:"Open-mode variant (modal / non-modal) for <dialog>",required:!1,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:1,markerOverride:{en:"as"}}]},di={action:"close",description:"Close a dialog, details element, or popover",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The element to close (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:1,sovPosition:1}]},pi={action:"select",description:"Select the contents of a text field or DOM element",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The element whose contents to select (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:1,sovPosition:1}]},mi={action:"clear",description:"Clear a variable, local, or input element",category:"variable",primaryRole:"patient",roles:[{role:"patient",description:"The variable or element to clear (defaults to me)",required:!1,expectedTypes:["selector","reference","expression"],default:{type:"reference",value:"me"},svoPosition:1,sovPosition:1}]},fi={action:"reset",description:"Reset a <form> element to its default values",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The form element to reset (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:1,sovPosition:1}]},hi={action:"breakpoint",description:"Drop into the debugger",category:"control-flow",primaryRole:"patient",roles:[],bareKeyword:!0},yi={action:"call",description:"Call a function",category:"control-flow",primaryRole:"patient",roles:[{role:"patient",description:"The function to call",required:!0,expectedTypes:["expression","reference"],markerOptional:{he:!0,zh:!0},svoPosition:1,sovPosition:1}]},gi={action:"return",description:"Return a value from a function",category:"control-flow",primaryRole:"patient",roles:[{role:"patient",description:"The value to return",required:!1,expectedTypes:["literal","expression","reference"],svoPosition:1,sovPosition:1}]},vi={action:"js",description:"Execute raw JavaScript code",category:"control-flow",primaryRole:"patient",hasBody:!0,roles:[{role:"patient",description:"The JavaScript code to execute",required:!1,expectedTypes:["expression"],svoPosition:1,sovPosition:1}]},ki={action:"async",description:"Execute commands asynchronously",category:"async",primaryRole:"patient",hasBody:!0,roles:[]},xi={action:"tell",description:"Execute commands in context of another element",category:"control-flow",primaryRole:"destination",hasBody:!0,roles:[{role:"destination",description:"The element to tell",required:!0,expectedTypes:["selector","reference"],svoPosition:1,sovPosition:1,markerOverride:{en:"",he:"\u05D0\u05EA",zh:"\u628A"}}]},Si={action:"default",description:"Set a default value for a variable",category:"variable",primaryRole:"destination",roles:[{role:"destination",description:"The variable to set default for",required:!0,expectedTypes:["selector","reference","expression","property-path"],svoPosition:1,sovPosition:1,markerOverride:{en:"",ar:"",tl:"",sw:"",bn:"\u0995\u09C7",qu:"ta",ja:"\u3092",ko:"\uB97C",tr:"i",hi:"\u0915\u094B",de:"",es:"",fr:"",it:"",pt:"",pl:"",ru:"",uk:"",vi:"",id:"",ms:"",th:"",zh:"\u628A",he:"\u05D0\u05EA"}},{role:"patient",description:"The default value",required:!0,expectedTypes:["literal","expression"],svoPosition:2,sovPosition:2,markerOverride:{en:"to",ar:"\u0625\u0644\u0649",tl:"sa",sw:"kwa",bn:"\u09A4\u09C7",qu:"man",ja:"\u306B",ko:"\uC5D0",tr:"e",hi:"\u092E\u0947\u0902",de:"zu",es:"a",fr:"\xE0",it:"in",pt:"para",pl:"do",ru:"\u0432",uk:"\u0432",vi:"v\xE0o",id:"ke",ms:"ke",th:"\u0E43\u0E19",zh:"\u5230",he:"\u05E2\u05DC"}}]},bi={action:"init",description:"Initialization block that runs once",category:"control-flow",primaryRole:"patient",hasBody:!0,roles:[]},wi={action:"behavior",description:"Define a reusable behavior",category:"control-flow",primaryRole:"patient",hasBody:!0,roles:[{role:"patient",description:"The behavior name (PascalCase identifier)",required:!0,expectedTypes:["literal","reference","expression"],svoPosition:1,sovPosition:1}]},Ei={action:"install",description:"Install a behavior on an element",category:"control-flow",primaryRole:"patient",roles:[{role:"patient",description:"The behavior name to install",required:!0,expectedTypes:["literal","reference","expression"],svoPosition:1,sovPosition:2},{role:"destination",description:"Element to install on (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:1}]},Ti={action:"measure",description:"Measure element dimensions (x, y, width, height, etc.)",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"Property to measure (x, y, width, height, top, left, etc.)",required:!1,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:1},{role:"source",description:"Element to measure (defaults to me)",required:!1,expectedTypes:["selector","reference"],default:{type:"reference",value:"me"},svoPosition:2,sovPosition:2,markerOverride:{en:"of"}}]},Ci={action:"swap",description:"Swap DOM content using various strategies (innerHTML, outerHTML, delete, etc.)",category:"dom-content",primaryRole:"destination",roles:[{role:"method",description:"The swap strategy (innerHTML, outerHTML, beforebegin, afterend, delete)",required:!1,expectedTypes:["literal"],svoPosition:1,sovPosition:3,markerOverride:{en:""}},{role:"destination",description:"The element to swap content in/for",required:!0,expectedTypes:["selector","reference"],svoPosition:2,sovPosition:1,markerOverride:{en:"of",es:"",fr:"",pt:"",it:"",de:"",pl:"",ru:"",uk:"",id:"",ms:"",sw:"",th:"",vi:"",he:"\u05D0\u05EA",zh:"\u628A"}},{role:"patient",description:"The content to swap in (optional for delete)",required:!1,expectedTypes:["literal","expression","selector"],svoPosition:3,sovPosition:2,markerOverride:{en:"with",es:"con",fr:"avec",pt:"com",it:"con",de:"mit",pl:"z",ru:"\u0441",uk:"\u0437",id:"dengan",ms:"dengan",sw:"na",th:"\u0E14\u0E49\u0E27\u0E22",vi:"v\u1EDBi",he:"\u05E2\u05DD",zh:"\u7528"}}]},Pi={action:"morph",description:"Morph an element into another using DOM diffing",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The element to morph",required:!0,expectedTypes:["selector","reference"],svoPosition:1,sovPosition:1,markerOverride:{en:""}},{role:"destination",description:"The target content/element to morph into",required:!0,expectedTypes:["literal","expression","selector","reference"],svoPosition:2,sovPosition:2,markerOverride:{en:"to"}}]},Ni={action:"beep",description:"Debug output for expressions with type information",category:"variable",primaryRole:"patient",roles:[{role:"patient",description:"The expression(s) to debug",required:!1,expectedTypes:["literal","selector","reference","expression"],svoPosition:1,sovPosition:1}]},Ri={action:"break",description:"Exit from the current loop",category:"control-flow",primaryRole:"patient",roles:[]},Li={action:"copy",description:"Copy text or element content to the clipboard",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The text or element to copy",required:!0,expectedTypes:["literal","selector","reference","expression"],svoPosition:1,sovPosition:1}]},Ai={action:"exit",description:"Exit from the current event handler",category:"control-flow",primaryRole:"patient",roles:[],bareKeyword:!0},Mi={action:"pick",description:"Select a random element from a collection",category:"variable",primaryRole:"patient",roles:[{role:"patient",description:"The items to pick from",required:!0,expectedTypes:["literal","expression","reference"],svoPosition:1,sovPosition:1},{role:"source",description:'The array to pick from (with "from" keyword)',required:!1,expectedTypes:["reference","expression"],svoPosition:2,sovPosition:2}]},Oi={action:"scroll",description:"Scroll the viewport to a target element",category:"navigation",primaryRole:"destination",argSkipTokens:["of","the","top","bottom","middle","center","nearest","left","right","smoothly","instantly"],roles:[{role:"destination",description:"The element to scroll to",required:!0,expectedTypes:["selector","reference","expression"],svoPosition:1,sovPosition:1,markerOverride:{en:"to"}}]},Sr={en:"url",es:"url",pt:"url",fr:"url",de:"url",it:"url",ja:"url",ko:"url",zh:"url",ar:"url",he:"url",hi:"url",bn:"url",tr:"url",ru:"url",uk:"url",pl:"url",id:"url",vi:"url",th:"url",ms:"url",tl:"url",sw:"url",qu:"url"},zi={en:"partials in",es:"partials in",pt:"partials in",fr:"partials in",de:"partials in",it:"partials in",ja:"partials in",ko:"partials in",zh:"partials in",ar:"partials in",he:"partials in",hi:"partials in",bn:"partials in",tr:"partials in",ru:"partials in",uk:"partials in",pl:"partials in",id:"partials in",vi:"partials in",th:"partials in",ms:"partials in",tl:"partials in",sw:"partials in",qu:"partials in"},Ii={action:"push",description:"Push a URL onto the browser history",category:"navigation",primaryRole:"patient",roles:[{role:"patient",description:"The URL to push (after the `url` keyword)",required:!0,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:1,markerOverride:Sr}]},Vi={action:"replace",description:"Replace the current browser history entry with a URL",category:"navigation",primaryRole:"patient",roles:[{role:"patient",description:"The URL to replace with (after the `url` keyword)",required:!0,expectedTypes:["literal","expression"],svoPosition:1,sovPosition:1,markerOverride:Sr}]},_i={action:"process",description:"Process hx-partial markup in HTML content",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The HTML content (string, element, or response) to process",required:!0,expectedTypes:["literal","reference","expression"],svoPosition:1,sovPosition:1,markerOverride:zi}]},Bi={action:"render",description:"Render a template with optional variables",category:"dom-content",primaryRole:"patient",roles:[{role:"patient",description:"The template to render",required:!0,expectedTypes:["selector","reference","expression"],svoPosition:1,sovPosition:2},{role:"style",description:"Variables to pass to the template (with keyword)",required:!1,expectedTypes:["expression","reference"],svoPosition:2,sovPosition:1}]},Ne={toggle:bo,add:wo,remove:Eo,put:To,set:Co,show:Oo,hide:zo,on:Io,trigger:Vo,wait:_o,fetch:Bo,increment:Do,decrement:$o,append:Wo,prepend:jo,log:qo,get:Ko,take:Fo,make:Uo,halt:Ho,settle:Go,throw:Yo,send:Zo,if:Jo,unless:Xo,else:Qo,repeat:ei,for:ti,while:ri,continue:ni,go:oi,scroll:Oi,push:Ii,replace:Vi,process:_i,transition:ii,clone:ai,focus:si,blur:li,empty:ci,open:ui,close:di,select:pi,clear:mi,reset:fi,breakpoint:hi,call:yi,return:gi,js:vi,async:ki,tell:xi,default:Si,init:bi,behavior:wi,install:Ei,measure:Ti,swap:Ci,morph:Pi,beep:Ni,break:Ri,copy:Li,exit:Ai,pick:Mi,render:Bi,bind:Po,live:No,eventsource:Ro,socket:Lo,worker:Ao,intercept:Mo,compound:{action:"compound",description:"A compound node representing chained statements",primaryRole:"patient",category:"control-flow",hasBody:!0,roles:[]}};function ne(o){return Ne[o]}function de(o,e){let t=o.possessive?.keywords?.[e];if(t)return t;let r=o.possessive?.specialForms;if(r){for(let[n,i]of Object.entries(r))if(i===e)return n}}var br=[{lang:"es",verb:"poner",verbAlts:["pon","colocar","put"],at:"en",end:"fin",of:"de"},{lang:"fr",verb:"mettre",at:"\xE0",end:"fin",of:"de"},{lang:"pt",verb:"colocar",at:"em",end:"fim",of:"de"},{lang:"it",verb:"mettere",at:"a",end:"fine",of:"di"},{lang:"de",verb:"setzen",at:"bei",end:"ende",of:"von"},{lang:"sw",verb:"weka",at:"katika",end:"mwisho",of:"ya"},{lang:"id",verb:"taruh",verbAlts:["letakkan","masukkan","tempatkan"],at:"di",end:"akhir",of:"dari"},{lang:"ms",verb:"letak",at:"di",end:"tamat",of:"daripada"},{lang:"vi",verb:"\u0111\u1EB7t",at:"t\u1EA1i",end:"k\u1EBFt th\xFAc",of:"c\u1EE7a"},{lang:"pl",verb:"umie\u015B\u0107",at:"przy",end:"koniec",of:"z"},{lang:"ru",verb:"\u043F\u043E\u043B\u043E\u0436\u0438\u0442\u044C",at:"\u0443",end:"\u043A\u043E\u043D\u0435\u0446",of:"\u0438\u0437"},{lang:"uk",verb:"\u043F\u043E\u043A\u043B\u0430\u0441\u0442\u0438",at:"\u0432",end:"\u043A\u0456\u043D\u0435\u0446\u044C",of:"\u0437"},{lang:"th",verb:"\u0E43\u0E2A\u0E48",at:"\u0E17\u0E35\u0E48",end:"\u0E08\u0E1A",of:"\u0E02\u0E2D\u0E07"},{lang:"tl",verb:"ilagay",at:"sa",end:"wakas",of:"ng"},{lang:"ar",verb:"\u0636\u0639",at:"\u0639\u0646\u062F",end:"\u0627\u0644\u0646\u0647\u0627\u064A\u0629",of:"\u0645\u0646"},{lang:"zh",verb:"\u653E\u7F6E",verbAlts:["\u653E","\u653E\u5165"],patientPrefix:"\u628A",at:"\u5728",end:"\u7ED3\u675F",of:"\u7684"},{lang:"he",verb:"\u05E9\u05D9\u05DD",patientPrefix:"\u05D0\u05EA",at:"at",end:"\u05E1\u05D5\u05E3",of:"of"},{lang:"tr",verb:"koy",sov:!0,objMarker:"i",at:"de",end:"son",of:"nin"},{lang:"ja",verb:"\u7F6E\u304F",sov:!0,objMarker:"\u3092",at:"\u3067",end:"\u7D42\u308F\u308A",of:"\u306E"},{lang:"ko",verb:"\uB123\uB2E4",sov:!0,objMarker:"\uB97C",at:"\uC5D0",end:"\uB05D",of:"\uC758"},{lang:"hi",verb:"\u0930\u0916\u0947\u0902",verbAlts:["\u0930\u0916","\u0921\u093E\u0932\u0947\u0902","\u0921\u093E\u0932"],sov:!0,objMarker:"\u0915\u094B",at:"\u092A\u0930",end:"\u0938\u092E\u093E\u092A\u094D\u0924",of:"\u0915\u093E"},{lang:"bn",verb:"\u09B0\u09BE\u0996\u09C1\u09A8",verbAlts:["\u09B0\u09BE\u0996"],sov:!0,objMarker:"\u0995\u09C7",at:"\u098F",end:"\u09B6\u09C7\u09B7",of:"\u09B0"},{lang:"qu",verb:"churay",sov:!0,objMarker:"ta",at:"pi",end:"tukuy",of:"pa"}];function Vt(o,e,t,r){let n=br.find(s=>s.lang===o);if(!n)return!1;let i=(s,a)=>(s??"").toLowerCase()===a.toLowerCase();return i(e,n.end)&&i(t,n.at)&&i(r,n.of)}function wr(o,e){let t=br.find(n=>n.lang===o);if(!t)return!1;let r=e.toLowerCase();return r===t.at.toLowerCase()||r===t.of.toLowerCase()||r===t.end.toLowerCase()}var Er=new Set(["\u0628\u062F\u0644","\u063A\u064A\u0631","\u0623\u0636\u0641","\u0623\u0632\u0644","\u0636\u0639","\u0627\u062C\u0639\u0644","\u0639\u064A\u0646","\u0632\u062F","\u0627\u0646\u0642\u0635","\u0633\u062C\u0644","\u0623\u0638\u0647\u0631","\u0623\u062E\u0641","\u0634\u063A\u0644","\u0623\u0631\u0633\u0644","\u0631\u0643\u0632","\u0634\u0648\u0634","\u062A\u0648\u0642\u0641","\u0627\u0646\u0633\u062E","\u0627\u062D\u0630\u0641","\u0627\u0635\u0646\u0639","\u0627\u0646\u062A\u0638\u0631","\u0627\u0646\u062A\u0642\u0627\u0644","\u0623\u0648"]),Di={patient:["\u0639\u0644\u0649"],destination:["\u0625\u0644\u0649","\u0627\u0644\u0649"],source:["\u0645\u0646"],agent:["\u0645\u0646"],manner:["\u0628"],style:["\u0628"],goal:["\u0625\u0644\u0649","\u0627\u0644\u0649"],method:["\u0628"]},_t=class{calculate(e){return this.calculateWithBreakdown(e).final}calculateWithBreakdown(e){let t=this.scoreRoleCoverage(e),r=this.scoreStemPenalty(e),n=this.scoreLanguageBoost(e),i=this.scoreLanguageAdjustment(e),s=t;return s=Math.max(.5,s+r),s=Math.min(1,s+n),s=Math.max(0,Math.min(1,s+i)),{roleCoverage:t,stemPenalty:r,languageBoost:n,languageAdjustment:i,final:s}}scoreRoleCoverage(e){let{pattern:t,captured:r}=e,n=0,i=0,s=a=>t.extraction?.[a]?.default!==void 0;for(let a of t.template.tokens)if(a.type==="role")i+=1,r.has(a.role)&&(n+=1);else if(a.type==="group")for(let l of a.tokens)l.type==="role"&&(i+=.8,r.has(l.role)?n+=.8:s(l.role)&&(n+=.8*.6));return i>0?n/i:1}scoreStemPenalty(e){let{stemMatchCount:t,totalKeywordMatches:r}=e;return t<=0||r<=0?0:-(t/r)*.15}scoreLanguageBoost(e){let{pattern:t}=e;if(t.language!=="ar")return 0;let r=t.template.tokens[0];return!r||r.type!=="literal"?0:Er.has(r.value)||r.alternatives?.some(n=>Er.has(n))?.15:0}scoreLanguageAdjustment(e){let{pattern:t,captured:r}=e;if(t.language!=="ar")return 0;let n=0;for(let[i,s]of r.entries()){let a=Di[i];if(!a||a.length===0)continue;let l="metadata"in s?s.metadata:void 0;l&&typeof l.prepositionValue=="string"&&(a.includes(l.prepositionValue)?n+=.1:n-=.1)}return Math.max(-.1,Math.min(.1,n))}},Tr=new _t;var $i=new Set(Object.values(Ne).filter(o=>o.bareKeyword===!0).map(o=>o.action)),A=class A{constructor(e){this.matchCache=new Map;this.stemMatchCount=0;this.totalKeywordMatches=0;this.confidenceModel=e??Tr}matchPattern(e,t){let r=e.mark(),n=new Map;if(this.currentProfile=I(t.language),this.currentPatternCommand=t.command,this.stemMatchCount=0,this.totalKeywordMatches=0,!this.matchTokenSequence(e,t.template.tokens,n))return e.reset(r),null;let s=this.confidenceModel.calculate({pattern:t,captured:n,stemMatchCount:this.stemMatchCount,totalKeywordMatches:this.totalKeywordMatches});return this.applyExtractionRules(t,n),{pattern:t,captured:n,consumedTokens:e.position()-r.position,confidence:s}}matchBest(e,t){this.matchCache.clear();let r=[],n=e.position();for(let s of t){let a=e.mark(),l=`${n}:${s.id}`,c;this.matchCache.has(l)?c=this.matchCache.get(l):(c=this.matchPattern(e,s),this.matchCache.set(l,c)),c&&r.push(c),e.reset(a)}if(r.length===0)return null;r.sort((s,a)=>{let l=a.pattern.priority-s.pattern.priority;return l!==0?l:a.confidence-s.confidence});let i=r[0];return this.matchPattern(e,i.pattern),i}matchTokenSequence(e,t,r,n){let i=t[0],s=i?.type==="literal"&&(i.value==="and"||i.value==="then"||i.alternatives?.includes("and")||i.alternatives?.includes("then"));if(this.currentProfile?.code==="ar"&&!s)for(;e.peek()?.kind==="conjunction";)e.advance();let a=0;for(let l=0;l<t.length;l++){let c=t[l];a>0&&c.type==="literal"&&this.tryConsumeEventSourceClause(e,r,c);let d=this.matchPatternToken(e,c,r,t[l+1]??n);if(a=c.type==="role"&&c.role==="event"?2:Math.max(0,a-1),!d){if(this.isOptional(c))continue;return!1}}return!0}tryConsumeEventSourceClause(e,t,r){if(t.has("source"))return;let n=e.peek(),i=e.peek(1);if(!n||!i||this.patternTokenWouldMatch(r,n))return;let s=this.currentProfile?.roleMarkers?.source,a=c=>{if(c.kind!=="particle"&&c.kind!=="keyword")return!1;if((c.normalized??"").toLowerCase()==="source")return!0;if(!s)return!1;let d=c.value.toLowerCase();return s.primary?.toLowerCase()===d?!0:!!s.alternatives?.some(u=>u.toLowerCase()===d)},l=s?.position;if(l!=="after"&&a(n)&&i.kind==="selector"){e.advance();let c=this.tokenToSemanticValue(e.advance());c&&t.set("source",c);return}if(l==="after"&&n.kind==="selector"&&a(i)){let c=this.tokenToSemanticValue(n);e.advance(),e.advance(),c&&t.set("source",c)}}matchPatternToken(e,t,r,n){switch(t.type){case"literal":return this.matchLiteralToken(e,t);case"role":return this.matchRoleToken(e,t,r,n);case"group":return this.matchGroupToken(e,t,r,n);default:return!1}}matchLiteralToken(e,t){let r=e.peek();if(!r)return!1;let n=this.getMatchType(r,t.value);if(n!=="none")return this.totalKeywordMatches++,n==="stem"&&this.stemMatchCount++,e.advance(),!0;if(t.alternatives)for(let i of t.alternatives){let s=this.getMatchType(r,i);if(s!=="none")return this.totalKeywordMatches++,s==="stem"&&this.stemMatchCount++,e.advance(),!0}for(let i of[t.value,...t.alternatives??[]])for(let s of["-","_"])if(i.includes(s)&&this.tryMatchShatteredCompound(e,i,s))return this.totalKeywordMatches++,!0;return!1}tryFoldHyphenActionKeyword(e){let t=this.currentProfile;if(!t)return null;let r=e.mark(),n=[];for(;;){let s=e.peek();if(!s||s.kind!=="identifier"&&s.kind!=="keyword")break;n.push(s.value),e.advance();let a=e.peek();if(!a||a.value!=="-")break;e.advance(),n.push("-")}if(n.length<3||n[n.length-1]==="-")return e.reset(r),null;let i=n.join("").toLowerCase();for(let[s,a]of Object.entries(t.keywords))if(a.primary.toLowerCase()===i||a.alternatives?.some(l=>l.toLowerCase()===i))return $(s);return e.reset(r),null}tryMatchShatteredCompound(e,t,r){let n=t.split(r);if(n.length<2||n.some(s=>s.length===0))return!1;let i=e.mark();for(let s=0;s<n.length;s++){if(s>0){let l=e.peek();if(!l||l.value!==r)return e.reset(i),!1;e.advance()}let a=e.peek();if(!a||a.kind!=="identifier"&&a.kind!=="keyword"&&a.kind!=="particle"||a.value.toLowerCase()!==n[s].toLowerCase())return e.reset(i),!1;e.advance()}return!0}matchRoleToken(e,t,r,n){this.skipNoiseWords(e);let i=e.peek();if(!i)return t.optional||!1;if(t.role==="action"&&this.currentProfile&&e.peek(1)?.value==="-"){let g=this.tryFoldHyphenActionKeyword(e);if(g)return r.set(t.role,g),!0}if(t.role==="event"&&this.currentPatternCommand==="on"){if(!A.tokenLooksLikeEvent(i))return t.optional||!1;let g=(i.normalized??i.value).toLowerCase();if(A.POSITIONAL_OR_SCOPE_KEYWORDS.has(g)||this.currentProfile&&(de(this.currentProfile,i.value)??de(this.currentProfile,g))!==void 0||i.value.includes("?."))return t.optional||!1}if(t.role==="event"){let g=(i.normalized??i.value).toLowerCase();if(A.STRUCTURAL_NEVER_EVENT.has(g))return t.optional||!1}if(t.role==="duration"){let g=(i.normalized??i.value).toLowerCase();if(A.POSITIONAL_OR_SCOPE_KEYWORDS.has(g))return t.optional||!1}if(t.optional&&n===void 0&&t.role!=="event"&&t.role!=="action"&&i.kind==="keyword"&&(i.normalized??i.value).toLowerCase()in Ne)return!0;let s=this.tryMatchPositionalExpression(e);if(s)return t.expectedTypes&&t.expectedTypes.length>0&&!$e(s.type,t.expectedTypes)?t.optional||!1:(r.set(t.role,s),!0);let a=this.tryMatchCaretScopeExpression(e);if(a)return t.expectedTypes&&t.expectedTypes.length>0&&!$e(a.type,t.expectedTypes)?t.optional||!1:(r.set(t.role,a),!0);if(t.role!=="event"&&(!t.expectedTypes||t.expectedTypes.includes("expression"))){let g=this.tryMatchOperatorRunExpression(e);if(g)return r.set(t.role,g),!0}if(t.expectedTypes?.includes("property-path")){let g=this.tryMatchOfPossessiveExpression(e);if(g)return r.set(t.role,g),!0;let S=this.tryMatchPostNominalPossessiveExpression(e);if(S)return r.set(t.role,S),!0}let l=this.tryMatchPossessiveExpression(e);if(l)return t.expectedTypes&&t.expectedTypes.length>0&&!t.expectedTypes.includes(l.type)&&!t.expectedTypes.includes("expression")?t.optional||!1:(r.set(t.role,l),!0);let c=this.tryMatchMethodCallExpression(e);if(c)return t.expectedTypes&&t.expectedTypes.length>0&&!t.expectedTypes.includes(c.type)&&!t.expectedTypes.includes("expression")?t.optional||!1:(r.set(t.role,c),!0);let u=t.role==="event"&&this.currentPatternCommand==="on"||A.DECLARATION_COMMANDS.has(this.currentPatternCommand??"")?null:this.tryMatchBareCallExpression(e);if(u)return t.expectedTypes&&t.expectedTypes.length>0&&!t.expectedTypes.includes(u.type)&&!t.expectedTypes.includes("expression")?t.optional||!1:(r.set(t.role,u),!0);let f=this.tryMatchPossessiveSelectorExpression(e);if(f)return t.expectedTypes&&t.expectedTypes.length>0&&!$e(f.type,t.expectedTypes)?t.optional||!1:(r.set(t.role,f),!0);let m=t.role!=="condition",p=this.tryMatchPropertyAccessExpression(e,m);if(p)return t.expectedTypes&&t.expectedTypes.length>0&&!t.expectedTypes.includes(p.type)&&!t.expectedTypes.includes("expression")?t.optional||!1:(r.set(t.role,p),!0);let h=this.tryMatchSelectorPropertyExpression(e);if(h)return t.expectedTypes&&t.expectedTypes.length>0&&!$e(h.type,t.expectedTypes)?t.optional||!1:(r.set(t.role,h),!0);if(i.kind==="identifier"&&i.value==="{"&&(!t.expectedTypes?.length||t.expectedTypes.includes("literal"))){let g=this.tryMatchBraceRunLiteral(e);if(g)return r.set(t.role,g),!0}let y=this.tokenToSemanticValue(i);if(!y)return t.optional||!1;if(t.expectedTypes&&t.expectedTypes.length>0&&!t.expectedTypes.includes(y.type)){let g=y.type==="selector"&&String(y.value).startsWith("@"),S=t.expectedTypes.some(E=>E==="expression"||E==="reference");if(!(g&&S))return t.optional||!1}if(r.set(t.role,y),e.advance(),t.role==="event"){let g=e.peek();g&&g.kind==="selector"&&g.value.startsWith("[")&&"value"in y&&(r.set(t.role,$(`${String(y.value)}${g.value}`)),e.advance());let S=e.peek();if(S&&(S.kind==="particle"||S.kind==="keyword")&&(S.normalized??"").toLowerCase()==="source"&&!this.patternTokenWouldMatch(n,S)){let E=e.peek(1);if(E&&(E.kind==="selector"||E.kind==="identifier")){e.advance();let C=this.tokenToSemanticValue(e.advance());C&&!r.has("source")&&r.set("source",C)}}}return!0}patternTokenWouldMatch(e,t){return e?e.type==="literal"?this.getMatchType(t,e.value)!=="none"?!0:!!e.alternatives?.some(r=>this.getMatchType(t,r)!=="none"):e.type==="group"?this.patternTokenWouldMatch(e.tokens?.[0],t):!1:!1}tryMatchPositionalExpression(e){let t=e.peek();if(!t)return null;let r=(t.normalized??t.value).toLowerCase();if(!A.POSITIONAL_KEYWORDS.has(r)&&!A.POSITIONAL_KEYWORDS.has(t.value.toLowerCase()))return null;let n=e.mark(),i=[t.normalized??t.value];e.advance();let s=e.peek();if(!s||s.kind!=="selector")return e.reset(n),null;i.push(s.value),e.advance();let a=0;for(;a++<8;){let d=e.peek();if(d&&d.kind==="selector"&&d.value.startsWith("."))i.push(d.value),e.advance();else break}let l=e.peek(),c=e.peek(1);return l&&c&&c.kind==="selector"&&(l.kind==="keyword"||l.kind==="particle"||l.kind==="identifier")&&!A.POSITIONAL_KEYWORDS.has((l.normalized??l.value).toLowerCase())&&!A.COMMAND_ACTION_KEYWORDS.has((l.normalized??l.value).toLowerCase())&&(i.push(l.normalized??l.value,c.value),e.advance(),e.advance()),{type:"expression",raw:i.join(" ")}}tryMatchCaretScopeExpression(e){let t=e.peek();if(!t||t.kind!=="identifier"||!t.value.startsWith("^"))return null;let r=e.peek(1),n=e.peek(2),i=(r?.normalized??"").toLowerCase(),s=!!r&&(r.value.toLowerCase()==="on"||i==="destination"||i==="on");return!r||!n||n.kind!=="selector"||!s?null:(e.advance(),e.advance(),e.advance(),{type:"expression",raw:`${t.value} on ${n.value}`})}isOfPossessiveMarker(e){let t=e.value.toLowerCase(),r=(e.normalized??"").toLowerCase();if(t==="of"||t==="ng"||r==="of"||r==="source")return!0;let n=this.currentProfile?.code?A.OF_POSSESSIVE_MARKERS[this.currentProfile.code]:void 0;return!!n&&n.has(t)}tryMatchOperatorRunExpression(e){let t=e.mark(),r=e.position();if(!this.tryConsumeRunOperand(e))return e.reset(t),null;let n=1;for(;;){let s=e.peek();if(!s||!A.RUN_OPERATORS.has(s.value))break;let a=e.mark();if(e.advance(),!this.tryConsumeRunOperand(e)){e.reset(a);break}n++}if(n<2)return e.reset(t),null;let i=e.tokens.slice(r,e.position()).map(s=>s.value).join(" ");return{type:"expression",raw:i,value:i}}tryConsumeRunOperand(e){let t=e.peek();if(!t)return!1;if(t.value==="("){let r=e.mark(),n=0;for(;!e.isAtEnd();){let i=e.advance();if(i.value==="(")n++;else if(i.value===")"&&(n--,n===0))return!0}return e.reset(r),!1}return this.tryMatchPossessiveExpression(e)?!0:(t.kind==="literal"||t.kind==="identifier"||t.kind==="selector"||t.kind==="keyword")&&!A.RUN_OPERATORS.has(t.value)&&t.value!==")"?(e.advance(),!0):!1}tryMatchOfPossessiveExpression(e){let t=e.peek();if(!t||t.kind!=="selector")return null;let r=e.mark();e.advance();let n=e.peek();if(!n||!this.isOfPossessiveMarker(n))return e.reset(r),null;e.advance();let i=e.peek();return!i||i.kind!=="selector"?(e.reset(r),null):(e.advance(),se(re(i.value),t.value))}tryMatchPossessiveExpression(e){let t=e.peek();if(!t||!this.currentProfile)return null;let r=[t.value,t.normalized].filter(Boolean),n;for(let l of r)if(n=de(this.currentProfile,l)??de(this.currentProfile,l.toLowerCase()),n)break;if(!n)return null;let i=e.mark();e.advance();let s=this.currentProfile.possessive?.connectors;if(s&&s.length>0){let l=e.peek();if(l){let c=l.value.toLowerCase(),d=(l.normalized??"").toLowerCase();s.some(u=>u.toLowerCase()===c||u.toLowerCase()===d)&&e.advance()}}let a=e.peek();if(!a||wr(this.currentProfile.code,a.value))return e.reset(i),null;if(a.kind==="identifier"||a.kind==="keyword"&&!this.isStructuralKeyword(a.value)&&!(a.normalized&&this.isStructuralKeyword(a.normalized))&&!(a.normalized&&this.isRoleMarkerConcept(a.normalized))||a.kind==="selector"&&a.value.startsWith("*")||a.kind==="selector"&&a.value.startsWith("@")||a.kind==="selector"&&a.value.startsWith(".")&&/^\.[a-zA-Z_]\w*/.test(a.value)){e.advance();let l=a.value;a.kind==="selector"&&l.startsWith(".")&&/^\.[a-zA-Z_]\w*/.test(l)&&(l=l.substring(1));let c=l;for(;e.peek()?.kind==="selector"&&e.peek().value.startsWith(".")&&/^\.[a-zA-Z_]\w*/.test(e.peek().value);)c+=e.peek().value,e.advance();let d=e.peek();if(d&&d.value.startsWith("(")){let u="",f=0,m=0;for(;!e.isAtEnd()&&m++<A.MAX_METHOD_ARGS+2;){let p=e.peek();if(!p)break;u+=p.value,e.advance();for(let h of p.value)h==="("?f++:h===")"&&f--;if(f<=0)break}c+=u}return se(J(n),c)}return e.reset(i),null}tryMatchPostNominalPossessiveExpression(e){if(!this.currentProfile||this.currentProfile.possessive?.markerPosition!=="after-object")return null;let t=u=>{for(let f of[u.value,u.normalized].filter(Boolean))if(de(this.currentProfile,f)??de(this.currentProfile,f.toLowerCase()))return!0;return!1},r=e.peek();if(!r)return null;let n=r.kind==="selector"&&r.value.startsWith(".")&&/^\.[a-zA-Z_]\w*/.test(r.value);if(!(r.kind==="identifier"&&!this.isStructuralKeyword(r.value)&&!(r.normalized&&this.isStructuralKeyword(r.normalized))&&!(r.normalized&&this.isRoleMarkerConcept(r.normalized))||r.kind==="selector"&&(r.value.startsWith("*")||r.value.startsWith("@"))||n)||t(r))return null;let s=e.mark(),a=r.value;n&&(a=a.substring(1)),e.advance();let l=a;for(;e.peek()?.kind==="selector"&&e.peek().value.startsWith(".")&&/^\.[a-zA-Z_]\w*/.test(e.peek().value);)l+=e.peek().value,e.advance();let c=e.peek();if(!c)return e.reset(s),null;let d;for(let u of[c.value,c.normalized].filter(Boolean))if(d=de(this.currentProfile,u)??de(this.currentProfile,u.toLowerCase()),d)break;return d?(e.advance(),se(J(d),l)):(e.reset(s),null)}isStructuralKeyword(e){return new Set(["into","in","to","from","at","by","with","without","before","after","of","as","on","then","end","else","if","repeat","while","for","toggle","add","remove","put","set","show","hide","increment","decrement","send","trigger","call"]).has(e.toLowerCase())}isRoleMarkerConcept(e){return new Set(["destination","source","patient","object","event","eventmarker","manner","instrument"]).has(e.toLowerCase())}static tokenLooksLikeEvent(e){if(e.kind==="selector"||e.kind==="url"||e.kind==="literal")return!1;let t=e.value;if(/[/#@*]/.test(t)||t.startsWith('"')||t.startsWith("'")||t.startsWith("`"))return!1;let r=e.normalized?.toLowerCase();return!(r&&$i.has(r))}tryMatchBraceRunLiteral(e){let t=e.peek();if(!t||t.kind!=="identifier"||t.value!=="{")return null;let r=e.mark();e.advance();let n=["{"],i=1,s=0;for(;!e.isAtEnd()&&s++<A.MAX_BRACE_RUN_TOKENS;){let a=e.advance();if(!a)break;if(a.value==="{")i++;else if(a.value==="}"&&(i--,i===0))return n.push("}"),$(n.join(" "));n.push(a.value)}return e.reset(r),null}tryMatchBareCallExpression(e){let t=e.peek();if(!t||t.kind!=="identifier"||!/^[A-Za-z_][\w$]*$/.test(t.value))return null;let r=e.peek(1);if(!r||r.value!=="(")return null;let n=e.mark();e.advance(),e.advance();let i=[],s=!1,a=0;for(;!e.isAtEnd()&&a++<A.MAX_METHOD_ARGS+2;){let l=e.peek();if(!l)break;if(l.value===")"){e.advance(),s=!0;break}if(l.value===","){e.advance();continue}i.push(l.value),e.advance()}return s?{type:"expression",raw:`${t.value}(${i.join(", ")})`}:(e.reset(n),null)}tryMatchMethodCallExpression(e){let t=e.peek();if(!t||t.kind!=="selector")return null;let r=e.mark();e.advance();let n=e.peek();if(!n||n.kind!=="operator"||n.value!==".")return e.reset(r),null;e.advance();let i=e.peek();if(!i||i.kind!=="identifier")return e.reset(r),null;e.advance();let s=e.peek();if(!s||s.kind!=="punctuation"||s.value!=="(")return e.reset(r),null;e.advance();let a=[];for(;!e.isAtEnd()&&a.length<A.MAX_METHOD_ARGS;){let c=e.peek();if(!c)break;if(c.kind==="punctuation"&&c.value===")"){e.advance();break}if(c.kind==="punctuation"&&c.value===","){e.advance();continue}a.push(c.value),e.advance()}return{type:"expression",raw:`${t.value}.${i.value}(${a.join(", ")})`}}tryMatchPropertyAccessExpression(e,t=!0){let r=e.peek();if(!r||r.kind!=="identifier"&&r.kind!=="keyword")return null;let n=e.mark();e.advance();let i=r.value.toLowerCase(),s=e.peek();if((r.kind==="identifier"||A.PROPERTY_ACCESS_BASES.has(i))&&s&&s.kind==="selector"&&/^\.[a-zA-Z_]/.test(s.value)){let m=r.value,p=[],h=0;for(;h<A.MAX_PROPERTY_DEPTH;){let S=e.peek();if(S&&S.kind==="selector"&&/^\.[a-zA-Z_]/.test(S.value))m+=`.${S.value.slice(1)}`,p.push(S.value.slice(1)),e.advance(),h++;else break}let y=e.peek(),g=!!y&&y.value.startsWith("(");if(t&&!g&&p.length>0&&xe(i))return se(J(i),p.join("."));if(g){let S=e.mark(),E=[],C=0,x=!1;for(;!e.isAtEnd();){let k=e.peek();if(!k)break;if(k.value==="(")C++;else if(k.value===")"){if(E.push(k.value),e.advance(),C--,C===0&&(x=!0),x)break;continue}E.push(k.value),e.advance()}x?m+=E.join(""):e.reset(S)}return{type:"expression",raw:m}}let a=e.peek();if(!a||a.kind!=="operator"||a.value!==".")return e.reset(n),null;e.advance();let l=e.peek();if(!l||l.kind!=="identifier")return e.reset(n),null;e.advance();let c=`${r.value}.${l.value}`,d=1;for(;!e.isAtEnd()&&d<A.MAX_PROPERTY_DEPTH;){let m=e.peek();if(!m||m.kind!=="operator"||m.value!==".")break;e.advance();let p=e.peek();if(!p||p.kind!=="identifier")break;e.advance(),c+=`.${p.value}`,d++}let u=e.peek();if(u&&u.kind==="punctuation"&&u.value==="("){e.advance();let m=[],p=0;for(;!e.isAtEnd()&&m.length<A.MAX_METHOD_ARGS;){let y=e.peek();if(!y)break;if(y.kind==="punctuation"&&y.value===")"){if(p===0){e.advance();break}p--}if(y.kind==="punctuation"&&y.value==="("&&p++,y.kind==="punctuation"&&y.value===","){e.advance();continue}m.push(y.value),e.advance()}return{type:"expression",raw:`${c}(${m.join(", ")})`}}let f=r.value.toLowerCase();if(t&&xe(f)){let m=c.split(".").slice(1).join(".");return se(J(f),m)}return{type:"expression",raw:c}}tryMatchPossessiveSelectorExpression(e){let t=e.peek();if(!t||t.kind!=="selector")return null;let r=e.mark();e.advance();let n=e.peek(),i=this.currentProfile?.possessive?.marker?.replace(/^-/,""),s=!!n&&n.kind==="punctuation"&&n.value==="'s",a=!!n&&n.value==="'"&&(e.peek(1)?.value??"").toLowerCase()==="s",l=(()=>{if(!this.currentPatternCommand||(n?.normalized??"").toLowerCase()!=="source")return!1;let f=Ne[this.currentPatternCommand];return!!f&&f.roles.some(m=>m.role==="source")})(),c=!!n&&!!i&&i!=="'s"&&n.value===i&&(n.kind==="particle"||n.kind==="punctuation")&&!l;if(!s&&!c&&!a)return e.reset(r),null;e.advance(),a&&e.advance();let d=e.peek();return!d||!(d.kind==="identifier"||(s||a)&&(d.kind==="selector"||d.kind==="keyword"))?(e.reset(r),null):(e.advance(),se(re(t.value),d.value))}tryMatchSelectorPropertyExpression(e){let t=e.peek();if(!t||t.kind!=="selector"||!t.value.startsWith("#"))return null;let r=e.mark();e.advance();let n=e.peek();if(!n||n.kind!=="selector"||!n.value.startsWith("."))return e.reset(r),null;let i=e.peek(1);i&&i.kind,e.advance();let s=n.value.slice(1);return se(re(t.value),s)}matchGroupToken(e,t,r,n){let i=e.mark(),s=new Set(r.keys());if(!this.matchTokenSequence(e,t.tokens,r,n)){e.reset(i);for(let l of r.keys())s.has(l)||r.delete(l);return t.optional||!1}return!0}getMatchType(e,t){return e.value===t?"exact":e.normalized===t?"normalized":e.stem===t&&e.stemConfidence!==void 0&&e.stemConfidence>=.7?"stem":e.kind==="keyword"&&e.value.toLowerCase()===t.toLowerCase()?"case-insensitive":"none"}tokenToSemanticValue(e){switch(e.kind){case"selector":return re(e.value);case"literal":return this.parseLiteralValue(e.value);case"keyword":let t=(e.normalized||e.value).toLowerCase();return xe(t)?J(t):$(e.normalized||e.value);case"identifier":if(e.value.startsWith("@"))return re(e.value);if(e.value.startsWith(":")||e.value.startsWith("$"))return J(e.value);let r=e.value.toLowerCase();return xe(r)?J(r):{type:"expression",raw:e.value};case"url":return $(e.value,"string");default:return null}}parseLiteralValue(e){if(e.startsWith('"')||e.startsWith("'")||e.startsWith("`")||e.startsWith("\u300C")){let n=e.slice(1,-1);return $(n,"string")}if(e==="true")return $(!0,"boolean");if(e==="false")return $(!1,"boolean");let t=e.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/);if(t){let n=parseFloat(t[1]);return t[2]?$(e,"duration"):$(n,"number")}let r=parseFloat(e);return isNaN(r)?$(e,"string"):$(r,"number")}applyExtractionRules(e,t){for(let[r,n]of Object.entries(e.extraction))t.has(r)||(n.value!==void 0?t.set(r,{type:"literal",value:n.value}):n.default&&t.set(r,n.default))}isOptional(e){return e.type!=="literal"&&e.optional===!0}skipNoiseWords(e){let t=e.peek();if(!t)return;let r=t.value.toLowerCase();if(A.ENGLISH_NOISE_WORDS.has(r)){let n=e.mark();e.advance();let i=e.peek();if(i&&(i.kind==="selector"||i.kind==="identifier"))return;let s=e.peek(1);if(i&&i.kind==="keyword"&&s&&s.kind==="selector"&&/^\.[a-zA-Z_]/.test(s.value))return;let a=i?(i.normalized??i.value).toLowerCase():"";if(i&&A.POSITIONAL_OR_SCOPE_KEYWORDS.has(a))return;let l=e.peek(1),c=l?(l.normalized??l.value).toLowerCase():"",d=this.currentProfile?.wordOrder!=="SOV"&&A.COMMAND_ACTION_KEYWORDS.has(c),u=!l||l.kind==="particle"||A.CLAUSE_BOUNDARY_KEYWORDS.has(c)||d;if(i&&i.kind==="keyword"&&this.currentProfile?.code!=="en"&&xe(a)&&u||i&&i.kind==="keyword"&&this.currentProfile?.code==="en"&&xe(a))return;e.reset(n)}r==="class"&&e.advance()}extractEventModifiers(e){let t={},r=!1;for(;!e.isAtEnd();){let n=e.peek();if(!n||n.kind!=="event-modifier")break;let i=n.metadata;if(!i)break;switch(r=!0,i.modifierName){case"once":t.once=!0;break;case"debounce":typeof i.value=="number"&&(t.debounce=i.value);break;case"throttle":typeof i.value=="number"&&(t.throttle=i.value);break;case"queue":(i.value==="first"||i.value==="last"||i.value==="all"||i.value==="none")&&(t.queue=i.value);break}e.advance()}return r?t:void 0}};A.POSITIONAL_KEYWORDS=new Set(["first","last","next","previous","random","closest"]),A.POSITIONAL_OR_SCOPE_KEYWORDS=new Set(["first","last","next","previous","random","closest","parent"]),A.STRUCTURAL_NEVER_EVENT=new Set(["if","unless","else","end","then"]),A.PROPERTY_ACCESS_BASES=new Set(["it","me","you","my","its","your","event","result","target","detail","body","window","document","self","this"]),A.COMMAND_ACTION_KEYWORDS=new Set(Object.keys(Ne).map(e=>e.toLowerCase())),A.CLAUSE_BOUNDARY_KEYWORDS=new Set(["then","and","or","end","else"]),A.OF_POSSESSIVE_MARKERS={ms:new Set(["daripada"]),sw:new Set(["ya"]),vi:new Set(["c\u1EE7a"]),zh:new Set(["\u7684"]),it:new Set(["di"]),pl:new Set(["z"]),uk:new Set(["\u0437"]),th:new Set(["\u0E02\u0E2D\u0E07"]),ja:new Set(["\u306E"]),ko:new Set(["\uC758"]),bn:new Set(["\u09B0"]),hi:new Set(["\u0915\u093E"]),qu:new Set(["pa"]),tr:new Set(["nin"])},A.RUN_OPERATORS=new Set(["+","-","*","/"]),A.MAX_BRACE_RUN_TOKENS=64,A.MAX_PROPERTY_DEPTH=10,A.MAX_METHOD_ARGS=20,A.DECLARATION_COMMANDS=new Set(["behavior","def","install"]),A.ENGLISH_NOISE_WORDS=new Set(["the","a","an"]);var Bt=A,le=new Bt;var Wi=["===","!==","->","==","!=","<=",">=","&&","||","**","+=","-=","*=","/=","+","-","*","/","=",">","<","!","&","|","%","^","~"],st=class{constructor(e=Wi){this.name="operator";this.operators=[...e].sort((t,r)=>r.length-t.length)}canExtract(e,t){return this.operators.some(r=>e.startsWith(r,t))}extract(e,t){for(let r of this.operators)if(e.startsWith(r,t))return{value:r,length:r.length};return null}},ji="()[]{},:;",lt=class{constructor(e=ji){this.punctuation=e;this.name="punctuation"}canExtract(e,t){return this.punctuation.includes(e[t])}extract(e,t){let r=e[t];return this.punctuation.includes(r)?{value:r,length:1}:null}};function Dt(o,e){let t=o[e];if(t==="#"){let r=o.slice(e).match(/^#[a-zA-Z_][\w-]*/);return r?r[0]:null}if(t==="."){let r=o.slice(e).match(/^\.\{[a-zA-Z_$][\w$]*\}/);if(r)return r[0];let n=o.slice(e).match(/^\.[a-zA-Z_][\w-]*/);return n?n[0]:null}if(t==="@"){let r=o.slice(e).match(/^@[a-zA-Z_][\w-]*/);return r?r[0]:null}if(t==="*"){let r=o.slice(e).match(/^\*(?:--)?[a-zA-Z_][\w-]*/);return r?r[0]:null}if(t==="["){let r=0,n=e;for(;n<o.length;){if(o[n]==="["&&r++,o[n]==="]"&&(r--,r===0))return o.slice(e,n+1);n++}return null}if(t==="<"){let r=o.slice(e).match(/^<(?=[\w.#[])[\w-]*(?:[#.][\w-]+|\[[^\]]+\])*\s*\/>/);return r?r[0]:null}return null}var We=class{constructor(){this.name="css-selector"}canExtract(e,t){let r=e[t];return r==="#"||r==="."||r==="["||r==="<"?!0:r==="@"||r==="*"?Dt(e,t)!==null:!1}extract(e,t){let r=Dt(e,t);return r?{value:r,length:r.length,metadata:{type:"css-selector"}}:null}};var je=class{constructor(){this.name="event-modifier"}canExtract(e,t){if(e[t]!==".")return!1;let r=e.slice(t);return/^\.(once|prevent|stop|debounce|throttle|queue)/.test(r)}extract(e,t){let r=e.slice(t).match(/^\.(?:once|prevent|stop|debounce|throttle|queue)(?:\(([^)]+)\))?/);if(!r)return null;let n=r[0],i=n.slice(1).split("(")[0],s=r[1];return{value:n,length:n.length,metadata:{modifierName:i,value:s?i==="queue"?s:parseInt(s,10):void 0}}}};function Nr(o,e){let t=o.slice(e);if(t.startsWith("http://")||t.startsWith("https://")){let r=t.match(/^https?:\/\/[^\s]*/);return r?r[0]:null}if(t.startsWith("//")){let r=t.match(/^\/\/[^\s]*/);return r?r[0]:null}if(t.startsWith("./")||t.startsWith("../")){let r=t.match(/^\.\.?\/[^\s]*/);return r?r[0]:null}if(t.startsWith("/")){let r=t.match(/^\/[^\s]*/);return r?r[0]:null}return null}var qe=class{constructor(){this.name="url"}canExtract(e,t){let r=e.slice(t);return r.startsWith("http://")||r.startsWith("https://")||r.startsWith("//")||r.startsWith("./")||r.startsWith("../")||r.startsWith("/")}extract(e,t){let r=Nr(e,t);return r?{value:r,length:r.length,metadata:{type:"url"}}:null}};var Ke=class{constructor(){this.name="variable-ref"}canExtract(e,t){let r=e[t];return(r===":"||r==="$"||r==="^")&&t+1<e.length&&/[a-zA-Z_]/.test(e[t+1])}extract(e,t){if(!this.canExtract(e,t))return null;let r=1;for(;t+r<e.length&&/[a-zA-Z0-9_]/.test(e[t+r]);)r++;return{value:e.substring(t,t+r),length:r,metadata:{type:"variable-reference"}}}};var Rr=ue([[1536,1791],[1872,1919],[2208,2303],[64336,65023],[65136,65279]]),qi=new Set(["\u0641\u064A","\u0639\u0644\u0649","\u0645\u0646","\u0625\u0644\u0649","\u0627\u0644\u0649","\u0645\u0639","\u0639\u0646","\u0642\u0628\u0644","\u0628\u0639\u062F","\u0628\u064A\u0646"]),ct=class{constructor(){this.name="arabic-keyword"}setContext(e){this.context=e}canExtract(e,t){return Rr(e[t])}extract(e,t){if(!this.context)throw new Error("ArabicKeywordExtractor: context not set");let r=t;this.context.isKeywordStart(e,t);let n="",i=t;for(;i<e.length&&(Rr(e[i])||e[i]==="\u0640");)n+=e[i],i++;if(!n)return null;let s=this.context.lookupKeyword(n),a=s&&s.normalized!==s.native?s.normalized:void 0;if(qi.has(n))return{value:n,length:i-r,metadata:{prepositionValue:n,normalized:a}};let l,c,d;if(!s&&this.context.normalizer){let u=this.context.normalizer.normalize(n);if(u.stem!==n&&u.confidence>=.7){let f=this.context.lookupKeyword(u.stem);f&&(l=f.normalized,c=u.stem,d=u.confidence)}}return{value:n,length:i-r,metadata:{normalized:a||l,stem:c,stemConfidence:d}}}};var Fe=ue([[1536,1791],[1872,1919],[2208,2303],[64336,65023],[65136,65279]]),Ue=new Map([["\u0648",{normalized:"and",type:"conjunction"}],["\u0641",{normalized:"then",type:"conjunction"}],["\u0628",{normalized:"with",type:"preposition"}],["\u0644",{normalized:"to",type:"preposition"}],["\u0643",{normalized:"like",type:"preposition"}],["\u0648\u0644",{normalized:"and-to",type:"conjunction"}],["\u0648\u0628",{normalized:"and-with",type:"conjunction"}],["\u0648\u0643",{normalized:"and-like",type:"conjunction"}],["\u0641\u0644",{normalized:"then-to",type:"conjunction"}],["\u0641\u0628",{normalized:"then-with",type:"conjunction"}],["\u0641\u0643",{normalized:"then-like",type:"conjunction"}]]),Ki=new Set(["\u0648\u062B\u064A\u0642\u0629"]),ut=class{constructor(){this.name="arabic-proclitic"}setContext(e){this.context=e}canExtract(e,t){let r=e[t];return Ue.has(r)||t+1<e.length&&Ue.has(e.slice(t,t+2))}extract(e,t){if(!this.context)throw new Error("ArabicProcliticExtractor: context not set");let r=t;for(;r<e.length&&(Fe(e[r])||e[r]==="\u0640");)r++;let n=e.slice(t,r);if(this.context.isKeyword(n)||Ki.has(n))return null;if(t+2<=e.length){let d=e.slice(t,t+2),u=Ue.get(d);if(u){let f=t+2;if(f<e.length&&Fe(e[f])){let m=0,p=f;for(;p<e.length&&Fe(e[p]);)m++,p++;if(m>=2)if(Ue.get(e[t])){let y=e.slice(t+1,r);if(!this.context.isKeyword(y))return{value:d,length:2,metadata:{procliticType:u.type,normalized:u.normalized}}}else return{value:d,length:2,metadata:{procliticType:u.type,normalized:u.normalized}}}}}let i=e[t],s=Ue.get(i);if(!s)return null;let a=t+1;if(a>=e.length||!Fe(e[a]))return null;let l=0,c=a;for(;c<e.length&&Fe(e[c]);)l++,c++;return l<2?null:{value:i,length:1,metadata:{procliticType:s.type,normalized:s.normalized}}}};var Fi=ue([[1536,1791],[1872,1919],[2208,2303],[64336,65023],[65136,65279]]),Lr=new Map([["\u0639\u0646\u062F\u0645\u0627",{normalized:"on",formality:"formal",confidence:.95,description:"when (formal MSA)"}],["\u062D\u064A\u0646\u0645\u0627",{normalized:"on",formality:"formal",confidence:.93,description:"when/whenever (formal)"}],["\u0639\u0646\u062F",{normalized:"on",formality:"neutral",confidence:.88,description:"at/when (neutral)"}],["\u062D\u064A\u0646",{normalized:"on",formality:"neutral",confidence:.85,description:"when/time (neutral)"}],["\u0644\u0645\u0651\u0627",{normalized:"on",formality:"dialectal",confidence:.7,description:"when (dialectal, with shadda)"}],["\u0644\u0645\u0627",{normalized:"on",formality:"dialectal",confidence:.68,description:"when (dialectal, no diacritic)"}],["\u0644\u062F\u0649",{normalized:"on",formality:"neutral",confidence:.82,description:"at/with (temporal)"}]]),dt=class{constructor(){this.name="arabic-temporal"}setContext(e){this._context=e,this._context}canExtract(e,t){for(let[r]of Lr)if(e.startsWith(r,t))return!0;return!1}extract(e,t){let r=Array.from(Lr.entries()).sort(([n],[i])=>i.length-n.length);for(let[n,i]of r)if(e.startsWith(n,t)){let s=t+n.length;if(s>=e.length||/\s/.test(e[s])||!Fi(e[s]))return{value:n,length:n.length,metadata:{temporalFormality:i.formality,temporalConfidence:i.confidence,normalized:i.normalized,description:i.description}}}return null}};function Ui(o){let e=o.charCodeAt(0);return e>=65&&e<=90||e>=97&&e<=122||e===95||e===36}function Hi(o){let e=o.charCodeAt(0);return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===95||e===36}var pt=class{constructor(){this.name="ascii-identifier"}setContext(e){this.context=e}canExtract(e,t){return Ui(e[t])}extract(e,t){if(!this.context)throw new Error("AsciiIdentifierExtractor: context not set");let r=t,n="",i=t;for(;i<e.length&&Hi(e[i]);)n+=e[i],i++;if(!n)return null;let s=this.context.lookupKeyword(n),a=s&&s.normalized!==s.native?s.normalized:void 0;return{value:n,length:i-r,metadata:{normalized:a}}}};function Ar(){return[new qe,new je,new Ke,new We]}function Gi(o){let e=o.charCodeAt(0);return e>=1536&&e<=1791||e>=1872&&e<=1919||e>=2208&&e<=2303||e>=64336&&e<=65023||e>=65136&&e<=65279}function Yi(o){for(let e of o)if(Gi(e))return!0;return!1}function Zi(o){return o.replace(/[\u064B-\u0652\u0670]/g,"")}var Ji=[{pattern:"\u0648\u0627\u0644",confidencePenalty:.15,prefixType:"conjunction"},{pattern:"\u0641\u0627\u0644",confidencePenalty:.15,prefixType:"conjunction"},{pattern:"\u0628\u0627\u0644",confidencePenalty:.15,prefixType:"preposition"},{pattern:"\u0643\u0627\u0644",confidencePenalty:.15,prefixType:"preposition"},{pattern:"\u0644\u0644",confidencePenalty:.12,prefixType:"preposition"}],Xi=[{pattern:"\u0627\u0644",confidencePenalty:.08,prefixType:"article",minRemaining:2},{pattern:"\u0648",confidencePenalty:.08,prefixType:"conjunction",minRemaining:3},{pattern:"\u0641",confidencePenalty:.08,prefixType:"conjunction",minRemaining:3},{pattern:"\u0628",confidencePenalty:.1,prefixType:"preposition",minRemaining:3},{pattern:"\u0644",confidencePenalty:.1,prefixType:"preposition",minRemaining:3},{pattern:"\u0643",confidencePenalty:.1,prefixType:"preposition",minRemaining:3}],Qi=[{pattern:"\u064A",confidencePenalty:.12,prefixType:"verb-marker",minRemaining:3},{pattern:"\u062A",confidencePenalty:.12,prefixType:"verb-marker",minRemaining:3},{pattern:"\u0646",confidencePenalty:.12,prefixType:"verb-marker",minRemaining:3},{pattern:"\u0623",confidencePenalty:.12,prefixType:"verb-marker",minRemaining:3},{pattern:"\u0627",confidencePenalty:.12,prefixType:"verb-marker",minRemaining:3}],ea=[{pattern:"\u0648\u0646",confidencePenalty:.1,type:"masculine-plural"},{pattern:"\u064A\u0646",confidencePenalty:.1,type:"masculine-plural-accusative"},{pattern:"\u0627\u062A",confidencePenalty:.1,type:"feminine-plural"},{pattern:"\u0627\u0646",confidencePenalty:.1,type:"dual-nominative"},{pattern:"\u064A\u0646",confidencePenalty:.1,type:"dual-accusative"},{pattern:"\u0647\u0627",confidencePenalty:.1,type:"pronoun-her"},{pattern:"\u0647\u0645",confidencePenalty:.1,type:"pronoun-them"},{pattern:"\u0647\u0646",confidencePenalty:.1,type:"pronoun-them-f"},{pattern:"\u0646\u0627",confidencePenalty:.1,type:"pronoun-us"},{pattern:"\u0643\u0645",confidencePenalty:.1,type:"pronoun-you-pl"},{pattern:"\u0643",confidencePenalty:.08,type:"pronoun-you"},{pattern:"\u0647",confidencePenalty:.08,type:"pronoun-him"},{pattern:"\u064A",confidencePenalty:.08,type:"pronoun-me"},{pattern:"\u0629",confidencePenalty:.08,type:"feminine"}],He=class{constructor(){this.language="ar"}isNormalizable(e){return!(!Yi(e)||e.length<2)}normalize(e){let t=Zi(e),r=1,n=[],i=[];for(let a of Ji)if(t.startsWith(a.pattern)){let l=t.slice(a.pattern.length);if(l.length>=2){t=l,r-=a.confidencePenalty,n.push(a.pattern);break}}if(n.length===0){for(let a of Xi)if(t.startsWith(a.pattern)){let l=t.slice(a.pattern.length),c=a.minRemaining??2;if(l.length>=c){t=l,r-=a.confidencePenalty,n.push(a.pattern);break}}}if(!(t.endsWith("\u0627\u062A")||t.endsWith("\u0629")||t.endsWith("\u0648\u0646")||t.endsWith("\u064A\u0646")||t.endsWith("\u0647\u0627")||t.endsWith("\u0647\u0645")||t.endsWith("\u0647\u0646")||t.endsWith("\u0646\u0627")||t.endsWith("\u0643\u0645"))&&(n.length===0||n[0]==="\u0648"||n[0]==="\u0641")){for(let a of Qi)if(t.startsWith(a.pattern)){let l=t.slice(a.pattern.length),c=a.minRemaining??3;if(l.length>=c){t=l,r-=a.confidencePenalty,n.push(a.pattern);break}}}for(let a of ea)if(t.endsWith(a.pattern)){let l=t.slice(0,-a.pattern.length);l.length>=2&&(t=l,r-=a.confidencePenalty,i.push(a.pattern))}return r=Math.max(.5,r),n.length===0&&i.length===0?zt(e):It(t,r,{removedPrefixes:n,removedSuffixes:i})}},cl=new He;var ta=new Set(["\u0648\u0644","\u0648\u0628","\u0648\u0643","\u0641\u0644","\u0641\u0628","\u0641\u0643"]),ra=new Set(["\u0641\u064A","\u0639\u0644\u0649","\u0645\u0646","\u0625\u0644\u0649","\u0627\u0644\u0649","\u0645\u0639","\u0639\u0646","\u0642\u0628\u0644","\u0628\u0639\u062F","\u0628\u064A\u0646","\u0628","\u0644","\u0643"]),na=[{native:"\u0635\u062D\u064A\u062D",normalized:"true"},{native:"\u062E\u0637\u0623",normalized:"false"},{native:"null",normalized:"null"},{native:"\u0641\u0627\u0631\u063A",normalized:"null"},{native:"\u063A\u064A\u0631 \u0645\u0639\u0631\u0641",normalized:"undefined"},{native:"\u0627\u0644\u0623\u0648\u0644",normalized:"first"},{native:"\u0623\u0648\u0644",normalized:"first"},{native:"\u0627\u0644\u0623\u062E\u064A\u0631",normalized:"last"},{native:"\u0622\u062E\u0631",normalized:"last"},{native:"\u0627\u0644\u062A\u0627\u0644\u064A",normalized:"next"},{native:"\u0627\u0644\u0633\u0627\u0628\u0642",normalized:"previous"},{native:"\u0627\u0644\u0623\u0642\u0631\u0628",normalized:"closest"},{native:"\u0627\u0644\u0623\u0628",normalized:"parent"},{native:"\u0627\u0644\u0646\u0642\u0631",normalized:"click"},{native:"\u0646\u0642\u0631",normalized:"click"},{native:"\u0627\u0644\u0625\u062F\u062E\u0627\u0644",normalized:"input"},{native:"\u0625\u062F\u062E\u0627\u0644",normalized:"input"},{native:"\u0627\u0644\u062A\u063A\u064A\u064A\u0631",normalized:"change"},{native:"\u062A\u063A\u064A\u064A\u0631",normalized:"change"},{native:"\u0627\u0644\u0625\u0631\u0633\u0627\u0644",normalized:"submit"},{native:"\u0625\u0631\u0633\u0627\u0644",normalized:"submit"},{native:"\u0627\u0644\u062A\u0631\u0643\u064A\u0632",normalized:"focus"},{native:"\u0641\u0642\u062F\u0627\u0646 \u0627\u0644\u062A\u0631\u0643\u064A\u0632",normalized:"blur"},{native:"\u0636\u063A\u0637",normalized:"keydown"},{native:"\u0631\u0641\u0639",normalized:"keyup"},{native:"\u062A\u0645\u0631\u064A\u0631 \u0627\u0644\u0641\u0623\u0631\u0629",normalized:"mouseover"},{native:"\u0645\u063A\u0627\u062F\u0631\u0629 \u0627\u0644\u0641\u0623\u0631\u0629",normalized:"mouseout"},{native:"\u062A\u062D\u0645\u064A\u0644",normalized:"load"},{native:"\u062A\u0645\u0631\u064A\u0631",normalized:"scroll"},{native:"\u0641\u0623\u0631\u0629 \u0623\u0633\u0641\u0644",normalized:"mousedown"},{native:"\u0641\u0623\u0631\u0629 \u0623\u0639\u0644\u0649",normalized:"mouseup"},{native:"\u0641\u0623\u0631\u0629 \u062F\u062E\u0648\u0644",normalized:"mouseenter"},{native:"\u0641\u0623\u0631\u0629 \u062E\u0631\u0648\u062C",normalized:"mouseleave"},{native:"\u0641\u0623\u0631\u0629 \u0641\u0648\u0642",normalized:"mouseover"},{native:"\u0641\u0623\u0631\u0629 \u062E\u0627\u0631\u062C",normalized:"mouseout"},{native:"\u0641\u0623\u0631\u0629 \u062A\u062D\u0631\u0643",normalized:"mousemove"},{native:"\u0645\u0641\u062A\u0627\u062D \u0623\u0633\u0641\u0644",normalized:"keydown"},{native:"\u0645\u0641\u062A\u0627\u062D \u0623\u0639\u0644\u0649",normalized:"keyup"},{native:"\u0647\u064A",normalized:"it"},{native:"\u062B\u0627\u0646\u064A\u0629",normalized:"s"},{native:"\u062B\u0648\u0627\u0646\u064A",normalized:"s"},{native:"\u0645\u0644\u064A \u062B\u0627\u0646\u064A\u0629",normalized:"ms"},{native:"\u062F\u0642\u064A\u0642\u0629",normalized:"m"},{native:"\u062F\u0642\u0627\u0626\u0642",normalized:"m"},{native:"\u0633\u0627\u0639\u0629",normalized:"h"},{native:"\u0633\u0627\u0639\u0627\u062A",normalized:"h"},{native:"\u0639\u0646\u062F\u0645\u0627",normalized:"on"},{native:"\u062D\u064A\u0646\u0645\u0627",normalized:"on"},{native:"\u0639\u0646\u062F",normalized:"on"},{native:"\u062D\u064A\u0646",normalized:"on"},{native:"\u0644\u0645\u0651\u0627",normalized:"on"},{native:"\u0644\u0645\u0627",normalized:"on"},{native:"\u0644\u062F\u0649",normalized:"on"}],$t=class extends Be{constructor(){super();this.language="ar";this.direction="rtl";this.initializeKeywordsFromProfile(ke,na),this.normalizer=new He,this.registerExtractors(Ar()),this.registerExtractor(new Mt),this.registerExtractor(new Ot),this.registerExtractor(new pt),this.registerExtractor(new dt),this.registerExtractor(new ut),this.registerExtractor(new ct),this.registerExtractor(new st),this.registerExtractor(new lt)}tokenizeWithExtractors(t){let r=[],n=0;for(;n<t.length;){for(;n<t.length&&ae(t[n]);)n++;if(n>=t.length)break;let i=this.tryMultiWordKeyword(t,n);if(i){r.push(i),n=i.position.end;continue}let s=!1;for(let a of this.extractors)if(a.canExtract(t,n)){let l=a.extract(t,n);if(l){let c=l.metadata?.normalized,d=l.metadata?.stem,u=l.metadata?.stemConfidence,f={};if(l.metadata)for(let[h,y]of Object.entries(l.metadata))h!=="normalized"&&h!=="stem"&&h!=="stemConfidence"&&(f[h]=y);let m;f.procliticType==="conjunction"?m="conjunction":f.procliticType==="preposition"?m="particle":m=this.classifyToken(l.value);let p={};c&&(p.normalized=c),d&&(p.stem=d),u!==void 0&&(p.stemConfidence=u),Object.keys(f).length>0&&(p.metadata=f),r.push(B(l.value,m,_(n,n+l.length),Object.keys(p).length>0?p:void 0)),n+=l.length,s=!0;break}}if(!s){let a=t[n],l=this.classifyUnknownChar(a);r.push(B(a,l,_(n,n+1))),n++}}return new H(r,this.language)}classifyToken(t){return ta.has(t)?"conjunction":ra.has(t)?"particle":this.isKeyword(t)?"keyword":t.startsWith("/")||t.startsWith("./")||t.startsWith("../")||t.startsWith("http")?"url":/^\.(once|prevent|stop|debounce|throttle|queue)(\(.*\))?$/.test(t)?"event-modifier":t.startsWith("#")||t.startsWith(".")||t.startsWith("[")||t.startsWith("*")||t.startsWith("<")?"selector":t.startsWith('"')||t.startsWith("'")||/^\d/.test(t)?"literal":"identifier"}},mt=new $t;function Y(o,e){return or(o,e)}function ft(){return Ct()}var yt=["if","unless","repeat","for","while"];function ce(o,e){let t=new Set([e]),n=I(o)?.keywords?.[e];if(n){n.primary&&t.add(n.primary.toLowerCase());for(let i of n.alternatives??[])t.add(i.toLowerCase())}return t}function te(o,e){return e.has(o.value.toLowerCase())?!0:o.normalized?e.has(o.normalized.toLowerCase()):!1}var ia=new Set(yt);function jt(o,e){let t=o.normalized?.toLowerCase();return t?ia.has(t):e.some(r=>te(o,r))}var Mr=new Set(["me","it","you","the","body","window","document","its","event","result","target","self","this","them","parent","next","previous","closest","first","last"]),aa=new Set(["destination","source","style","patient","on","from","to"]);function sa(o){if(!o||o.kind==="selector")return!1;let e=(o.normalized??o.value).toLowerCase(),t=o.value.toLowerCase();return!(Mr.has(e)||Mr.has(t)||aa.has(e))}var Or=new Set(["ja","ko"]);function Wt(o){let e=new Set;o?.primary&&e.add(o.primary.toLowerCase());for(let t of o?.alternatives??[])e.add(t.toLowerCase());return e}function Ir(o,e){let t=[],r=e.position.end,n=o.slice(e.position.end).match(/^\s*\(([^)]*)\)/);if(n){r=e.position.end+n[0].length;for(let i of n[1].split(/[,،、]/)){let s=i.trim();s&&t.push(s)}}return{parameters:t,headerEnd:r}}function Vr(o,e,t){let r=e+1;if(r>=o.length)return-1;let n=Wt(I(t)?.roleMarkers?.patient);return n.size>0&&te(o[r],n)&&r++,r<o.length?r:-1}function _r(o,e,t){if(!I(e))return null;let r=ce(e,"behavior"),n=ce(e,"def"),i=o.toLowerCase(),s=[...r].some(d=>i.includes(d)),a=/\bdef\b/.test(i)||[...n].some(d=>d!=="def"&&i.includes(d));if(!s&&!a)return null;let l=Y(o,e).tokens;if(l.length<2)return null;if(te(l[0],r))return zr(o,e,l,t,0);let c=l.findIndex((d,u)=>u>0&&te(d,r));return c>0&&/^[A-Z][A-Za-z0-9_]*$/.test(l[0].value)?zr(o,e,l,t,c):te(l[0],n)?la(o,e,l,t):null}function Br(o,e,t){let r=I(e);if(!r)return null;let n=r.wordOrder!=="SOV",i=Or.has(e)?Wt(r.roleMarkers?.event):new Set,s=Or.has(e)?Wt(r.keywords?.on):new Set,a=i.size>0&&s.size>0,l=ce(e,"end"),c=ce(e,"on"),d=o.toLowerCase(),u=[...l].some(k=>d.includes(k)),f=(n||a)&&(()=>{let k=0;for(let T of c)if(T){for(let v=d.indexOf(T);v>=0;v=d.indexOf(T,v+T.length))if(++k>=2)return!0}return!1})();if(!u&&!f)return null;let m=Y(o,e).tokens;if(m.length<2)return null;let p=yt.map(k=>ce(e,k)),h=k=>jt(k,p),y=k=>te(k,l),g=[],S=0,E=0;for(let k=0;k<m.length;k++){let T=m[k];if(y(T)){if(S>0){S--;continue}let v=o.slice(m[E].position.start,T.position.start).trim();v&&g.push(v),E=k+1}else if(h(T))S++;else if(n&&S===0&&k>E&&te(T,c)&&sa(m[k+1])){let v=o.slice(m[E].position.start,T.position.start).trim();v&&g.push(v),E=k}else if(a&&S===0&&k-1>E&&te(T,i)&&m[k+1]!==void 0&&te(m[k+1],s)){let v=m[k-1],b=o.slice(m[E].position.start,v.position.start).trim();b&&g.push(b),E=k-1}}if(E<m.length){let k=o.slice(m[E].position.start).trim();k&&g.push(k)}if(g.length<2)return null;let C=[],x=[];for(let k of g){let T;try{T=t.statement(k,e)}catch{return null}if(!T||T.kind!=="event-handler")return null;let v=T;C.push(v);let b=!v.body||v.body.length===0;x.push(b?.2:v.metadata?.confidence??.75)}return De(C,"then",{sourceLanguage:e,confidence:ht(x),sourceText:o})}function ht(o){return o.length>0?o.reduce((e,t)=>e+t,0)/o.length:0}function Dr(o){let e=[];for(let t of o){let r=t.statements;t.kind==="compound"&&Array.isArray(r)?e.push(...r):e.push(t)}return e}function zr(o,e,t,r,n){let i=n>0,s=i?0:Vr(t,n,e);if(s<0)return null;let a=t[s],l=a.value;if(!/^[A-Z][A-Za-z0-9_]*$/.test(l))return null;let{parameters:c,headerEnd:d}=Ir(o,a),u=i?n+1:t.findIndex(v=>v.position.start>=d);u<=s&&(u=s+1);let f=ce(e,"init"),m=ce(e,"end"),p=yt.map(v=>ce(e,v)),h=v=>jt(v,p),y=v=>te(v,m),g=[],S=[],E=[],C=!1,x=0,k=u;for(let v=u;v<t.length;v++){let b=t[v];if(y(b)){if(x>0){x--;continue}if(v===k){C=!0;break}if(te(t[k],f)){let N=o.slice(t[k].position.end,b.position.start).trim();if(N)try{let P=Dr(r.body(N,e));S.push(...P),E.push(ht(P.map(z=>z.metadata?.confidence??.75)))}catch{E.push(0)}}else{let N=o.slice(t[k].position.start,b.position.start).trim();try{let P=r.statement(N,e);if(P&&P.kind==="event-handler"){let z=P;g.push(z);let M=!z.body||z.body.length===0;E.push(M?.2:z.metadata?.confidence??.75)}else E.push(0)}catch{E.push(0)}}k=v+1}else h(b)&&x++}if(g.length===0&&S.length===0)return null;let T=(C?1:.8)*ht(E);return vr(l,c,g,S.length>0?S:void 0,{sourceLanguage:e,confidence:T,sourceText:o})}function la(o,e,t,r){let n=Vr(t,0,e);if(n<0)return null;let i=t[n],s=i.value;if(!/^[a-zA-Z_$][\w$]*(?:\.[a-zA-Z_$][\w$]*)*$/.test(s))return null;let{parameters:a,headerEnd:l}=Ir(o,i),c=t.findIndex(x=>x.position.start>=l);c<=n&&(c=n+1);let d=ce(e,"end"),u=yt.map(x=>ce(e,x)),f=x=>jt(x,u),m=x=>te(x,d),p=0,h=-1;for(let x=c;x<t.length;x++)if(m(t[x])){if(p===0){h=x;break}p--}else f(t[x])&&p++;let y=t[c]?.position.start??l,g=h>=0?t[h].position.start:o.length,S=o.slice(y,g).trim();if(!S)return null;let E;try{E=Dr(r.body(S,e))}catch{return null}if(E.length===0)return null;let C=ht(E.map(x=>x.metadata?.confidence??.75));return h<0&&(C*=.8),kr(s,a,E,{sourceLanguage:e,confidence:C,sourceText:o})}var Se={ko:{\uD074\uB9AD:"click",\uC785\uB825:"input",\uBCC0\uACBD:"change",\uC81C\uCD9C:"submit",\uD0A4\uB2E4\uC6B4:"keydown",\uD0A4\uC5C5:"keyup",\uB9C8\uC6B0\uC2A4\uC624\uBC84:"mouseover",\uB9C8\uC6B0\uC2A4\uC544\uC6C3:"mouseout",\uB9C8\uC6B0\uC2A4\uB2E4\uC6B4:"mousedown",\uB9C8\uC6B0\uC2A4\uC5C5:"mouseup",\uD3EC\uCEE4\uC2A4:"focus",\uBE14\uB7EC:"blur",\uB85C\uB4DC:"load",\uB9AC\uC0AC\uC774\uC988:"resize",\uC2A4\uD06C\uB864:"scroll"},ja:{\u30AF\u30EA\u30C3\u30AF:"click",\u5165\u529B:"input",\u5909\u66F4:"change",\u9001\u4FE1:"submit",\u30AD\u30FC\u30C0\u30A6\u30F3:"keydown",\u30AD\u30FC\u30A2\u30C3\u30D7:"keyup",\u30AD\u30FC\u30D7\u30EC\u30B9:"keypress",\u30DE\u30A6\u30B9\u30AA\u30FC\u30D0\u30FC:"mouseover",\u30DE\u30A6\u30B9\u30A2\u30A6\u30C8:"mouseout",\u30DE\u30A6\u30B9\u62BC\u4E0B:"mousedown",\u30DE\u30A6\u30B9\u89E3\u653E:"mouseup",\u30D5\u30A9\u30FC\u30AB\u30B9:"focus",\u30D6\u30E9\u30FC:"blur",\u30ED\u30FC\u30C9:"load",\u8AAD\u307F\u8FBC\u307F:"load",\u30B5\u30A4\u30BA\u5909\u66F4:"resize",\u30B9\u30AF\u30ED\u30FC\u30EB:"scroll"},ar:{\u0627\u0644\u0646\u0642\u0631:"click",\u0646\u0642\u0631:"click",\u0627\u0644\u0625\u062F\u062E\u0627\u0644:"input",\u0625\u062F\u062E\u0627\u0644:"input",\u0627\u0644\u062A\u063A\u064A\u064A\u0631:"change",\u062A\u063A\u064A\u064A\u0631:"change",\u0627\u0644\u0625\u0631\u0633\u0627\u0644:"submit",\u0625\u0631\u0633\u0627\u0644:"submit","\u0636\u063A\u0637 \u0627\u0644\u0645\u0641\u062A\u0627\u062D":"keydown","\u0631\u0641\u0639 \u0627\u0644\u0645\u0641\u062A\u0627\u062D":"keyup","\u062A\u0645\u0631\u064A\u0631 \u0627\u0644\u0645\u0627\u0648\u0633":"mouseover",\u0627\u0644\u062A\u0631\u0643\u064A\u0632:"focus",\u062A\u062D\u0645\u064A\u0644:"load",\u062A\u0645\u0631\u064A\u0631:"scroll"},es:{clic:"click",click:"click",entrada:"input",cambio:"change",env\u00EDo:"submit",enviar:"submit","tecla abajo":"keydown","tecla arriba":"keyup","rat\xF3n encima":"mouseover","rat\xF3n fuera":"mouseout",enfoque:"focus",desenfoque:"blur",carga:"load",desplazamiento:"scroll"},tr:{t\u0131klama:"click",t\u0131kla:"click",t\u0131k:"click",giri\u015F:"input",girdi:"input",de\u011Fi\u015Fiklik:"change",de\u011Fi\u015Fim:"change",g\u00F6nderme:"submit",g\u00F6nder:"submit",tu\u015Fbasma:"keydown",tu\u015Fb\u0131rakma:"keyup",fare_bas:"mousedown",fare_b\u0131rak:"mouseup",farei\u00E7inde:"mouseover",fared\u0131\u015F\u0131nda:"mouseout",odaklanma:"focus",odak:"focus",bulan\u0131kl\u0131k:"blur",y\u00FCkleme:"load",y\u00FCkle:"load",boyutland\u0131rma:"resize",boyutland\u0131r:"resize",kayd\u0131rma:"scroll"},pt:{clique:"click",clicar:"click",click:"click",entrada:"input",inserir:"input",mudan\u00E7a:"change",mudanca:"change",alterar:"change",envio:"submit",enviar:"submit","tecla baixo":"keydown","tecla cima":"keyup","pressionar tecla":"keydown","soltar tecla":"keyup","mouse sobre":"mouseover","mouse fora":"mouseout",foco:"focus",focar:"focus",desfoque:"blur",desfocar:"blur",carregar:"load",carregamento:"load",rolagem:"scroll",rolar:"scroll"},zh:{\u70B9\u51FB:"click",\u5355\u51FB:"click",\u53CC\u51FB:"dblclick",\u8F93\u5165:"input",\u6539\u53D8:"change",\u53D8\u5316:"change",\u53D8\u66F4:"change",\u63D0\u4EA4:"submit",\u53D1\u9001:"submit",\u6309\u952E:"keydown",\u952E\u5165:"keydown",\u677E\u952E:"keyup",\u9F20\u6807\u8FDB\u5165:"mouseover",\u9F20\u6807\u79FB\u5165:"mouseover",\u9F20\u6807\u79BB\u5F00:"mouseout",\u9F20\u6807\u79FB\u51FA:"mouseout",\u7126\u70B9:"focus",\u805A\u7126:"focus",\u5931\u7126:"blur",\u6A21\u7CCA:"blur",\u52A0\u8F7D:"load",\u8F7D\u5165:"load",\u6EDA\u52A8:"scroll"},fr:{clic:"click",cliquer:"click",click:"click",saisie:"input",entr\u00E9e:"input",changement:"change",changer:"change",soumettre:"submit",soumission:"submit",envoi:"submit","touche bas":"keydown","touche haut":"keyup","souris dessus":"mouseover","souris dehors":"mouseout",focus:"focus",focaliser:"focus",d\u00E9focus:"blur",d\u00E9focaliser:"blur",chargement:"load",charger:"load",d\u00E9filement:"scroll",d\u00E9filer:"scroll"},de:{klick:"click",klicken:"click",click:"click",eingabe:"input",eingeben:"input",\u00E4nderung:"change",\u00E4ndern:"change",absenden:"submit",einreichen:"submit","taste runter":"keydown","taste hoch":"keyup","maus \xFCber":"mouseover","maus raus":"mouseout",fokus:"focus",fokussieren:"focus",defokussieren:"blur",unsch\u00E4rfe:"blur",laden:"load",ladung:"load",scrollen:"scroll",bl\u00E4ttern:"scroll"},id:{klik:"click",click:"click",masukan:"input",input:"input",ubah:"change",perubahan:"change",kirim:"submit","tekan tombol":"keydown","lepas tombol":"keyup","mouse masuk":"mouseover","mouse keluar":"mouseout",fokus:"focus",blur:"blur",muat:"load",memuat:"load",gulir:"scroll",menggulir:"scroll"},bn:{\u0995\u09CD\u09B2\u09BF\u0995:"click",\u0987\u09A8\u09AA\u09C1\u099F:"input",\u099C\u09AE\u09BE:"submit",\u09B2\u09CB\u09A1:"load",\u09B8\u09CD\u0995\u09CD\u09B0\u09CB\u09B2:"scroll",\u09B0\u09BF\u09B8\u09BE\u0987\u099C:"resize",\u099D\u09BE\u09AA\u09B8\u09BE:"blur",\u09AB\u09CB\u0995\u09BE\u09B8:"focus",\u09AA\u09B0\u09BF\u09AC\u09B0\u09CD\u09A4\u09A8:"change"},qu:{click:"click","\xF1it'iy":"click",\u00F1itiy:"click",yaykuchiy:"input",yaykuy:"input",tikray:"change","t'ikray":"change",apachiy:"submit",kachay:"submit","llave uray":"keydown","llave hawa":"keyup","q'away":"focus",qhaway:"focus",paqariy:"blur","mana q'away":"blur",cargay:"load",apakuy:"load",apamuy:"load",kunray:"scroll",muyuy:"scroll",hatun_kay:"resize"},sw:{bofya:"click",click:"click",kubofya:"click",ingiza:"input",kubadilisha:"change",mabadiliko:"change",tuma:"submit",kutuma:"submit","bonyeza chini":"keydown","bonyeza juu":"keyup","panya juu":"mouseover","panya nje":"mouseout",lenga:"focus",kulenga:"focus",blur:"blur",pakia:"load",kupakia:"load",sogeza:"scroll",kusogeza:"scroll"}};var ca=Object.fromEntries(Object.entries(Se).map(([o,e])=>{let t={};for(let[r,n]of Object.entries(e))n in t||(t[n]=r);return[o,t]})),ua={ar:new Set(["mouseover"]),bn:new Set(["resize"]),de:new Set(["keydown","keyup","load","mouseout","mouseover"]),fr:new Set(["blur"]),id:new Set(["input","keyup","mouseout","mouseover"]),ja:new Set(["keypress","mousedown","mouseup","resize"]),qu:new Set(["change","focus","load","resize","submit"]),sw:new Set(["change","click","input","keydown","keyup","mouseout","mouseover","submit"]),tr:new Set(["keydown","keyup","load","mousedown","mouseout","mouseover","mouseup","resize","scroll"]),zh:new Set(["focus","keyup","mouseout","mouseover"])};function $r(o,e){return ua[e]?.has(o)?o:ca[e]?.[o]??o}var gt=class{render(e,t){if(e.kind==="compound")return this.renderCompound(e,t);if(e.kind==="behavior")return this.renderBehavior(e,t);if(e.kind==="def")return this.renderDef(e,t);let r=Nt(t,e.action);if(r.length===0)return this.renderExplicit(e);let n=this.findBestPattern(e,r);return n?this.renderWithPattern(e,n):this.renderExplicit(e)}renderCompound(e,t){if(e.statements.length>1&&e.statements.every(i=>i.kind==="event-handler")){let i=this.keyword(t,"end"),s=[];for(let a of e.statements)s.push(this.render(a,t),i);return s.join(`
3
+ `)}let r=e.statements.map(i=>this.render(i,t)),n=this.getChainWord(e.chainType,t);return r.join(` ${n} `)}keyword(e,t){return I(e)?.keywords?.[t]?.primary??t}renderBlockHeader(e,t,r){return r.length>0?`${e} ${t}(${r.join(", ")})`:`${e} ${t}`}renderBehavior(e,t){let r=this.keyword(t,"end"),n=[this.renderBlockHeader(this.keyword(t,"behavior"),e.name,e.parameters)];for(let i of e.eventHandlers)n.push(` ${this.render(i,t)}`,` ${r}`);if(e.initBlock&&e.initBlock.length>0){n.push(` ${this.keyword(t,"init")}`);for(let i of e.initBlock)n.push(` ${this.render(i,t)}`);n.push(` ${r}`)}return n.push(r),n.join(`
4
4
  `)}renderDef(e,t){let r=[this.renderBlockHeader(this.keyword(t,"def"),e.name,e.parameters)];for(let n of e.body)r.push(` ${this.render(n,t)}`);return r.push(this.keyword(t,"end")),r.join(`
5
- `)}getChainWord(e,t){let r=V(t);return r?.keywords?r.keywords[e]?.primary??e:e}renderExplicit(e){return ee(e)}supportedLanguages(){return ft()}findBestPattern(e,t){let r=t;if(e.kind==="event-handler"){let i=t.filter(s=>!/-event-/i.test(s.id));i.length>0&&(r=i)}let n=r.map(i=>{let s=i.priority;for(let a of i.template.tokens)a.type==="role"&&(e.roles.has(a.role)?s+=10:a.optional||(s-=50));return/-at-end|-at-start|-before$|-after$/i.test(i.id)&&(s-=30),i.language==="en"&&((i.id.includes("standard")||i.id.includes("en-source"))&&(s+=20),(i.id.includes("-when")||i.id.includes("-if")||i.id.includes("-upon"))&&(s-=15)),{pattern:i,score:s}});return n.sort((i,s)=>s.score-i.score),n.length>0?n[0].pattern:null}renderWithPattern(e,t){let r=[],n=t.language;for(let i of t.template.tokens){let s=this.renderPatternToken(i,e,n);s!==null&&r.push(s)}if(e.kind==="event-handler"){let i=e;if(i.body&&i.body.length>0){let s=i.body.map(a=>this.render(a,n));r.push(s.join(" "))}}return r.join(" ")}renderPatternToken(e,t,r){switch(e.type){case"literal":return e.value;case"role":{let n=t.roles.get(e.role);return n?e.role==="event"&&t.kind==="event-handler"?this.renderEventName(n,r):this.valueToNaturalString(n,r):(e.optional,null)}case"group":{if(!e.tokens.filter(a=>a.type==="role"&&!a.optional).every(a=>t.roles.has(a.role))&&e.optional)return null;if(e.optional&&e.tokens.find(l=>l.type==="role"&&l.role==="destination")){let l=t.roles.get("destination");if(l?.type==="reference"&&l.value==="me")return null}if(e.optional&&e.tokens.find(l=>l.type==="role"&&l.role==="quantity")){let l=t.roles.get("quantity");if(l?.type==="literal"&&Number(l.value)===1)return null}let i=[],s=!1;for(let a of e.tokens){let l=this.renderPatternToken(a,t,r);l!==null&&(i.push(l),a.type==="role"&&(s=!0))}return e.optional&&!s?null:i.length>0?i.join(" "):null}default:return null}}renderEventName(e,t){if(e.type!=="literal"||typeof e.value!="string")return this.valueToNaturalString(e,t);let r=e.value,n=i=>i.includes(":")?i:$r(i,t);return r.includes(" or ")?r.split(" or ").map(i=>n(i.trim())).join(" or "):n(r)}valueToNaturalString(e,t="en"){switch(e.type){case"literal":return typeof e.value=="string"&&e.dataType==="string"?`"${e.value}"`:String(e.value);case"selector":return e.value;case"reference":return this.renderReference(e,t);case"property-path":return this.renderPropertyPath(e,t);case"expression":return e.raw;case"flag":return e.name}}renderReference(e,t){let r=V(t);return r?.references?r.references[e.value]??e.value:e.value}renderPropertyPath(e,t){let r=V(t),n=e.property,i=e.object.type==="reference"?e.object.value:null;if(r?.possessive?.specialForms&&i){let a=r.possessive.specialForms[i];if(a){let{markerPosition:l,usePossessiveAdjectives:c}=r.possessive;return c&&l==="after-object"?`${n} ${a}`:`${a} ${n}`}}let s=this.valueToNaturalString(e.object,t);if(r?.possessive){let{marker:a,markerPosition:l,usePossessiveAdjectives:c}=r.possessive;if(c&&i&&l==="after-object")return`${n} ${s}`;if(a)switch(l){case"between":return r.usesSpaces?`${s}${a} ${n}`:`${s}${a}${n}`;case"after-object":return`${s}${a} ${n}`;case"before-property":return`${s} ${a} ${n}`}}return t==="en"||!r?.possessive?s==="me"?`my ${n}`:s==="it"?`its ${n}`:`${s}'s ${n}`:`${s} ${n}`}},qt=new gt;function Ge(o,e){return qt.render(o,e)}function Ye(o){return qt.renderExplicit(o)}var da={getSchema:ne};function Re(o){return nt(o,{schemaLookup:da})}var Le=new Set(["if","unless","while","repeat","for"]),pa=new Set(["then","end","else","if","unless","while","for","repeat","and"]),ma=new Set(["first","last","next","previous","random","closest"]),Ae=new Set(["click","dblclick","input","change","submit","keydown","keyup","keypress","mouseover","mouseout","mousedown","mouseup","focus","blur","load","scroll","resize","contextmenu","transitionend","transitionstart","transitionrun","transitioncancel","animationend","animationstart","animationiteration","animationcancel","pointerdown","pointerup","pointermove","pointerenter","pointerleave","pointercancel","pointerover","pointerout","touchstart","touchend","touchmove","touchcancel","mousemove","mouseenter","mouseleave","wheel","dragstart","dragend","dragover","dragenter","dragleave","drop","drag","loadend","loadstart","error","abort","close","open","message","popstate","hashchange","storage","online","offline","visibilitychange"]),Ze=class extends Error{constructor(e,t,r,n){super(e),this.name="SemanticParseError",this.language=t,this.input=r,this.diagnostics=n}};function W(o,e,t){return{message:o,severity:e,source:"semantic-parser",...t&&{code:t}}}function X(o,e){return e.length===0?o:{...o,diagnostics:e}}function Wr(o){if(o.length>=2){let e=o[0];if((e==='"'||e==="'")&&o.endsWith(e))return o.slice(1,-1)}return o}var fa=["body","statements","thenBranch","elseBranch","eventHandlers","initBlock"];function jr(o,e){if(!o||typeof o!="object")return o;if(o.action&&o.roles instanceof Map){let r=ne(o.action),n=r?.primaryRole;if(r&&n&&n!=="patient"&&!r.roles.some(i=>i.role==="patient")&&o.roles.has("patient")&&!o.roles.has(n)){let i=o.roles,s=i.get("patient");s!==void 0&&(i.delete("patient"),i.set(n,s))}if(o.action==="tell"){let i=o.roles,s=i.get("patient"),a=i.get("destination");s&&(s.type==="selector"||s.type==="reference")&&(!a||a.type==="literal")&&(i.delete("patient"),i.set("destination",s))}if(o.action==="transition"){let i=o.roles,s=i.get("destination");s&&s.type==="literal"&&!i.has("goal")&&(i.delete("destination"),i.set("goal",s));let a=i.get("patient");a&&a.type==="literal"&&typeof a.value=="string"&&/^[A-Za-z_][A-Za-z0-9_-]*$/.test(a.value)&&i.set("patient",{type:"expression",raw:a.value})}if(o.action==="morph"){let i=o.roles,s=i.get("patient");s&&s.type==="literal"&&typeof s.value=="string"&&/<[a-zA-Z][^>]*\/?>/.test(s.value)&&i.set("patient",{type:"expression",raw:s.value})}if(o.action==="wait"){let i=o.roles;if(!i.has("event")){let s=i.get("duration"),a=s?.type==="expression"?s.raw:s?.type==="literal"?s.value:void 0;typeof a=="string"&&Ae.has(a.toLowerCase())&&(i.delete("duration"),i.set("event",{type:"literal",value:a,dataType:"string"}))}}if(o.kind==="command"&&o.action!=="on"){let i=o.roles,s=i.get("event");if(s&&s.type==="expression"){let a=s.raw;typeof a=="string"&&/^[A-Za-z_][A-Za-z0-9_-]*(:[A-Za-z0-9_-]+)?$/.test(a)&&i.set("event",{type:"literal",value:a,dataType:"string"})}}if(e?.size){let i=o.roles;for(let s of["destination","source"]){let a=i.get(s);a&&a.type==="literal"&&typeof a.value=="string"&&e.has(a.value)&&i.set(s,{type:"expression",raw:a.value})}}}let t=o;for(let r of fa){let n=t[r];if(Array.isArray(n))for(let i of n)jr(i,e)}return o}var L=class L{constructor(){this.parseDepth=0;this.boundIdentifiers=new Set}parse(e,t){this.parseDepth===0&&this.boundIdentifiers.clear(),this.parseDepth++;try{return jr(this.parseInternal(e,t),this.boundIdentifiers)}finally{this.parseDepth--}}registerBoundIdentifiers(e){let t=e.action==="repeat"||e.action==="for"?"patient":e.action==="set"?"destination":null;if(!t)return;let r=e.roles.get(t);r?.type==="expression"&&typeof r.raw=="string"&&/^[A-Za-z_]\w*$/.test(r.raw)&&this.boundIdentifiers.add(r.raw)}parseInternal(e,t){let r=_r(e,t,{statement:(v,b)=>this.parse(v,b),body:(v,b)=>this.parseStatements(v,b)});if(r)return r;let n=Br(e,t,{statement:(v,b)=>this.parse(v,b),body:(v,b)=>this.parseStatements(v,b)});if(n)return n;let{modifiers:i,remainingInput:s}=this.extractStandaloneModifiers(e,t),a=s||e,c=this.stripAsyncModifier(a,t).remainingInput??a,u=this.stripDoNotThrowModifier(c,t).remainingInput??c,f=[],m=Y(u,t),p=Q(t);if(p.length===0)throw new Ze(`No patterns available for language: ${t}`,t,u,[W(`No patterns registered for language '${t}'`,"error","no-patterns")]);let h=[...p].sort((v,b)=>b.priority-v.priority);{let v=m.tokens;if(V(t)?.wordOrder==="VSO"&&v.length>=4&&v[0]?.normalized==="source"){let b=v.findIndex(N=>N.normalized==="on");if(b>=2&&b+1<v.length){let N=u.slice(v[0].position.start,v[b].position.start).trim(),P=v[b+1].position.end,z=u.slice(v[b].position.start,P)+" "+N+u.slice(P);if(z!==u)try{let M=this.parse(z,t);if(M&&M.kind==="event-handler"){let O=i?this.applyModifiers(M,i):M;return X(O,f)}}catch{}}}}{let v=m.tokens;for(let b=1;b<v.length-1;b++){let N=v[b],P=N.value,z=(N.normalized??N.value).toLowerCase();if(!(z==="or"||L.OR_KEYWORDS.has(P)||L.OR_KEYWORDS.has(z)))continue;let O=v[b+1],D=(O.normalized??O.value).toLowerCase();if(!L.KNOWN_EVENTS.has(D))break;let I=b+1,K=v[b+2];K&&K.kind==="selector"&&K.value.startsWith("[")&&(I=b+2);let U=v[b].position.start,he=v[I].position.end,oe=(u.slice(0,U).trimEnd()+" "+u.slice(he).trimStart()).trim();if(oe&&oe!==u)try{let ye=this.parse(oe,t);if(ye&&ye.kind==="event-handler"){ye.additionalEvents=[{type:"literal",value:D}];let xt=i?this.applyModifiers(ye,i):ye;return X(xt,f)}}catch{}break}}let y=h.filter(v=>v.command==="on"),g=m.mark(),S=le.matchBest(m,y);if(S){f.push(W(`event pattern matched: ${S.pattern.id} (confidence: ${S.confidence.toFixed(2)})`,"info","pattern-match"));let v=!1;if(/^event-[a-z]+-bare$/.test(S.pattern.id)){let b=S.captured.get("event"),N=(b?.raw??b?.value??"").toString().toLowerCase(),P=Se[t],z=L.KNOWN_EVENTS.has(N)||!!P&&Object.keys(P).some(M=>M.toLowerCase()===N);if(N&&!z){let M=this.trySOVEventExtraction(u,t,h);if(M){f.push(W(`bare-event mis-anchor on "${N}" rejected; SOV extraction preferred`,"info","stage-bare-event-guard"));let O=i?this.applyModifiers(M,i):M;return X(O,f)}if(b?.type==="reference"||b?.type==="expression"){m.reset(g);let O=h.filter(I=>I.command!=="on"),D=le.matchBest(m,O);m.reset(g),D&&D.pattern.command!=="on"?(v=!0,f.push(W(`bare-event mis-anchor on reference "${N}" rejected; command ${D.pattern.command} preferred`,"info","stage-bare-event-guard"))):le.matchBest(m,y)}}}if(!v){let b=this.buildEventHandler(S,m,t),N=i?this.applyModifiers(b,i):b;return X(N,f)}}f.push(W(`event patterns: ${y.length} tried, no match`,"info","stage-event"));let E=this.tryTrailingEventExtraction(u,t,h);if(E){f.push(W("trailing event extraction succeeded","info","stage-trailing-event"));let v=i?this.applyModifiers(E,i):E;return X(v,f)}let C=h.filter(v=>v.command!=="on"),k=le.matchBest(m,C);if(k){if(Le.has(k.pattern.command)){let v=this.trySOVEventExtraction(u,t,h);if(v){f.push(W(`SOV event extraction preferred over bare ${k.pattern.command} command`,"info","stage-sov-loop"));let N=i?this.applyModifiers(v,i):v;return X(N,f)}let b=this.tryMidStreamEventExtraction(u,t,h);if(b){f.push(W(`mid-stream event extraction preferred over bare ${k.pattern.command} command`,"info","stage-midstream-loop"));let N=i?this.applyModifiers(b,i):b;return X(N,f)}}else if(L.KNOWN_EVENTS.has(k.pattern.command)&&this.hasSOVEventMarkerHead(u,t)){let v=this.trySOVEventExtraction(u,t,h);if(v){f.push(W(`SOV event extraction preferred over command-homonym event ${k.pattern.command}`,"info","stage-sov-homonym"));let b=i?this.applyModifiers(v,i):v;return X(b,f)}}else if(V(t)?.wordOrder==="VSO"){let v=this.tryMidStreamEventExtraction(u,t,h);if(v){f.push(W(`mid-stream event extraction preferred over bare ${k.pattern.command} command`,"info","stage-midstream-cmd"));let b=i?this.applyModifiers(v,i):v;return X(b,f)}}if(k.consumedTokens<m.tokens.length&&V(t)?.wordOrder==="SOV"){let v=this.trySOVEventExtraction(u,t,h);if(v){f.push(W(`SOV event extraction preferred over partial ${k.pattern.command} command (trailing remainder)`,"info","stage-sov-trailing"));let b=i?this.applyModifiers(v,i):v;return X(b,f)}}return f.push(W(`command pattern matched: ${k.pattern.id} (confidence: ${k.confidence.toFixed(2)})`,"info","pattern-match")),X(this.buildCommand(k,t),f)}if(f.push(W(`command patterns: ${C.length} tried, no match`,"info","stage-command")),!u.includes(`
6
- `)&&V(t)?.wordOrder==="VSO"){let v=this.tryMidStreamEventExtraction(u,t,h);if(v){f.push(W("mid-stream event extraction succeeded with no leading command match","info","stage-midstream-nocmd"));let b=i?this.applyModifiers(v,i):v;return X(b,f)}}let x=this.trySOVEventExtraction(u,t,h);if(x){f.push(W("SOV event extraction succeeded","info","stage-sov"));let v=i?this.applyModifiers(x,i):x;return X(v,f)}f.push(W("SOV event extraction: no event keyword found","info","stage-sov"));let T=this.tryCompoundCommandParsing(m,C,t);if(T)return f.push(W("compound command parsing succeeded","info","stage-compound")),X(T,f);throw f.push(W("compound parsing: no then-keywords or no command matches","info","stage-compound")),f.push(W(`all parse stages exhausted for "${u}"`,"error","parse-failed")),new Ze(`Could not parse input in ${t}: ${u}`,t,u,f)}parseStatements(e,t){let r=Y(e,t),n=Q(t).filter(i=>i.command!=="on").sort((i,s)=>s.priority-i.priority);return this.parseBodyWithClauses(r,n,t)}canParse(e,t){try{return this.parse(e,t),!0}catch{return!1}}supportedLanguages(){return ft()}buildCommand(e,t){if(!e)throw new Error("No match to build command from");let r={};for(let[i,s]of e.captured)r[i]=s;let n=G(e.pattern.command,r,{sourceLanguage:t,patternId:e.pattern.id,confidence:e.confidence});return this.registerBoundIdentifiers(n),n}buildEventHandler(e,t,r){if(!e)throw new Error("No match to build event handler from");let n=e.captured.get("event");if(!n)throw new Error("Event handler pattern matched but no event captured");let i=le.extractEventModifiers(t),s=this.extractOrConjunctionEvents(t,r),a=n;s.length>0&&n.type==="literal"&&(a={type:"literal",value:[String(n.value),...s.map(u=>String("value"in u?u.value:""))].join(" or ")});let l,c=e.captured.get("action");if(c&&c.type==="literal"&&c.value==="if"){let d=t.tokens,u=-1;for(let f=t.position()-1;f>=0;f--){let m=d[f],p=(m.normalized??m.value).toLowerCase();if(this.isIfKeyword(p,r)){u=f;break}}if(u>=0){let f=Q(r).filter(y=>y.command!=="on").sort((y,g)=>g.priority-y.priority),m=new H(d.slice(u),r),p=this.parseBodyWithClauses(m,f,r);if(p.some(y=>y.kind==="conditional")||p.length===1&&p[0]?.kind==="compound"&&p[0].statements.some(y=>y.kind==="conditional")){for(;!t.isAtEnd();)t.advance();return fe(a,p,i,{sourceLanguage:r,patternId:e.pattern.id,confidence:e.confidence})}}}if(c&&c.type==="literal"){let d=c.value,u={};for(let[C,k]of e.captured)C!=="event"&&C!=="action"&&C!=="continues"&&(u[C]=k);if(d==="repeat"){let C=t.peek(),k=T=>(T.normalized??T.value).toLowerCase();if(C&&C.kind==="keyword"&&k(C)==="forever")u.loopType={type:"literal",value:"forever"},delete u.patient,t.advance();else if(C&&C.kind==="keyword"&&k(C)==="event"){t.advance();let T=t.peek();if(T)for(u.event={type:"literal",value:k(T)},u.loopType={type:"literal",value:"until-event"},delete u.patient;!t.isAtEnd();){let v=t.peek();if(!v||v.kind==="conjunction"||v.kind==="keyword"&&(this.isThenKeyword(v.value,r)||this.isEndKeyword(v.value,r)))break;t.advance()}}let x=u.patient;x&&x.type==="reference"&&x.value==="me"&&delete u.patient}let f=G(d,u,{sourceLanguage:r,patternId:e.pattern.id,confidence:e.confidence});if(this.registerBoundIdentifiers(f),!Le.has(d)||d==="repeat"){let C=e.pattern.id.includes("verb-first"),k=t.tokens,x=t.position(),T=b=>b.kind==="conjunction"||b.kind==="keyword"&&(this.isThenKeyword(b.value,r)||this.isEndKeyword(b.value,r)),v=-1;for(let b=x-1;b>=0;b--){let N=k[b];if(T(N))break;if((N.normalized??N.value).toLowerCase()===d){v=b;break}}if(v>=0){let b=x;for(;b<k.length&&!T(k[b]);)b++;let N=k.slice(v,b),P=N;if(C){let z=String(n.value??"").toLowerCase(),M=N.findIndex(O=>(O.normalized??O.value).toLowerCase()===z);if(M<0)P=null;else{let O=N[M-1],D=O&&O.kind==="keyword"&&O.normalized?.toLowerCase()==="on"?M-1:M;P=[...N.slice(0,D),...N.slice(M+1)]}}if(P&&P.length>1){let z=Q(r).filter(j=>j.command!=="on").sort((j,pe)=>pe.priority-j.priority),M=this.parseClause(P,z,r),O=M[0],D=j=>j!==null&&typeof j=="object"&&typeof j.type=="string"?j.type:typeof j,I=ne(d),K=I?.primaryRole,U=j=>j==="patient"&&K&&K!=="patient"&&!I?.roles.some(pe=>pe.role==="patient")?K:j,he=(j,pe)=>{if(!Le.has(d)||!I)return!1;let be=I.roles.find(Fr=>Fr.role===U(j));return be?be.expectedTypes.length>0&&!be.expectedTypes.includes(D(pe)):!0},oe=!!O&&O.kind==="command"&&Object.entries(u).every(([j,pe])=>{if(he(j,pe))return!0;let be=O.roles.get(U(j));return be!==void 0&&D(be)===D(pe)}),ye=O?.metadata?.patternId??"",xt=!Le.has(d)||/^repeat-.*-(times|for-in|while-head|until-head)$/.test(ye);if(M.length===1&&O&&O.kind==="command"&&O.action===d&&oe&&xt&&O.roles.size>Object.keys(u).length)for(f=O;t.position()<b;)t.advance()}}}if(!Le.has(d)){let C=f;if(ne(d)?.roles.some(P=>P.role==="quantity"&&!P.required)&&!C.roles.has("quantity")){let P=t.peek();P&&/^-?\d+(\.\d+)?$/.test(P.value)&&(f=G(d,{...Object.fromEntries(C.roles),quantity:{type:"literal",value:parseFloat(P.value),dataType:"number"}},C.metadata),t.advance())}let x=f;if(ne(d)?.roles.some(P=>P.role==="duration"&&!P.required)&&!x.roles.has("duration")){let P=t.peek();P&&/^\d+(\.\d+)?(ms|s)$/i.test(P.value)&&(f=G(d,{...Object.fromEntries(x.roles),duration:{type:"literal",value:P.value,dataType:"string"}},x.metadata),t.advance(),this.consumeForPostposition(t,r))}let v=f,b=ne(d);if(b?.roles.find(P=>P.role==="responseType"&&!P.required)&&!v.roles.has("responseType")){let P=I=>typeof I=="string"&&L.RESPONSE_TYPE_WORDS.has(I.toLowerCase()),z=(I,K)=>{let U=Object.fromEntries(v.roles);K&&delete U.destination,U.responseType={type:"expression",raw:I},f=G(d,U,v.metadata)},M=v.roles.get("destination"),O=b?.roles.find(I=>I.role==="destination"),D=M?.raw??M?.value;if(M&&O&&!O.expectedTypes.includes(M.type)&&P(D))z(D,!0);else{let I=t.peek();I&&P(I.value)&&(z(I.value,!1),t.advance())}}if(d==="wait"){let P=f;if(!P.roles.has("event")){let z=t.peek();if(z&&Ae.has(z.value.toLowerCase())){let M=Object.fromEntries(P.roles),O=M.duration;O&&O.type!=="literal"&&O.type!=="expression"&&delete M.duration;let D=M.patient;D&&D.type==="reference"&&D.value==="me"&&delete M.patient,M.event={type:"literal",value:z.value,dataType:"string"},f=G(d,M,P.metadata),t.advance(),this.consumeForPostposition(t,r)}}}}let m=e.captured.get("continues"),p=m?.type==="literal"&&m.value==="then",h=t.peek(),y=!!h&&this.isThenKeyword(h.value,r),S=Le.has(d)&&!!h&&!this.isEndKeyword(h.value,r),E=!!h&&!this.isEndKeyword(h.value,r);if(p||y||S||E){let C=Q(r).filter(T=>T.command!=="on").sort((T,v)=>v.priority-T.priority),k=Q(r).filter(T=>T.id.startsWith("grammar-")&&T.id.includes("-continuation")).sort((T,v)=>v.priority-T.priority),x=this.parseBodyWithGrammarPatterns(t,C,k,r);x.length>0?l=[f,...x]:l=[f]}else l=[f]}else{let d=Q(r).filter(u=>u.command!=="on").sort((u,f)=>f.priority-u.priority);l=this.parseBodyWithClauses(t,d,r)}return fe(a,l,i,{sourceLanguage:r,patternId:e.pattern.id,confidence:e.confidence})}parseBodyWithClauses(e,t,r){let n=[],i=[],s=0,a=[];for(;!e.isAtEnd();){let l=e.peek();if(!l)break;if(i.length===0){let p=this.consumeJsBlock(e,r);if(p){n.push(p);continue}let h=this.tryParseConditionalBlock(e,t,r);if(h){n.push(h);continue}}let c=l.kind==="conjunction"||l.kind==="keyword"&&this.isThenKeyword(l.value,r),d=i[i.length-1],u=e.peek(1),f=d?.value.toLowerCase()==="at"&&u?.value.toLowerCase()==="of"||It(r,l.value,d?.value,u?.value),m=l.kind==="keyword"&&this.isEndKeyword(l.value,r)&&!f;if(m&&s>0){s--,a.pop(),i.push(l),e.advance();continue}if(c&&a.includes("if")){i.push(l),e.advance();continue}if(c){if(i.length>0){let p=this.parseClause(i,t,r);n.push(...p),i.length=0,s=p.filter(h=>{let y=h;return(y.action==="for"||y.action==="repeat"||y.action==="while")&&(!Array.isArray(y.body)||y.body.length===0)}).length,a.length=0;for(let h=0;h<s;h++)a.push("other")}e.advance();continue}if(m){e.advance();let p=[];for(;!e.isAtEnd();){let h=e.peek();if(!h||h.kind==="conjunction"||h.kind==="keyword"&&(this.isThenKeyword(h.value,r)||this.isEndKeyword(h.value,r)))break;p.push(h),e.advance()}if(p.length>0){let h=i.length>0?this.parseClause(i,t,r):[];h.length===0&&i.length>0?n.push(...this.parseClause([...i,...p],t,r)):(n.push(...h),n.push(...this.parseClause(p,t,r)))}else if(i.length>0){let h=this.parseClause(i,t,r);n.push(...h)}i.length=0;break}if(l.kind==="keyword"){let p=(l.normalized??l.value).toLowerCase();(this.isIfKeyword(p,r)||this.isUnlessKeyword(p,r)||p==="while"||p==="for"||p==="repeat")&&(s++,a.push(this.isIfKeyword(p,r)?"if":"other"))}i.push(l),e.advance()}if(i.length>0){let l=this.parseClause(i,t,r);n.push(...l)}this.foldFrontedWhileIntoRepeat(n,r);for(let l=n.length-1;l>=0;l--){let c=n[l];c.kind==="command"&&c.action==="for"&&(!(c.roles instanceof Map)||c.roles.size===0)&&(!Array.isArray(c.body)||c.body.length===0)&&n.splice(l,1)}return n.length>1?[De(n,"then",{sourceLanguage:r})]:n}foldFrontedWhileIntoRepeat(e,t){for(let r=0;r+1<e.length;r++){let n=e[r],i=e[r+1];if(n.kind!=="command"||n.action!=="while"||i.kind!=="command"||i.action!=="repeat")continue;let s=n.roles.get("condition");if(!s||i.roles.has("condition")||Array.isArray(n.body)||Array.isArray(i.body))continue;let a=new Map(i.roles);a.set("condition",s),a.set("loopType",{type:"literal",value:"while",dataType:"string"}),e.splice(r,2,{...i,roles:a,metadata:{...i.metadata,sourceLanguage:t,patternId:`repeat-${t}-fronted-while-fold`,confidence:Math.max(i.metadata?.confidence??0,n.metadata?.confidence??0)}})}}parseClause(e,t,r){if(e.length===0)return[];let n=null,i=e,s=e[e.length-1];if(s&&e.length>=2){let y=(s.normalized??s.value).toLowerCase();this.isUnlessKeyword(y,r)&&(n="unless",i=e.slice(0,-1))}let a=null;if(n&&i.length>=3){let y=V(r),g=y?L.buildVerbLookup(y):null;if(g)for(let S=1;S<i.length-1;S++){let E=i[S],C=g.get(E.value.toLowerCase())??(E.normalized?g.get(E.normalized.toLowerCase()):void 0);if(C&&!L.CONDITION_OPERATORS.has(C)){a=i.slice(0,S),i=i.slice(S);break}}}let l=new H(i,r),c=[],d=0,u=[],f=a,m=()=>{if(u.length===0)return;let y=u.slice();if(u.length=0,n&&c.length===0&&f===null){f=y;return}let g=y[0];if(g&&(g.kind==="identifier"||g.kind==="selector"||g.kind==="literal"||g.kind==="reference"))for(let E of this.parseSOVClauseByVerbAnchoring(y,r)){let C=E.action,k=E.roles;C&&ne(C)&&k instanceof Map&&k.size>0&&c.push(E)}};for(;!l.isAtEnd();){let y=l.peek(),g=!!y&&y.normalized?.toLowerCase()==="repeat",S=l.mark(),E=le.matchBest(l,t);if(g&&E&&E.pattern.command!=="repeat"){l.reset(S),m(),c.push(G("repeat",{},{sourceLanguage:r,confidence:.6})),d++,l.advance();continue}if(E&&E.pattern.command==="if"){let C=l.mark(),k=u.length;for(l.reset(S);!l.isAtEnd();){let T=l.peek();if(!T||this.isIfKeyword((T.normalized??T.value).toLowerCase(),r))break;u.push(T),l.advance()}let x=this.tryParseConditionalBlock(l,t,r);if(x){m(),c.push(x),d++;continue}u.length=k,l.reset(C)}if(E){m();let C=this.buildCommand(E,r);c.push(C),d++,this.tryAttachTrailingRole(l,C,r)}else{let C=l.peek();C&&C.normalized?.toLowerCase()==="repeat"?(m(),c.push(G("repeat",{},{sourceLanguage:r,confidence:.6})),d++):C&&u.push(C),l.advance()}}m();let p=c;if(d===0){let y=this.parseSOVClauseByVerbAnchoring(i,r);y.length>0&&(p=y)}let h=f;return n&&p.length>0&&h&&h.length>0?[G(n,{condition:{type:"expression",raw:this.joinTokenText(h)}},{sourceLanguage:r,patternId:`${n}-${r}-trailing-guard`,confidence:.85}),...p]:p}tryAttachTrailingRole(e,t,r){let n=ne(t.action);if(!n)return;let i=V(r);if(!i)return;let s=t.roles,a=(c,d)=>{if(!c)return!1;if(c.kind==="selector")return!0;let u=(c.normalized??c.value).toLowerCase();return pa.has(u)?!1:u==="body"||u==="it"||u==="you"||u==="result"||u==="document"||u==="window"||this.boundIdentifiers.has(c.value)?!0:d?!1:c.kind==="identifier"||c.kind==="reference"},l=[{role:"source",strict:!1},{role:"destination",strict:!0}];for(let{role:c,strict:d}of l){if(!n.roles.some(y=>y.role===c))continue;let u=i.roleMarkers?.[c];if(!u)continue;let f=s.get(c);if(f&&!(f.type==="reference"&&f.value==="me"))continue;let m=y=>{if(!y||y.kind!=="particle"&&y.kind!=="keyword")return!1;let g=y.value.toLowerCase();return u.primary?.toLowerCase()===g?!0:d?!1:(y.normalized??"").toLowerCase()===c?!0:!!u.alternatives?.some(S=>S.toLowerCase()===g)},p=e.peek(),h=e.peek(1);if(!p||!h)return;if(d&&u.position==="after"){let y=e.peek(2),g=(p.normalized??p.value).toLowerCase();if(ma.has(g)&&h.kind==="selector"&&m(y)){s.set(c,{type:"expression",raw:`${g} ${h.value}`}),e.advance(),e.advance(),e.advance();return}}if(u.position==="after"){if(a(p,d)&&m(h)){let y=this.tokenToSemanticValue(p);e.advance(),e.advance(),y&&s.set(c,y);return}}else if(m(p)&&a(h,d)){e.advance();let y=this.tokenToSemanticValue(e.advance());y&&s.set(c,y);return}}}static buildVerbLookup(e){let t=new Map;for(let[r,n]of Object.entries(e.keywords))if(!["on","if","else","when","where","while","end","then","and"].includes(r)&&(t.set(n.primary.toLowerCase(),r),n.alternatives))for(let i of n.alternatives)t.set(i.toLowerCase(),r);return t}static buildMarkerToRoleLookup(e){let t=new Map;for(let[r,n]of Object.entries(e.roleMarkers)){if(!n)continue;if((r!=="event"||!t.has(n.primary))&&t.set(n.primary,r),n.alternatives)for(let s of n.alternatives)t.has(s)||t.set(s,r)}return t}parseSOVClauseByVerbAnchoring(e,t){let r=V(t);if(!r||r.wordOrder!=="SOV")return[];let n=L.buildVerbLookup(r),i=L.buildMarkerToRoleLookup(r),s=[],a=0;for(;a<e.length;){let l=-1,c="";for(let p=a;p<e.length;p++){let h=e[p];if(i.has(h.value))continue;let y=n.get(h.value.toLowerCase()),g=h.normalized?n.get(h.normalized.toLowerCase()):void 0,S=y||g;if(S){l=p,c=S;break}}if(l===-1)break;let d=e.slice(a,l),u=e.length;for(let p=l+1;p<e.length;p++){let h=e[p];if(h.kind==="conjunction"||this.isThenKeyword(h.value,t)){u=p;break}if(p>l+1&&!i.has(h.value)&&(n.get(h.value.toLowerCase())||(h.normalized?n.get(h.normalized.toLowerCase()):void 0))){u=p;break}}let f=e.slice(l+1,u),m=this.extractRolesFromMarkedTokens(d,f,i,c,t);if(s.push(G(c,m,{sourceLanguage:t,confidence:.7})),a=u,a<e.length){let p=e[a];(p.kind==="conjunction"||this.isThenKeyword(p.value,t))&&a++}}return s}extractRolesFromMarkedTokens(e,t,r,n,i){let s={},a=l=>{let c=[];for(let d of l){let u=r.get(d.value);if(u&&d.kind==="particle"&&c.length>0){let f=this.tokensToSemanticValue(c);if(f){let m=this.mapRoleForCommand(u,n,s);m&&(s[m]=f)}c=[]}else c.push(d)}if(c.length>0)if(c.length===1&&/^\d+(\.\d+)?(ms|s)$/i.test(c[0].value)&&!s.duration&&ne(n)?.roles.some(u=>u.role==="duration"))s.duration={type:"literal",value:c[0].value,dataType:"string"};else{let u=this.tokensToSemanticValue(c);u&&(s.patient?s.destination||(s.destination=u):s.patient=u)}};return a(e),a(t),s}mapRoleForCommand(e,t,r){return r[e]?e==="patient"&&!r.destination?"destination":e==="destination"&&!r.patient?"patient":e==="source"&&!r.source?"source":null:e}tokensToSemanticValue(e){if(e.length===0)return null;let t=e.filter(i=>i.kind!=="whitespace");if(t.length===0)return null;if(t.length===1)return this.tokenToSemanticValue(t[0]);let r=t.map(i=>i.value).join(""),n=t[0];return n.kind==="selector"||n.value.startsWith("#")||n.value.startsWith(".")||n.value.startsWith("@")||n.value.startsWith("*")?re(r):n.kind==="literal"||n.value.startsWith('"')||n.value.startsWith("'")?$(Wr(r),"string"):n.kind==="reference"?J(r):$(r)}tokenToSemanticValue(e){let t=e.value;if(e.kind==="selector"||t.startsWith("#")||t.startsWith(".")||t.startsWith("@")||t.startsWith("*"))return re(t);if(t.startsWith('"')||t.startsWith("'"))return $(Wr(t),"string");if(/^-?\d+(\.\d+)?$/.test(t))return $(parseFloat(t));if(t==="true"||t==="\u771F"||t==="\uCC38"||t==="do\u011Fru")return $(!0);if(t==="false"||t==="\u507D"||t==="\uAC70\uC9D3"||t==="yanl\u0131\u015F")return $(!1);let r=e.normalized?.toLowerCase();return r==="me"||r==="it"||r==="you"||r==="result"||r==="body"?J(r):e.kind==="reference"?J(e.normalized||"me"):$(t)}parseBodyWithGrammarPatterns(e,t,r,n){let i=[],s=[],a=!1,l=()=>{!a&&s.length>0&&i.push(...this.parseSOVClauseByVerbAnchoring(s,n)),s=[],a=!1},c=0,d=()=>{let u=0;for(let f of i){let m=f;(m.action==="for"||m.action==="repeat"||m.action==="while")&&(!Array.isArray(m.body)||m.body.length===0)&&u++}return u-c};for(;!e.isAtEnd();){let u=e.peek();if(u&&this.isThenKeyword(u.value,n)){l(),e.advance();continue}if(u&&this.isEndKeyword(u.value,n)){let m=e.peek(-1),p=e.peek(1);if(!It(n,u.value,m?.value,p?.value)){if(l(),d()>0){c++,e.advance();continue}e.advance();break}}if(u&&!a&&this.isIfKeyword((u.normalized??u.value).toLowerCase(),n)){l();let m=this.tryParseConditionalBlock(e,t,n);if(m){i.push(m),a=!0;continue}}let f=!1;if(r.length>0){let m=le.matchBest(e,r);if(m){let p=m.pattern.command,h={};for(let[S,E]of m.captured)S!=="event"&&S!=="action"&&S!=="continues"&&(h[S]=E);let y=G(p,h,{sourceLanguage:n,patternId:m.pattern.id});i.push(y),f=!0,a=!0;let g=m.captured.get("continues");if(g&&g.type==="literal"&&g.value==="then")continue}}if(!f){let m=e.mark(),p=le.matchBest(e,t);if(p){if(p.pattern.command==="if"){let y=e.mark();for(e.reset(m);!e.isAtEnd();){let S=e.peek();if(!S||this.isIfKeyword((S.normalized??S.value).toLowerCase(),n))break;e.advance()}let g=this.tryParseConditionalBlock(e,t,n);if(g){l(),i.push(g),a=!0;continue}e.reset(y)}let h=this.buildCommand(p,n);i.push(h),this.tryAttachTrailingRole(e,h,n),f=!0,a=!0}}f||(u&&s.push(u),e.advance())}l();for(let u=i.length-1;u>=0;u--){let f=i[u];f.kind==="command"&&f.action==="for"&&(!(f.roles instanceof Map)||f.roles.size===0)&&(!Array.isArray(f.body)||f.body.length===0)&&i.splice(u,1)}return i}tryCompoundCommandParsing(e,t,r){let n=e.tokens,i=n.some(c=>c.kind==="conjunction"||c.kind==="keyword"&&this.isThenKeyword(c.value,r)),s=n.some(c=>this.isElseKeyword(c.value,r));if(!i&&!s)return null;let a=new H(n,r),l=this.parseBodyWithClauses(a,t,r);return l.length===0?null:l.length===1?l[0]:De(l,"then",{sourceLanguage:r,confidence:.65})}matchEventMarkerPhrase(e,t,r){let n=L.SOV_EVENT_MARKER_PHRASES[r];if(!n)return 0;for(let i of n)if(i.every((s,a)=>e[t+a]?.value===s))return i.length;return 0}hasSOVEventMarkerHead(e,t){let r=L.SOV_EVENT_MARKERS[t];if(r===void 0)return!1;let{tokens:n}=Y(e,t),i=Se[t],s=new Set;if(i)for(let a of Object.keys(i))s.add(a.toLowerCase());for(let a=0;a<n.length;a++){let l=n[a],c=l.value.toLowerCase(),d=l.normalized?.toLowerCase();if(!(!!d&&(L.KNOWN_EVENTS.has(d)||Ae.has(d))||L.KNOWN_EVENTS.has(c)||Ae.has(c)||s.has(c)))continue;let f=this.matchEventParamPhrase(n,a+1).len,m=n[a+1+f];if(m&&(m.kind==="particle"||m.kind==="keyword")&&r.has(m.value)||this.matchEventMarkerPhrase(n,a+1+f,t)>0)return!0}return!1}matchEventParamPhrase(e,t){if(e[t]?.value!=="(")return{len:0,names:[]};let r=[];for(let n=t+1;n<e.length;n++){let i=e[n].value;if(i===")")return{len:n-t+1,names:r};if(i!==","){if(e[n].kind!=="identifier")break;r.push(i)}}return{len:0,names:[]}}isStrippableSourceRef(e,t){if(!e)return!1;let r=e.normalized?.toLowerCase();if(e.kind==="keyword"&&(r==="me"||r==="i"||r==="it"))return!0;let n=e.value.toLowerCase();return t.has(n)||!!r&&t.has(r)}tryTrailingEventExtraction(e,t,r){let n=Y(e,t).tokens;if(n.length<3)return null;let i=Se[t],s=new Set;if(i)for(let E of Object.keys(i))s.add(E.toLowerCase());let a=n.length-2,l=n[a];if(!(l.kind==="keyword"&&l.normalized?.toLowerCase()==="on"))return null;let d=n[n.length-1],u=d.value.toLowerCase(),f=d.normalized?.toLowerCase();if(!(!!f&&L.KNOWN_EVENTS.has(f)||L.KNOWN_EVENTS.has(u)||s.has(u)))return null;let p=f&&L.KNOWN_EVENTS.has(f)?f:i?.[u]??u,h=n.slice(0,a);if(h.length===0)return null;let y=r.filter(E=>E.command!=="on"),g=new H(h,t),S=this.parseBodyWithClauses(g,y,t);return S.length===0?null:fe({type:"literal",value:p},S,void 0,{sourceLanguage:t,confidence:.75})}tryMidStreamEventExtraction(e,t,r){let n=Y(e,t).tokens;if(n.length<3)return null;let i=Se[t],s=new Set;if(i)for(let a of Object.keys(i))s.add(a.toLowerCase());for(let a=0;a<n.length-1;a++){let l=n[a];if(!(l.kind==="keyword"&&l.normalized?.toLowerCase()==="on"))continue;let d=n[a+1],u=d.value.toLowerCase(),f=d.normalized?.toLowerCase();if(!(!!f&&L.KNOWN_EVENTS.has(f)||L.KNOWN_EVENTS.has(u)||s.has(u)))continue;let p=f&&L.KNOWN_EVENTS.has(f)?f:i?.[u]??u,h=n.filter((E,C)=>C!==a&&C!==a+1);if(h.length===0)return null;let y=r.filter(E=>E.command!=="on"),g=new H(h,t),S=this.parseBodyWithClauses(g,y,t);return S.length===0?null:fe({type:"literal",value:p},S,void 0,{sourceLanguage:t,confidence:.75})}return null}trySOVEventExtraction(e,t,r){let n=L.SOV_EVENT_MARKERS[t];if(!n)return null;let s=Y(e,t).tokens,a=Se[t],l=new Set;if(a)for(let k of Object.keys(a))l.add(k.toLowerCase());let c=L.SOV_SOURCE_MARKERS[t],d=-1,u="",f="",m=1,p=[];for(let k=0;k<s.length;k++){let x=s[k],T=x.value.toLowerCase(),v=T,b="",N=T.indexOf("[");N>0&&(v=T.slice(0,N),b=x.value.slice(N));let P=x.normalized?.toLowerCase(),z=P&&(L.KNOWN_EVENTS.has(P)||Ae.has(P)),M=l.has(T)||l.has(v),O=L.KNOWN_EVENTS.has(v)||Ae.has(v);if(z||M||O){let D=s[k-1];if(D&&(D.normalized??D.value).toLowerCase()==="event")continue;let I;z?I=P:M?I=a?.[T]??a?.[v]??v:I=v;let K=this.matchEventParamPhrase(s,k+1);if(n.size>0){let U=1+K.len,he=s[k+U];he&&he.kind==="selector"&&he.value.startsWith("[")&&(U+=1);let oe=s[k+U];if(oe&&(oe.kind==="particle"||oe.kind==="keyword")&&n.has(oe.value)){d=k,u=I,f=b||(U===K.len+2?s[k+U-1].value:""),m=U+1,p=K.names;break}}else{d=k,u=I,f=b,m=1+K.len+this.matchEventMarkerPhrase(s,k+1+K.len,t),p=K.names;break}}}if(d===-1){let k=new Set(r.filter(x=>x.command!=="on").map(x=>x.command));for(let x=0;x<s.length;x++){let T=s[x];if(T.kind==="identifier")if(n.size>0){let v=1,b=s[x+1];b&&b.kind==="selector"&&b.value.startsWith("[")&&(v=2);let N=s[x+v];if(N&&(N.kind==="particle"||N.kind==="keyword")&&n.has(N.value)){d=x,u=T.value,f=v===2?s[x+1].value:"",m=v+1;break}}else{let v=this.matchEventMarkerPhrase(s,x+1,t);if(v>0){d=x,u=T.value,f="",m=1+v;break}let b=s[x+1];if(b&&b.kind==="keyword"&&b.normalized!=null&&k.has(b.normalized)){d=x,u=T.value,f="",m=1;break}}}}if(d===-1)return null;let h=new Set;for(let k=d;k<d+m;k++)h.add(k);if(c){let k=d+m;if(k<s.length){let x=s[k];if((x.kind==="particle"||x.kind==="keyword")&&c.markers.has(x.value))h.add(k);else if(this.isStrippableSourceRef(x,c.windowTokens)){let T=s[k+1];T&&(T.kind==="particle"||T.kind==="keyword")&&c.markers.has(T.value)&&(h.add(k),h.add(k+1))}}if(d>=2){let x=s[d-1];(x.kind==="particle"||x.kind==="keyword")&&c.markers.has(x.value)&&this.isStrippableSourceRef(s[d-2],c.windowTokens)&&(h.add(d-2),h.add(d-1))}for(let x=0;x<d;x++){let T=s[x],v=T.value.toLowerCase(),b=T.normalized?.toLowerCase();if(c.windowTokens.has(v)||b&&c.windowTokens.has(b)){h.add(x);break}}}let y=s.filter((k,x)=>!h.has(x));if(y.length===0)return null;let g=r.filter(k=>k.command!=="on"),S=new H(y,t),E=this.parseBodyWithClauses(S,g,t);if(E.length===0)return null;let C={sourceLanguage:t,confidence:.75};return f&&(C.keyFilter=f),fe({type:"literal",value:u},E,void 0,C,p)}profileKeywordMatches(e,t,r){let n=V(e)?.keywords?.[t];return n?n.primary?.toLowerCase()===r?!0:!!n.alternatives?.some(i=>i.toLowerCase()===r):!1}consumeForPostposition(e,t){let r=e.peek();if(!r)return;let n=(r.normalized??"").toLowerCase(),i=V(t)?.keywords?.for;(n==="for"||r.value===i?.primary||(i?.alternatives??[]).includes(r.value))&&e.advance()}isThenKeyword(e,t){let r=e.toLowerCase(),i={en:new Set(["then"]),ja:new Set(["\u305D\u308C\u304B\u3089","\u6B21\u306B","\u305D\u3057\u3066"]),ar:new Set(["\u062B\u0645","\u0628\u0639\u062F\u0647\u0627","\u062B\u0645\u0651"]),es:new Set(["entonces","luego","despu\xE9s"]),ko:new Set(["\uADF8\uB2E4\uC74C","\uADF8\uB9AC\uACE0","\uADF8\uB7F0\uD6C4","\uADF8\uB7EC\uBA74"]),zh:new Set(["\u7136\u540E","\u63A5\u7740","\u90A3\u4E48"]),tr:new Set(["ard\u0131ndan","daha sonra","ardindan"]),pt:new Set(["ent\xE3o","depois","logo"]),fr:new Set(["puis","ensuite","alors"]),de:new Set(["dann","danach","anschlie\xDFend"]),id:new Set(["lalu","kemudian","setelah itu"]),tl:new Set(["pagkatapos","tapos"]),bn:new Set(["\u09A4\u09BE\u09B0\u09AA\u09B0"]),qu:new Set(["chaymantataq","hinaspa","chaymanta","chayqa"]),sw:new Set(["kisha","halafu","baadaye"])}[t];return i?i.has(r):r==="then"||this.profileKeywordMatches(t,"then",r)}isElseKeyword(e,t){let r=e.toLowerCase();return r==="else"?!0:this.profileKeywordMatches(t,"else",r)}isEndKeyword(e,t){let r=e.toLowerCase(),i={en:new Set(["end"]),ja:new Set(["\u7D42\u308F\u308A","\u304A\u308F\u308A"]),ar:new Set(["\u0646\u0647\u0627\u064A\u0629","\u0627\u0646\u062A\u0647\u0649","\u0627\u0644\u0646\u0647\u0627\u064A\u0629"]),es:new Set(["fin","final","terminar"]),ko:new Set(["\uB05D","\uB9C8\uCE68"]),zh:new Set(["\u7ED3\u675F","\u7EC8\u6B62","\u5B8C"]),tr:new Set(["son","biti\u015F","bitti"]),pt:new Set(["fim","final","t\xE9rmino"]),fr:new Set(["fin","terminer","finir"]),de:new Set(["ende","fertig"]),id:new Set(["selesai","akhir","tamat"]),tl:new Set(["wakas","tapos"]),bn:new Set(["\u09B8\u09AE\u09BE\u09AA\u09CD\u09A4"]),qu:new Set(["tukukuy","tukuy","puchukay"]),sw:new Set(["mwisho","maliza","tamati"])}[t];return i?r==="end"||i.has(r):r==="end"||this.profileKeywordMatches(t,"end",r)}isJsKeyword(e){let t=(e.normalized??e.value).toLowerCase();return t==="js"||this.profileKeywordMatches("en","js",t)}consumeJsBlock(e,t){let r=e.peek();if(!r||!this.isJsKeyword(r))return null;let n=e.mark(),i=[];e.advance();let s=!1;for(;!e.isAtEnd();){let l=e.peek();if(!l)break;if(e.advance(),this.isEndKeyword(l.value,t)){s=!0;break}i.push(l)}if(!s)return e.reset(n),null;let a=i.map(l=>l.value).join(" ").trim();return G("js",{patient:{type:"expression",raw:a||"()"}},{sourceLanguage:t,patternId:`js-opaque-${t}`,confidence:1})}isIfKeyword(e,t){let r=e.toLowerCase();return r==="if"?!0:this.profileKeywordMatches(t,"if",r)}isUnlessKeyword(e,t){let r=e.toLowerCase();return r==="unless"?!0:this.profileKeywordMatches(t,"unless",r)}isBlockEndToken(e,t,r){return this.isEndKeyword(e.value,r)?!0:e.kind!=="keyword"||(e.normalized??"").toLowerCase()!=="end"?!1:!(t&&t.kind==="selector")}tryParseConditionalBlock(e,t,r){let n=e.peek();if(!n)return null;let i=(n.normalized??n.value).toLowerCase();if(!this.isIfKeyword(i,r))return null;let s=e.mark();e.advance();let a=[],l=0;for(;!e.isAtEnd();){let x=e.peek();if(!x)break;let T=(x.normalized??x.value).toLowerCase();if(this.isIfKeyword(T,r)||this.isUnlessKeyword(T,r)){l++,a.push(x),e.advance();continue}if(this.isBlockEndToken(x,e.peek(1)??void 0,r)){if(l===0){e.advance();break}l--,a.push(x),e.advance();continue}a.push(x),e.advance()}if(a.length===0)return e.reset(s),null;let c=V(r),d=c?.wordOrder==="SOV"?L.buildVerbLookup(c):null,u=0,f=0,m=[],p=!1;for(;u<a.length;u++){let x=a[u],T=(x.normalized??x.value).toLowerCase();if(this.isIfKeyword(T,r)||this.isUnlessKeyword(T,r)?f++:this.isBlockEndToken(x,a[u+1],r)&&f--,f===0&&this.isThenKeyword(x.value,r)){p=!0,u++;break}if(f===0&&m.length>0){let v=(a[u-1].normalized??a[u-1].value).toLowerCase(),b=a[u-1].value.toLowerCase(),N=(x.normalized??x.value).toLowerCase(),P=L.CONDITION_COPULAS.has(v)||L.CONDITION_COPULAS_SURFACE.has(b)&&L.CONDITION_PREDICATES.has(N),z=d!==null&&d.has(x.value.toLowerCase())&&!L.CONDITION_PREDICATES.has(N);if(!L.CONDITION_OPERATORS.has(N)&&(!P||z)&&(this.tokensBeginCommand(a.slice(u),t,r)||this.sovCommandStartsAt(a.slice(u),d)))break}m.push(x)}if(m.length===0)return e.reset(s),null;let h=[],y=[],g=!1,S=0;for(;u<a.length;u++){let x=a[u],T=(x.normalized??x.value).toLowerCase();if(this.isIfKeyword(T,r)||this.isUnlessKeyword(T,r)?S++:this.isBlockEndToken(x,a[u+1],r)&&S--,S===0&&!g&&this.isElseKeyword(x.value,r)){g=!0;continue}(g?y:h).push(x)}let E={type:"expression",raw:this.joinTokenText(m)},C=this.parseBranch(h,t,r),k=y.length>0?this.parseBranch(y,t,r):void 0;return C.length===0&&(!k||k.length===0)?(e.reset(s),null):kr(E,C,k,{sourceLanguage:r,patternId:`conditional-${r}-folded`,confidence:1})}joinTokenText(e){return e.map(t=>t.kind==="keyword"?t.normalized??t.value:t.value).join(" ").trim()}tokensBeginCommand(e,t,r){if(e.length===0)return!1;let n=new H(e,r);return le.matchBest(n,t)!==null}sovCommandStartsAt(e,t){if(!t)return!1;let r=a=>t.has(a.value.toLowerCase())||!!a.normalized&&t.has(a.normalized.toLowerCase()),n=a=>a.kind==="identifier"||a.kind==="selector"||a.kind==="literal"||a.kind==="reference",i=0,s=0;for(;i+1<e.length;){let a=e[i],l=e[i+1];if(!n(a)||l.kind!=="particle")break;s+=1,i+=2;let c=e[i];if(s>=1&&c&&r(c))return!0}return!1}parseBranch(e,t,r){if(e.length===0)return[];let n=new H(e,r),i=this.parseBodyWithClauses(n,t,r);return i.length===1&&i[0]?.kind==="compound"?i[0].statements:i}extractStandaloneModifiers(e,t){let n=Y(e,t).tokens;if(n.length===0)return{modifiers:null,remainingInput:null};let s=n[0].value.toLowerCase(),a=L.STANDALONE_MODIFIERS[s];if(!a)return{modifiers:null,remainingInput:null};let l={},c=1;if(a==="once")l.once=!0;else{let m=1;if(m<n.length){let p=n[m];(p.kind==="keyword"||p.kind==="particle")&&(m++,c++)}if(m<n.length){let p=n[m];if(p.kind==="literal"){let h=p.value.match(/^(\d+)(ms|s|m)?$/);if(h){let y=parseInt(h[1],10),g=h[2]||"ms";g==="s"?y*=1e3:g==="m"&&(y*=6e4),l[a]=y,c=m+1}}}l[a]||(l[a]=a==="debounce"?300:100)}let d=n.slice(c);if(d.length===0)return{modifiers:null,remainingInput:null};let u=d[0].position.start,f=e.slice(u);return{modifiers:l,remainingInput:f}}stripAsyncModifier(e,t){let r=V(t)?.keywords?.async,n=new Set(["async"]);r?.primary&&n.add(r.primary.toLowerCase()),r?.alternatives?.forEach(c=>n.add(c.toLowerCase()));let i=Y(e,t).tokens,s=i.findIndex(c=>n.has(c.value.toLowerCase()));if(s===-1)return{remainingInput:null};let a=i[s],l=(e.slice(0,a.position.start)+e.slice(a.position.end)).replace(/\s{2,}/g," ").trim();return l.length===0?{remainingInput:null}:{remainingInput:l}}stripDoNotThrowModifier(e,t){let r=Y(e,t).tokens;for(let n=0;n<r.length-1;n++){if(r[n].value.toLowerCase()!=="do")continue;let i=-1;for(let c=n+1;c<=n+5&&c<r.length;c++){let d=r[c];if(d.normalized?.toLowerCase()==="throw"){i=c;break}let u=d.kind;if(u==="selector"||u==="literal"||u==="reference"||u==="conjunction")break}if(i===-1)continue;let s=r[n].position.start,a=r[i].position.end,l=(e.slice(0,s)+e.slice(a)).replace(/\s{2,}/g," ").trim();return l.length===0?{remainingInput:null}:{remainingInput:l}}return{remainingInput:null}}applyModifiers(e,t){return{...e,eventModifiers:{...e.eventModifiers,...t}}}extractOrConjunctionEvents(e,t){let r=[];for(;;){let n=e.mark(),i=e.peek();if(!i)break;let s=(i.normalized||i.value).toLowerCase();if(!L.OR_KEYWORDS.has(s)){e.reset(n);break}e.advance();let a=e.peek();if(!a){e.reset(n);break}let l=(a.normalized||a.value).toLowerCase();e.advance(),r.push({type:"literal",value:l})}return r}};L.KNOWN_EVENTS=new Set(["click","dblclick","input","change","submit","keydown","keyup","keypress","mouseover","mouseout","mousedown","mouseup","focus","blur","load","scroll","resize","contextmenu"]),L.RESPONSE_TYPE_WORDS=new Set(["json","text","html","xml","blob","arraybuffer","formdata","response"]),L.SOV_EVENT_MARKERS={ja:new Set(["\u3067"]),ko:new Set,tr:new Set(["de","da","te","ta"]),bn:new Set(["\u098F"]),qu:new Set(["pi"]),hi:new Set(["\u092A\u0930"])},L.SOV_EVENT_MARKER_PHRASES={ko:[["\uD560","\uB54C"],["\uD560\uB54C"]]},L.SOV_SOURCE_MARKERS={ja:{markers:new Set(["\u304B\u3089"]),windowTokens:new Set(["\u30A6\u30A3\u30F3\u30C9\u30A6","\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8","window","document"])},ko:{markers:new Set(["\uC5D0\uC11C"]),windowTokens:new Set(["\uCC3D","\uC708\uB3C4\uC6B0","\uBB38\uC11C","window","document"])},tr:{markers:new Set(["den","dan","ten","tan"]),windowTokens:new Set(["pencere","belge","window","document"])},bn:{markers:new Set(["\u09A5\u09C7\u0995\u09C7","\u09AE\u09A7\u09CD\u09AF\u09C7"]),windowTokens:new Set(["\u0989\u0987\u09A8\u09CD\u09A1\u09CB","\u09A1\u0995\u09C1\u09AE\u09C7\u09A8\u09CD\u099F","window","document"])},qu:{markers:new Set(["manta"]),windowTokens:new Set(["k_iri","ventana","window","document"])},hi:{markers:new Set(["\u0938\u0947"]),windowTokens:new Set(["\u0935\u093F\u0902\u0921\u094B","\u0926\u0938\u094D\u0924\u093E\u0935\u0947\u091C\u093C","window","document"])}},L.CONDITION_COPULAS=new Set(["is","am","are","be","was","were","not","no"]),L.CONDITION_COPULAS_SURFACE=new Set(["est","\u0435\u0441\u0442\u044C","\u0454","\xE9","ay","\u0647\u0648","adalah","\u0E40\u0E1B\u0E47\u0E19","\u09B9\u09AF\u09BC","\u0939\u0948","dir","kanqa"]),L.CONDITION_PREDICATES=new Set(["empty","null","undefined"]),L.CONDITION_OPERATORS=new Set(["matches","match","contains","exists","has","have","equals","includes"]),L.STANDALONE_MODIFIERS={once:"once",debounced:"debounce",debounce:"debounce",throttled:"throttle",throttle:"throttle"},L.OR_KEYWORDS=new Set(["or","\u0623\u0648","o","ou","oder","atau","atau","\u6216","\u307E\u305F\u306F","\uB610\uB294","veya","\u0985\u09A5\u09AC\u09BE","utaq","au","\u0430\u0431\u043E","\u0438\u043B\u0438","ho\u1EB7c","lub","\u05D0\u05D5","\u0E2B\u0E23\u0E37\u0E2D","o","\u092F\u093E","\u0985\u09A5\u09AC\u09BE"]);var vt=L,Kt=new vt;function Me(o,e){return Kt.parse(o,e)}function Ft(o,e){return Kt.canParse(o,e)}function Ut(o,e){if(me(o))return o;let t=Me(o,e);return Ye(t)}function Ht(o,e){let t=Re(o);return Ge(t,e)}function Gt(o,e){return me(o)?Re(o):Me(o,e)}Tt("ar",mt,xe);var ha="1.0.0-ar",ya=["ar"];function ga(){return[...ya]}function qr(o){if(o!=="ar")throw new Error(`Language not supported in this bundle: ${o}. Supported: ar`)}function va(o,e){return qr(e),[...Y(o,e).tokens]}function Kr(o){return qr(o),Q(o)}function xa(o,e){return Kr(o).filter(t=>t.command===e).sort((t,r)=>r.priority-t.priority)}return Jr(ka);})();
5
+ `)}getChainWord(e,t){let r=I(t);return r?.keywords?r.keywords[e]?.primary??e:e}renderExplicit(e){return ee(e)}supportedLanguages(){return ft()}findBestPattern(e,t){let r=t;if(e.kind==="event-handler"){let i=t.filter(s=>!/-event-/i.test(s.id));i.length>0&&(r=i)}let n=r.map(i=>{let s=i.priority;for(let a of i.template.tokens)a.type==="role"&&(e.roles.has(a.role)?s+=10:a.optional||(s-=50));return/-at-end|-at-start|-before$|-after$/i.test(i.id)&&(s-=30),i.language==="en"&&((i.id.includes("standard")||i.id.includes("en-source"))&&(s+=20),(i.id.includes("-when")||i.id.includes("-if")||i.id.includes("-upon"))&&(s-=15)),{pattern:i,score:s}});return n.sort((i,s)=>s.score-i.score),n.length>0?n[0].pattern:null}renderWithPattern(e,t){let r=[],n=t.language;for(let i of t.template.tokens){let s=this.renderPatternToken(i,e,n);s!==null&&r.push(s)}if(e.kind==="event-handler"){let i=e;if(i.body&&i.body.length>0){let s=i.body.map(a=>this.render(a,n));r.push(s.join(" "))}}return r.join(" ")}renderPatternToken(e,t,r){switch(e.type){case"literal":return e.value;case"role":{let n=t.roles.get(e.role);return n?e.role==="event"&&t.kind==="event-handler"?this.renderEventName(n,r):this.valueToNaturalString(n,r):(e.optional,null)}case"group":{if(!e.tokens.filter(a=>a.type==="role"&&!a.optional).every(a=>t.roles.has(a.role))&&e.optional)return null;if(e.optional&&e.tokens.find(l=>l.type==="role"&&l.role==="destination")){let l=t.roles.get("destination");if(l?.type==="reference"&&l.value==="me")return null}if(e.optional&&e.tokens.find(l=>l.type==="role"&&l.role==="quantity")){let l=t.roles.get("quantity");if(l?.type==="literal"&&Number(l.value)===1)return null}let i=[],s=!1;for(let a of e.tokens){let l=this.renderPatternToken(a,t,r);l!==null&&(i.push(l),a.type==="role"&&(s=!0))}return e.optional&&!s?null:i.length>0?i.join(" "):null}default:return null}}renderEventName(e,t){if(e.type!=="literal"||typeof e.value!="string")return this.valueToNaturalString(e,t);let r=e.value,n=i=>i.includes(":")?i:$r(i,t);return r.includes(" or ")?r.split(" or ").map(i=>n(i.trim())).join(" or "):n(r)}valueToNaturalString(e,t="en"){switch(e.type){case"literal":return typeof e.value=="string"&&e.dataType==="string"?`"${e.value}"`:String(e.value);case"selector":return e.value;case"reference":return this.renderReference(e,t);case"property-path":return this.renderPropertyPath(e,t);case"expression":return e.raw;case"flag":return e.name}}renderReference(e,t){let r=I(t);return r?.references?r.references[e.value]??e.value:e.value}renderPropertyPath(e,t){let r=I(t),n=e.property,i=e.object.type==="reference"?e.object.value:null;if(r?.possessive?.specialForms&&i){let a=r.possessive.specialForms[i];if(a){let{markerPosition:l,usePossessiveAdjectives:c}=r.possessive;return c&&l==="after-object"?`${n} ${a}`:`${a} ${n}`}}let s=this.valueToNaturalString(e.object,t);if(r?.possessive){let{marker:a,markerPosition:l,usePossessiveAdjectives:c}=r.possessive;if(c&&i&&l==="after-object")return`${n} ${s}`;if(a)switch(l){case"between":return r.usesSpaces?`${s}${a} ${n}`:`${s}${a}${n}`;case"after-object":return`${s}${a} ${n}`;case"before-property":return`${s} ${a} ${n}`}}return t==="en"||!r?.possessive?s==="me"?`my ${n}`:s==="it"?`its ${n}`:`${s}'s ${n}`:`${s} ${n}`}},qt=new gt;function Ge(o,e){return qt.render(o,e)}function Ye(o){return qt.renderExplicit(o)}var da={getSchema:ne};function Re(o){return nt(o,{schemaLookup:da})}var Le=new Set(["if","unless","while","repeat","for"]),pa=new Set(["then","end","else","if","unless","while","for","repeat","and"]),ma=new Set(["first","last","next","previous","random","closest"]),Ae=new Set(["click","dblclick","input","change","submit","keydown","keyup","keypress","mouseover","mouseout","mousedown","mouseup","focus","blur","load","scroll","resize","contextmenu","transitionend","transitionstart","transitionrun","transitioncancel","animationend","animationstart","animationiteration","animationcancel","pointerdown","pointerup","pointermove","pointerenter","pointerleave","pointercancel","pointerover","pointerout","touchstart","touchend","touchmove","touchcancel","mousemove","mouseenter","mouseleave","wheel","dragstart","dragend","dragover","dragenter","dragleave","drop","drag","loadend","loadstart","error","abort","close","open","message","popstate","hashchange","storage","online","offline","visibilitychange"]),Ze=class extends Error{constructor(e,t,r,n){super(e),this.name="SemanticParseError",this.language=t,this.input=r,this.diagnostics=n}};function W(o,e,t){return{message:o,severity:e,source:"semantic-parser",...t&&{code:t}}}function X(o,e){return e.length===0?o:{...o,diagnostics:e}}function Wr(o){if(o.length>=2){let e=o[0];if((e==='"'||e==="'")&&o.endsWith(e))return o.slice(1,-1)}return o}var fa=["body","statements","thenBranch","elseBranch","eventHandlers","initBlock"];function jr(o,e){if(!o||typeof o!="object")return o;if(o.action&&o.roles instanceof Map){let r=ne(o.action),n=r?.primaryRole;if(r&&n&&n!=="patient"&&!r.roles.some(i=>i.role==="patient")&&o.roles.has("patient")&&!o.roles.has(n)){let i=o.roles,s=i.get("patient");s!==void 0&&(i.delete("patient"),i.set(n,s))}if(o.action==="tell"){let i=o.roles,s=i.get("patient"),a=i.get("destination");s&&(s.type==="selector"||s.type==="reference")&&(!a||a.type==="literal")&&(i.delete("patient"),i.set("destination",s))}if(o.action==="transition"){let i=o.roles,s=i.get("destination");s&&s.type==="literal"&&!i.has("goal")&&(i.delete("destination"),i.set("goal",s));let a=i.get("patient");a&&a.type==="literal"&&typeof a.value=="string"&&/^[A-Za-z_][A-Za-z0-9_-]*$/.test(a.value)&&i.set("patient",{type:"expression",raw:a.value})}if(o.action==="morph"){let i=o.roles,s=i.get("patient");s&&s.type==="literal"&&typeof s.value=="string"&&/<[a-zA-Z][^>]*\/?>/.test(s.value)&&i.set("patient",{type:"expression",raw:s.value})}if(o.action==="wait"){let i=o.roles;if(!i.has("event")){let s=i.get("duration"),a=s?.type==="expression"?s.raw:s?.type==="literal"?s.value:void 0;typeof a=="string"&&Ae.has(a.toLowerCase())&&(i.delete("duration"),i.set("event",{type:"literal",value:a,dataType:"string"}))}}if(o.kind==="command"&&o.action!=="on"){let i=o.roles,s=i.get("event");if(s&&s.type==="expression"){let a=s.raw;typeof a=="string"&&/^[A-Za-z_][A-Za-z0-9_-]*(:[A-Za-z0-9_-]+)?$/.test(a)&&i.set("event",{type:"literal",value:a,dataType:"string"})}}if(e?.size){let i=o.roles;for(let s of["destination","source"]){let a=i.get(s);a&&a.type==="literal"&&typeof a.value=="string"&&e.has(a.value)&&i.set(s,{type:"expression",raw:a.value})}}}let t=o;for(let r of fa){let n=t[r];if(Array.isArray(n))for(let i of n)jr(i,e)}return o}var L=class L{constructor(){this.parseDepth=0;this.boundIdentifiers=new Set}parse(e,t){this.parseDepth===0&&this.boundIdentifiers.clear(),this.parseDepth++;try{return jr(this.parseInternal(e,t),this.boundIdentifiers)}finally{this.parseDepth--}}registerBoundIdentifiers(e){let t=e.action==="repeat"||e.action==="for"?"patient":e.action==="set"?"destination":null;if(!t)return;let r=e.roles.get(t);r?.type==="expression"&&typeof r.raw=="string"&&/^[A-Za-z_]\w*$/.test(r.raw)&&this.boundIdentifiers.add(r.raw)}parseInternal(e,t){let r=_r(e,t,{statement:(v,b)=>this.parse(v,b),body:(v,b)=>this.parseStatements(v,b)});if(r)return r;let n=Br(e,t,{statement:(v,b)=>this.parse(v,b),body:(v,b)=>this.parseStatements(v,b)});if(n)return n;let{modifiers:i,remainingInput:s}=this.extractStandaloneModifiers(e,t),a=s||e,c=this.stripAsyncModifier(a,t).remainingInput??a,u=this.stripDoNotThrowModifier(c,t).remainingInput??c,f=[],m=Y(u,t),p=Q(t);if(p.length===0)throw new Ze(`No patterns available for language: ${t}`,t,u,[W(`No patterns registered for language '${t}'`,"error","no-patterns")]);let h=[...p].sort((v,b)=>b.priority-v.priority);{let v=m.tokens;if(I(t)?.wordOrder==="VSO"&&v.length>=4&&v[0]?.normalized==="source"){let b=v.findIndex(N=>N.normalized==="on");if(b>=2&&b+1<v.length){let N=u.slice(v[0].position.start,v[b].position.start).trim(),P=v[b+1].position.end,z=u.slice(v[b].position.start,P)+" "+N+u.slice(P);if(z!==u)try{let M=this.parse(z,t);if(M&&M.kind==="event-handler"){let O=i?this.applyModifiers(M,i):M;return X(O,f)}}catch{}}}}{let v=m.tokens;for(let b=1;b<v.length-1;b++){let N=v[b],P=N.value,z=(N.normalized??N.value).toLowerCase();if(!(z==="or"||L.OR_KEYWORDS.has(P)||L.OR_KEYWORDS.has(z)))continue;let O=v[b+1],D=(O.normalized??O.value).toLowerCase();if(!L.KNOWN_EVENTS.has(D))break;let V=b+1,K=v[b+2];K&&K.kind==="selector"&&K.value.startsWith("[")&&(V=b+2);let U=v[b].position.start,he=v[V].position.end,oe=(u.slice(0,U).trimEnd()+" "+u.slice(he).trimStart()).trim();if(oe&&oe!==u)try{let ye=this.parse(oe,t);if(ye&&ye.kind==="event-handler"){ye.additionalEvents=[{type:"literal",value:D}];let kt=i?this.applyModifiers(ye,i):ye;return X(kt,f)}}catch{}break}}let y=h.filter(v=>v.command==="on"),g=m.mark(),S=le.matchBest(m,y);if(S){f.push(W(`event pattern matched: ${S.pattern.id} (confidence: ${S.confidence.toFixed(2)})`,"info","pattern-match"));let v=!1;if(/^event-[a-z]+-bare$/.test(S.pattern.id)){let b=S.captured.get("event"),N=(b?.raw??b?.value??"").toString().toLowerCase(),P=Se[t],z=L.KNOWN_EVENTS.has(N)||!!P&&Object.keys(P).some(M=>M.toLowerCase()===N);if(N&&!z){let M=this.trySOVEventExtraction(u,t,h);if(M){f.push(W(`bare-event mis-anchor on "${N}" rejected; SOV extraction preferred`,"info","stage-bare-event-guard"));let O=i?this.applyModifiers(M,i):M;return X(O,f)}if(b?.type==="reference"||b?.type==="expression"){m.reset(g);let O=h.filter(V=>V.command!=="on"),D=le.matchBest(m,O);m.reset(g),D&&D.pattern.command!=="on"?(v=!0,f.push(W(`bare-event mis-anchor on reference "${N}" rejected; command ${D.pattern.command} preferred`,"info","stage-bare-event-guard"))):le.matchBest(m,y)}}}if(!v){let b=this.buildEventHandler(S,m,t),N=i?this.applyModifiers(b,i):b;return X(N,f)}}f.push(W(`event patterns: ${y.length} tried, no match`,"info","stage-event"));let E=this.tryTrailingEventExtraction(u,t,h);if(E){f.push(W("trailing event extraction succeeded","info","stage-trailing-event"));let v=i?this.applyModifiers(E,i):E;return X(v,f)}let C=h.filter(v=>v.command!=="on"),x=le.matchBest(m,C);if(x){if(Le.has(x.pattern.command)){let v=this.trySOVEventExtraction(u,t,h);if(v){f.push(W(`SOV event extraction preferred over bare ${x.pattern.command} command`,"info","stage-sov-loop"));let N=i?this.applyModifiers(v,i):v;return X(N,f)}let b=this.tryMidStreamEventExtraction(u,t,h);if(b){f.push(W(`mid-stream event extraction preferred over bare ${x.pattern.command} command`,"info","stage-midstream-loop"));let N=i?this.applyModifiers(b,i):b;return X(N,f)}}else if(L.KNOWN_EVENTS.has(x.pattern.command)&&this.hasSOVEventMarkerHead(u,t)){let v=this.trySOVEventExtraction(u,t,h);if(v){f.push(W(`SOV event extraction preferred over command-homonym event ${x.pattern.command}`,"info","stage-sov-homonym"));let b=i?this.applyModifiers(v,i):v;return X(b,f)}}else if(I(t)?.wordOrder==="VSO"){let v=this.tryMidStreamEventExtraction(u,t,h);if(v){f.push(W(`mid-stream event extraction preferred over bare ${x.pattern.command} command`,"info","stage-midstream-cmd"));let b=i?this.applyModifiers(v,i):v;return X(b,f)}}if(x.consumedTokens<m.tokens.length&&I(t)?.wordOrder==="SOV"){let v=this.trySOVEventExtraction(u,t,h);if(v){f.push(W(`SOV event extraction preferred over partial ${x.pattern.command} command (trailing remainder)`,"info","stage-sov-trailing"));let b=i?this.applyModifiers(v,i):v;return X(b,f)}}return f.push(W(`command pattern matched: ${x.pattern.id} (confidence: ${x.confidence.toFixed(2)})`,"info","pattern-match")),X(this.buildCommand(x,t),f)}if(f.push(W(`command patterns: ${C.length} tried, no match`,"info","stage-command")),!u.includes(`
6
+ `)&&I(t)?.wordOrder==="VSO"){let v=this.tryMidStreamEventExtraction(u,t,h);if(v){f.push(W("mid-stream event extraction succeeded with no leading command match","info","stage-midstream-nocmd"));let b=i?this.applyModifiers(v,i):v;return X(b,f)}}let k=this.trySOVEventExtraction(u,t,h);if(k){f.push(W("SOV event extraction succeeded","info","stage-sov"));let v=i?this.applyModifiers(k,i):k;return X(v,f)}f.push(W("SOV event extraction: no event keyword found","info","stage-sov"));let T=this.tryCompoundCommandParsing(m,C,t);if(T)return f.push(W("compound command parsing succeeded","info","stage-compound")),X(T,f);throw f.push(W("compound parsing: no then-keywords or no command matches","info","stage-compound")),f.push(W(`all parse stages exhausted for "${u}"`,"error","parse-failed")),new Ze(`Could not parse input in ${t}: ${u}`,t,u,f)}parseStatements(e,t){let r=Y(e,t),n=Q(t).filter(i=>i.command!=="on").sort((i,s)=>s.priority-i.priority);return this.parseBodyWithClauses(r,n,t)}canParse(e,t){try{return this.parse(e,t),!0}catch{return!1}}supportedLanguages(){return ft()}buildCommand(e,t){if(!e)throw new Error("No match to build command from");let r={};for(let[i,s]of e.captured)r[i]=s;let n=G(e.pattern.command,r,{sourceLanguage:t,patternId:e.pattern.id,confidence:e.confidence});return this.registerBoundIdentifiers(n),n}buildEventHandler(e,t,r){if(!e)throw new Error("No match to build event handler from");let n=e.captured.get("event");if(!n)throw new Error("Event handler pattern matched but no event captured");let i=le.extractEventModifiers(t),s=this.extractOrConjunctionEvents(t,r),a=n;s.length>0&&n.type==="literal"&&(a={type:"literal",value:[String(n.value),...s.map(u=>String("value"in u?u.value:""))].join(" or ")});let l,c=e.captured.get("action");if(c&&c.type==="literal"&&c.value==="if"){let d=t.tokens,u=-1;for(let f=t.position()-1;f>=0;f--){let m=d[f],p=(m.normalized??m.value).toLowerCase();if(this.isIfKeyword(p,r)){u=f;break}}if(u>=0){let f=Q(r).filter(y=>y.command!=="on").sort((y,g)=>g.priority-y.priority),m=new H(d.slice(u),r),p=this.parseBodyWithClauses(m,f,r);if(p.some(y=>y.kind==="conditional")||p.length===1&&p[0]?.kind==="compound"&&p[0].statements.some(y=>y.kind==="conditional")){for(;!t.isAtEnd();)t.advance();return fe(a,p,i,{sourceLanguage:r,patternId:e.pattern.id,confidence:e.confidence})}}}if(c&&c.type==="literal"){let d=c.value,u={};for(let[C,x]of e.captured)C!=="event"&&C!=="action"&&C!=="continues"&&(u[C]=x);if(d==="repeat"){let C=t.peek(),x=T=>(T.normalized??T.value).toLowerCase();if(C&&C.kind==="keyword"&&x(C)==="forever")u.loopType={type:"literal",value:"forever"},delete u.patient,t.advance();else if(C&&C.kind==="keyword"&&x(C)==="event"){t.advance();let T=t.peek();if(T)for(u.event={type:"literal",value:x(T)},u.loopType={type:"literal",value:"until-event"},delete u.patient;!t.isAtEnd();){let v=t.peek();if(!v||v.kind==="conjunction"||v.kind==="keyword"&&(this.isThenKeyword(v.value,r)||this.isEndKeyword(v.value,r)))break;t.advance()}}let k=u.patient;k&&k.type==="reference"&&k.value==="me"&&delete u.patient}let f=G(d,u,{sourceLanguage:r,patternId:e.pattern.id,confidence:e.confidence});if(this.registerBoundIdentifiers(f),!Le.has(d)||d==="repeat"){let C=e.pattern.id.includes("verb-first"),x=t.tokens,k=t.position(),T=b=>b.kind==="conjunction"||b.kind==="keyword"&&(this.isThenKeyword(b.value,r)||this.isEndKeyword(b.value,r)),v=-1;for(let b=k-1;b>=0;b--){let N=x[b];if(T(N))break;if((N.normalized??N.value).toLowerCase()===d){v=b;break}}if(v>=0){let b=k;for(;b<x.length&&!T(x[b]);)b++;let N=x.slice(v,b),P=N;if(C){let z=String(n.value??"").toLowerCase(),M=N.findIndex(O=>(O.normalized??O.value).toLowerCase()===z);if(M<0)P=null;else{let O=N[M-1],D=O&&O.kind==="keyword"&&O.normalized?.toLowerCase()==="on"?M-1:M;P=[...N.slice(0,D),...N.slice(M+1)]}}if(P&&P.length>1){let z=Q(r).filter(j=>j.command!=="on").sort((j,pe)=>pe.priority-j.priority),M=this.parseClause(P,z,r),O=M[0],D=j=>j!==null&&typeof j=="object"&&typeof j.type=="string"?j.type:typeof j,V=ne(d),K=V?.primaryRole,U=j=>j==="patient"&&K&&K!=="patient"&&!V?.roles.some(pe=>pe.role==="patient")?K:j,he=(j,pe)=>{if(!Le.has(d)||!V)return!1;let be=V.roles.find(Fr=>Fr.role===U(j));return be?be.expectedTypes.length>0&&!be.expectedTypes.includes(D(pe)):!0},oe=!!O&&O.kind==="command"&&Object.entries(u).every(([j,pe])=>{if(he(j,pe))return!0;let be=O.roles.get(U(j));return be!==void 0&&D(be)===D(pe)}),ye=O?.metadata?.patternId??"",kt=!Le.has(d)||/^repeat-.*-(times|for-in|while-head|until-head)$/.test(ye);if(M.length===1&&O&&O.kind==="command"&&O.action===d&&oe&&kt&&O.roles.size>Object.keys(u).length)for(f=O;t.position()<b;)t.advance()}}}if(!Le.has(d)){let C=f;if(ne(d)?.roles.some(P=>P.role==="quantity"&&!P.required)&&!C.roles.has("quantity")){let P=t.peek();P&&/^-?\d+(\.\d+)?$/.test(P.value)&&(f=G(d,{...Object.fromEntries(C.roles),quantity:{type:"literal",value:parseFloat(P.value),dataType:"number"}},C.metadata),t.advance())}let k=f;if(ne(d)?.roles.some(P=>P.role==="duration"&&!P.required)&&!k.roles.has("duration")){let P=t.peek();P&&/^\d+(\.\d+)?(ms|s)$/i.test(P.value)&&(f=G(d,{...Object.fromEntries(k.roles),duration:{type:"literal",value:P.value,dataType:"string"}},k.metadata),t.advance(),this.consumeForPostposition(t,r))}let v=f,b=ne(d);if(b?.roles.find(P=>P.role==="responseType"&&!P.required)&&!v.roles.has("responseType")){let P=V=>typeof V=="string"&&L.RESPONSE_TYPE_WORDS.has(V.toLowerCase()),z=(V,K)=>{let U=Object.fromEntries(v.roles);K&&delete U.destination,U.responseType={type:"expression",raw:V},f=G(d,U,v.metadata)},M=v.roles.get("destination"),O=b?.roles.find(V=>V.role==="destination"),D=M?.raw??M?.value;if(M&&O&&!O.expectedTypes.includes(M.type)&&P(D))z(D,!0);else{let V=t.peek();V&&P(V.value)&&(z(V.value,!1),t.advance())}}if(d==="wait"){let P=f;if(!P.roles.has("event")){let z=t.peek();if(z&&Ae.has(z.value.toLowerCase())){let M=Object.fromEntries(P.roles),O=M.duration;O&&O.type!=="literal"&&O.type!=="expression"&&delete M.duration;let D=M.patient;D&&D.type==="reference"&&D.value==="me"&&delete M.patient,M.event={type:"literal",value:z.value,dataType:"string"},f=G(d,M,P.metadata),t.advance(),this.consumeForPostposition(t,r)}}}}let m=e.captured.get("continues"),p=m?.type==="literal"&&m.value==="then",h=t.peek(),y=!!h&&this.isThenKeyword(h.value,r),S=Le.has(d)&&!!h&&!this.isEndKeyword(h.value,r),E=!!h&&!this.isEndKeyword(h.value,r);if(p||y||S||E){let C=Q(r).filter(T=>T.command!=="on").sort((T,v)=>v.priority-T.priority),x=Q(r).filter(T=>T.id.startsWith("grammar-")&&T.id.includes("-continuation")).sort((T,v)=>v.priority-T.priority),k=this.parseBodyWithGrammarPatterns(t,C,x,r);k.length>0?l=[f,...k]:l=[f]}else l=[f]}else{let d=Q(r).filter(u=>u.command!=="on").sort((u,f)=>f.priority-u.priority);l=this.parseBodyWithClauses(t,d,r)}return fe(a,l,i,{sourceLanguage:r,patternId:e.pattern.id,confidence:e.confidence})}parseBodyWithClauses(e,t,r){let n=[],i=[],s=0,a=[];for(;!e.isAtEnd();){let l=e.peek();if(!l)break;if(i.length===0){let p=this.consumeJsBlock(e,r);if(p){n.push(p);continue}let h=this.tryParseConditionalBlock(e,t,r);if(h){n.push(h);continue}}let c=l.kind==="conjunction"||l.kind==="keyword"&&this.isThenKeyword(l.value,r),d=i[i.length-1],u=e.peek(1),f=d?.value.toLowerCase()==="at"&&u?.value.toLowerCase()==="of"||Vt(r,l.value,d?.value,u?.value),m=l.kind==="keyword"&&this.isEndKeyword(l.value,r)&&!f;if(m&&s>0){s--,a.pop(),i.push(l),e.advance();continue}if(c&&a.includes("if")){i.push(l),e.advance();continue}if(c){if(i.length>0){let p=this.parseClause(i,t,r);n.push(...p),i.length=0,s=p.filter(h=>{let y=h;return(y.action==="for"||y.action==="repeat"||y.action==="while")&&(!Array.isArray(y.body)||y.body.length===0)}).length,a.length=0;for(let h=0;h<s;h++)a.push("other")}e.advance();continue}if(m){e.advance();let p=[];for(;!e.isAtEnd();){let h=e.peek();if(!h||h.kind==="conjunction"||h.kind==="keyword"&&(this.isThenKeyword(h.value,r)||this.isEndKeyword(h.value,r)))break;p.push(h),e.advance()}if(p.length>0){let h=i.length>0?this.parseClause(i,t,r):[];h.length===0&&i.length>0?n.push(...this.parseClause([...i,...p],t,r)):(n.push(...h),n.push(...this.parseClause(p,t,r)))}else if(i.length>0){let h=this.parseClause(i,t,r);n.push(...h)}i.length=0;break}if(l.kind==="keyword"){let p=(l.normalized??l.value).toLowerCase();(this.isIfKeyword(p,r)||this.isUnlessKeyword(p,r)||p==="while"||p==="for"||p==="repeat")&&(s++,a.push(this.isIfKeyword(p,r)?"if":"other"))}i.push(l),e.advance()}if(i.length>0){let l=this.parseClause(i,t,r);n.push(...l)}this.foldFrontedWhileIntoRepeat(n,r);for(let l=n.length-1;l>=0;l--){let c=n[l];c.kind==="command"&&c.action==="for"&&(!(c.roles instanceof Map)||c.roles.size===0)&&(!Array.isArray(c.body)||c.body.length===0)&&n.splice(l,1)}return n.length>1?[De(n,"then",{sourceLanguage:r})]:n}foldFrontedWhileIntoRepeat(e,t){for(let r=0;r+1<e.length;r++){let n=e[r],i=e[r+1];if(n.kind!=="command"||n.action!=="while"||i.kind!=="command"||i.action!=="repeat")continue;let s=n.roles.get("condition");if(!s||i.roles.has("condition")||Array.isArray(n.body)||Array.isArray(i.body))continue;let a=new Map(i.roles);a.set("condition",s),a.set("loopType",{type:"literal",value:"while",dataType:"string"}),e.splice(r,2,{...i,roles:a,metadata:{...i.metadata,sourceLanguage:t,patternId:`repeat-${t}-fronted-while-fold`,confidence:Math.max(i.metadata?.confidence??0,n.metadata?.confidence??0)}})}}parseClause(e,t,r){if(e.length===0)return[];let n=null,i=e,s=e[e.length-1];if(s&&e.length>=2){let y=(s.normalized??s.value).toLowerCase();this.isUnlessKeyword(y,r)&&(n="unless",i=e.slice(0,-1))}let a=null;if(n&&i.length>=3){let y=I(r),g=y?L.buildVerbLookup(y):null;if(g)for(let S=1;S<i.length-1;S++){let E=i[S],C=g.get(E.value.toLowerCase())??(E.normalized?g.get(E.normalized.toLowerCase()):void 0);if(C&&!L.CONDITION_OPERATORS.has(C)){a=i.slice(0,S),i=i.slice(S);break}}}let l=new H(i,r),c=[],d=0,u=[],f=a,m=()=>{if(u.length===0)return;let y=u.slice();if(u.length=0,n&&c.length===0&&f===null){f=y;return}let g=y[0];if(g&&(g.kind==="identifier"||g.kind==="selector"||g.kind==="literal"||g.kind==="reference"))for(let E of this.parseSOVClauseByVerbAnchoring(y,r)){let C=E.action,x=E.roles;C&&ne(C)&&x instanceof Map&&x.size>0&&c.push(E)}};for(;!l.isAtEnd();){let y=l.peek(),g=!!y&&y.normalized?.toLowerCase()==="repeat",S=l.mark(),E=le.matchBest(l,t);if(g&&E&&E.pattern.command!=="repeat"){l.reset(S),m(),c.push(G("repeat",{},{sourceLanguage:r,confidence:.6})),d++,l.advance();continue}if(E&&E.pattern.command==="if"){let C=l.mark(),x=u.length;for(l.reset(S);!l.isAtEnd();){let T=l.peek();if(!T||this.isIfKeyword((T.normalized??T.value).toLowerCase(),r))break;u.push(T),l.advance()}let k=this.tryParseConditionalBlock(l,t,r);if(k){m(),c.push(k),d++;continue}u.length=x,l.reset(C)}if(E){m();let C=this.buildCommand(E,r);c.push(C),d++,this.tryAttachTrailingRole(l,C,r)}else{let C=l.peek();C&&C.normalized?.toLowerCase()==="repeat"?(m(),c.push(G("repeat",{},{sourceLanguage:r,confidence:.6})),d++):C&&u.push(C),l.advance()}}m();let p=c;if(d===0){let y=this.parseSOVClauseByVerbAnchoring(i,r);y.length>0&&(p=y)}let h=f;return n&&p.length>0&&h&&h.length>0?[G(n,{condition:{type:"expression",raw:this.joinTokenText(h)}},{sourceLanguage:r,patternId:`${n}-${r}-trailing-guard`,confidence:.85}),...p]:p}tryAttachTrailingRole(e,t,r){let n=ne(t.action);if(!n)return;let i=I(r);if(!i)return;let s=t.roles,a=(c,d)=>{if(!c)return!1;if(c.kind==="selector")return!0;let u=(c.normalized??c.value).toLowerCase();return pa.has(u)?!1:u==="body"||u==="it"||u==="you"||u==="result"||u==="document"||u==="window"||this.boundIdentifiers.has(c.value)?!0:d?!1:c.kind==="identifier"||c.kind==="reference"},l=[{role:"source",strict:!1},{role:"destination",strict:!0}];for(let{role:c,strict:d}of l){if(!n.roles.some(y=>y.role===c))continue;let u=i.roleMarkers?.[c];if(!u)continue;let f=s.get(c);if(f&&!(f.type==="reference"&&f.value==="me"))continue;let m=y=>{if(!y||y.kind!=="particle"&&y.kind!=="keyword")return!1;let g=y.value.toLowerCase();return u.primary?.toLowerCase()===g?!0:d?!1:(y.normalized??"").toLowerCase()===c?!0:!!u.alternatives?.some(S=>S.toLowerCase()===g)},p=e.peek(),h=e.peek(1);if(!p||!h)return;if(d&&u.position==="after"){let y=e.peek(2),g=(p.normalized??p.value).toLowerCase();if(ma.has(g)&&h.kind==="selector"&&m(y)){s.set(c,{type:"expression",raw:`${g} ${h.value}`}),e.advance(),e.advance(),e.advance();return}}if(u.position==="after"){if(a(p,d)&&m(h)){let y=this.tokenToSemanticValue(p);e.advance(),e.advance(),y&&s.set(c,y);return}}else if(m(p)&&a(h,d)){e.advance();let y=this.tokenToSemanticValue(e.advance());y&&s.set(c,y);return}}}static buildVerbLookup(e){let t=new Map;for(let[r,n]of Object.entries(e.keywords))if(!["on","if","else","when","where","while","end","then","and"].includes(r)&&(t.set(n.primary.toLowerCase(),r),n.alternatives))for(let i of n.alternatives)t.set(i.toLowerCase(),r);return t}static buildMarkerToRoleLookup(e){let t=new Map;for(let[r,n]of Object.entries(e.roleMarkers)){if(!n)continue;if((r!=="event"||!t.has(n.primary))&&t.set(n.primary,r),n.alternatives)for(let s of n.alternatives)t.has(s)||t.set(s,r)}return t}parseSOVClauseByVerbAnchoring(e,t){let r=I(t);if(!r||r.wordOrder!=="SOV")return[];let n=L.buildVerbLookup(r),i=L.buildMarkerToRoleLookup(r),s=[],a=0;for(;a<e.length;){let l=-1,c="";for(let p=a;p<e.length;p++){let h=e[p];if(i.has(h.value))continue;let y=n.get(h.value.toLowerCase()),g=h.normalized?n.get(h.normalized.toLowerCase()):void 0,S=y||g;if(S){l=p,c=S;break}}if(l===-1)break;let d=e.slice(a,l),u=e.length;for(let p=l+1;p<e.length;p++){let h=e[p];if(h.kind==="conjunction"||this.isThenKeyword(h.value,t)){u=p;break}if(p>l+1&&!i.has(h.value)&&(n.get(h.value.toLowerCase())||(h.normalized?n.get(h.normalized.toLowerCase()):void 0))){u=p;break}}let f=e.slice(l+1,u),m=this.extractRolesFromMarkedTokens(d,f,i,c,t);if(s.push(G(c,m,{sourceLanguage:t,confidence:.7})),a=u,a<e.length){let p=e[a];(p.kind==="conjunction"||this.isThenKeyword(p.value,t))&&a++}}return s}extractRolesFromMarkedTokens(e,t,r,n,i){let s={},a=l=>{let c=[];for(let d of l){let u=r.get(d.value);if(u&&d.kind==="particle"&&c.length>0){let f=this.tokensToSemanticValue(c);if(f){let m=this.mapRoleForCommand(u,n,s);m&&(s[m]=f)}c=[]}else c.push(d)}if(c.length>0)if(c.length===1&&/^\d+(\.\d+)?(ms|s)$/i.test(c[0].value)&&!s.duration&&ne(n)?.roles.some(u=>u.role==="duration"))s.duration={type:"literal",value:c[0].value,dataType:"string"};else{let u=this.tokensToSemanticValue(c);u&&(s.patient?s.destination||(s.destination=u):s.patient=u)}};return a(e),a(t),s}mapRoleForCommand(e,t,r){return r[e]?e==="patient"&&!r.destination?"destination":e==="destination"&&!r.patient?"patient":e==="source"&&!r.source?"source":null:e}tokensToSemanticValue(e){if(e.length===0)return null;let t=e.filter(i=>i.kind!=="whitespace");if(t.length===0)return null;if(t.length===1)return this.tokenToSemanticValue(t[0]);let r=t.map(i=>i.value).join(""),n=t[0];return n.kind==="selector"||n.value.startsWith("#")||n.value.startsWith(".")||n.value.startsWith("@")||n.value.startsWith("*")?re(r):n.kind==="literal"||n.value.startsWith('"')||n.value.startsWith("'")?$(Wr(r),"string"):n.kind==="reference"?J(r):$(r)}tokenToSemanticValue(e){let t=e.value;if(e.kind==="selector"||t.startsWith("#")||t.startsWith(".")||t.startsWith("@")||t.startsWith("*"))return re(t);if(t.startsWith('"')||t.startsWith("'"))return $(Wr(t),"string");if(/^-?\d+(\.\d+)?$/.test(t))return $(parseFloat(t));if(t==="true"||t==="\u771F"||t==="\uCC38"||t==="do\u011Fru")return $(!0);if(t==="false"||t==="\u507D"||t==="\uAC70\uC9D3"||t==="yanl\u0131\u015F")return $(!1);let r=e.normalized?.toLowerCase();return r==="me"||r==="it"||r==="you"||r==="result"||r==="body"?J(r):e.kind==="reference"?J(e.normalized||"me"):$(t)}parseBodyWithGrammarPatterns(e,t,r,n){let i=[],s=[],a=!1,l=()=>{!a&&s.length>0&&i.push(...this.parseSOVClauseByVerbAnchoring(s,n)),s=[],a=!1},c=0,d=()=>{let u=0;for(let f of i){let m=f;(m.action==="for"||m.action==="repeat"||m.action==="while")&&(!Array.isArray(m.body)||m.body.length===0)&&u++}return u-c};for(;!e.isAtEnd();){let u=e.peek();if(u&&this.isThenKeyword(u.value,n)){l(),e.advance();continue}if(u&&this.isEndKeyword(u.value,n)){let m=e.peek(-1),p=e.peek(1);if(!Vt(n,u.value,m?.value,p?.value)){if(l(),d()>0){c++,e.advance();continue}e.advance();break}}if(u&&!a&&this.isIfKeyword((u.normalized??u.value).toLowerCase(),n)){l();let m=this.tryParseConditionalBlock(e,t,n);if(m){i.push(m),a=!0;continue}}let f=!1;if(r.length>0){let m=le.matchBest(e,r);if(m){let p=m.pattern.command,h={};for(let[S,E]of m.captured)S!=="event"&&S!=="action"&&S!=="continues"&&(h[S]=E);let y=G(p,h,{sourceLanguage:n,patternId:m.pattern.id});i.push(y),f=!0,a=!0;let g=m.captured.get("continues");if(g&&g.type==="literal"&&g.value==="then")continue}}if(!f){let m=e.mark(),p=le.matchBest(e,t);if(p){if(p.pattern.command==="if"){let y=e.mark();for(e.reset(m);!e.isAtEnd();){let S=e.peek();if(!S||this.isIfKeyword((S.normalized??S.value).toLowerCase(),n))break;e.advance()}let g=this.tryParseConditionalBlock(e,t,n);if(g){l(),i.push(g),a=!0;continue}e.reset(y)}let h=this.buildCommand(p,n);i.push(h),this.tryAttachTrailingRole(e,h,n),f=!0,a=!0}}f||(u&&s.push(u),e.advance())}l();for(let u=i.length-1;u>=0;u--){let f=i[u];f.kind==="command"&&f.action==="for"&&(!(f.roles instanceof Map)||f.roles.size===0)&&(!Array.isArray(f.body)||f.body.length===0)&&i.splice(u,1)}return i}tryCompoundCommandParsing(e,t,r){let n=e.tokens,i=n.some(c=>c.kind==="conjunction"||c.kind==="keyword"&&this.isThenKeyword(c.value,r)),s=n.some(c=>this.isElseKeyword(c.value,r));if(!i&&!s)return null;let a=new H(n,r),l=this.parseBodyWithClauses(a,t,r);return l.length===0?null:l.length===1?l[0]:De(l,"then",{sourceLanguage:r,confidence:.65})}matchEventMarkerPhrase(e,t,r){let n=L.SOV_EVENT_MARKER_PHRASES[r];if(!n)return 0;for(let i of n)if(i.every((s,a)=>e[t+a]?.value===s))return i.length;return 0}hasSOVEventMarkerHead(e,t){let r=L.SOV_EVENT_MARKERS[t];if(r===void 0)return!1;let{tokens:n}=Y(e,t),i=Se[t],s=new Set;if(i)for(let a of Object.keys(i))s.add(a.toLowerCase());for(let a=0;a<n.length;a++){let l=n[a],c=l.value.toLowerCase(),d=l.normalized?.toLowerCase();if(!(!!d&&(L.KNOWN_EVENTS.has(d)||Ae.has(d))||L.KNOWN_EVENTS.has(c)||Ae.has(c)||s.has(c)))continue;let f=this.matchEventParamPhrase(n,a+1).len,m=n[a+1+f];if(m&&(m.kind==="particle"||m.kind==="keyword")&&r.has(m.value)||this.matchEventMarkerPhrase(n,a+1+f,t)>0)return!0}return!1}matchEventParamPhrase(e,t){if(e[t]?.value!=="(")return{len:0,names:[]};let r=[];for(let n=t+1;n<e.length;n++){let i=e[n].value;if(i===")")return{len:n-t+1,names:r};if(i!==","){if(e[n].kind!=="identifier")break;r.push(i)}}return{len:0,names:[]}}isStrippableSourceRef(e,t){if(!e)return!1;let r=e.normalized?.toLowerCase();if(e.kind==="keyword"&&(r==="me"||r==="i"||r==="it"))return!0;let n=e.value.toLowerCase();return t.has(n)||!!r&&t.has(r)}tryTrailingEventExtraction(e,t,r){let n=Y(e,t).tokens;if(n.length<3)return null;let i=Se[t],s=new Set;if(i)for(let E of Object.keys(i))s.add(E.toLowerCase());let a=n.length-2,l=n[a];if(!(l.kind==="keyword"&&l.normalized?.toLowerCase()==="on"))return null;let d=n[n.length-1],u=d.value.toLowerCase(),f=d.normalized?.toLowerCase();if(!(!!f&&L.KNOWN_EVENTS.has(f)||L.KNOWN_EVENTS.has(u)||s.has(u)))return null;let p=f&&L.KNOWN_EVENTS.has(f)?f:i?.[u]??u,h=n.slice(0,a);if(h.length===0)return null;let y=r.filter(E=>E.command!=="on"),g=new H(h,t),S=this.parseBodyWithClauses(g,y,t);return S.length===0?null:fe({type:"literal",value:p},S,void 0,{sourceLanguage:t,confidence:.75})}tryMidStreamEventExtraction(e,t,r){let n=Y(e,t).tokens;if(n.length<3)return null;let i=Se[t],s=new Set;if(i)for(let a of Object.keys(i))s.add(a.toLowerCase());for(let a=0;a<n.length-1;a++){let l=n[a];if(!(l.kind==="keyword"&&l.normalized?.toLowerCase()==="on"))continue;let d=n[a+1],u=d.value.toLowerCase(),f=d.normalized?.toLowerCase();if(!(!!f&&L.KNOWN_EVENTS.has(f)||L.KNOWN_EVENTS.has(u)||s.has(u)))continue;let p=f&&L.KNOWN_EVENTS.has(f)?f:i?.[u]??u,h=n.filter((E,C)=>C!==a&&C!==a+1);if(h.length===0)return null;let y=r.filter(E=>E.command!=="on"),g=new H(h,t),S=this.parseBodyWithClauses(g,y,t);return S.length===0?null:fe({type:"literal",value:p},S,void 0,{sourceLanguage:t,confidence:.75})}return null}trySOVEventExtraction(e,t,r){let n=L.SOV_EVENT_MARKERS[t];if(!n)return null;let s=Y(e,t).tokens,a=Se[t],l=new Set;if(a)for(let x of Object.keys(a))l.add(x.toLowerCase());let c=L.SOV_SOURCE_MARKERS[t],d=-1,u="",f="",m=1,p=[];for(let x=0;x<s.length;x++){let k=s[x],T=k.value.toLowerCase(),v=T,b="",N=T.indexOf("[");N>0&&(v=T.slice(0,N),b=k.value.slice(N));let P=k.normalized?.toLowerCase(),z=P&&(L.KNOWN_EVENTS.has(P)||Ae.has(P)),M=l.has(T)||l.has(v),O=L.KNOWN_EVENTS.has(v)||Ae.has(v);if(z||M||O){let D=s[x-1];if(D&&(D.normalized??D.value).toLowerCase()==="event")continue;let V;z?V=P:M?V=a?.[T]??a?.[v]??v:V=v;let K=this.matchEventParamPhrase(s,x+1);if(n.size>0){let U=1+K.len,he=s[x+U];he&&he.kind==="selector"&&he.value.startsWith("[")&&(U+=1);let oe=s[x+U];if(oe&&(oe.kind==="particle"||oe.kind==="keyword")&&n.has(oe.value)){d=x,u=V,f=b||(U===K.len+2?s[x+U-1].value:""),m=U+1,p=K.names;break}}else{d=x,u=V,f=b,m=1+K.len+this.matchEventMarkerPhrase(s,x+1+K.len,t),p=K.names;break}}}if(d===-1){let x=new Set(r.filter(k=>k.command!=="on").map(k=>k.command));for(let k=0;k<s.length;k++){let T=s[k];if(T.kind==="identifier")if(n.size>0){let v=1,b=s[k+1];b&&b.kind==="selector"&&b.value.startsWith("[")&&(v=2);let N=s[k+v];if(N&&(N.kind==="particle"||N.kind==="keyword")&&n.has(N.value)){d=k,u=T.value,f=v===2?s[k+1].value:"",m=v+1;break}}else{let v=this.matchEventMarkerPhrase(s,k+1,t);if(v>0){d=k,u=T.value,f="",m=1+v;break}let b=s[k+1];if(b&&b.kind==="keyword"&&b.normalized!=null&&x.has(b.normalized)){d=k,u=T.value,f="",m=1;break}}}}if(d===-1)return null;let h=new Set;for(let x=d;x<d+m;x++)h.add(x);if(c){let x=d+m;if(x<s.length){let k=s[x];if((k.kind==="particle"||k.kind==="keyword")&&c.markers.has(k.value))h.add(x);else if(this.isStrippableSourceRef(k,c.windowTokens)){let T=s[x+1];T&&(T.kind==="particle"||T.kind==="keyword")&&c.markers.has(T.value)&&(h.add(x),h.add(x+1))}}if(d>=2){let k=s[d-1];(k.kind==="particle"||k.kind==="keyword")&&c.markers.has(k.value)&&this.isStrippableSourceRef(s[d-2],c.windowTokens)&&(h.add(d-2),h.add(d-1))}for(let k=0;k<d;k++){let T=s[k],v=T.value.toLowerCase(),b=T.normalized?.toLowerCase();if(c.windowTokens.has(v)||b&&c.windowTokens.has(b)){h.add(k);break}}}let y=s.filter((x,k)=>!h.has(k));if(y.length===0)return null;let g=r.filter(x=>x.command!=="on"),S=new H(y,t),E=this.parseBodyWithClauses(S,g,t);if(E.length===0)return null;let C={sourceLanguage:t,confidence:.75};return f&&(C.keyFilter=f),fe({type:"literal",value:u},E,void 0,C,p)}profileKeywordMatches(e,t,r){let n=I(e)?.keywords?.[t];return n?n.primary?.toLowerCase()===r?!0:!!n.alternatives?.some(i=>i.toLowerCase()===r):!1}consumeForPostposition(e,t){let r=e.peek();if(!r)return;let n=(r.normalized??"").toLowerCase(),i=I(t)?.keywords?.for;(n==="for"||r.value===i?.primary||(i?.alternatives??[]).includes(r.value))&&e.advance()}isThenKeyword(e,t){let r=e.toLowerCase(),i={en:new Set(["then"]),ja:new Set(["\u305D\u308C\u304B\u3089","\u6B21\u306B","\u305D\u3057\u3066"]),ar:new Set(["\u062B\u0645","\u0628\u0639\u062F\u0647\u0627","\u062B\u0645\u0651"]),es:new Set(["entonces","luego","despu\xE9s"]),ko:new Set(["\uADF8\uB2E4\uC74C","\uADF8\uB9AC\uACE0","\uADF8\uB7F0\uD6C4","\uADF8\uB7EC\uBA74"]),zh:new Set(["\u7136\u540E","\u63A5\u7740","\u90A3\u4E48"]),tr:new Set(["ard\u0131ndan","daha sonra","ardindan"]),pt:new Set(["ent\xE3o","depois","logo"]),fr:new Set(["puis","ensuite","alors"]),de:new Set(["dann","danach","anschlie\xDFend"]),id:new Set(["lalu","kemudian","setelah itu"]),tl:new Set(["pagkatapos","tapos"]),bn:new Set(["\u09A4\u09BE\u09B0\u09AA\u09B0"]),qu:new Set(["chaymantataq","hinaspa","chaymanta","chayqa"]),sw:new Set(["kisha","halafu","baadaye"])}[t];return i?i.has(r):r==="then"||this.profileKeywordMatches(t,"then",r)}isElseKeyword(e,t){let r=e.toLowerCase();return r==="else"?!0:this.profileKeywordMatches(t,"else",r)}isEndKeyword(e,t){let r=e.toLowerCase(),i={en:new Set(["end"]),ja:new Set(["\u7D42\u308F\u308A","\u304A\u308F\u308A"]),ar:new Set(["\u0646\u0647\u0627\u064A\u0629","\u0627\u0646\u062A\u0647\u0649","\u0627\u0644\u0646\u0647\u0627\u064A\u0629"]),es:new Set(["fin","final","terminar"]),ko:new Set(["\uB05D","\uB9C8\uCE68"]),zh:new Set(["\u7ED3\u675F","\u7EC8\u6B62","\u5B8C"]),tr:new Set(["son","biti\u015F","bitti"]),pt:new Set(["fim","final","t\xE9rmino"]),fr:new Set(["fin","terminer","finir"]),de:new Set(["ende","fertig"]),id:new Set(["selesai","akhir","tamat"]),tl:new Set(["wakas","tapos"]),bn:new Set(["\u09B8\u09AE\u09BE\u09AA\u09CD\u09A4"]),qu:new Set(["tukukuy","tukuy","puchukay"]),sw:new Set(["mwisho","maliza","tamati"])}[t];return i?r==="end"||i.has(r):r==="end"||this.profileKeywordMatches(t,"end",r)}isJsKeyword(e){let t=(e.normalized??e.value).toLowerCase();return t==="js"||this.profileKeywordMatches("en","js",t)}consumeJsBlock(e,t){let r=e.peek();if(!r||!this.isJsKeyword(r))return null;let n=e.mark(),i=[];e.advance();let s=!1;for(;!e.isAtEnd();){let l=e.peek();if(!l)break;if(e.advance(),this.isEndKeyword(l.value,t)){s=!0;break}i.push(l)}if(!s)return e.reset(n),null;let a=i.map(l=>l.value).join(" ").trim();return G("js",{patient:{type:"expression",raw:a||"()"}},{sourceLanguage:t,patternId:`js-opaque-${t}`,confidence:1})}isIfKeyword(e,t){let r=e.toLowerCase();return r==="if"?!0:this.profileKeywordMatches(t,"if",r)}isUnlessKeyword(e,t){let r=e.toLowerCase();return r==="unless"?!0:this.profileKeywordMatches(t,"unless",r)}isBlockEndToken(e,t,r){return this.isEndKeyword(e.value,r)?!0:e.kind!=="keyword"||(e.normalized??"").toLowerCase()!=="end"?!1:!(t&&t.kind==="selector")}tryParseConditionalBlock(e,t,r){let n=e.peek();if(!n)return null;let i=(n.normalized??n.value).toLowerCase();if(!this.isIfKeyword(i,r))return null;let s=e.mark();e.advance();let a=[],l=0;for(;!e.isAtEnd();){let k=e.peek();if(!k)break;let T=(k.normalized??k.value).toLowerCase();if(this.isIfKeyword(T,r)||this.isUnlessKeyword(T,r)){l++,a.push(k),e.advance();continue}if(this.isBlockEndToken(k,e.peek(1)??void 0,r)){if(l===0){e.advance();break}l--,a.push(k),e.advance();continue}a.push(k),e.advance()}if(a.length===0)return e.reset(s),null;let c=I(r),d=c?.wordOrder==="SOV"?L.buildVerbLookup(c):null,u=0,f=0,m=[],p=!1;for(;u<a.length;u++){let k=a[u],T=(k.normalized??k.value).toLowerCase();if(this.isIfKeyword(T,r)||this.isUnlessKeyword(T,r)?f++:this.isBlockEndToken(k,a[u+1],r)&&f--,f===0&&this.isThenKeyword(k.value,r)){p=!0,u++;break}if(f===0&&m.length>0){let v=(a[u-1].normalized??a[u-1].value).toLowerCase(),b=a[u-1].value.toLowerCase(),N=(k.normalized??k.value).toLowerCase(),P=L.CONDITION_COPULAS.has(v)||L.CONDITION_COPULAS_SURFACE.has(b)&&L.CONDITION_PREDICATES.has(N),z=d!==null&&d.has(k.value.toLowerCase())&&!L.CONDITION_PREDICATES.has(N);if(!L.CONDITION_OPERATORS.has(N)&&(!P||z)&&(this.tokensBeginCommand(a.slice(u),t,r)||this.sovCommandStartsAt(a.slice(u),d)))break}m.push(k)}if(m.length===0)return e.reset(s),null;let h=[],y=[],g=!1,S=0;for(;u<a.length;u++){let k=a[u],T=(k.normalized??k.value).toLowerCase();if(this.isIfKeyword(T,r)||this.isUnlessKeyword(T,r)?S++:this.isBlockEndToken(k,a[u+1],r)&&S--,S===0&&!g&&this.isElseKeyword(k.value,r)){g=!0;continue}(g?y:h).push(k)}let E={type:"expression",raw:this.joinTokenText(m)},C=this.parseBranch(h,t,r),x=y.length>0?this.parseBranch(y,t,r):void 0;return C.length===0&&(!x||x.length===0)?(e.reset(s),null):xr(E,C,x,{sourceLanguage:r,patternId:`conditional-${r}-folded`,confidence:1})}joinTokenText(e){return e.map(t=>t.kind==="keyword"?t.normalized??t.value:t.value).join(" ").trim()}tokensBeginCommand(e,t,r){if(e.length===0)return!1;let n=new H(e,r);return le.matchBest(n,t)!==null}sovCommandStartsAt(e,t){if(!t)return!1;let r=a=>t.has(a.value.toLowerCase())||!!a.normalized&&t.has(a.normalized.toLowerCase()),n=a=>a.kind==="identifier"||a.kind==="selector"||a.kind==="literal"||a.kind==="reference",i=0,s=0;for(;i+1<e.length;){let a=e[i],l=e[i+1];if(!n(a)||l.kind!=="particle")break;s+=1,i+=2;let c=e[i];if(s>=1&&c&&r(c))return!0}return!1}parseBranch(e,t,r){if(e.length===0)return[];let n=new H(e,r),i=this.parseBodyWithClauses(n,t,r);return i.length===1&&i[0]?.kind==="compound"?i[0].statements:i}extractStandaloneModifiers(e,t){let n=Y(e,t).tokens;if(n.length===0)return{modifiers:null,remainingInput:null};let s=n[0].value.toLowerCase(),a=L.STANDALONE_MODIFIERS[s];if(!a)return{modifiers:null,remainingInput:null};let l={},c=1;if(a==="once")l.once=!0;else{let m=1;if(m<n.length){let p=n[m];(p.kind==="keyword"||p.kind==="particle")&&(m++,c++)}if(m<n.length){let p=n[m];if(p.kind==="literal"){let h=p.value.match(/^(\d+)(ms|s|m)?$/);if(h){let y=parseInt(h[1],10),g=h[2]||"ms";g==="s"?y*=1e3:g==="m"&&(y*=6e4),l[a]=y,c=m+1}}}l[a]||(l[a]=a==="debounce"?300:100)}let d=n.slice(c);if(d.length===0)return{modifiers:null,remainingInput:null};let u=d[0].position.start,f=e.slice(u);return{modifiers:l,remainingInput:f}}stripAsyncModifier(e,t){let r=I(t)?.keywords?.async,n=new Set(["async"]);r?.primary&&n.add(r.primary.toLowerCase()),r?.alternatives?.forEach(c=>n.add(c.toLowerCase()));let i=Y(e,t).tokens,s=i.findIndex(c=>n.has(c.value.toLowerCase()));if(s===-1)return{remainingInput:null};let a=i[s],l=(e.slice(0,a.position.start)+e.slice(a.position.end)).replace(/\s{2,}/g," ").trim();return l.length===0?{remainingInput:null}:{remainingInput:l}}stripDoNotThrowModifier(e,t){let r=Y(e,t).tokens;for(let n=0;n<r.length-1;n++){if(r[n].value.toLowerCase()!=="do")continue;let i=-1;for(let c=n+1;c<=n+5&&c<r.length;c++){let d=r[c];if(d.normalized?.toLowerCase()==="throw"){i=c;break}let u=d.kind;if(u==="selector"||u==="literal"||u==="reference"||u==="conjunction")break}if(i===-1)continue;let s=r[n].position.start,a=r[i].position.end,l=(e.slice(0,s)+e.slice(a)).replace(/\s{2,}/g," ").trim();return l.length===0?{remainingInput:null}:{remainingInput:l}}return{remainingInput:null}}applyModifiers(e,t){return{...e,eventModifiers:{...e.eventModifiers,...t}}}extractOrConjunctionEvents(e,t){let r=[];for(;;){let n=e.mark(),i=e.peek();if(!i)break;let s=(i.normalized||i.value).toLowerCase();if(!L.OR_KEYWORDS.has(s)){e.reset(n);break}e.advance();let a=e.peek();if(!a){e.reset(n);break}let l=(a.normalized||a.value).toLowerCase();e.advance(),r.push({type:"literal",value:l})}return r}};L.KNOWN_EVENTS=new Set(["click","dblclick","input","change","submit","keydown","keyup","keypress","mouseover","mouseout","mousedown","mouseup","focus","blur","load","scroll","resize","contextmenu"]),L.RESPONSE_TYPE_WORDS=new Set(["json","text","html","xml","blob","arraybuffer","formdata","response"]),L.SOV_EVENT_MARKERS={ja:new Set(["\u3067"]),ko:new Set,tr:new Set(["de","da","te","ta"]),bn:new Set(["\u098F"]),qu:new Set(["pi"]),hi:new Set(["\u092A\u0930"])},L.SOV_EVENT_MARKER_PHRASES={ko:[["\uD560","\uB54C"],["\uD560\uB54C"]]},L.SOV_SOURCE_MARKERS={ja:{markers:new Set(["\u304B\u3089"]),windowTokens:new Set(["\u30A6\u30A3\u30F3\u30C9\u30A6","\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8","window","document"])},ko:{markers:new Set(["\uC5D0\uC11C"]),windowTokens:new Set(["\uCC3D","\uC708\uB3C4\uC6B0","\uBB38\uC11C","window","document"])},tr:{markers:new Set(["den","dan","ten","tan"]),windowTokens:new Set(["pencere","belge","window","document"])},bn:{markers:new Set(["\u09A5\u09C7\u0995\u09C7","\u09AE\u09A7\u09CD\u09AF\u09C7"]),windowTokens:new Set(["\u0989\u0987\u09A8\u09CD\u09A1\u09CB","\u09A1\u0995\u09C1\u09AE\u09C7\u09A8\u09CD\u099F","window","document"])},qu:{markers:new Set(["manta"]),windowTokens:new Set(["k_iri","ventana","window","document"])},hi:{markers:new Set(["\u0938\u0947"]),windowTokens:new Set(["\u0935\u093F\u0902\u0921\u094B","\u0926\u0938\u094D\u0924\u093E\u0935\u0947\u091C\u093C","window","document"])}},L.CONDITION_COPULAS=new Set(["is","am","are","be","was","were","not","no"]),L.CONDITION_COPULAS_SURFACE=new Set(["est","\u0435\u0441\u0442\u044C","\u0454","\xE9","ay","\u0647\u0648","adalah","\u0E40\u0E1B\u0E47\u0E19","\u09B9\u09AF\u09BC","\u0939\u0948","dir","kanqa"]),L.CONDITION_PREDICATES=new Set(["empty","null","undefined"]),L.CONDITION_OPERATORS=new Set(["matches","match","contains","exists","has","have","equals","includes"]),L.STANDALONE_MODIFIERS={once:"once",debounced:"debounce",debounce:"debounce",throttled:"throttle",throttle:"throttle"},L.OR_KEYWORDS=new Set(["or","\u0623\u0648","o","ou","oder","atau","atau","\u6216","\u307E\u305F\u306F","\uB610\uB294","veya","\u0985\u09A5\u09AC\u09BE","utaq","au","\u0430\u0431\u043E","\u0438\u043B\u0438","ho\u1EB7c","lub","\u05D0\u05D5","\u0E2B\u0E23\u0E37\u0E2D","o","\u092F\u093E","\u0985\u09A5\u09AC\u09BE"]);var vt=L,Kt=new vt;function Me(o,e){return Kt.parse(o,e)}function Ft(o,e){return Kt.canParse(o,e)}function Ut(o,e){if(me(o))return o;let t=Me(o,e);return Ye(t)}function Ht(o,e){let t=Re(o);return Ge(t,e)}function Gt(o,e){return me(o)?Re(o):Me(o,e)}Tt("ar",mt,ke);var ha="1.0.0-ar",ya=["ar"];function ga(){return[...ya]}function qr(o){if(o!=="ar")throw new Error(`Language not supported in this bundle: ${o}. Supported: ar`)}function va(o,e){return qr(e),[...Y(o,e).tokens]}function Kr(o){return qr(o),Q(o)}function ka(o,e){return Kr(o).filter(t=>t.command===e).sort((t,r)=>r.priority-t.priority)}return Jr(xa);})();