@lokascript/semantic 2.6.0 → 2.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 LokaScriptSemanticJa=(()=>{var gt=Object.defineProperty;var qr=Object.getOwnPropertyDescriptor;var Wr=Object.getOwnPropertyNames;var Kr=Object.prototype.hasOwnProperty;var Fr=(o,e)=>{for(var t in e)gt(o,t,{get:e[t],enumerable:!0})},Ur=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Wr(e))!Kr.call(o,n)&&n!==t&&gt(o,n,{get:()=>e[n],enumerable:!(r=qr(e,n))||r.enumerable});return o};var Hr=o=>Ur(gt({},"__esModule",{value:!0}),o);var ma={};Fr(ma,{ASTBuilder:()=>Oe,DEFAULT_CONFIDENCE_THRESHOLD:()=>Ft,HIGH_CONFIDENCE_THRESHOLD:()=>Ut,VERSION:()=>la,buildAST:()=>Yt,canParse:()=>Dt,createCommandNode:()=>H,createEventHandler:()=>me,createLiteral:()=>B,createPropertyPath:()=>ae,createReference:()=>J,createSelector:()=>re,fromExplicit:()=>Wt,getCommandMapper:()=>Me,getPatternsForLanguage:()=>$r,getPatternsForLanguageAndCommand:()=>pa,getProfile:()=>Ze,getSupportedLanguages:()=>ua,getTokenizer:()=>Je,isExplicitSyntax:()=>de,isLanguageSupported:()=>Tt,japaneseProfile:()=>ve,japaneseTokenizer:()=>ut,parse:()=>Ae,parseAny:()=>Kt,parseExplicit:()=>Pe,registerCommandMapper:()=>xt,render:()=>Ue,renderExplicit:()=>He,toExplicit:()=>qt,tokenize:()=>da,tryGetProfile:()=>I});var Ft=.5,Ut=.8;var Gr=new Set(["me","my","myself","you","your","yourself","it","its","result","event","target","body","detail","window","document"]),Yr=new Set(["and","or","not","no"]),Jr=new Set(["true","false","null","undefined"]),Zr=new Set(["is","matches","match","contains","in"]),Xr=new Set(["next","previous","closest","first","last"]),Qr=new Set(["ms","s","seconds","second","milliseconds","millisecond","minutes","minute","hours","hour"]);function Ht(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"&&Zr.has(p.value.toLowerCase())||p.type==="IDENTIFIER"&&Xr.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(T=>/[\d.]/.test(T)),g=t,S=c(T=>/[a-zA-Z]/.test(T));Qr.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();Gr.has(g)?e.push(m("CONTEXT_VAR",y,p)):Yr.has(g)?e.push(m("LOGICAL",y,p)):Jr.has(g)?e.push(m("BOOLEAN",y,p)):e.push(m("IDENTIFIER",y,p));continue}a()}return e.push(m("EOF","",t)),e}var en=new Set(["my","its","your"]),tn=new Set(["is","matches","match","contains","in","exists","does"]),rn=new Set(["next","previous","closest","first","last"]),Ye=class{constructor(){this.tokens=[];this.current=0}parse(e){try{return this.tokens=Ht(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"&&en.has(e.contextType??"")&&this.check("IDENTIFIER")&&!tn.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(rn.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 vt(o){return new Ye().parse(o)}function Y(o,e){switch(o.type){case"literal":return nn(o);case"selector":return on(o,e);case"reference":return an(o);case"property-path":return sn(o,e);case"expression":return ln(o);case"flag":return{type:"literal",value:o.enabled};default:let t=o;throw new Error(`Unknown semantic value type: ${t.type}`)}}function nn(o){let e={type:"literal",value:o.value};return o.dataType?{...e,dataType:o.dataType}:e}function on(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 an(o){return{type:"contextReference",contextType:o.value,name:o.value}}function sn(o,e){return{type:"propertyAccess",object:Y(o.object,e),property:o.property}}function ln(o){let e=vt(o.raw);return!e.success||!e.node?{type:"identifier",name:o.raw}:e.node}function kt(o,e){return o.roles.get(e)}function w(o,e,t){let r=kt(o,e);return r?Y(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 cn={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)}},un={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)}},dn={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)}},pn={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)}},mn={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)}},fn={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)}},hn={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)}},yn={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)}},gn={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})}},vn={action:"log",toAST(o,e){let t=w(o,"patient"),r=[];return t&&r.push(t),R("log",r)}},kn={action:"put",toAST(o,e){let t=w(o,"patient"),r=w(o,"destination"),n=kt(o,"manner")??kt(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)}},xn={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})}},Sn={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)}},bn={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)}},wn={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)}},Tn={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)}},En={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)}},Cn={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)}},Nn={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)}},Pn={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)}},Rn={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)}},Ln={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)}},An={action:"call",toAST(o,e){let t=w(o,"patient");return R("call",t?[t]:[])}},Mn={action:"return",toAST(o,e){let t=w(o,"patient");return R("return",t?[t]:[])}},On={action:"halt",toAST(o,e){let t=o.roles.get("patient");return t?R("halt",[Y(t)]):R("halt",[])}},Vn={action:"throw",toAST(o,e){let t=w(o,"patient");return R("throw",t?[t]:[])}},In={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})}},zn={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)}},_n={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)}},Bn={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)}},jn={action:"make",toAST(o,e){let t=w(o,"patient");return R("make",t?[t]:[])}},$n={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)}},Dn={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)}},qn={action:"js",toAST(o,e){let t=w(o,"patient");return R("js",t?[t]:[])}},Wn={action:"async",toAST(o,e){return R("async",[])}},Kn={action:"if",toAST(o,e){let t=w(o,"condition");return R("if",t?[t]:[])}},Fn={action:"unless",toAST(o,e){let t=w(o,"condition");return R("unless",t?[t]:[])}},Un={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)}},Hn={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)}},Gn={action:"while",toAST(o,e){let t=w(o,"condition");return R("while",t?[t]:[])}},Yn={action:"continue",toAST(o,e){return R("continue",[])}},Jn={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)}},Zn={action:"init",toAST(o,e){return R("init",[])}},Xn={action:"behavior",toAST(o,e){let t=w(o,"patient");return R("behavior",t?[t]:[])}},Qn={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)}},eo={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)}},Gt=new Map([["toggle",cn],["add",un],["remove",dn],["set",pn],["show",mn],["hide",fn],["increment",hn],["decrement",yn],["wait",gn],["log",vn],["put",kn],["fetch",xn],["append",Sn],["prepend",bn],["get",Rn],["take",Ln],["trigger",wn],["send",Tn],["on",eo],["go",En],["transition",Cn],["focus",Nn],["blur",Pn],["call",An],["return",Mn],["halt",On],["throw",Vn],["settle",In],["swap",zn],["morph",_n],["clone",Bn],["measure",$n],["make",jn],["tell",Dn],["default",Jn],["js",qn],["async",Wn],["if",Kn],["unless",Fn],["repeat",Un],["for",Hn],["while",Gn],["continue",Yn],["init",Zn],["behavior",Xn],["install",Qn]]);function Me(o){return Gt.get(o)}function xt(o){Gt.set(o.action,o)}var Oe=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=Me(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]=Y(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(Y(l))}for(let a of i){let l=e.roles.get(a);if(l){let c=this.roleToModifierKey(a);r[c]=Y(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?Y(d):void 0,f=e.roles.get("destination"),m=f?Y(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=Y(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(Y(n));break}case"for":{e.loopVariable&&r.push({type:"string",value:e.loopVariable});let n=e.roles.get("source");n&&r.push(Y(n));break}case"while":case"until":{let n=e.roles.get("condition");n&&r.push(Y(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 Yt(o){let e=new Oe;return{ast:e.build(o),warnings:e.warnings}}var ye=new Map,ge=new Map,Ve=new Map;var Jt=null;function Xt(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]=Xt(i,n):t[r]=n)}return t}function Qt(o,e){return Xt(o,e)}function St(o){if(!o.extends)return o;let e=ge.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=St(e);return Qt(t,o)}function bt(o,e,t){ye.set(o,e),ge.set(o,t),Ve.delete(o)}var Zt=new Map;function be(o){return o.split("-")[0]}function we(o){return o.includes("-")}function Je(o){let e=ye.get(o);if(!e&&we(o)){let t=be(o);e=ye.get(t)}if(!e){let t=Array.from(ye.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 Ze(o){let e=ge.get(o);if(!e&&we(o)){let t=be(o);e=ge.get(t)}if(!e){let t=Array.from(ge.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 St(e)}function I(o){let e=ge.get(o);return!e&&we(o)&&(e=ge.get(be(o))),e?St(e):void 0}function wt(){return Array.from(ye.keys())}function Tt(o){return ye.has(o)?!0:we(o)?ye.has(be(o)):!1}function er(o,e){return Je(e).tokenize(o)}function Q(o){let e=Ve.get(o);if(!e&&we(o)&&(e=Ve.get(be(o))),e)return e;let t=Zt.get(o);if(!t&&we(o)&&(t=Zt.get(be(o))),t)return Ve.set(o,t),t;if(!Jt)throw new Error(`No patterns registered for language '${o}'. Either import the language module or set a pattern generator.`);let r=Ze(o),n=Jt(r);return Ve.set(o,n),n}function Et(o,e){return Q(o).filter(t=>t.command===e).sort((t,r)=>r.priority-t.priority)}var ve={code:"ja",name:"Japanese",nativeName:"\u65E5\u672C\u8A9E",regions:["east-asian","priority"],direction:"ltr",script:"cjk",wordOrder:"SOV",markingStrategy:"particle",usesSpaces:!1,defaultVerbForm:"base",verb:{position:"end",suffixes:["\u308B","\u3066","\u305F","\u307E\u3059","\u306A\u3044"],subjectDrop:!0},references:{me:"\u81EA\u5206",it:"\u305D\u308C",you:"\u3042\u306A\u305F",result:"\u7D50\u679C",event:"\u30A4\u30D9\u30F3\u30C8",target:"\u30BF\u30FC\u30B2\u30C3\u30C8",body:"\u30DC\u30C7\u30A3"},possessive:{marker:"\u306E",markerPosition:"between",keywords:{\u79C1\u306E:"me",\u3042\u306A\u305F\u306E:"you",\u305D\u306E:"it"}},roleMarkers:{patient:{primary:"\u3092",position:"after"},destination:{primary:"\u306B",alternatives:["\u3078","\u3067","\u306E"],position:"after"},source:{primary:"\u304B\u3089",position:"after"},style:{primary:"\u3067",position:"after"},event:{primary:"\u3092",position:"after"}},keywords:{toggle:{primary:"\u5207\u308A\u66FF\u3048",alternatives:["\u5207\u308A\u66FF\u3048\u308B","\u30C8\u30B0\u30EB","\u30C8\u30B0\u30EB\u3059\u308B"],normalized:"toggle"},add:{primary:"\u8FFD\u52A0",alternatives:["\u8FFD\u52A0\u3059\u308B","\u52A0\u3048\u308B"],normalized:"add"},remove:{primary:"\u524A\u9664",alternatives:["\u524A\u9664\u3059\u308B","\u53D6\u308A\u9664\u304F"],normalized:"remove"},put:{primary:"\u7F6E\u304F",alternatives:["\u5165\u308C\u308B"],normalized:"put"},append:{primary:"\u672B\u5C3E\u8FFD\u52A0",alternatives:["\u672B\u5C3E\u306B\u8FFD\u52A0","\u30A2\u30DA\u30F3\u30C9"],normalized:"append"},prepend:{primary:"\u5148\u982D\u8FFD\u52A0",alternatives:["\u5148\u982D\u306B\u8FFD\u52A0","\u30D7\u30EA\u30DA\u30F3\u30C9"],normalized:"prepend"},take:{primary:"\u53D6\u308B",normalized:"take"},make:{primary:"\u4F5C\u308B",alternatives:["\u4F5C\u6210"],normalized:"make"},clone:{primary:"\u8907\u88FD",alternatives:["\u30AF\u30ED\u30FC\u30F3"],normalized:"clone"},swap:{primary:"\u4EA4\u63DB",alternatives:["\u30B9\u30EF\u30C3\u30D7","\u5165\u308C\u66FF\u3048"],normalized:"swap"},morph:{primary:"\u5909\u5F62",alternatives:["\u30E2\u30FC\u30D5","\u5909\u63DB"],normalized:"morph"},set:{primary:"\u8A2D\u5B9A",alternatives:["\u8A2D\u5B9A\u3059\u308B"],normalized:"set"},get:{primary:"\u53D6\u5F97",alternatives:["\u53D6\u5F97\u3059\u308B","\u30B2\u30C3\u30C8"],normalized:"get"},increment:{primary:"\u5897\u52A0",alternatives:["\u5897\u3084\u3059","\u30A4\u30F3\u30AF\u30EA\u30E1\u30F3\u30C8"],normalized:"increment"},decrement:{primary:"\u6E1B\u5C11",alternatives:["\u6E1B\u3089\u3059","\u30C7\u30AF\u30EA\u30E1\u30F3\u30C8"],normalized:"decrement"},log:{primary:"\u8A18\u9332",alternatives:["\u30ED\u30B0","\u51FA\u529B"],normalized:"log"},show:{primary:"\u8868\u793A",alternatives:["\u8868\u793A\u3059\u308B","\u898B\u305B\u308B"],normalized:"show"},hide:{primary:"\u96A0\u3059",alternatives:["\u975E\u8868\u793A","\u975E\u8868\u793A\u306B\u3059\u308B"],normalized:"hide"},transition:{primary:"\u9077\u79FB",alternatives:["\u30C8\u30E9\u30F3\u30B8\u30B7\u30E7\u30F3","\u30A2\u30CB\u30E1\u30FC\u30B7\u30E7\u30F3"],normalized:"transition"},on:{primary:"\u3067",alternatives:["\u6642"],normalized:"on"},trigger:{primary:"\u5F15\u304D\u91D1",alternatives:["\u767A\u706B","\u30C8\u30EA\u30AC\u30FC"],normalized:"trigger"},send:{primary:"\u9001\u308B",alternatives:["\u9001\u4FE1"],normalized:"send"},focus:{primary:"\u30D5\u30A9\u30FC\u30AB\u30B9",alternatives:["\u96C6\u4E2D"],normalized:"focus"},blur:{primary:"\u307C\u304B\u3057",alternatives:["\u30D5\u30A9\u30FC\u30AB\u30B9\u89E3\u9664","\u30D6\u30E9\u30FC"],normalized:"blur"},empty:{primary:"\u7A7A\u306B",alternatives:["\u7A7A\u306B\u3059\u308B"],normalized:"empty"},open:{primary:"\u958B\u304F",alternatives:["\u30AA\u30FC\u30D7\u30F3"],normalized:"open"},close:{primary:"\u9589\u3058\u308B",alternatives:["\u30AF\u30ED\u30FC\u30BA"],normalized:"close"},select:{primary:"\u9078\u3076",alternatives:["\u30BB\u30EC\u30AF\u30C8"],normalized:"select"},clear:{primary:"\u30AF\u30EA\u30A2",alternatives:["\u6D88\u53BB"],normalized:"clear"},reset:{primary:"\u30EA\u30BB\u30C3\u30C8",alternatives:["\u518D\u8A2D\u5B9A"],normalized:"reset"},breakpoint:{primary:"\u30D6\u30EC\u30FC\u30AF\u30DD\u30A4\u30F3\u30C8",normalized:"breakpoint"},go:{primary:"\u79FB\u52D5",alternatives:["\u884C\u304F","\u30CA\u30D3\u30B2\u30FC\u30C8"],normalized:"go"},scroll:{primary:"\u30B9\u30AF\u30ED\u30FC\u30EB",normalized:"scroll"},push:{primary:"\u30D7\u30C3\u30B7\u30E5",normalized:"push"},replace:{primary:"\u7F6E\u63DB",alternatives:["\u7F6E\u304D\u63DB\u3048"],normalized:"replace"},process:{primary:"\u51E6\u7406",normalized:"process"},wait:{primary:"\u5F85\u3064",alternatives:["\u5F85\u6A5F"],normalized:"wait"},fetch:{primary:"\u30D5\u30A7\u30C3\u30C1",normalized:"fetch"},settle:{primary:"\u5B89\u5B9A",alternatives:["\u843D\u3061\u7740\u304F"],normalized:"settle"},if:{primary:"\u3082\u3057",normalized:"if"},when:{primary:"\u3068\u304D",alternatives:["\u3068\u304D\u306B"],normalized:"when"},where:{primary:"\u3069\u3053",normalized:"where"},else:{primary:"\u305D\u3046\u3067\u306A\u3051\u308C\u3070",alternatives:["\u305D\u308C\u4EE5\u5916"],normalized:"else"},unless:{primary:"\u306A\u3044\u9650\u308A",normalized:"unless"},repeat:{primary:"\u7E70\u308A\u8FD4\u3057",alternatives:["\u7E70\u308A\u8FD4\u3059","\u30EA\u30D4\u30FC\u30C8"],normalized:"repeat"},for:{primary:"\u305F\u3081\u306B",alternatives:["\u5404"],normalized:"for"},while:{primary:"\u306E\u9593",alternatives:["\u9593"],normalized:"while"},forever:{primary:"forever",normalized:"forever"},continue:{primary:"\u7D9A\u3051\u308B",alternatives:["\u7D99\u7D9A"],normalized:"continue"},halt:{primary:"\u505C\u6B62",alternatives:["\u6B62\u3081\u308B","\u30CF\u30EB\u30C8"],normalized:"halt"},throw:{primary:"\u6295\u3052\u308B",alternatives:["\u30B9\u30ED\u30FC"],normalized:"throw"},call:{primary:"\u547C\u3073\u51FA\u3057",alternatives:["\u30B3\u30FC\u30EB","\u547C\u3076"],normalized:"call"},return:{primary:"\u623B\u308B",alternatives:["\u8FD4\u3059","\u30EA\u30BF\u30FC\u30F3"],normalized:"return"},then:{primary:"\u305D\u308C\u304B\u3089",alternatives:["\u6B21\u306B","\u306A\u3089\u3070","\u306A\u3089"],normalized:"then"},and:{primary:"\u307E\u305F",alternatives:["\u3068","\u305D\u3057\u3066"],normalized:"and"},end:{primary:"\u7D42\u308F\u308A",alternatives:["\u304A\u308F\u308A"],normalized:"end"},js:{primary:"JS\u5B9F\u884C",alternatives:["js"],normalized:"js"},async:{primary:"\u975E\u540C\u671F",alternatives:["\u30A2\u30B7\u30F3\u30AF"],normalized:"async"},tell:{primary:"\u4F1D\u3048\u308B",alternatives:["\u30C6\u30EB"],normalized:"tell"},default:{primary:"\u65E2\u5B9A",alternatives:["\u30C7\u30D5\u30A9\u30EB\u30C8"],normalized:"default"},init:{primary:"\u521D\u671F\u5316",alternatives:["\u30A4\u30CB\u30C3\u30C8"],normalized:"init"},behavior:{primary:"\u632F\u308B\u821E\u3044",alternatives:["\u30D3\u30D8\u30A4\u30D3\u30A2"],normalized:"behavior"},install:{primary:"\u30A4\u30F3\u30B9\u30C8\u30FC\u30EB",alternatives:["\u5C0E\u5165"],normalized:"install"},measure:{primary:"\u6E2C\u5B9A",alternatives:["\u8A08\u6E2C","\u30E1\u30B8\u30E3\u30FC"],normalized:"measure"},beep:{primary:"\u30D3\u30FC\u30D7",normalized:"beep"},break:{primary:"\u4E2D\u65AD",normalized:"break"},copy:{primary:"\u30B3\u30D4\u30FC",normalized:"copy"},exit:{primary:"\u9000\u51FA",normalized:"exit"},pick:{primary:"\u9078\u629E",normalized:"pick"},render:{primary:"\u63CF\u753B",normalized:"render"},into:{primary:"\u3078",alternatives:["\u306B"],normalized:"into"},before:{primary:"\u524D\u306B",alternatives:["\u524D"],normalized:"before"},after:{primary:"\u5F8C\u306B",alternatives:["\u5F8C"],normalized:"after"},until:{primary:"\u307E\u3067",alternatives:["\u8FC4"],normalized:"until"},event:{primary:"\u30A4\u30D9\u30F3\u30C8",alternatives:["\u4E8B\u8C61"],normalized:"event"},from:{primary:"\u304B\u3089",normalized:"from"},connect:{primary:"\u63A5\u7D9A",alternatives:["\u63A5\u7D9A\u3059\u308B"],normalized:"connect"},stream:{primary:"\u30B9\u30C8\u30EA\u30FC\u30E0",alternatives:["\u914D\u4FE1"],normalized:"stream"},live:{primary:"\u30E9\u30A4\u30D6",alternatives:["\u5B9F\u6642\u9593"],normalized:"live"},socket:{primary:"\u30BD\u30B1\u30C3\u30C8",alternatives:["websocket"],normalized:"socket"},bind:{primary:"\u30D0\u30A4\u30F3\u30C9",alternatives:["\u7D50\u3073\u3064\u3051\u308B","bind"],normalized:"bind"},intercept:{primary:"\u30A4\u30F3\u30BF\u30FC\u30BB\u30D7\u30C8",alternatives:["\u508D\u53D7","intercept"],normalized:"intercept"},worker:{primary:"\u30EF\u30FC\u30AB\u30FC",alternatives:["worker"],normalized:"worker"},eventsource:{primary:"eventsource",alternatives:["\u30A4\u30D9\u30F3\u30C8\u30BD\u30FC\u30B9"],normalized:"eventsource"}},tokenization:{particles:["\u3092","\u306B","\u3067","\u304B\u3089","\u306E","\u304C","\u306F","\u3082","\u3078","\u3068"],boundaryStrategy:"particle"},eventHandler:{eventMarker:{primary:"\u3067",position:"after"},temporalMarkers:["\u6642","\u3068\u304D"]}};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 Qe(o,e){return{type:"property-path",object:o,property:e}}function Ct(o,e=!0){return{type:"flag",name:o,enabled:e}}function rr(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 Nt(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 nr(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 or(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 Pt=new Set(["me","you","it","result","event","target","body"]);function et(o,e=Pt){return e.has(o)}var tr=new Set(["body","then","else","condition","loop-body","variable","catch","finally"]);function to(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 tt(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=no(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??Pt,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,Ct(x,C));continue}throw new Error(`Unknown flag "${x}" for command "${a}". Valid roles: ${[...u].join(", ")}`)}l.set(x,Ct(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&&!tr.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(tr.has(y)&&S.startsWith("[")&&to(S)){let C=io(p,h+1),x=p.slice(h+1,C+1);l.set(g,{type:"expression",raw:x});continue}let T=oo(S,c);l.set(g,T)}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(Nt("on",l,[],{sourceLanguage:"explicit"}));throw new Error("Event handler requires event role: [on event:click ...]")}let p=Xe(l,"body",e);return l.delete("body"),f(Nt("on",l,p,{sourceLanguage:"explicit"}))}case"if":{let m=Xe(l,"then",e),p=Xe(l,"else",e);return l.delete("then"),l.delete("else"),f(nr(a,l,m,p.length>0?p:void 0,{sourceLanguage:"explicit"}))}case"repeat":{let m=Xe(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,T=y?.type==="literal"&&typeof y.value=="string"?y.value:void 0;return f(or(a,l,g,m,S,T,{sourceLanguage:"explicit"}))}default:return f(rr(a,l,{sourceLanguage:"explicit"}))}}function de(o){let e=o.trim();return e.startsWith("[")&&e.endsWith("]")}function Xe(o,e,t){let r=o.get(e);return r?r.type==="expression"?[tt(r.raw,t)]:[]:[]}function ro(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 no(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 oo(o,e){if(o.startsWith("#")||o.startsWith(".")||o.startsWith("[")||o.startsWith("@")||o.startsWith("*"))return Ie(o,ro(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(et(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 io(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=ao(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 ao(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}:${ir(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 ir(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`${ir(o.object)}'s ${o.property}`;case"expression":return o.raw;case"flag":return o.name}}var so=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 lo(o){return new so(o)}function Ee(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 co(o,e){return o?.possessive?.keywords?.[e]}function ar(o){return!1}var ze=class Ce{constructor(){this.logger=lo("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&&!Ee(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&&!Ee(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&&!Ee(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&&!Ee(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&&!Ee(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&&!Ee(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=co(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()),Qe(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<Ce.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<Ce.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<Ce.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(),Qe(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 Qe(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<=Ce.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 ar(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 ar(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(Ce.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}};ze.MAX_MARKER_SCAN=3;ze.MAX_PROPERTY_DEPTH=10;ze.MAX_METHOD_ARGS=20;ze.ENGLISH_NOISE_WORDS=new Set(["the","a","an"]);var uo=ze,Ya=new uo;var Rt=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}},Lt=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 po(o){return"setContext"in o&&typeof o.setContext=="function"}function mo(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 X=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 j(o,e){return{start:o,end:e}}function $(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 pe(o){return/\s/.test(o)}function rt(o){return o==="#"||o==="."||o==="["||o==="@"||o==="*"||o==="<"}function nt(o){return o==='"'||o==="'"||o==="`"||o==="\u300C"||o==="\u300D"}function ie(o){return/\d/.test(o)}function ot(o){return/[a-zA-Z]/.test(o)}function W(o){return/[a-zA-Z0-9_-]/.test(o)}function sr(o,e){if(e>=o.length)return null;let t=o[e];if(!rt(t))return null;let r=e,n="";if(t==="#"||t==="."){for(n+=o[r++];r<o.length&&W(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&&W(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&&W(o[r]);)n+=o[r++];if(n.length<=1)return null}else if(t==="*"){for(n+=o[r++];r<o.length&&W(o[r]);)n+=o[r++];if(n.length<=1)return null}else if(t==="<"){if(n+=o[r++],r>=o.length||!ot(o[r]))return null;for(;r<o.length&&W(o[r]);)n+=o[r++];for(;r<o.length;){let i=o[r];if(i==="."){if(n+=o[r++],r>=o.length||!W(o[r]))return null;for(;r<o.length&&W(o[r]);)n+=o[r++]}else if(i==="#"){if(n+=o[r++],r>=o.length||!W(o[r]))return null;for(;r<o.length&&W(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&&pe(o[r]);)n+=o[r++];if(r<o.length&&o[r]==="/")for(n+=o[r++];r<o.length&&pe(o[r]);)n+=o[r++];if(r>=o.length||o[r]!==">")return null;n+=o[r++]}return n||null}function fo(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 pe(r)||r==="*"||!W(r)}function lr(o,e){if(e>=o.length)return null;let t=o[e];if(!nt(t)||t==="'"&&fo(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 cr(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 ur(o,e){if(!cr(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 dr(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 ho=["===","!==","->","==","!=","<=",">=","&&","||","**","+=","-=","*=","/=","+","-","*","/","=",">","<","!","&","|","%","^","~"];var es=new Set(ho),yo=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"]),go=["click","dblclick","input","change","submit","keydown","keyup","keypress","mousedown","mouseup","mouseover","mouseout","mouseenter","mouseleave","mousemove","pointerdown","pointerup","pointermove","focus","blur","load","resize","scroll"],pr=class mr{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){po(e)&&e.setContext(mo(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&&pe(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($(a.value,this.classifyToken(a.value),j(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($(s,a,j(r,r+1))),r++}}return new X(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($(".","operator",j(t,t+1))),!0;let l=t+1;for(;l<e.length&&W(e[l]);)l++;return l<e.length&&e[l]==="("?(r.push($(".","operator",j(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 go)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(" ")&&!yo.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 $(r.native,"keyword",j(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 $(i.native,"keyword",j(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 $(e,"keyword",j(t,r),s)}trySelector(e,t){let r=sr(e,t);return r?$(r,"selector",j(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{...$(n,"event-modifier",j(t,t+n.length)),metadata:{modifierName:i,value:s?i==="queue"?s:parseInt(s,10):void 0}}}tryString(e,t){let r=lr(e,t);return r?$(r,"literal",j(t,t+r.length)):null}tryNumber(e,t){let r=dr(e,t);return r?$(r,"literal",j(t,t+r.length)):null}tryMatchTimeUnit(e,t,r,n=!1){let i=t;if(n)for(;i<e.length&&pe(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(W(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,...mr.STANDARD_TIME_UNITS],u=this.tryMatchTimeUnit(e,c,d,s);return u&&(l+=u.suffix,c=u.endPos),$(l,"literal",j(t,c))}tryUrl(e,t){let r=ur(e,t);return r?$(r,"url",j(t,t+r.length)):null}tryVariableRef(e,t){if(e[t]!==":"||t+1>=e.length||!W(e[t+1]))return null;let r=t+1;for(;r<e.length&&W(e[r]);)r++;let n=e.slice(t,r);return $(n,"identifier",j(t,r))}tryOperator(e,t){let r=e.slice(t,t+2);if(["==","!=","<=",">=","&&","||","->"].includes(r))return $(r,"operator",j(t,t+2));let n=e[t];return["<",">","!","+","-","*","/","="].includes(n)?$(n,"operator",j(t,t+1)):["(",")","{","}",",",";",":"].includes(n)?$(n,"punctuation",j(t,t+1)):null}tryMultiCharParticle(e,t,r){for(let n of r)if(e.slice(t,t+n.length)===n)return $(n,"particle",j(t,t+n.length));return null}};pr.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 _e=pr;function At(o){return{stem:o,confidence:1}}function Be(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 B(o,e){let t={type:"literal",value:o};return e!==void 0?{type:"literal",value:o,dataType:e}:t}function ke(o){return et(o)}function J(o){return{type:"reference",value:o}}function ae(o,e){return{type:"property-path",object:o,property:e}}function H(o,e,t){let r={kind:"command",action:o,roles:new Map(Object.entries(e))};return t!==void 0?{...r,metadata:t}:r}function me(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 fr(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 hr(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 je(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 yr(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 vo={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)"}},ko={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"}},xo={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"}},So={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"}},bo={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>"}},wo={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>"}},To={action:"live",description:"Reactive block: re-run the body when its dependencies change",category:"control-flow",primaryRole:"patient",hasBody:!0,bareKeyword:!0,roles:[]},Eo={action:"eventsource",description:"Open a Server-Sent Events stream and handle its events",category:"async",primaryRole:"patient",hasBody:!0,bareKeyword:!0,roles:[]},Co={action:"socket",description:"Open a WebSocket and handle its messages",category:"async",primaryRole:"patient",hasBody:!0,bareKeyword:!0,roles:[]},No={action:"worker",description:"Define a Web Worker with inline methods",category:"async",primaryRole:"patient",hasBody:!0,bareKeyword:!0,roles:[]},Po={action:"intercept",description:"Service-worker fetch interception / caching strategies",category:"async",primaryRole:"patient",hasBody:!0,bareKeyword:!0,roles:[]},Ro={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}]},Lo={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}]},Ao={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}]},Mo={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}]},Oo={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}]},Vo={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}]},Io={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"}}]},zo={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"}}]},_o={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"}}]},Bo={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"}}]},jo={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}]},$o={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}]},Do={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}]},qo={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}]},Wo={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}]},Ko={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}]},Fo={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}]},Uo={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"}}]},Ho={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}]},Go={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}]},Yo={action:"else",description:"Else branch of conditional",category:"control-flow",primaryRole:"patient",hasBody:!0,roles:[]},Jo={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"'},Zo={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"}}]},Xo={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}]},Qo={action:"continue",description:"Continue to next loop iteration",category:"control-flow",primaryRole:"patient",roles:[]},ei={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"]}}]},ti={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}]},ri={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"}}]},ni={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}]},oi={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}]},ii={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}]},ai={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"}}]},si={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}]},li={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}]},ci={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}]},ui={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}]},di={action:"breakpoint",description:"Drop into the debugger",category:"control-flow",primaryRole:"patient",roles:[],bareKeyword:!0},pi={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}]},mi={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}]},fi={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}]},hi={action:"async",description:"Execute commands asynchronously",category:"async",primaryRole:"patient",hasBody:!0,roles:[]},yi={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"}}]},gi={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"}}]},vi={action:"init",description:"Initialization block that runs once",category:"control-flow",primaryRole:"patient",hasBody:!0,roles:[]},ki={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}]},xi={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}]},Si={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"}}]},bi={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"}}]},wi={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"}}]},Ti={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}]},Ei={action:"break",description:"Exit from the current loop",category:"control-flow",primaryRole:"patient",roles:[]},Ci={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}]},Ni={action:"exit",description:"Exit from the current event handler",category:"control-flow",primaryRole:"patient",roles:[],bareKeyword:!0},Pi={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}]},Ri={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"}}]},gr={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"},Li={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"},Ai={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:gr}]},Mi={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:gr}]},Oi={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:Li}]},Vi={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:vo,add:ko,remove:xo,put:So,set:bo,show:Ro,hide:Lo,on:Ao,trigger:Mo,wait:Oo,fetch:Vo,increment:Io,decrement:zo,append:_o,prepend:Bo,log:jo,get:$o,take:Do,make:qo,halt:Wo,settle:Ko,throw:Fo,send:Uo,if:Ho,unless:Go,else:Yo,repeat:Jo,for:Zo,while:Xo,continue:Qo,go:ei,scroll:Ri,push:Ai,replace:Mi,process:Oi,transition:ti,clone:ri,focus:ni,blur:oi,empty:ii,open:ai,close:si,select:li,clear:ci,reset:ui,breakpoint:di,call:pi,return:mi,js:fi,async:hi,tell:yi,default:gi,init:vi,behavior:ki,install:xi,measure:Si,swap:bi,morph:wi,beep:Ti,break:Ei,copy:Ci,exit:Ni,pick:Pi,render:Vi,bind:wo,live:To,eventsource:Eo,socket:Co,worker:No,intercept:Po,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 ce(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 vr=[{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 Mt(o,e,t,r){let n=vr.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 kr(o,e){let t=vr.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 xr=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"]),Ii={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"]},Ot=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:xr.has(r.value)||r.alternatives?.some(n=>xr.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=Ii[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))}},Sr=new Ot;var zi=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??Sr}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 B(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&&(ce(this.currentProfile,i.value)??ce(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(T=>T==="expression"||T==="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,B(`${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 T=e.peek(1);if(T&&(T.kind==="selector"||T.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(),ae(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=ce(this.currentProfile,l)??ce(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||kr(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 ae(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(ce(this.currentProfile,f)??ce(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=ce(this.currentProfile,u)??ce(this.currentProfile,u.toLowerCase()),d)break;return d?(e.advance(),ae(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&&zi.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("}"),B(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 ae(J(i),p.join("."));if(g){let S=e.mark(),T=[],C=0,x=!1;for(;!e.isAtEnd();){let k=e.peek();if(!k)break;if(k.value==="(")C++;else if(k.value===")"){if(T.push(k.value),e.advance(),C--,C===0&&(x=!0),x)break;continue}T.push(k.value),e.advance()}x?m+=T.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 ae(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(),ae(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 ae(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):B(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 B(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 B(n,"string")}if(e==="true")return B(!0,"boolean");if(e==="false")return B(!1,"boolean");let t=e.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/);if(t){let n=parseFloat(t[1]);return t[2]?B(e,"duration"):B(n,"number")}let r=parseFloat(e);return isNaN(r)?B(e,"string"):B(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 Vt=A,se=new Vt;var _i=["===","!==","->","==","!=","<=",">=","&&","||","**","+=","-=","*=","/=","+","-","*","/","=",">","<","!","&","|","%","^","~"],it=class{constructor(e=_i){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}},Bi="()[]{},:;",at=class{constructor(e=Bi){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 It(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 De=class{constructor(){this.name="css-selector"}canExtract(e,t){let r=e[t];return r==="#"||r==="."||r==="["||r==="<"?!0:r==="@"||r==="*"?It(e,t)!==null:!1}extract(e,t){let r=It(e,t);return r?{value:r,length:r.length,metadata:{type:"css-selector"}}:null}};var qe=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 br(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 We=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=br(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"}}}};function ji(o){let e=o.charCodeAt(0);return e>=12352&&e<=12447}function $i(o){let e=o.charCodeAt(0);return e>=12448&&e<=12543}function Di(o){let e=o.charCodeAt(0);return e>=19968&&e<=40879||e>=13312&&e<=19903}function wr(o){return ji(o)||$i(o)||Di(o)}var st=class{constructor(){this.name="japanese-keyword"}setContext(e){this.context=e}canExtract(e,t){return wr(e[t])}extract(e,t){if(!this.context)throw new Error("JapaneseKeywordExtractor: context not set");let r=t;this.context.isKeywordStart(e,t);let n="",i=t;for(;i<e.length&&wr(e[i]);)n+=e[i],i++;let s=n,a=n.length;for(let u=n.length;u>0;u--){let f=n.substring(0,u);if(this.context.lookupKeyword(f)){s=f,a=u;break}}if(n=s,i=t+a,!n)return null;let l=this.context.lookupKeyword(n),c=l&&l.normalized!==l.native?l.normalized:void 0,d;if(!l&&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&&(d=f.normalized)}}return{value:n,length:i-r,metadata:{normalized:c||d}}}};var Tr=new Map([["\u3092",{role:"patient",confidence:.95}],["\u306B",{role:"destination",confidence:.85}],["\u304C",{role:"subject",confidence:.9}],["\u306E",{role:"possessive",confidence:.9}],["\u3068",{role:"conjunction",confidence:.8}],["\u3067",{role:"instrument",confidence:.85}],["\u3078",{role:"direction",confidence:.85}],["\u3084",{role:"listing",confidence:.8}],["\u304B",{role:"question",confidence:.85}],["\u3082",{role:"also",confidence:.85}],["\u306F",{role:"topic",confidence:.9}]]),Er=new Map([["\u304B\u3089",{role:"source",confidence:.95}],["\u307E\u3067",{role:"until",confidence:.95}],["\u3088\u308A",{role:"comparison",confidence:.9}],["\u3068\u3057\u3066",{role:"as",confidence:.9}],["\u306B\u3064\u3044\u3066",{role:"about",confidence:.9}],["\u306B\u3088\u3063\u3066",{role:"by-means",confidence:.9}],["\u306B\u3066",{role:"at-location",confidence:.85}]]),lt=class{constructor(){this.name="japanese-particle"}setContext(e){this._context=e}longerKeywordStartsHere(e,t){if(!this._context)return!1;for(let r=4;r>=2;r--){let n=e.slice(t,t+r);if(n.length===r&&this._context.isKeyword(n))return!0}return!1}canExtract(e,t){let r=e[t];if(Tr.has(r)&&!this.longerKeywordStartsHere(e,t))return!0;for(let[n]of Er)if(e.startsWith(n,t))return!0;return!1}extract(e,t){for(let[i,s]of Er)if(e.startsWith(i,t))return{value:i,length:i.length,metadata:{role:s.role,confidence:s.confidence,variant:i}};let r=e[t];if(this.longerKeywordStartsHere(e,t))return null;let n=Tr.get(r);return n?{value:r,length:1,metadata:{role:n.role,confidence:n.confidence,variant:r}}:null}};function qi(o){let e=o.charCodeAt(0);return e>=65&&e<=90||e>=97&&e<=122||e===95||e===36}function Wi(o){let e=o.charCodeAt(0);return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===95||e===36}var ct=class{constructor(){this.name="ascii-identifier"}setContext(e){this.context=e}canExtract(e,t){return qi(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&&Wi(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 Cr(){return[new We,new qe,new Ke,new De]}var Ki=[{pattern:"\u3057\u305F\u3089",confidence:.88,conjugationType:"conditional-tara",minStemLength:2},{pattern:"\u3059\u308B\u3068",confidence:.88,conjugationType:"conditional-to",minStemLength:2},{pattern:"\u3059\u308C\u3070",confidence:.85,conjugationType:"conditional-ba",minStemLength:2},{pattern:"\u305F\u3089",confidence:.85,conjugationType:"conditional-tara",minStemLength:2},{pattern:"\u308C\u3070",confidence:.82,conjugationType:"conditional-ba",minStemLength:2},{pattern:"\u3066\u3044\u307E\u3057\u305F",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"\u3066\u3044\u307E\u3059",confidence:.85,conjugationType:"progressive",minStemLength:2},{pattern:"\u3066\u304F\u3060\u3055\u3044",confidence:.85,conjugationType:"request",minStemLength:2},{pattern:"\u3067\u304F\u3060\u3055\u3044",confidence:.85,conjugationType:"request",minStemLength:2},{pattern:"\u3066\u3044\u308B",confidence:.85,conjugationType:"progressive",minStemLength:2},{pattern:"\u3066\u304A\u304F",confidence:.82,conjugationType:"progressive",minStemLength:2},{pattern:"\u3066\u307F\u308B",confidence:.82,conjugationType:"progressive",minStemLength:2},{pattern:"\u3066\u3042\u308B",confidence:.82,conjugationType:"progressive",minStemLength:2},{pattern:"\u3066\u304F\u308C",confidence:.8,conjugationType:"casual-request",minStemLength:2},{pattern:"\u3067\u304F\u308C",confidence:.8,conjugationType:"casual-request",minStemLength:2},{pattern:"\u3061\u3083\u3063\u305F",confidence:.82,conjugationType:"contracted-past",minStemLength:2},{pattern:"\u3058\u3083\u3063\u305F",confidence:.82,conjugationType:"contracted-past",minStemLength:2},{pattern:"\u3061\u3083\u3046",confidence:.82,conjugationType:"contracted",minStemLength:2},{pattern:"\u3058\u3083\u3046",confidence:.82,conjugationType:"contracted",minStemLength:2},{pattern:"\u307E\u3057\u305F",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"\u307E\u305B\u3093",confidence:.85,conjugationType:"negative",minStemLength:2},{pattern:"\u307E\u3059",confidence:.85,conjugationType:"polite",minStemLength:2},{pattern:"\u3066",confidence:.85,conjugationType:"te-form",minStemLength:2},{pattern:"\u305F",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"\u306A\u3044",confidence:.82,conjugationType:"negative",minStemLength:2},{pattern:"\u306A\u304B\u3063\u305F",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"\u3089\u308C\u308B",confidence:.8,conjugationType:"potential",minStemLength:2},{pattern:"\u308C\u308B",confidence:.78,conjugationType:"potential",minStemLength:2},{pattern:"\u3089\u308C\u305F",confidence:.8,conjugationType:"passive",minStemLength:2},{pattern:"\u3055\u305B\u308B",confidence:.8,conjugationType:"causative",minStemLength:2},{pattern:"\u305B\u308B",confidence:.78,conjugationType:"causative",minStemLength:2},{pattern:"\u3088\u3046",confidence:.8,conjugationType:"volitional",minStemLength:2},{pattern:"\u308B",confidence:.75,conjugationType:"dictionary",minStemLength:3}],Fi=[{pattern:"\u3057\u305F\u3089",confidence:.88,conjugationType:"conditional-tara"},{pattern:"\u3059\u308B\u3068",confidence:.88,conjugationType:"conditional-to"},{pattern:"\u3059\u308C\u3070",confidence:.85,conjugationType:"conditional-ba"},{pattern:"\u3057\u3066\u3044\u307E\u3059",confidence:.85,conjugationType:"progressive"},{pattern:"\u3057\u3066\u3044\u308B",confidence:.85,conjugationType:"progressive"},{pattern:"\u3057\u307E\u3057\u305F",confidence:.85,conjugationType:"past"},{pattern:"\u3057\u307E\u3059",confidence:.85,conjugationType:"polite"},{pattern:"\u3057\u306A\u3044",confidence:.82,conjugationType:"negative"},{pattern:"\u3057\u3066",confidence:.85,conjugationType:"te-form"},{pattern:"\u3057\u305F",confidence:.85,conjugationType:"past"},{pattern:"\u3059\u308B",confidence:.88,conjugationType:"dictionary"}];function Nr(o){let e=o.charCodeAt(0);return e>=12352&&e<=12447}function Ui(o){let e=o.charCodeAt(0);return e>=12448&&e<=12543}function Hi(o){let e=o.charCodeAt(0);return e>=19968&&e<=40959||e>=13312&&e<=19903}function Gi(o){for(let e of o)if(Nr(e)||Ui(e)||Hi(e))return!0;return!1}var Fe=class{constructor(){this.language="ja"}isNormalizable(e){if(!Gi(e)||e.length<2)return!1;let t=e[e.length-1];return Nr(t)}normalize(e){let t=this.normalizeCompound(e);if(t)return t;let r=this.trySuruNormalization(e);if(r)return r;for(let n of Ki)if(e.endsWith(n.pattern)){let i=e.slice(0,-n.pattern.length),s=n.minStemLength??2;if(i.length<s)continue;let a={removedSuffixes:[n.pattern]};return n.conjugationType&&(a.conjugationType=n.conjugationType),Be(i,n.confidence,a)}return At(e)}trySuruNormalization(e){for(let t of Fi)if(e.endsWith(t.pattern)){let r=e.slice(0,-t.pattern.length);if(r.length<1)continue;return Be(r,t.confidence,{removedSuffixes:[t.pattern],conjugationType:t.conjugationType,originalForm:"suru-verb"})}return null}normalizeCompound(e){let t=[{pattern:"\u3066\u3044\u306A\u304B\u3063\u305F",suffixes:["\u3066","\u3044","\u306A\u304B\u3063\u305F"],confidence:.8,minStemLength:2},{pattern:"\u3067\u3044\u306A\u304B\u3063\u305F",suffixes:["\u3067","\u3044","\u306A\u304B\u3063\u305F"],confidence:.8,minStemLength:2},{pattern:"\u3066\u3044\u306A\u3044",suffixes:["\u3066","\u3044","\u306A\u3044"],confidence:.82,minStemLength:2},{pattern:"\u3067\u3044\u306A\u3044",suffixes:["\u3067","\u3044","\u306A\u3044"],confidence:.82,minStemLength:2},{pattern:"\u3066\u3044\u305F",suffixes:["\u3066","\u3044","\u305F"],confidence:.85,minStemLength:2},{pattern:"\u3067\u3044\u305F",suffixes:["\u3067","\u3044","\u305F"],confidence:.85,minStemLength:2}];for(let{pattern:r,suffixes:n,confidence:i,minStemLength:s}of t)if(e.endsWith(r)){let a=e.slice(0,-r.length);if(a.length<s)continue;return Be(a,i,{removedSuffixes:n,conjugationType:"compound"})}return null}},Ys=new Fe;var Yi=new Set(["\u3092","\u306B","\u3067","\u304B\u3089","\u307E\u3067","\u3078","\u3068","\u306E","\u304C","\u306F","\u3082","\u3088\u308A"]),Ji=[{native:"\u771F",normalized:"true"},{native:"\u507D",normalized:"false"},{native:"\u30CC\u30EB",normalized:"null"},{native:"\u672A\u5B9A\u7FA9",normalized:"undefined"},{native:"\u6700\u521D",normalized:"first"},{native:"\u6700\u5F8C",normalized:"last"},{native:"\u6B21",normalized:"next"},{native:"\u524D",normalized:"previous"},{native:"\u6700\u3082\u8FD1\u3044",normalized:"closest"},{native:"\u89AA",normalized:"parent"},{native:"\u30AF\u30EA\u30C3\u30AF",normalized:"click"},{native:"\u5909\u66F4",normalized:"change"},{native:"\u9001\u4FE1",normalized:"submit"},{native:"\u5165\u529B",normalized:"input"},{native:"\u30ED\u30FC\u30C9",normalized:"load"},{native:"\u8AAD\u307F\u8FBC\u307F",normalized:"load"},{native:"\u30B9\u30AF\u30ED\u30FC\u30EB",normalized:"scroll"},{native:"\u30AD\u30FC\u30C0\u30A6\u30F3",normalized:"keydown"},{native:"\u30AD\u30FC\u30A2\u30C3\u30D7",normalized:"keyup"},{native:"\u30DE\u30A6\u30B9\u30AA\u30FC\u30D0\u30FC",normalized:"mouseover"},{native:"\u30DE\u30A6\u30B9\u30A2\u30A6\u30C8",normalized:"mouseout"},{native:"\u30DE\u30A6\u30B9\u62BC\u4E0B",normalized:"mousedown"},{native:"\u30DE\u30A6\u30B9\u89E3\u653E",normalized:"mouseup"},{native:"\u307E\u305F\u306F",normalized:"or"},{native:"\u79C1",normalized:"me"},{native:"\u3057\u305F\u3089",normalized:"on"},{native:"\u3059\u308B\u3068",normalized:"on"},{native:"\u6642\u306B",normalized:"on"},{native:"\u79D2",normalized:"s"},{native:"\u30DF\u30EA\u79D2",normalized:"ms"},{native:"\u5206",normalized:"m"},{native:"\u6642\u9593",normalized:"h"}],zt=class extends _e{constructor(){super();this.language="ja";this.direction="ltr";this.initializeKeywordsFromProfile(ve,Ji),this.normalizer=new Fe,this.registerExtractors(Cr()),this.registerExtractor(new Rt),this.registerExtractor(new Lt),this.registerExtractor(new ct),this.registerExtractor(new lt),this.registerExtractor(new st),this.registerExtractor(new it),this.registerExtractor(new at)}classifyToken(t){return Yi.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("'")||t.startsWith("\u300C")||/^\d/.test(t)?"literal":"identifier"}},ut=new zt;function G(o,e){return er(o,e)}function dt(){return wt()}var mt=["if","unless","repeat","for","while"];function le(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 Xi=new Set(mt);function Bt(o,e){let t=o.normalized?.toLowerCase();return t?Xi.has(t):e.some(r=>te(o,r))}var Pr=new Set(["me","it","you","the","body","window","document","its","event","result","target","self","this","them","parent","next","previous","closest","first","last"]),Qi=new Set(["destination","source","style","patient","on","from","to"]);function ea(o){if(!o||o.kind==="selector")return!1;let e=(o.normalized??o.value).toLowerCase(),t=o.value.toLowerCase();return!(Pr.has(e)||Pr.has(t)||Qi.has(e))}var Rr=new Set(["ja","ko"]);function _t(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 Ar(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 Mr(o,e,t){let r=e+1;if(r>=o.length)return-1;let n=_t(I(t)?.roleMarkers?.patient);return n.size>0&&te(o[r],n)&&r++,r<o.length?r:-1}function Or(o,e,t){if(!I(e))return null;let r=le(e,"behavior"),n=le(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=G(o,e).tokens;if(l.length<2)return null;if(te(l[0],r))return Lr(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)?Lr(o,e,l,t,c):te(l[0],n)?ta(o,e,l,t):null}function Vr(o,e,t){let r=I(e);if(!r)return null;let n=r.wordOrder!=="SOV",i=Rr.has(e)?_t(r.roleMarkers?.event):new Set,s=Rr.has(e)?_t(r.keywords?.on):new Set,a=i.size>0&&s.size>0,l=le(e,"end"),c=le(e,"on"),d=o.toLowerCase(),u=[...l].some(k=>d.includes(k)),f=(n||a)&&(()=>{let k=0;for(let E of c)if(E){for(let v=d.indexOf(E);v>=0;v=d.indexOf(E,v+E.length))if(++k>=2)return!0}return!1})();if(!u&&!f)return null;let m=G(o,e).tokens;if(m.length<2)return null;let p=mt.map(k=>le(e,k)),h=k=>Bt(k,p),y=k=>te(k,l),g=[],S=0,T=0;for(let k=0;k<m.length;k++){let E=m[k];if(y(E)){if(S>0){S--;continue}let v=o.slice(m[T].position.start,E.position.start).trim();v&&g.push(v),T=k+1}else if(h(E))S++;else if(n&&S===0&&k>T&&te(E,c)&&ea(m[k+1])){let v=o.slice(m[T].position.start,E.position.start).trim();v&&g.push(v),T=k}else if(a&&S===0&&k-1>T&&te(E,i)&&m[k+1]!==void 0&&te(m[k+1],s)){let v=m[k-1],b=o.slice(m[T].position.start,v.position.start).trim();b&&g.push(b),T=k-1}}if(T<m.length){let k=o.slice(m[T].position.start).trim();k&&g.push(k)}if(g.length<2)return null;let C=[],x=[];for(let k of g){let E;try{E=t.statement(k,e)}catch{return null}if(!E||E.kind!=="event-handler")return null;let v=E;C.push(v);let b=!v.body||v.body.length===0;x.push(b?.2:v.metadata?.confidence??.75)}return je(C,"then",{sourceLanguage:e,confidence:pt(x),sourceText:o})}function pt(o){return o.length>0?o.reduce((e,t)=>e+t,0)/o.length:0}function Ir(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 Lr(o,e,t,r,n){let i=n>0,s=i?0:Mr(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}=Ar(o,a),u=i?n+1:t.findIndex(v=>v.position.start>=d);u<=s&&(u=s+1);let f=le(e,"init"),m=le(e,"end"),p=mt.map(v=>le(e,v)),h=v=>Bt(v,p),y=v=>te(v,m),g=[],S=[],T=[],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 P=o.slice(t[k].position.end,b.position.start).trim();if(P)try{let N=Ir(r.body(P,e));S.push(...N),T.push(pt(N.map(V=>V.metadata?.confidence??.75)))}catch{T.push(0)}}else{let P=o.slice(t[k].position.start,b.position.start).trim();try{let N=r.statement(P,e);if(N&&N.kind==="event-handler"){let V=N;g.push(V);let M=!V.body||V.body.length===0;T.push(M?.2:V.metadata?.confidence??.75)}else T.push(0)}catch{T.push(0)}}k=v+1}else h(b)&&x++}if(g.length===0&&S.length===0)return null;let E=(C?1:.8)*pt(T);return fr(l,c,g,S.length>0?S:void 0,{sourceLanguage:e,confidence:E,sourceText:o})}function ta(o,e,t,r){let n=Mr(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}=Ar(o,i),c=t.findIndex(x=>x.position.start>=l);c<=n&&(c=n+1);let d=le(e,"end"),u=mt.map(x=>le(e,x)),f=x=>Bt(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 T;try{T=Ir(r.body(S,e))}catch{return null}if(T.length===0)return null;let C=pt(T.map(x=>x.metadata?.confidence??.75));return h<0&&(C*=.8),hr(s,a,T,{sourceLanguage:e,confidence:C,sourceText:o})}var xe={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 ra=Object.fromEntries(Object.entries(xe).map(([o,e])=>{let t={};for(let[r,n]of Object.entries(e))n in t||(t[n]=r);return[o,t]})),na={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 zr(o,e){return na[e]?.has(o)?o:ra[e]?.[o]??o}var ft=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=Et(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(`
1
+ "use strict";var LokaScriptSemanticJa=(()=>{var gt=Object.defineProperty;var qr=Object.getOwnPropertyDescriptor;var Wr=Object.getOwnPropertyNames;var Kr=Object.prototype.hasOwnProperty;var Fr=(o,e)=>{for(var t in e)gt(o,t,{get:e[t],enumerable:!0})},Ur=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Wr(e))!Kr.call(o,n)&&n!==t&&gt(o,n,{get:()=>e[n],enumerable:!(r=qr(e,n))||r.enumerable});return o};var Hr=o=>Ur(gt({},"__esModule",{value:!0}),o);var ma={};Fr(ma,{ASTBuilder:()=>Oe,DEFAULT_CONFIDENCE_THRESHOLD:()=>Ft,HIGH_CONFIDENCE_THRESHOLD:()=>Ut,VERSION:()=>la,buildAST:()=>Yt,canParse:()=>$t,createCommandNode:()=>H,createEventHandler:()=>me,createLiteral:()=>B,createPropertyPath:()=>ae,createReference:()=>J,createSelector:()=>re,fromExplicit:()=>Wt,getCommandMapper:()=>Me,getPatternsForLanguage:()=>Dr,getPatternsForLanguageAndCommand:()=>pa,getProfile:()=>Ze,getSupportedLanguages:()=>ua,getTokenizer:()=>Je,isExplicitSyntax:()=>de,isLanguageSupported:()=>Tt,japaneseProfile:()=>ve,japaneseTokenizer:()=>ut,parse:()=>Ae,parseAny:()=>Kt,parseExplicit:()=>Pe,registerCommandMapper:()=>xt,render:()=>Ue,renderExplicit:()=>He,toExplicit:()=>qt,tokenize:()=>da,tryGetProfile:()=>I});var Ft=.5,Ut=.8;var Gr=new Set(["me","my","myself","you","your","yourself","it","its","result","event","target","body","detail","window","document"]),Yr=new Set(["and","or","not","no"]),Jr=new Set(["true","false","null","undefined"]),Zr=new Set(["is","matches","match","contains","in"]),Xr=new Set(["next","previous","closest","first","last"]),Qr=new Set(["ms","s","seconds","second","milliseconds","millisecond","minutes","minute","hours","hour"]);function Ht(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"&&Zr.has(p.value.toLowerCase())||p.type==="IDENTIFIER"&&Xr.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(T=>/[\d.]/.test(T)),g=t,S=c(T=>/[a-zA-Z]/.test(T));Qr.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();Gr.has(g)?e.push(m("CONTEXT_VAR",y,p)):Yr.has(g)?e.push(m("LOGICAL",y,p)):Jr.has(g)?e.push(m("BOOLEAN",y,p)):e.push(m("IDENTIFIER",y,p));continue}a()}return e.push(m("EOF","",t)),e}var en=new Set(["my","its","your"]),tn=new Set(["is","matches","match","contains","in","exists","does"]),rn=new Set(["next","previous","closest","first","last"]),Ye=class{constructor(){this.tokens=[];this.current=0}parse(e){try{return this.tokens=Ht(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"&&en.has(e.contextType??"")&&this.check("IDENTIFIER")&&!tn.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(rn.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 vt(o){return new Ye().parse(o)}function Y(o,e){switch(o.type){case"literal":return nn(o);case"selector":return on(o,e);case"reference":return an(o);case"property-path":return sn(o,e);case"expression":return ln(o);case"flag":return{type:"literal",value:o.enabled};default:let t=o;throw new Error(`Unknown semantic value type: ${t.type}`)}}function nn(o){let e={type:"literal",value:o.value};return o.dataType?{...e,dataType:o.dataType}:e}function on(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 an(o){return{type:"contextReference",contextType:o.value,name:o.value}}function sn(o,e){return{type:"propertyAccess",object:Y(o.object,e),property:o.property}}function ln(o){let e=vt(o.raw);return!e.success||!e.node?{type:"identifier",name:o.raw}:e.node}function kt(o,e){return o.roles.get(e)}function w(o,e,t){let r=kt(o,e);return r?Y(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 cn={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)}},un={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)}},dn={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)}},pn={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)}},mn={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)}},fn={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)}},hn={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)}},yn={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)}},gn={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})}},vn={action:"log",toAST(o,e){let t=w(o,"patient"),r=[];return t&&r.push(t),R("log",r)}},kn={action:"put",toAST(o,e){let t=w(o,"patient"),r=w(o,"destination"),n=kt(o,"manner")??kt(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)}},xn={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})}},Sn={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)}},bn={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)}},wn={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)}},Tn={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)}},En={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)}},Cn={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)}},Nn={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)}},Pn={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)}},Rn={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)}},Ln={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)}},An={action:"call",toAST(o,e){let t=w(o,"patient");return R("call",t?[t]:[])}},Mn={action:"return",toAST(o,e){let t=w(o,"patient");return R("return",t?[t]:[])}},On={action:"halt",toAST(o,e){let t=o.roles.get("patient");return t?R("halt",[Y(t)]):R("halt",[])}},Vn={action:"throw",toAST(o,e){let t=w(o,"patient");return R("throw",t?[t]:[])}},In={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})}},zn={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)}},_n={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)}},Bn={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)}},jn={action:"make",toAST(o,e){let t=w(o,"patient");return R("make",t?[t]:[])}},Dn={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)}},$n={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)}},qn={action:"js",toAST(o,e){let t=w(o,"patient");return R("js",t?[t]:[])}},Wn={action:"async",toAST(o,e){return R("async",[])}},Kn={action:"if",toAST(o,e){let t=w(o,"condition");return R("if",t?[t]:[])}},Fn={action:"unless",toAST(o,e){let t=w(o,"condition");return R("unless",t?[t]:[])}},Un={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)}},Hn={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)}},Gn={action:"while",toAST(o,e){let t=w(o,"condition");return R("while",t?[t]:[])}},Yn={action:"continue",toAST(o,e){return R("continue",[])}},Jn={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)}},Zn={action:"init",toAST(o,e){return R("init",[])}},Xn={action:"behavior",toAST(o,e){let t=w(o,"patient");return R("behavior",t?[t]:[])}},Qn={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)}},eo={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)}},Gt=new Map([["toggle",cn],["add",un],["remove",dn],["set",pn],["show",mn],["hide",fn],["increment",hn],["decrement",yn],["wait",gn],["log",vn],["put",kn],["fetch",xn],["append",Sn],["prepend",bn],["get",Rn],["take",Ln],["trigger",wn],["send",Tn],["on",eo],["go",En],["transition",Cn],["focus",Nn],["blur",Pn],["call",An],["return",Mn],["halt",On],["throw",Vn],["settle",In],["swap",zn],["morph",_n],["clone",Bn],["measure",Dn],["make",jn],["tell",$n],["default",Jn],["js",qn],["async",Wn],["if",Kn],["unless",Fn],["repeat",Un],["for",Hn],["while",Gn],["continue",Yn],["init",Zn],["behavior",Xn],["install",Qn]]);function Me(o){return Gt.get(o)}function xt(o){Gt.set(o.action,o)}var Oe=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=Me(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]=Y(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(Y(l))}for(let a of i){let l=e.roles.get(a);if(l){let c=this.roleToModifierKey(a);r[c]=Y(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?Y(d):void 0,f=e.roles.get("destination"),m=f?Y(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=Y(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(Y(n));break}case"for":{e.loopVariable&&r.push({type:"string",value:e.loopVariable});let n=e.roles.get("source");n&&r.push(Y(n));break}case"while":case"until":{let n=e.roles.get("condition");n&&r.push(Y(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 Yt(o){let e=new Oe;return{ast:e.build(o),warnings:e.warnings}}var ye=new Map,ge=new Map,Ve=new Map;var Jt=null;function Xt(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]=Xt(i,n):t[r]=n)}return t}function Qt(o,e){return Xt(o,e)}function St(o){if(!o.extends)return o;let e=ge.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=St(e);return Qt(t,o)}function bt(o,e,t){ye.set(o,e),ge.set(o,t),Ve.delete(o)}var Zt=new Map;function be(o){return o.split("-")[0]}function we(o){return o.includes("-")}function Je(o){let e=ye.get(o);if(!e&&we(o)){let t=be(o);e=ye.get(t)}if(!e){let t=Array.from(ye.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 Ze(o){let e=ge.get(o);if(!e&&we(o)){let t=be(o);e=ge.get(t)}if(!e){let t=Array.from(ge.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 St(e)}function I(o){let e=ge.get(o);return!e&&we(o)&&(e=ge.get(be(o))),e?St(e):void 0}function wt(){return Array.from(ye.keys())}function Tt(o){return ye.has(o)?!0:we(o)?ye.has(be(o)):!1}function er(o,e){return Je(e).tokenize(o)}function Q(o){let e=Ve.get(o);if(!e&&we(o)&&(e=Ve.get(be(o))),e)return e;let t=Zt.get(o);if(!t&&we(o)&&(t=Zt.get(be(o))),t)return Ve.set(o,t),t;if(!Jt)throw new Error(`No patterns registered for language '${o}'. Either import the language module or set a pattern generator.`);let r=Ze(o),n=Jt(r);return Ve.set(o,n),n}function Et(o,e){return Q(o).filter(t=>t.command===e).sort((t,r)=>r.priority-t.priority)}var ve={code:"ja",name:"Japanese",nativeName:"\u65E5\u672C\u8A9E",regions:["east-asian","priority"],direction:"ltr",script:"cjk",wordOrder:"SOV",markingStrategy:"particle",usesSpaces:!1,defaultVerbForm:"base",verb:{position:"end",suffixes:["\u308B","\u3066","\u305F","\u307E\u3059","\u306A\u3044"],subjectDrop:!0},references:{me:"\u81EA\u5206",it:"\u305D\u308C",you:"\u3042\u306A\u305F",result:"\u7D50\u679C",event:"\u30A4\u30D9\u30F3\u30C8",target:"\u30BF\u30FC\u30B2\u30C3\u30C8",body:"\u30DC\u30C7\u30A3"},possessive:{marker:"\u306E",markerPosition:"between",keywords:{\u79C1\u306E:"me",\u3042\u306A\u305F\u306E:"you",\u305D\u306E:"it"}},roleMarkers:{patient:{primary:"\u3092",position:"after"},destination:{primary:"\u306B",alternatives:["\u3078","\u3067","\u306E"],position:"after"},source:{primary:"\u304B\u3089",position:"after"},style:{primary:"\u3067",position:"after"},event:{primary:"\u3092",position:"after"}},keywords:{toggle:{primary:"\u5207\u308A\u66FF\u3048",alternatives:["\u5207\u308A\u66FF\u3048\u308B","\u30C8\u30B0\u30EB","\u30C8\u30B0\u30EB\u3059\u308B"],normalized:"toggle"},add:{primary:"\u8FFD\u52A0",alternatives:["\u8FFD\u52A0\u3059\u308B","\u52A0\u3048\u308B"],normalized:"add"},remove:{primary:"\u524A\u9664",alternatives:["\u524A\u9664\u3059\u308B","\u53D6\u308A\u9664\u304F"],normalized:"remove"},put:{primary:"\u7F6E\u304F",alternatives:["\u5165\u308C\u308B"],normalized:"put"},append:{primary:"\u672B\u5C3E\u8FFD\u52A0",alternatives:["\u672B\u5C3E\u306B\u8FFD\u52A0","\u30A2\u30DA\u30F3\u30C9"],normalized:"append"},prepend:{primary:"\u5148\u982D\u8FFD\u52A0",alternatives:["\u5148\u982D\u306B\u8FFD\u52A0","\u30D7\u30EA\u30DA\u30F3\u30C9"],normalized:"prepend"},take:{primary:"\u53D6\u308B",normalized:"take"},make:{primary:"\u4F5C\u308B",alternatives:["\u4F5C\u6210"],normalized:"make"},clone:{primary:"\u8907\u88FD",alternatives:["\u30AF\u30ED\u30FC\u30F3"],normalized:"clone"},swap:{primary:"\u4EA4\u63DB",alternatives:["\u30B9\u30EF\u30C3\u30D7","\u5165\u308C\u66FF\u3048"],normalized:"swap"},morph:{primary:"\u5909\u5F62",alternatives:["\u30E2\u30FC\u30D5","\u5909\u63DB"],normalized:"morph"},set:{primary:"\u8A2D\u5B9A",alternatives:["\u8A2D\u5B9A\u3059\u308B"],normalized:"set"},get:{primary:"\u53D6\u5F97",alternatives:["\u53D6\u5F97\u3059\u308B","\u30B2\u30C3\u30C8"],normalized:"get"},increment:{primary:"\u5897\u52A0",alternatives:["\u5897\u3084\u3059","\u30A4\u30F3\u30AF\u30EA\u30E1\u30F3\u30C8"],normalized:"increment"},decrement:{primary:"\u6E1B\u5C11",alternatives:["\u6E1B\u3089\u3059","\u30C7\u30AF\u30EA\u30E1\u30F3\u30C8"],normalized:"decrement"},log:{primary:"\u8A18\u9332",alternatives:["\u30ED\u30B0","\u51FA\u529B"],normalized:"log"},show:{primary:"\u8868\u793A",alternatives:["\u8868\u793A\u3059\u308B","\u898B\u305B\u308B"],normalized:"show"},hide:{primary:"\u96A0\u3059",alternatives:["\u975E\u8868\u793A","\u975E\u8868\u793A\u306B\u3059\u308B"],normalized:"hide"},transition:{primary:"\u9077\u79FB",alternatives:["\u30C8\u30E9\u30F3\u30B8\u30B7\u30E7\u30F3","\u30A2\u30CB\u30E1\u30FC\u30B7\u30E7\u30F3"],normalized:"transition"},on:{primary:"\u3067",alternatives:["\u6642"],normalized:"on"},trigger:{primary:"\u5F15\u304D\u91D1",alternatives:["\u767A\u706B","\u30C8\u30EA\u30AC\u30FC"],normalized:"trigger"},send:{primary:"\u9001\u308B",alternatives:["\u9001\u4FE1"],normalized:"send"},focus:{primary:"\u30D5\u30A9\u30FC\u30AB\u30B9",alternatives:["\u96C6\u4E2D"],normalized:"focus"},blur:{primary:"\u307C\u304B\u3057",alternatives:["\u30D5\u30A9\u30FC\u30AB\u30B9\u89E3\u9664","\u30D6\u30E9\u30FC"],normalized:"blur"},empty:{primary:"\u7A7A\u306B",alternatives:["\u7A7A\u306B\u3059\u308B"],normalized:"empty"},open:{primary:"\u958B\u304F",alternatives:["\u30AA\u30FC\u30D7\u30F3"],normalized:"open"},close:{primary:"\u9589\u3058\u308B",alternatives:["\u30AF\u30ED\u30FC\u30BA"],normalized:"close"},select:{primary:"\u9078\u3076",alternatives:["\u30BB\u30EC\u30AF\u30C8"],normalized:"select"},clear:{primary:"\u30AF\u30EA\u30A2",alternatives:["\u6D88\u53BB"],normalized:"clear"},reset:{primary:"\u30EA\u30BB\u30C3\u30C8",alternatives:["\u518D\u8A2D\u5B9A"],normalized:"reset"},breakpoint:{primary:"\u30D6\u30EC\u30FC\u30AF\u30DD\u30A4\u30F3\u30C8",normalized:"breakpoint"},go:{primary:"\u79FB\u52D5",alternatives:["\u884C\u304F","\u30CA\u30D3\u30B2\u30FC\u30C8"],normalized:"go"},scroll:{primary:"\u30B9\u30AF\u30ED\u30FC\u30EB",normalized:"scroll"},push:{primary:"\u30D7\u30C3\u30B7\u30E5",normalized:"push"},replace:{primary:"\u7F6E\u63DB",alternatives:["\u7F6E\u304D\u63DB\u3048"],normalized:"replace"},process:{primary:"\u51E6\u7406",normalized:"process"},wait:{primary:"\u5F85\u3064",alternatives:["\u5F85\u6A5F"],normalized:"wait"},fetch:{primary:"\u30D5\u30A7\u30C3\u30C1",normalized:"fetch"},settle:{primary:"\u5B89\u5B9A",alternatives:["\u843D\u3061\u7740\u304F"],normalized:"settle"},if:{primary:"\u3082\u3057",normalized:"if"},when:{primary:"\u3068\u304D",alternatives:["\u3068\u304D\u306B"],normalized:"when"},where:{primary:"\u3069\u3053",normalized:"where"},else:{primary:"\u305D\u3046\u3067\u306A\u3051\u308C\u3070",alternatives:["\u305D\u308C\u4EE5\u5916"],normalized:"else"},unless:{primary:"\u306A\u3044\u9650\u308A",normalized:"unless"},repeat:{primary:"\u7E70\u308A\u8FD4\u3057",alternatives:["\u7E70\u308A\u8FD4\u3059","\u30EA\u30D4\u30FC\u30C8"],normalized:"repeat"},for:{primary:"\u305F\u3081\u306B",alternatives:["\u5404"],normalized:"for"},while:{primary:"\u306E\u9593",alternatives:["\u9593"],normalized:"while"},forever:{primary:"forever",normalized:"forever"},continue:{primary:"\u7D9A\u3051\u308B",alternatives:["\u7D99\u7D9A"],normalized:"continue"},halt:{primary:"\u505C\u6B62",alternatives:["\u6B62\u3081\u308B","\u30CF\u30EB\u30C8"],normalized:"halt"},throw:{primary:"\u6295\u3052\u308B",alternatives:["\u30B9\u30ED\u30FC"],normalized:"throw"},call:{primary:"\u547C\u3073\u51FA\u3057",alternatives:["\u30B3\u30FC\u30EB","\u547C\u3076"],normalized:"call"},return:{primary:"\u623B\u308B",alternatives:["\u8FD4\u3059","\u30EA\u30BF\u30FC\u30F3"],normalized:"return"},then:{primary:"\u305D\u308C\u304B\u3089",alternatives:["\u6B21\u306B","\u306A\u3089\u3070","\u306A\u3089"],normalized:"then"},and:{primary:"\u307E\u305F",alternatives:["\u3068","\u305D\u3057\u3066"],normalized:"and"},end:{primary:"\u7D42\u308F\u308A",alternatives:["\u304A\u308F\u308A"],normalized:"end"},js:{primary:"JS\u5B9F\u884C",alternatives:["js"],normalized:"js"},async:{primary:"\u975E\u540C\u671F",alternatives:["\u30A2\u30B7\u30F3\u30AF"],normalized:"async"},tell:{primary:"\u4F1D\u3048\u308B",alternatives:["\u30C6\u30EB"],normalized:"tell"},default:{primary:"\u65E2\u5B9A",alternatives:["\u30C7\u30D5\u30A9\u30EB\u30C8"],normalized:"default"},init:{primary:"\u521D\u671F\u5316",alternatives:["\u30A4\u30CB\u30C3\u30C8"],normalized:"init"},behavior:{primary:"\u632F\u308B\u821E\u3044",alternatives:["\u30D3\u30D8\u30A4\u30D3\u30A2"],normalized:"behavior"},install:{primary:"\u30A4\u30F3\u30B9\u30C8\u30FC\u30EB",alternatives:["\u5C0E\u5165"],normalized:"install"},measure:{primary:"\u6E2C\u5B9A",alternatives:["\u8A08\u6E2C","\u30E1\u30B8\u30E3\u30FC"],normalized:"measure"},beep:{primary:"\u30D3\u30FC\u30D7",normalized:"beep"},break:{primary:"\u4E2D\u65AD",normalized:"break"},copy:{primary:"\u30B3\u30D4\u30FC",normalized:"copy"},exit:{primary:"\u9000\u51FA",normalized:"exit"},pick:{primary:"\u9078\u629E",normalized:"pick"},render:{primary:"\u63CF\u753B",normalized:"render"},into:{primary:"\u3078",alternatives:["\u306B"],normalized:"into"},before:{primary:"\u524D\u306B",alternatives:["\u524D"],normalized:"before"},after:{primary:"\u5F8C\u306B",alternatives:["\u5F8C"],normalized:"after"},until:{primary:"\u307E\u3067",alternatives:["\u8FC4"],normalized:"until"},event:{primary:"\u30A4\u30D9\u30F3\u30C8",alternatives:["\u4E8B\u8C61"],normalized:"event"},from:{primary:"\u304B\u3089",normalized:"from"},connect:{primary:"\u63A5\u7D9A",alternatives:["\u63A5\u7D9A\u3059\u308B"],normalized:"connect"},stream:{primary:"\u30B9\u30C8\u30EA\u30FC\u30E0",alternatives:["\u914D\u4FE1"],normalized:"stream"},live:{primary:"\u30E9\u30A4\u30D6",alternatives:["\u5B9F\u6642\u9593"],normalized:"live"},socket:{primary:"\u30BD\u30B1\u30C3\u30C8",alternatives:["websocket"],normalized:"socket"},bind:{primary:"\u30D0\u30A4\u30F3\u30C9",alternatives:["\u7D50\u3073\u3064\u3051\u308B","bind"],normalized:"bind"},intercept:{primary:"\u30A4\u30F3\u30BF\u30FC\u30BB\u30D7\u30C8",alternatives:["\u508D\u53D7","intercept"],normalized:"intercept"},worker:{primary:"\u30EF\u30FC\u30AB\u30FC",alternatives:["worker"],normalized:"worker"},eventsource:{primary:"eventsource",alternatives:["\u30A4\u30D9\u30F3\u30C8\u30BD\u30FC\u30B9"],normalized:"eventsource"}},tokenization:{particles:["\u3092","\u306B","\u3067","\u304B\u3089","\u306E","\u304C","\u306F","\u3082","\u3078","\u3068"],boundaryStrategy:"particle"},eventHandler:{eventMarker:{primary:"\u3067",position:"after"},temporalMarkers:["\u6642","\u3068\u304D"]}};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 Qe(o,e){return{type:"property-path",object:o,property:e}}function Ct(o,e=!0){return{type:"flag",name:o,enabled:e}}function rr(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 Nt(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 nr(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 or(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 Pt=new Set(["me","you","it","result","event","target","body"]);function et(o,e=Pt){return e.has(o)}var tr=new Set(["body","then","else","condition","loop-body","variable","catch","finally"]);function to(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 tt(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=no(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??Pt,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,Ct(x,C));continue}throw new Error(`Unknown flag "${x}" for command "${a}". Valid roles: ${[...u].join(", ")}`)}l.set(x,Ct(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&&!tr.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(tr.has(y)&&S.startsWith("[")&&to(S)){let C=io(p,h+1),x=p.slice(h+1,C+1);l.set(g,{type:"expression",raw:x});continue}let T=oo(S,c);l.set(g,T)}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(Nt("on",l,[],{sourceLanguage:"explicit"}));throw new Error("Event handler requires event role: [on event:click ...]")}let p=Xe(l,"body",e);return l.delete("body"),f(Nt("on",l,p,{sourceLanguage:"explicit"}))}case"if":{let m=Xe(l,"then",e),p=Xe(l,"else",e);return l.delete("then"),l.delete("else"),f(nr(a,l,m,p.length>0?p:void 0,{sourceLanguage:"explicit"}))}case"repeat":{let m=Xe(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,T=y?.type==="literal"&&typeof y.value=="string"?y.value:void 0;return f(or(a,l,g,m,S,T,{sourceLanguage:"explicit"}))}default:return f(rr(a,l,{sourceLanguage:"explicit"}))}}function de(o){let e=o.trim();return e.startsWith("[")&&e.endsWith("]")}function Xe(o,e,t){let r=o.get(e);return r?r.type==="expression"?[tt(r.raw,t)]:[]:[]}function ro(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 no(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 oo(o,e){if(o.startsWith("#")||o.startsWith(".")||o.startsWith("[")||o.startsWith("@")||o.startsWith("*"))return Ie(o,ro(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(et(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 io(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=ao(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 ao(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}:${ir(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 ir(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`${ir(o.object)}'s ${o.property}`;case"expression":return o.raw;case"flag":return o.name}}var so=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 lo(o){return new so(o)}function Ee(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 co(o,e){return o?.possessive?.keywords?.[e]}function ar(o){return!1}var ze=class Ce{constructor(){this.logger=lo("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&&!Ee(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&&!Ee(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&&!Ee(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&&!Ee(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&&!Ee(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&&!Ee(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=co(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()),Qe(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<Ce.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<Ce.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<Ce.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(),Qe(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 Qe(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<=Ce.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 ar(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 ar(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(Ce.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}};ze.MAX_MARKER_SCAN=3;ze.MAX_PROPERTY_DEPTH=10;ze.MAX_METHOD_ARGS=20;ze.ENGLISH_NOISE_WORDS=new Set(["the","a","an"]);var uo=ze,Ya=new uo;var Rt=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}},Lt=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 po(o){return"setContext"in o&&typeof o.setContext=="function"}function mo(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 X=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 j(o,e){return{start:o,end:e}}function D(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 pe(o){return/\s/.test(o)}function rt(o){return o==="#"||o==="."||o==="["||o==="@"||o==="*"||o==="<"}function nt(o){return o==='"'||o==="'"||o==="`"||o==="\u300C"||o==="\u300D"}function ie(o){return/\d/.test(o)}function ot(o){return/[a-zA-Z]/.test(o)}function W(o){return/[a-zA-Z0-9_-]/.test(o)}function sr(o,e){if(e>=o.length)return null;let t=o[e];if(!rt(t))return null;let r=e,n="";if(t==="#"||t==="."){for(n+=o[r++];r<o.length&&W(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&&W(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&&W(o[r]);)n+=o[r++];if(n.length<=1)return null}else if(t==="*"){for(n+=o[r++];r<o.length&&W(o[r]);)n+=o[r++];if(n.length<=1)return null}else if(t==="<"){if(n+=o[r++],r>=o.length||!ot(o[r]))return null;for(;r<o.length&&W(o[r]);)n+=o[r++];for(;r<o.length;){let i=o[r];if(i==="."){if(n+=o[r++],r>=o.length||!W(o[r]))return null;for(;r<o.length&&W(o[r]);)n+=o[r++]}else if(i==="#"){if(n+=o[r++],r>=o.length||!W(o[r]))return null;for(;r<o.length&&W(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&&pe(o[r]);)n+=o[r++];if(r<o.length&&o[r]==="/")for(n+=o[r++];r<o.length&&pe(o[r]);)n+=o[r++];if(r>=o.length||o[r]!==">")return null;n+=o[r++]}return n||null}function fo(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 pe(r)||r==="*"||!W(r)}function lr(o,e){if(e>=o.length)return null;let t=o[e];if(!nt(t)||t==="'"&&fo(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 cr(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 ur(o,e){if(!cr(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 dr(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 ho=["===","!==","->","==","!=","<=",">=","&&","||","**","+=","-=","*=","/=","+","-","*","/","=",">","<","!","&","|","%","^","~"];var es=new Set(ho),yo=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"]),go=["click","dblclick","input","change","submit","keydown","keyup","keypress","mousedown","mouseup","mouseover","mouseout","mouseenter","mouseleave","mousemove","pointerdown","pointerup","pointermove","focus","blur","load","resize","scroll"],pr=class mr{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){po(e)&&e.setContext(mo(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&&pe(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(D(a.value,this.classifyToken(a.value),j(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(D(s,a,j(r,r+1))),r++}}return new X(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(D(".","operator",j(t,t+1))),!0;let l=t+1;for(;l<e.length&&W(e[l]);)l++;return l<e.length&&e[l]==="("?(r.push(D(".","operator",j(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 go)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(" ")&&!yo.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 D(r.native,"keyword",j(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 D(i.native,"keyword",j(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 D(e,"keyword",j(t,r),s)}trySelector(e,t){let r=sr(e,t);return r?D(r,"selector",j(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{...D(n,"event-modifier",j(t,t+n.length)),metadata:{modifierName:i,value:s?i==="queue"?s:parseInt(s,10):void 0}}}tryString(e,t){let r=lr(e,t);return r?D(r,"literal",j(t,t+r.length)):null}tryNumber(e,t){let r=dr(e,t);return r?D(r,"literal",j(t,t+r.length)):null}tryMatchTimeUnit(e,t,r,n=!1){let i=t;if(n)for(;i<e.length&&pe(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(W(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,...mr.STANDARD_TIME_UNITS],u=this.tryMatchTimeUnit(e,c,d,s);return u&&(l+=u.suffix,c=u.endPos),D(l,"literal",j(t,c))}tryUrl(e,t){let r=ur(e,t);return r?D(r,"url",j(t,t+r.length)):null}tryVariableRef(e,t){if(e[t]!==":"||t+1>=e.length||!W(e[t+1]))return null;let r=t+1;for(;r<e.length&&W(e[r]);)r++;let n=e.slice(t,r);return D(n,"identifier",j(t,r))}tryOperator(e,t){let r=e.slice(t,t+2);if(["==","!=","<=",">=","&&","||","->"].includes(r))return D(r,"operator",j(t,t+2));let n=e[t];return["<",">","!","+","-","*","/","="].includes(n)?D(n,"operator",j(t,t+1)):["(",")","{","}",",",";",":"].includes(n)?D(n,"punctuation",j(t,t+1)):null}tryMultiCharParticle(e,t,r){for(let n of r)if(e.slice(t,t+n.length)===n)return D(n,"particle",j(t,t+n.length));return null}};pr.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 _e=pr;function At(o){return{stem:o,confidence:1}}function Be(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 B(o,e){let t={type:"literal",value:o};return e!==void 0?{type:"literal",value:o,dataType:e}:t}function ke(o){return et(o)}function J(o){return{type:"reference",value:o}}function ae(o,e){return{type:"property-path",object:o,property:e}}function H(o,e,t){let r={kind:"command",action:o,roles:new Map(Object.entries(e))};return t!==void 0?{...r,metadata:t}:r}function me(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 fr(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 hr(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 je(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 yr(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 De(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 vo={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)"}},ko={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"}},xo={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"}},So={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"}},bo={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>"}},wo={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>"}},To={action:"live",description:"Reactive block: re-run the body when its dependencies change",category:"control-flow",primaryRole:"patient",hasBody:!0,bareKeyword:!0,roles:[]},Eo={action:"eventsource",description:"Open a Server-Sent Events stream and handle its events",category:"async",primaryRole:"patient",hasBody:!0,bareKeyword:!0,roles:[]},Co={action:"socket",description:"Open a WebSocket and handle its messages",category:"async",primaryRole:"patient",hasBody:!0,bareKeyword:!0,roles:[]},No={action:"worker",description:"Define a Web Worker with inline methods",category:"async",primaryRole:"patient",hasBody:!0,bareKeyword:!0,roles:[]},Po={action:"intercept",description:"Service-worker fetch interception / caching strategies",category:"async",primaryRole:"patient",hasBody:!0,bareKeyword:!0,roles:[]},Ro={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}]},Lo={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}]},Ao={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}]},Mo={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}]},Oo={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}]},Vo={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}]},Io={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"}}]},zo={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"}}]},_o={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"}}]},Bo={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"}}]},jo={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}]},Do={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}]},$o={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}]},qo={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}]},Wo={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}]},Ko={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}]},Fo={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}]},Uo={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"}}]},Ho={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}]},Go={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}]},Yo={action:"else",description:"Else branch of conditional",category:"control-flow",primaryRole:"patient",hasBody:!0,roles:[]},Jo={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"'},Zo={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"}}]},Xo={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}]},Qo={action:"continue",description:"Continue to next loop iteration",category:"control-flow",primaryRole:"patient",roles:[]},ei={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"]}}]},ti={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}]},ri={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"}}]},ni={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}]},oi={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}]},ii={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}]},ai={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"}}]},si={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}]},li={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}]},ci={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}]},ui={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}]},di={action:"breakpoint",description:"Drop into the debugger",category:"control-flow",primaryRole:"patient",roles:[],bareKeyword:!0},pi={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}]},mi={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}]},fi={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}]},hi={action:"async",description:"Execute commands asynchronously",category:"async",primaryRole:"patient",hasBody:!0,roles:[]},yi={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"}}]},gi={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"}}]},vi={action:"init",description:"Initialization block that runs once",category:"control-flow",primaryRole:"patient",hasBody:!0,roles:[]},ki={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}]},xi={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}]},Si={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"}}]},bi={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"}}]},wi={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"}}]},Ti={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}]},Ei={action:"break",description:"Exit from the current loop",category:"control-flow",primaryRole:"patient",roles:[]},Ci={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}]},Ni={action:"exit",description:"Exit from the current event handler",category:"control-flow",primaryRole:"patient",roles:[],bareKeyword:!0},Pi={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}]},Ri={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"}}]},gr={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"},Li={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"},Ai={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:gr}]},Mi={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:gr}]},Oi={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:Li}]},Vi={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:vo,add:ko,remove:xo,put:So,set:bo,show:Ro,hide:Lo,on:Ao,trigger:Mo,wait:Oo,fetch:Vo,increment:Io,decrement:zo,append:_o,prepend:Bo,log:jo,get:Do,take:$o,make:qo,halt:Wo,settle:Ko,throw:Fo,send:Uo,if:Ho,unless:Go,else:Yo,repeat:Jo,for:Zo,while:Xo,continue:Qo,go:ei,scroll:Ri,push:Ai,replace:Mi,process:Oi,transition:ti,clone:ri,focus:ni,blur:oi,empty:ii,open:ai,close:si,select:li,clear:ci,reset:ui,breakpoint:di,call:pi,return:mi,js:fi,async:hi,tell:yi,default:gi,init:vi,behavior:ki,install:xi,measure:Si,swap:bi,morph:wi,beep:Ti,break:Ei,copy:Ci,exit:Ni,pick:Pi,render:Vi,bind:wo,live:To,eventsource:Eo,socket:Co,worker:No,intercept:Po,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 ce(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 vr=[{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 Mt(o,e,t,r){let n=vr.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 kr(o,e){let t=vr.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 xr=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"]),Ii={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"]},Ot=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:xr.has(r.value)||r.alternatives?.some(n=>xr.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=Ii[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))}},Sr=new Ot;var zi=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??Sr}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 B(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&&(ce(this.currentProfile,i.value)??ce(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&&!De(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&&!De(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&&!De(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&&!De(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(T=>T==="expression"||T==="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,B(`${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 T=e.peek(1);if(T&&(T.kind==="selector"||T.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(),ae(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=ce(this.currentProfile,l)??ce(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||kr(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 ae(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(ce(this.currentProfile,f)??ce(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=ce(this.currentProfile,u)??ce(this.currentProfile,u.toLowerCase()),d)break;return d?(e.advance(),ae(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&&zi.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("}"),B(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 ae(J(i),p.join("."));if(g){let S=e.mark(),T=[],C=0,x=!1;for(;!e.isAtEnd();){let k=e.peek();if(!k)break;if(k.value==="(")C++;else if(k.value===")"){if(T.push(k.value),e.advance(),C--,C===0&&(x=!0),x)break;continue}T.push(k.value),e.advance()}x?m+=T.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 ae(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(),ae(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 ae(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):B(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 B(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 B(n,"string")}if(e==="true")return B(!0,"boolean");if(e==="false")return B(!1,"boolean");let t=e.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/);if(t){let n=parseFloat(t[1]);return t[2]?B(e,"duration"):B(n,"number")}let r=parseFloat(e);return isNaN(r)?B(e,"string"):B(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 Vt=A,se=new Vt;var _i=["===","!==","->","==","!=","<=",">=","&&","||","**","+=","-=","*=","/=","+","-","*","/","=",">","<","!","&","|","%","^","~"],it=class{constructor(e=_i){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}},Bi="()[]{},:;",at=class{constructor(e=Bi){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 It(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 $e=class{constructor(){this.name="css-selector"}canExtract(e,t){let r=e[t];return r==="#"||r==="."||r==="["||r==="<"?!0:r==="@"||r==="*"?It(e,t)!==null:!1}extract(e,t){let r=It(e,t);return r?{value:r,length:r.length,metadata:{type:"css-selector"}}:null}};var qe=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 br(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 We=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=br(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"}}}};function ji(o){let e=o.charCodeAt(0);return e>=12352&&e<=12447}function Di(o){let e=o.charCodeAt(0);return e>=12448&&e<=12543}function $i(o){let e=o.charCodeAt(0);return e>=19968&&e<=40879||e>=13312&&e<=19903}function wr(o){return ji(o)||Di(o)||$i(o)}var st=class{constructor(){this.name="japanese-keyword"}setContext(e){this.context=e}canExtract(e,t){return wr(e[t])}extract(e,t){if(!this.context)throw new Error("JapaneseKeywordExtractor: context not set");let r=t;this.context.isKeywordStart(e,t);let n="",i=t;for(;i<e.length&&wr(e[i]);)n+=e[i],i++;let s=n,a=n.length;for(let u=n.length;u>0;u--){let f=n.substring(0,u);if(this.context.lookupKeyword(f)){s=f,a=u;break}}if(n=s,i=t+a,!n)return null;let l=this.context.lookupKeyword(n),c=l&&l.normalized!==l.native?l.normalized:void 0,d;if(!l&&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&&(d=f.normalized)}}return{value:n,length:i-r,metadata:{normalized:c||d}}}};var Tr=new Map([["\u3092",{role:"patient",confidence:.95}],["\u306B",{role:"destination",confidence:.85}],["\u304C",{role:"subject",confidence:.9}],["\u306E",{role:"possessive",confidence:.9}],["\u3068",{role:"conjunction",confidence:.8}],["\u3067",{role:"instrument",confidence:.85}],["\u3078",{role:"direction",confidence:.85}],["\u3084",{role:"listing",confidence:.8}],["\u304B",{role:"question",confidence:.85}],["\u3082",{role:"also",confidence:.85}],["\u306F",{role:"topic",confidence:.9}]]),Er=new Map([["\u304B\u3089",{role:"source",confidence:.95}],["\u307E\u3067",{role:"until",confidence:.95}],["\u3088\u308A",{role:"comparison",confidence:.9}],["\u3068\u3057\u3066",{role:"as",confidence:.9}],["\u306B\u3064\u3044\u3066",{role:"about",confidence:.9}],["\u306B\u3088\u3063\u3066",{role:"by-means",confidence:.9}],["\u306B\u3066",{role:"at-location",confidence:.85}]]),lt=class{constructor(){this.name="japanese-particle"}setContext(e){this._context=e}longerKeywordStartsHere(e,t){if(!this._context)return!1;for(let r=4;r>=2;r--){let n=e.slice(t,t+r);if(n.length===r&&this._context.isKeyword(n))return!0}return!1}canExtract(e,t){let r=e[t];if(Tr.has(r)&&!this.longerKeywordStartsHere(e,t))return!0;for(let[n]of Er)if(e.startsWith(n,t))return!0;return!1}extract(e,t){for(let[i,s]of Er)if(e.startsWith(i,t))return{value:i,length:i.length,metadata:{role:s.role,confidence:s.confidence,variant:i}};let r=e[t];if(this.longerKeywordStartsHere(e,t))return null;let n=Tr.get(r);return n?{value:r,length:1,metadata:{role:n.role,confidence:n.confidence,variant:r}}:null}};function qi(o){let e=o.charCodeAt(0);return e>=65&&e<=90||e>=97&&e<=122||e===95||e===36}function Wi(o){let e=o.charCodeAt(0);return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===95||e===36}var ct=class{constructor(){this.name="ascii-identifier"}setContext(e){this.context=e}canExtract(e,t){return qi(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&&Wi(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 Cr(){return[new We,new qe,new Ke,new $e]}var Ki=[{pattern:"\u3057\u305F\u3089",confidence:.88,conjugationType:"conditional-tara",minStemLength:2},{pattern:"\u3059\u308B\u3068",confidence:.88,conjugationType:"conditional-to",minStemLength:2},{pattern:"\u3059\u308C\u3070",confidence:.85,conjugationType:"conditional-ba",minStemLength:2},{pattern:"\u305F\u3089",confidence:.85,conjugationType:"conditional-tara",minStemLength:2},{pattern:"\u308C\u3070",confidence:.82,conjugationType:"conditional-ba",minStemLength:2},{pattern:"\u3066\u3044\u307E\u3057\u305F",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"\u3066\u3044\u307E\u3059",confidence:.85,conjugationType:"progressive",minStemLength:2},{pattern:"\u3066\u304F\u3060\u3055\u3044",confidence:.85,conjugationType:"request",minStemLength:2},{pattern:"\u3067\u304F\u3060\u3055\u3044",confidence:.85,conjugationType:"request",minStemLength:2},{pattern:"\u3066\u3044\u308B",confidence:.85,conjugationType:"progressive",minStemLength:2},{pattern:"\u3066\u304A\u304F",confidence:.82,conjugationType:"progressive",minStemLength:2},{pattern:"\u3066\u307F\u308B",confidence:.82,conjugationType:"progressive",minStemLength:2},{pattern:"\u3066\u3042\u308B",confidence:.82,conjugationType:"progressive",minStemLength:2},{pattern:"\u3066\u304F\u308C",confidence:.8,conjugationType:"casual-request",minStemLength:2},{pattern:"\u3067\u304F\u308C",confidence:.8,conjugationType:"casual-request",minStemLength:2},{pattern:"\u3061\u3083\u3063\u305F",confidence:.82,conjugationType:"contracted-past",minStemLength:2},{pattern:"\u3058\u3083\u3063\u305F",confidence:.82,conjugationType:"contracted-past",minStemLength:2},{pattern:"\u3061\u3083\u3046",confidence:.82,conjugationType:"contracted",minStemLength:2},{pattern:"\u3058\u3083\u3046",confidence:.82,conjugationType:"contracted",minStemLength:2},{pattern:"\u307E\u3057\u305F",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"\u307E\u305B\u3093",confidence:.85,conjugationType:"negative",minStemLength:2},{pattern:"\u307E\u3059",confidence:.85,conjugationType:"polite",minStemLength:2},{pattern:"\u3066",confidence:.85,conjugationType:"te-form",minStemLength:2},{pattern:"\u305F",confidence:.85,conjugationType:"past",minStemLength:2},{pattern:"\u306A\u3044",confidence:.82,conjugationType:"negative",minStemLength:2},{pattern:"\u306A\u304B\u3063\u305F",confidence:.82,conjugationType:"past",minStemLength:2},{pattern:"\u3089\u308C\u308B",confidence:.8,conjugationType:"potential",minStemLength:2},{pattern:"\u308C\u308B",confidence:.78,conjugationType:"potential",minStemLength:2},{pattern:"\u3089\u308C\u305F",confidence:.8,conjugationType:"passive",minStemLength:2},{pattern:"\u3055\u305B\u308B",confidence:.8,conjugationType:"causative",minStemLength:2},{pattern:"\u305B\u308B",confidence:.78,conjugationType:"causative",minStemLength:2},{pattern:"\u3088\u3046",confidence:.8,conjugationType:"volitional",minStemLength:2},{pattern:"\u308B",confidence:.75,conjugationType:"dictionary",minStemLength:3}],Fi=[{pattern:"\u3057\u305F\u3089",confidence:.88,conjugationType:"conditional-tara"},{pattern:"\u3059\u308B\u3068",confidence:.88,conjugationType:"conditional-to"},{pattern:"\u3059\u308C\u3070",confidence:.85,conjugationType:"conditional-ba"},{pattern:"\u3057\u3066\u3044\u307E\u3059",confidence:.85,conjugationType:"progressive"},{pattern:"\u3057\u3066\u3044\u308B",confidence:.85,conjugationType:"progressive"},{pattern:"\u3057\u307E\u3057\u305F",confidence:.85,conjugationType:"past"},{pattern:"\u3057\u307E\u3059",confidence:.85,conjugationType:"polite"},{pattern:"\u3057\u306A\u3044",confidence:.82,conjugationType:"negative"},{pattern:"\u3057\u3066",confidence:.85,conjugationType:"te-form"},{pattern:"\u3057\u305F",confidence:.85,conjugationType:"past"},{pattern:"\u3059\u308B",confidence:.88,conjugationType:"dictionary"}];function Nr(o){let e=o.charCodeAt(0);return e>=12352&&e<=12447}function Ui(o){let e=o.charCodeAt(0);return e>=12448&&e<=12543}function Hi(o){let e=o.charCodeAt(0);return e>=19968&&e<=40959||e>=13312&&e<=19903}function Gi(o){for(let e of o)if(Nr(e)||Ui(e)||Hi(e))return!0;return!1}var Fe=class{constructor(){this.language="ja"}isNormalizable(e){if(!Gi(e)||e.length<2)return!1;let t=e[e.length-1];return Nr(t)}normalize(e){let t=this.normalizeCompound(e);if(t)return t;let r=this.trySuruNormalization(e);if(r)return r;for(let n of Ki)if(e.endsWith(n.pattern)){let i=e.slice(0,-n.pattern.length),s=n.minStemLength??2;if(i.length<s)continue;let a={removedSuffixes:[n.pattern]};return n.conjugationType&&(a.conjugationType=n.conjugationType),Be(i,n.confidence,a)}return At(e)}trySuruNormalization(e){for(let t of Fi)if(e.endsWith(t.pattern)){let r=e.slice(0,-t.pattern.length);if(r.length<1)continue;return Be(r,t.confidence,{removedSuffixes:[t.pattern],conjugationType:t.conjugationType,originalForm:"suru-verb"})}return null}normalizeCompound(e){let t=[{pattern:"\u3066\u3044\u306A\u304B\u3063\u305F",suffixes:["\u3066","\u3044","\u306A\u304B\u3063\u305F"],confidence:.8,minStemLength:2},{pattern:"\u3067\u3044\u306A\u304B\u3063\u305F",suffixes:["\u3067","\u3044","\u306A\u304B\u3063\u305F"],confidence:.8,minStemLength:2},{pattern:"\u3066\u3044\u306A\u3044",suffixes:["\u3066","\u3044","\u306A\u3044"],confidence:.82,minStemLength:2},{pattern:"\u3067\u3044\u306A\u3044",suffixes:["\u3067","\u3044","\u306A\u3044"],confidence:.82,minStemLength:2},{pattern:"\u3066\u3044\u305F",suffixes:["\u3066","\u3044","\u305F"],confidence:.85,minStemLength:2},{pattern:"\u3067\u3044\u305F",suffixes:["\u3067","\u3044","\u305F"],confidence:.85,minStemLength:2}];for(let{pattern:r,suffixes:n,confidence:i,minStemLength:s}of t)if(e.endsWith(r)){let a=e.slice(0,-r.length);if(a.length<s)continue;return Be(a,i,{removedSuffixes:n,conjugationType:"compound"})}return null}},Ys=new Fe;var Yi=new Set(["\u3092","\u306B","\u3067","\u304B\u3089","\u307E\u3067","\u3078","\u3068","\u306E","\u304C","\u306F","\u3082","\u3088\u308A"]),Ji=[{native:"\u771F",normalized:"true"},{native:"\u507D",normalized:"false"},{native:"\u30CC\u30EB",normalized:"null"},{native:"\u672A\u5B9A\u7FA9",normalized:"undefined"},{native:"\u6700\u521D",normalized:"first"},{native:"\u6700\u5F8C",normalized:"last"},{native:"\u6B21",normalized:"next"},{native:"\u524D",normalized:"previous"},{native:"\u6700\u3082\u8FD1\u3044",normalized:"closest"},{native:"\u89AA",normalized:"parent"},{native:"\u30AF\u30EA\u30C3\u30AF",normalized:"click"},{native:"\u5909\u66F4",normalized:"change"},{native:"\u9001\u4FE1",normalized:"submit"},{native:"\u5165\u529B",normalized:"input"},{native:"\u30ED\u30FC\u30C9",normalized:"load"},{native:"\u8AAD\u307F\u8FBC\u307F",normalized:"load"},{native:"\u30B9\u30AF\u30ED\u30FC\u30EB",normalized:"scroll"},{native:"\u30AD\u30FC\u30C0\u30A6\u30F3",normalized:"keydown"},{native:"\u30AD\u30FC\u30A2\u30C3\u30D7",normalized:"keyup"},{native:"\u30DE\u30A6\u30B9\u30AA\u30FC\u30D0\u30FC",normalized:"mouseover"},{native:"\u30DE\u30A6\u30B9\u30A2\u30A6\u30C8",normalized:"mouseout"},{native:"\u30DE\u30A6\u30B9\u62BC\u4E0B",normalized:"mousedown"},{native:"\u30DE\u30A6\u30B9\u89E3\u653E",normalized:"mouseup"},{native:"\u307E\u305F\u306F",normalized:"or"},{native:"\u79C1",normalized:"me"},{native:"\u3057\u305F\u3089",normalized:"on"},{native:"\u3059\u308B\u3068",normalized:"on"},{native:"\u6642\u306B",normalized:"on"},{native:"\u79D2",normalized:"s"},{native:"\u30DF\u30EA\u79D2",normalized:"ms"},{native:"\u5206",normalized:"m"},{native:"\u6642\u9593",normalized:"h"}],zt=class extends _e{constructor(){super();this.language="ja";this.direction="ltr";this.initializeKeywordsFromProfile(ve,Ji),this.normalizer=new Fe,this.registerExtractors(Cr()),this.registerExtractor(new Rt),this.registerExtractor(new Lt),this.registerExtractor(new ct),this.registerExtractor(new lt),this.registerExtractor(new st),this.registerExtractor(new it),this.registerExtractor(new at)}classifyToken(t){return Yi.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("'")||t.startsWith("\u300C")||/^\d/.test(t)?"literal":"identifier"}},ut=new zt;function G(o,e){return er(o,e)}function dt(){return wt()}var mt=["if","unless","repeat","for","while"];function le(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 Xi=new Set(mt);function Bt(o,e){let t=o.normalized?.toLowerCase();return t?Xi.has(t):e.some(r=>te(o,r))}var Pr=new Set(["me","it","you","the","body","window","document","its","event","result","target","self","this","them","parent","next","previous","closest","first","last"]),Qi=new Set(["destination","source","style","patient","on","from","to"]);function ea(o){if(!o||o.kind==="selector")return!1;let e=(o.normalized??o.value).toLowerCase(),t=o.value.toLowerCase();return!(Pr.has(e)||Pr.has(t)||Qi.has(e))}var Rr=new Set(["ja","ko"]);function _t(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 Ar(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 Mr(o,e,t){let r=e+1;if(r>=o.length)return-1;let n=_t(I(t)?.roleMarkers?.patient);return n.size>0&&te(o[r],n)&&r++,r<o.length?r:-1}function Or(o,e,t){if(!I(e))return null;let r=le(e,"behavior"),n=le(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=G(o,e).tokens;if(l.length<2)return null;if(te(l[0],r))return Lr(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)?Lr(o,e,l,t,c):te(l[0],n)?ta(o,e,l,t):null}function Vr(o,e,t){let r=I(e);if(!r)return null;let n=r.wordOrder!=="SOV",i=Rr.has(e)?_t(r.roleMarkers?.event):new Set,s=Rr.has(e)?_t(r.keywords?.on):new Set,a=i.size>0&&s.size>0,l=le(e,"end"),c=le(e,"on"),d=o.toLowerCase(),u=[...l].some(k=>d.includes(k)),f=(n||a)&&(()=>{let k=0;for(let E of c)if(E){for(let v=d.indexOf(E);v>=0;v=d.indexOf(E,v+E.length))if(++k>=2)return!0}return!1})();if(!u&&!f)return null;let m=G(o,e).tokens;if(m.length<2)return null;let p=mt.map(k=>le(e,k)),h=k=>Bt(k,p),y=k=>te(k,l),g=[],S=0,T=0;for(let k=0;k<m.length;k++){let E=m[k];if(y(E)){if(S>0){S--;continue}let v=o.slice(m[T].position.start,E.position.start).trim();v&&g.push(v),T=k+1}else if(h(E))S++;else if(n&&S===0&&k>T&&te(E,c)&&ea(m[k+1])){let v=o.slice(m[T].position.start,E.position.start).trim();v&&g.push(v),T=k}else if(a&&S===0&&k-1>T&&te(E,i)&&m[k+1]!==void 0&&te(m[k+1],s)){let v=m[k-1],b=o.slice(m[T].position.start,v.position.start).trim();b&&g.push(b),T=k-1}}if(T<m.length){let k=o.slice(m[T].position.start).trim();k&&g.push(k)}if(g.length<2)return null;let C=[],x=[];for(let k of g){let E;try{E=t.statement(k,e)}catch{return null}if(!E||E.kind!=="event-handler")return null;let v=E;C.push(v);let b=!v.body||v.body.length===0;x.push(b?.2:v.metadata?.confidence??.75)}return je(C,"then",{sourceLanguage:e,confidence:pt(x),sourceText:o})}function pt(o){return o.length>0?o.reduce((e,t)=>e+t,0)/o.length:0}function Ir(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 Lr(o,e,t,r,n){let i=n>0,s=i?0:Mr(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}=Ar(o,a),u=i?n+1:t.findIndex(v=>v.position.start>=d);u<=s&&(u=s+1);let f=le(e,"init"),m=le(e,"end"),p=mt.map(v=>le(e,v)),h=v=>Bt(v,p),y=v=>te(v,m),g=[],S=[],T=[],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 P=o.slice(t[k].position.end,b.position.start).trim();if(P)try{let N=Ir(r.body(P,e));S.push(...N),T.push(pt(N.map(V=>V.metadata?.confidence??.75)))}catch{T.push(0)}}else{let P=o.slice(t[k].position.start,b.position.start).trim();try{let N=r.statement(P,e);if(N&&N.kind==="event-handler"){let V=N;g.push(V);let M=!V.body||V.body.length===0;T.push(M?.2:V.metadata?.confidence??.75)}else T.push(0)}catch{T.push(0)}}k=v+1}else h(b)&&x++}if(g.length===0&&S.length===0)return null;let E=(C?1:.8)*pt(T);return fr(l,c,g,S.length>0?S:void 0,{sourceLanguage:e,confidence:E,sourceText:o})}function ta(o,e,t,r){let n=Mr(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}=Ar(o,i),c=t.findIndex(x=>x.position.start>=l);c<=n&&(c=n+1);let d=le(e,"end"),u=mt.map(x=>le(e,x)),f=x=>Bt(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 T;try{T=Ir(r.body(S,e))}catch{return null}if(T.length===0)return null;let C=pt(T.map(x=>x.metadata?.confidence??.75));return h<0&&(C*=.8),hr(s,a,T,{sourceLanguage:e,confidence:C,sourceText:o})}var xe={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 ra=Object.fromEntries(Object.entries(xe).map(([o,e])=>{let t={};for(let[r,n]of Object.entries(e))n in t||(t[n]=r);return[o,t]})),na={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 zr(o,e){return na[e]?.has(o)?o:ra[e]?.[o]??o}var ft=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=Et(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
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=I(t);return r?.keywords?r.keywords[e]?.primary??e:e}renderExplicit(e){return ee(e)}supportedLanguages(){return dt()}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:zr(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}`}},jt=new ft;function Ue(o,e){return jt.render(o,e)}function He(o){return jt.renderExplicit(o)}var oa={getSchema:ne};function Pe(o){return tt(o,{schemaLookup:oa})}var Re=new Set(["if","unless","while","repeat","for"]),ia=new Set(["then","end","else","if","unless","while","for","repeat","and"]),aa=new Set(["first","last","next","previous","random","closest"]),Le=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"]),Ge=class extends Error{constructor(e,t,r,n){super(e),this.name="SemanticParseError",this.language=t,this.input=r,this.diagnostics=n}};function D(o,e,t){return{message:o,severity:e,source:"semantic-parser",...t&&{code:t}}}function Z(o,e){return e.length===0?o:{...o,diagnostics:e}}function _r(o){if(o.length>=2){let e=o[0];if((e==='"'||e==="'")&&o.endsWith(e))return o.slice(1,-1)}return o}var sa=["body","statements","thenBranch","elseBranch","eventHandlers","initBlock"];function Br(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"&&Le.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 sa){let n=t[r];if(Array.isArray(n))for(let i of n)Br(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 Br(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=Or(e,t,{statement:(v,b)=>this.parse(v,b),body:(v,b)=>this.parseStatements(v,b)});if(r)return r;let n=Vr(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=G(u,t),p=Q(t);if(p.length===0)throw new Ge(`No patterns available for language: ${t}`,t,u,[D(`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(P=>P.normalized==="on");if(b>=2&&b+1<v.length){let P=u.slice(v[0].position.start,v[b].position.start).trim(),N=v[b+1].position.end,V=u.slice(v[b].position.start,N)+" "+P+u.slice(N);if(V!==u)try{let M=this.parse(V,t);if(M&&M.kind==="event-handler"){let O=i?this.applyModifiers(M,i):M;return Z(O,f)}}catch{}}}}{let v=m.tokens;for(let b=1;b<v.length-1;b++){let P=v[b],N=P.value,V=(P.normalized??P.value).toLowerCase();if(!(V==="or"||L.OR_KEYWORDS.has(N)||L.OR_KEYWORDS.has(V)))continue;let O=v[b+1],_=(O.normalized??O.value).toLowerCase();if(!L.KNOWN_EVENTS.has(_))break;let z=b+1,K=v[b+2];K&&K.kind==="selector"&&K.value.startsWith("[")&&(z=b+2);let U=v[b].position.start,fe=v[z].position.end,oe=(u.slice(0,U).trimEnd()+" "+u.slice(fe).trimStart()).trim();if(oe&&oe!==u)try{let he=this.parse(oe,t);if(he&&he.kind==="event-handler"){he.additionalEvents=[{type:"literal",value:_}];let yt=i?this.applyModifiers(he,i):he;return Z(yt,f)}}catch{}break}}let y=h.filter(v=>v.command==="on"),g=m.mark(),S=se.matchBest(m,y);if(S){f.push(D(`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"),P=(b?.raw??b?.value??"").toString().toLowerCase(),N=xe[t],V=L.KNOWN_EVENTS.has(P)||!!N&&Object.keys(N).some(M=>M.toLowerCase()===P);if(P&&!V){let M=this.trySOVEventExtraction(u,t,h);if(M){f.push(D(`bare-event mis-anchor on "${P}" rejected; SOV extraction preferred`,"info","stage-bare-event-guard"));let O=i?this.applyModifiers(M,i):M;return Z(O,f)}if(b?.type==="reference"||b?.type==="expression"){m.reset(g);let O=h.filter(z=>z.command!=="on"),_=se.matchBest(m,O);m.reset(g),_&&_.pattern.command!=="on"?(v=!0,f.push(D(`bare-event mis-anchor on reference "${P}" rejected; command ${_.pattern.command} preferred`,"info","stage-bare-event-guard"))):se.matchBest(m,y)}}}if(!v){let b=this.buildEventHandler(S,m,t),P=i?this.applyModifiers(b,i):b;return Z(P,f)}}f.push(D(`event patterns: ${y.length} tried, no match`,"info","stage-event"));let T=this.tryTrailingEventExtraction(u,t,h);if(T){f.push(D("trailing event extraction succeeded","info","stage-trailing-event"));let v=i?this.applyModifiers(T,i):T;return Z(v,f)}let C=h.filter(v=>v.command!=="on"),x=se.matchBest(m,C);if(x){if(Re.has(x.pattern.command)){let v=this.trySOVEventExtraction(u,t,h);if(v){f.push(D(`SOV event extraction preferred over bare ${x.pattern.command} command`,"info","stage-sov-loop"));let P=i?this.applyModifiers(v,i):v;return Z(P,f)}let b=this.tryMidStreamEventExtraction(u,t,h);if(b){f.push(D(`mid-stream event extraction preferred over bare ${x.pattern.command} command`,"info","stage-midstream-loop"));let P=i?this.applyModifiers(b,i):b;return Z(P,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(D(`SOV event extraction preferred over command-homonym event ${x.pattern.command}`,"info","stage-sov-homonym"));let b=i?this.applyModifiers(v,i):v;return Z(b,f)}}else if(I(t)?.wordOrder==="VSO"){let v=this.tryMidStreamEventExtraction(u,t,h);if(v){f.push(D(`mid-stream event extraction preferred over bare ${x.pattern.command} command`,"info","stage-midstream-cmd"));let b=i?this.applyModifiers(v,i):v;return Z(b,f)}}if(x.consumedTokens<m.tokens.length&&I(t)?.wordOrder==="SOV"){let v=this.trySOVEventExtraction(u,t,h);if(v){f.push(D(`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 Z(b,f)}}return f.push(D(`command pattern matched: ${x.pattern.id} (confidence: ${x.confidence.toFixed(2)})`,"info","pattern-match")),Z(this.buildCommand(x,t),f)}if(f.push(D(`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(D("mid-stream event extraction succeeded with no leading command match","info","stage-midstream-nocmd"));let b=i?this.applyModifiers(v,i):v;return Z(b,f)}}let k=this.trySOVEventExtraction(u,t,h);if(k){f.push(D("SOV event extraction succeeded","info","stage-sov"));let v=i?this.applyModifiers(k,i):k;return Z(v,f)}f.push(D("SOV event extraction: no event keyword found","info","stage-sov"));let E=this.tryCompoundCommandParsing(m,C,t);if(E)return f.push(D("compound command parsing succeeded","info","stage-compound")),Z(E,f);throw f.push(D("compound parsing: no then-keywords or no command matches","info","stage-compound")),f.push(D(`all parse stages exhausted for "${u}"`,"error","parse-failed")),new Ge(`Could not parse input in ${t}: ${u}`,t,u,f)}parseStatements(e,t){let r=G(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 dt()}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=H(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=se.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 X(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 me(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=E=>(E.normalized??E.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 E=t.peek();if(E)for(u.event={type:"literal",value:x(E)},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=H(d,u,{sourceLanguage:r,patternId:e.pattern.id,confidence:e.confidence});if(this.registerBoundIdentifiers(f),!Re.has(d)||d==="repeat"){let C=e.pattern.id.includes("verb-first"),x=t.tokens,k=t.position(),E=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 P=x[b];if(E(P))break;if((P.normalized??P.value).toLowerCase()===d){v=b;break}}if(v>=0){let b=k;for(;b<x.length&&!E(x[b]);)b++;let P=x.slice(v,b),N=P;if(C){let V=String(n.value??"").toLowerCase(),M=P.findIndex(O=>(O.normalized??O.value).toLowerCase()===V);if(M<0)N=null;else{let O=P[M-1],_=O&&O.kind==="keyword"&&O.normalized?.toLowerCase()==="on"?M-1:M;N=[...P.slice(0,_),...P.slice(M+1)]}}if(N&&N.length>1){let V=Q(r).filter(q=>q.command!=="on").sort((q,ue)=>ue.priority-q.priority),M=this.parseClause(N,V,r),O=M[0],_=q=>q!==null&&typeof q=="object"&&typeof q.type=="string"?q.type:typeof q,z=ne(d),K=z?.primaryRole,U=q=>q==="patient"&&K&&K!=="patient"&&!z?.roles.some(ue=>ue.role==="patient")?K:q,fe=(q,ue)=>{if(!Re.has(d)||!z)return!1;let Se=z.roles.find(Dr=>Dr.role===U(q));return Se?Se.expectedTypes.length>0&&!Se.expectedTypes.includes(_(ue)):!0},oe=!!O&&O.kind==="command"&&Object.entries(u).every(([q,ue])=>{if(fe(q,ue))return!0;let Se=O.roles.get(U(q));return Se!==void 0&&_(Se)===_(ue)}),he=O?.metadata?.patternId??"",yt=!Re.has(d)||/^repeat-.*-(times|for-in|while-head|until-head)$/.test(he);if(M.length===1&&O&&O.kind==="command"&&O.action===d&&oe&&yt&&O.roles.size>Object.keys(u).length)for(f=O;t.position()<b;)t.advance()}}}if(!Re.has(d)){let C=f;if(ne(d)?.roles.some(N=>N.role==="quantity"&&!N.required)&&!C.roles.has("quantity")){let N=t.peek();N&&/^-?\d+(\.\d+)?$/.test(N.value)&&(f=H(d,{...Object.fromEntries(C.roles),quantity:{type:"literal",value:parseFloat(N.value),dataType:"number"}},C.metadata),t.advance())}let k=f;if(ne(d)?.roles.some(N=>N.role==="duration"&&!N.required)&&!k.roles.has("duration")){let N=t.peek();N&&/^\d+(\.\d+)?(ms|s)$/i.test(N.value)&&(f=H(d,{...Object.fromEntries(k.roles),duration:{type:"literal",value:N.value,dataType:"string"}},k.metadata),t.advance(),this.consumeForPostposition(t,r))}let v=f,b=ne(d);if(b?.roles.find(N=>N.role==="responseType"&&!N.required)&&!v.roles.has("responseType")){let N=z=>typeof z=="string"&&L.RESPONSE_TYPE_WORDS.has(z.toLowerCase()),V=(z,K)=>{let U=Object.fromEntries(v.roles);K&&delete U.destination,U.responseType={type:"expression",raw:z},f=H(d,U,v.metadata)},M=v.roles.get("destination"),O=b?.roles.find(z=>z.role==="destination"),_=M?.raw??M?.value;if(M&&O&&!O.expectedTypes.includes(M.type)&&N(_))V(_,!0);else{let z=t.peek();z&&N(z.value)&&(V(z.value,!1),t.advance())}}if(d==="wait"){let N=f;if(!N.roles.has("event")){let V=t.peek();if(V&&Le.has(V.value.toLowerCase())){let M=Object.fromEntries(N.roles),O=M.duration;O&&O.type!=="literal"&&O.type!=="expression"&&delete M.duration;let _=M.patient;_&&_.type==="reference"&&_.value==="me"&&delete M.patient,M.event={type:"literal",value:V.value,dataType:"string"},f=H(d,M,N.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=Re.has(d)&&!!h&&!this.isEndKeyword(h.value,r),T=!!h&&!this.isEndKeyword(h.value,r);if(p||y||S||T){let C=Q(r).filter(E=>E.command!=="on").sort((E,v)=>v.priority-E.priority),x=Q(r).filter(E=>E.id.startsWith("grammar-")&&E.id.includes("-continuation")).sort((E,v)=>v.priority-E.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 me(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"||Mt(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?[je(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 T=i[S],C=g.get(T.value.toLowerCase())??(T.normalized?g.get(T.normalized.toLowerCase()):void 0);if(C&&!L.CONDITION_OPERATORS.has(C)){a=i.slice(0,S),i=i.slice(S);break}}}let l=new X(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 T of this.parseSOVClauseByVerbAnchoring(y,r)){let C=T.action,x=T.roles;C&&ne(C)&&x instanceof Map&&x.size>0&&c.push(T)}};for(;!l.isAtEnd();){let y=l.peek(),g=!!y&&y.normalized?.toLowerCase()==="repeat",S=l.mark(),T=se.matchBest(l,t);if(g&&T&&T.pattern.command!=="repeat"){l.reset(S),m(),c.push(H("repeat",{},{sourceLanguage:r,confidence:.6})),d++,l.advance();continue}if(T&&T.pattern.command==="if"){let C=l.mark(),x=u.length;for(l.reset(S);!l.isAtEnd();){let E=l.peek();if(!E||this.isIfKeyword((E.normalized??E.value).toLowerCase(),r))break;u.push(E),l.advance()}let k=this.tryParseConditionalBlock(l,t,r);if(k){m(),c.push(k),d++;continue}u.length=x,l.reset(C)}if(T){m();let C=this.buildCommand(T,r);c.push(C),d++,this.tryAttachTrailingRole(l,C,r)}else{let C=l.peek();C&&C.normalized?.toLowerCase()==="repeat"?(m(),c.push(H("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?[H(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 ia.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(aa.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(H(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("'")?B(_r(r),"string"):n.kind==="reference"?J(r):B(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 B(_r(t),"string");if(/^-?\d+(\.\d+)?$/.test(t))return B(parseFloat(t));if(t==="true"||t==="\u771F"||t==="\uCC38"||t==="do\u011Fru")return B(!0);if(t==="false"||t==="\u507D"||t==="\uAC70\uC9D3"||t==="yanl\u0131\u015F")return B(!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"):B(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(!Mt(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=se.matchBest(e,r);if(m){let p=m.pattern.command,h={};for(let[S,T]of m.captured)S!=="event"&&S!=="action"&&S!=="continues"&&(h[S]=T);let y=H(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=se.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 X(n,r),l=this.parseBodyWithClauses(a,t,r);return l.length===0?null:l.length===1?l[0]:je(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}=G(e,t),i=xe[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)||Le.has(d))||L.KNOWN_EVENTS.has(c)||Le.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=G(e,t).tokens;if(n.length<3)return null;let i=xe[t],s=new Set;if(i)for(let T of Object.keys(i))s.add(T.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(T=>T.command!=="on"),g=new X(h,t),S=this.parseBodyWithClauses(g,y,t);return S.length===0?null:me({type:"literal",value:p},S,void 0,{sourceLanguage:t,confidence:.75})}tryMidStreamEventExtraction(e,t,r){let n=G(e,t).tokens;if(n.length<3)return null;let i=xe[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((T,C)=>C!==a&&C!==a+1);if(h.length===0)return null;let y=r.filter(T=>T.command!=="on"),g=new X(h,t),S=this.parseBodyWithClauses(g,y,t);return S.length===0?null:me({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=G(e,t).tokens,a=xe[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],E=k.value.toLowerCase(),v=E,b="",P=E.indexOf("[");P>0&&(v=E.slice(0,P),b=k.value.slice(P));let N=k.normalized?.toLowerCase(),V=N&&(L.KNOWN_EVENTS.has(N)||Le.has(N)),M=l.has(E)||l.has(v),O=L.KNOWN_EVENTS.has(v)||Le.has(v);if(V||M||O){let _=s[x-1];if(_&&(_.normalized??_.value).toLowerCase()==="event")continue;let z;V?z=N:M?z=a?.[E]??a?.[v]??v:z=v;let K=this.matchEventParamPhrase(s,x+1);if(n.size>0){let U=1+K.len,fe=s[x+U];fe&&fe.kind==="selector"&&fe.value.startsWith("[")&&(U+=1);let oe=s[x+U];if(oe&&(oe.kind==="particle"||oe.kind==="keyword")&&n.has(oe.value)){d=x,u=z,f=b||(U===K.len+2?s[x+U-1].value:""),m=U+1,p=K.names;break}}else{d=x,u=z,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 E=s[k];if(E.kind==="identifier")if(n.size>0){let v=1,b=s[k+1];b&&b.kind==="selector"&&b.value.startsWith("[")&&(v=2);let P=s[k+v];if(P&&(P.kind==="particle"||P.kind==="keyword")&&n.has(P.value)){d=k,u=E.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=E.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=E.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 E=s[x+1];E&&(E.kind==="particle"||E.kind==="keyword")&&c.markers.has(E.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 E=s[k],v=E.value.toLowerCase(),b=E.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 X(y,t),T=this.parseBodyWithClauses(S,g,t);if(T.length===0)return null;let C={sourceLanguage:t,confidence:.75};return f&&(C.keyFilter=f),me({type:"literal",value:u},T,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 H("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 E=(k.normalized??k.value).toLowerCase();if(this.isIfKeyword(E,r)||this.isUnlessKeyword(E,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],E=(k.normalized??k.value).toLowerCase();if(this.isIfKeyword(E,r)||this.isUnlessKeyword(E,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(),P=(k.normalized??k.value).toLowerCase(),N=L.CONDITION_COPULAS.has(v)||L.CONDITION_COPULAS_SURFACE.has(b)&&L.CONDITION_PREDICATES.has(P),V=d!==null&&d.has(k.value.toLowerCase())&&!L.CONDITION_PREDICATES.has(P);if(!L.CONDITION_OPERATORS.has(P)&&(!N||V)&&(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],E=(k.normalized??k.value).toLowerCase();if(this.isIfKeyword(E,r)||this.isUnlessKeyword(E,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 T={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):yr(T,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 X(e,r);return se.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 X(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=G(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=G(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=G(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 ht=L,$t=new ht;function Ae(o,e){return $t.parse(o,e)}function Dt(o,e){return $t.canParse(o,e)}function qt(o,e){if(de(o))return o;let t=Ae(o,e);return He(t)}function Wt(o,e){let t=Pe(o);return Ue(t,e)}function Kt(o,e){return de(o)?Pe(o):Ae(o,e)}bt("ja",ut,ve);var la="1.0.0-ja",ca=["ja"];function ua(){return[...ca]}function jr(o){if(o!=="ja")throw new Error(`Language not supported in this bundle: ${o}. Supported: ja`)}function da(o,e){return jr(e),[...G(o,e).tokens]}function $r(o){return jr(o),Q(o)}function pa(o,e){return $r(o).filter(t=>t.command===e).sort((t,r)=>r.priority-t.priority)}return Hr(ma);})();
5
+ `)}getChainWord(e,t){let r=I(t);return r?.keywords?r.keywords[e]?.primary??e:e}renderExplicit(e){return ee(e)}supportedLanguages(){return dt()}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:zr(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}`}},jt=new ft;function Ue(o,e){return jt.render(o,e)}function He(o){return jt.renderExplicit(o)}var oa={getSchema:ne};function Pe(o){return tt(o,{schemaLookup:oa})}var Re=new Set(["if","unless","while","repeat","for"]),ia=new Set(["then","end","else","if","unless","while","for","repeat","and"]),aa=new Set(["first","last","next","previous","random","closest"]),Le=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"]),Ge=class extends Error{constructor(e,t,r,n){super(e),this.name="SemanticParseError",this.language=t,this.input=r,this.diagnostics=n}};function $(o,e,t){return{message:o,severity:e,source:"semantic-parser",...t&&{code:t}}}function Z(o,e){return e.length===0?o:{...o,diagnostics:e}}function _r(o){if(o.length>=2){let e=o[0];if((e==='"'||e==="'")&&o.endsWith(e))return o.slice(1,-1)}return o}var sa=["body","statements","thenBranch","elseBranch","eventHandlers","initBlock"];function Br(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"&&Le.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 sa){let n=t[r];if(Array.isArray(n))for(let i of n)Br(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 Br(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=Or(e,t,{statement:(v,b)=>this.parse(v,b),body:(v,b)=>this.parseStatements(v,b)});if(r)return r;let n=Vr(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=G(u,t),p=Q(t);if(p.length===0)throw new Ge(`No patterns available for language: ${t}`,t,u,[$(`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(P=>P.normalized==="on");if(b>=2&&b+1<v.length){let P=u.slice(v[0].position.start,v[b].position.start).trim(),N=v[b+1].position.end,V=u.slice(v[b].position.start,N)+" "+P+u.slice(N);if(V!==u)try{let M=this.parse(V,t);if(M&&M.kind==="event-handler"){let O=i?this.applyModifiers(M,i):M;return Z(O,f)}}catch{}}}}{let v=m.tokens;for(let b=1;b<v.length-1;b++){let P=v[b],N=P.value,V=(P.normalized??P.value).toLowerCase();if(!(V==="or"||L.OR_KEYWORDS.has(N)||L.OR_KEYWORDS.has(V)))continue;let O=v[b+1],_=(O.normalized??O.value).toLowerCase();if(!L.KNOWN_EVENTS.has(_))break;let z=b+1,K=v[b+2];K&&K.kind==="selector"&&K.value.startsWith("[")&&(z=b+2);let U=v[b].position.start,fe=v[z].position.end,oe=(u.slice(0,U).trimEnd()+" "+u.slice(fe).trimStart()).trim();if(oe&&oe!==u)try{let he=this.parse(oe,t);if(he&&he.kind==="event-handler"){he.additionalEvents=[{type:"literal",value:_}];let yt=i?this.applyModifiers(he,i):he;return Z(yt,f)}}catch{}break}}let y=h.filter(v=>v.command==="on"),g=m.mark(),S=se.matchBest(m,y);if(S){f.push($(`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"),P=(b?.raw??b?.value??"").toString().toLowerCase(),N=xe[t],V=L.KNOWN_EVENTS.has(P)||!!N&&Object.keys(N).some(M=>M.toLowerCase()===P);if(P&&!V){let M=this.trySOVEventExtraction(u,t,h);if(M){f.push($(`bare-event mis-anchor on "${P}" rejected; SOV extraction preferred`,"info","stage-bare-event-guard"));let O=i?this.applyModifiers(M,i):M;return Z(O,f)}if(b?.type==="reference"||b?.type==="expression"){m.reset(g);let O=h.filter(z=>z.command!=="on"),_=se.matchBest(m,O);m.reset(g),_&&_.pattern.command!=="on"?(v=!0,f.push($(`bare-event mis-anchor on reference "${P}" rejected; command ${_.pattern.command} preferred`,"info","stage-bare-event-guard"))):se.matchBest(m,y)}}}if(!v){let b=this.buildEventHandler(S,m,t),P=i?this.applyModifiers(b,i):b;return Z(P,f)}}f.push($(`event patterns: ${y.length} tried, no match`,"info","stage-event"));let T=this.tryTrailingEventExtraction(u,t,h);if(T){f.push($("trailing event extraction succeeded","info","stage-trailing-event"));let v=i?this.applyModifiers(T,i):T;return Z(v,f)}let C=h.filter(v=>v.command!=="on"),x=se.matchBest(m,C);if(x){if(Re.has(x.pattern.command)){let v=this.trySOVEventExtraction(u,t,h);if(v){f.push($(`SOV event extraction preferred over bare ${x.pattern.command} command`,"info","stage-sov-loop"));let P=i?this.applyModifiers(v,i):v;return Z(P,f)}let b=this.tryMidStreamEventExtraction(u,t,h);if(b){f.push($(`mid-stream event extraction preferred over bare ${x.pattern.command} command`,"info","stage-midstream-loop"));let P=i?this.applyModifiers(b,i):b;return Z(P,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($(`SOV event extraction preferred over command-homonym event ${x.pattern.command}`,"info","stage-sov-homonym"));let b=i?this.applyModifiers(v,i):v;return Z(b,f)}}else if(I(t)?.wordOrder==="VSO"){let v=this.tryMidStreamEventExtraction(u,t,h);if(v){f.push($(`mid-stream event extraction preferred over bare ${x.pattern.command} command`,"info","stage-midstream-cmd"));let b=i?this.applyModifiers(v,i):v;return Z(b,f)}}if(x.consumedTokens<m.tokens.length&&I(t)?.wordOrder==="SOV"){let v=this.trySOVEventExtraction(u,t,h);if(v){f.push($(`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 Z(b,f)}}return f.push($(`command pattern matched: ${x.pattern.id} (confidence: ${x.confidence.toFixed(2)})`,"info","pattern-match")),Z(this.buildCommand(x,t),f)}if(f.push($(`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($("mid-stream event extraction succeeded with no leading command match","info","stage-midstream-nocmd"));let b=i?this.applyModifiers(v,i):v;return Z(b,f)}}let k=this.trySOVEventExtraction(u,t,h);if(k){f.push($("SOV event extraction succeeded","info","stage-sov"));let v=i?this.applyModifiers(k,i):k;return Z(v,f)}f.push($("SOV event extraction: no event keyword found","info","stage-sov"));let E=this.tryCompoundCommandParsing(m,C,t);if(E)return f.push($("compound command parsing succeeded","info","stage-compound")),Z(E,f);throw f.push($("compound parsing: no then-keywords or no command matches","info","stage-compound")),f.push($(`all parse stages exhausted for "${u}"`,"error","parse-failed")),new Ge(`Could not parse input in ${t}: ${u}`,t,u,f)}parseStatements(e,t){let r=G(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 dt()}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=H(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=se.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 X(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 me(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=E=>(E.normalized??E.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 E=t.peek();if(E)for(u.event={type:"literal",value:x(E)},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=H(d,u,{sourceLanguage:r,patternId:e.pattern.id,confidence:e.confidence});if(this.registerBoundIdentifiers(f),!Re.has(d)||d==="repeat"){let C=e.pattern.id.includes("verb-first"),x=t.tokens,k=t.position(),E=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 P=x[b];if(E(P))break;if((P.normalized??P.value).toLowerCase()===d){v=b;break}}if(v>=0){let b=k;for(;b<x.length&&!E(x[b]);)b++;let P=x.slice(v,b),N=P;if(C){let V=String(n.value??"").toLowerCase(),M=P.findIndex(O=>(O.normalized??O.value).toLowerCase()===V);if(M<0)N=null;else{let O=P[M-1],_=O&&O.kind==="keyword"&&O.normalized?.toLowerCase()==="on"?M-1:M;N=[...P.slice(0,_),...P.slice(M+1)]}}if(N&&N.length>1){let V=Q(r).filter(q=>q.command!=="on").sort((q,ue)=>ue.priority-q.priority),M=this.parseClause(N,V,r),O=M[0],_=q=>q!==null&&typeof q=="object"&&typeof q.type=="string"?q.type:typeof q,z=ne(d),K=z?.primaryRole,U=q=>q==="patient"&&K&&K!=="patient"&&!z?.roles.some(ue=>ue.role==="patient")?K:q,fe=(q,ue)=>{if(!Re.has(d)||!z)return!1;let Se=z.roles.find($r=>$r.role===U(q));return Se?Se.expectedTypes.length>0&&!Se.expectedTypes.includes(_(ue)):!0},oe=!!O&&O.kind==="command"&&Object.entries(u).every(([q,ue])=>{if(fe(q,ue))return!0;let Se=O.roles.get(U(q));return Se!==void 0&&_(Se)===_(ue)}),he=O?.metadata?.patternId??"",yt=!Re.has(d)||/^repeat-.*-(times|for-in|while-head|until-head)$/.test(he);if(M.length===1&&O&&O.kind==="command"&&O.action===d&&oe&&yt&&O.roles.size>Object.keys(u).length)for(f=O;t.position()<b;)t.advance()}}}if(!Re.has(d)){let C=f;if(ne(d)?.roles.some(N=>N.role==="quantity"&&!N.required)&&!C.roles.has("quantity")){let N=t.peek();N&&/^-?\d+(\.\d+)?$/.test(N.value)&&(f=H(d,{...Object.fromEntries(C.roles),quantity:{type:"literal",value:parseFloat(N.value),dataType:"number"}},C.metadata),t.advance())}let k=f;if(ne(d)?.roles.some(N=>N.role==="duration"&&!N.required)&&!k.roles.has("duration")){let N=t.peek();N&&/^\d+(\.\d+)?(ms|s)$/i.test(N.value)&&(f=H(d,{...Object.fromEntries(k.roles),duration:{type:"literal",value:N.value,dataType:"string"}},k.metadata),t.advance(),this.consumeForPostposition(t,r))}let v=f,b=ne(d);if(b?.roles.find(N=>N.role==="responseType"&&!N.required)&&!v.roles.has("responseType")){let N=z=>typeof z=="string"&&L.RESPONSE_TYPE_WORDS.has(z.toLowerCase()),V=(z,K)=>{let U=Object.fromEntries(v.roles);K&&delete U.destination,U.responseType={type:"expression",raw:z},f=H(d,U,v.metadata)},M=v.roles.get("destination"),O=b?.roles.find(z=>z.role==="destination"),_=M?.raw??M?.value;if(M&&O&&!O.expectedTypes.includes(M.type)&&N(_))V(_,!0);else{let z=t.peek();z&&N(z.value)&&(V(z.value,!1),t.advance())}}if(d==="wait"){let N=f;if(!N.roles.has("event")){let V=t.peek();if(V&&Le.has(V.value.toLowerCase())){let M=Object.fromEntries(N.roles),O=M.duration;O&&O.type!=="literal"&&O.type!=="expression"&&delete M.duration;let _=M.patient;_&&_.type==="reference"&&_.value==="me"&&delete M.patient,M.event={type:"literal",value:V.value,dataType:"string"},f=H(d,M,N.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=Re.has(d)&&!!h&&!this.isEndKeyword(h.value,r),T=!!h&&!this.isEndKeyword(h.value,r);if(p||y||S||T){let C=Q(r).filter(E=>E.command!=="on").sort((E,v)=>v.priority-E.priority),x=Q(r).filter(E=>E.id.startsWith("grammar-")&&E.id.includes("-continuation")).sort((E,v)=>v.priority-E.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 me(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"||Mt(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?[je(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 T=i[S],C=g.get(T.value.toLowerCase())??(T.normalized?g.get(T.normalized.toLowerCase()):void 0);if(C&&!L.CONDITION_OPERATORS.has(C)){a=i.slice(0,S),i=i.slice(S);break}}}let l=new X(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 T of this.parseSOVClauseByVerbAnchoring(y,r)){let C=T.action,x=T.roles;C&&ne(C)&&x instanceof Map&&x.size>0&&c.push(T)}};for(;!l.isAtEnd();){let y=l.peek(),g=!!y&&y.normalized?.toLowerCase()==="repeat",S=l.mark(),T=se.matchBest(l,t);if(g&&T&&T.pattern.command!=="repeat"){l.reset(S),m(),c.push(H("repeat",{},{sourceLanguage:r,confidence:.6})),d++,l.advance();continue}if(T&&T.pattern.command==="if"){let C=l.mark(),x=u.length;for(l.reset(S);!l.isAtEnd();){let E=l.peek();if(!E||this.isIfKeyword((E.normalized??E.value).toLowerCase(),r))break;u.push(E),l.advance()}let k=this.tryParseConditionalBlock(l,t,r);if(k){m(),c.push(k),d++;continue}u.length=x,l.reset(C)}if(T){m();let C=this.buildCommand(T,r);c.push(C),d++,this.tryAttachTrailingRole(l,C,r)}else{let C=l.peek();C&&C.normalized?.toLowerCase()==="repeat"?(m(),c.push(H("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?[H(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 ia.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(aa.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(H(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("'")?B(_r(r),"string"):n.kind==="reference"?J(r):B(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 B(_r(t),"string");if(/^-?\d+(\.\d+)?$/.test(t))return B(parseFloat(t));if(t==="true"||t==="\u771F"||t==="\uCC38"||t==="do\u011Fru")return B(!0);if(t==="false"||t==="\u507D"||t==="\uAC70\uC9D3"||t==="yanl\u0131\u015F")return B(!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"):B(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(!Mt(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=se.matchBest(e,r);if(m){let p=m.pattern.command,h={};for(let[S,T]of m.captured)S!=="event"&&S!=="action"&&S!=="continues"&&(h[S]=T);let y=H(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=se.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 X(n,r),l=this.parseBodyWithClauses(a,t,r);return l.length===0?null:l.length===1?l[0]:je(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}=G(e,t),i=xe[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)||Le.has(d))||L.KNOWN_EVENTS.has(c)||Le.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=G(e,t).tokens;if(n.length<3)return null;let i=xe[t],s=new Set;if(i)for(let T of Object.keys(i))s.add(T.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(T=>T.command!=="on"),g=new X(h,t),S=this.parseBodyWithClauses(g,y,t);return S.length===0?null:me({type:"literal",value:p},S,void 0,{sourceLanguage:t,confidence:.75})}tryMidStreamEventExtraction(e,t,r){let n=G(e,t).tokens;if(n.length<3)return null;let i=xe[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((T,C)=>C!==a&&C!==a+1);if(h.length===0)return null;let y=r.filter(T=>T.command!=="on"),g=new X(h,t),S=this.parseBodyWithClauses(g,y,t);return S.length===0?null:me({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=G(e,t).tokens,a=xe[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],E=k.value.toLowerCase(),v=E,b="",P=E.indexOf("[");P>0&&(v=E.slice(0,P),b=k.value.slice(P));let N=k.normalized?.toLowerCase(),V=N&&(L.KNOWN_EVENTS.has(N)||Le.has(N)),M=l.has(E)||l.has(v),O=L.KNOWN_EVENTS.has(v)||Le.has(v);if(V||M||O){let _=s[x-1];if(_&&(_.normalized??_.value).toLowerCase()==="event")continue;let z;V?z=N:M?z=a?.[E]??a?.[v]??v:z=v;let K=this.matchEventParamPhrase(s,x+1);if(n.size>0){let U=1+K.len,fe=s[x+U];fe&&fe.kind==="selector"&&fe.value.startsWith("[")&&(U+=1);let oe=s[x+U];if(oe&&(oe.kind==="particle"||oe.kind==="keyword")&&n.has(oe.value)){d=x,u=z,f=b||(U===K.len+2?s[x+U-1].value:""),m=U+1,p=K.names;break}}else{d=x,u=z,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 E=s[k];if(E.kind==="identifier")if(n.size>0){let v=1,b=s[k+1];b&&b.kind==="selector"&&b.value.startsWith("[")&&(v=2);let P=s[k+v];if(P&&(P.kind==="particle"||P.kind==="keyword")&&n.has(P.value)){d=k,u=E.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=E.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=E.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 E=s[x+1];E&&(E.kind==="particle"||E.kind==="keyword")&&c.markers.has(E.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 E=s[k],v=E.value.toLowerCase(),b=E.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 X(y,t),T=this.parseBodyWithClauses(S,g,t);if(T.length===0)return null;let C={sourceLanguage:t,confidence:.75};return f&&(C.keyFilter=f),me({type:"literal",value:u},T,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 H("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 E=(k.normalized??k.value).toLowerCase();if(this.isIfKeyword(E,r)||this.isUnlessKeyword(E,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],E=(k.normalized??k.value).toLowerCase();if(this.isIfKeyword(E,r)||this.isUnlessKeyword(E,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(),P=(k.normalized??k.value).toLowerCase(),N=L.CONDITION_COPULAS.has(v)||L.CONDITION_COPULAS_SURFACE.has(b)&&L.CONDITION_PREDICATES.has(P),V=d!==null&&d.has(k.value.toLowerCase())&&!L.CONDITION_PREDICATES.has(P);if(!L.CONDITION_OPERATORS.has(P)&&(!N||V)&&(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],E=(k.normalized??k.value).toLowerCase();if(this.isIfKeyword(E,r)||this.isUnlessKeyword(E,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 T={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):yr(T,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 X(e,r);return se.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 X(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=G(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=G(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=G(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 ht=L,Dt=new ht;function Ae(o,e){return Dt.parse(o,e)}function $t(o,e){return Dt.canParse(o,e)}function qt(o,e){if(de(o))return o;let t=Ae(o,e);return He(t)}function Wt(o,e){let t=Pe(o);return Ue(t,e)}function Kt(o,e){return de(o)?Pe(o):Ae(o,e)}bt("ja",ut,ve);var la="1.0.0-ja",ca=["ja"];function ua(){return[...ca]}function jr(o){if(o!=="ja")throw new Error(`Language not supported in this bundle: ${o}. Supported: ja`)}function da(o,e){return jr(e),[...G(o,e).tokens]}function Dr(o){return jr(o),Q(o)}function pa(o,e){return Dr(o).filter(t=>t.command===e).sort((t,r)=>r.priority-t.priority)}return Hr(ma);})();