@hyperfixi/core 2.9.0 → 2.9.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 (49) hide show
  1. package/dist/ast-utils/index.js +905 -882
  2. package/dist/ast-utils/index.mjs +905 -882
  3. package/dist/chunks/{bridge-D9JLmPkk.js → bridge-BYhqTOnL.js} +2 -2
  4. package/dist/chunks/browser-modular-D2BHzZFB.js +2 -0
  5. package/dist/chunks/feature-eventsource-Bxg_UNZo.js +2 -0
  6. package/dist/chunks/feature-sockets-CcTxD5sT.js +2 -0
  7. package/dist/chunks/feature-webworker-DoqZ0Grg.js +2 -0
  8. package/dist/chunks/{index-6DUg7Qjm.js → index-DXgJaDj-.js} +2 -2
  9. package/dist/commands/index.js +168 -112
  10. package/dist/commands/index.mjs +168 -112
  11. package/dist/hyperfixi-browser-classic-i18n.js +1 -1
  12. package/dist/hyperfixi-browser-minimal.js +1 -1
  13. package/dist/hyperfixi-browser-standard.js +1 -1
  14. package/dist/hyperfixi-browser.js +1 -1
  15. package/dist/hyperfixi-classic-i18n.js +1 -1
  16. package/dist/hyperfixi-hx-v4.js +1 -1
  17. package/dist/hyperfixi-minimal.js +1 -1
  18. package/dist/hyperfixi-multilingual.js +1 -1
  19. package/dist/hyperfixi-standard.js +1 -1
  20. package/dist/hyperfixi.js +1 -1
  21. package/dist/hyperfixi.mjs +1 -1
  22. package/dist/index.js +1505 -1402
  23. package/dist/index.min.js +1 -1
  24. package/dist/index.mjs +1505 -1402
  25. package/dist/lokascript-browser-classic-i18n.js +1 -1
  26. package/dist/lokascript-browser-minimal.js +1 -1
  27. package/dist/lokascript-browser-standard.js +1 -1
  28. package/dist/lokascript-browser.js +1 -1
  29. package/dist/lokascript-multilingual.js +1 -1
  30. package/dist/lsp-metadata.js +5 -5
  31. package/dist/lsp-metadata.mjs +5 -5
  32. package/dist/metadata.js +25 -25
  33. package/dist/metadata.mjs +25 -25
  34. package/dist/multilingual/index.js +17 -17
  35. package/dist/multilingual/index.mjs +17 -17
  36. package/dist/parser/command-parsers/utility-commands.d.ts +1 -0
  37. package/dist/parser/full-parser.js +155 -106
  38. package/dist/parser/full-parser.mjs +155 -106
  39. package/dist/parser/parser.d.ts +1 -0
  40. package/dist/reference/index.js +1 -0
  41. package/dist/reference/index.mjs +1 -0
  42. package/dist/registry/index.js +155 -106
  43. package/dist/registry/index.mjs +155 -106
  44. package/dist/types/base-types.d.ts +3 -0
  45. package/package.json +5 -5
  46. package/dist/chunks/browser-modular-CPiVQXM0.js +0 -2
  47. package/dist/chunks/feature-eventsource-BpZvPy_K.js +0 -2
  48. package/dist/chunks/feature-sockets-CrYvjZ4j.js +0 -2
  49. package/dist/chunks/feature-webworker-BSYguEIW.js +0 -2
@@ -1 +1 @@
1
- var hyperfixi=function(){"use strict";const t="then",e="else",n="end",r="and",s="for",i="while",o="until",a="forever",c="times",u="index",l="in",h="to",f="from",d="with",p="of",m="on",y="event",g="behavior",v="global",b="the",w="start",E=new Set(["add","append","async","beep","blur","break","breakpoint","call","clear","close","continue","copy","decrement","default","empty","exit","fetch","focus","for","get","go","halt","hide","open","if","increment","install","js","log","make","measure","morph","pick","process","push","put","remove","render","repeat","replace","reset","return","scroll","select","send","set","settle","show","start","swap","take","tell","throw","toggle","transition","trigger","unless","wait"]),x=new Set(["put","trigger","send","remove","take","toggle","set","show","hide","add","halt","measure","js","go","tell","pick","start","swap","morph","push","replace","process"]),k=(new Set(["if","unless","repeat","wait","for","while"]),"at start of"),S="at end of",A=["into","before","after","at",k,S,"at the start of","at the end of"],N=new Set(["if","else","unless","for","while","until","end","and","or","not","in","to","from","into","with","without","as","matches","contains","then","on","when","every","init","def","behavior","the","of","first","last"]),C=new Set(["hsl","hsla","rgb","rgba","hwb","lab","lch","oklch","oklab","color","color-mix","calc","min","max","clamp","var","url","linear-gradient","radial-gradient","conic-gradient","repeating-linear-gradient","repeating-radial-gradient","repeating-conic-gradient"]),T=new Set(["me","it","you","result","my","its","your"]),O=new Set(["and","or","not","no"]),$=new Set(["==","!=","===","!==","<",">","<=",">=","is","is not","am","is a","is an","is not a","is not an","precedes","does not precede","follows","does not follow","contains","starts with","ends with","does not start with","does not end with","has","have","does not contain","include","includes","does not include","match","matches","exists","does not exist","is empty","is not empty","is in","is not in","is between","is not between","equals","in","is equal to","is really equal to","is not equal to","is not really equal to","is greater than","is less than","is greater than or equal to","is less than or equal to","really equals","am in","am not in","am between","am not between","is really","is not really","is equal","is not equal","contain","do not contain","does not contains","do not match","does not match","ignoring case","sorted by","mapped to","split by","joined by"]),R=new Set(["click","dblclick","mousedown","mouseup","mouseover","mouseout","mousemove","mouseenter","mouseleave","focus","blur","change","input","submit","reset","select","load","unload","resize","scroll","keydown","keyup","keypress","touchstart","touchend","touchmove","touchcancel","drag","drop","dragover","dragenter","dragleave","cut","copy","paste","toggle"]),L=new Set(["on","init","behavior","def","if","else","unless","for","while","until","end","and","or","not","in","to","from","into","with","as","then","when","where","after","before","by","at","between","async","no","start","of","the","new","global","local","equal","equals","greater","less","than","really","catch","finally","throw","return"]);var I;!function(t){t.IDENTIFIER="identifier",t.STRING="string",t.NUMBER="number",t.SELECTOR="selector",t.OPERATOR="operator",t.TIME="time",t.TEMPLATE="template",t.COMMENT="comment",t.SYMBOL="symbol",t.UNKNOWN="unknown"}(I||(I={}));const j=new Set(["+","-","*","/","mod"]),M=new Set(["ms","s","seconds","minutes","hours","days"]);function D(t,e=1){const n=t.position+e;return t.input.length>n?t.input[n]:""}function P(t){const e=t.input[t.position];return t.position++,"\n"===e?(t.line++,t.column=1):"\r"===e?("\n"===(t.input.length>t.position?t.input[t.position]:"")&&t.position++,t.line++,t.column=1):t.column++,e}function F(t){const e=t.input,n=e.length;for(;n>t.position;){const n=e[t.position];if(" "!==n&&"\t"!==n&&"\r"!==n&&"\n"!==n)break;P(t)}}function B(t,e,n,r,s){const i=r??t.position-n.length,o=t.position;let a=t.column-n.length;if(void 0!==r){a=1;let e=-1;for(let n=0;r>n;n++)"\n"!==t.input[n]&&"\r"!==t.input[n]||(e=n);a=r-e}const c={kind:e,value:n,start:i,end:o,line:_(t,i),column:a};t.tokens.push(c)}function _(t,e){let n=1;for(let r=0;e>r&&t.input.length>r;r++){const e=t.input[r];"\n"===e?n++:"\r"===e&&(n++,t.input.length>r+1&&"\n"===t.input[r+1]&&r++)}return n}function V(t){const e=t.position;let n="";for(P(t),P(t);t.input.length>t.position&&"\n"!==t.input[t.position];)n+=P(t);B(t,I.COMMENT,"--"+n,e)}function q(t){const e=t.position,n=P(t);let r=n;for(;t.input.length>t.position;){const e=P(t);if(r+=e,e===n)break;"\\"===e&&t.input.length>t.position&&(r+=P(t))}B(t,I.STRING,r,e)}function H(t){const e=t.position;P(t);let n="";for(;t.input.length>t.position;){const e=t.input[t.position];if("`"===e){P(t);break}if("\\"===e){if(P(t),t.input.length>t.position){const e=P(t);switch(e){case"n":n+="\n";break;case"t":n+="\t";break;case"r":n+="\r";break;case"\\":n+="\\";break;case"`":n+="`";break;default:n+=e}}}else n+=P(t)}if(t.position>=t.input.length&&!t.input.endsWith("`"))throw Error(`Unterminated template literal at line ${t.line}, column ${t.column-n.length}`);B(t,I.TEMPLATE,n,e)}function U(t){const e=t.position;let n=P(t);if(t.input.length>t.position&&"{"===t.input[t.position]){for(n+=P(t);t.input.length>t.position;){const e=t.input[t.position];if(n+=P(t),"}"===e)break}B(t,I.SELECTOR,n,e)}else{for(;t.input.length>t.position;){const e=t.input[t.position];if("\\"===e)P(t),t.input.length>t.position&&(n+=P(t));else{if(!K(e)&&"-"!==e&&"_"!==e&&":"!==e)break;n+=P(t)}}B(t,I.SELECTOR,n,e)}}function W(t){const e=t.position;if(Q(t))return void function(t,e){const n=t.input;let r="",s=0,i="";for(;n.length>t.position;){const e=n[t.position];if(i)r+=P(t),e===i&&(i="");else if('"'!==e&&"'"!==e){if("<"===e){if("/"===n[t.position+1]){for(;n.length>t.position&&">"!==n[t.position];)r+=P(t);if(n.length>t.position&&(r+=P(t)),s--,0>=s)break;continue}let e=0,i="";for(;n.length>t.position;){const s=n[t.position];if(i)r+=P(t),s===i&&(i="");else if('"'!==s&&"'"!==s){if(">"===s){e="/"===n[t.position-1],r+=P(t);break}r+=P(t)}else i=s,r+=P(t)}if(e||s++,0>=s)break;continue}r+=P(t)}else i=e,r+=P(t)}B(t,I.SELECTOR,r,e)}(t,e);let n="";for(n+=P(t);t.input.length-1>t.position;){const e=t.input[t.position],r=t.input[t.position+1];if(n+=P(t),"/"===e&&">"===r){n+=P(t);break}}B(t,I.SELECTOR,n,e)}function z(t){const e=t.position;let n=P(t);for(;t.input.length>t.position;){const e=t.input[t.position];if(!K(e)&&"_"!==e&&"-"!==e)break;n+=P(t)}B(t,I.SYMBOL,n,e)}function J(t){const e=t.position;let n="";const r=t.input[t.position];if(("'"===r||"'"===r)&&"s"===D(t,1))return n="'s",P(t),P(t),void B(t,I.OPERATOR,n,e);const s=t.input.substring(t.position,t.position+2),i=t.input.substring(t.position,t.position+3);["===","!=="].includes(i)?(n=i,P(t),P(t),P(t)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(s)?(n=s,P(t),P(t)):n=P(t),B(t,I.OPERATOR,n,e)}function Z(t){const e=t.position,n=t.input,r=n.length;let s="";for(;r>t.position;){const e=n[t.position];if("0">e||e>"9")break;s+=P(t)}if(r>t.position&&"."===n[t.position]&&(t.position+1>=r||"."!==n[t.position+1]))for(s+=P(t);r>t.position;){const e=n[t.position];if("0">e||e>"9")break;s+=P(t)}if(r>t.position){const e=n[t.position];if("e"===e||"E"===e){const e=r>t.position+1?n[t.position+1]:"",i=r>t.position+2?n[t.position+2]:"";if(e>="0"&&"9">=e||!("+"!==e&&"-"!==e||"0">i||i>"9"))for(s+=P(t),"+"!==n[t.position]&&"-"!==n[t.position]||(s+=P(t));r>t.position;){const e=n[t.position];if("0">e||e>"9")break;s+=P(t)}}}const i=t.position;let o="";for(;r>t.position;){const e=n[t.position];if(("a">e||e>"z")&&("A">e||e>"Z"))break;o+=P(t)}M.has(o)?B(t,I.TIME,s+o,e):(t.position=i,B(t,I.NUMBER,s,e))}function G(t){const e=t.position,n=t.input,r=n.length;let s="";for(;r>t.position;){const e=n[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;s+=P(t)}const i=function(t,e,n){const r=e.toLowerCase(),s=t.position;if("'s"===e||"'s"===e)return 0;const i=t.tokens[t.tokens.length-1];if(i&&(i.kind===I.IDENTIFIER||i.kind===I.SELECTOR)){const e=t.input.length>t.position?t.input[t.position]:"";if("'"===e||"'"===e)return 0}F(t);let o="";for(;t.input.length>t.position;){const e=t.input[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;o+=P(t)}if(o){const e=o.toLowerCase(),s=`${r} ${e}`,i=function(t,e,n,r){const s=e.toLowerCase(),i=n.toLowerCase();if("at"===s){const e=t.position;if("the"===i){F(t);let n="";for(;t.input.length>t.position;){const e=t.input[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;n+=P(t)}const s=n.toLowerCase();if("start"===s||"end"===s){F(t);let e="";for(;t.input.length>t.position;){const n=t.input[t.position];if(("a">n||n>"z")&&("A">n||n>"Z")&&("0">n||n>"9")&&"_"!==n&&"-"!==n)break;e+=P(t)}if("of"===e.toLowerCase())return B(t,I.IDENTIFIER,`at the ${s} of`,r),1}return t.position=e,0}if("start"===i||"end"===i){F(t);let n="";for(;t.input.length>t.position;){const e=t.input[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;n+=P(t)}return"of"===n.toLowerCase()?(B(t,I.IDENTIFIER,`at ${i} of`,r),1):(t.position=e,0)}}return 0}(t,r,e,n);if(i)return 1;const a=function(t,e,n){const r=t.position;let s=`${e} ${n}`,i=t.position;const o=[e,n];for(;8>o.length&&(F(t),t.input.length>t.position);){let e="";for(;t.input.length>t.position;){const n=t.input[t.position];if(("a">n||n>"z")&&("A">n||n>"Z"))break;e+=P(t)}if(!e)break;o.push(e.toLowerCase());const n=o.join(" ");$.has(n)&&(s=n,i=t.position)}return $.has(s)&&s!==`${e} ${n}`?(t.position=i,s):(t.position=r,null)}(t,r,e);if(a)return B(t,I.OPERATOR,a,n),1;if($.has(s))return B(t,I.OPERATOR,s,n),1}return $.has(r)?(t.position=s,B(t,I.OPERATOR,e,n),1):(t.position=s,0)}(t,s,e);if(i)return;const o=function(t){const e=t.toLowerCase();return"include"===e||"includes"===e||O.has(e)||j.has(t)||j.has(e)||$.has(e)?I.OPERATOR:I.IDENTIFIER}(s);B(t,o,s,e)}function X(t){const e=t.position,n=t.input,r=n.length;P(t);let s="$";for(;r>t.position;){const e=n[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e)break;s+=P(t)}B(t,I.IDENTIFIER,s,e)}function Y(t){return/[a-zA-Z]/.test(t)}function K(t){return/[a-zA-Z0-9]/.test(t)}function Q(t){const e=t.input,n=e[t.position+1];if(!n||!/[a-zA-Z]/.test(n))return 0;let r=t.position+1,s="";for(;e.length>r&&/[a-zA-Z0-9-]/.test(e[r]);)s+=e[r],r++;return s.length>0&&-1!==e.indexOf("</"+s+">",r)}function tt(t){if(Q(t))return 1;let e=t.position+1,n=0;for(;t.input.length>e;){const r=t.input[e];if("/"===r&&t.input.length>e+1&&">"===t.input[e+1])return n;if(K(r)||"."===r||"#"===r||"["===r||"]"===r||":"===r||"-"===r||"_"===r||" "===r||"="===r||'"'===r||"'"===r||"("===r||")"===r||"*"===r||"^"===r||"$"===r||"~"===r||"|"===r||">"===r||"+"===r||","===r||"{"===r||"}"===r)n=1,e++;else{if(" "!==r&&"\t"!==r)return 0;e++}if(e-t.position>50)return 0}return 0}function et(t){return"+-*/^%=!<>&|(){}[],.;:?''~$".includes(t)}const nt=function(){if("undefined"!=typeof localStorage)try{const t=localStorage,e=t.getItem("hyperfixi:debug")||t.getItem("lokascript:debug");if("*"===e||"true"===e)return 1}catch{}return"undefined"!=typeof process&&"true"===process.env?.HYPERFIXI_DEBUG?1:0}(),rt=nt,st=nt,it=nt,ot=nt,at=(...t)=>{rt&&console.log("🔧",...t)},ct=(...t)=>{st&&console.log("🎯",...t)},ut=(...t)=>{it&&console.log("📝",...t)},lt=(...t)=>{ot&&console.log("🚀",...t)};let ht=0,ft=null;if("undefined"!=typeof window&&"undefined"!=typeof URLSearchParams)try{"semantic"===new URLSearchParams(window.location.search).get("debug")&&(ht=1,ft=window,console.log("%c[HyperFixi] Semantic debug auto-enabled via URL param","color: #667eea; font-weight: bold"))}catch{}let dt={totalParses:0,semanticSuccesses:0,semanticFallbacks:0,traditionalParses:0,averageConfidence:0,confidenceHistory:[]};class pt{constructor(t){this.analyzer=t.analyzer,this.language=t.language,this.confidenceThreshold=t.confidenceThreshold??.5,this.debugEnabled=t.debug??0}isAvailable(){return this.analyzer.supportsLanguage(this.language)}shouldSkipSemantic(t){const e=t.trim().split(/\s+/)[0]?.toLowerCase();if(pt.SKIP_SEMANTIC_COMMANDS.has(e))return 1;const n=t.toLowerCase();return/\bjs\b/.test(n)||/\btell\b/.test(n)||/\*[a-zA-Z]/.test(t)?1:0}trySemanticParse(t){const e=performance.now();if(this.shouldSkipSemantic(t))return{success:0,confidence:0,errors:["Command skipped for semantic parsing - using traditional parser"]};if(!this.isAvailable())return{success:0,confidence:0,errors:[`Semantic parsing not available for language '${this.language}'`]};try{const r=this.analyzer.analyze(t,this.language),s=performance.now()-e;this.debugEnabled&&console.log("[SemanticIntegration] Analysis result:",{input:t,language:this.language,confidence:r.confidence,command:r.command?.name,threshold:this.confidenceThreshold});const i=r.confidence>=this.confidenceThreshold&&!!r.command,o=!i&&r.confidence>0;if(ht){const e={};if(r.command?.roles)for(const[t,n]of r.command.roles)e[t]=n.value;const a={input:t.substring(0,100),language:this.language,confidence:r.confidence,threshold:this.confidenceThreshold,semanticSuccess:i,fallbackTriggered:o,command:r.command?.name,roles:Object.keys(e).length>0?e:void 0,errors:r.errors,timestamp:Date.now(),duration:s};!function(t){if(!ht)return;const e=t.semanticSuccess?"semantic":t.fallbackTriggered?"fallback":"traditional",n=Math.round(100*t.confidence),r=Math.round(100*t.threshold),s=t.semanticSuccess?"color: #4caf50; font-weight: bold":t.fallbackTriggered?"color: #ff9800; font-weight: bold":"color: #9e9e9e";if(console.groupCollapsed(`%c[Semantic] ${e.toUpperCase()} %c${t.input.substring(0,50)}${t.input.length>50?"...":""}`,s,"color: #888"),console.log(`Confidence: ${n}% (threshold: ${r}%)`),t.command&&console.log("Command: "+t.command),t.roles&&Object.keys(t.roles).length>0&&console.log("Roles:",t.roles),t.duration&&console.log(`Duration: ${t.duration.toFixed(2)}ms`),t.errors?.length&&console.log("Errors:",t.errors),console.groupEnd(),ft){const e=new CustomEvent("lokascript:semantic:parse",{detail:t,bubbles:1});ft.dispatchEvent(e)}}(a),n=a,dt.totalParses++,n.semanticSuccess?dt.semanticSuccesses++:n.fallbackTriggered?dt.semanticFallbacks++:dt.traditionalParses++,dt.confidenceHistory.push(n.confidence),dt.confidenceHistory.length>100&&dt.confidenceHistory.shift(),dt.averageConfidence=dt.confidenceHistory.reduce((t,e)=>t+e,0)/dt.confidenceHistory.length}return i?{success:1,node:this.buildCommandNode(r),confidence:r.confidence,tokensConsumed:r.tokensConsumed}:{success:0,confidence:r.confidence,tokensConsumed:r.tokensConsumed,errors:r.errors}}catch(t){return{success:0,confidence:0,errors:[t instanceof Error?t.message:t+""]}}var n}buildCommandNode(t){const{command:e}=t;if(!e)throw Error("Cannot build command node without command data");if("repeat"===e.name)return this.buildRepeatCommandNode(e);if("for"===e.name)return this.buildRepeatCommandNode(e);if("set"===e.name)return this.buildSetCommandNode(e);if("if"===e.name||"unless"===e.name)return this.buildIfCommandNode(e);const n=[],r={};for(const[t,s]of e.roles){const i=this.semanticValueToExpression(s);switch(t){case"patient":case"event":n.push(i);break;case"destination":"put"===e.name?r.into=i:"add"===e.name||"append"===e.name||"prepend"===e.name?r.to=i:r.on=i;break;case"source":"fetch"===e.name?n.push(i):r.from=i;break;case"quantity":r.by=i;break;case"duration":r.over=i;break;case"responseType":r.as=i;break;case"style":r.with=i;break;case"condition":r.when=i;break;default:r[t]=i}}return{type:"command",name:e.name,args:n,modifiers:Object.keys(r).length>0?r:void 0,isBlocking:0,start:0,end:0,line:1,column:0}}buildRepeatCommandNode(t){const e=[],n={},r=t.roles.get("loopType");r&&e.push({type:"identifier",name:r.value+"",start:0,end:0,line:1,column:0});const s=t.roles.get("patient");"for"==(r?r.value+"":"")&&s&&e.push({type:"identifier",name:"expression"===s.type&&s.raw||s.value+"",start:0,end:0,line:1,column:0});const i=t.roles.get("event");i&&e.push({type:"string",value:i.value+"",start:0,end:0,line:1,column:0});const o=t.roles.get("source");o&&e.push(this.semanticValueToExpression(o));const a=t.roles.get("quantity");a&&e.push(this.semanticValueToExpression(a));const c=t.roles.get("condition");return c&&(n.condition=this.semanticValueToExpression(c)),{type:"command",name:"repeat",args:e,modifiers:Object.keys(n).length>0?n:void 0,isBlocking:0,start:0,end:0,line:1,column:0}}buildSetCommandNode(t){const e=[],n=t.roles.get("destination");if(n)if("property-path"===n.type){const t=n;e.push({type:"possessiveExpression",object:this.semanticValueToExpression(t.object),property:this.createPropertyNode(t.property),start:0,end:0,line:1,column:0})}else e.push(this.semanticValueToExpression(n));e.push({type:"identifier",name:"to",start:0,end:0,line:1,column:0});const r=t.roles.get("patient");return r&&e.push(this.semanticValueToExpression(r)),{type:"command",name:"set",args:e,isBlocking:0,start:0,end:0,line:1,column:0}}createPropertyNode(t){return t.startsWith("*")?{type:"cssProperty",name:t.substring(1),start:0,end:0,line:1,column:0}:{type:"identifier",name:t,start:0,end:0,line:1,column:0}}buildIfCommandNode(t){const e=[],n=t.roles.get("condition");return n&&e.push(this.semanticValueToExpression(n)),{type:"command",name:t.name,args:e,isBlocking:0,start:0,end:0,line:1,column:0}}semanticValueToExpression(t){switch(t.type){case"selector":return{type:"selector",value:t.value,start:0,end:0,line:1,column:0};case"reference":return{type:"identifier",name:t.value,start:0,end:0,line:1,column:0};case"literal":return"string"==typeof t.value&&t.value.includes("${")&&t.value.includes("}")?{type:"templateLiteral",value:t.value,start:0,end:0,line:1,column:0}:{type:"literal",value:t.value,raw:t.raw??t.value,start:0,end:0,line:1,column:0};case"property-path":{const e=t;return{type:"memberExpression",object:this.semanticValueToExpression(e.object),property:{type:"identifier",name:e.property,start:0,end:0,line:1,column:0},computed:0,start:0,end:0,line:1,column:0}}default:return this.parseExpressionString(t.raw||"")}}parseExpressionString(t){let e=0;const n=()=>{for(;t.length>e&&/\s/.test(t[e]);)e++},r=()=>{n();const r=e;for(;t.length>e&&/[a-zA-Z0-9_$]/.test(t[e]);)e++;return t.slice(r,e)},s=()=>{const r=[];if(e++,n(),")"!==t[e])for(r.push(i()),n();","===t[e];)e++,n(),r.push(i()),n();return")"===t[e]&&e++,r},i=()=>{n();const i=r();if(!i)return{type:"identifier",name:t.trim(),start:0,end:0,line:1,column:0};let o={type:"identifier",name:i,start:0,end:0,line:1,column:0};for(;t.length>e;){n();const i=t[e];if("."===i){e++;const t=r();t&&(o={type:"memberExpression",object:o,property:{type:"identifier",name:t,start:0,end:0,line:1,column:0},computed:0,start:0,end:0,line:1,column:0})}else{if("("!==i)break;o={type:"callExpression",callee:o,arguments:s(),start:0,end:0,line:1,column:0}}}return o};return i()}getLanguage(){return this.language}getConfidenceThreshold(){return this.confidenceThreshold}}pt.SKIP_SEMANTIC_COMMANDS=new Set(["swap","morph","js","tell"]);const mt=new Set(["then","end","to","into","on","with","from","in","by","for","while","until","unless","else","catch","finally"]),yt=new Set([")","]","}",","]);function gt(t,e){return{infix:{bp:[t,t+1],handler:e??((e,n,r)=>{const s=r.parseExpr(t+1);return{type:"binaryExpression",operator:n.value,left:e,right:s,start:e.start,end:s.end??n.end,line:e.line??n.line,column:e.column??n.column}})}}}function vt(t,e){return{infix:{bp:[t+1,t],handler:(e,n,r)=>{const s=r.parseExpr(t);return{type:"binaryExpression",operator:n.value,left:e,right:s,start:e.start,end:s.end??n.end,line:e.line??n.line,column:e.column??n.column}}}}}function bt(t,e){return{prefix:{bp:t,handler:e??((e,n)=>{const r=n.parseExpr(t);return{type:"unaryExpression",operator:e.value,operand:r,argument:r,prefix:1,start:e.start,end:r.end??e.end,line:e.line,column:e.column}})}}}function wt(t){return(e,n,r)=>{const s=r.advance();if(!s||!s.value)throw Error(`Type check requires a type name after 'is ${t?"not ":""}a/an', got: <end>`);let i=1;const o=r.peek();return o&&"!"===o.value&&(r.advance(),i=0),{type:"typeCheckExpression",value:e,typeName:s.value,nullOk:i,negated:t,start:e.start,end:s.end}}}const Et=function(...t){const e=new Map;for(const n of t)for(const[t,r]of n){const n=e.get(t);e.set(t,n?{prefix:r.prefix??n.prefix,infix:r.infix??n.infix}:{...r})}return e}(new Map([["or",gt(10)],["||",gt(10)],["and",gt(20)],["&&",gt(20)],["==",gt(30)],["!=",gt(30)],["<",gt(30)],[">",gt(30)],["<=",gt(30)],[">=",gt(30)],["is",gt(30)],["matches",gt(30)],["contains",gt(30)],["starts with",gt(30)],["ends with",gt(30)],["does not start with",gt(30)],["does not end with",gt(30)],["is between",gt(30,(t,e,n)=>{const r=n.parseExpr(31),s=n.peek();if(!s||"and"!==s.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(s?.value??"<end>"));n.advance();const i=n.parseExpr(31);return{type:"betweenExpression",value:t,min:r,max:i,negated:0,start:t.start,end:i.end}})],["is not between",gt(30,(t,e,n)=>{const r=n.parseExpr(31),s=n.peek();if(!s||"and"!==s.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(s?.value??"<end>"));n.advance();const i=n.parseExpr(31);return{type:"betweenExpression",value:t,min:r,max:i,negated:1,start:t.start,end:i.end}})],["am between",gt(30,(t,e,n)=>{const r=n.parseExpr(31),s=n.peek();if(!s||"and"!==s.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(s?.value??"<end>"));n.advance();const i=n.parseExpr(31);return{type:"betweenExpression",value:t,min:r,max:i,negated:0,start:t.start,end:i.end}})],["am not between",gt(30,(t,e,n)=>{const r=n.parseExpr(31),s=n.peek();if(!s||"and"!==s.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(s?.value??"<end>"));n.advance();const i=n.parseExpr(31);return{type:"betweenExpression",value:t,min:r,max:i,negated:1,start:t.start,end:i.end}})],["ignoring case",{infix:{bp:[25,26],handler:(t,e,n)=>(t.ignoringCase=1,t)}}],["where",gt(28,(t,e,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"where",collection:t,right:r,start:t.start,end:r.end}})],["sorted by",gt(28,(t,e,n)=>{const r=n.parseExpr(29);let s="asc";const i=n.peek();if(i&&"string"==typeof i.value){const t=i.value.toLowerCase();"asc"===t||"ascending"===t?(n.advance(),s="asc"):"desc"!==t&&"descending"!==t||(n.advance(),s="desc")}return{type:"collectionExpression",operator:"sorted by",collection:t,right:r,order:s,start:t.start,end:r.end}})],["mapped to",gt(28,(t,e,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"mapped to",collection:t,right:r,start:t.start,end:r.end}})],["split by",gt(28,(t,e,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"split by",collection:t,right:r,start:t.start,end:r.end}})],["joined by",gt(28,(t,e,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"joined by",collection:t,right:r,start:t.start,end:r.end}})],["+",{...gt(40),...bt(80)}],["-",{...gt(40),...bt(80)}],["*",gt(50)],["/",gt(50)],["%",gt(50)],["mod",gt(50)],["^",vt(60)],["**",vt(60)],["as",gt(70,(t,e,n)=>{const r=()=>{const t=n.peek();!t||"a"!==t.value&&"an"!==t.value||n.advance();const e=n.parseExpr(71),r=n.peek();if(r&&":"===r.value&&e&&"identifier"===e.type){n.advance();const t=n.advance();t&&void 0!==t.value&&(e.name=`${e.name}:${t.value}`,e.end=t.end)}return e};let s=r(),i={type:"asExpression",expression:t,targetType:s,start:t.start,end:s.end??e.end,line:t.line??e.line,column:t.column??e.column};for(;n.peek()&&"|"===n.peek().value;){n.advance();const t=r();i={type:"asExpression",expression:i,targetType:t,start:i.start,end:t.end??i.end,line:i.line,column:i.column}}return i})],["not",bt(80)],["!",bt(80)],["no",bt(27)]]),new Map([["===",gt(30)],["!==",gt(30)],["is not",gt(30)],["am",gt(30)],["is in",gt(30)],["is not in",gt(30)],["precedes",gt(30)],["does not precede",gt(30)],["follows",gt(30)],["does not follow",gt(30)],["is a",gt(30,wt(0))],["is an",gt(30,wt(0))],["is not a",gt(30,wt(1))],["is not an",gt(30,wt(1))],["has",gt(30)],["have",gt(30)],["match",gt(30)],["include",gt(30)],["includes",gt(30)],["equals",gt(30)],["does not contain",gt(30)],["does not include",gt(30)],["am in",gt(30)],["am not in",gt(30)],["is really",gt(30)],["is not really",gt(30)],["is equal",gt(30)],["is not equal",gt(30)],["contain",gt(30)],["do not contain",gt(30)],["does not contains",gt(30)],["do not match",gt(30)],["does not match",gt(30)],["is equal to",gt(30)],["is not equal to",gt(30)],["is really equal to",gt(30)],["is not really equal to",gt(30)],["really equals",gt(30)],["is greater than",gt(30)],["is less than",gt(30)],["is greater than or equal to",gt(30)],["is less than or equal to",gt(30)],["in",gt(30)],["of",vt(30)],["really",gt(30)],["exists",{prefix:{bp:80,handler:(t,e)=>({type:"unaryExpression",operator:t.value,operand:e.parseExpr(80),start:t.start})},infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:0,start:t.start})}}],["does not exist",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:0,start:t.start})}}],["is empty",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:0,start:t.start})}}],["is not empty",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:0,start:t.start})}}],["some",bt(80)]]),new Map([["=",vt(5)]])),xt=new Map,kt=new Map,St=new Map,At=new Set,Nt=new Set,Ct=new Set,Tt=new Set;function Ot(t){return xt.get(t.toLowerCase())}function $t(t,e){if(0!==Nt.size)for(const n of Nt)try{n(t,e)}catch(t){void 0!==console&&console.error("[hyperfixi] globalReadHook threw:",t)}}function Rt(t,e,n){if(0!==Ct.size)for(const r of Ct)try{r(t,e,n)}catch(t){void 0!==console&&console.error("[hyperfixi] localWriteHook threw:",t)}}function Lt(t,e){if(0!==Tt.size)for(const n of Tt)try{n(t,e)}catch(t){void 0!==console&&console.error("[hyperfixi] localReadHook threw:",t)}}function It(t,e,n){if(t.globals.set(e,n),0!==At.size)for(const r of At)try{r(e,n,t)}catch(t){void 0!==console&&console.error("[hyperfixi] globalWriteHook threw:",t)}}function jt(t){return t.kind!==I.IDENTIFIER?0:E.has(t.value.toLowerCase())}function Mt(t){return t.kind!==I.IDENTIFIER?0:L.has(t.value.toLowerCase())}function Dt(t){return t.kind!==I.IDENTIFIER?0:R.has(t.value.toLowerCase())}function Pt(t){return t.kind!==I.IDENTIFIER?0:T.has(t.value.toLowerCase())}function Ft(t){return $.has(t.value.toLowerCase())}function Bt(t){return t.kind===I.IDENTIFIER}function _t(t){return t.kind===I.SELECTOR}function Vt(t){return t.kind!==I.SELECTOR?0:!t.value.startsWith("<")}function qt(t){return t.kind===I.STRING||t.kind===I.NUMBER||t.kind===I.TEMPLATE}function Ht(t){return t.kind===I.IDENTIFIER}function Ut(t){return t.kind===I.TIME}function Wt(t){return t.kind===I.SYMBOL}function zt(t){return t.kind===I.COMMENT}function Jt(t){if(t.kind!==I.IDENTIFIER)return 0;const e=t.value.toLowerCase();return!(E.has(e)||L.has(e)||R.has(e)||T.has(e))}function Zt(t){return t.kind===I.STRING}function Gt(t){return t.kind===I.NUMBER}function Xt(t){if(t.kind===I.IDENTIFIER){const e=t.value;return"true"===e||"false"===e||"null"===e||"undefined"===e}return 0}function Yt(t){return t.kind===I.TEMPLATE}function Kt(t){return t.kind===I.SELECTOR&&t.value.startsWith("<")}function Qt(t){return t.kind===I.SELECTOR&&t.value.startsWith("#")}function te(t){return t.kind===I.SELECTOR&&t.value.startsWith(".")}function ee(t){return t.kind!==I.SELECTOR?0:!t.value.startsWith("#")&&!t.value.startsWith(".")}function ne(t){if(t.kind!==I.OPERATOR)return 0;const e=t.value.toLowerCase();return!O.has(e)&&!$.has(e)}function re(t){const e=t.value.toLowerCase();return"then"===e||"and"===e||"else"===e||"end"===e||"on"===e}function se(t,e,n){return{type:"literal",value:t,raw:e,start:n.start,end:n.end,line:n.line,column:n.column}}function ie(t,e){return{type:"identifier",name:t,start:e.start,end:e.end,line:e.line,column:e.column}}function oe(t,e,n,r){return{type:"binaryExpression",operator:t,left:e,right:n,start:r.start,end:r.end,line:r.line,column:r.column}}function ae(t,e){return{type:"block",commands:t,start:e.start,end:e.end,line:e.line,column:e.column}}function ce(t,e){return{type:"string",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}function ue(t,e){return{type:"objectLiteral",properties:t,start:e.start,end:e.end,line:e.line,column:e.column}}function le(t,e){return{type:"arrayLiteral",elements:t,start:e.start,end:e.end,line:e.line,column:e.column}}function he(t,e,n){return{type:"propertyOfExpression",property:t,target:e,start:n.start,end:n.end,line:n.line,column:n.column}}function fe(t,e,n){return{type:"command",name:"__ERROR__",args:[],diagnostics:[{message:e,severity:"error",code:"parse-error",line:t.line,column:t.column,...n&&{source:n}}],start:t.start,end:t.end,line:t.line,column:t.column}}const de=[{command:"append",keywords:["to"],syntax:"append <value> [to <target>]"},{command:"make",keywords:["a","an","from","called"],syntax:"make (a|an) <type> [from <args>] [called <name>]"},{command:"send",keywords:["to"],syntax:"send <event> to <target>"},{command:"throw",keywords:[],syntax:"throw <error>"}];function pe(t,e){return t?e.some(e=>t.value===e||t.value.toLowerCase()===e):0}const me=[t,r,e,n];function ye(t,e=[]){if(t.isAtEnd())return 1;for(const e of me)if(t.check(e))return 1;for(const n of e)if(t.check(n))return 1;return t.checkIsCommand()?1:0}function ge(t,e=[]){if(!ye(t,e))return t.parseExpression()}function ve(t,e,n){return t.check(e)?(t.advance(),n.push(t.createIdentifier(e)),1):0}function be(t,e,n){for(const r of e)if(t.check(r))return t.advance(),n.push(t.createIdentifier(r)),r;return null}function we(t,e){return t.check(e)?(t.advance(),1):0}function Ee(t){const e=t.savePosition();let n;if(t.checkIdentifierLike()){const r=t.peek().value;t.advance(),t.check(":")?(t.advance(),n=r):t.restorePosition(e)}const r=t.parseExpression();return void 0!==n?{name:n,value:r}:{value:r}}class xe{constructor(t){this.args=[],this.isBlocking=0,this.name=t}static from(t){const e=new xe(t.value);return e.startPos={start:t.start??0,end:t.end??0,line:t.line??1,column:t.column??1},e}static fromIdentifier(t){const e=new xe(t.name);return void 0!==t.start&&(e.startPos={start:t.start,end:t.end??0,line:t.line??1,column:t.column??1}),e}static named(t){return new xe(t)}withArgs(...t){return this.args.push(...t),this}withBody(t){return this.body=t,this}withImplicitTarget(t){return this.implicitTarget=t,this}withModifier(t,e){return this.modifiers||(this.modifiers={}),this.modifiers[t]=e,this}withModifiers(t){return this.modifiers={...this.modifiers,...t},this}withName(t){return this.name=t,this}withOriginalCommand(t){return this.originalCmd=t,this}blocking(t=1){return this.isBlocking=t,this}startingAt(t){return this.startPos={start:t.start??0,end:t.end??0,line:t.line??1,column:t.column??1},this}endingAt(t){return this.endPos={start:t.start??this.startPos?.start??0,end:t.end,line:t.line??this.startPos?.line??1,column:t.column??this.startPos?.column??1},this}build(){const t={type:"command",name:this.name,args:this.args,isBlocking:this.isBlocking,start:this.startPos?.start??0,end:this.endPos?.end??this.startPos?.end??0,line:this.startPos?.line??1,column:this.startPos?.column??1};return this.body&&(t.body=this.body),this.implicitTarget&&(t.implicitTarget=this.implicitTarget),this.modifiers&&(t.modifiers=this.modifiers),this.originalCmd&&(t.originalCommand=this.originalCmd),t}clone(){const t=new xe(this.name);return t.args=[...this.args],t.body=this.body?[...this.body]:void 0,t.implicitTarget=this.implicitTarget,t.isBlocking=this.isBlocking,t.modifiers=this.modifiers?{...this.modifiers}:void 0,t.originalCmd=this.originalCmd,t.startPos=this.startPos?{...this.startPos}:void 0,t.endPos=this.endPos?{...this.endPos}:void 0,t}}function ke(t,e){const n=[];let r="";const s=t.peek().start||0,i=t.peek().line||1,o=t.peek().column||1;if(t.checkIdentifierLike()){for(r=t.advance().value;t.check(":")&&!t.isAtEnd();)t.advance(),r+=":",t.checkIdentifierLike()&&(r+=t.advance().value);if(t.check("(")){t.advance();const e=[];for(;!t.isAtEnd()&&!t.check(")");){const{name:n,value:r}=Ee(t);if(e.push(void 0!==n?{type:"objectLiteral",properties:[{key:{type:"identifier",name:n},value:r}],start:r.start,end:r.end,line:r.line,column:r.column}:r),t.check(","))t.advance();else if(!t.check(")"))break}t.check(")")&&t.advance(),n.push({type:"functionCall",name:r,args:e,start:s,end:t.getPosition().end,line:i,column:o})}else n.push({type:"string",value:r,start:s,end:t.getPosition().end,line:i,column:o})}const a=[...n];for(;!ye(t);){if(t.check("on")||t.check("to")){const e=t.advance().value;a.push(t.createIdentifier(e));continue}a.push(t.parsePrimary())}return xe.fromIdentifier(e).withArgs(...a).endingAt(t.getPosition()).build()}function Se(t,e){const n=[];if(t.check(b)){const e=t.advance();if(n.push({type:"identifier",name:b,start:e.start,end:e.end,line:e.line,column:e.column}),t.check(y)){const e=t.advance();n.push({type:"identifier",name:y,start:e.start,end:e.end,line:e.line,column:e.column})}}return xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function Ae(r,s){const i=[];let o=0;const a=r.savePosition();for(let e=0;500>e&&!r.isAtEnd();e++){const e=r.peek();if(e.value===t){o=1;break}if(e.value===n||e.value===g||"def"===e.value||e.value===m)break;r.advance()}r.restorePosition(a);let c=0;if(!o){const t=r.savePosition(),i=s.line,o=100;for(;!r.isAtEnd()&&o>r.current-t;){const t=r.peek(),s=t.value?.toLowerCase();if(s===g||"def"===s||s===m)break;if(s===e||s===n){t.line===i&&(c=1);break}if((r.checkIsCommand()||r.isCommand(s))&&void 0!==t.line&&t.line!==i){c=1;break}r.advance()}r.restorePosition(t)}const u=o||c;let l;if(u)l=r.parseExpression();else{const e=[],n=20;let i=0;for(;!r.isAtEnd()&&!r.checkIsCommand()&&!r.isCommand(r.peek().value)&&!r.check(t)&&n>i;){const t=r.savePosition();e.push(r.parseLogicalAnd()),r.savePosition()===t&&r.advance(),i++}if(0===e.length)throw Error("Expected condition after if/unless");l=1===e.length?e[0]:{type:"expression",tokens:e,start:e[0].start,end:e[e.length-1].end,line:s.line,column:s.column}}if(i.push(l),u){o&&r.advance();const t=[];for(;!r.isAtEnd()&&!r.check(e)&&!r.check(n)&&(r.checkIsCommand()||r.isCommand(r.peek().value));){r.advance();const e=r.parseCommand();e&&t.push(e)}if(0===t.length&&r.isAtEnd())throw Error("Expected command after 'then' in if statement - incomplete conditional");i.push(ae(t,{start:s.start,end:r.getPosition().end,line:s.line,column:s.column}));let a=0;if(r.check(e))if(r.advance(),r.check("if")){const t=r.peek();r.advance();const e=Ae(r,t);i.push(ae([e],{start:t.start,end:r.getPosition().end,line:t.line,column:t.column})),a=1}else{const t=[];for(;!r.isAtEnd()&&!r.check(n)&&(r.checkIsCommand()||r.isCommand(r.peek().value));){r.advance();const e=r.parseCommand();e&&t.push(e)}i.push(ae(t,{start:s.start,end:r.getPosition().end,line:s.line,column:s.column}))}a||r.consume(n,"Expected 'end' after if block")}else{if(!r.checkIsCommand()&&!r.isCommand(r.peek().value))throw Error("Expected command after if condition in single-line form");{r.advance();const t=r.parseCommand();i.push(ae([t],{start:s.start,end:r.getPosition().end,line:s.line,column:s.column}))}}return xe.from(s).withArgs(...i).endingAt(r.getPosition()).build()}function Ne(t,e){const n=[],r={};if(t.checkAnySelector()||t.checkContextVar()||t.match("<")){const e=t.parsePrimary();if(n.push(e),t.match("*")){if(t.checkIdentifierLike()){const e=t.advance();n.push({type:"identifier",name:"*"+e.value,start:e.start-1,end:e.end,line:e.line,column:e.column})}}else if(t.checkIdentifierLike()){const e=t.parsePrimary();n.push(e)}}else if(t.checkIdentifierLike()){const e=t.parsePrimary();n.push(e)}if(t.match("and")&&t.match("set")&&t.checkIdentifierLike()){const e=t.advance();r.set={type:"identifier",name:e.value,start:e.start,end:e.end,line:e.line,column:e.column}}const s=xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition());return Object.keys(r).length>0&&s.withModifiers(r),s.build()}function Ce(t,e){const n=[],r=ge(t,[f]);r&&n.push(r),ve(t,f,n);const s=ge(t);return s&&n.push(s),xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function Te(t,e){const n=[];if(t.check("between")){t.advance(),n.push(t.createIdentifier("between"));const i=ge(t,[r]);if(i&&"binaryExpression"===i.type&&"and"===i.operator)i.left&&n.push(i.left),n.push(t.createIdentifier("and")),i.right&&n.push(i.right);else{i&&n.push(i),ve(t,r,n);const e=ge(t,[f,m,s]);e&&n.push(e)}if(be(t,[f,m],n)){const e=ge(t);e&&n.push(e)}return xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}const i=ge(t,[f,m]);if(i&&n.push(i),be(t,[f,m],n)){const e=ge(t);e&&n.push(e)}return t.check("modal")&&(t.advance(),n.push({type:"literal",value:"modal",raw:"modal"})),xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function Oe(t,e){const r=t.parseExpression();if(!r)return t.addError("Put command requires content expression"),null;const s=t.peek();if(!s||!A.includes(s.value))return t.addError(`Expected operation keyword (${A.join(", ")}) after put expression, got: ${s?.value}`),null;let i=t.advance().value;const o=i.toLowerCase();"at start of"===o||"at the start of"===o?i=k:"at end of"===o||"at the end of"===o?i=S:"at"===i&&(t.check(w)||t.check(b)?(we(t,b),t.check(w)&&(t.advance(),t.check(p)&&(t.advance(),i=k))):t.check(n)&&(t.advance(),t.check(p)&&(t.advance(),i=S)));const a=t.parseExpression();return a?xe.fromIdentifier(e).withArgs(r,t.createIdentifier(i),a).endingAt(t.getPosition()).build():(t.addError("Put command requires target expression after operation keyword"),null)}const $e=["innerhtml","outerhtml","into","over","delete","morph","morphouter"];function Re(s,i){const o=s.savePosition();let a=null,c=[];try{a=function(t){if(!t.check(":"))return null;if(t.advance(),t.check(":")){t.advance();const e=t.advance();return{type:"identifier",name:e.value,scope:"global",start:e.start-2,end:e.end}}const e=t.advance();return{type:"identifier",name:e.value,scope:"element",start:e.start-1,end:e.end}}(s)??function(t){if(!t.check(v)&&!t.check("local"))return null;const e=t.advance(),n=t.advance();return{type:"identifier",name:n.value,scope:e.value,start:e.start,end:n.end}}(s)??function(t){if(!t.check(b))return null;const e=t.savePosition();t.advance();const n=t.parseExpression();if(!n)return t.restorePosition(e),null;if("binaryExpression"===n.type&&n.operator===p){const t=n.left,e=n.right;return he(t,e,{start:t.start??0,end:e.end??0,line:t.line??1,column:t.column??1})}return t.check(h)?n:(t.restorePosition(e),null)}(s),a||(a=s.parseExpression())}catch{s.restorePosition(o),a=null}if(!a){const i=function(s){if(s.match(":")){const t=s.advance();return{expression:{type:"identifier",name:t.value,scope:"element",start:t.start,end:t.end},tokens:[]}}const i=[];for(;!(s.isAtEnd()||s.check(h)||s.check(t)||s.check(r)||s.check(e)||s.check(n));)i.push(s.parsePrimary());if(0===i.length)return{expression:null,tokens:[]};if(i.length>=4){const t=(t,e)=>t[e];if(t(i[0],"value")===b&&t(i[2],"value")===p){const e=i[1],n=i[3];return{expression:he(ie(t(e,"value")||t(e,"name")||"",{start:e.start??0,end:e.end??0,line:e.line??1,column:e.column??1}),{type:"idSelector"===n.type?"idSelector":"cssSelector",value:t(n,"value")||t(n,"name")||"",start:n.start??0,end:n.end??0,line:n.line,column:n.column},{start:i[0].start??0,end:n.end??0,line:i[0].line??1,column:i[0].column??1}),tokens:[]}}}return 1===i.length?{expression:i[0],tokens:[]}:{expression:null,tokens:i}}(s);a=i.expression,c=i.tokens}if(!s.check(h)){const t=s.isAtEnd()?"end of input":s.peek().value;throw Error("Expected 'to' in set command, found: "+t)}s.advance();const u=s.parseExpression()??s.parsePrimary();let l;var f;s.check(m)&&(f=s.peekAt(1))&&("selector"===f.kind||f.value.startsWith("<")||Le.has(f.value))&&(s.advance(),l=ge(s));const d=[];a?d.push(a):c.length>0&&d.push(...c),d.push(s.createIdentifier(h)),u&&d.push(u);const y=xe.fromIdentifier(i).withArgs(...d);return l&&y.withModifier("on",l),y.endingAt(s.getPosition()).build()}const Le=new Set(["me","my","it","its","you","your","yourself"]),Ie=new Set(["to","the","url","of","in","new","window","top","middle","bottom","left","center","right","smoothly","instantly","back","forward"]),je=new Set(["in","then","and","else","end","otherwise","when","where","catch","finally"]);function Me(t){return t.isAtEnd()||je.has(t.peek().value)}function De(t,e){return{type:"string",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}function Pe(t){const e=t.peek();if("/"===e.value)return 1;if(t.checkIdentifierLike()){const n=t.peekAt(1);return!!n&&":"===n.value&&n.start===e.end}return 0}function Fe(t,e){const n=[];for(;!ye(t,["catch","finally"])&&(t.checkIdentifierLike()||t.checkSelector()||t.checkLiteral()||t.checkTimeExpression()||t.match("<"));)n.push(t.parsePrimary());return xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function Be(t){if(t.isAtEnd())return 1;const e=t.peek().value;return["as","with","{","then","end","else","otherwise",")"].includes(e)||ye(t)}function _e(t,e=Be){const n=t.savePosition();let r="";for(;!t.isAtEnd()&&!e(t);)r+=t.advance().value;return r&&"/"!==r?{type:"literal",value:r,raw:r,start:n,end:t.savePosition()}:(t.restorePosition(n),null)}function Ve(t){if(t.check("{"))return 0;if(!t.checkIdentifierLike())return 0;const e=t.peekAt(1);return null!==e&&":"===e.value}function qe(t){const e=[],n=t.getPosition();do{if(!t.checkIdentifierLike())break;const n=t.advance(),r={type:"identifier",name:n.value,start:n.start,end:n.end,line:n.line,column:n.column};t.consume(":","Expected ':' after property name in fetch named arguments");const s=t.parsePrimary();s&&e.push({key:r,value:s})}while(t.match(",")&&!t.isAtEnd());const r=t.getPosition();return{type:"objectLiteral",properties:e,start:n.start,end:r.end,line:n.line,column:n.column}}const He=new Set(["em","ex","cap","ch","ic","rem","lh","rlh","vw","vh","vi","vb","vmin","vmax","cm","mm","Q","pc","pt","px"]);class Ue{constructor(t,e,n){this.current=0,this.errors=[],this.warnings=[],this.prattCache=new Map,this.tokens=t,this.keywordResolver=e?.keywords,this.registryIntegration=e?.registryIntegration,e?.semanticAnalyzer&&e?.language&&(this.semanticAdapter=new pt({analyzer:e.semanticAnalyzer,language:e.language,confidenceThreshold:e.semanticConfidenceThreshold??.5})),this.originalInput=n||t.map(t=>t.value).join(" ")}resolveKeyword(t){return this.keywordResolver?this.keywordResolver.resolve(t)??t:t}addWarning(t){this.warnings.push(t)}parse(){this.prattCache.clear();const t=this.parseInternal();return this.errors.length>0&&(t.errors=[...this.errors]),t}parseInternal(){try{if(0===this.tokens.length)return this.addError("Cannot parse empty input"),{success:0,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings};if(this.check("behavior")){const t=[];for(;this.check("behavior");){this.advance();const e=this.parseBehaviorDefinition();if(e&&t.push(e),this.error)break}return this.error?{success:0,node:1===t.length?t[0]:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:1,node:1===t.length?t[0]:this.createProgramNode(t),tokens:this.tokens,warnings:this.warnings}}const t=this.peek(),e=t&&Ot(t.value)?t.value:null;if(this.check("init")||this.check("on")||this.check("def")||this.checkComment()||null!==e){const t=[];for(;!this.isAtEnd();)if(this.checkComment())this.advance();else{if(this.check("then")){const t=this.peekAt(1);if(null!==t&&("init"===t.value||"on"===t.value||"def"===t.value||void 0!==Ot(t.value))){this.advance();continue}}if(this.check("init")){this.advance();const e=this.parseTopLevelInitBlock();e&&t.push(e)}else if(this.check("on")){this.advance();const e=this.parseEventHandler();e&&t.push(e)}else{if(!this.check("def")){const e=this.peek(),n=e?Ot(e.value):void 0;if(n){const e=this.advance(),r=n(this.getContext(),e);r&&t.push(r);continue}break}{this.advance();const e=this.parseDefFeature();e&&t.push(e)}}}return this.isAtEnd()?this.error?{success:0,node:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:1,node:this.createProgramNode(t),tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:0,node:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings})}if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){const t=this.parseCommandSequence();if(t){if(!this.isAtEnd()&&this.check("on")){ut("✅ PARSER: Found event handlers after command sequence, parsing as program");const e=[t];ut(`✅ PARSER: Starting with ${e.length} statement(s) from command sequence`);let n=0;for(;!this.isAtEnd()&&this.check("on");){ut(`✅ PARSER: Parsing event handler #${n+1}, current token: ${this.peek().value}`),this.advance();const t=this.parseEventHandler();if(ut("✅ PARSER: parseEventHandler returned:",t?`type=${t.type}, event=${t.event}`:"null"),t&&(e.push(t),n++,ut(`✅ PARSER: Added event handler, now have ${e.length} statements total`)),ut(`✅ PARSER: After parsing event handler, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd=${this.isAtEnd()}, check('on')=${this.check("on")}`),!this.isAtEnd()&&!this.check("on")){if(!this.isAtEnd())return ut("⚠️ PARSER: Unexpected token after event handlers: "+this.peek().value),this.addError("Unexpected token after event handlers: "+this.peek().value),{success:0,node:this.createProgramNode(e),tokens:this.tokens,error:this.error};ut("✅ PARSER: No more event handlers, at end of input");break}}return ut(`✅ PARSER: Finished parsing, creating Program node with ${e.length} statements`),this.error?{success:0,node:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:1,node:this.createProgramNode(e),tokens:this.tokens,warnings:this.warnings}}return this.isAtEnd()?this.error?{success:0,node:t,tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:1,node:t,tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:0,node:t||this.createErrorNode(),tokens:this.tokens,error:this.error})}}const n=this.parseExpression();if(this.error)return{success:0,node:n||this.createErrorNode(),tokens:this.tokens,error:this.error};if(!this.isAtEnd()){const t=this.peek();return n&&["number","string","identifier"].includes(t.kind)?this.addError(`Unexpected token: ${t.value} (missing operator between values? expected one of +, -, *, /, etc.)`):this.addError("Unexpected token: "+t.value),{success:0,node:n||this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}return{success:1,node:n,tokens:this.tokens,warnings:this.warnings}}catch(t){return this.addError(t instanceof Error?t.message:"Unknown parsing error"),{success:0,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}}parseExpression(){return this.parseExpressionPratt(0)}parseExpressionPratt(t){const e=`${this.current}:${t}`,n=this.prattCache.get(e);if(n)return this.current=n.endPos,n.node;if(this.isAtEnd())return this.addError("Unexpected end of expression"),this.createErrorNode();const r=this.peek(),s=Ue.PRATT_TABLE.get(r.value);let i;if(s?.prefix){const t=this.advance();if(this.isAtEnd())return this.addError(`Expected expression after '${t.value}' operator`),this.createErrorNode();i=s.prefix.handler(t,this.makePrattContext())}else i=this.parseCall();for(;!this.isAtEnd();){const e=this.peek();if(60>=t){const t=this.tryParseStringPostfix(i,e);if(t){i=t;continue}}const n=Ue.PRATT_TABLE.get(e.value);if(!n?.infix){if(mt.has(e.value)||yt.has(e.value))break;break}const[r]=n.infix.bp;if(t>r)break;if("="===e.value&&this.tokens.length>this.current+1&&">"===this.tokens[this.current+1].value){if(this.advance(),this.advance(),this.addError('Arrow functions (=>) are not supported in hyperscript. Use "js ... end" blocks for JavaScript callbacks.'),!this.isAtEnd())try{this.parseExpressionPratt(0)}catch(t){ut("arrow body discarded after error:",t instanceof Error?t.message:t+"")}return this.createErrorNode()}if("+"===e.value||"-"===e.value){const t=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(t&&("+"===t.value||"-"===t.value))return this.addError(`Invalid operator combination: ${e.value}${t.value}`),i}if("*"===e.value||"/"===e.value||"%"===e.value){const t=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(t&&("*"===t.value||"/"===t.value||"%"===t.value||"+"===t.value||"-"===t.value))return this.addError("*"===e.value&&"*"===t.value?"Unexpected token: "+t.value:`Invalid operator combination: ${e.value}${t.value}`),i}const s=this.advance();if(this.isAtEnd()&&!Ue.POSTFIX_UNARY_OPERATORS.has(s.value))return this.addError(`Expected expression after '${s.value}' operator`),i;i=n.infix.handler(i,s,this.makePrattContext())}return this.prattCache.set(e,{node:i,endPos:this.current}),i}tryParseStringPostfix(t,e){const n=e.value;let r=null;if(He.has(n)?r=n:"%"===n&&(this.canStartOperand(this.tokens.length>this.current+1?this.tokens[this.current+1]:null)||(r="%")),null==r)return null;const s=this.advance();return{type:"stringPostfix",expression:t,unit:r,start:t.start,end:s.end,line:t.line,column:t.column}}canStartOperand(t){if(!t)return 0;const e=t.value;return mt.has(e)||yt.has(e)?0:"number"===t.kind||"string"===t.kind||"identifier"===t.kind||"symbol"===t.kind?1:["(","[","{","-","+","!","#",".","<","$","@"].includes(e)}makePrattContext(){const t=this;return{peek:()=>t.tokens.length>t.current?t.tokens[t.current]:void 0,advance:()=>{const e=t.tokens[t.current];return t.current++,e},parseExpr:e=>t.parseExpressionPratt(e),isStopToken:()=>{const e=t.tokens[t.current];return e?mt.has(e.value)||yt.has(e.value):1},atEnd:()=>t.current>=t.tokens.length}}parseLogicalAnd(){return this.parseExpressionPratt(11)}parseImplicitBinary(){let t=this.parseCall();for(;!(this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("and")||this.check("else")||this.check(")")||this.check("]")||this.check(","));){if("identifier"!==t.type){if("literal"===t.type&&(this.checkNumber()||this.checkIdentifier())){const e=this.peek();return this.addError(`Missing operator between '${t.raw||t.value}' and '${e.value}'`),t}break}if(this.isCommand(t.name))if(this.isCompoundCommand(t.name.toLowerCase())){if(!(this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkTimeExpression()||this.checkString()||this.checkNumber()||this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()))break;{const e=this.createCommandFromIdentifier(t);e&&(t=e)}}else if("wait"===t.name.toLowerCase()&&(this.checkTimeExpression()||this.checkNumber()||this.checkIdentifier()||this.checkContextVar()||this.check("("))){const e=this.createCommandFromIdentifier(t);e&&(t=e)}else{if(!this.checkSelector())break;{const e=this.parseCall();t=this.createBinaryExpression(" ",t,e)}}else{if(!this.checkSelector())break;{const e=this.parseCall();t=this.createBinaryExpression(" ",t,e)}}}return t}isCommand(t){return this.keywordResolver?this.keywordResolver.isCommand(t):(t=>E.has(t.toLowerCase()))(t)}isKeyword(t){return this.keywordResolver?this.keywordResolver.isKeyword(t):(t=>N.has(t.toLowerCase()))(t)}createCommandFromIdentifier(t){const e=[],n=this.resolveKeyword(t.name.toLowerCase());if(this.isCompoundCommand(n))return this.parseCompoundCommand(t);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.checkIsCommand())&&(this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()||this.checkEvent()||this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkString()||this.checkNumber()||this.checkTimeExpression()||this.match("<"));)e.push(this.parsePrimary());return{type:"command",name:t.name,args:e,isBlocking:0,...void 0!==t.start&&{start:t.start},end:this.getPosition().end,...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}}}isCompoundCommand(t){return x.has(t.toLowerCase())}parseCompoundCommand(s){return function(s,i){switch(i.name.toLowerCase()){case"put":return Oe(s,i);case"trigger":case"send":return ke(s,i);case"remove":return Ce(s,i);case"toggle":return Te(s,i);case"set":return Re(s,i);case"halt":return Se(s,i);case"measure":return Ne(s,i);case"js":return function(t,e){const r=[];if(t.match("(")){for(;!t.check(")")&&!t.isAtEnd();)t.checkIdentifierLike()&&r.push(t.advance().value),t.match(",");t.consume(")","Expected ) after js parameters")}const s=t.peek().start,i=function(t,e){const n=t.getInputSlice(e);if(!n)return e;let r=0;for(;n.length>r;){const t=n[r];if("'"!==t&&"’"!==t&&"‘"!==t)if('"'!==t)if("`"!==t)if("/"===t&&n.length>r+1&&"/"===n[r+1])for(r+=2;n.length>r&&"\n"!==n[r];)r++;else if("/"===t&&n.length>r+1&&"*"===n[r+1]){for(r+=2;n.length>r&&("*"!==n[r]||r+1>=n.length||"/"!==n[r+1]);)r++;r+=2}else{if(!("e"!==t&&"E"!==t||r+3>n.length||"end"!==n.slice(r,r+3).toLowerCase()||0!==r&&/[a-zA-Z0-9_]/.test(n[r-1])||n.length>r+3&&/[a-zA-Z0-9_]/.test(n[r+3])))return e+r;r++}else{for(r++;n.length>r&&"`"!==n[r];)"\\"===n[r]&&r++,r++;r++}else{for(r++;n.length>r&&'"'!==n[r];)"\\"===n[r]&&r++,r++;r++}else{for(r++;n.length>r&&n[r]!==t;)"\\"===n[r]&&r++,r++;r++}}return e+n.length}(t,s);for(;!t.isAtEnd()&&!t.check(n)&&t.peek().start<i;)t.advance();t.consume(n,"Expected end after js code body");const o={type:"literal",value:t.getInputSlice(s,i).trim(),start:e.start,end:t.getPosition().end},a={type:"arrayLiteral",elements:r.map(t=>({type:"literal",value:t,start:e.start,end:e.end})),start:e.start,end:t.getPosition().end};return xe.fromIdentifier(e).withArgs(o,a).endingAt(t.getPosition()).build()}(s,i);case"go":return function(t,e){const n=[];for(;!ye(t,["when","where","catch","finally"]);){const e=t.peek(),r=t.resolveKeyword(e.value).toLowerCase();if(Ie.has(r)){t.advance(),n.push(De(r,e));continue}if(Pe(t)){const r=_e(t,Me);if(r){n.push(r);continue}t.advance(),n.push(De(e.value,e));continue}if("+"===e.value||"-"===e.value){t.advance(),n.push(De(e.value,e));continue}if("number"===e.kind){t.advance();const r=t.peek();if(t.isAtEnd()||"px"!==r.value||r.start!==e.end)n.push({type:"literal",value:Number(e.value),raw:e.value,start:e.start,end:e.end,line:e.line,column:e.column});else{const r=t.advance();n.push(De(e.value+"px",{...e,end:r.end}))}continue}const s=t.current;if(n.push(t.parsePrimary()),t.current===s)break}return xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}(s,i);case"tell":return function(s,i){const o=s.parseExpression();if(!o)throw Error("tell command requires a target expression");const a=[];for(;!s.isAtEnd();){if(s.checkIsCommand()){try{s.advance();const t=s.parseCommand();if(!t)break;a.push(t)}catch{break}if(s.match(r))continue;if(s.check(t)||s.check(e)||s.check(n))break;if(s.checkIsCommand())continue;break}break}if(0===a.length)throw Error("tell command requires at least one command after the target");return xe.fromIdentifier(i).withArgs(o,...a).endingAt(s.getPosition()).build()}(s,i);case"pick":return function(t,e){const n=xe.fromIdentifier(e);we(t,b);const r=t.peek().value,s=t=>({type:"literal",value:t,start:e.start,end:e.end}),i=()=>{if(!t.match("of","from"))throw Error("pick: expected 'of' or 'from' before source expression");return t.parseExpression()};if("first"===r){t.advance();const e=t.parsePrimary(),r=i();return n.withArgs(r).withModifier("variant",s("first")).withModifier("count",e).endingAt(t.getPosition()).build()}if("last"===r){t.advance();const e=t.parsePrimary(),r=i();return n.withArgs(r).withModifier("variant",s("last")).withModifier("count",e).endingAt(t.getPosition()).build()}if("random"===r){let e;t.advance(),t.check("of")||t.check("from")||(e=t.parsePrimary());const r=i(),o=n.withArgs(r).withModifier("variant",s("random"));return e&&o.withModifier("count",e),o.endingAt(t.getPosition()).build()}if("item"===r||"items"===r||"character"===r||"characters"===r){let e,r;t.advance(),t.match("at","from"),e=t.match("start")?s("start"):t.parsePrimary();let o=0;(t.match("to")||t.match(".."))&&(t.match("end")?o=1:r=t.parsePrimary());let a="default";t.match("inclusive")?a="inclusive":t.match("exclusive")&&(a="exclusive");const c=i(),u=n.withArgs(c).withModifier("variant",s("range")).withModifier("rangeStart",e).withModifier("rangeMode",s(a));return o?u.withModifier("rangeEnd",s("end")):r&&u.withModifier("rangeEnd",r),u.endingAt(t.getPosition()).build()}if("match"===r||"matches"===r){t.advance(),t.match("of");const e=t.parsePrimary();let o;t.matchOperator("|")&&(o=t.advance().value);const a=i(),c=n.withArgs(a).withModifier("variant",s("match"===r?"match":"matches")).withModifier("regex",e);return o&&c.withModifier("flags",s(o)),c.endingAt(t.getPosition()).build()}return Fe(t,e)}(s,i);case"start":return function(t,e){if(!t.match("view"))throw Error("start: expected 'view transition' (only `start view transition ... end` is supported)");if(!t.match("transition"))throw Error("start view: expected 'transition'");const n={};if(t.match("using")){const e=t.parsePrimary();n.transitionName=e}const r=t.parseCommandListUntilEnd();return xe.fromIdentifier(e).withArgs(...r).withModifiers(n).endingAt(t.getPosition()).build()}(s,i);case"swap":case"morph":return function(t,e){const n=[];let r=null;if(!t.isAtEnd()){const e=t.peek();if(e&&e.value){const s=e.value.toLowerCase();$e.includes(s)&&(r=s,t.advance(),n.push(t.createIdentifier(r)))}}if("delete"===r){const r=t.parseExpression();return r&&n.push(r),xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}!t.isAtEnd()&&t.check(p)&&(t.advance(),n.push(t.createIdentifier("of")));const s=t.parseExpression();if(s&&n.push(s),!t.isAtEnd()&&t.check(d)){t.advance(),n.push(t.createIdentifier("with"));const e=t.parseExpression();e&&n.push(e)}return xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}(s,i);default:return Fe(s,i)}}(this.getContext(),s)}parsePutCommand(t){return Oe(this.getContext(),t)}parseSetCommand(t){return Re(this.getContext(),t)}parseHaltCommand(t){return Se(this.getContext(),t)}parseMeasureCommand(t){return Ne(this.getContext(),t)}parseTriggerCommand(t){return ke(this.getContext(),t)}parseCommandListUntilTerminator(t){const e=[],n=()=>this.check("end")||t.some(t=>this.check(t));for(ut("🔄 parseCommandListUntilTerminator: Starting (extraStops:",t.join(","),")");!this.isAtEnd()&&!n();){ut("📍 Loop iteration, current token:",this.peek().value,"kind:",this.peek().kind);let t=0;const r=this.checkIsCommand(),s=!r&&this.checkIdentifier()&&this.isCommand(this.peek().value);if(r||s){ut(r?"✅ Found COMMAND token:":"✅ Found IDENTIFIER that is a command:",this.peek().value),this.advance();const n=this.error;try{const r=this.parseCommand();this.error&&this.error!==n&&(ut("⚠️ parseCommandListUntilTerminator: Command parsing added error, restoring. Error was:",this.error.message),this.error=n),r&&(ut("✅ Parsed command:",r.name),e.push(r),t=1)}catch(t){ut("⚠️ parseCommandListUntilTerminator: Command parsing threw, restoring:",t instanceof Error?t.message:t+""),this.error=n}}else this.checkIdentifier()&&ut("❌ IDENTIFIER is not a command:",this.peek().value);if(!t){ut("❌ No command parsed, breaking. Current token:",this.peek().value);break}for(ut("📍 After parsing command, current token:",this.peek().value);!(this.isAtEnd()||n()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(","));)ut("⚠️ Skipping unexpected token:",this.peek().value),this.advance();if(this.match("then","and",","))ut("✅ Found separator, continuing");else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){ut("📍 No separator and no command, breaking. Current token:",this.peek().value);break}ut("✅ Next token is a command, continuing without separator")}}let r="end";for(const e of t)if(this.check(e)){r=e;break}return this.check("end")||t.some(t=>this.check(t))||(r=""),ut("✅ parseCommandListUntilTerminator: parsed",e.length,"commands (terminator:",r,")"),{commands:e,terminator:r}}parseCommandListUntilEnd(){const{commands:t}=this.parseCommandListUntilTerminator([]);if(ut('🔍 After loop, checking for "end". Current token:',this.peek().value),!this.check("end"))throw ut('❌ ERROR: Expected "end" but got:',this.peek().value,"at position:",this.peek().start),Error('Expected "end" to close repeat block');return ut('✅ Found "end", consuming it'),this.advance(),t}parseCommandListUntilEndOrElse(){const{commands:t,terminator:e}=this.parseCommandListUntilTerminator(["else"]),n="else"===e;if(!n){if(!this.check("end"))throw Error('Expected "end" to close repeat block');this.advance()}return{commands:t,hasElse:n}}parseRepeatBody(){const{commands:t,terminator:e}=this.parseCommandListUntilTerminator(["else","until","while"]);if("end"===e)this.advance();else if(""===e)throw Error('Expected "end", "else", "until", or "while" to close repeat block');return{commands:t,terminator:e}}parseRepeatCommand(t){return function(t,e){const n=[];let r="forever",h=null,p=null,m=null,g=null,v=null,w=null;if(t.check(s)){t.advance(),r=s;const e=t.peek();Bt(e)&&(v=e.value,t.advance()),t.check(l)&&(t.advance(),g=t.parseExpression())}else if(t.check(l))t.advance(),r=s,v="it",g=t.parseExpression();else if(t.check(i))t.advance(),r=i,m=t.parseExpression();else if(t.check(o))if(t.advance(),r=o,t.check(y)){t.advance(),r="until-event";const e=t.peek();if(ut("📍 Parsing event name, current token:",{value:e.value,kind:e.kind}),!Bt(e)&&!Dt(e))throw Error('Expected event name after "event"');if(h=e.value,t.advance(),ut("✅ Got event name:",h,"Next token:",t.peek().value),ut('🔍 Checking for "from", current token:',t.peek().value),t.check(f)){ut('✅ Found "from", advancing...'),t.advance(),ut('📍 After consuming "from", current token:',t.peek().value),we(t,b)&&ut('✅ Found "the", advancing...');const e=t.peek();ut("🔍 Before parsePrimary for event target:",{value:e.value,kind:e.kind,position:e.start}),p=t.parsePrimary(),ut("✅ After parsePrimary, eventTarget:",p)}else ut('❌ No "from" found, skipping target parsing')}else m=t.parseExpression();else t.check(a)?(t.advance(),r=a):(w=t.parseExpression(),t.check(c)&&(t.advance(),r=c));let E,x=null;if(t.check(d)){const e=t.peekAt(1);e&&e.value.toLowerCase()===u&&(t.advance(),t.advance(),x=u)}else if(t.check(u)){t.advance();const e=t.peek();Bt(e)?(x=e.value,t.advance()):x=u}let k=null,S=0;if(r===a){const e=t.parseRepeatBody();if(E=e.commands,"else"===e.terminator)t.advance(),k=t.parseCommandListUntilEnd();else if("until"===e.terminator||"while"===e.terminator){if(S=1,r=e.terminator,t.advance(),m=t.parseExpression(),!t.check("end"))throw Error('Expected "end" to close repeat block');t.advance()}}else{const e=t.parseCommandListUntilEndOrElse();E=e.commands,e.hasElse&&(t.advance(),k=t.parseCommandListUntilEnd())}n.push({type:"identifier",name:r,start:e.start,end:e.end,line:e.line,column:e.column});const A={start:e.start,end:e.end,line:e.line,column:e.column};v&&n.push(ce(v,A)),g&&n.push(g),m&&n.push(m),w&&n.push(w),h&&n.push(ce(h,A)),p&&n.push(p),x&&n.push(ce(x,A)),n.push(ae(E,{...A,end:A.end||0})),null!==k&&n.push(ae(k,{...A,end:A.end||0}));const N=xe.from(e).withArgs(...n);return S&&N.withModifier("bottomTested",{type:"literal",value:1,...A}),N.endingAt(t.getPosition()).build()}(this.getContext(),t)}parseForCommand(t){return function(t,e){const n=[];let r=null,s=null;t.check("each")&&t.advance();const i=t.peek();if(!Bt(i))throw Error('Expected variable name after "for"');if(r=i.value,t.advance(),!t.check(l))throw Error('Expected "in" after variable name in for loop');if(t.advance(),s=t.parseExpression(),!s)throw Error('Expected collection expression after "in"');let o=null;if(t.check(d)){const e=t.peekAt(1);e&&e.value.toLowerCase()===u&&(t.advance(),t.advance(),o=u)}else if(t.check(u)){t.advance();const e=t.peek();Bt(e)?(o=e.value,t.advance()):o=u}const a=t.parseCommandListUntilEnd();n.push({type:"identifier",name:"for",start:e.start,end:e.end,line:e.line,column:e.column});const c={start:e.start,end:e.end,line:e.line,column:e.column};return n.push(ce(r,c)),n.push(s),o&&n.push(ce(o,c)),n.push(ae(a,{...c,end:c.end||0})),xe.from({...e,value:"repeat"}).withArgs(...n).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseWaitCommand(t){return function(t,e){const n=[];if(t.checkTimeExpression()||t.checkLiteral()||t.checkContextVar()||t.check("(")||t.checkIdentifierLike()&&!t.check("for")&&!ye(t)){const r=t.parseExpression();return n.push(r),xe.from(e).withArgs(...n).blocking().endingAt(t.getPosition()).build()}if(t.check("for")){t.advance();const r=[];do{const e=t.peek();if(!Bt(e))throw Error('Expected event name after "for"');const n=e.value;t.advance();const s=[];if(t.check("(")){for(t.advance();!t.isAtEnd()&&!t.check(")");){const e=t.peek();if(!Bt(e))break;s.push(e.value),t.advance(),t.check(",")&&t.advance()}if(!t.check(")"))throw Error('Expected ")" after event parameters');t.advance()}if(r.push({name:n,params:s}),!t.check("or"))break;t.advance()}while(!t.isAtEnd());let s=null;t.check(f)&&(t.advance(),we(t,b),s=t.parsePrimary());const i={start:e.start,end:t.getPosition().end,line:e.line,column:e.column};n.push(le(r.map(t=>ue([{key:ie("name",i),value:se(t.name,`"${t.name}"`,i)},{key:ie("args",i),value:le(t.params.map(t=>se(t,`"${t}"`,i)),i)}],i)),i)),s&&n.push(s)}return xe.from(e).withArgs(...n).blocking().endingAt(t.getPosition()).build()}(this.getContext(),t)}parseInstallCommand(t){return function(t,e){const n=[];if(!t.checkIdentifierLike())throw Error('Expected behavior name after "install"');const r=t.advance().value,s=t.previous();if(n.push(ie(r,{start:s.start,end:s.end,line:s.line,column:s.column})),t.check("(")){t.advance();const r=[];for(;!t.isAtEnd()&&!t.check(")");)if(r.push(Ee(t)),t.check(","))t.advance();else if(!t.check(")"))break;if(!t.check(")"))throw Error('Expected ")" after behavior parameters');if(t.advance(),r.length>0){const s={start:e.start,end:t.getPosition().end,line:e.line,column:e.column};n.push(ue(r.map(t=>({key:t.name?ie(t.name,s):se("_positional","_positional",s),value:t.value})),s))}}return xe.from(e).withArgs(...n).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseTransitionCommand(t){return function(t,e){const n=[],r={};let s=null;const i=t.peek();if(Bt(i)||"*"===i.value){let e="";t.check("*")&&(e="*",t.advance());const n=function(t){if(!t.checkIdentifierLike())return"";let e=t.advance().value;for(;t.check("-")&&!t.isAtEnd();)e+="-",t.advance(),t.checkIdentifierLike()&&(e+=t.advance().value);return e}(t);n&&(e+=n,s={type:"string",value:e,start:i.start||0,end:t.getPosition().end,line:i.line,column:i.column})}if(!s)throw Error("Transition command requires a CSS property");if(n.push(s),!t.check(h))throw Error('Expected "to" keyword after property in transition command');t.advance();const o=t.parsePrimary();if(r.to=o,t.check("over")){t.advance();const e=t.parsePrimary();r.over=e}if(t.check(d)){t.advance();const e=t.parsePrimary();r.with=e}return xe.from(e).withArgs(...n).withModifiers(r).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseAddCommand(t){return function(t,e){const n=[];if(t.match("{"))n.push(t.parseCSSObjectLiteral());else{const e=ge(t,[h]);e&&n.push(e)}if(t.check(h)){t.advance();const e=ge(t);e&&n.push(e)}return xe.from(e).withArgs(...n).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseIfCommand(t){return Ae(this.getContext(),t)}parseRemoveCommand(t){return Ce(this.getContext(),t)}parseToggleCommand(t){return Te(this.getContext(),t)}parseRegularCommand(t){return Fe(this.getContext(),t)}parseCall(){let t=this.parsePrimary();for(;;)if(this.match("("))t=this.finishCall(t);else if(this.match(".")){const e=this.consumeIdentifierLike("Expected property name after '.' - malformed member access");t=this.createMemberExpression(t,this.createIdentifier(e.value),0)}else if(this.match("?.")){const e=this.consumeIdentifierLike("Expected property name after '?.' - malformed optional access"),n=this.createMemberExpression(t,this.createIdentifier(e.value),0);n.optional=1,t=n}else if(this.match("[")){const e=this.parseExpression();this.consume("]","Expected ']' after array index"),t=this.createMemberExpression(t,e,1)}else{if(!this.check("'s"))break;{let e;this.advance(),this.check("*")?(this.advance(),e="*"+this.consumeIdentifier("Expected property name after * in CSS property syntax").value):Wt(this.peek())&&this.peek().value.startsWith("@")?e=this.advance().value:this.check("[")&&this.tokens[this.current+1]?.value?.startsWith("@")?(this.advance(),e=this.advance().value,this.consume("]","Expected ']' after attribute reference")):e=this.consumeIdentifierLike("Expected property name after possessive").value,t=this.createPossessiveExpression(t,this.createIdentifier(e))}}return t}parsePrimary(){if(this.check("*")){const t=this.current;if(this.advance(),!this.isAtEnd()&&Bt(this.peek())){const t=this.advance().value;return this.createSelector("*"+t)}this.current=t}if(this.check("*")||this.check("/")||this.check("%")||this.check("mod")){const t=this.peek();return this.addError(`Binary operator '${t.value}' requires a left operand`),this.createErrorNode()}if(this.matchNumber()){const t=parseFloat(this.previous().value);return this.createLiteral(t,this.previous().value)}if(this.matchString()){const t=this.previous().value;if(2>t.length||t.startsWith('"')&&!t.endsWith('"')||t.startsWith("'")&&!t.endsWith("'"))return this.addError("Unclosed string literal - string not properly closed"),this.createErrorNode();const e=t.slice(1,-1),n=this.processEscapeSequences(e);return this.createLiteral(n,t)}if(this.matchTemplateLiteral()){const t=this.previous();return{type:"templateLiteral",value:t.value,start:t.start||0,end:t.end||0,line:t.line,column:t.column}}if(this.matchBoolean()){const t=this.previous().value;let e;switch(t){case"true":e=1;break;case"false":e=0;break;case"null":e=null;break;case"undefined":e=void 0;break;default:e="true"===t}return this.createLiteral(e,t)}if(this.matchTimeExpression()){const t=this.previous().value;return this.createLiteral(t,t)}if(this.matchQueryReference()){const t=this.previous().value,e=t.slice(1,-2).trim(),n=this.createSelector(e);return n.fromQuery=1,n.raw=t,n}if(this.matchSelector())return this.createSelector(this.previous().value);if(this.match("<"))return this.parseHyperscriptSelector();if(this.match("(")){if(this.isAtEnd())return this.addError("Expected expression inside parentheses"),this.createErrorNode();const t=this.parseExpression();return this.consume(")","Expected closing parenthesis ')' after expression - unclosed parentheses"),t}if(this.match("{"))return this.parseObjectLiteral();if(this.match("["))return this.parseAttributeOrArrayLiteral();if(this.check(":")){if(this.advance(),this.check(":")){this.advance();const t=this.advance();return{type:"identifier",name:t.value,scope:"global",start:t.start-2,end:t.end,line:t.line,column:t.column}}{const t=this.advance();return{type:"identifier",name:t.value,scope:"element",start:t.start-1,end:t.end,line:t.line,column:t.column}}}if(this.matchBasicOperator()){const t=this.previous();return this.createIdentifier(t.value)}const t=this.peek();if((!t||"end"!==t.value&&"else"!==t.value&&"then"!==t.value)&&(this.matchPredicate(Jt)||this.matchPredicate(Mt)||this.matchPredicate(Pt)||this.matchPredicate(jt)||this.matchPredicate(Dt))){const t=this.previous();if("new"===t.value)return this.parseConstructorCall();if("on"===t.value)return this.parseEventHandler();if("if"===t.value)return this.parseConditional();if("closest"===t.value||"first"===t.value||"last"===t.value||"previous"===t.value||"next"===t.value){if(this.check("(")||this.checkCssSelector()||this.checkClassSelector()||this.checkIdSelector()||this.check("<")||this.checkQueryReference())return this.parseNavigationFunction(t.value);if(this.check(".")){const e=this.current;if(this.advance(),this.checkIdentifier()){const e=this.advance().value,n=this.createSelector("."+e);return this.createCallExpression(this.createIdentifier(t.value),[n])}this.current=e}if(this.check("#")){const e=this.current;if(this.advance(),this.checkIdentifier()){const e=this.advance().value,n=this.createSelector("#"+e);return this.createCallExpression(this.createIdentifier(t.value),[n])}this.current=e}return this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||this.check("end")?this.createIdentifier(t.value):this.parseNavigationFunction(t.value)}const e=this.check(".")||this.check("?.");return"my"!==t.value||e?"its"!==t.value||e?"your"!==t.value||e?"the"===t.value?this.parseTheXofY():"values"===t.value&&this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:"values"},target:this.parsePrimary(),line:t.line,column:t.column}):this.createIdentifier(t.value):this.parseContextPropertyAccess("you"):this.parseContextPropertyAccess("it"):this.parseContextPropertyAccess("me")}if(this.match("$"))return this.parseDollarExpression();if("\\"===this.peek().value)return this.parseBlockLiteral();if(Wt(this.peek())&&this.peek().value.startsWith("@")){const t=this.advance();return{type:"attributeAccess",attributeName:t.value.substring(1),start:t.start,end:t.end,line:t.line,column:t.column}}const e=this.peek();return this.addError(`Unexpected token: ${e.value} at line ${e.line}, column ${e.column}`),this.advance(),this.createErrorNode()}parseBlockLiteral(){const t=this.peek().start;this.advance();const e=[];for(;!(this.isAtEnd()||this.check("-")&&">"===this.tokens[this.current+1]?.value);){if(!this.checkIdentifier()){this.addError("Unexpected token in block literal parameters: "+this.peek().value);break}e.push(this.advance().value),this.match(",")}return this.check("-")&&">"===this.tokens[this.current+1]?.value?(this.advance(),this.advance(),{type:"blockLiteral",parameters:e,body:this.parseExpression(),start:t,end:this.previous().end,line:this.previous().line,column:this.previous().column}):(this.addError("Expected '->' in block literal"),this.createErrorNode())}parseDollarExpression(){if(this.checkNumber()){const t=this.advance().value;return this.createLiteral(t,"$"+t)}if(this.checkIdentifier()){const t=this.advance();let e=this.createIdentifier(t.value);for(;this.match(".");){if(!this.checkIdentifier())return this.addError("Expected property name after '.' in dollar expression"),this.createErrorNode();{const t=this.advance();e=this.createMemberExpression(e,this.createIdentifier(t.value),0)}}return{type:"dollarExpression",expression:e,raw:`$${t.value}${this.previous().value||""}`,line:t.line,column:t.column-1}}return this.addError("Expected identifier or number after '$'"),this.createErrorNode()}parseHyperscriptSelector(){let t="";for(;!this.check("/")&&!this.isAtEnd();)t+=this.advance().value;return this.consume("/","Expected '/' in hyperscript selector"),this.consume(">","Expected '>' after '/' in hyperscript selector"),this.createSelector(t)}parseObjectLiteral(){const t=[],e=this.getPosition();if(this.check("}"))return this.advance(),{type:"objectLiteral",properties:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column};do{let e;if(this.check("["))this.advance(),e=this.parseExpression(),this.consume("]","Expected ']' after computed property name in object literal");else if(this.matchString()){const t=this.previous().value,n=t.slice(1,-1);e=this.createLiteral(n,t)}else{if(!this.check("-")&&!this.checkPredicate(Jt))return this.addError("Expected property name in object literal"),this.createErrorNode();{let t="",n=0;for(;this.check("-");)this.advance(),t+="-",n=1;for(this.checkPredicate(Jt)&&(t+=this.advance().value);this.check("-");)this.advance(),t+="-",n=1,this.checkPredicate(Jt)&&(t+=this.advance().value);if(""===t||"-"===t)return this.addError("Expected property name in object literal"),this.createErrorNode();e=n?this.createLiteral(t,t):this.createIdentifier(t)}}this.consume(":","Expected ':' after property name in object literal");const n=this.parseExpression();if(t.push({key:e,value:n}),!this.match(","))break;if(this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after object literal properties"),{type:"objectLiteral",properties:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseCSSObjectLiteral(){const t=this.getPosition(),e=[];do{if(this.check("}"))break;let n;if(this.matchPredicate(Jt))n=this.createIdentifier(this.previous().value);else{if(!this.matchString())return this.addError("Expected CSS property name"),this.createErrorNode();{const t=this.previous().value,e=t.slice(1,-1);n=this.createLiteral(e,t)}}if(!this.consume(":","Expected ':' after CSS property name"))return this.createErrorNode();const r=[];let s=0,i=0,o=-1,a=-1;for(;!this.isAtEnd()&&(0!==i||!this.check(";")&&!this.check("}"));){const t=this.advance();r.push(t.value),0>o&&"number"==typeof t.start&&(o=t.start),"number"==typeof t.end&&(a=t.end),"$"===t.value&&this.check("{")&&(s=1),"{"===t.value&&i++,"}"===t.value&&i--}const c=this.originalInput&&o>=0&&a>o?this.originalInput.slice(o,a):r.join(""),u=s?{type:"templateLiteral",value:c,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}:this.createLiteral(c,c);if(e.push({key:n,value:u}),this.check(";")&&this.advance(),this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after CSS object literal properties"),{type:"objectLiteral",properties:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseConstructorCall(){const t=this.previous();if(!this.checkIdentifier())return this.addError('Expected constructor name after "new"'),this.createErrorNode();const e=this.advance(),n=e.value;if(!this.check("("))return this.addError('Expected "(" after constructor name'),this.createErrorNode();this.advance();const r=[];if(!this.check(")"))do{r.push(this.parseExpression())}while(this.match(","));return this.consume(")","Expected ')' after constructor arguments"),{type:"callExpression",callee:{type:"identifier",name:n,start:e.start,end:e.end,line:e.line,column:e.column},arguments:r,isConstructor:1,start:t.start,end:this.previous().end,line:t.line,column:t.column}}parseTopLevelInitBlock(){const t=this.getPosition(),e=this.parseCommandBlock(["end"]);return this.consume("end","Expected 'end' after init block"),{type:"initBlock",commands:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseDefFeature(){const t=this.getPosition();let e="";if(!this.checkIdentifier())return this.addError("Expected function name after 'def'"),{type:"def",name:"",params:[],body:[],start:t.start,end:this.getPosition().end,line:t.line,column:t.column};for(e=this.advance().value;this.check(".");)this.advance(),this.checkIdentifier()&&(e+="."+this.advance().value);const n=[];if(this.check("(")){if(this.advance(),!this.check(")"))for(this.checkIdentifier()&&n.push(this.advance().value);this.check(",");)this.advance(),this.checkIdentifier()&&n.push(this.advance().value);this.consume(")","Expected ')' after parameter list")}const r=this.parseCommandBlock(["end","catch","finally"]);let s,i,o;return this.check("catch")&&(this.advance(),this.checkIdentifier()&&(s=this.advance().value),i=this.parseCommandBlock(["end","finally"])),this.check("finally")&&(this.advance(),o=this.parseCommandBlock(["end"])),this.consume("end","Expected 'end' after function definition"),{type:"def",name:e,params:n,body:r,...void 0!==s&&{errorSymbol:s},...void 0!==i&&{errorHandler:i},...void 0!==o&&{finallyHandler:o},start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseEventNameWithNamespace(t){let e;e=this.checkEvent()||this.checkIdentifier()||this.checkIsCommand()||this.checkIdentifierLike()?this.advance():this.consumeEvent(t);let n=e.value;return this.check(":")&&(this.advance(),n=`${n}:${this.advance().value}`),n}callExprToCommandNode(t,e){return{type:"command",name:t.callee.name,args:t.arguments,isBlocking:0,...void 0!==e.start&&{start:e.start},...void 0!==e.end&&{end:e.end},...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}}}createPseudoCommandNode(t,e,n,r,s){return{type:"command",name:"pseudo-command",args:[{type:"objectLiteral",properties:[{key:{type:"identifier",name:"methodName"},value:{type:"literal",value:t,raw:`"${t}"`}},{key:{type:"identifier",name:"methodArgs"},value:{type:"literal",value:e.arguments,raw:JSON.stringify(e.arguments)}},...n?[{key:{type:"identifier",name:"preposition"},value:{type:"literal",value:n,raw:`"${n}"`}}]:[],{key:{type:"identifier",name:"targetExpression"},value:r}]}],isBlocking:0,...void 0!==s.start&&{start:s.start},...void 0!==s.end&&{end:s.end},...void 0!==s.line&&{line:s.line},...void 0!==s.column&&{column:s.column}}}tryParsePseudoCommand(t,e){const n=t.callee.name,r=this.peek();if(!(Ue.PSEUDO_COMMAND_PREPOSITIONS.includes(r.value.toLowerCase())||Jt(r)&&!this.isCommand(r.value)||Pt(r)))return{node:this.callExprToCommandNode(t,e),isPseudo:0,targetFailed:0};let s,i;this.isCommand(n)&&this.addWarning({type:"command-shadow",message:`Method '${n}' shadows hyperscript command`,suggestions:[`Rename method to avoid confusion (e.g., '${n}Fn', 'my${n.charAt(0).toUpperCase()+n.slice(1)}')`,`Use 'call' command instead: call ${n}(...)`,"This works but may cause ambiguity"],severity:"warning",code:"PSEUDO_CMD_SHADOW",...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}}),Ue.PSEUDO_COMMAND_PREPOSITIONS.includes(this.peek().value.toLowerCase())&&(s=this.advance().value.toLowerCase());try{i=this.parseExpression()}catch{return{node:this.callExprToCommandNode(t,e),isPseudo:0,targetFailed:1}}return{node:this.createPseudoCommandNode(n,t,s,i,e),isPseudo:1,targetFailed:0}}parseCommandWithErrorRecovery(){this.advance();const t=this.error;try{const e=this.parseCommand();return this.error&&this.error!==t&&(ut("⚠️ Command parsing added error, restoring error state. Error was:",this.error.message),this.error=t),e}catch(e){return ut("⚠️ Command parsing threw exception, restoring error state:",e instanceof Error?e.message:e+""),this.error=t,null}}parseTemporalKeywordModifiers(t){if(!this.check("debounced")&&!this.check("throttled"))return;const e=this.advance().value.toLowerCase(),n="debounced"===e?"debounce":"throttle";if(this.match("at"))if(this.checkTimeExpression()){const s=this.advance(),i=(r=s.value).endsWith("ms")?parseInt(r,10):r.endsWith("seconds")||r.endsWith("s")?1e3*parseFloat(r):r.endsWith("minutes")?6e4*parseFloat(r):r.endsWith("hours")?36e5*parseFloat(r):r.endsWith("days")?864e5*parseFloat(r):parseInt(r,10);t[n]=i,ut(`🔧 parseEventHandler: Parsed '${e} at ${s.value}' (${i}ms)`)}else if(this.matchNumber()){const r=parseInt(this.previous().value,10);t[n]=r,ut(`🔧 parseEventHandler: Parsed '${e} at ${r}'`)}else this.addError(`Expected time expression after '${e} at', got: ${this.peek().value}`);else this.addError(`Expected 'at' after '${e}'`);var r}parseEventHandler(){ut("🔧 parseEventHandler: ENTRY - parsing event handler");const t=[];let e=0;if(this.check("first")&&!this.checkIsCommand()&&this.tokens.length>this.current+1){const t=this.tokens[this.current+1],n=t?.value?.toLowerCase();n&&"of"!==n&&"in"!==n&&"from"!==n&&(this.advance(),e=1,ut("🔧 parseEventHandler: Parsed 'first' as .once alias"))}const n=this.parseEventNameWithNamespace("Expected event name after 'on'");for(t.push(n),ut("🔧 parseEventHandler: Parsed first event name: "+n);this.check("or");){this.advance(),ut("🔧 parseEventHandler: Found 'or', parsing additional event name");const e=this.parseEventNameWithNamespace("Expected event name after 'or'");t.push(e),ut("🔧 parseEventHandler: Parsed additional event name: "+e)}let r;if(ut("🔧 parseEventHandler: Total events parsed: "+t.join(", ")),this.registryIntegration){const e=t[0];if(this.registryIntegration.hasEventSource(e)){const t=this.registryIntegration.getEventSource(e);r=t?.name,ut(`🔧 parseEventHandler: Detected custom event source '${r}' for event '${e}'`)}}const s=[];if(this.match("(")){if(!this.check(")"))do{const t=this.advance();s.push(t.value)}while(this.match(","));this.consume(")","Expected ')' after event parameters"),ut("🔧 parseEventHandler: Parsed event parameters: "+s.join(", "))}const i={};for(;this.check(".");){this.advance();const t=this.advance().value.toLowerCase();if("once"===t)i.once=1,ut("🔧 parseEventHandler: Parsed modifier '.once'");else if("prevent"===t)i.prevent=1,ut("🔧 parseEventHandler: Parsed modifier '.prevent'");else if("stop"===t)i.stop=1,ut("🔧 parseEventHandler: Parsed modifier '.stop'");else if("debounce"===t||"throttle"===t){if(!this.check("("))throw Error(`Expected '(' after '.${t}'`);{this.advance();const e=this.advance(),n=parseInt(e.value,10);if(isNaN(n))throw Error(`Expected number for ${t} delay, got: ${e.value}`);"debounce"===t?(i.debounce=n,ut(`🔧 parseEventHandler: Parsed modifier '.debounce(${n})'`)):(i.throttle=n,ut(`🔧 parseEventHandler: Parsed modifier '.throttle(${n})'`)),this.consume(")",`Expected ')' after ${t} delay`)}}else ut(`🔧 parseEventHandler: Warning - unknown modifier '.${t}'`)}let o,a,c,u;if(this.parseTemporalKeywordModifiers(i),e&&(i.once=1),Object.keys(i).length>0&&ut("🔧 parseEventHandler: Parsed modifiers:",i),this.match("[")&&(o=this.parseExpression(),this.consume("]","Expected ']' after event condition")),this.match("from")){const t=this.advance();a=t.value,ut(`🔧 parseEventHandler: Parsed 'from' target: ${a} (kind: ${t.kind})`),this.parseTemporalKeywordModifiers(i)}if(this.match("of")){const t=this.advance();c=t.value.startsWith("@")?t.value.substring(1):t.value,ut("🔧 parseEventHandler: Parsed attribute name: "+c)}this.match("in")&&(ut("🔧 parseEventHandler: Found 'in' keyword, parsing watch target"),u=this.parseExpression(),ut("🔧 parseEventHandler: Parsed watch target expression"));const l=[];for(ut(`✅ parseEventHandler: About to parse commands, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd: ${this.isAtEnd()}`);!this.isAtEnd();){if(ut(`✅ parseEventHandler: Loop iteration, current token: ${this.peek().value}, kind: ${this.peek().kind}`),this.check("on")){ut("✅ parseEventHandler: Stopping command parsing, found next event handler 'on'");break}if(this.checkComment())ut("✅ parseEventHandler: Skipping comment token: "+this.peek().value),this.advance();else{if(this.check("end")){ut("✅ parseEventHandler: Stopping command parsing, found 'end' keyword"),this.advance();break}if(this.checkIsCommand()){const t="("===this.tokens[this.current+1]?.value,e=this.peek().value.toLowerCase();if(t&&"js"!==e&&"tell"!==e){let t;const e=this.error;try{t=this.parseExpression()}catch(t){this.error=e,this.advance();const n=this.parseCommand();l.push(n);continue}if(t&&"callExpression"===t.type){const e=this.tryParsePseudoCommand(t,t);if(l.push(e.node),e.isPseudo||e.targetFailed)continue}}else{const t=this.parseCommandWithErrorRecovery();t&&(l.push(t),ut("✅ parseEventHandler: Parsed command, next token: "+(this.isAtEnd()?"END":this.peek().value)))}}else{if(!this.checkIdentifier())break;{const t=this.peek();if(this.isCommand(t.value)){const t=this.parseCommandWithErrorRecovery();t&&l.push(t)}else{let t;const e=this.error;try{t=this.parseExpression()}catch(t){ut("⚠️ Expression parsing error, restoring error state:",t instanceof Error?t.message:t+""),this.error=e;break}if(t&&"callExpression"===t.type){const e=this.tryParsePseudoCommand(t,t);if(l.push(e.node),e.targetFailed)continue}else{if(!t||"binaryExpression"!==t.type||" "!==t.operator)break;{const e=t;if(!e.left||"identifier"!==e.left.type||!this.isCommand(e.left.name))break;{const n={type:"command",name:e.left.name,args:[e.right],isBlocking:0,...void 0!==t.start&&{start:t.start},...void 0!==t.end&&{end:t.end},...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}};l.push(n)}}}}}}for(;!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(",")||this.check("on"));)this.advance();if(!this.match("then","and",",")&&!this.checkIsCommand()&&!this.isCommand(this.peek().value))break}}const h=this.getPosition(),f={type:"eventHandler",event:1===t.length?t[0]:t.join("|"),events:t,commands:l,...s.length>0&&{args:s},...o&&{condition:o},...a&&{target:a},...c&&{attributeName:c},...u&&{watchTarget:u},...r&&{customEventSource:r},...Object.keys(i).length>0&&{modifiers:i},start:h.start,end:h.end,line:h.line,column:h.column};return ut(`🔧 parseEventHandler: Created node with events: ${t.join(", ")}, attributeName: ${c||"none"}, watchTarget: ${u?"yes":"none"}`),f}parseBehaviorDefinition(){const t=this.getPosition(),e=this.consumeIdentifier("Expected behavior name after 'behavior' keyword").value;/^[A-Z]/.test(e)||this.addError(`Behavior name must start with uppercase letter (got "${e}")`);const n=[];if(this.match("(")){if(!this.check(")"))do{const t=this.consumeIdentifierLike("Expected parameter name");n.push(t.value)}while(this.match(","));this.consume(")","Expected ')' after behavior parameters")}const r=new Set(n),s=[];let i;for(;!this.isAtEnd()&&!this.check("end");)if(this.match("on")){const t=this.getPosition(),e=this.parseEventNameWithNamespace("Expected event name after 'on'"),n=[];if(this.check("(")){for(this.advance();!this.isAtEnd()&&!this.check(")");){const t=this.peek();Jt(t)?(n.push(t.value),this.advance(),this.check(",")&&this.advance()):this.advance()}this.check(")")&&this.advance()}let i;if(this.check("from")){this.advance();const t=[];if(this.check("the")&&this.advance(),!this.isAtEnd()){const e=this.peek(),n=r.has(e.value);this.checkIsCommand()&&!n||(t.push(e.value),i=e.value,this.advance())}}const o={type:"eventHandler",event:e,commands:this.parseCommandListUntilEnd(),...void 0!==i&&{target:i},...n.length>0&&{args:n},start:t.start,end:this.getPosition().end,line:t.line,column:t.column};s.push(o)}else{if(!this.match("init")){this.addError("Unexpected token in behavior body: "+this.peek().value);break}i={type:"initBlock",commands:this.parseCommandBlock(["end"]),start:t.start,end:this.getPosition().end,line:t.line,column:t.column},this.consume("end","Expected 'end' after init block")}return this.consume("end","Expected 'end' to close behavior definition"),{type:"behavior",name:e,parameters:n,eventHandlers:s,...void 0!==i?{initBlock:i}:{},start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseCommandSequence(){const t=[];for(;!this.isAtEnd();){if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){this.advance();const e=this.error,n=this.parseCommand();for(this.error&&this.error!==e&&(this.error.message.includes("Expected closing parenthesis")||this.error.message.includes("Expected ')'")||this.error.message.includes("unclosed parenthes")||this.error.message.includes("Unclosed parenthes")||(ut("⚠️ parseCommandSequence: Command parsing added non-critical error, restoring error state. Error was:",this.error.message),this.error=e)),t.push(n);!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("on"));)ut("⚠️ parseCommandSequence: Skipping unexpected token:",this.peek().value),this.advance();if(this.check("on")){ut('✅ parseCommandSequence: Found "on" token, stopping command sequence to allow event handler parsing');break}if(this.match("then"))continue;if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value))continue;break}{const e=this.peek(),n=this.getPosition(),r="Expected command, got: "+e.value;this.addError(r);const s=fe(n,r,e.value);if(t.push(s),this.synchronizeToCommandBoundary(),this.isAtEnd())break;if(this.match("then"))continue;if(this.check("end")||this.check("on"))break;if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value))continue;break}}return 1===t.length?t[0]:function(t){return{type:"CommandSequence",commands:t,start:t[0]?.start||0,end:t[t.length-1]?.end||0,line:t[0]?.line||1,column:t[0]?.column||1}}(t)}getMultiWordPattern(t){return function(t){return de.find(e=>e.command===t.toLowerCase())||null}(t)}isTokenKeyword(t,e){return pe(t,e)}parseMultiWordCommand(t,e){return function(t,e,n){const r=t.getMultiWordPattern(n);if(!r)return null;const s=[],i={};for(;!ye(t,["catch","finally",...r.keywords])&&!pe(t.peek(),r.keywords);){const e=t.parsePrimary();if(!e)break;if(s.push(e),!t.match(",")&&pe(t.peek(),r.keywords))break}for(;!t.isAtEnd()&&pe(t.peek(),r.keywords);){const e=t.advance().value,n=t.parseExpression();if(n&&(i[e]=n),!pe(t.peek(),r.keywords))break}const o=xe.from(e).withArgs(...s).endingAt(t.getPosition());return Object.keys(i).length>0&&o.withModifiers(i),o.build()}(this.getContext(),t,e)}parseCommandBlock(t){const e=[];for(;!this.isAtEnd()&&!t.some(t=>this.check(t));)if(this.checkComment())this.advance();else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value))break;{this.advance();const t=this.parseCommand();e.push(t)}}return e}trySemanticParse(t){if(!this.semanticAdapter||!this.semanticAdapter.isAvailable())return null;try{const e=this.semanticAdapter.trySemanticParse(t);return e.success&&e.node?(ut(`[Semantic] Successfully parsed with confidence ${e.confidence}:`,e.node.name),e.node):(ut(`[Semantic] Low confidence (${e.confidence}), falling back to traditional parser`),null)}catch(t){return ut("[Semantic] Error during semantic parse:",t),null}}getRemainingInput(){if(!this.originalInput)return this.tokens.slice(this.current>0?this.current-1:0).map(t=>t.value).join(" ");const t=this.current>0?this.tokens[this.current-1]:this.tokens[0];return t&&void 0!==t.start?this.originalInput.slice(t.start):this.originalInput}skipToCommandBoundary(){const t=["then","and","else","end"];for(;!this.isAtEnd();){const e=this.peek(),n=e.value.toLowerCase();if(t.includes(n))break;if(jt(e))break;this.advance()}}parseCommand(){const t=this.parseCommandCore();if(t&&"command"===t.type&&!t.body&&(this.check("when")||this.check("where"))){const e=this.peek().value.toLowerCase();this.advance();const n=this.parseExpression();n&&(t.modifiers={...t.modifiers??{},[e]:n})}return t}parseCommandCore(){const t=this.previous();let e=t.value;if(this.semanticAdapter&&!["install","wait","repeat","for","set","put","increment","decrement","add","append","toggle","if","unless","make","measure","trigger","halt","remove","exit","return","closest","js","tell","fetch"].includes(e.toLowerCase())){const t=this.getRemainingInput(),e=this.trySemanticParse(t);if(e)return this.skipToCommandBoundary(),e}if("beep"===e&&this.check("!")&&(this.advance(),e="beep!"),"fetch"===e)return function(t,e){const n={};let r=null;if(!t.isAtEnd()&&t.check("/")&&(r=_e(t)),r||(r=t.parsePrimary()),!r)return t.addError("fetch requires a URL"),xe.from(e).endingAt(t.getPosition()).build();!t.isAtEnd()&&t.check("{")&&(n.with=t.parsePrimary());for(let e=0;3>e&&!t.isAtEnd();e++)if(!t.check("as")||n.as){if(!t.check("with")||n.with){if(t.check("do")&&!n.doNotThrow){const e=t.peekAt(1),r=t.peekAt(2);if("not"===e?.value&&"throw"===r?.value){const e=t.advance();t.advance();const r=t.advance();n.doNotThrow={type:"literal",value:1,start:e.start,end:r.end,line:e.line,column:e.column};continue}}break}t.advance(),n.with=Ve(t)?qe(t):t.parsePrimary()}else t.advance(),t.isAtEnd()||we(t,"a")||we(t,"an"),n.as=t.parsePrimary();const s=xe.from(e).withArgs(r).endingAt(t.getPosition());return Object.keys(n).length>0&&s.withModifiers(n),s.build()}(this.getContext(),t);const n=this.parseMultiWordCommand(t,e);if(n)return n;const r=e.toLowerCase();if("repeat"===r)return this.parseRepeatCommand(t);if("for"===r)return this.parseForCommand(t);if("if"===r||"unless"===r)return this.parseIfCommand(t);if("wait"===r)return this.parseWaitCommand(t);if("install"===r)return this.parseInstallCommand(t);if("transition"===r)return this.parseTransitionCommand(t);if("add"===r)return this.parseAddCommand(t);if(this.isCompoundCommand(r))return this.parseCompoundCommand({type:"identifier",name:r,start:t.start||0,end:t.end||0,line:t.line,column:t.column})||function(t,e){return{type:"command",name:t,args:[],partial:1,start:e.start,end:e.end,line:e.line,column:e.column}}(r,this.getPosition());const s=[];if(("increment"===e||"decrement"===e)&&!this.isAtEnd())return function(t,e){const n=e.value,r="increment"===n?"+":"-";let s=0;t.check(v)&&(s=1,t.advance());const i=t.parseExpression();if(!i)throw Error("Expected variable or expression after "+n);let o;if(t.check("by")){t.advance();const e=t.parseExpression();if(!e)throw Error(`Expected amount after 'by' in ${n} command`);o=e}else o=se(1,"1",{start:e.start,end:t.previous().end,line:e.line,column:e.column});let a=i;s&&"identifier"===i.type&&(a={...i,scope:"global"});const c={start:e.start,end:t.previous().end,line:e.line,column:e.column},u=oe(r,i,o,c);u.coerceNumeric=1;const l=[a,ie(h,c),u];return xe.from(e).withName("set").withArgs(...l).withOriginalCommand(n).endingAt({end:t.previous().end}).build()}(this.getContext(),t);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.check("end")||this.checkIsCommand());){const t=this.parseExpression();if(s.push(t||this.parsePrimary()),this.match(","))continue;const e=["into","from","to","with","by","at","before","after","over"];if(e.some(t=>this.check(t)))continue;const n=s[s.length-1];if(!n||"identifier"!==n.type&&"keyword"!==n.type||!e.includes(n.name??n.value))break}const i=this.getPosition();return{type:"command",name:e,args:s,isBlocking:0,start:i.start,end:i.end,line:i.line,column:i.column}}parseConditional(){const t=this.parseExpression();this.consume("then","Expected 'then' after if condition");const e=this.parseConditionalBranch();let n;this.match("else")&&(n=this.parseConditionalBranch());const r=this.getPosition();return{type:"conditionalExpression",test:t,consequent:e,alternate:n,start:r.start,end:r.end,line:r.line,column:r.column}}parseConditionalBranch(){if(this.checkIsCommand()){const t=this.advance(),e=this.createIdentifier(t.value);return this.createCommandFromIdentifier(e)||e}if(this.checkIdentifier()||this.checkKeyword()){const t=this.peek();if(this.isCommand(t.value)){const t=this.advance(),e=this.createIdentifier(t.value);return this.createCommandFromIdentifier(e)||e}}return this.parseExpression()}parseNavigationFunction(t){const e=[];if(this.match("of"))e.push(this.parseExpression());else{if(this.check("("))return this.finishCall(this.createIdentifier(t));this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||e.push(this.parsePrimary())}const n=this.createCallExpression(this.createIdentifier(t),e);if("next"===t||"previous"===t){const t=this.parseRelativePositionalModifiers();t&&(n.relativePositional=t)}return n}parseRelativePositionalModifiers(){if(!(this.check("from")||this.check("within")||this.check("in")||this.check("with")))return null;let t,e,n,r=0,s=0;return this.match("from")&&(t=this.parseRelativePositionalOperand()),this.match("in")?(r=1,n=this.parseRelativePositionalOperand()):this.match("within")&&(e=this.parseRelativePositionalOperand()),this.match("with")&&(this.match("wrapping"),s=1),{from:t,within:e,inElt:n,inSearch:r,wrapping:s}}parseRelativePositionalOperand(){return this.match("the"),this.parsePrimary()}parseTheXofY(){if(!this.checkIdentifier())return this.createIdentifier("the");const t=this.peek(),e=t.value;return["first","last","next","previous","random","closest"].includes(e)?(this.advance(),this.parseNavigationFunction(e)):(this.advance(),this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:e},target:this.parseCall(),line:t.line,column:t.column}):this.createIdentifier(e))}parseContextPropertyAccess(t){if(this.match("*")){let e="";if(!this.checkIdentifier())return this.addError("Expected property name after 'my *'"),this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(""),0);for(e=this.advance().value;this.check("-")&&!this.isAtEnd();){if(e+="-",this.advance(),!this.checkIdentifier()){this.addError("Expected identifier after hyphen in CSS property name");break}e+=this.advance().value}const n="*"+e;return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(n),0)}{if(this.check("[")&&this.tokens[this.current+1]?.value?.startsWith("@")){this.advance();const e=this.advance();return this.consume("]","Expected ']' after attribute reference"),this.createMemberExpression(this.createIdentifier(t),{type:"attributeAccess",attributeName:e.value.substring(1),start:e.start,end:e.end,line:e.line,column:e.column},1)}if(Wt(this.peek())&&this.peek().value.startsWith("@")){const e=this.advance();return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(e.value),0)}const e=this.consumeIdentifierLike(`Expected property name after '${{me:"my",it:"its",you:"your"}[t]}'`);return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(e.value),0)}}parseMyPropertyAccess(){return this.parseContextPropertyAccess("me")}finishCall(t){const e=[];if(!this.check(")"))do{if(this.check(","))return this.addError("Unexpected token in function arguments"),this.createCallExpression(t,[this.createErrorNode()]);e.push(this.parseExpression())}while(this.match(","));if(!this.check(")")&&"identifier"===t.type){const e=t.name;C.has(e.toLowerCase())&&ut(`💡 Tip: CSS functions like ${e}() should be quoted for clean parsing. Use '${e}(...)' or \`${e}(...)\` instead.`)}return this.consume(")","Expected ')' after arguments"),this.createCallExpression(t,e)}createLiteral(t,e){return se(t,e,this.getPosition())}createIdentifier(t){return ie(t,this.getPosition())}createBinaryExpression(t,e,n){return oe(t,e,n,this.getPosition())}createUnaryExpression(t,e,n){return function(t,e,n,r){return{type:"unaryExpression",operator:t,argument:e,prefix:n,start:r.start,end:r.end,line:r.line,column:r.column}}(t,e,n,this.getPosition())}createCallExpression(t,e){return function(t,e,n){return{type:"callExpression",callee:t,arguments:e,start:n.start,end:n.end,line:n.line,column:n.column}}(t,e,this.getPosition())}createMemberExpression(t,e,n){return function(t,e,n,r){return{type:"memberExpression",object:t,property:e,computed:n,start:r.start,end:r.end,line:r.line,column:r.column}}(t,e,n,this.getPosition())}createSelector(t){return function(t,e){return{type:"selector",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}(t,this.getPosition())}createPossessiveExpression(t,e){return function(t,e,n){return{type:"possessiveExpression",object:t,property:e,start:n.start,end:n.end,line:n.line,column:n.column}}(t,e,this.getPosition())}createErrorNode(){return{type:"identifier",name:"__ERROR__",start:(t=this.getPosition()).start,end:t.end,line:t.line,column:t.column};var t}processEscapeSequences(t){return t.replace(/\\(.)/g,(t,e)=>{switch(e){case"n":return"\n";case"t":return"\t";case"r":return"\r";case"b":return"\b";case"f":return"\f";case"v":return"\v";case"0":return"\0";case"\\":return"\\";case'"':return'"';case"'":return"'";default:return e}})}createProgramNode(t){return function(t){if(ut(`✅ createProgramNode: Called with ${t.length} statements`),0===t.length)return ut("✅ createProgramNode: Returning error node (0 statements)"),{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===t.length)return ut(`✅ createProgramNode: Returning single statement (type=${t[0].type})`),t[0];const e={type:"Program",statements:t,start:t[0]?.start||0,end:t[t.length-1]?.end||0,line:t[0]?.line||1,column:t[0]?.column||1};return ut(`✅ createProgramNode: Returning Program node with ${t.length} statements, type=${e.type}`),e}(t)}match(...t){for(const e of t)if(this.check(e))return this.advance(),1;return 0}matchOperator(t){if(this.isAtEnd())return 0;const e=this.peek();return ne(e)&&e.value===t?(this.advance(),1):0}check(t){if(this.isAtEnd())return 0;const e=this.peek().value;return this.resolveKeyword(e)===t}checkPredicate(t){return this.isAtEnd()?0:t(this.peek())}matchPredicate(t){return this.checkPredicate(t)?(this.advance(),1):0}checkSelector(){return this.checkPredicate(Vt)}matchSelector(){return this.matchPredicate(Vt)}checkAnySelector(){return this.checkPredicate(_t)}checkLiteral(){return this.checkPredicate(qt)}checkIdentifierLike(){return this.checkPredicate(Bt)}checkIsCommand(){return this.checkPredicate(jt)}checkCommandTerminator(){return this.checkPredicate(re)}checkReference(){return this.checkPredicate(Ht)}checkTimeExpression(){return this.checkPredicate(Ut)}checkEvent(){return this.checkPredicate(Dt)}checkContextVar(){return this.checkPredicate(Pt)}checkComment(){return this.checkPredicate(zt)}checkIdentifier(){return this.checkPredicate(Jt)}checkKeyword(){return this.checkPredicate(Mt)}checkString(){return this.checkPredicate(Zt)}matchString(){return this.matchPredicate(Zt)}checkNumber(){return this.checkPredicate(Gt)}matchNumber(){return this.matchPredicate(Gt)}checkBoolean(){return this.checkPredicate(Xt)}matchBoolean(){return this.matchPredicate(Xt)}checkTemplateLiteral(){return this.checkPredicate(Yt)}matchTemplateLiteral(){return this.matchPredicate(Yt)}checkQueryReference(){return this.checkPredicate(Kt)}matchQueryReference(){return this.matchPredicate(Kt)}checkIdSelector(){return this.checkPredicate(Qt)}checkClassSelector(){return this.checkPredicate(te)}checkCssSelector(){return this.checkPredicate(ee)}checkBasicOperator(){return this.checkPredicate(ne)}matchBasicOperator(){return this.matchPredicate(ne)}matchTimeExpression(){return this.matchPredicate(Ut)}matchIdentifierLike(){return this.matchPredicate(Bt)}matchComparisonOperator(){return this.matchPredicate(Ft)}consumePredicate(t,e){return this.checkPredicate(t)?this.advance():(this.addError(e),this.peek())}consumeIdentifier(t){return this.consumePredicate(Jt,t)}consumeIdentifierLike(t){return this.consumePredicate(Bt,t)}consumeEvent(t){return this.consumePredicate(Dt,t)}advance(){return this.isAtEnd()||this.current++,this.previous()}isAtEnd(){return this.current>=this.tokens.length}peek(){return this.isAtEnd()?{kind:"unknown",value:"",start:0,end:0,line:1,column:1}:this.tokens[this.current]}peekAt(t){const e=this.current+t;return e>=0&&this.tokens.length>e?this.tokens[e]:null}previous(){return this.tokens[this.current-1]}consume(t,e){return this.check(t)?this.advance():(this.addError(e),this.peek())}addError(t){const e=this.peek();let n=e.start||0,r=e.line||1,s=e.column||1;if(t.includes("property name after '.'")){const t=this.current>0?this.previous():e;n=t.end||t.start||0,r=t.line||1,s=t.column||1}if(t.includes("parenthes")){const t=this.current>0?this.previous():e;n=t.end||t.start||0,r=t.line||1,s=t.column||1,0===n&&this.current>0&&(n=this.current)}if(t.includes("Expected expression after")){const t=this.current>0?this.previous():e;n=t.start||0,r=t.line||1,s=t.column||1,0===n&&(n=Math.max(1,this.current-1))}if(t.includes("Missing operand")){let t=e;for(let e=this.current-1;e>=0;e--){const n=this.tokens[e];if(n&&("+"===n.value||"-"===n.value)){t=n;break}}n=t.start||0,r=t.line||1,s=t.column||1}this.error={message:t,line:Math.max(1,r),column:Math.max(1,s),position:Math.max(0,n)},this.errors.push(this.error)}synchronizeToCommandBoundary(){for(;!this.isAtEnd();){const t=this.peek();if("then"===t.value||"end"===t.value||"on"===t.value)return;if(this.checkIsCommand()||this.isCommand(t.value)&&!this.isKeyword(t.value))return;ut("⚠️ synchronize: Skipping token:",t.value),this.advance()}}parseAttributeOrArrayLiteral(){const t=this.previous().start,e=this.previous().line,n=this.previous().column;if(!this.isAtEnd()&&this.peek().value.startsWith("@")){const r=[];for(;!this.check("]")&&!this.isAtEnd();){const t=this.advance();r.push(t.value)}this.consume("]","Expected ']' after attribute literal");const s=r.join("");if(!s.includes("="))return{type:"attributeAccess",attributeName:s.replace(/^@/,""),start:t,end:this.previous().end,line:e,column:n};const i="["+s+"]";return{type:"literal",value:i,raw:i,start:t,end:this.previous().end,line:e,column:n}}const r=new Set(["=","~=","|=","^=","$=","*="]),s=this.tokens[this.current],i=this.tokens[this.current+1];if("identifier"===s?.kind&&("]"===i?.value||i&&r.has(i.value)&&"string"===this.tokens[this.current+2]?.kind)){let t="["+this.advance().value;if(this.check("]"))this.advance(),t+="]";else{const e=this.advance().value,n=this.advance().value;t+=e+'"'+(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?n.slice(1,-1):n)+'"',this.consume("]","Expected ']' after attribute selector"),t+="]"}return this.createSelector(t)}const o=[];if(!this.check("]"))do{if(this.check("]"))break;o.push(this.parseExpression())}while(this.match(","));return this.consume("]","Expected ']' after array elements"),{type:"arrayLiteral",elements:o,start:t,end:this.previous().end,line:e,column:n}}getPosition(){const t=this.current>0?this.previous():this.peek();return{start:t.start||0,end:t.end||0,line:t.line||1,column:t.column||1}}getContext(){const t=this,e={tokens:this.tokens,advance:this.advance.bind(this),peek:this.peek.bind(this),previous:this.previous.bind(this),consume:this.consume.bind(this),check:this.check.bind(this),checkIdentifierLike:this.checkIdentifierLike.bind(this),checkSelector:this.checkSelector.bind(this),checkAnySelector:this.checkAnySelector.bind(this),checkLiteral:this.checkLiteral.bind(this),checkReference:this.checkReference.bind(this),checkTimeExpression:this.checkTimeExpression.bind(this),checkEvent:this.checkEvent.bind(this),checkIsCommand:this.checkIsCommand.bind(this),checkContextVar:this.checkContextVar.bind(this),match:this.match.bind(this),matchOperator:this.matchOperator.bind(this),isAtEnd:this.isAtEnd.bind(this),createIdentifier:this.createIdentifier.bind(this),parseExpression:this.parseExpression.bind(this),parsePrimary:this.parsePrimary.bind(this),parseLogicalAnd:this.parseLogicalAnd.bind(this),parseCSSObjectLiteral:this.parseCSSObjectLiteral.bind(this),parseCommand:this.parseCommand.bind(this),parseCommandSequence:this.parseCommandSequence.bind(this),parseCommandListUntilEnd:this.parseCommandListUntilEnd.bind(this),parseCommandListUntilEndOrElse:this.parseCommandListUntilEndOrElse.bind(this),parseRepeatBody:this.parseRepeatBody.bind(this),getPosition:this.getPosition.bind(this),addError:this.addError.bind(this),addWarning:this.addWarning.bind(this),isCommand:this.isCommand.bind(this),isCompoundCommand:this.isCompoundCommand.bind(this),isKeyword:this.isKeyword.bind(this),getMultiWordPattern:this.getMultiWordPattern.bind(this),resolveKeyword:this.resolveKeyword.bind(this),savePosition:()=>t.current,restorePosition:e=>{t.current=e},peekAt:e=>t.peekAt(e),getInputSlice:(t,e)=>this.originalInput?0>t||t>=this.originalInput.length?"":void 0!==e?this.originalInput.slice(t,e):this.originalInput.slice(t):""};return Object.defineProperty(e,"current",{get:()=>t.current,set:e=>{t.current=e},enumerable:1,configurable:1}),e}}function We(t,e){const n=function(t){const e={input:"",position:0,line:1,column:1,tokens:[]};e.input=t;const n=t.length;for(;n>e.position&&(F(e),n>e.position);){const n=t[e.position];if("-"!==n||"-"!==D(e,1))if('"'!==n){if("'"===n||"'"===n){const t=D(e,1),n=e.tokens[e.tokens.length-1];if("s"!==t||!n||n.kind!==I.IDENTIFIER&&n.kind!==I.SELECTOR&&"]"!==n.value&&")"!==n.value&&"}"!==n.value)q(e);else{const t=e.position;P(e),P(e),B(e,I.OPERATOR,"'s",t)}continue}if("`"!==n)if("<"!==n)if("#"!==n){if("."===n){if("."===D(e,1)){const t=e.position;P(e),P(e),B(e,I.OPERATOR,"..",t);continue}const t=e.tokens[e.tokens.length-1],n=new Set(["from","to","into","on","in","at","between","first","last","next","previous","closest","random","of","some","no"]),r=t&&t.kind===I.IDENTIFIER&&E.has(t.value.toLowerCase()),s=t&&t.kind===I.IDENTIFIER&&n.has(t.value.toLowerCase());if((!t||t.kind===I.OPERATOR&&")"!==t.value&&"]"!==t.value||r||s||"("===t.value||"["===t.value||"{"===t.value||","===t.value||";"===t.value)&&(!t||t.end!==e.position)&&(Y(D(e))||"{"===D(e)||"-"===D(e))){U(e);continue}}if("@"!==n)if("{"!==n)if("}"!==n){if("["===n){const t=e.tokens[e.tokens.length-1],n=t&&t.kind===I.IDENTIFIER&&R.has(t.value)&&e.tokens.length>=2&&"on"===e.tokens[e.tokens.length-2]?.value;(!t||t.kind!==I.IDENTIFIER&&")"!==t.value&&"]"!==t.value||n)&&n?(B(e,I.SYMBOL,"["),P(e)):(B(e,I.OPERATOR,"["),P(e));continue}if("]"!==n){if("$"===n){const t=D(e,1);if(t>="a"&&"z">=t||t>="A"&&"Z">=t||"_"===t){X(e);continue}}et(n)?J(e):"0">n||n>"9"?("a">n||n>"z")&&("A">n||n>"Z")&&"_"!==n?(B(e,I.UNKNOWN,n),P(e)):G(e):Z(e)}else B(e,I.OPERATOR,"]"),P(e)}else B(e,I.OPERATOR,"}"),P(e);else B(e,I.OPERATOR,"{"),P(e);else z(e)}else U(e);else tt(e)?W(e):J(e);else H(e)}else q(e);else V(e)}return e.tokens}(t);return new Ue(n,e,t).parse()}Ue.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty","ignoring case"]),Ue.PRATT_TABLE=Et,Ue.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];class ze{constructor(){this.hooks=new Map,this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}register(t,e){this.unregister(t),this.hooks.set(t,e),e.beforeExecute&&this.beforeExecuteHooks.push(e.beforeExecute),e.afterExecute&&this.afterExecuteHooks.push(e.afterExecute),e.onError&&this.onErrorHooks.push(e.onError),e.interceptCommand&&this.interceptCommandHooks.push(e.interceptCommand)}unregister(t){const e=this.hooks.get(t);if(!e)return 0;if(e.beforeExecute){const t=this.beforeExecuteHooks.indexOf(e.beforeExecute);t>-1&&this.beforeExecuteHooks.splice(t,1)}if(e.afterExecute){const t=this.afterExecuteHooks.indexOf(e.afterExecute);t>-1&&this.afterExecuteHooks.splice(t,1)}if(e.onError){const t=this.onErrorHooks.indexOf(e.onError);t>-1&&this.onErrorHooks.splice(t,1)}if(e.interceptCommand){const t=this.interceptCommandHooks.indexOf(e.interceptCommand);t>-1&&this.interceptCommandHooks.splice(t,1)}return this.hooks.delete(t)}has(t){return this.hooks.has(t)}async runBeforeExecute(t){for(const e of this.beforeExecuteHooks)await e(t)}async runAfterExecute(t,e){for(const n of this.afterExecuteHooks)await n(t,e)}async runOnError(t,e){let n=e;for(const e of this.onErrorHooks){const r=await e(t,n);r instanceof Error&&(n=r)}return n}shouldIntercept(t,e){for(const n of this.interceptCommandHooks)if(n(t,e))return 1;return 0}getRegisteredNames(){return Array.from(this.hooks.keys())}clear(){this.hooks.clear(),this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}}function Je(t){return t instanceof Error&&("isHalt"in t||"isExit"in t||"isBreak"in t||"isContinue"in t||"isReturn"in t)?t:null}function Ze(t){return{ok:1,value:t}}function Ge(t){return{ok:0,error:t}}function Xe(t){return 1==t.ok}const Ye=new Map,Ke=new WeakMap;function Qe(t){let e=Ke.get(t);return e||(e=new Map,Ke.set(t,e)),e}function tn(t){return t.owner||(t.me instanceof Element?t.me:null)}function en(t,e){const n=tn(t);if(n)return Lt(e,t),Qe(n).get(e)}function nn(t,e,n){const r=tn(t);r&&(Qe(r).set(e,n),Rt(e,n,t))}function rn(t,e){return{me:t??null,owner:t??null,it:null,you:null,result:null,locals:new Map,globals:e||Ye,flags:{halted:0,breaking:0,continuing:0,returning:0,async:0}}}function sn(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"tagName"in t&&"string"==typeof t.tagName&&"classList"in t}function on(t){return null!==t&&"object"==typeof t&&"length"in t&&"number"==typeof t.length&&(Symbol.iterator in t||"function"==typeof t.item)}function an(t){if(null==t)return 0;if("number"==typeof t)return isFinite(t)?t:0;if("string"==typeof t)return parseFloat(t);if("boolean"==typeof t)return t?1:0;if(Array.isArray(t))return t.length;if("object"==typeof t){if("length"in t&&"number"==typeof t.length)return t.length;if("function"==typeof t.valueOf){const e=t.valueOf();if("number"==typeof e)return e}return NaN}return 0}function cn(t,e,n,r){if("element"!==r){if("global"===r)return It(n,t,e),void("undefined"!=typeof window&&(window[t]=e));if(t.startsWith("$"))return void It(n,t.slice(1),e);if(n.locals&&n.locals.has(t))return n.locals.set(t,e),void Rt(t,e,n);if(n.globals&&n.globals.has(t))return It(n,t,e),void("undefined"!=typeof window&&t in window&&(window[t]=e));if(n.variables&&n.variables.has(t))n.variables.set(t,e);else{if("undefined"!=typeof window&&t in window)return window[t]=e,void It(n,t,e);n.locals.set(t,e),Rt(t,e,n)}}else nn(n,t,e)}const un=new class{constructor(t={}){this.types=new Map,this.coercionCache=new Map,this.config={strictMode:0,cacheCoercions:1,...t},this.registerBuiltinTypes()}register(t){this.types.has(t.name)&&console.warn(`ExpressionTypeRegistry: Overwriting existing type '${t.name}'`),this.types.set(t.name,t)}get(t){return this.types.get(t)}has(t){return this.types.has(t)}getTypeNames(){return Array.from(this.types.keys())}inferType(t){for(const[e,n]of this.types)if(n.isType(t))return e;return"Unknown"}getHyperScriptType(t){const e=this.inferType(t),n=this.types.get(e);return n?.hyperscriptType??"unknown"}coerce(t,e,n){const r=this.types.get(e);if(!r){if(this.config.strictMode)throw Error("Unknown target type: "+e);return null}if(r.isType(t))return t;if(this.config.cacheCoercions){const n=`${this.inferType(t)}:${e}:${JSON.stringify(t)}`;if(this.coercionCache.has(n))return this.coercionCache.get(n)}const s=this.inferType(t),i=r.coerceFrom?.[s];if(i){const r=i(t,n);if(this.config.cacheCoercions&&null!==r){const n=`${s}:${e}:${JSON.stringify(t)}`;this.coercionCache.set(n,r)}return r}return r.defaultValue}canCoerce(t,e){const n=this.types.get(e);if(!n)return 0;if(n.isType(t))return 1;const r=this.inferType(t);return void 0!==n.coerceFrom?.[r]}getCoercionInfo(t,e){const n=this.types.get(e);return n&&(t===e||n.coerceFrom?.[t])?{possible:1,direct:1}:{possible:0,direct:0}}clearCache(){this.coercionCache.clear()}getStats(){return{typeCount:this.types.size,cacheSize:this.coercionCache.size,typeNames:this.getTypeNames()}}registerBuiltinTypes(){this.register({name:"String",hyperscriptType:"string",tsType:"string",isType:t=>"string"==typeof t,defaultValue:"",description:"Text string value",examples:["hello","world",""],coerceFrom:{Number:t=>t+"",Boolean:t=>t+"",Null:()=>"",Undefined:()=>"",Array:t=>Array.isArray(t)?t.join(", "):null,Object:t=>{try{return JSON.stringify(t)}catch{return t+""}},Element:t=>t instanceof Element?t.textContent??t.outerHTML:null}}),this.register({name:"Number",hyperscriptType:"number",tsType:"number",isType:t=>"number"==typeof t&&!isNaN(t),defaultValue:0,description:"Numeric value (integer or float)",examples:[0,1,3.14,-42],coerceFrom:{String:t=>{const e=parseFloat(t);return isNaN(e)?null:e},Boolean:t=>t?1:0,Null:()=>0,Undefined:()=>null}}),this.register({name:"Boolean",hyperscriptType:"boolean",tsType:"boolean",isType:t=>"boolean"==typeof t,defaultValue:0,description:"True or false value",examples:[1,0],coerceFrom:{String:t=>{const e=t.toLowerCase().trim();return"true"===e||"yes"===e||"1"===e?1:"false"===e||"no"===e||"0"===e||""===e?0:e.length>0},Number:t=>0!==t,Null:()=>0,Undefined:()=>0,Array:t=>Array.isArray(t)?t.length>0:0,Element:t=>t instanceof Element,ElementList:t=>Array.isArray(t)&&t.length>0}}),this.register({name:"Element",hyperscriptType:"element",tsType:"Element | HTMLElement",isType:t=>t instanceof Element,defaultValue:null,description:"DOM Element",coerceFrom:{String:(t,e)=>{const n=t;if(n.startsWith("#")||n.startsWith(".")||n.match(/^[\w-]+$/))try{return document.querySelector(n)}catch{return null}return null},ElementList:t=>Array.isArray(t)&&t.length>0?t[0]:null,NodeList:t=>t.length>0?t[0]:null}}),this.register({name:"ElementList",hyperscriptType:"element-list",tsType:"Element[]",isType:t=>Array.isArray(t)&&t.length>0&&t.every(t=>t instanceof Element),defaultValue:[],description:"Array of DOM Elements",coerceFrom:{Element:t=>t instanceof Element?[t]:[],NodeList:t=>Array.from(t),String:t=>{try{return Array.from(document.querySelectorAll(t))}catch{return[]}},Array:t=>{const e=t;return e.every(t=>t instanceof Element)?e:[]}}}),this.register({name:"Array",hyperscriptType:"array",tsType:"unknown[]",isType:t=>Array.isArray(t),defaultValue:[],description:"Array of values",coerceFrom:{String:t=>{const e=t;try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map(t=>t.trim())},ElementList:t=>t,NodeList:t=>Array.from(t),Object:t=>Object.values(t)}}),this.register({name:"Object",hyperscriptType:"object",tsType:"Record<string, unknown>",isType:t=>!("object"!=typeof t||null===t||Array.isArray(t)||t instanceof Element),defaultValue:{},description:"Plain JavaScript object",coerceFrom:{String:t=>{try{const e=JSON.parse(t);if("object"==typeof e&&null!==e&&!Array.isArray(e))return e}catch{}return null},Array:t=>{const e={};return t.forEach((t,n)=>{e[n+""]=t}),e}}}),this.register({name:"Null",hyperscriptType:"null",tsType:"null",isType:t=>null===t,defaultValue:null,description:"Null value"}),this.register({name:"Undefined",hyperscriptType:"undefined",tsType:"undefined",isType:t=>void 0===t,defaultValue:void 0,description:"Undefined value"}),this.register({name:"Function",hyperscriptType:"function",tsType:"Function",isType:t=>"function"==typeof t,defaultValue:null,description:"JavaScript function"}),this.register({name:"Event",hyperscriptType:"event",tsType:"Event",isType:t=>t instanceof Event,defaultValue:null,description:"DOM Event"}),this.register({name:"NodeList",hyperscriptType:"element-list",tsType:"NodeList",isType:t=>t instanceof NodeList,defaultValue:null,description:"DOM NodeList (typically from querySelectorAll)",coerceFrom:{Array:t=>null}}),this.register({name:"Unknown",hyperscriptType:"unknown",tsType:"unknown",isType:t=>1,defaultValue:null,description:"Unknown/any value type"})}};function ln(t){const e=un.get("String");return e?e.isType(t):"string"==typeof t}function hn(t){const e=un.get("Number");return e?e.isType(t):"number"==typeof t}function fn(t){const e=un.get("Boolean");return e?e.isType(t):"boolean"==typeof t}function dn(t){const e=un.get("Object");return e?e.isType(t):"object"==typeof t&&null!==t}function pn(t){const e=un.get("Function");return e?e.isType(t):"function"==typeof t}function mn(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"style"in t}function yn(t){return t instanceof Element}function gn(t){return t instanceof HTMLElement}const vn=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function bn(t,e){return vn.has(e.toLowerCase())?t.hasAttribute(e):t.getAttribute(e)}const wn={id:t=>t.id,classname:t=>t.className,class:t=>t.className,tagname:t=>t.tagName.toLowerCase(),innertext:t=>t.textContent?.trim(),innerHTML:t=>t.innerHTML,outerhtml:t=>t.outerHTML,value:t=>function(t){if(null===t||"object"!=typeof t||!("tagName"in t))return 0;const e=t.tagName;return"INPUT"===e||"SELECT"===e||"TEXTAREA"===e}(t)?t.value:void 0,checked:t=>function(t){return null!==t&&"object"==typeof t&&"tagName"in t&&"INPUT"===t.tagName}(t)?t.checked:void 0,disabled:t=>"disabled"in t?t.disabled:void 0,selected:t=>function(t){return null!=t&&"object"==typeof t&&"tagName"in t&&"OPTION"===t.tagName}(t)?t.selected:void 0,tabindex:t=>mn(t)?t.tabIndex:void 0,hidden:t=>mn(t)?t.hidden:void 0,style:t=>getComputedStyle(t),children:t=>Array.from(t.children),parent:t=>t.parentElement,firstchild:t=>t.firstElementChild,lastchild:t=>t.lastElementChild,nextsibling:t=>t.nextElementSibling,previoussibling:t=>t.previousElementSibling,next:t=>t.nextElementSibling,previous:t=>t.previousElementSibling,values:t=>function(t){if(t instanceof HTMLFormElement)return new FormData(t);const e=new FormData;return t.querySelectorAll("input, select, textarea").forEach(t=>{const n=t.getAttribute("name");n&&"value"in t&&e.append(n,t.value)}),e}(t)};function En(t,e){if(e.startsWith("*"))return function(t,e){if(!gn(t))return;if(e.startsWith("computed-"))return getComputedStyle(t).getPropertyValue(e.slice(9))||"";const n=e.replace(/-([a-z])/g,(t,e)=>e.toUpperCase());return t.style[n]}(t,e.slice(1));if(e.startsWith("computed-")){const n=e.slice(9);return gn(t)?getComputedStyle(t).getPropertyValue(n):void 0}if(e.startsWith("@"))return bn(t,e.slice(1));const n=wn[e.toLowerCase()];if(n)return n(t);if(function(t,e){return t.hasAttribute(e)}(t,e))return bn(t,e);const r=t[e];return pn(r)?r.bind(t):r}const xn={1:"one",2:"two",3:"three",4:"four",5:"five"};function kn(t,e,n,r){return t.length!==e?`${n} requires exactly ${s=e,xn[s]??s+""} argument${1===e?"":"s"}${r?` (${r})`:""}`:null;var s}function Sn(t,e,n,r){return"string"!=typeof t[e]?`${n} ${r||"argument "+(e+1)} must be a string`:null}function An(t,e,n){return kn(t,1,e,n)??Sn(t,0,e,n)}function Nn(t,e){return kn(t,2,e,"left, right")}function Cn(){return null}function Tn(t,e,n,r){return t.length>e?`${n} expression takes at most ${1===e?"one":e+""} argument${1===e?"":"s"}${r?` (${r})`:""}`:null}function On(t,e,n,r,s){return e>t.length||t.length>n?`${r} requires ${e}-${n} arguments${s?` (${s})`:""}`:null}function $n(t,e,n,r=[]){return{type:t,message:e,suggestions:r,...n&&{path:n}}}const Rn=("undefined"!=typeof process?1:0)||"undefined"!=typeof process&&"true"===process.env.HYPERFIXI_SKIP_VALIDATION||"undefined"!=typeof globalThis&&"true"===globalThis.HYPERFIXI_SKIP_VALIDATION;let Ln;function In(){return Ln({validate:t=>({success:1,data:t})})}function jn(t,e){if(Rn)return In();const n=Ln({validate:n=>{if("object"!=typeof n||null===n||Array.isArray(n))return{success:0,error:$n("type-mismatch","Expected object, received "+typeof n)};const r=n,s={};if(e?.strict){const e=Object.keys(t),n=Object.keys(r).filter(t=>!e.includes(t));if(n.length>0)return{success:0,error:$n("runtime-error","Unexpected properties: "+n.join(", "))}}for(const[e,n]of Object.entries(t)){const t=r[e];if(!(e in r)&&!n.t)return{success:0,error:$n("missing-argument",`Required field "${e}" is missing`,e)};const i=n.validate(t);if(!i.success)return{success:0,error:$n("validation-error",i.error.message||`Field "${e}" validation failed`,i.error.path?`${e}.${i.error.path}`:e)};void 0!==i.data&&(s[e]=i.data)}return{success:1,data:s}}});return n.strict=()=>jn(t,{strict:1}),n}Ln=function(t){return t.describe||(t.describe=function(t){return this.description=t,this}),t.safeParse||(t.safeParse=function(t){const e=this.validate(t);return e.success?{success:1,data:e.data}:{success:0,error:{errors:e.error?[e.error]:[]}}}),t.parse||(t.parse=function(t){const e=this.validate(t);if(e.success&&void 0!==e.data)return e.data;throw Error(e.error?.message||"Validation failed")}),t.optional||(t.optional=function(){const t=this.validate.bind(this),e={...this,t:1,validate:e=>null==e?{success:1,data:void 0}:t(e)};return Ln(e)}),t.min||(t.min=function(t){const e=this.validate.bind(this),n={...this,validate:n=>{const r=e(n);return r.success&&"string"==typeof r.data&&t>r.data.length?{success:0,error:$n("runtime-error",`String must be at least ${t} characters long`)}:r}};return Ln(n)}),t.max||(t.max=function(t){const e=this.validate.bind(this),n={...this,validate:n=>{const r=e(n);return r.success&&"string"==typeof r.data&&r.data.length>t?{success:0,error:$n("runtime-error",`String must be at most ${t} characters long`)}:r}};return Ln(n)}),t.default||(t.default=function(t){const e=this.validate.bind(this),n={...this,i:t,o:1,validate:n=>void 0===n?{success:1,data:t}:e(n)};return Ln(n)}),t.rest||(t.rest=function(t){return this}),t.refine||(t.refine=function(t,e){const n=this.validate.bind(this),r={...this,validate:r=>{const s=n(r);return s.success?t(s.data)?s:{success:0,error:$n("runtime-error",e||"Refinement validation failed")}:s}};return Ln(r)}),new Proxy(t,{get:(t,e,n)=>e in t||"string"!=typeof e||e.startsWith("_")||"constructor"===e||"validate"===e||"then"===e?Reflect.get(t,e,n):function(...t){return n}})};const Mn=t=>function(t={}){return Rn?In():Ln({validate:e=>t.optional&&null==e?{success:1,data:void 0}:"string"!=typeof e?{success:0,error:$n("type-mismatch","Expected string, received "+typeof e)}:void 0!==t.minLength&&t.minLength>e.length?{success:0,error:$n("runtime-error",`String must be at least ${t.minLength} characters long`)}:void 0!==t.maxLength&&e.length>t.maxLength?{success:0,error:$n("runtime-error",`String must be at most ${t.maxLength} characters long`)}:t.pattern&&!t.pattern.test(e)?t.pattern.source.startsWith("^")&&t.pattern.source.endsWith("$")?{success:0,error:$n("runtime-error",`Expected "${t.pattern.source.slice(1,-1)}", received "${e}"`)}:{success:0,error:$n("missing-argument","String does not match required pattern")}:{success:1,data:e},...t.description&&{description:t.description}})}(t||{}),Dn=t=>function(t={}){return Rn?In():Ln({validate:e=>{const n=Number(e);return isNaN(n)?{success:0,error:$n("type-mismatch","Expected number, received "+typeof e)}:void 0!==t.min&&t.min>n?{success:0,error:$n("runtime-error","Number must be at least "+t.min)}:void 0!==t.max&&n>t.max?{success:0,error:$n("runtime-error","Number must be at most "+t.max)}:{success:1,data:n}}})}(t||{}),Pn=()=>Rn?In():Ln({validate:t=>"boolean"!=typeof t?{success:0,error:$n("type-mismatch","Expected boolean, received "+typeof t)}:{success:1,data:t}}),Fn=t=>jn(t),Bn=t=>function(t){return Rn?In():Ln({validate:e=>{if(!Array.isArray(e))return{success:0,error:$n("type-mismatch","Expected array, received "+typeof e)};if(e.length!==t.length)return{success:0,error:$n("runtime-error",`Expected tuple of length ${t.length}, received length ${e.length}`)};const n=[];for(let r=0;t.length>r;r++){const s=t[r].validate(e[r]);if(!s.success)return{success:0,error:$n("runtime-error",s.error.message,s.error.path?`${r}.${s.error.path}`:""+r)};n.push(s.data)}return{success:1,data:n}}})}(t),_n=()=>In(),Vn=()=>In(),qn=()=>function(t,e="Custom validation failed"){return Rn?In():Ln({validate:n=>t(n)?{success:1,data:n}:{success:0,error:$n("runtime-error",e)}})}(t=>void 0===t,"Expected undefined");class Hn{trackPerformance(t,e,n,r){t.evaluationHistory&&t.evaluationHistory.push({expressionName:this.name,category:this.category,input:e,output:n.success?n.value:n.error,timestamp:r,duration:Date.now()-r,success:n.success})}trackSimple(t,e,n,r=(n?"success":"error")){t.evaluationHistory&&t.evaluationHistory.push({expressionName:this.name,category:this.category,input:"operation",output:r,timestamp:e,duration:Date.now()-e,success:n})}toBoolean(t){return 0==t||0===t||0n===t||""===t||null==t||hn(t)&&isNaN(t)?0:1}success(t,e){return{success:1,value:t,type:e}}failure(t,e,n,r,s=[]){return{success:0,error:{name:t,type:e,message:n,code:r,suggestions:s}}}validationSuccess(){return{isValid:1,errors:[],suggestions:[]}}validationFailure(t,e,n=[]){return{isValid:0,errors:[{type:t,message:e,suggestions:n}],suggestions:n}}isElement(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"tagName"in t&&"string"==typeof t.tagName}inferType(t){return null===t?"null":void 0===t?"undefined":this.isElement(t)?"element":Array.isArray(t)?"array":dn(t)?"object":typeof t}inferEvaluationType(t){return void 0===t?"Undefined":null===t?"Null":ln(t)?"String":hn(t)?"Number":fn(t)?"Boolean":Array.isArray(t)?"Array":this.isElement(t)?"Element":"Object"}normalizeCollection(t){return Array.isArray(t)?t:t instanceof NodeList?Array.from(t):ln(t)?t.split(""):null==t?[]:dn(t)&&Symbol.iterator in t?Array.from(t):[]}toNumber(t){if(hn(t)&&Number.isFinite(t))return t;if(ln(t)){const e=Number(t);return Number.isFinite(e)?e:null}return fn(t)?t?1:0:null}}function Un(t,e,n,r,s="runtime-error"){return{success:0,error:{name:t+"ConversionError",type:s,message:n,code:e,suggestions:r}}}function Wn(t,e){return{success:1,value:t,type:e}}function zn(t,e){return`${t}: ${e instanceof Error?e.message:e+""}`}const Jn={Array:(t,e)=>{try{return Array.isArray(t)?Wn(t,"array"):t instanceof NodeList?Wn(Array.from(t),"array"):Wn(null==t?[]:[t],"array")}catch(t){return Un("Array","ARRAY_CONVERSION_FAILED",zn("Failed to convert value to Array",t),["Check if value is iterable","Ensure value is not circular reference"])}},String:(t,e)=>{try{return null==t?Wn("","string"):ln(t)?Wn(t,"string"):dn(t)?Wn(JSON.stringify(t),"string"):Wn(t+"","string")}catch(t){return Un("String","STRING_CONVERSION_FAILED",zn("Failed to convert value to String",t),["Check if object has circular references","Ensure value is serializable"])}},Boolean:(t,e)=>{try{if(fn(t))return Wn(t,"boolean");if(null==t)return Wn(0,"boolean");if(ln(t)){const e=t.toLowerCase().trim();return Wn("false"!==e&&"0"!==e&&""!==e,"boolean")}return hn(t)?Wn(0!==t&&!isNaN(t),"boolean"):Wn(!!t,"boolean")}catch(t){return Un("Boolean","BOOLEAN_CONVERSION_FAILED",zn("Failed to convert value to Boolean",t),["Use explicit true/false values","Check for unexpected data types"])}},Number:(t,e)=>{try{if(hn(t))return Wn(t,"number");if(null==t)return Wn(0,"number");const e=Number(t);return isNaN(e)?Un("Number","INVALID_NUMBER",`Cannot convert "${t}" to a valid number`,["Check if value contains non-numeric characters","Use a valid numeric format"],"invalid-argument"):Wn(e,"number")}catch(t){return Un("Number","NUMBER_CONVERSION_FAILED",zn("Failed to convert value to Number",t),["Ensure value is convertible to number","Check for special characters"])}},Int:(t,e)=>{const n=Jn.Number(t,e);return n.success?Wn(Math.trunc(n.value),"number"):n},Float:(t,e)=>{const n=Jn.Number(t,e);return n.success?Wn(parseFloat(""+n.value),"number"):n},Date:(t,e)=>{try{if(t instanceof Date)return Wn(t,"object");if(null==t)return Wn(new Date(""),"object");if(ln(t)&&/^\d{4}-\d{2}-\d{2}$/.test(t)){const[e,n,r]=t.split("-").map(Number);return Wn(new Date(e,n-1,r),"object")}const e=new Date(t);return isNaN(e.getTime())?Un("Date","INVALID_DATE",`Cannot convert "${t}" to a valid date`,["Use ISO 8601 format (YYYY-MM-DD)","Check date string format","Ensure date values are valid"],"invalid-argument"):Wn(e,"object")}catch(t){return Un("Date","DATE_CONVERSION_FAILED",zn("Failed to convert value to Date",t),["Check date format","Ensure value is a valid date string or timestamp"])}},JSON:(t,e)=>{if(!ln(t))return Wn(t,"object");try{return Wn(JSON.parse(t),"object")}catch(t){return Un("JSON","JSON_PARSE_FAILED",zn("Failed to parse value as JSON",t),["Check JSON syntax and escaping","Use `as JSONString` to stringify a value instead"],"syntax-error")}},JSONString:(t,e)=>{try{return Wn(JSON.stringify(t),"string")}catch(t){return Un("JSONString","JSON_STRINGIFY_FAILED",zn("Failed to stringify value as JSON",t),["Check for circular references","Ensure all properties are serializable","Remove functions and undefined values"])}},Object:(t,e)=>{try{if(dn(t))return Wn(t,"object");if(ln(t))try{return Wn(JSON.parse(t),"object")}catch(t){return Un("Object","JSON_PARSE_FAILED",zn("Cannot parse JSON string",t),["Check JSON syntax","Ensure proper escaping of quotes","Validate JSON format"],"syntax-error")}return Wn({},"object")}catch(t){return Un("Object","OBJECT_CONVERSION_FAILED",zn("Failed to convert value to Object",t),["Ensure value is valid JSON string or object","Check for syntax errors"])}},Values:(t,e)=>{try{if(t instanceof HTMLFormElement)return Wn(Kn(t),"object");if(t instanceof HTMLElement){const e=t.querySelectorAll("input, select, textarea"),n={};return e.forEach(t=>{const e=t;if(e.name){const t=Qn(e);void 0!==t&&(n[e.name]=t)}}),Wn(n,"object")}return Wn({},"object")}catch(t){return Un("FormValues","FORM_VALUES_EXTRACTION_FAILED",zn("Failed to extract form values",t),["Ensure element is a form or contains form inputs","Check form structure","Verify input names are set"])}},FormEncoded:(t,e)=>{try{let n=t;if(t instanceof HTMLElement){const r=Jn.Values(t,e);if(!r.success)return r;n=r.value}if(!dn(n))return Wn("","string");const r=new URLSearchParams;for(const[t,e]of Object.entries(n))if(null!=e)if(Array.isArray(e))for(const n of e)r.append(t,n+"");else r.append(t,e+"");return Wn(""+r,"string")}catch(t){return Un("FormEncoded","FORM_ENCODE_FAILED",zn("Failed to URL-encode values",t),["Ensure input is a form element or plain object of scalar/array values"])}},Set:(t,e)=>{try{return Wn(new Set(t),"object")}catch(t){return Un("Set","SET_CONVERSION_FAILED",zn("Failed to convert to Set",t),["Ensure the value is iterable"])}},Map:(t,e)=>{try{return Wn(new Map(Object.entries(t??{})),"object")}catch(t){return Un("Map","MAP_CONVERSION_FAILED",zn("Failed to convert to Map",t),["Ensure the value is a plain object"])}},Keys:(t,e)=>t instanceof Map?Wn(Array.from(t.keys()),"array"):Wn(Object.keys(t??{}),"array"),Entries:(t,e)=>t instanceof Map?Wn(Array.from(t.entries()),"array"):Wn(Object.entries(t??{}),"array"),Reversed:(t,e)=>{try{return Wn(Array.from(t).reverse(),"array")}catch(t){return Un("Reversed","REVERSED_CONVERSION_FAILED",zn("Failed to reverse value",t),["Ensure the value is array-like"])}},Unique:(t,e)=>{try{return Wn([...new Set(t)],"array")}catch(t){return Un("Unique","UNIQUE_CONVERSION_FAILED",zn("Failed to dedupe value",t),["Ensure the value is iterable"])}},Flat:(t,e)=>{try{return Wn(Array.from(t).flat(),"array")}catch(t){return Un("Flat","FLAT_CONVERSION_FAILED",zn("Failed to flatten value",t),["Ensure the value is array-like"])}}},Zn=Fn({value:Vn(),type:Mn().min(1)}),Gn=Fn({value:Vn(),type:Mn().min(1)});new class extends Hn{constructor(){super(...arguments),this.name="as",this.category="Conversion",this.syntax="value as Type",this.description='Converts values between different types using the "as" keyword',this.outputType="Any",this.inputSchema=Zn,this.metadata={category:"Conversion",complexity:"medium",sideEffects:[],dependencies:[],returnTypes:["Any"],examples:[{input:'"123" as Int',description:"Convert string to integer",expectedOutput:123},{input:"form as Values",description:"Extract form values as object",expectedOutput:{name:"John",age:"25"}},{input:"[1,2,3] as JSONString",description:"Convert array to JSON string (upstream 0.9.90: use JSONString, not JSON)",expectedOutput:"[1,2,3]"},{input:"'{\"a\":1}' as JSON",description:"Parse a JSON string (upstream 0.9.90: as JSON now parses)",expectedOutput:{a:1}},{input:'"2023-12-25" as Date',description:"Parse date string",expectedOutput:new Date(2023,11,25)}],relatedExpressions:["is","Object","Array"],performance:{averageTime:1,complexity:"O(n)"}},this.documentation={summary:'Converts values between different types using the "as" keyword with comprehensive type safety',parameters:[{name:"value",type:"object",description:"The value to convert",optional:0,examples:['"123"',"form","[1,2,3]","true","null"]},{name:"type",type:"string",description:"Target conversion type",optional:0,examples:["Int","String","Boolean","Array","JSON","Object","Date","Values","HTML","Fragment"]}],returns:{type:"object",description:"Structured result with converted value or detailed error information",examples:['{ success: true, value: 123, type: "number" }',"{ success: false, error: { ... } }"]},examples:[{title:"String to number conversion",code:"if my.value as Int > 100",explanation:"Convert form input to integer for comparison",output:"Boolean result"},{title:"Form data extraction",code:"put closest <form /> as Values into result",explanation:"Extract all form values as structured object",output:'{ name: "John", age: "25", ... }'},{title:"Array to JSON serialization",code:"put items as JSONString into storage",explanation:"Convert array to JSON string for storage (upstream 0.9.90: use `as JSONString`)",output:'"[1,2,3]"'},{title:"Date parsing with validation",code:"put my.dateInput as Date into event.detail.date",explanation:"Parse date input with automatic validation",output:"Date object or validation error"},{title:"Boolean conversion with smart parsing",code:'if "false" as Boolean then hide else show',explanation:"Parse string boolean values correctly",output:"false (not true like naive conversion)"}],seeAlso:["is","Values","JSON","Array","Object"],tags:["conversion","types","validation","forms","json","parsing"]}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:{name:"AsExpressionValidationError",type:"validation-error",message:r.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:r.suggestions}};const{value:s,type:i}=e;if(i.startsWith("Fixed")){const r=i.match(/^Fixed:(\d+)$/),o=r?parseInt(r[1],10):0,a=Jn.Number(s,t);if(!a.success)return a;const c={success:1,value:a.value.toFixed(o),type:"string"};return this.trackPerformance(t,e,c,n),c}let o=Jn[i];if(o){const r=o(s,t);return this.trackPerformance(t,e,r,n),r}const a={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON",jsonstring:"JSONString",formencoded:"FormEncoded"}[i.toLowerCase()];if(a&&(o=Jn[a],o)){const r=o(s,t);return this.trackPerformance(t,e,r,n),r}const c={success:0,error:{name:"UnknownConversionTypeError",type:"validation-error",message:"Unknown conversion type: "+i,code:"UNKNOWN_CONVERSION_TYPE",suggestions:["Use supported types: String, Number, Boolean, Array, Object, Date, JSON, Values","Check type spelling and capitalization","See documentation for complete list of conversion types"]}};return this.trackPerformance(t,e,c,n),c}catch(r){const s={success:0,error:{name:"AsExpressionError",type:"runtime-error",message:"Conversion failed: "+(r instanceof Error?r.message:r+""),code:"CONVERSION_FAILED",suggestions:["Check value and type compatibility","Ensure value is convertible to target type"]}};return this.trackPerformance(t,e,s,n),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?{isValid:1,errors:[],suggestions:[]}:{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:t.message,suggestions:["Expected valid input structure, got: "+t.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(t){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}},new class extends Hn{constructor(){super(...arguments),this.name="is",this.category="Conversion",this.syntax="value is Type",this.description="Checks if a value is of a specific type",this.outputType="Boolean",this.inputSchema=Gn,this.metadata={category:"Conversion",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"42 is number",description:"Check if value is a number",expectedOutput:1},{input:"null is empty",description:"Check if value is empty/null",expectedOutput:1},{input:"element is Element",description:"Check if value is DOM element",expectedOutput:1,context:{element:"<div>...</div>"}}],relatedExpressions:["as","empty","exists"],performance:{averageTime:.1,complexity:"O(1)"}},this.documentation={summary:"Checks if a value is of a specific type with comprehensive type detection",parameters:[{name:"value",type:"object",description:"The value to check",optional:0,examples:["42","null","element",'"text"',"[]"]},{name:"type",type:"string",description:"Type name to check against",optional:0,examples:["number","string","boolean","array","object","element","empty","null"]}],returns:{type:"object",description:"Boolean result indicating type match",examples:['{ success: true, value: true, type: "boolean" }']},examples:[{title:"Number validation",code:"if my.age is number then proceed",explanation:"Check if form input is valid number",output:"Boolean result"},{title:"Empty check",code:"if result is empty then show message",explanation:"Check if result is null, undefined, or empty",output:"Boolean result"},{title:"Element validation",code:"if target is element then addClass",explanation:"Ensure target is valid DOM element before manipulation",output:"Boolean result"}],seeAlso:["as","empty","exists","null"],tags:["validation","types","checking","guards"]}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:{name:"IsExpressionValidationError",type:"validation-error",message:r.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:r.suggestions}};const{value:s,type:i}=e,o=i.toLowerCase();let a;switch(o){case"null":a=null===s;break;case"undefined":a=void 0===s;break;case"string":a=ln(s);break;case"number":a=hn(s)&&!isNaN(s);break;case"boolean":a=fn(s);break;case"object":a=dn(s);break;case"array":a=Array.isArray(s);break;case"function":a=pn(s);break;case"date":a=s instanceof Date;break;case"element":a=s instanceof Element;break;case"node":a=s instanceof Node;break;case"node-list":a=s instanceof NodeList;break;case"empty":a=null==s||""===s||Array.isArray(s)&&0===s.length||dn(s)&&0===Object.keys(s).length;break;default:a=s?.constructor?.name?.toLowerCase()===o}const c=this.success(a,"boolean");return this.trackPerformance(t,e,c,n),c}catch(r){const s=this.failure("IsExpressionError","type-mismatch","Type check failed: "+(r instanceof Error?r.message:r+""),"TYPE_CHECK_FAILED",["Check type name spelling","Ensure value is accessible"]);return this.trackPerformance(t,e,s,n),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:t.message,suggestions:["Expected valid input structure, got: "+t.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(t){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}};const Xn={conversions:{dynamicResolvers:[]}},Yn={Array:t=>Array.isArray(t)?t:t instanceof NodeList?Array.from(t):null==t?[]:[t],String:t=>null==t?"":ln(t)?t:dn(t)?JSON.stringify(t):t+"",Boolean:t=>{if(fn(t))return t;if(null==t)return 0;if(ln(t)){const e=t.toLowerCase().trim();return"false"===e||"0"===e||""===e?0:1}return hn(t)?0!==t&&!isNaN(t):!!t},Number:t=>{if(hn(t))return t;if(null==t)return 0;const e=Number(t);return isNaN(e)?0:e},Math:t=>{if(hn(t))return t;if(null==t)return 0;const e=(t+"").trim();if(!e)return 0;try{return function(t){if(t=t.replace(/\s/g,""),!/^[0-9+\-*/().]+$/.test(t))throw Error("Invalid characters in math expression");try{const e=Function(`"use strict"; return (${t})`)();if(!hn(e)||!isFinite(e))throw Error("Expression did not evaluate to a finite number");return e}catch(t){throw Error("Math expression evaluation failed: "+(t instanceof Error?t.message:t+""))}}(e)}catch(t){return console.warn("Math conversion failed:",t),0}},Int:t=>{const e=Yn.Number(t);return Math.trunc(e)},Float:t=>{const e=Yn.Number(t);return parseFloat(""+e)},Date:t=>{if(t instanceof Date)return t;if(null==t)return new Date(NaN);if(ln(t)&&/^\d{4}-\d{2}-\d{2}$/.test(t)){const[e,n,r]=t.split("-").map(Number);return new Date(e,n-1,r)}return new Date(t)},JSON:t=>{if(!ln(t))return t;try{return JSON.parse(t)}catch{return t}},JSONString:t=>{try{return JSON.stringify(t)}catch{return"{}"}},Object:t=>{if(dn(t))return t;if(ln(t))try{return JSON.parse(t)}catch(t){return{}}return{}},Fragment:t=>{const e=document.createDocumentFragment(),n=Array.isArray(t)||t instanceof NodeList?Array.from(t):[t];for(const t of n)if(t instanceof Node)e.append(t);else{const n=document.createElement("template");n.innerHTML=null==t?"":t+"",e.append(n.content)}return e},HTML:t=>ln(t)?t:t instanceof NodeList?Array.from(t).map(t=>t instanceof Element?t.outerHTML:t.textContent||"").join(""):Array.isArray(t)?t.map(t=>t instanceof Element?t.outerHTML:Yn.String(t)).join(""):t instanceof Element?t.outerHTML:Yn.String(t),Values:(t,e)=>{if(t instanceof HTMLFormElement)return Kn(t);if(t instanceof HTMLElement){const e=t.querySelectorAll("input, select, textarea"),n={};return e.forEach(t=>{t.name&&(n[t.name]=Qn(t))}),n}return{}},FormEncoded:(t,e)=>{const n=t instanceof HTMLElement?Yn.Values(t,e):t;if(!dn(n))return"";const r=new URLSearchParams;for(const[t,e]of Object.entries(n))if(null!=e)if(Array.isArray(e))for(const n of e)r.append(t,n+"");else r.append(t,e+"");return""+r},Set:t=>new Set(t),Map:t=>new Map(Object.entries(t??{})),Keys:t=>t instanceof Map?Array.from(t.keys()):Object.keys(t??{}),Entries:t=>t instanceof Map?Array.from(t.entries()):Object.entries(t??{}),Reversed:t=>Array.from(t).reverse(),Unique:t=>[...new Set(t)],Flat:t=>Array.from(t).flat(),"Values:Form":(t,e)=>{const n=Yn.Values(t,e);return Yn.FormEncoded(n,e)},"Values:JSON":(t,e)=>{const n=Yn.Values(t,e);return JSON.stringify(n)}};function Kn(t){const e={};return t.querySelectorAll("input, select, textarea").forEach(t=>{const n=t;if(n.name){const t=Qn(n);void 0!==t&&(void 0!==e[n.name]?(Array.isArray(e[n.name])||(e[n.name]=[e[n.name]]),e[n.name].push(t)):e[n.name]=t)}}),e}function Qn(t){if(t instanceof HTMLInputElement)switch(t.type){case"checkbox":return t.checked;case"radio":return t.checked?t.value:void 0;case"number":case"range":return t.valueAsNumber;case"date":case"datetime-local":return t.valueAsDate;case"file":return t.files;default:return t.value}return t instanceof HTMLSelectElement&&t.multiple?Array.from(t.selectedOptions).map(t=>t.value):t.value}const tr={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON",jsonstring:"JSONString",formencoded:"FormEncoded"};function er(t,e,n){if("string"!=typeof e)throw Error("Conversion type must be a string");if(e.startsWith("Fixed")){const{precision:n}=function(t){const e=t.match(/^Fixed(?::(\d+))?$/);return e?{precision:e[1]?parseInt(e[1],10):0}:{}}(e);return Yn.Number(t).toFixed(n??0)}if(null==t)return t;let r=Yn[e];if(r)return r(t,n);const s=tr[e.toLowerCase()];if(s&&(r=Yn[s],r))return r(t,n);const i=Xn.conversions[e];if("function"==typeof i)return i(t,n);for(const n of Xn.conversions.dynamicResolvers){const r=n(e,t);if(void 0!==r)return r}return console.warn("Unknown conversion type: "+e),t}const nr={as:{name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(t,...e){const[n,r]=e;return er(n,r,t)},validate:t=>kn(t,2,"as","value, type")??Sn(t,1,"as","conversion type")},is:{name:"is",category:"Conversion",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is a","is an"],async evaluate(t,...e){const[n,r]=e;if(!ln(r))throw Error("Type check requires a string type");switch(r.toLowerCase()){case"null":return null===n;case"undefined":return void 0===n;case"string":return ln(n);case"number":return hn(n)&&!isNaN(n);case"boolean":return fn(n);case"object":return dn(n);case"array":return Array.isArray(n);case"function":return pn(n);case"date":return n instanceof Date;case"element":return n instanceof Element;case"node":return n instanceof Node;case"nodelist":return n instanceof NodeList;case"empty":return null==n||""===n||Array.isArray(n)&&0===n.length||dn(n)&&0===Object.keys(n).length;default:return n?.constructor?.name?.toLowerCase()===r.toLowerCase()}},validate:t=>kn(t,2,"is","value, type")??Sn(t,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(t,e)=>e,validate:t=>kn(t,1,"async","expression")}},rr=new Set(["__proto__","constructor","prototype"]);function sr(t,e){if(t instanceof Element)return En(t,e);if(dn(t)){if(rr.has(e))return;return t[e]}return t[e]}function ir(t){let e;if(Array.isArray(t))e=t;else{if(!("undefined"!=typeof NodeList&&t instanceof NodeList||"undefined"!=typeof HTMLCollection&&t instanceof HTMLCollection))return 0;e=Array.from(t)}return 0===e.length?0:e.every(t=>t instanceof Element||null!=t&&"object"==typeof t&&t.constructor!==Object&&!Array.isArray(t))}const or={possessive:{name:"possessive",category:"Reference",evaluatesTo:"Any",operators:["'s","s"],async evaluate(t,...e){const[n,r]=e;if(null!=n){if("string"!=typeof r)throw Error("Property name must be a string");return ir(n)&&!(r in n)?Array.from(n,t=>sr(t,r)):sr(n,r)}},validate:t=>kn(t,2,"possessive","element, property")??Sn(t,1,"possessive","property name")},my:{name:"my",category:"Reference",evaluatesTo:"Any",operators:["my"],async evaluate(t,...e){const[n]=e;if(t.me){if("string"!=typeof n)throw Error("Property name must be a string");if(t.me instanceof Element)return En(t.me,n);if(dn(t.me)){if(rr.has(n))return;return t.me[n]}return t.me[n]}},validate:t=>An(t,"my","property")},its:{name:"its",category:"Reference",evaluatesTo:"Any",operators:["its"],async evaluate(t,...e){const[n]=e;if(null==t.it)return;if("string"!=typeof n)throw Error("Property name must be a string");const r=t.it;if(r instanceof Element)return En(r,n);if(dn(r)){if(rr.has(n))return;return r[n]}return r[n]},validate:t=>An(t,"its","property")},your:{name:"your",category:"Reference",evaluatesTo:"Any",operators:["your"],async evaluate(t,...e){const[n]=e;if(t.you){if("string"!=typeof n)throw Error("Property name must be a string");if(t.you instanceof Element)return En(t.you,n);if(dn(t.you)){if(rr.has(n))return;return t.you[n]}return t.you[n]}},validate:t=>An(t,"your","property")},of:{name:"of",category:"Reference",evaluatesTo:"Any",operators:["of"],async evaluate(t,...e){const[n,r]=e;if(null!=r){if("string"!=typeof n)throw Error("Property name must be a string");if(r instanceof Element)return En(r,n);if(dn(r)){if(rr.has(n))return;return r[n]}return r[n]}},validate:t=>kn(t,2,"of","property, object")??Sn(t,0,"of","property name")},attribute:{name:"attribute",category:"Reference",evaluatesTo:"String",operators:["@"],async evaluate(t,...e){const[n,r]=e;if("string"!=typeof n)throw Error("Attribute name must be a string");const s=r||t.me;return s&&s instanceof Element?s.getAttribute(n):null},validate:t=>On(t,1,2,"attribute","attributeName, optional element")??Sn(t,0,"attribute","attribute name")??(2>t.length||null==t[1]||t[1]instanceof Element?null:"attribute element must be an Element")},attributeWithValue:{name:"attributeWithValue",category:"Reference",evaluatesTo:"Boolean",operators:["@="],async evaluate(t,...e){const[n,r,s]=e;if("string"!=typeof n)throw Error("Attribute name must be a string");if("string"!=typeof r)throw Error("Expected value must be a string");const i=s||t.me;return i&&i instanceof Element?i.getAttribute(n)===r:0},validate:t=>On(t,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??Sn(t,0,"attributeWithValue","attribute name")??Sn(t,1,"attributeWithValue","expected value")??(3>t.length||null==t[2]||t[2]instanceof Element?null:"attributeWithValue element must be an Element")},classReference:{name:"classReference",category:"Reference",evaluatesTo:"Array",operators:["."],async evaluate(t,...e){const[n]=e;if("string"!=typeof n)throw Error("Class name must be a string");const r=n.startsWith(".")?n.slice(1):n,s=document.getElementsByClassName(r);return Array.from(s)},validate:t=>An(t,"classReference","className")},idReference:{name:"idReference",category:"Reference",evaluatesTo:"Element",operators:["#"],async evaluate(t,...e){const[n]=e;if("string"!=typeof n)throw Error("ID value must be a string");const r=n.startsWith("#")?n.slice(1):n;return document.getElementById(r)},validate:t=>An(t,"idReference","idValue")}};function ar(t){return Array.isArray(t)?t:null==t?[]:"string"==typeof t?[t]:t instanceof NodeList||t instanceof HTMLCollection||"number"==typeof t.length?Array.from(t):[t]}function cr(t,e){const n=t.registry?.get(e);if(!n)throw Error(`Expression '${e}' not in ExecutionContext.registry. The bundle's ExpressionRegistry must include this expression's category. Use createExpressionRegistry() with the relevant category objects (referencesExpressions, logicalExpressions, conversionExpressions, positionalExpressions, propertiesExpressions, specialExpressions, mathematicalExpressions).`);return n}function ur(t){if(t&&"object"==typeof t&&"success"in t){if(t.success)return"value"in t?t.value:void 0;const e=t.errors||[];throw Error(e.length>0?e[0].message:"Expression evaluation failed")}return t}async function lr(t,e){if(!t)throw Error("Cannot evaluate null or undefined AST node");if("literal"===t.type)return t.value;if("identifier"===t.type)return gr(t,e);const n=t;switch(t.type){case"literal":return function(t){return t.value}(n);case"identifier":return gr(n,e);case"binaryExpression":return async function(t,e){const n=t.operator,r=t.right,s=t.left;if("="===n){const n=await lr(t.right,e);if("identifier"===s?.type&&"string"==typeof s.name){const t=s.name;return t.startsWith("$")?It(e,t.slice(1),n):"global"===s.scope?It(e,t,n):"element"===s.scope?nn(e,t,n):(e.locals||(e.locals=new Map),e.locals.set(t,n)),n}throw Error(`Assignment target must be a variable identifier (got '${s?.type??"undefined"}')`)}if("has"===n||"have"===n){const n=await lr(t.left,e);return n instanceof Element&&"selector"===r.type&&"string"==typeof r.value&&r.value.startsWith(".")?n.classList.contains(r.value.slice(1)):0}if("in"===n||"is in"===n){const n="callExpression"===s?.type&&"identifier"===s.callee?.type?s.callee.name:null;if(("first"===n||"last"===n)&&Array.isArray(s.arguments)){const r=s.arguments[0];if("selector"===r?.type&&"string"==typeof r.value){const s=await lr(t.right,e);if(s&&"function"==typeof s.querySelectorAll){const t=Array.from(s.querySelectorAll(r.value));return 0===t.length?null:"first"===n?t[0]:t[t.length-1]}}}if("selector"===s?.type&&s.fromQuery&&"string"==typeof s.value){const n=await lr(t.right,e),r=n&&"function"==typeof n.querySelectorAll?n:null;if(r)return Array.from(r.querySelectorAll(s.value))}}if("of"===n&&"selector"===s?.type&&"string"==typeof s.value&&/^\*[a-zA-Z][\w-]*$/.test(s.value)){const n=await lr(t.right,e);return cr(e,"styleRef").evaluate(e,s.value.slice(1),n)}if("of"===n){const n=vr(t.left);if(n){const r=await lr(t.right,e);let s=r;for(const t of n){if(null==s)return;s=yn(s)?En(s,t):s[t]}return"function"==typeof s?s.bind(r):s}}const i=await lr(t.left,e);if("and"===n){if(!i)return i;const n=await lr(t.right,e);return cr(e,"and").evaluate(e,i,n)}if("or"===n){if(i)return i;const n=await lr(t.right,e);return cr(e,"or").evaluate(e,i,n)}const o=await lr(t.right,e),a=t=>"string"==typeof t?t.toLowerCase():t,c=t.ignoringCase?a(i):i,u=t.ignoringCase?a(o):o;switch(n){case"+":{let n=i,r=o;return t.coerceNumeric&&("string"==typeof n&&(n=an(n)),"string"==typeof r&&(r=an(r))),"string"==typeof n||"string"==typeof r?(n??"")+""+(r??""):Array.isArray(n)?Array.isArray(r)?[...n,...r]:[...n,r]:ur(await cr(e,"addition").evaluate(e,{left:n,right:r}))}case"-":return ur(await cr(e,"subtraction").evaluate(e,{left:i,right:o}));case"*":return ur(await cr(e,"multiplication").evaluate(e,{left:i,right:o}));case"/":return ur(await cr(e,"division").evaluate(e,{left:i,right:o}));case"%":case"mod":return ur(await cr(e,"modulo").evaluate(e,{left:i,right:o}));case"^":case"**":return ur(await cr(e,"power").evaluate(e,{left:i,right:o}));case">":case"is greater than":return cr(e,"greaterThan").evaluate(e,i,o);case"<":case"is less than":return cr(e,"lessThan").evaluate(e,i,o);case">=":case"is greater than or equal to":return cr(e,"greaterThanOrEqual").evaluate(e,i,o);case"<=":case"is less than or equal to":return cr(e,"lessThanOrEqual").evaluate(e,i,o);case"==":return cr(e,"equals").evaluate(e,c,u);case"is":case"am":case"equals":case"is equal":case"is equal to":{const n=Er(t,i,o);return void 0!==n?n:cr(e,"equals").evaluate(e,c,u)}case"!=":return cr(e,"notEquals").evaluate(e,c,u);case"is not":case"is not equal":case"is not equal to":{const n=Er(t,i,o);return void 0!==n?!n:cr(e,"notEquals").evaluate(e,c,u)}case"===":case"really equals":case"is really":case"is really equal to":return cr(e,"strictEquals").evaluate(e,c,u);case"!==":case"is not really":case"is not really equal to":return cr(e,"strictNotEquals").evaluate(e,c,u);case"as":return cr(e,"as").evaluate(e,i,kr(o));case"contains":case"contain":case"includes":case"include":return cr(e,"contains").evaluate(e,c,u);case"does not contain":case"do not contain":case"does not contains":case"does not include":return cr(e,"doesNotContain").evaluate(e,c,u);case"starts with":return cr(e,"startsWith").evaluate(e,c,u);case"ends with":return cr(e,"endsWith").evaluate(e,c,u);case"does not start with":return!await cr(e,"startsWith").evaluate(e,c,u);case"does not end with":return!await cr(e,"endsWith").evaluate(e,c,u);case"match":case"matches":return cr(e,"matches").evaluate(e,c,wr(t.right,u));case"does not match":case"do not match":return!await cr(e,"matches").evaluate(e,c,wr(t.right,u));case"in":case"is in":case"am in":return br(i,o);case"is not in":case"am not in":return!br(i,o);case"of":return o&&"object"==typeof o?o[i]:void 0;case"precedes":return xr(i,o,Node.DOCUMENT_POSITION_FOLLOWING);case"does not precede":return!xr(i,o,Node.DOCUMENT_POSITION_FOLLOWING);case"follows":return xr(i,o,Node.DOCUMENT_POSITION_PRECEDING);case"does not follow":return!xr(i,o,Node.DOCUMENT_POSITION_PRECEDING);default:throw Error("Unknown binary operator: "+n)}}(n,e);case"asExpression":return async function(t,e){const n=await lr(t.expression,e),r=kr(t.targetType);return cr(e,"as").evaluate(e,n,r)}(n,e);case"betweenExpression":return async function(t,e){const n=await lr(t.value,e),r=await lr(t.min,e),s=await lr(t.max,e),i=t=>"string"==typeof t?t.toLowerCase():t,[o,a,c]=t.ignoringCase?[i(n),i(r),i(s)]:[n,r,s],u=await cr(e,"between").evaluate(e,o,a,c);return t.negated?!u:u}(n,e);case"typeCheckExpression":return async function(t,e){const n=function(t,e,n){if(null==t&&n)return 1;if(Object.prototype.toString.call(t).slice(8,-1)===e)return 1;const r=globalThis[e];return"function"==typeof r&&t instanceof r}(await lr(t.value,e),t.typeName+"",0!=t.nullOk);return t.negated?!n:n}(n,e);case"collectionExpression":return async function(t,e){const n=await lr(t.collection,e);if(null==n)return n;const r=async(t,n)=>lr(t,{...e,it:n});switch(t.operator){case"where":return async function(t,e,n){const r=ar(t),s=[];for(const t of r)await n(e,t)&&s.push(t);return s}(n,t.right,r);case"sorted by":return async function(t,e,n,r){const s=[...ar(t)],i=await Promise.all(s.map(t=>r(e,t))),o=s.map((t,e)=>e);o.sort((t,e)=>{const n=i[t],r=i[e];return n===r?0:null==n?1:null==r||r>n?-1:1});const a=o.map(t=>s[t]);return"desc"===n?a.reverse():a}(n,t.right,t.order??"asc",r);case"mapped to":return async function(t,e,n){const r=ar(t);return Promise.all(r.map(t=>n(e,t)))}(n,t.right,r);case"split by":return i=await lr(t.right,e),null==(s=n)?[]:(s+"").split(null==i?"":i+"");case"joined by":return function(t,e){const n=null==e?"":e+"";return ar(t).map(t=>null==t?"":t+"").join(n)}(n,await lr(t.right,e));default:throw Error("Unknown collection operator: "+t.operator)}var s,i}(n,e);case"unaryExpression":return async function(t,e){const n=t.operand??t.argument;if(!n)throw Error(`Unary expression has no operand (operator: ${t.operator})`);const r=await lr(n,e);switch(t.operator){case"not":case"!":return cr(e,"not").evaluate(e,r);case"no":return cr(e,"no").evaluate(e,r);case"-":return-r;case"+":return+r;case"exists":case"some":return cr(e,"exists").evaluate(e,r);case"does not exist":return cr(e,"doesNotExist").evaluate(e,r);case"is empty":return cr(e,"isEmpty").evaluate(e,r);case"is not empty":return cr(e,"isNotEmpty").evaluate(e,r);default:throw Error("Unknown unary operator: "+t.operator)}}(n,e);case"memberExpression":return async function(t,e){const n=await lr(t.object,e);if(t.computed){const r=await lr(t.property,e);return Array.isArray(n)&&"number"==typeof r&&0>r?n[n.length+r]:n?.[r]}return Cr(n,t.property.name,e)}(n,e);case"propertyAccess":return async function(t,e){let n=await lr(t.object,e);for(const r of(t.property+"").split(".")){if(null==n)return;n=await Cr(n,r,e)}return n}(n,e);case"callExpression":return async function(t,e){const n=await lr(t.callee,e);if(t.isConstructor&&"function"==typeof n)return new n(...await Promise.all(t.arguments.map(t=>lr(t,e))));if("identifier"===t.callee.type){const r=t.callee.name,s=await async function(t,e,n){return Tr.has(e)?Promise.all(t.map(t=>"identifier"===t.type&&t.name?t.name:"selector"===t.type&&t.value?t.value:lr(t,n))):Promise.all(t.map(t=>lr(t,n)))}(t.arguments,r,e);switch(r){case"closest":return cr(e,"closest").evaluate(e,...s);case"previous":case"next":{const n=t.relativePositional;if(n){const t=n.from?Or(await lr(n.from,e)):e.me,i=n.within?Or(await lr(n.within,e)):void 0,o=n.inElt?await lr(n.inElt,e):void 0;return cr(e,r).evaluate(e,s[0],t,{within:i,inElt:o,inSearch:n.inSearch,wrapping:n.wrapping})}return cr(e,r).evaluate(e,...s)}case"first":return cr(e,"first").evaluate(e,...s);case"last":return cr(e,"last").evaluate(e,...s);default:if("function"==typeof n)return n(...s);throw Error("Cannot call non-function: "+r)}}if("function"==typeof n){const r=await Promise.all(t.arguments.map(t=>lr(t,e)));if("memberExpression"===t.callee.type&&t.callee.object){const s=await lr(t.callee.object,e);return n.apply(s,r)}return n(...r)}throw Error("Cannot call non-function")}(n,e);case"selector":return async function(t,e){let n=t.value;if("string"==typeof n&&!t.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(n))return cr(e,"styleRef").evaluate(e,n.slice(1));if("string"==typeof n&&t.fromQuery&&/\$[^=]/.test(n)){const{selector:r,elements:s}=await async function(t,e){const n=jr(t),r=await Promise.all(n.filter(t=>"expr"in t).map(t=>pr(t.expr,e)));return Mr(n,r)}(n,e),i=Lr(t,r);s.forEach((t,e)=>t.setAttribute("data-hs-query-id",e+""));try{return await cr(e,"elementWithSelector").evaluate(e,i)}finally{s.forEach(t=>t.removeAttribute("data-hs-query-id"))}}"string"==typeof n&&!t.fromQuery&&n.includes("{")&&(n=await function(t,e){return Nr(t,/\{([^}]*)\}/g,async(t,n)=>(await pr(n.trim(),e)??"")+"")}(n,e));const r="string"==typeof n?Lr(t,n):n,s=await cr(e,"elementWithSelector").evaluate(e,r);return!t.fromQuery&&"string"==typeof n&&n.startsWith("#")&&Array.isArray(s)?s[0]??null:s}(n,e);case"contextReference":return async function(t,e){switch(t.contextType){case"me":case"you":case"it":return cr(e,t.contextType).evaluate(e);case"my":case"myself":case"I":return cr(e,"me").evaluate(e);case"your":case"yourself":return cr(e,"you").evaluate(e);case"its":return cr(e,"it").evaluate(e);case"event":return e.event;case"target":return e.target??e.event?.target??cr(e,"me").evaluate(e);case"body":return"undefined"!=typeof document?document.body:void 0;case"document":return cr(e,"document").evaluate(e);case"window":return cr(e,"window").evaluate(e);default:return}}(n,e);case"possessiveExpression":return async function(t,e){const n=await lr(t.object,e),r=t.property.name;return cr(e,"possessive").evaluate(e,n,r)}(n,e);case"eventHandler":return async function(t,e){return{event:t.event,selector:t.selector,commands:t.commands,handler:async n=>{const r={...e,event:n,target:n.target,currentTarget:n.currentTarget};for(const e of t.commands)await lr(e,r)}}}(n,e);case"conditionalExpression":return async function(t,e){return await lr(t.test,e)?lr(t.consequent,e):t.alternate?lr(t.alternate,e):void 0}(n,e);case"string":return n.value;case"arrayLiteral":return async function(t,e){const n=[];for(const r of t.elements)n.push(await lr(r,e));return n}(n,e);case"objectLiteral":return async function(t,e){const n={};for(const r of t.properties){const t=r.key;let s;s="identifier"===t.type?t.name:"literal"===t.type&&"string"===t.valueType?t.value:await lr(t,e)+"",n[s]=await lr(r.value,e)}return n}(n,e);case"attributeAccess":return async function(t,e){const n=t.attributeName;return e.me&&e.me instanceof Element?e.me.getAttribute(n):"@"+n}(n,e);case"propertyOfExpression":return async function(t,e){const n=t.property;if("identifier"!==n?.type)throw Error('Property name must be an identifier in "the X of Y" pattern');const r=n.name,s=await lr(t.target,e);if(null==s)throw Error(`Cannot access property "${r}" of ${s}`);return cr(e,"possessive").evaluate(e,s,r)}(n,e);case"templateLiteral":return async function(t,e){let n=t.value;return n=await Nr(n,/\$([a-zA-Z_$][a-zA-Z0-9_.$]*|\d+)/g,async(t,n)=>{try{if(/^\d+$/.test(n))return n;if(n.includes(".")){const t=n.split(".");let r=Ar(t[0],e);for(let e=1;t.length>e&&null!=r;e++)r=r[t[e]];return(r??"")+""}return(Ar(n,e)??"")+""}catch{return""}}),n=await Nr(n,/\$(?:\{([^}]+)\}|\(([^)]+)\))/g,async(t,n,r)=>{const s=n||r;try{return await pr(s,e)+""}catch{return"undefined"}}),n}(n,e);case"stringPostfix":return async function(t,e){return`${await lr(t.expression,e)}${t.unit}`}(n,e);case"blockLiteral":return Sr(n,e);default:{const n=kt.get(t.type);if(n)return n(t,e);throw Error("Unknown AST node type: "+t.type)}}}class hr extends Error{constructor(t){super(`Expression node "${t}" is not synchronously evaluable`),this.name="NotSyncEvaluable"}}function fr(t,e){const n=t;switch(n?.type){case"literal":case"string":return n.value;case"selector":return function(t,e){const n=t.value;if("string"!=typeof n)throw new hr("selector");if(!t.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(n))throw new hr("selector");if(t.fromQuery&&/\$[^=]/.test(n)){const{selector:r,elements:s}=function(t,e){const n=jr(t),r=n.filter(t=>"expr"in t).map(t=>dr(t.expr,e));return Mr(n,r)}(n,e),i=Lr(t,r),o=e?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!o)throw new hr("selector");s.forEach((t,e)=>t.setAttribute("data-hs-query-id",e+""));try{return Array.from(o.querySelectorAll(i))}finally{s.forEach(t=>t.removeAttribute("data-hs-query-id"))}}const r=!t.fromQuery&&n.includes("{")?function(t,e){return t.replace(/\{([^}]*)\}/g,(t,n)=>(dr(n.trim(),e)??"")+"")}(n,e):n,s=Lr(t,r),i=e?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!i)throw new hr("selector");const o=Array.from(i.querySelectorAll(s));return!t.fromQuery&&r.startsWith("#")?o[0]??null:o}(n,e);case"identifier":return function(t,e,n){return"me"===t||"my"===t||"I"===t?e.me:"you"===t||"your"===t||"yourself"===t?e.you:"it"===t||"its"===t?e.it??e.result:"window"===t?"undefined"!=typeof window?window:globalThis:"document"===t?"undefined"!=typeof document?document:void 0:"element"===n?en(e,t):e.locals?.has(t)?e.locals.get(t):e.globals?.has(t)?e.globals.get(t):t.startsWith("$")&&e.globals?.has(t.slice(1))?e.globals.get(t.slice(1)):void 0!==e[t]?e[t]:"undefined"!=typeof globalThis&&t in globalThis?globalThis[t]:void 0}(n.name,e,n.scope);case"contextReference":return function(t,e){switch(t){case"me":return e.me;case"you":return e.you;case"it":return e.it??e.result;case"event":return e.event;case"target":return e.target??e.event?.target??e.me;default:throw new hr("contextReference")}}(n.contextType,e);case"arrayLiteral":return n.elements.map(t=>fr(t,e));case"objectLiteral":return function(t,e){const n={};for(const r of t.properties){const t=r.key;let s;s="identifier"===t.type?t.name:"literal"===t.type&&"string"===t.valueType?t.value:fr(t,e)+"",n[s]=fr(r.value,e)}return n}(n,e);case"asExpression":return er(fr(n.expression,e),kr(n.targetType),e);case"stringPostfix":return`${fr(n.expression,e)}${n.unit}`;case"blockLiteral":return Sr(n,e);case"memberExpression":{const t=fr(n.object,e);if(null==t)return;if(t instanceof Element||Array.isArray(t)||"undefined"!=typeof Node&&t instanceof Node)throw new hr("memberExpression");const r=t[n.computed?fr(n.property,e)+"":n.property?.name];return"function"==typeof r?r.bind(t):r}default:throw new hr(n?.type??"unknown")}}function dr(t,e){const n=We(t);if(!n.success||!n.node){const t=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(t?.message??"unknown error"))}return fr(n.node,e)}async function pr(t,e){const n=We(t);if(!n.success||!n.node){const t=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(t?.message??"unknown error"))}const r=e.registry?e:{...e,registry:await yr()};return lr(n.node,r)}let mr=null;async function yr(){if(!mr){const t=await Promise.resolve().then(function(){return Oo});mr=t.createFullExpressionRegistry()}return mr}async function gr(t,e){const n=t.name;return"me"===n||"my"===n||"I"===n?cr(e,"me").evaluate(e):"you"===n||"your"===n||"yourself"===n?cr(e,"you").evaluate(e):"it"===n||"its"===n?cr(e,"it").evaluate(e):"window"===n?cr(e,"window").evaluate(e):"document"===n?cr(e,"document").evaluate(e):"global"===t.scope&&e.globals?.has(n)?($t(n,e),e.globals.get(n)):"element"===t.scope?en(e,n):e.locals&&e.locals.has(n)?(Lt(n,e),e.locals.get(n)):e.globals&&e.globals.has(n)?(n.startsWith("$")&&$t(n.slice(1),e),e.globals.get(n)):n.startsWith("$")&&e.globals&&e.globals.has(n.slice(1))?($t(n.slice(1),e),e.globals.get(n.slice(1))):void 0!==e[n]?e[n]:"undefined"!=typeof globalThis&&n in globalThis?globalThis[n]:void 0}function vr(t){const e=t;if(!e)return null;if("identifier"===e.type&&"string"==typeof e.name)return[e.name];if("memberExpression"===e.type&&!e.computed){const t=vr(e.object);if(!t)return null;const n=e.property,r="identifier"===n?.type&&"string"==typeof n.name?n.name:"string"==typeof n?.value?n.value:null;return null==r?null:[...t,r]}return null}function br(t,e){return Array.isArray(e)?e.includes(t):"string"==typeof e?e.includes(t+""):t instanceof Node&&e instanceof Node?t===e||e.contains(t):null!=e&&"object"==typeof e&&t in e}function wr(t,e){return t&&"selector"===t.type&&"string"==typeof t.value?t.value:e}function Er(t,e,n){if(void 0!==n)return;const r=t.right;if(!r||"identifier"!==r.type||"string"!=typeof r.name)return;if(null==e||"object"!=typeof e)return;const s=e[r.name];return"boolean"==typeof s?1==s:void 0}function xr(t,e,n){return t instanceof Node&&e instanceof Node&&0!==(t.compareDocumentPosition(e)&n)}function kr(t){if("string"==typeof t)return t;if(t&&"object"==typeof t){if("string"==typeof t.name)return t.name;if("string"==typeof t.value)return t.value}return t+""}function Sr(t,e){const n=t.parameters??[];return(...r)=>{const s=new Map(e.locals??new Map);n.forEach((t,e)=>s.set(t,r[e]));const i={...e,locals:s};try{return fr(t.body,i)}catch(e){if(e instanceof hr)return lr(t.body,i);throw e}}}function Ar(t,e){return e.locals?.has(t)?(Lt(t,e),e.locals.get(t)):"me"===t&&e.me?e.me:"you"===t&&e.you?e.you:"it"===t&&e.it?e.it:"result"===t&&e.result?e.result:"undefined"!=typeof window&&"window"===t?window:e.globals?.has(t)?e.globals.get(t):void 0}async function Nr(t,e,n){const r=[];let s;for(;null!==(s=e.exec(t));)r.push({index:s.index,length:s[0].length,replacement:await n(s[0],...s.slice(1))});let i=t;for(let t=r.length-1;t>=0;t--){const{index:e,length:n,replacement:s}=r[t];i=i.substring(0,e)+s+i.substring(e+n)}return i}function Cr(t,e,n){if("string"==typeof e&&e.startsWith("@")){const n=e.substring(1);return t&&"function"==typeof t.getAttribute?t.getAttribute(n):void 0}return t instanceof Element&&"string"==typeof e?En(t,e):ir(t)&&!(e in t)?cr(n,"possessive").evaluate(n,t,e):t?.[e]}const Tr=new Set(["closest","previous","next"]);function Or(t){return t instanceof Element?t:Array.isArray(t)&&t[0]instanceof Element?t[0]:void 0}const $r=RegExp("(\\.[a-zA-Z0-9_-]+):(?!(hover|active|focus|visited|link|focus-within|focus-visible|first-child|last-child|only-child|nth-child|nth-last-child|nth-of-type|nth-last-of-type|first-of-type|last-of-type|only-of-type|empty|root|target|lang|dir|not|has|is|where|matches|before|after|first-letter|first-line|selection|placeholder|marker|backdrop|enabled|disabled|checked|indeterminate|required|optional|valid|invalid|in-range|out-of-range|read-only|read-write|default|defined|fullscreen|modal|picture-in-picture|autofill)(?![a-zA-Z0-9_-]))","g"),Rr=/[:&()[\]/]/g;function Lr(t,e){return t.fromQuery||!e.startsWith(".")||e.includes("{")?function(t){return t.replace($r,"$1\\:")}(e):function(t){return t[0]+t.slice(1).replace(Rr,"\\$&")}(e)}const Ir=/\$\{([^}]+)\}|\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g;function jr(t){const e=[];let n,r=0;for(Ir.lastIndex=0;null!==(n=Ir.exec(t));)n.index>r&&e.push({lit:t.slice(r,n.index)}),e.push({expr:n[1]??n[2]}),r=n.index+n[0].length;return t.length>r&&e.push({lit:t.slice(r)}),e}function Mr(t,e){let n="";const r=[];let s=0;for(const i of t){if("lit"in i){n+=i.lit;continue}const t=e[s++];yn(t)?(n+=`[data-hs-query-id='${r.length}']`,r.push(t)):n+=(t??"")+""}return{selector:n,elements:r}}class Dr{constructor(t){this.elementCleanups=new WeakMap,this.elementCount=0,this.typeCounts={listener:0,observer:0,interval:0,timeout:0,custom:0},this.globalCleanups=[],this.debugMode=t?.debug??0}registerListener(t,e,n,r,s){this.addCleanup(t,{type:"listener",target:e,eventName:n,cleanup:()=>{e.removeEventListener(n,r,s),this.debugMode&&lt(`CleanupRegistry: Removed listener '${n}'`)},description:n+" listener"})}registerObserver(t,e){this.addCleanup(t,{type:"observer",cleanup:()=>{e.disconnect(),this.debugMode&&lt("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(t,e){this.addCleanup(t,{type:"interval",cleanup:()=>{clearInterval(e),this.debugMode&&lt("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(t,e){this.addCleanup(t,{type:"timeout",cleanup:()=>{clearTimeout(e),this.debugMode&&lt("CleanupRegistry: Cleared timeout")},description:"Timeout"})}registerCustom(t,e,n){this.addCleanup(t,{type:"custom",cleanup:e,description:n||"Custom cleanup"})}registerGlobal(t,e="custom",n){this.globalCleanups.push({type:e,cleanup:t,description:n||"Global cleanup"}),this.debugMode&&lt("CleanupRegistry: Registered global cleanup: "+(n||e))}addCleanup(t,e){const n=this.elementCleanups.get(t);n?n.push(e):(this.elementCleanups.set(t,[e]),this.elementCount++),this.typeCounts[e.type]++,this.debugMode&&lt(`CleanupRegistry: Registered ${e.type} for element`,t)}cleanupElement(t){const e=this.elementCleanups.get(t);if(!e||0===e.length)return 0;let n=0;for(const t of e){try{t.cleanup(),n++}catch(t){this.debugMode&&lt("CleanupRegistry: Error during cleanup:",t)}this.typeCounts[t.type]--}return this.elementCleanups.delete(t),this.elementCount--,this.debugMode&&lt(`CleanupRegistry: Cleaned up ${n} resources for element`),n}cleanupElementTree(t){let e=this.cleanupElement(t);const n=t.querySelectorAll("*");for(const t of n)e+=this.cleanupElement(t);return e}cleanupGlobal(){let t=0;for(const e of this.globalCleanups)try{e.cleanup(),t++}catch(t){this.debugMode&&lt("CleanupRegistry: Error during global cleanup:",t)}return this.globalCleanups=[],this.debugMode&&lt(`CleanupRegistry: Cleaned up ${t} global resources`),t}cleanupAll(){return this.cleanupGlobal()}hasCleanups(t){const e=this.elementCleanups.get(t);return void 0!==e&&e.length>0}getCleanupCount(t){const e=this.elementCleanups.get(t);return e?.length??0}getStats(){let t=0,e=0,n=0,r=0,s=0;for(const i of this.globalCleanups)switch(i.type){case"listener":t++;break;case"observer":e++;break;case"interval":n++;break;case"timeout":r++;break;case"custom":s++}return{elementsTracked:this.elementCount,listeners:this.typeCounts.listener+t,observers:this.typeCounts.observer+e,intervals:this.typeCounts.interval+n,timeouts:this.typeCounts.timeout+r,custom:this.typeCounts.custom+s,global:this.globalCleanups.length}}setDebugMode(t){this.debugMode=t}}class Pr{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(t,e){const n=t.toLowerCase();this.sources.has(n)&&lt("[EventSourceRegistry] Overwriting existing event source: "+t),this.sources.set(n,e)}unregister(t){const e=t.toLowerCase(),n=this.sources.get(e);if(n){for(const[t,n]of this.subscriptions.entries())n.source===e&&(n.unsubscribe(),this.subscriptions.delete(t));return n.destroy?.(),this.sources.delete(e)}return 0}get(t){return this.sources.get(t.toLowerCase())}has(t){return this.sources.has(t.toLowerCase())}subscribe(t,e,n){const r=this.get(t);if(!r)return void lt("[EventSourceRegistry] Unknown event source: "+t);r.initialize?.();const s=r.subscribe(e,n);return this.subscriptions.set(s.id,s),s}unsubscribe(t){const e=this.subscriptions.get(t);return e?(e.unsubscribe(),this.subscriptions.delete(t)):0}getSourceNames(){return Array.from(this.sources.keys())}getSubscriptions(){return Array.from(this.subscriptions.values())}findSourceForEvent(t){for(const[e,n]of this.sources.entries())if(n.supports?.(t)??n.supportedEvents?.includes(t))return e}generateId(){return`sub_${this.nextId++}_${Date.now().toString(36)}`}destroy(){for(const t of this.subscriptions.values())t.unsubscribe();this.subscriptions.clear();for(const t of this.sources.values())t.destroy?.();this.sources.clear()}}class Fr{constructor(){this.providers=new Map,this.globalProviders=new Map}register(t,e,n){const r=t.toLowerCase();this.providers.set(r,"function"==typeof e?{name:r,provide:e,cache:n?.cache??1,description:n?.description,dependencies:n?.dependencies}:e)}registerGlobal(t,e,n){const r=t.toLowerCase();this.globalProviders.set(r,"function"==typeof e?{name:r,provide:e,cache:n?.cache??1,description:n?.description,dependencies:n?.dependencies}:e)}unregister(t){return this.providers.delete(t.toLowerCase())}unregisterGlobal(t){return this.globalProviders.delete(t.toLowerCase())}get(t){const e=t.toLowerCase();return this.providers.get(e)??this.globalProviders.get(e)}has(t){const e=t.toLowerCase();return this.providers.has(e)||this.globalProviders.has(e)}async resolve(t,e,n){const r=this.get(t);if(!r)return;const s="__provider_"+r.name;if(r.cache&&n?.has(s))return n.get(s);if(r.dependencies)for(const t of r.dependencies)await this.resolve(t,e,n);const i=await r.provide(e);return r.cache&&n&&n.set(s,i),i}resolveSync(t,e,n){const r=this.get(t);if(!r)return;const s="__provider_"+r.name;if(r.cache&&n?.has(s))return n.get(s);const i=r.provide(e);if(i instanceof Promise)throw Error(`Context provider '${t}' is async. Use resolve() instead of resolveSync().`);return r.cache&&n&&n.set(s,i),i}enhance(t){const e=this,n=new Map;return new Proxy(t,{get(t,r,s){if("string"==typeof r&&e.get(r))try{return e.resolveSync(r,t,n)}catch{return e.resolve(r,t,n)}return Reflect.get(t,r,s)},has:(t,n)=>"string"==typeof n&&e.has(n)?1:Reflect.has(t,n)})}async resolveAll(t){const e=new Map,n={},r=[...this.globalProviders.entries(),...this.providers.entries()];for(const[s,i]of r)try{n[s]=await this.resolve(s,t,e)}catch(t){lt(`[ContextProviderRegistry] Failed to resolve '${s}':`,t),n[s]=void 0}return n}getProviderNames(){return[...new Set([...this.globalProviders.keys(),...this.providers.keys()])]}clear(){this.providers.clear(),this.globalProviders.clear()}}const Br={evaluate:(t,e)=>lr(t,e)};class _r{static toTyped(t){return{me:t.me,...void 0!==t.owner&&{owner:t.owner},it:t.it,you:t.you,result:t.result,...void 0!==t.event&&{event:t.event},variables:t.variables||new Map,locals:t.locals||new Map,globals:t.globals||new Map,...void 0!==t.events&&{events:t.events},meta:t.meta||{},...void 0!==t.registry&&{registry:t.registry},expressionStack:[],evaluationDepth:0,validationMode:"strict",evaluationHistory:[]}}static fromTyped(t,e){return{...e,me:t.me,it:t.it,you:t.you,result:t.result,...void 0!==t.event&&{event:t.event},...void 0!==t.variables&&{variables:t.variables},locals:t.locals,globals:t.globals,...void 0!==t.events&&{events:t.events},...void 0!==t.meta&&{meta:t.meta}}}}class Vr{constructor(t,e,n){this.impl=t,this.hookRegistry=n??null}setHookRegistry(t){this.hookRegistry=t}createHookContext(t,e,n={}){return{commandName:this.name,element:t.me instanceof Element?t.me:null,args:e,modifiers:n,event:t.event??void 0,executionContext:t}}get name(){const t=this.impl.name;if(t)return t;const e=this.impl.metadata?.name;return"string"==typeof e?e:""}get metadata(){const t=this.impl.metadata?.syntax;return{description:this.impl.metadata?.description||"",examples:this.impl.metadata?.examples||[],syntax:Array.isArray(t)?t.join(" | "):t||""}}async execute(t,...e){const n=e[0],r=this.createHookContext(t,e,n&&"object"==typeof n&&"modifiers"in n&&n.modifiers||{});try{if(at(`CommandAdapterV2: Executing '${this.name}' with args:`,e),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(r),this.hookRegistry?.shouldIntercept(this.name,r))return void at(`CommandAdapterV2: '${this.name}' intercepted by hook`);const s=_r.toTyped(t);let i,o;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(at(`CommandAdapterV2: '${this.name}' has parseInput(), calling it`),n&&"object"==typeof n&&("args"in n||"modifiers"in n)){const e=n.modifiers,r=e?.when||e?.where;if(r&&!await lr(r,t))return void at(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);i=await this.impl.parseInput({args:n.args||[],modifiers:e||{},commandName:n.commandName},Br,t)}else i=e;else at(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),i=e;if(at("CommandAdapterV2: Calling execute with parsed input:",i),2===this.impl.execute.length)o=await this.impl.execute(i,s);else{const t=Array.isArray(i)?i:[i];o=await this.impl.execute(s,...t)}return at("CommandAdapterV2: Command result:",o),Object.assign(t,_r.fromTyped(s,t)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(r,o),o}catch(t){if(Jr(t)||at(`CommandAdapterV2: Error executing '${this.name}':`,t),this.hookRegistry&&t instanceof Error)throw await this.hookRegistry.runOnError(r,t);throw t}}validate(t){return this.impl.validate?this.impl.validate(t):{isValid:1,errors:[],suggestions:[]}}}class qr{constructor(t,e){this.adapters=new Map,this.implementations=new Map,this.hookRegistry=e}setHookRegistry(t){this.hookRegistry=t;for(const e of this.adapters.values())e.setHookRegistry(t);lt(`CommandRegistryV2: Hook registry set and propagated to ${this.adapters.size} adapters`)}getHookRegistry(){return this.hookRegistry}register(t){const e=t.name||t.metadata?.name;if(!e||"string"!=typeof e)throw Error("Cannot register command: no name found. Provide a 'name' property or 'metadata.name' on the implementation.");const n=e.toLowerCase();lt(`CommandRegistryV2: Registering command '${n}'`),this.implementations.set(n,t);const r=new Vr(t,void 0,this.hookRegistry);this.adapters.set(n,r),E.add(n);const s=t.metadata?.aliases;if(s&&Array.isArray(s))for(const e of s){const n=e.toLowerCase();this.implementations.set(n,t),this.adapters.set(n,r),E.add(n)}}getAdapter(t){return this.adapters.get(t.toLowerCase())}has(t){return this.adapters.has(t.toLowerCase())}getCommandNames(){return Array.from(this.adapters.keys())}getImplementation(t){return this.implementations.get(t.toLowerCase())}getAdapters(){return new Map(this.adapters)}validateCommand(t,e){const n=this.getAdapter(t);return n?n.validate(e):{isValid:0,errors:[{type:"runtime-error",message:"Unknown command: "+t,suggestions:["Available commands: "+this.getCommandNames().join(", ")]}],suggestions:["Available commands: "+this.getCommandNames().join(", ")]}}}let Hr=null;function Ur(){return Hr||(Hr=function(){const t=new qr,e=new Pr,n=new Fr,r=new Set,s={commands:t,eventSources:e,context:n,use(i){if(r.has(i.name))lt(`[LokaScriptRegistry] Plugin '${i.name}' is already installed`);else{if(i.commands)for(const e of i.commands)t.register(e);if(i.eventSources)for(const t of i.eventSources)e.register(t.name,t);if(i.contextProviders)for(const{name:t,provide:e,options:r}of i.contextProviders)n.register(t,e,r);i.setup?.(s),r.add(i.name)}},reset(){r.clear()}};return s}()),Hr}class Wr{constructor(t={}){this.contextCache=new WeakMap;const e=Ur();this.options={enableContextProviders:t.enableContextProviders??1,enableEventSources:t.enableEventSources??1,registry:t.registry??{}},this.contextRegistry=this.options.registry.context??e.context,this.eventSourceRegistry=this.options.registry.eventSources??e.eventSources,lt(`[RegistryIntegration] Initialized (context=${this.options.enableContextProviders}, events=${this.options.enableEventSources})`)}enhanceContext(t){if(!this.options.enableContextProviders)return t;const e=this.contextCache.get(t);if(e)return e;try{const e=this.contextRegistry.enhance(t);return this.contextCache.set(t,e),lt(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),e}catch(e){return lt("[RegistryIntegration] Failed to enhance context: "+(e instanceof Error?e.message:e+"")),t}}getEventSource(t){if(!this.options.enableEventSources)return;const e=this.eventSourceRegistry.get(t);if(e)return lt(`[RegistryIntegration] Found event source for '${t}'`),e;const n=this.eventSourceRegistry.findSourceForEvent(t);if(n){const e=this.eventSourceRegistry.get(n);return lt(`[RegistryIntegration] Found event source '${n}' supporting '${t}'`),e}}hasEventSource(t){return void 0!==this.getEventSource(t)}subscribeToEventSource(t,e,n){if(!this.options.enableEventSources)throw Error("Event sources are disabled in this runtime");const r=this.eventSourceRegistry.subscribe(t,e,n);if(!r)throw Error(`Failed to subscribe to event source '${t}'`);return lt(`[RegistryIntegration] Subscribed to '${t}' event '${e.event}' (id: ${r.id})`),r}getEventSourceNames(){return this.eventSourceRegistry.getSourceNames()}getContextProviderNames(){return this.contextRegistry.getProviderNames()}destroy(){this.eventSourceRegistry.destroy(),this.contextCache=new WeakMap,lt("[RegistryIntegration] Destroyed")}}function zr(t){const e=Error(t.type.toUpperCase()+"_EXECUTION");return e["is"+t.type.charAt(0).toUpperCase()+t.type.slice(1)]=1,"returnValue"in t&&(e.returnValue=t.returnValue),e}function Jr(t){return t instanceof Error?null!==Je(t)||"HALT_EXECUTION"===t.message||"EXIT_COMMAND"===t.message||"EXIT_EXECUTION"===t.message:0}function Zr(t){if(void 0===t)return;let e=t;if(e&&"object"==typeof e){const t=e;if("result"in t&&"wasAsync"in t)e=t.result;else if("result"in t&&"executed"in t){if(e=t.result,t.preserveArrayResult)return void 0!==e?e:void 0}else if("lastResult"in t&&"type"in t)e=t.lastResult;else if("conditionResult"in t&&"executedBranch"in t){if(void 0===t.result)return;e=t.result}else"value"in t&&1===Object.keys(t).length||"value"in t&&"target"in t&&"targetType"in t?e=t.value:"data"in t&&"status"in t&&"headers"in t&&(e=t.data)}return Array.isArray(e)&&e.length>0&&(e=e[0]),e}function Gr(t){return null!==t&&"object"==typeof t&&"command"in t&&"selector"in t}const Xr=new WeakMap;class Yr{constructor(t){this.autoCleanupObserver=null,this.registryIntegration=null,this.runtimeWarnings=[],this.options={commandTimeout:1e4,enableErrorReporting:1,enableResultPattern:1,enableAutoCleanup:1,...t},this.registry=t.registry,this.expressionRegistry=t.expressionRegistry,this.behaviorRegistry=new Map,this.globalVariables=Ye,this.hookRegistry=new ze,t.hooks&&this.hookRegistry.register("default",t.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new Dr,this.options.enableAutoCleanup&&this.setupAutoCleanup(),0!=t.registryIntegration&&(this.registryIntegration=new Wr("object"==typeof t.registryIntegration?t.registryIntegration:{}),lt("RuntimeBase: Registry integration enabled")),this.behaviorAPI={has:t=>this.behaviorRegistry.has(t),get:t=>this.behaviorRegistry.get(t),set:(t,e)=>this.behaviorRegistry.set(t,e),resolve:null,install:async(t,e,n)=>await this.installBehaviorOnElement(t,e,n)}}setupAutoCleanup(){"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.autoCleanupObserver=new MutationObserver(t=>{const e=[];for(const n of t)for(const t of n.removedNodes)t instanceof Element&&e.push(t);e.length>0&&queueMicrotask(()=>{for(const t of e)if(!t.isConnected){const e=this.cleanupRegistry.cleanupElementTree(t);e>0&&lt(`RuntimeBase: Auto-cleaned ${e} resources for removed element`)}})}),document.body?this.autoCleanupObserver.observe(document.body,{childList:1,subtree:1}):document.addEventListener("DOMContentLoaded",()=>{this.autoCleanupObserver?.observe(document.body,{childList:1,subtree:1})},{once:1}))}registerHooks(t,e){this.hookRegistry.register(t,e)}unregisterHooks(t){return this.hookRegistry.unregister(t)}getRegisteredHooks(){return this.hookRegistry.getRegisteredNames()}cleanup(t){return this.cleanupRegistry.cleanupElement(t)}trackListener(t,e,n,r,s){this.cleanupRegistry.registerListener(t,e,n,r,s)}cleanupTree(t){return this.cleanupRegistry.cleanupElementTree(t)}getCleanupStats(){return this.cleanupRegistry.getStats()}getCleanupRegistry(){return this.cleanupRegistry}logError(...t){this.options.enableErrorReporting&&console.error(...t)}logWarn(...t){this.options.enableErrorReporting&&console.warn(...t)}destroy(){this.autoCleanupObserver&&(this.autoCleanupObserver.disconnect(),this.autoCleanupObserver=null),this.cleanupRegistry.cleanupAll(),this.hookRegistry.clear(),this.behaviorRegistry.clear(),lt("RuntimeBase: Destroyed")}hasErrorDiagnostics(t){const e=t.diagnostics;return!!e?.some(t=>"error"===t.severity)}getWarnings(){return this.runtimeWarnings}async execute(t,e){lt(`RUNTIME BASE: execute() called with node type: '${t.type}'`),e.registry||(e.registry=this.expressionRegistry),e.locals.has("_behaviors")||e.locals.set("_behaviors",this.behaviorAPI),e.locals.has("_runtimeExecute")||e.locals.set("_runtimeExecute",(t,n)=>this.execute(t,n||e));try{if(this.hasErrorDiagnostics(t)){const e=t.diagnostics?.[0];return lt("⚠️ RUNTIME: Skipping error node: "+(e?.message||"unknown error")),void this.runtimeWarnings.push(e?.message||"Skipped error node")}switch(t.type){case"command":if(this.options.enableResultPattern){const n=await this.processCommandWithResult(t,e);if(!Xe(n)){if("return"===n.error.type){const t=n.error.returnValue;return void 0!==t&&Object.assign(e,{it:t,result:t}),t}throw zr(n.error)}return n.value}try{return await this.processCommand(t,e)}catch(t){const n=Je(t);if(n?.isReturn){const t=n.returnValue;return void 0!==t&&Object.assign(e,{it:t,result:t}),t}throw t}case"eventHandler":return await this.executeEventHandler(t,e);case"event":{const n={type:"eventHandler",event:t.event,events:[t.event],commands:t.body||[],target:t.filter,modifiers:t.modifiers||{}};return await this.executeEventHandler(n,e)}case"behavior":return await this.executeBehaviorDefinition(t,e);case"Program":return await this.executeProgram(t,e);case"initBlock":case"block":return await this.executeBlock(t,e);case"sequence":case"CommandSequence":if(this.options.enableResultPattern){const n=t,r=await this.executeCommandSequenceWithResult(n.commands||[],e);if(!Xe(r))throw zr(r.error);return r.value}return await this.executeCommandSequence(t,e);case"objectLiteral":return await this.executeObjectLiteral(t,e);default:if(this.options.enableResultPattern){const n=await this.evaluateExpressionWithResult(t,e);if(!Xe(n))throw zr(n.error);return n.value}return await this.evaluateExpression(t,e)}}catch(t){throw t}}async processCommand(t,e){const{name:n,args:r,modifiers:s}=t,i=n.toLowerCase();if(at(`RUNTIME BASE: Processing command '${i}'`),this.registry.has(i)){const t=await this.registry.getAdapter(i);if(!t)throw Error(`Command '${i}' is registered but failed to load adapter.`);try{return await t.execute(e,{args:r||[],modifiers:s||{},commandName:i,runtime:this})}catch(t){throw Jr(t)||this.logError(`Error executing command '${i}':`,t),t}}const o=`Unknown command: ${n}. Ensure it is registered in the Runtime options.`;throw this.logWarn(o),Error(o)}toSignal(t){const e=Je(t);if(e){if(e.isHalt||"HALT_EXECUTION"===e.message)return{type:"halt"};if(e.isExit||"EXIT_COMMAND"===e.message)return{type:"exit",returnValue:e.returnValue};if(e.isBreak)return{type:"break"};if(e.isContinue)return{type:"continue"};if(e.isReturn)return{type:"return",returnValue:e.returnValue}}if(t instanceof Error){if("HALT_EXECUTION"===t.message)return{type:"halt"};if("EXIT_COMMAND"===t.message)return{type:"exit"}}return null}async processCommandWithResult(t,e){const{name:n,args:r,modifiers:s}=t,i=n.toLowerCase();if(at(`RUNTIME BASE (Result): Processing command '${i}'`),!this.registry.has(i)){const t=`Unknown command: ${n}. Ensure it is registered in the Runtime options.`;throw this.logWarn(t),Error(t)}const o=await this.registry.getAdapter(i);if(!o)throw Error(`Command '${i}' is registered but failed to load adapter.`);try{return Ze(await o.execute(e,{args:r||[],modifiers:s||{},commandName:i,runtime:this}))}catch(t){const e=this.toSignal(t);if(e)return Ge(e);throw this.logError(`Error executing command '${i}':`,t),t}}async executeCommandSequenceWithResult(t,e){let n;for(const r of t){if(this.hasErrorDiagnostics(r)){const t=r.diagnostics?.[0];lt("⚠️ RUNTIME: Skipping error node: "+(t?.message||"unknown error")),this.runtimeWarnings.push(t?.message||"Skipped error node");continue}if("command"===r.type){const t=await this.processCommandWithResult(r,e);if(!Xe(t)){const n=t.error;switch(n.type){case"halt":case"exit":case"break":case"continue":return t;case"return":return void 0!==n.returnValue&&Object.assign(e,{it:n.returnValue,result:n.returnValue}),Ze(n.returnValue)}}n=t.value}else{const t=await this.evaluateExpressionWithResult(r,e);if(!Xe(t))return t;n=t.value}}return Ze(n)}async evaluateExpression(t,e){const n=e.registry?e:{...e,registry:this.expressionRegistry},r=await lr(t,n);return Gr(r)?await this.executeCommandFromPattern(r.command,r.selector,e):r}async evaluateExpressionWithResult(t,e){const n=e.registry?e:{...e,registry:this.expressionRegistry},r=await async function(t,e){try{return Ze(await lr(t,e))}catch(t){if(t instanceof Error){const e=t;if(e.isHalt||"HALT_EXECUTION"===e.message)return Ge({type:"halt"});if(e.isExit||"EXIT_COMMAND"===e.message)return Ge({type:"exit",returnValue:e.returnValue});if(e.isBreak)return Ge({type:"break"});if(e.isContinue)return Ge({type:"continue"});if(e.isReturn)return Ge({type:"return",returnValue:e.returnValue})}throw t}}(t,n);if(!Xe(r))return r;const s=r.value;if(Gr(s)){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:s.command,args:[{type:"literal",value:s.selector}]},e);try{return Ze(await this.executeCommandFromPattern(s.command,s.selector,e))}catch(t){const e=this.toSignal(t);if(e)return Ge(e);throw t}}return Ze(s)}async executeCommandFromPattern(t,e,n){return this.processCommand({type:"command",name:t,args:[{type:"literal",value:e}]},n)}async executeProgram(t,e){if(!t.statements||!Array.isArray(t.statements))return;let n;const r=[],s=[],i=[];for(const e of t.statements)"eventHandler"===e.type?r.push(e):"initBlock"===e.type?s.push(e):i.push(e);for(const t of r)try{await this.execute(t,e)}catch(t){if(Jr(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of s)try{n=await this.execute(t,e)}catch(t){if(Jr(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of i)try{n=await this.execute(t,e)}catch(t){if(Jr(t)&&(t.isHalt||t.isExit))break;throw t}return n}async executeBlock(t,e){if(t.commands&&Array.isArray(t.commands))for(const n of t.commands)try{await this.execute(n,e)}catch(t){if(Jr(t)&&t.isHalt)break;throw t}}async executeCommandSequence(t,e){if(!t.commands||!Array.isArray(t.commands))return;let n;for(const r of t.commands)try{n=await this.execute(r,e)}catch(t){if(Jr(t)){if(t.isHalt||t.isExit)break;if(t.isReturn){if(void 0!==t.returnValue)return Object.assign(e,{it:t.returnValue,result:t.returnValue}),t.returnValue;break}if(t.isBreak)throw t}throw t}return n}async executeObjectLiteral(t,e){const n={};if(!t.properties)return n;for(const r of t.properties){let t;t="identifier"===r.key.type?r.key.name:"literal"===r.key.type?r.key.value+"":await this.execute(r.key,e)+"";const s=await this.execute(r.value,e);n[t]=s}return n}enhanceContext(t){return this.registryIntegration?this.registryIntegration.enhanceContext(t):t}async executeBehaviorDefinition(t,e){const{name:n,parameters:r=[],eventHandlers:s=[],initBlock:i}=t,o=t.imperativeInstaller;"function"==typeof o?(this.behaviorRegistry.set(n,{name:n,parameters:r,type:"imperative",install:o}),lt(`RUNTIME BASE: Registered imperative behavior '${n}'`)):(this.behaviorRegistry.set(n,{name:n,parameters:r,eventHandlers:s,initBlock:i}),lt(`RUNTIME BASE: Registered behavior '${n}'`))}async installBehaviorOnElement(t,e,n){lt("BEHAVIOR: installBehaviorOnElement called: "+t);let r=this.behaviorRegistry.get(t);if(!r&&(this.behaviorAPI.resolve&&this.behaviorAPI.resolve(t)&&(r=this.behaviorRegistry.get(t)),!r))throw Error(`Behavior "${t}" not found`);if("imperative"===r.type)return void("function"==typeof r.install&&(lt(`BEHAVIOR: Installing imperative behavior '${t}'`),r.install(e,n),lt(`BEHAVIOR: Finished installing imperative behavior '${t}'`)));lt("BEHAVIOR: Found behavior, eventHandlers count: "+(r.eventHandlers?.length||0));const s={me:e,owner:e,you:null,it:null,result:null,locals:new Map,globals:this.globalVariables,registry:this.expressionRegistry,halted:0,returned:0,broke:0,continued:0,async:0},i=this.enhanceContext(s);if(r.parameters)for(const t of r.parameters)i.locals.set(t,t in n?n[t]:void 0);for(const[t,e]of Object.entries(n))r.parameters?.includes(t)||i.locals.set(t,e);if(r.initBlock){lt("BEHAVIOR: Running init block for "+t);const e=this.options.commandTimeout??1e4;try{await Promise.race([this.execute(r.initBlock,i),new Promise((n,r)=>setTimeout(()=>r(Error(`Behavior "${t}" init block timed out after ${e}ms`)),e))]),lt("BEHAVIOR: Init block completed for "+t)}catch(e){if(lt(`BEHAVIOR: Init block error for ${t}:`,e),!(e instanceof Error&&Jr(e)))throw e}}if(lt(`BEHAVIOR: About to attach ${r.eventHandlers?.length||0} handlers for ${t}`),r.eventHandlers){const e=this.options.commandTimeout??1e4;for(const n of r.eventHandlers)await Promise.race([this.executeEventHandler(n,i),new Promise((n,r)=>setTimeout(()=>r(Error(`Behavior "${t}" handler attachment timed out after ${e}ms`)),e))])}lt("BEHAVIOR: Finished installing "+t)}async executeEventHandler(t,e){const{event:n,events:r,commands:s,target:i,args:o,selector:a,attributeName:c,watchTarget:u,modifiers:l}=t,h=r&&r.length>0?r:[n];lt(`BEHAVIOR: executeEventHandler: event='${n}', target='${i}'`);let f=[],d=null;if(i){const t="string"==typeof i?i.toLowerCase():"";if("window"===t||"the window"===t)d=window;else if("document"===t||"the document"===t||"body"===t)d=document;else if("me"===t||"myself"===t)f=e.me?[e.me]:[];else if("string"==typeof i&&e.locals.has(i)){const t=e.locals.get(i);lt(`BEHAVIOR: Target resolution: found local '${i}', isElement: ${this.isElement(t)}`),this.isElement(t)?f=[t]:Array.isArray(t)?f=t.filter(t=>this.isElement(t)):"string"==typeof t&&(f=this.queryElements(t,e))}else lt(`BEHAVIOR: Target resolution: querying for '${i}'`),f=this.queryElements(i,e)}else f=e.me?[e.me]:[];if(0===f.length&&!d)return void lt(`BEHAVIOR: executeEventHandler - No targets found for event '${n}', returning early`);if("mutation"===n&&c)return void this.setupMutationObserver(f,c,s,e);if("change"===n&&u)return void this.setupChangeObserver(u,s,e);const p=t.customEventSource;if(p&&this.registryIntegration){lt(`BEHAVIOR: executeEventHandler - Using custom event source '${p}' for event '${n}'`);const t=async t=>{const r=new Map(e.locals),i={...e,locals:r,it:t,event:t},o=this.enhanceContext(i);lt(`CUSTOM EVENT: Executing commands for event '${n}'`);try{await this.execute({type:"program",commands:s},o)}catch(t){this.logError(`[HyperFixi] Error executing commands for custom event '${n}':`,t)}};try{const r=this.registryIntegration.subscribeToEventSource(p,{event:n,handler:t,target:i,selector:a},e);lt(`BEHAVIOR: Subscribed to custom event source '${p}' (id: ${r.id})`),this.cleanupRegistry.registerGlobal(()=>r.unsubscribe(),"listener",`Custom event source '${p}' subscription ${r.id}`)}catch(t){this.logError(`[HyperFixi] Failed to subscribe to custom event source '${p}':`,t)}return}const m=Yr.createEventHandler(this,s,e,a,o);let y,g=null;if(l){let t=m;if(l.prevent){const e=t;t=async t=>(t.preventDefault(),e(t))}if(l.stop){const e=t;t=async t=>(t.stopPropagation(),e(t))}if(l.debounce){const e=l.debounce;let n;y=r=>{n&&clearTimeout(n),n=setTimeout(()=>t(r),e)},g=()=>{n&&(clearTimeout(n),n=void 0)}}else if(l.throttle){const e=l.throttle;let n=0;y=r=>{const s=Date.now();e>s-n||(n=s,t(r))}}else y=t}else y=m;const v=l?.once?{once:1}:void 0;if(d){for(const t of h)d.addEventListener(t,y,v),f.length>0?this.cleanupRegistry.registerListener(f[0],d,t,y):this.cleanupRegistry.registerGlobal(()=>d.removeEventListener(t,y),"listener",`Global ${t} listener`);g&&(f.length>0?this.cleanupRegistry.registerCustom(f[0],g,"debounce-timeout"):this.cleanupRegistry.registerGlobal(g,"timeout","debounce-timeout"))}else for(const t of f){for(const e of h){if("resize"===e&&"undefined"!=typeof ResizeObserver){const e=new ResizeObserver(t=>{for(const n of t){const t=new CustomEvent("resize",{detail:n,bubbles:0,cancelable:0});if(t.synthetic=1,y(t),v?.once){e.disconnect();break}}});e.observe(t),this.cleanupRegistry.registerCustom(t,()=>e.disconnect(),"resize-observer");continue}t.addEventListener(e,y,v),this.cleanupRegistry.registerListener(t,t,e,y)}g&&this.cleanupRegistry.registerCustom(t,g,"debounce-timeout")}}static createEventHandler(t,e,n,r,s){return async i=>{const o=Xr.get(i)??0;if(o>=100)return;if(Xr.set(i,o+1),r&&i.target instanceof Element)try{if(!i.target.matches(r)&&!i.target.closest(r))return}catch{lt(`Event delegation: invalid CSS selector '${r}', skipping filter`)}const a=new Map(n.locals),c={...n,locals:a,it:i,event:i};a.has("target")||c.locals.set("target",i.target);const u=t.enhanceContext(c);if(s&&s.length>0){const t=i,e=t.detail;for(const n of s)u.locals.set(n,t[n]??e?.[n]??null)}for(const n of e)try{const e=Zr(await t.execute(n,u));void 0!==e&&Object.assign(u,{it:e,result:e})}catch(e){if(Jr(e)){if(e.isHalt||e.isExit)break;if(e.isReturn){void 0!==e.returnValue&&Object.assign(u,{it:e.returnValue,result:e.returnValue});break}}throw t.logError("COMMAND FAILED:",e),e}}}setupMutationObserver(t,e,n,r){lt(`RUNTIME BASE: Setting up MutationObserver for attribute '${e}' on ${t.length} elements`);for(const s of t){const t=new MutationObserver(async t=>{for(const i of t)if("attributes"===i.type&&i.attributeName===e){ct(`MUTATION DETECTED: attribute '${e}' changed on`,s);const t={...r,me:s,it:i,locals:new Map(r.locals)},o=i.oldValue,a=s.getAttribute(e);t.locals.set("oldValue",o),t.locals.set("newValue",a);const c=this.enhanceContext(t);for(const t of n)try{await this.execute(t,c)}catch(t){if(Jr(t)){if(t.isHalt||t.isExit||t.isReturn)break}else this.logError("Error executing mutation handler command:",t)}}});t.observe(s,{attributes:1,attributeOldValue:1,attributeFilter:[e]}),this.cleanupRegistry.registerObserver(s,t),lt("RUNTIME BASE: MutationObserver attached to",s,`for attribute '${e}'`)}}async setupChangeObserver(t,e,n){lt("RUNTIME BASE: Setting up MutationObserver for content changes on watch target");const r=await this.execute(t,n);let s=[];this.isElement(r)?s=[r]:Array.isArray(r)&&(s=r.filter(t=>this.isElement(t))),lt(`RUNTIME BASE: Watching ${s.length} target elements for content changes`);for(const t of s){const r=new MutationObserver(async r=>{for(const s of r)if("childList"===s.type||"characterData"===s.type){ct("CONTENT CHANGE DETECTED on",t,"mutation type:",s.type);const r={...n,me:n.me,it:s,locals:new Map(n.locals)};r.locals.set("target",t);const i=s.oldValue,o=t.textContent;null!==i&&r.locals.set("oldValue",i),r.locals.set("newValue",o);const a=this.enhanceContext(r);for(const t of e)try{await this.execute(t,a)}catch(t){if(Jr(t)){if(t.isHalt||t.isExit||t.isReturn)break}else this.logError("Error executing change handler command:",t)}}});r.observe(t,{childList:1,characterData:1,subtree:1,characterDataOldValue:1}),this.cleanupRegistry.registerObserver(t,r),lt("RUNTIME BASE: MutationObserver attached to",t,"for content changes")}}queryElements(t,e){const n=e.me,r=(n instanceof Element?n.ownerDocument:null)??("undefined"!=typeof document?document:null);if(!r)return[];let s=t;s.startsWith("<")&&s.endsWith("/>")&&(s=s.slice(1,-2).trim());try{return Array.from(r.querySelectorAll(s))}catch{return lt(`queryElements: invalid CSS selector '${s}'`),[]}}isElement(t){return"undefined"!=typeof HTMLElement&&t instanceof HTMLElement?1:t&&"object"==typeof t?!!t.style&&!!t.classList:0}}function Kr(...t){const e=new Map;for(const n of t)for(const[t,r]of Object.entries(n))e.set(t,r);return e}const Qr=Fn({selector:Mn().min(1),single:Pn().optional().default(0)});function ts(t,e){if(e.startsWith("computed-")){const n=e.substring(9);return getComputedStyle(t).getPropertyValue(n)||""}const n=e.replace(/-([a-z])/g,(t,e)=>e.toUpperCase());return t.style[n]}new class extends Hn{constructor(){super(...arguments),this.name="me",this.category="Reference",this.syntax="me",this.description="References the current element in the execution context",this.inputSchema=qn(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=t.me,s=this.isElement(r)?r:null,i=this.success(s,"element");return this.trackPerformance(t,e,i,n),i}catch(r){const s=this.failure("MeExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "me"',"ME_EVALUATION_FAILED",["Ensure element context is properly set",'Check if "me" is available in current scope']);return this.trackPerformance(t,e,s,n),s}}validate(t){return void 0!==t?this.validationFailure("type-mismatch",'"me" expression takes no arguments',['Use "me" without any parameters']):this.validationSuccess()}},new class extends Hn{constructor(){super(...arguments),this.name="you",this.category="Reference",this.syntax="you",this.description="References the target element (usually event target or command target)",this.inputSchema=qn(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=t.you,s=this.isElement(r)?r:null,i=this.success(s,"element");return this.trackPerformance(t,e,i,n),i}catch(r){const s=this.failure("YouExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "you"',"YOU_EVALUATION_FAILED",["Ensure target element is available in context",'Check if "you" is set by event or command']);return this.trackPerformance(t,e,s,n),s}}validate(t){return void 0!==t?this.validationFailure("type-mismatch",'"you" expression takes no arguments',['Use "you" without any parameters']):this.validationSuccess()}},new class extends Hn{constructor(){super(...arguments),this.name="it",this.category="Reference",this.syntax="it",this.description="References the current context variable (result of previous operation or loop item)",this.inputSchema=qn(),this.outputType="Any",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=t.it,s={success:1,value:r,type:this.inferType(r)};return this.trackPerformance(t,e,s,n),s}catch(r){const s=this.failure("ItExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "it"',"IT_EVALUATION_FAILED",['Ensure "it" is set by previous operation',"Check if context variable is available"]);return this.trackPerformance(t,e,s,n),s}}validate(t){return void 0!==t?this.validationFailure("type-mismatch",'"it" expression takes no arguments',['Use "it" without any parameters']):this.validationSuccess()}},new class extends Hn{constructor(){super(...arguments),this.name="css-selector",this.category="Reference",this.syntax="<selector/> or <selector/> (single)",this.description="Queries DOM elements using CSS selectors with validation",this.inputSchema=Qr,this.outputType="ElementList",this.metadata={category:"Reference",complexity:"medium"}}async evaluate(t,e){const n=Date.now();try{if(!this.isValidCSSSelector(e.selector)){const r=this.failure("CSSSelectorError","invalid-argument",`Invalid CSS selector: "${e.selector}"`,"INVALID_CSS_SELECTOR",["Check selector syntax","Use valid CSS selector patterns like .class, #id, tag[attr]","Avoid special characters that need escaping"]);return this.trackPerformance(t,e,r,n),r}let r;if(e.single)r=document.querySelector(e.selector);else{const t=Array.from(document.querySelectorAll(e.selector));r=t.length>0?t:null}const s={success:1,value:r,type:Array.isArray(r)?"element-list":"element"};return this.trackPerformance(t,e,s,n),s}catch(r){const s=this.failure("CSSSelectorError","runtime-error",r instanceof Error?r.message:"CSS selector evaluation failed","CSS_SELECTOR_EVALUATION_FAILED",["Check if selector is valid CSS","Ensure DOM is ready when query executes","Verify elements exist in document"]);return this.trackPerformance(t,e,s,n),s}}validate(t){try{const e=this.inputSchema.safeParse(t);if(!e.success)return{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid input: "+t.message,suggestions:this.getValidationSuggestion(t.code??"unknown")}))??[],suggestions:["Provide valid CSS selector string","Check selector syntax"]};const{selector:n}=e.data;return this.isValidCSSSelector(n)?this.validationSuccess():this.validationFailure("syntax-error",`Invalid CSS selector syntax: "${n}"`,["Use .class for class selectors","Use #id for ID selectors","Use tag for element selectors","Use [attr] for attribute selectors"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Ensure input matches expected format"])}}isValidCSSSelector(t){try{return document.querySelector(t),1}catch{return 0}}getValidationSuggestion(t){return[{too_small:"CSS selector cannot be empty",invalid_type:"Selector must be a string",required:"CSS selector is required"}[t]||"Check input format and types"]}};const es={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.me??null,validate:Cn},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.you??null,validate:Cn},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it,validate:Cn},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it,validate:Cn},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.result,validate:Cn},querySelector:{name:"querySelector",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){const[n]=e;if("string"!=typeof n)throw Error("querySelector requires a string selector");return document.querySelector(n)},validate:t=>An(t,"querySelector","selector")},querySelectorAll:{name:"querySelectorAll",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const n=e[0];if("string"!=typeof n)throw Error("querySelectorAll requires a string selector");const r=document.querySelectorAll(n);return Array.from(r)},validate:t=>An(t,"querySelectorAll","selector")},getElementById:{name:"getElementById",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){const n=e[0];if("string"!=typeof n)throw Error("getElementById requires a string ID");return document.getElementById(n)},validate:t=>An(t,"getElementById","ID")},getElementsByClassName:{name:"getElementsByClassName",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const n=e[0];if("string"!=typeof n)throw Error("getElementsByClassName requires a string class name");const r=document.getElementsByClassName(n);return Array.from(r)},validate:t=>An(t,"getElementsByClassName","className")},closest:{name:"closest",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){let n=e[0];if(n&&"object"==typeof n&&"type"in n){const t=n;"identifier"===t.type&&t.name?n=t.name:"literal"===t.type&&"string"==typeof t.value&&(n=t.value)}if("string"!=typeof n)throw Error("closest requires a string selector");return t.me?t.me.closest(n):null},validate(t){if(1!==t.length)return"closest requires exactly 1 argument (selector)";const e=t[0];return"string"==typeof e||e&&"object"==typeof e&&"type"in e&&("identifier"===e.type||"literal"===e.type)?null:"closest selector must be a string or identifier"}},parent:{name:"parent",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.me?t.me.parentElement:null,validate:Cn},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async t=>window,validate:Cn},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async t=>document,validate:Cn},elementWithSelector:{name:"elementWithSelector",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const n=e[0];if("string"!=typeof n)throw Error("Selector must be a string");const r=t?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!r)throw Error("DOM not available - cannot resolve element selector");const s=r.querySelectorAll(n);return Array.from(s)},validate:t=>An(t,"elementWithSelector","selector")},styleRef:{name:"styleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const n=e[0],r=e[1];if("string"!=typeof n)throw Error("StyleRef requires a string property name");const s=r||t.me;if(s&&s instanceof HTMLElement)return ts(s,n)},validate:t=>On(t,1,2,"styleRef","property, optional element")??Sn(t,0,"styleRef","property")??(2===t.length&&t[1]&&"object"!=typeof t[1]?"styleRef element must be an HTMLElement":null)},possessiveStyleRef:{name:"possessiveStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const n=e[0],r=e[1];if("string"!=typeof n||"string"!=typeof r)throw Error("Possessive styleRef requires possessor and property strings");let s=null;if("my"===n&&t.me?s=t.me instanceof HTMLElement?t.me:null:"its"===n&&t.it&&(s=t.it instanceof HTMLElement?t.it:null),s)return ts(s,r)},validate:t=>kn(t,2,"possessiveStyleRef","possessor, property")??Sn(t,0,"possessiveStyleRef","possessor")??Sn(t,1,"possessiveStyleRef","property")},ofStyleRef:{name:"ofStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const n=e[0],r=e[1];if("string"!=typeof n||"string"!=typeof r)throw Error("Of styleRef requires property and reference strings");let s=null;if("me"===r&&t.me?s=t.me instanceof HTMLElement?t.me:null:"it"===r&&t.it&&(s=t.it instanceof HTMLElement?t.it:null),s)return ts(s,n)},validate:t=>kn(t,2,"ofStyleRef","property, reference")??Sn(t,0,"ofStyleRef","property")??Sn(t,1,"ofStyleRef","reference")}};class ns{constructor(t=100,e=5e3){this.maxSize=t,this.ttl=e,this.cache=new Map,this.accessOrder=new Map,this.accessCounter=0}get(t){const e=this.cache.get(t);if(e){if(this.ttl>=Date.now()-e.timestamp)return e.accessCount++,this.accessOrder.set(t,++this.accessCounter),e.result;this.delete(t)}}set(t,e){this.maxSize>this.cache.size||this.cache.has(t)||this.evictLRU(),this.cache.set(t,{result:e,timestamp:Date.now(),accessCount:1}),this.accessOrder.set(t,++this.accessCounter)}delete(t){return this.accessOrder.delete(t),this.cache.delete(t)}clear(){this.cache.clear(),this.accessOrder.clear(),this.accessCounter=0}size(){return this.cache.size}evictLRU(){let t,e=1/0;for(const[n,r]of this.accessOrder)e>r&&(e=r,t=n);void 0!==t&&this.delete(t)}getStats(){const t=Array.from(this.cache.values()),e=Date.now();return{size:this.cache.size,maxSize:this.maxSize,hitRate:t.length>0?t.filter(t=>t.accessCount>1).length/t.length:0,avgAge:t.length>0?t.reduce((t,n)=>t+(e-n.timestamp),0)/t.length:0,totalAccesses:t.reduce((t,e)=>t+e.accessCount,0)}}}const rs=new class{constructor(){this.domQueryCache=new ns(200,3e3),this.exprResultCache=new ns(500,2e3),this.cssMatchCache=new ns(100,5e3),this.formValueCache=new ns(50,1e3),this.hits=0,this.misses=0}querySelector(t){const e="querySelector:"+t,n=this.domQueryCache.get(e);if(void 0!==n)return this.hits++,n;this.misses++;const r=document.querySelector(t);return this.domQueryCache.set(e,r),r}querySelectorAll(t){const e="querySelectorAll:"+t,n=this.domQueryCache.get(e);if(void 0!==n)return this.hits++,n;this.misses++;const r=Array.from(document.querySelectorAll(t));return this.domQueryCache.set(e,r),r}getElementById(t){const e="getElementById:"+t,n=this.domQueryCache.get(e);if(void 0!==n)return this.hits++,n;this.misses++;const r=document.getElementById(t);return this.domQueryCache.set(e,r),r}getElementsByClassName(t){const e="getElementsByClassName:"+t,n=this.domQueryCache.get(e);if(void 0!==n)return this.hits++,n;this.misses++;const r=Array.from(document.getElementsByClassName(t));return this.domQueryCache.set(e,r),r}matches(t,e){const n=`matches:${this.getElementCacheKey(t)}:${e}`,r=this.cssMatchCache.get(n);if(void 0!==r)return this.hits++,r;this.misses++;const s=t.matches(e);return this.cssMatchCache.set(n,s),s}getExpressionResult(t){const e=this.exprResultCache.get(t);if(void 0!==e)return this.hits++,e;this.misses++}setExpressionResult(t,e){this.exprResultCache.set(t,e)}getFormValue(t){const e=this.getElementCacheKey(t),n=this.formValueCache.get("formValue:"+e);if(void 0!==n)return this.hits++,n;this.misses++}setFormValue(t,e){const n=this.getElementCacheKey(t);this.formValueCache.set("formValue:"+n,e)}invalidateElementCache(t){const e=this.getElementCacheKey(t);for(const t of[this.domQueryCache,this.cssMatchCache,this.formValueCache])for(const n of Array.from(t.cache.keys()))"string"==typeof n&&n.includes(e)&&t.delete(n)}invalidateAll(){this.domQueryCache.clear(),this.exprResultCache.clear(),this.cssMatchCache.clear(),this.formValueCache.clear(),this.hits=0,this.misses=0}getElementCacheKey(t){if(t.id)return"#"+t.id;const e=Array.from(t.classList).sort().join("."),n=this.getElementPosition(t);return`${t.tagName.toLowerCase()}${e?"."+e:""}@${n}`}getElementPosition(t){return""+Array.from(t.parentElement?.children||[]).indexOf(t)}getPerformanceStats(){const t=this.hits+this.misses;return{hits:this.hits,misses:this.misses,hitRate:Math.round(100*(t>0?this.hits/t*100:0))/100,domQueryCache:this.domQueryCache.getStats(),exprResultCache:this.exprResultCache.getStats(),cssMatchCache:this.cssMatchCache.getStats(),formValueCache:this.formValueCache.getStats()}}cleanup(){const t=Date.now();[this.domQueryCache,this.exprResultCache,this.cssMatchCache,this.formValueCache].forEach(e=>{Array.from(e.cache.entries()).forEach(([n,r])=>{t-r.timestamp>e.ttl&&e.delete(n)})})}};"undefined"!=typeof window&&setInterval(()=>{rs.cleanup()},1e4);const ss=new class{constructor(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0},this.startTimes=new Map}startTimer(t){this.startTimes.set(t,performance.now())}endTimer(t){const e=this.startTimes.get(t);if(e){const n=performance.now()-e;return this.startTimes.delete(t),n}return 0}recordTokenization(t){this.metrics.tokenizationTime+=t}recordEvaluation(t){this.metrics.evaluationTime+=t}updateCacheMetrics(){const t=rs.getPerformanceStats();this.metrics.cacheHitRate=t.hitRate}getMetrics(){return this.updateCacheMetrics(),{...this.metrics}}reset(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0}}};function is(){rs.cleanup(),ss.getMetrics().memoryUsage>52428800&&ss.reset()}let os=null;function as(t,e){if("number"==typeof t){if(!Number.isFinite(t))throw Error(`${e} must be a finite number, got ${t}`);return t}if("string"==typeof t){const n=t.trim();if(""===n)return 0;const r=parseFloat(n);if(isNaN(r))throw Error(`${e} cannot be converted to number: "${t}"`);return r}if("boolean"==typeof t)return t?1:0;if(null==t)return 0;if("object"==typeof t&&null!==t){if(Array.isArray(t)&&1===t.length){const n=t[0];if(Array.isArray(n))throw Error(e+" is a nested array, cannot convert to number");return as(n,e)}if("string"==typeof t.textContent||"value"in t){const e=t.value??t.textContent;if(null!=e){const t=(e+"").trim();if(""===t)return 0;const n=parseFloat(t);if(!isNaN(n))return n}}const n=t.valueOf();if("number"==typeof n&&Number.isFinite(n))return n}throw Error(`${e} cannot be converted to number: ${typeof t}`)}function cs(t){if("number"==typeof t)return Number.isFinite(t)?t:null;if("string"==typeof t){const e=t.trim();if(""===e)return 0;const n=parseFloat(e);return isNaN(n)?null:n}return"boolean"==typeof t?t?1:0:null==t?0:null}function us(t,e){if(!Number.isFinite(t)){if(Number.isNaN(t))throw Error(e+" resulted in non-finite value: NaN");throw Error(`${e} resulted in non-finite value: ${t>0?"Infinity":"-Infinity"}`)}return t}function ls(t){try{return as(t,"_"),1}catch{return 0}}function hs(t,e,n){if("==="===n)return t===e;if("!=="===n)return t!==e;if(null==t||null==e)return function(t,e,n){if(null==t&&null==e)switch(n){case"==":case">=":case"<=":return 1;default:return 0}switch(n){case"==":case">":case"<":case">=":case"<=":default:return 0;case"!=":return 1}}(t,e,n);const[r,s]=function(t,e){if("number"==typeof t&&"number"==typeof e)return[t,e];if("string"==typeof t&&"string"==typeof e){const n=parseFloat(t),r=parseFloat(e);return isNaN(n)||isNaN(r)?[t,e]:[n,r]}const n=cs(t),r=cs(e);return null!==n&&null!==r?[n,r]:[t+"",e+""]}(t,e);switch(n){case">":return r>s;case"<":return s>r;case">=":return r>=s;case"<=":return s>=r;case"==":return fs(t,e);case"!=":return!fs(t,e);default:return 0}}function fs(t,e){if(t===e)return 1;if(typeof t==typeof e)return"string"==typeof t||"number"==typeof t?t===e:0;if("number"==typeof t&&"string"==typeof e){const n=parseFloat(e);return!isNaN(n)&&t===n}if("string"==typeof t&&"number"==typeof e){const n=parseFloat(t);return!isNaN(n)&&n===e}return"boolean"==typeof t?fs(t?1:0,e):"boolean"==typeof e?fs(t,e?1:0):t+""==e+""}function ds(t,e=[]){return{isValid:0,errors:t,suggestions:e}}function ps(t,e,n=[],r="error"){return{type:t,message:e,suggestions:n,severity:r}}function ms(t,e,n,r,s,i=1,o){return e&&"object"==typeof e&&"evaluationHistory"in e&&Array.isArray(e.evaluationHistory)&&e.evaluationHistory.push({expressionName:t.name,category:t.category,input:n,output:r,timestamp:s,duration:Date.now()-s,success:i,...void 0!==o&&{error:o}}),r}"undefined"!=typeof window&&function(t=3e4){os&&clearInterval(os),os=setInterval(is,t)}();const ys=Fn({left:_n().describe("Left operand value"),right:_n().describe("Right operand value")}).strict(),gs=Fn({operand:_n().describe("Operand value to negate")}).strict();function vs(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType}new class extends Hn{constructor(){super(...arguments),this.name="and",this.category="Logical",this.syntax="left and right",this.description="Logical AND operation with comprehensive boolean type coercion",this.inputSchema=ys,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:r.errors[0]};const s=this.toBoolean(e.left);if(!s)return this.trackSimple(t,n,1,"boolean"),this.success(0,"boolean");const i=this.toBoolean(e.right),o=s&&i;return this.trackSimple(t,n,1,"boolean"),this.success(o,"boolean")}catch(e){return this.trackSimple(t,n,0),this.failure("AndExpressionError","runtime-error","Logical AND operation failed: "+(e instanceof Error?e.message:e+""),"AND_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid AND operation input: "+t.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends Hn{constructor(){super(...arguments),this.name="or",this.category="Logical",this.syntax="left or right",this.description="Logical OR operation with comprehensive boolean type coercion",this.inputSchema=ys,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:r.errors[0]};const s=this.toBoolean(e.left);if(s)return this.trackSimple(t,n,1,"boolean"),this.success(1,"boolean");const i=this.toBoolean(e.right),o=s||i;return this.trackSimple(t,n,1,"boolean"),this.success(o,"boolean")}catch(e){return this.trackSimple(t,n,0),this.failure("OrExpressionError","runtime-error","Logical OR operation failed: "+(e instanceof Error?e.message:e+""),"OR_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid OR operation input: "+t.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends Hn{constructor(){super(...arguments),this.name="not",this.category="Logical",this.syntax="not operand",this.description="Logical NOT operation with comprehensive boolean type coercion",this.inputSchema=gs,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:r.errors[0]};const s=!this.toBoolean(e.operand);return this.trackSimple(t,n,1,"boolean"),this.success(s,"boolean")}catch(e){return this.trackSimple(t,n,0),this.failure("NotExpressionError","runtime-error","Logical NOT operation failed: "+(e instanceof Error?e.message:e+""),"NOT_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid NOT operation input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a single operand","Ensure operand is a valid value"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}};const bs=Bn([_n(),_n()]),ws=Bn([_n(),Mn()]),Es={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(t,e,n){const r=Date.now();try{return ms(this,t,[e,n],e==n,r)}catch(s){throw ms(this,t,[e,n],0,r,0,s instanceof Error?s:Error(s+"")),s}},validate:t=>Nn(t,"equals"),inputSchema:bs,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"value is 5",description:"Check if value equals 5 using loose equality",expectedOutput:1,context:{result:5}},{input:'"5" == 5',description:'String "5" equals number 5 with type coercion',expectedOutput:1}],relatedExpressions:["strictEquals","notEquals"],performance:{averageTime:.001,complexity:"O(1)"}},documentation:{summary:"Compares two values for loose equality, allowing type coercion",parameters:[{name:"left",type:"unknown",description:"Left operand for comparison",optional:0,examples:["5",'"hello"',"true","null"]},{name:"right",type:"unknown",description:"Right operand for comparison",optional:0,examples:["5",'"hello"',"true","null"]}],returns:{type:"Boolean",description:"True if values are loosely equal, false otherwise",examples:["true","false"]},examples:[{title:"Basic equality check",code:"if my.value is 10",explanation:"Check if element value equals 10",output:"Boolean result"},{title:"Type coercion",code:'if "5" == 5',explanation:'String "5" equals number 5 with automatic type conversion',output:"true"},{title:"Null checks",code:"if value is null",explanation:"Check if value is null or undefined",output:"Boolean result"}],seeAlso:["strictEquals","notEquals","matches"],tags:["comparison","equality","logic","type-coercion"]}},xs={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],async evaluate(t,e,n){const r=t.evaluationHistory,s=e===n;return r&&ms(this,t,[e,n],s,r?Date.now():0),s},validate:t=>Nn(t,"strictEquals")},ks={name:"notEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=","is not","does not equal"],async evaluate(t,e,n){const r=t.evaluationHistory,s=e!=n;return r&&ms(this,t,[e,n],s,r?Date.now():0),s},validate:t=>Nn(t,"notEquals")},Ss={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],async evaluate(t,e,n){const r=t.evaluationHistory,s=e!==n;return r&&ms(this,t,[e,n],s,r?Date.now():0),s},validate:t=>Nn(t,"strictNotEquals")},As={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0,i=hs(e,n,"<");return r&&ms(this,t,[e,n],i,s),i},validate:t=>Nn(t,"lessThan")},Ns={name:"lessThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<=","is less than or equal to"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0,i=hs(e,n,"<=");return r&&ms(this,t,[e,n],i,s),i},validate:t=>Nn(t,"lessThanOrEqual")},Cs={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0,i=hs(e,n,">");return r&&ms(this,t,[e,n],i,s),i},validate:t=>Nn(t,"greaterThan")},Ts={name:"greaterThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">=","is greater than or equal to"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0,i=hs(e,n,">=");return r&&ms(this,t,[e,n],i,s),i},validate:t=>Nn(t,"greaterThanOrEqual")},Os={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(t,e,n){const r=Date.now();try{return ms(this,t,[e,n],e&&n,r)}catch(s){throw ms(this,t,[e,n],0,r,0,s instanceof Error?s:Error(s+"")),s}},validate:t=>Nn(t,"and"),inputSchema:bs,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"true and false",description:"Logical AND of boolean values",expectedOutput:0},{input:"name and age",description:"Both name and age must be truthy",expectedOutput:1,context:{variables:new Map([["name","John"],["age",25]])}}],relatedExpressions:["or","not"],performance:{averageTime:.001,complexity:"O(1)"}},documentation:{summary:"Logical AND operation that returns true only if both operands are truthy",parameters:[{name:"left",type:"unknown",description:"Left operand (evaluated for truthiness)",optional:0,examples:["true","name","5",'"hello"']},{name:"right",type:"unknown",description:"Right operand (evaluated for truthiness)",optional:0,examples:["false","age","0",'""']}],returns:{type:"Boolean",description:"True if both operands are truthy, false otherwise",examples:["true","false"]},examples:[{title:"Form validation",code:"if name and email",explanation:"Check if both name and email have values",output:"Boolean result"},{title:"Multiple conditions",code:"if age > 18 and hasLicense",explanation:"Combine multiple conditions",output:"Boolean result"},{title:"Short-circuit evaluation",code:"if element and element.value",explanation:"Check element exists before accessing properties",output:"Boolean result"}],seeAlso:["or","not","exists"],tags:["logic","boolean","conditions","validation"]}},$s={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],async evaluate(t,e,n){const r=t.evaluationHistory,s=e||n;return r&&ms(this,t,[e,n],s,r?Date.now():0),s},validate:t=>Nn(t,"or")},Rs={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],async evaluate(t,e){const n=t.evaluationHistory,r=!e;return n&&ms(this,t,[e],r,n?Date.now():0),r},validate:t=>kn(t,1,"not","operand")},Ls={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0;let s;return s=null==e?1:ln(e)||Array.isArray(e)||e instanceof NodeList?0===e.length:e instanceof Node||e instanceof Element?0:dn(e)?0===Object.keys(e).length:0,n&&ms(this,t,[e],s,r),s},validate:t=>kn(t,1,"isEmpty","value")},Is={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0;let s;return s=null==e||0==e?1:Array.isArray(e)||e instanceof NodeList?0===e.length:(ln(e),0),n&&ms(this,t,[e],s,r),s},validate:t=>kn(t,1,"no","value")},js={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0,s=!await Ls.evaluate(t,e);return n&&ms(this,t,[e],s,r),s},validate:t=>kn(t,1,"isNotEmpty","value")},Ms={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0,s=Ds(e);return n&&ms(this,t,[e],s,r),s},validate:t=>kn(t,1,"exists","value")};function Ds(t){return null==t?0:Array.isArray(t)||"undefined"!=typeof NodeList&&t instanceof NodeList?t.length>0:1}const Ps={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0,s=!Ds(e);return n&&ms(this,t,[e],s,r),s},validate:t=>kn(t,1,"doesNotExist","value")},Fs={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0;let i;if(e&&n){if(vs(e)&&vs(n))return i=e.contains(n),r&&ms(this,t,[e,n],i,s),i;if(ln(e)&&e.match(/^[.#][\w-]+$/)){const o=document.querySelector(e);if(o&&vs(n))return i=o.contains(n),r&&ms(this,t,[e,n],i,s),i;if(o&&ln(n)&&n.match(/^[.#][\w-]+$/)){const a=document.querySelector(n);return i=a?o.contains(a):0,r&&ms(this,t,[e,n],i,s),i}}if(ln(n)&&n.match(/^[.#][\w-]+$/)&&vs(e)){const o=document.querySelector(n);return i=o?e.contains(o):0,r&&ms(this,t,[e,n],i,s),i}}if(ln(e)&&ln(n))i=e.includes(n);else if(Array.isArray(e)||"undefined"!=typeof NodeList&&e instanceof NodeList){const t=Array.from(e);i=t.includes(n)||n instanceof Node&&t.some(t=>t instanceof Node&&t.contains(n))}else i=dn(e)&&ln(n)?n in e:0;return r&&ms(this,t,[e,n],i,s),i},validate:t=>kn(t,2,"contains","container, value")},Bs={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0,i=!await Fs.evaluate(t,e,n);return r&&ms(this,t,[e,n],i,s),i},validate:t=>kn(t,2,"doesNotContain","container, value")},_s={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0,i=null!=e&&null!=n?(e+"").startsWith(n+""):0;return r&&ms(this,t,[e,n],i,s),i},validate:t=>kn(t,2,"startsWith","str, prefix")},Vs={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0,i=null!=e&&null!=n?(e+"").endsWith(n+""):0;return r&&ms(this,t,[e,n],i,s),i},validate:t=>kn(t,2,"endsWith","str, suffix")},qs={name:"between",category:"Logical",evaluatesTo:"Boolean",operators:["is between","between"],async evaluate(t,e,n,r){const s=t.evaluationHistory;let i=n,o=r;if(null!=i&&null!=o&&i>o){const t=i;i=o,o=t}const a=null!=i&&null!=o&&e>=i&&o>=e;return s&&ms(this,t,[e,n,r],a,s?Date.now():0),a},validate:t=>kn(t,3,"between","value, min, max")},Hs={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(t,e,n){const r=Date.now();try{let s;if(e instanceof Element&&ln(n)){const t=n;if(t.startsWith(".")||t.startsWith("#")||t.startsWith(":")||t.startsWith("[")||/^[a-zA-Z][\w-]*$/.test(t))try{s=function(t,e){return rs.matches(t,e)}(e,t)}catch(t){s=0}else s=0}else if(ln(e)&&ln(n)){const t=e,r=n;try{s=(r.startsWith("/")&&r.endsWith("/")?RegExp(r.slice(1,-1)):RegExp(r)).test(t)}catch(e){s=t.includes(r)}}else s=0;return ms(this,t,[e,n],s,r)}catch(s){throw ms(this,t,[e,n],0,r,0,s instanceof Error?s:Error(s+"")),s}},validate:t=>kn(t,2,"matches","element, selector"),inputSchema:ws,metadata:{category:"Logical",complexity:"medium",sideEffects:["dom-query"],dependencies:[],returnTypes:["Boolean"],examples:[{input:'element matches ".active"',description:"Check if element has active class",expectedOutput:1},{input:'text matches "/^hello/"',description:'Check if text starts with "hello" using regex',expectedOutput:1,context:{variables:new Map([["text","hello world"]])}}],relatedExpressions:["contains","startsWith","endsWith"],performance:{averageTime:.5,complexity:"O(n)"}},documentation:{summary:"Tests if element matches CSS selector or string matches regex pattern",parameters:[{name:"element",type:"Element | string",description:"DOM element or string to test",optional:0,examples:["<div>",'"hello world"',"me","target"]},{name:"selector",type:"string",description:"CSS selector or regex pattern to match against",optional:0,examples:['".active"','"#navbar"','"/^hello/"','"\\\\d+"']}],returns:{type:"Boolean",description:"True if element matches selector/pattern",examples:["true","false"]},examples:[{title:"CSS class matching",code:'if me matches ".active"',explanation:'Check if current element has "active" class',output:"Boolean result"},{title:"Attribute matching",code:'if target matches "[data-role=\\"button\\"]"',explanation:"Check if element has specific data attribute",output:"Boolean result"},{title:"Regex pattern matching",code:'if email matches "/^[^@]+@[^@]+\\\\.[^@]+$/"',explanation:"Validate email format with regex",output:"Boolean result"},{title:"Complex CSS selector",code:'if element matches ".card:hover .button"',explanation:"Match complex CSS selector with pseudo-classes",output:"Boolean result"}],seeAlso:["contains","startsWith","endsWith","querySelector"],tags:["pattern","css","regex","validation","dom"]}},Us={name:"has",category:"Logical",evaluatesTo:"Boolean",operators:["has","have"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0;let i=0;if(e instanceof Element&&ln(n)){const t=n;t.startsWith(".")?i=e.classList.contains(t.slice(1)):t.startsWith("[")&&t.endsWith("]")&&(i=e.hasAttribute(t.slice(1,-1)))}return r&&ms(this,t,[e,n],i,s),i},validate:t=>kn(t,2,"has","element, selector")},Ws={name:"doesNotHave",category:"Logical",evaluatesTo:"Boolean",operators:["does not have"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0,i=!await Us.evaluate(t,e,n);return r&&ms(this,t,[e,n],i,s),i},validate:t=>kn(t,2,"doesNotHave","element, selector")},zs={equals:Es,strictEquals:xs,notEquals:ks,strictNotEquals:Ss,lessThan:As,lessThanOrEqual:Ns,greaterThan:Cs,greaterThanOrEqual:Ts,and:Os,or:$s,not:Rs,no:Is,isEmpty:Ls,isNotEmpty:js,exists:Ms,doesNotExist:Ps,contains:Fs,doesNotContain:Bs,startsWith:_s,endsWith:Vs,between:qs,matches:Hs,has:Us,doesNotHave:Ws},Js=Fn({value:Mn().describe("String literal value")}).strict(),Zs=Fn({value:Dn().describe("Number literal value")}).strict(),Gs=Fn({value:Pn().describe("Boolean literal value")}).strict(),Xs=Fn({left:_n().describe("Left operand"),right:_n().describe("Right operand")}).strict(),Ys={stringLiteral:new class extends Hn{constructor(){super(...arguments),this.name="stringLiteral",this.category="Special",this.syntax="\"string\" or 'string'",this.description="String literals with template interpolation support",this.outputType="String",this.inputSchema=Js,this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid){const e=this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions);return this.trackSimple(t,n,0),e}let s=e.value;(s.includes("${")||s.includes("$"))&&(s=this.interpolateString(s,t));const i=this.success(s,"string");return this.trackSimple(t,n,1,s),i}catch(e){return this.trackSimple(t,n,0),this.failure("StringEvaluationError","runtime-error","String literal evaluation failed: "+(e instanceof Error?e.message:e+""),"STRING_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid string literal input",["Provide a value parameter","Ensure value is a string"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}interpolateString(t,e){let n=t.replace(/\$\{([^}]+)\}/g,(t,n)=>{try{const t=this.resolveExpression(n.trim(),e);return void 0!==t?t+"":""}catch(t){return""}});return n=n.replace(/\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g,(t,n)=>{try{const t=this.resolveVariable(n,e);return void 0!==t?t+"":""}catch(t){return""}}),n}resolveExpression(t,e){if(t.includes(".")){const n=t.split(".");let r=this.resolveVariable(n[0],e);for(let t=1;n.length>t&&null!=r;t++)r=r[n[t]];return r}return this.resolveVariable(t,e)}resolveVariable(t,e){return"me"===t&&e.me?e.me:"you"===t&&e.you?e.you:"it"===t&&e.it?e.it:"result"===t&&e.result?e.result:e.locals?.has(t)?(Lt(t,e),e.locals.get(t)):e.globals?.has(t)?e.globals.get(t):void 0}},numberLiteral:new class extends Hn{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=Zs,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);return r.isValid?Number.isFinite(e.value)?(this.trackSimple(t,n,1,e.value),this.success(e.value,"number")):(this.trackSimple(t,n,0),this.failure("NumberValidationError","invalid-argument","Number literal must be finite","NUMBER_NOT_FINITE")):(this.trackSimple(t,n,0),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(e){return this.trackSimple(t,n,0),this.failure("NumberEvaluationError","runtime-error","Number literal evaluation failed: "+(e instanceof Error?e.message:e+""),"NUMBER_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?Number.isFinite(e.data.value)?this.validationSuccess():this.validationFailure("invalid-argument","Number literal value must be finite",["Use finite numbers only","Avoid Infinity and NaN values"]):this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid number literal input",["Provide a value parameter","Ensure value is a number"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},booleanLiteral:new class extends Hn{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=Gs,this.outputType="Boolean",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);return r.isValid?(this.trackSimple(t,n,1,e.value),this.success(e.value,"boolean")):(this.trackSimple(t,n,0),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(e){return this.trackSimple(t,n,0),this.failure("BooleanEvaluationError","runtime-error","Boolean literal evaluation failed: "+(e instanceof Error?e.message:e+""),"BOOLEAN_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid boolean literal input",["Provide a value parameter","Ensure value is a boolean"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},addition:new class extends Hn{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=Xs,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return this.trackSimple(t,n,0),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions);const s=as(e.left,"left operand")+as(e.right,"right operand");return this.trackSimple(t,n,1,s),this.success(s,"number")}catch(e){return this.trackSimple(t,n,0),this.failure("AdditionError","runtime-error","Addition failed: "+(e instanceof Error?e.message:e+""),"ADDITION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid addition input",["Provide left and right operands"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},stringConcatenation:new class extends Hn{constructor(){super(...arguments),this.name="stringConcatenation",this.category="Special",this.syntax="left + right (string concatenation)",this.description="Concatenation of two values into a string",this.inputSchema=Xs,this.outputType="String",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return this.trackSimple(t,n,0),this.failure("ValidationError","validation-error",r.errors[0]?.message||"Invalid input","STRING_CONCATENATION_VALIDATION_FAILED",r.suggestions);const s=this.convertToString(e.left)+this.convertToString(e.right);return this.trackSimple(t,n,1,s),this.success(s,"string")}catch(e){return this.trackSimple(t,n,0),this.failure("StringConcatenationError","runtime-error",e instanceof Error?e.message:"String concatenation failed","STRING_CONCATENATION_ERROR",["Check that operands can be converted to strings"])}}validate(t){const e=Xs.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid string concatenation input",["Provide left and right operands for concatenation"])}convertToString(t){if(null===t)return"null";if(void 0===t)return"undefined";if(ln(t))return t;if(hn(t))return""+t;if(fn(t))return""+t;if(t instanceof Date)return""+t;try{return t+""}catch{return"[object Object]"}}},multiplication:new class extends Hn{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=Xs,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return this.trackSimple(t,n,0),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions);const s=as(e.left,"left operand")*as(e.right,"right operand");return this.trackSimple(t,n,1,s),this.success(s,"number")}catch(e){return this.trackSimple(t,n,0),this.failure("MultiplicationError","runtime-error","Multiplication failed: "+(e instanceof Error?e.message:e+""),"MULTIPLICATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid multiplication input",["Provide left and right operands"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}};function Ks(){return Kr(es,zs,Ys)}class Qs{constructor(t){this.observer=null,this.initialized=0,this.runtime=t}init(){"undefined"!=typeof document&&(this.initialized||(this.initialized=1,this.scanDocument(),this.observer=new MutationObserver(t=>{for(const e of t)"childList"===e.type?e.addedNodes.forEach(t=>{t.nodeType===Node.ELEMENT_NODE&&(this.processElement(t),this.scanElement(t))}):"attributes"===e.type&&"_"===e.attributeName&&this.processElement(e.target)}),this.observer.observe(document.body,{childList:1,subtree:1,attributes:1,attributeFilter:["_"]})))}destroy(){this.observer&&(this.observer.disconnect(),this.observer=null),this.initialized=0}reset(){this.destroy()}scanAndProcessAll(){this.scanDocument()}scanDocument(){document.body&&this.scanElement(document.body)}scanElement(t){t.hasAttribute("_")&&this.processElement(t),t.querySelectorAll("[_]").forEach(t=>this.processElement(t))}processElement(t){const e=t.getAttribute("_");if(!e)return;const n=rn(t);this.runtime.execute(e,n).catch(n=>{console.error('[HyperFixi] Error executing _="" attribute:',n),console.error("Element:",t),console.error("Code:",e)})}}function ti(t,e,n,r,s,i){function o(t){if(void 0!==t&&"function"!=typeof t)throw new TypeError("Function expected");return t}for(var a,c=r.kind,u="getter"===c?"get":"setter"===c?"set":"value",l=!e&&t?r.static?t:t.prototype:null,h=e||(l?Object.getOwnPropertyDescriptor(l,r.name):{}),f=0,d=n.length-1;d>=0;d--){var p={};for(var m in r)p[m]="access"===m?{}:r[m];for(var m in r.access)p.access[m]=r.access[m];p.addInitializer=function(t){if(f)throw new TypeError("Cannot add initializers after decoration has completed");i.push(o(t||null))};var y=(0,n[d])("accessor"===c?{get:h.get,set:h.set}:h[u],p);if("accessor"===c){if(void 0===y)continue;if(null===y||"object"!=typeof y)throw new TypeError("Object expected");(a=o(y.get))&&(h.get=a),(a=o(y.set))&&(h.set=a),(a=o(y.init))&&s.unshift(a)}else(a=o(y))&&("field"===c?s.unshift(a):h[u]=a)}l&&Object.defineProperty(l,r.name,h),f=1}function ei(t,e,n){for(var r=arguments.length>2,s=0;e.length>s;s++)n=r?e[s].call(t,n):e[s].call(t);return r?n:void 0}function ni(t,e,n){return"symbol"==typeof e&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:1,value:n?"".concat(n," ",e):e})}function ri(t){const e=t.trim();return e.startsWith("[@")&&e.endsWith("]")||e.startsWith("@")?1:0}function si(t){const e=t.trim();if(e.startsWith("[@")&&e.endsWith("]")){const t=e.slice(2,-1),n=t.indexOf("=");if(-1===n)return{name:t.trim()};const r=t.slice(0,n).trim();let s=t.slice(n+1).trim();return(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),{name:r,value:s}}if(e.startsWith("@"))return{name:e.substring(1).trim()};throw Error("Invalid attribute syntax: "+t)}function ii(t,e){for(const n of t)e(n);return t}function oi(t,e,n){for(const r of t)for(const t of e)n(r,t);return t}function ai(t,e,n){const r=t.hasAttribute(e);void 0!==n?r&&t.getAttribute(e)===n?t.removeAttribute(e):t.setAttribute(e,n):r?t.removeAttribute(e):t.setAttribute(e,"")}function ci(t){if(!t)return[];if("string"==typeof t)return t.trim().split(/[\s,]+/).map(t=>{const e=t.trim();return e.startsWith(".")?e.substring(1):e}).filter(t=>t.length>0&&li(t));if(Array.isArray(t))return t.map(t=>{const e=(t+"").trim();return e.startsWith(".")?e.substring(1):e}).filter(t=>t.length>0&&li(t));const e=(t+"").trim(),n=e.startsWith(".")?e.substring(1):e;return n.length>0&&li(n)?[n]:[]}function ui(t){const e=t.trim();return/^\{[^}]+\}$/.test(e)}function li(t){if(!t||0===t.trim().length)return 0;const e=t.trim();return ui(e)?1:/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(e)}function hi(t,e){return t.map(t=>{if(ui(t)){const n=function(t){const e=t.trim(),n=e.match(/^\{(.+)\}$/);return n?n[1].trim():e}(t),r=e.locals.get(n)??e.globals.get(n);return null!=r?r+"":(at(`Dynamic class variable '${n}' not found in context`),"")}return t}).filter(t=>t.length>0)}"function"==typeof SuppressedError&&SuppressedError;const fi=Symbol("command:name"),di=Symbol("command:category"),pi=Symbol("command:metadata");function mi(t){return function(e,n){const r=e;r[fi]=t.name,r[di]=t.category,Object.defineProperty(e.prototype,"name",{value:t.name,writable:0,enumerable:1})}}function yi(t){return function(e,n){const r=e,s=r[di];if(!s)throw Error("@meta decorator requires @command decorator to be applied first on "+e.name);const i={description:t.description,syntax:t.syntax,examples:t.examples,category:s,sideEffects:t.sideEffects,deprecated:t.deprecated,deprecationMessage:t.deprecationMessage,aliases:t.aliases,relatedCommands:t.relatedCommands,isBlocking:t.isBlocking??0,hasBody:t.hasBody??0,version:"1.0.0",compatibility:t.compatibility};r[pi]=i,Object.defineProperty(e,"metadata",{value:i,writable:0,enumerable:1,configurable:0}),Object.defineProperty(e.prototype,"metadata",{get:()=>i,enumerable:1,configurable:0})}}function gi(t){return()=>new t}function vi(t,e){return e}function bi(t,e,n){if(sn(t))return t;if(!t){const t=e.me;if(!t)throw Error(vi(0,"No target element — provide explicit target or ensure context.me is set"));return wi(t)}if("string"==typeof t){const n=t.trim();if("me"===n){if(!e.me)throw Error(vi(0,'Context reference "me" is not available'));return wi(e.me)}if("it"===n){if(!sn(e.it))throw Error(vi(0,'Context reference "it" is not an HTMLElement'));return e.it}if("you"===n){if(!e.you)throw Error(vi(0,'Context reference "you" is not available'));return wi(e.you)}const r=e.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!r)throw Error(vi(0,"DOM not available — cannot resolve element selector"));const s=r.querySelector(n);if(!s)throw Error(vi(0,"Element not found with selector: "+n));if(!sn(s))throw Error(vi(0,"Element found but is not an HTMLElement: "+n));return s}throw Error(vi(0,"Invalid target type: "+typeof t))}function wi(t){if(sn(t))return t;throw Error("Value is not an HTMLElement")}function Ei(t,e,n){switch(t.toLowerCase()){case"my":case"me":if(!e.me)throw Error(vi(0,'No "me" element in context'));if(!sn(e.me))throw Error(vi(0,"context.me is not an HTMLElement"));return e.me;case"its":case"it":if(!e.it)throw Error(vi(0,'No "it" value in context'));if(!sn(e.it))throw Error(vi(0,"context.it is not an HTMLElement"));return e.it;case"your":case"you":if(!e.you)throw Error(vi(0,'No "you" element in context'));if(!sn(e.you))throw Error(vi(0,"context.you is not an HTMLElement"));return e.you;default:throw Error(vi(0,"Unknown possessive: "+t))}}const xi=["on","from","to","in","with","at"];async function ki(t,e,n,r,s={},i){let o=t;if(s.filterPrepositions&&t&&(o=t.filter(t=>{const e=t;return"identifier"===e?.type&&"string"==typeof e.name?!xi.includes(e.name.toLowerCase()):1})),(!o||0===o.length)&&s.fallbackModifierKey&&i){const t=i[s.fallbackModifierKey];t&&(o=[t])}if(!o||0===o.length){if(!n.me)throw Error(r+" command: no target specified and context.me is null");if(!sn(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}const a=[];for(const t of o){const s=await e.evaluate(t,n);if(""!==s&&("string"!=typeof s||""!==s.trim()))if(sn(s))a.push(s);else if(on(s)){const t=Array.from(s).filter(sn);a.push(...t)}else if(Array.isArray(s)){const t=s.filter(sn);a.push(...t)}else{if("string"!=typeof s){if(null==s)continue;throw Error(`Invalid ${r} target: expected HTMLElement or CSS selector, got ${typeof s}`)}try{let t=s;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const e=n.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!e)throw Error("DOM not available - cannot resolve element selector");const r=e.querySelectorAll(t),i=Array.from(r).filter(sn);a.push(...i)}catch(t){throw Error(`Invalid CSS selector: "${s}" - ${t instanceof Error?t.message:t+""}`)}}}if(0===a.length){if(!n.me)throw Error(r+" command: no target specified and context.me is null");if(!sn(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}return a}function Si(t){return"string"==typeof t&&t.trim().startsWith("*")}function Ai(t){const e=function(t){const e=t.trim();if(!e.startsWith("*"))return null;const n=e.substring(1).trim();return n?{property:n}:null}(t);if(!e)return null;const n=e.property.toLowerCase();return["display","visibility","opacity"].includes(n)?n:null}function Ni(t,e,n){t.style.setProperty(e,n)}const Ci=["dialog","details","summary","select"];function Ti(t){return t&&"object"==typeof t?"string"==typeof t.selector?t.selector:"string"==typeof t.value?t.value:"string"==typeof t.name?t.name:null:null}async function Oi(t,e,n){return function(t){if(!t||"object"!=typeof t)return 0;const e=t.type;if("selector"!==e&&"cssSelector"!==e&&"classSelector"!==e)return 0;const n=Ti(t);return"string"==typeof n&&n.startsWith(".")}(t)||function(t){if(!t||"object"!=typeof t)return 0;const e=t.type;if("selector"!==e&&"cssSelector"!==e&&"cssProperty"!==e)return 0;const n=Ti(t);return"string"==typeof n&&n.startsWith("*")}(t)?{value:Ti(t),extractedFromNode:1}:function(t){if(!t||"object"!=typeof t)return 0;if("attributeAccess"===t.type)return 1;if("selector"===t.type||"cssSelector"===t.type){const e=Ti(t);return"string"==typeof e&&e.startsWith("@")}return 0}(t)?{value:(r=t,"attributeAccess"===r.type?"@"+r.attributeName:Ti(r)),extractedFromNode:1}:{value:await e.evaluate(t,n),extractedFromNode:0};var r}class $i{async resolveTargets(t,e,n,r){return ki(t,e,n,this.mode,{filterPrepositions:1,fallbackModifierKey:this.preposition},r)}async evaluateFirst(t,e,n){return Oi(t,e,n)}parseClassNames(t){return ci(t)}isAttribute(t){return ri(t.trim())}isCSSProperty(t){return Si(t.trim())}validateTargets(t){return Array.isArray(t)&&function(t){return Array.isArray(t)&&t.length>0&&t.every(t=>sn(t))}(t)}validateType(t,e){return function(t,e){return"string"==typeof t&&e.includes(t)}(t,e)}validateStringArray(t,e=1){return Array.isArray(t)&&function(t,e=1){return Array.isArray(t)&&t.length>=e&&t.every(t=>"string"==typeof t&&t.length>0)}(t,e)}}let Ri=(()=>{let t,e,n=[yi({description:"Add CSS classes, attributes, or styles to elements",syntax:"add <classes|@attr|{styles}> [to <target>]",examples:["add .active to me",'add "active selected" to <button/>',"add .highlighted to #modal",'add [@data-test="value"] to #element'],sideEffects:["dom-mutation"]}),mi({name:"add",category:"dom"})],r=[],s=$i;return e=class extends s{constructor(){super(...arguments),this.mode="add",this.preposition="to"}async parseInput(t,e,n){if(!t.args||0===t.args.length)throw Error("add command requires an argument");const{value:r}=await this.evaluateFirst(t.args[0],e,n);if("object"==typeof r&&null!==r&&!Array.isArray(r))return{type:"styles",styles:r,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)};if("string"==typeof r){const s=r.trim();if(this.isAttribute(s)){const{name:r,value:i}=function(t){const e=si(t);return{name:e.name,value:e.value??""}}(s);return{type:"attribute",name:r,value:i,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}if(this.isCSSProperty(s)){const r=s.substring(1).trim();if(2>t.args.length)throw Error("add *property requires a value argument");const i=await e.evaluate(t.args[1],n);return{type:"styles",styles:{[r]:i+""},targets:await this.resolveTargets(t.args.slice(2),e,n,t.modifiers)}}}const s=this.parseClassNames(r);if(0===s.length)throw Error("add command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}async execute(t,e){switch(t.type){case"classes":{const n=hi(t.classes,e);n.length>0&&oi(t.targets,n,(t,e)=>{t.classList.contains(e)||t.classList.add(e)});break}case"attribute":n=t.name,r=t.value,ii(t.targets,t=>{t.setAttribute(n,r)});break;case"styles":oi(t.targets,Object.entries(t.styles),(t,[e,n])=>{t.style.setProperty(e,n)})}var n,r}validate(t){if("object"!=typeof t||null===t)return 0;const e=t;if(!this.validateType(e.type,["classes","attribute","styles"]))return 0;if(!this.validateTargets(e.targets))return 0;if("classes"===e.type){if(!this.validateStringArray(t.classes,1))return 0}else if("attribute"===e.type){if("string"!=typeof t.name||0===t.name.length)return 0;if("string"!=typeof t.value)return 0}else if("styles"===e.type){const e=t;if("object"!=typeof e.styles||null===e.styles)return 0;if(Array.isArray(e.styles))return 0;const n=e.styles;if(0===Object.keys(n).length)return 0;if(!Object.values(n).every(t=>"string"==typeof t))return 0}return 1}},ni(e,"AddCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;ti(null,t={value:e},n,{kind:"class",name:e.name,metadata:i},null,r),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:i}),ei(e,r)})(),e})();const Li=gi(Ri);function Ii(t){return t.parentNode?(t.remove(),1):0}let ji=(()=>{let t,e,n=[yi({description:"Remove CSS classes, attributes, styles, or elements from the DOM",syntax:"remove <classes|@attr|*prop|element> [from <target>]",examples:["remove .active from me",'remove "active selected" from <button/>',"remove .highlighted from #modal","remove me","remove closest .item"],sideEffects:["dom-mutation"]}),mi({name:"remove",category:"dom"})],r=[],s=$i;return e=class extends s{constructor(){super(...arguments),this.mode="remove",this.preposition="from"}async parseInput(t,e,n){if(!t.args||0===t.args.length)throw Error("remove command requires an argument");const{value:r}=await this.evaluateFirst(t.args[0],e,n);if(sn(r))return{type:"element",targets:[r]};if(Array.isArray(r)&&r.length>0&&sn(r[0]))return{type:"element",targets:r.filter(t=>sn(t))};if("string"==typeof r){const s=r.trim();if(this.isAttribute(s))return{type:"attribute",name:si(s).name,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)};if(this.isCSSProperty(s))return{type:"styles",properties:[s.substring(1).trim()],targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}const s=this.parseClassNames(r);if(0===s.length)throw Error("remove command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}execute(t,e){switch(t.type){case"classes":{const n=hi(t.classes,e);n.length>0&&oi(t.targets,n,(t,e)=>{t.classList.remove(e)});break}case"attribute":n=t.name,ii(t.targets,t=>{t.removeAttribute(n)});break;case"styles":oi(t.targets,t.properties,(t,e)=>{t.style.removeProperty(e)});break;case"element":for(const e of t.targets)Ii(e)}var n}validate(t){if("object"!=typeof t||null===t)return 0;const e=t;if(!this.validateType(e.type,["classes","attribute","styles","element"]))return 0;if(!this.validateTargets(e.targets))return 0;if("classes"===e.type){if(!this.validateStringArray(t.classes,1))return 0}else if("attribute"===e.type){if("string"!=typeof t.name||0===t.name.length)return 0}else if("styles"===e.type&&!this.validateStringArray(t.properties,1))return 0;return 1}},ni(e,"RemoveCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;ti(null,t={value:e},n,{kind:"class",name:e.name,metadata:i},null,r),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:i}),ei(e,r)})(),e})();const Mi=gi(ji);function Di(t){const e=t.trim().match(/^(\d+(?:\.\d+)?)\s*(s|ms|sec|seconds?|milliseconds?)?$/i);if(!e)return null;const n=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();return"ms"===r||"millisecond"===r||"milliseconds"===r?{number:n,milliseconds:Math.floor(n)}:"s"===r||"sec"===r||"second"===r||"seconds"===r?{number:n,milliseconds:Math.floor(1e3*n)}:null}function Pi(t){if("number"==typeof t){if(0>t)throw Error("Duration must be >= 0");return Math.floor(t)}if("string"==typeof t){const e=Di(t);if(!e)throw Error(`Invalid duration format: "${t}"`);return e.milliseconds}throw Error("Invalid duration type: "+typeof t)}function Fi(t){return 0===t.length?[]:"SUMMARY"===t[0].tagName?t.map(t=>t.closest("details")).filter(t=>null!==t):t}function Bi(t,e,n){return()=>{"class"===e?t.classList.toggle(n):"attribute"===e&&ai(t,n)}}function _i(t,e,n,r){const s=Bi(t,e,n),i=setTimeout(s,r);return()=>{clearTimeout(i)}}function Vi(t,e,n,r){const s=Bi(t,e,n),i=()=>{s(),t.removeEventListener(r,i)};return t.addEventListener(r,i,{once:1}),()=>{t.removeEventListener(r,i)}}function qi(t,e,n){if(e.startsWith("@")){const r=e.substring(1);return void(0==n?t.removeAttribute(r):t.setAttribute(r,1==n?"":n+""))}const r=n+"";switch(e){case"textContent":return void(t.textContent=r);case"innerHTML":return void(t.innerHTML=r);case"innerText":return void(t.innerText=r);case"id":return void(t.id=r);case"className":return void(t.className=r);case"value":return void("value"in t&&(t.value=r));case"checked":return void("checked"in t&&(t.checked=!!n))}if(e.includes(".")){const r=e.split(".");let s=t;for(let t=0;r.length-1>t;t++)if(s=s[r[t]],null==s)return;return void(s[r[r.length-1]]=n)}if(e.includes("-")||e in t.style)t.style.setProperty(e,r);else try{t[e]=n}catch(t){if(!(t instanceof TypeError&&(t.message.includes("only a getter")||t.message.includes("read only"))))throw Error(`Cannot set property '${e}': ${t instanceof Error?t.message:"Unknown error"}`)}}const Hi=/^the\s+(.+?)\s+of\s+(.+)$/i,Ui=new Set(["disabled","checked","hidden","readOnly","readonly","required","multiple","selected","autofocus","autoplay","controls","loop","muted","open","reversed","async","defer","noValidate","novalidate","formNoValidate","formnovalidate","draggable","spellcheck","contentEditable"]);function Wi(t){return"string"==typeof t&&Hi.test(t)}function zi(t,e){const n=t.match(Hi);if(!n)return null;try{return{element:bi(n[2].trim(),e),property:n[1].trim()}}catch{return null}}async function Ji(t,e,n){if(function(t){return t&&"object"==typeof t?"propertyOfExpression"===t.type&&"object"==typeof t.property&&null!==t.property:0}(t))return async function(t,e,n){const r=t.property?.name;if(!r)return null;let s=await e.evaluate(t.target,n);return Array.isArray(s)&&(s=s[0]),sn(s)?{element:s,property:r}:null}(t,e,n);if(function(t){return t&&"object"==typeof t?"propertyAccess"!==t.type?0:"string"==typeof t.property||"object"==typeof t.property&&null!==t.property&&"string"==typeof t.property.name:0}(t))return async function(t,e,n){const r="string"==typeof t.property?t.property:t.property?.name;if(!r)return null;let s=await e.evaluate(t.object,n);return Array.isArray(s)&&(s=s[0]),sn(s)?{element:s,property:r}:null}(t,e,n);const r=t;if("possessiveExpression"===r?.type||"memberExpression"===r?.type){const t=r.object,s=r.property;let i=await e.evaluate(t,n);if(Array.isArray(i)&&(i=i[0]),!sn(i))return null;const o=s?.name||s?.value;return o?{element:i,property:o}:null}return null}function Zi(t,e){const{element:n,property:r}=t;r.startsWith("*")?Ni(n,r.substring(1),e+""):qi(n,r,e)}async function Gi(t,e,n){let r,s;if(t?.for){const s=await e.evaluate(t.for,n);r="number"==typeof s?s:"string"==typeof s?function(t,e=300){if("number"==typeof t)return Math.max(0,Math.floor(t));if("string"==typeof t){const n=Di(t);return n?n.milliseconds:e}return e}(s):void 0}if(t?.until){const r=await e.evaluate(t.until,n);"string"==typeof r&&(s=r)}return{duration:r,untilEvent:s}}const Xi=gi((()=>{let t,e,n=[yi({description:"Toggle classes, attributes, or interactive elements",syntax:["toggle <class> [on <target>]","toggle @attr","toggle <element> [as modal]","toggle <expr> for <duration>"],examples:["toggle .active on me","toggle @disabled","toggle #myDialog as modal","toggle .loading for 2s"],sideEffects:["dom-mutation"]}),mi({name:"toggle",category:"dom"})],r=[];return e=class{async parseInput(t,e,n){if(!t.args?.length)throw Error("toggle command requires an argument");let r=0;if(function(t){if(!t||"asExpression"!==t.type)return 0;const e=t.targetType,n="string"==typeof e?e:e?.name;return"string"==typeof n&&"modal"===n.toLowerCase()}(t.args[0])){r=1;const e=t.args[0].expression;t={...t,args:[e,...t.args.slice(1)]}}const s=t.args[0],i=s?.name;if("between"===i&&t.args.length>=4){const{duration:r,untilEvent:s}=await Gi(t.modifiers,e,n),i=async t=>{const r=t;return"selector"===r?.type?r.value:e.evaluate(t,n)},o=await i(t.args[1]),a=await i(t.args[3]),c=[];for(let e=4;t.args.length>e;e++){const n=t.args[e]?.name;"on"!==n&&"from"!==n&&c.push(t.args[e])}const u={filterPrepositions:1,fallbackModifierKey:"on"},l=await ki(c,e,n,"toggle",u,t.modifiers);return{type:"classes-between",classA:(o+"").replace(/^\./,""),classB:(a+"").replace(/^\./,""),targets:l,duration:r,untilEvent:s}}const o=await Ji(s,e,n);if(o)return{type:"property",target:o};if("selector"===s.type&&"string"==typeof s.value&&s.value.startsWith("*")){let r=s.value,i=1;if("*"===r&&t.args.length>1&&"identifier"===t.args[1].type&&(r="*"+t.args[1].name,i=2),"*"===r&&t.modifiers?.on){const s=t.modifiers.on?.name;if(s&&["display","visibility","opacity"].includes(s)){r="*"+s;const{duration:i,untilEvent:o}=await Gi(t.modifiers,e,n),a=Ai(r);if(a){const t=n.me;return{type:"css-property",property:a,targets:t?[t]:[],duration:i,untilEvent:o}}}}const o=Ai(r);if(o){const{duration:r,untilEvent:s}=await Gi(t.modifiers,e,n),a={filterPrepositions:1,fallbackModifierKey:"on"};return{type:"css-property",property:o,targets:await ki(t.args.slice(i),e,n,"toggle",a,t.modifiers),duration:r,untilEvent:s}}}const{duration:a,untilEvent:c}=await Gi(t.modifiers,e,n),{value:u}=await Oi(s,e,n);if(Wi(u)){const t=zi(u,n);if(t)return{type:"property",target:t}}const{type:l,expression:h}=function(t,e){const n=e?.name,r=function(t){if(!t||"object"!=typeof t)return 0;if("identifier"!==t.type)return 0;const e=t.name;return"string"==typeof e&&function(t){if("string"!=typeof t)return 0;const e=t.toLowerCase();return Ci.includes(e)}(e)}(e);if(sn(t)||Array.isArray(t)&&t.every(t=>sn(t)))return{type:"element",expression:""};if(r&&n)return{type:"element",expression:n};if("string"==typeof t){const e=t.trim();return e.startsWith("@")||e.startsWith("[@")?{type:"attribute",expression:e}:e.startsWith("*")?{type:"css-property",expression:e}:e.startsWith(".")?{type:"class",expression:e}:e.startsWith("#")||function(t){if("string"!=typeof t)return 0;const e=t.toLowerCase();return Ci.some(t=>e.includes(t))}(e)?{type:"element",expression:e}:{type:"class",expression:e}}return{type:"class",expression:""}}(u,s),f={filterPrepositions:1,fallbackModifierKey:"on"};switch(l){case"attribute":{const{name:r,value:s}=si(h);return{type:"attribute",name:r,value:s,targets:await ki(t.args.slice(1),e,n,"toggle",f,t.modifiers),duration:a,untilEvent:c}}case"css-property":{const r=Ai(h);if(!r)throw Error("Invalid CSS property: "+h);return{type:"css-property",property:r,targets:await ki(t.args.slice(1),e,n,"toggle",f,t.modifiers)}}case"element":{let i;if(sn(u))i=[u];else if(Array.isArray(u)&&u.every(t=>sn(t)))i=u;else if(h){const t=document.querySelectorAll(h);i=Array.from(t).filter(t=>sn(t))}else i=await ki([s],e,n,"toggle",f,t.modifiers);const o=function(t){if(0===t.length)return null;const e=t[0].tagName;if(!t.every(t=>t.tagName===e))return null;switch(e){case"DIALOG":return"dialog";case"DETAILS":return"details";case"SELECT":return"select";case"SUMMARY":return t.map(t=>t.closest("details")).filter(t=>null!==t).length>0?"details":null;default:return null}}(i);if("dialog"===o){const s=r?"modal":await async function(t,e,n,r){if(e?.as){const t=await n.evaluate(e.as,r);if("string"==typeof t&&"modal"===t.toLowerCase())return"modal"}if(t.length>=2){const e=await n.evaluate(t[1],r);if("string"==typeof e){const s=e.toLowerCase();if("modal"===s||"as modal"===s)return"modal";if("as"===s&&t.length>=3){const e=await n.evaluate(t[2],r);if("string"==typeof e&&"modal"===e.toLowerCase())return"modal"}}}return"non-modal"}(t.args,t.modifiers,e,n);return{type:"dialog",mode:s,targets:i}}return"details"===o?{type:"details",targets:Fi(i)}:"select"===o?{type:"select",targets:i}:{type:"classes",classes:ci(h),targets:i,duration:a,untilEvent:c}}default:{const r=ci(h||u);if(!r.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:r,targets:await ki(t.args.slice(1),e,n,"toggle",f,t.modifiers),duration:a,untilEvent:c}}}}async execute(t,e){switch(t.type){case"classes":{const n=hi(t.classes,e);if(0===n.length)return[...t.targets];if(oi(t.targets,n,(t,e)=>{t.classList.toggle(e)}),(t.duration||t.untilEvent)&&n.length)for(const e of t.targets)t.duration&&_i(e,"class",n[0],t.duration),t.untilEvent&&Vi(e,"class",n[0],t.untilEvent);return[...t.targets]}case"attribute":if(n=t.name,r=t.value,ii(t.targets,t=>{ai(t,n,r)}),t.duration||t.untilEvent)for(const e of t.targets)t.duration&&_i(e,"attribute",t.name,t.duration),t.untilEvent&&Vi(e,"attribute",t.name,t.untilEvent);return[...t.targets];case"css-property":return ii(t.targets,e=>function(t,e){const n=window.getComputedStyle(t);switch(e){case"display":"none"===n.display?(t.style.display=t.dataset.previousDisplay||"block",delete t.dataset.previousDisplay):(t.dataset.previousDisplay=n.display,t.style.display="none");break;case"visibility":t.style.visibility="hidden"===n.visibility?"visible":"hidden";break;case"opacity":t.style.opacity=0===parseFloat(n.opacity)?"1":"0"}}(e,t.property));case"property":return function(t){const e=function(t){const{element:e,property:n}=t;return n.startsWith("*")?function(t,e){return window.getComputedStyle(t).getPropertyValue(e)}(e,n.substring(1)):En(e,n)}(t),n=t.property,r=n.startsWith("@")?n.substring(1):n;if("boolean"==typeof e||Ui.has(r)||Ui.has(r.toLowerCase())){const n=!e;return Zi(t,n),n}if("number"==typeof e){const n=0===e?1:0;return Zi(t,n),n}if("string"==typeof e){const r="__ht_"+n,s=t.element[r];return""===e&&void 0!==s?(Zi(t,s),s):(t.element[r]=e,Zi(t,""),"")}Zi(t,!e)}(t.target),[t.target.element];case"dialog":return ii(t.targets,e=>{return r=t.mode,void((n=e).open?n.close():"modal"===r?n.showModal():n.show());var n,r});case"details":return ii(t.targets,t=>{var e;(e=t).open=!e.open});case"select":return ii(t.targets,t=>function(t){if(document.activeElement===t)t.blur();else{if(t.focus(),"showPicker"in t&&"function"==typeof t.showPicker)try{return void t.showPicker()}catch{}const e=new MouseEvent("click",{view:window,bubbles:1,cancelable:1});t.dispatchEvent(e)}}(t));case"classes-between":for(const e of t.targets){const n=e.classList.contains(t.classA),r=e.classList.contains(t.classB);n?(e.classList.remove(t.classA),e.classList.add(t.classB)):r?(e.classList.remove(t.classB),e.classList.add(t.classA)):e.classList.add(t.classA)}if(t.duration||t.untilEvent)for(const e of t.targets)t.duration&&_i(e,"class",t.classA,t.duration),t.untilEvent&&Vi(e,"class",t.classA,t.untilEvent);return[...t.targets]}var n,r}},ni(e,"ToggleCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),ei(e,r)})(),e})());class Yi{async parseInput(t,e,n){const{targets:r}=await async function(t,e,n,r){return{targets:await ki(t.args,e,n,r)}}(t,e,n,this.mode);return{targets:r,mode:this.mode,defaultDisplay:"show"===this.mode?"block":void 0}}validate(t){if("object"!=typeof t||null===t)return 0;const e=t;return Array.isArray(e.targets)&&e.targets.every(t=>sn(t))?"show"!==e.mode&&"hide"!==e.mode||"show"===e.mode&&"string"!=typeof e.defaultDisplay?0:1:0}showElement(t,e="block"){const n=t.dataset.originalDisplay;void 0!==n?(t.style.display=n||e,delete t.dataset.originalDisplay):"none"===t.style.display&&(t.style.display=e),t.classList.add("show")}hideElement(t){if(!t.dataset.originalDisplay){const e=t.style.display;t.dataset.originalDisplay="none"===e?"":e}t.style.display="none",t.classList.remove("show")}}let Ki=(()=>{let t,e,n=[yi({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"]}),mi({name:"show",category:"dom"})],r=[],s=Yi;return e=class extends s{constructor(){super(...arguments),this.mode="show"}async execute(t,e){const n=t.defaultDisplay||"block";for(const e of t.targets)this.showElement(e,n)}validate(t){if("object"!=typeof t||null===t)return 0;const e=t;return Array.isArray(e.targets)&&e.targets.every(t=>sn(t))?"string"!=typeof e.defaultDisplay?0:1:0}},ni(e,"ShowCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;ti(null,t={value:e},n,{kind:"class",name:e.name,metadata:i},null,r),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:i}),ei(e,r)})(),e})();const Qi=gi(Ki);let to=(()=>{let t,e,n=[yi({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"]}),mi({name:"hide",category:"dom"})],r=[],s=Yi;return e=class extends s{constructor(){super(...arguments),this.mode="hide"}async execute(t,e){for(const e of t.targets)this.hideElement(e)}validate(t){if("object"!=typeof t||null===t)return 0;const e=t;return Array.isArray(e.targets)&&e.targets.every(t=>sn(t))?1:0}},ni(e,"HideCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;ti(null,t={value:e},n,{kind:"class",name:e.name,metadata:i},null,r),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:i}),ei(e,r)})(),e})();const eo=gi(to),no=gi((()=>{let t,e,n=[yi({description:"Insert content into elements or properties",syntax:["put <value> into <target>","put <value> before <target>","put <value> after <target>"],examples:['put "Hello World" into me',"put <div>Content</div> before #target","put value into #elem's innerHTML"],sideEffects:["dom-mutation"]}),mi({name:"put",category:"dom"})],r=[];return e=class{async parseInput(t,e,n){if(!t.args?.length)throw Error("put requires arguments");const r=t=>t?.type||"unknown",s=["into","before","after","at","at start of","at end of"];let i=-1,o=null;for(let e=0;t.args.length>e;e++){const n=t.args[e],a=r(n),c="literal"===a?n.value:n.name;if(("literal"===a||"identifier"===a)&&s.includes(c)){i=e,o=c;break}}let a=null,c=null;if(-1===i){const e=s.find(e=>t.modifiers[e]);if(e)a=t.args[0],o=e,c=t.modifiers[e];else if(3>t.args.length){if(2>t.args.length)throw Error("put requires content and position");a=t.args[0],o=t.args[1]?.value||t.args[1]?.name||"into"}else a=t.args[0],o=t.args[1]?.value||t.args[1]?.name||null,c=t.args[2]}else a=t.args.slice(0,i)[0]||null,c=t.args.slice(i+1)[0]||null;if(!a)throw Error("put requires content");if(!o)throw Error("put requires position keyword");const u=await e.evaluate(a,n),l=this.mapPosition(o);let h,f,d=null;if(c){const t=r(c),s=await Ji(c,e,n);if(s)return{value:u,targets:[s.element],position:"replace",memberPath:s.property};if("memberExpression"===t){const t=c.object,r=c.property;if("selector"===t?.type)d=t.value;else if("identifier"===t?.type){const s=t.name;if("my"===s||"me"===s||"I"===s){if(n.me&&r?.name)return{value:u,targets:[n.me],position:"replace",memberPath:r.name}}else if("its"===s||"it"===s){const t=await e.evaluate(c,n);"string"==typeof t&&(d=t)}else d=s}if(d&&r?.name)h=r.name;else if(!d&&!h){const t=await e.evaluate(c,n);"string"==typeof t&&(d=t)}}else if("identifier"===t&&"me"===c.name)d=null;else if("selector"===t||"cssSelector"===t)d=c.value||c.selector;else if("literal"===t){const t=c.value;if("string"==typeof t&&Wi(t)){const e=zi(t,n);if(e)return{value:u,targets:[e.element],position:"replace",memberPath:e.property}}"string"==typeof t&&this.looksLikeCss(t)?d=t:f=t+""}else if("identifier"===t){const t=c.name;if(this.looksLikeCss(t))d=t;else{const r=await e.evaluate(c,n),s=this.resolveEvaluatedAsElements(r);if(s)return{value:u,targets:s,position:l,memberPath:h};f=t}}else{const t=await e.evaluate(c,n),r=this.resolveEvaluatedAsElements(t);if(r)return{value:u,targets:r,position:l,memberPath:h};"string"==typeof t&&(this.looksLikeCss(t)?d=t:f=t)}}return f?{value:u,targets:[],position:l,memberPath:h,variableName:f}:{value:u,targets:await this.resolveTargets(d,n),position:l,memberPath:h}}async execute(t,e){const{value:n,targets:r,position:s,memberPath:i,variableName:o}=t;if(o)return e.locals&&e.locals.set(o,n),e[o]=n,void Object.assign(e,{it:n});if(i)for(const t of r)this.setProperty(t,i,n);else for(const t of r){const e=this.parseValue(n);this.insertContent(t,e,s)}return r}mapPosition(t){switch(t){case"into":return"replace";case"before":return"beforebegin";case"after":return"afterend";case"at start of":return"afterbegin";case"at end of":return"beforeend";default:throw Error("Invalid position: "+t)}}async resolveTargets(t,e){if(!t||"me"===t){if(!e.me||!sn(e.me))throw Error("put: no target and context.me is null");return[e.me]}const n=Array.from(document.querySelectorAll(t)).filter(t=>sn(t));if(!n.length)throw Error(`No elements: "${t}"`);return n}parseValue(t){return sn(t)?t:null==t?"":t+""}insertContent(t,e,n){if("replace"!==n)if(sn(e)){const r=e;switch(n){case"beforebegin":t.parentElement?.insertBefore(r,t);break;case"afterbegin":t.insertBefore(r,t.firstChild);break;case"beforeend":t.appendChild(r);break;case"afterend":t.parentElement?.insertBefore(r,t.nextSibling)}}else e.includes("<")&&e.includes(">")?t.insertAdjacentHTML(n,e):t.insertAdjacentText(n,e);else sn(e)?(t.innerHTML="",t.appendChild(e)):e.includes("<")&&e.includes(">")?t.innerHTML=e:t.textContent=e}resolveEvaluatedAsElements(t){if(sn(t))return[t];if(Array.isArray(t)){const e=t.filter(sn);return e.length>0?e:null}if("undefined"!=typeof NodeList&&t instanceof NodeList){const e=Array.from(t).filter(sn);return e.length>0?e:null}return null}looksLikeCss(t){return t?/^[#.\[]/.test(t)||/[>+~\s]/.test(t)&&t.length>1?1:["div","span","p","a","button","input","form","ul","li","ol","table","tr","td","th","img","h1","h2","h3","h4","h5","h6","section","article","header","footer","nav","main","aside","dialog","label","select","option","textarea"].includes(t.toLowerCase()):0}setProperty(t,e,n){const r=e.split(".");let s=t;for(let t=0;r.length-1>t;t++){if(!s[r[t]])throw Error(`Property path "${e}" does not exist`);s=s[r[t]]}s[r[r.length-1]]=n}},ni(e,"PutCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),ei(e,r)})(),e})()),ro=gi((()=>{let t,e,n=[yi({description:"Set values to variables, attributes, or properties",syntax:["set <target> to <value>"],examples:['set myVar to "value"','set @data-theme to "dark"','set my innerHTML to "content"'],sideEffects:["state-mutation","dom-mutation"]}),mi({name:"set",category:"data"})],r=[];return e=class{async parseInput(t,e,n){if(!t.args?.length)throw Error("set command requires a target");const r=t.args[0],s=r?.name||r?.value,i=r?.scope,o=r?.type;if(o){const s=St.get(o);if(s)return{type:"node-write",node:r,value:await this.extractValue(t,e,n),writer:s}}const a=await this.resolveAttributeWriteTarget(r,t,e,n);if(a){const r=await this.extractValue(t,e,n);return{type:"attribute",elements:a.elements,name:a.name,value:r}}const c=await Ji(r,e,n);if(c){const r=await this.extractValue(t,e,n);if(c.property.startsWith("*")){const t=c.property.substring(1);return{type:"style",element:c.element,property:t,value:r+""}}return{type:"property",element:c.element,property:c.property,value:r}}if("memberExpression"===r?.type||"propertyAccess"===r?.type){const s=await this.tryParseMemberExpression(r,t,e,n);if(s)return s}let u;if(u="identifier"!==r?.type&&"variable"!==r?.type||"string"!=typeof s?await e.evaluate(r,n):s,function(t){if("object"!=typeof t||null===t||Array.isArray(t))return 0;if(sn(t)||t instanceof Node)return 0;const e=Object.getPrototypeOf(t);return e===Object.prototype||null===e}(u))return{type:"object-literal",properties:u,targets:await this.resolveTargets(t.modifiers.on,e,n)};if(Wi(u)){const r=zi(u,n);if(r){const s=await this.extractValue(t,e,n);return{type:"property",element:r.element,property:r.property,value:s}}return this.parseTheXofY(u,t,e,n)}if("string"==typeof u&&Si(u)){const r=u.substring(1).trim(),s=await this.extractValue(t,e,n);return{type:"style",element:await this.resolveElement(t.modifiers.on,e,n),property:r,value:s+""}}if("string"==typeof u&&ri(u)){const r=u.substring(1).trim(),s=await this.extractValue(t,e,n);return{type:"attribute",elements:await this.resolveTargets(t.modifiers.on,e,n),name:r,value:s}}if("string"==typeof u){const r=u.match(/^(my|me|its?|your?)\s+(.+)$/i);if(r){const s=Ei(r[1],n),i=await this.extractValue(t,e,n);return{type:"property",element:s,property:r[2],value:i}}}if(sn(u))return{type:"property",element:u,property:"textContent",value:await this.extractValue(t,e,n)};if(Array.isArray(u)&&u.length>0&&sn(u[0])){const r=await this.extractValue(t,e,n);return{type:"property",element:u[0],property:"textContent",value:r}}if("string"!=typeof u)throw Error("set command target must be a string or object literal"+("memberExpression"===r?.type||"propertyAccess"===r?.type?` (a property chain evaluated to ${null===u?"null":typeof u} — check that all intermediate objects exist)`:""));return{type:"variable",name:u,value:await this.extractValue(t,e,n),scope:"element"===i||"global"===i?i:void 0}}async execute(t,e){switch(t.type){case"variable":return"element"===t.scope?nn(e,t.name,t.value):"global"===t.scope?cn(t.name,t.value,e,"global"):cn(t.name,t.value,e),"result"!==t.name&&"it"!==t.name||Object.assign(e,{[t.name]:t.value}),Object.assign(e,{it:t.value}),{target:t.name,value:t.value,targetType:"variable"};case"attribute":for(const e of t.elements)e.setAttribute(t.name,t.value+"");return Object.assign(e,{it:t.value}),{target:"@"+t.name,value:t.value,targetType:"attribute"};case"property":return qi(t.element,t.property,t.value),Object.assign(e,{it:t.value}),{target:t.element,value:t.value,targetType:"property"};case"style":return Ni(t.element,t.property,t.value),Object.assign(e,{it:t.value}),{target:t.element,value:t.value,targetType:"property"};case"object-literal":for(const e of t.targets)for(const[n,r]of Object.entries(t.properties))qi(e,n,r);return Object.assign(e,{it:t.properties}),{target:t.targets[0]||"unknown",value:t.properties,targetType:"property"};case"member-assignment":return t.container[t.property]=t.value,Object.assign(e,{it:t.value}),{target:t.property,value:t.value,targetType:"property"};case"node-write":return await t.writer(t.node,t.value,e),Object.assign(e,{it:t.value}),{target:t.node.name??"",value:t.value,targetType:"variable"};default:throw Error("Unknown input type: "+t.type)}}async resolveAttributeWriteTarget(t,e,n,r){const s=t;if("attributeAccess"===s?.type)return{elements:await this.resolveTargets(e.modifiers.on,n,r),name:s.attributeName};if("binaryExpression"===s?.type&&"of"===s.operator&&"attributeAccess"===s.left?.type){const t=await this.evaluateToElement(s.right,n,r);if(t)return{elements:[t],name:s.left.attributeName}}if("memberExpression"===s?.type&&"attributeAccess"===s.property?.type){const t=await this.evaluateToElement(s.object,n,r);if(t)return{elements:[t],name:s.property.attributeName}}return null}async evaluateToElement(t,e,n){const r=await e.evaluate(t,n),s=Array.isArray(r)?r[0]:r;return sn(s)?s:null}async tryParseMemberExpression(t,e,n,r){const s=t.object,i=t.property;if(s?.name&&i?.name){const t=s.name.toLowerCase();if(["me","my","it","its","you","your"].includes(t)){const s=Ei(t,r),o=await this.extractValue(e,n,r);return{type:"property",element:s,property:i.name,value:o}}}const o=t.object,a=t.computed;if(o){const s=o;let c;if("memberExpression"===s.type&&!s.computed&&"style"===s.property?.name&&s.object){const t=await n.evaluate(s.object,r);c=(t&&"object"==typeof t&&"style"in t?t.style:void 0)??await n.evaluate(o,r)}else c=await n.evaluate(o,r);if(null!=c&&"object"==typeof c){const s=a?await n.evaluate(t.property,r)+"":i?.name||"";if(s)return{type:"member-assignment",container:c,property:s,value:await this.extractValue(e,n,r)}}}return null}async extractValue(t,e,n){if(t.modifiers.to)return e.evaluate(t.modifiers.to,n);const r=t.args.findIndex(t=>"identifier"===t.type&&"to"===t.name);if(r>=0&&t.args.length>r+1)return e.evaluate(t.args[r+1],n);if(t.args.length>=2)return e.evaluate(t.args[1],n);throw Error('set command requires a value (use "to" keyword)')}async resolveElement(t,e,n){return bi(t?await e.evaluate(t,n):void 0,n)}async resolveTargets(t,e,n){return function(t,e){if(Array.isArray(t))return t.filter(sn);if(on(t))return Array.from(t).filter(sn);if(sn(t))return[t];if(!t){const t=e.me;return t&&sn(t)?[t]:[]}if("string"==typeof t){const n=t.trim();if("me"===n)return e.me&&sn(e.me)?[e.me]:[];if("it"===n)return sn(e.it)?[e.it]:[];if("you"===n)return e.you&&sn(e.you)?[e.you]:[];const r=e.me?.ownerDocument??("undefined"!=typeof document?document:null);if(r){let t=n;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const e=r.querySelectorAll(t);return Array.from(e).filter(sn)}}return[]}(t?await e.evaluate(t,n):void 0,n)}async parseTheXofY(t,e,n,r){const s=t.match(/^the\s+(.+?)\s+of\s+(.+)$/i);if(!s)throw Error('Invalid "the X of Y" syntax');const[,i,o]=s,a=bi(o,r),c=await this.extractValue(e,n,r);return{type:"property",element:a,property:i.trim(),value:c}}validate(t){if(!t||"object"!=typeof t)return 0;const e=t;if(!e.type||"string"!=typeof e.type)return 0;if(!["variable","attribute","property","style","object-literal"].includes(e.type))return 0;switch(e.type){case"variable":return"string"==typeof e.name&&"value"in e;case"attribute":return"string"==typeof e.name&&Array.isArray(e.elements)&&e.elements.every(sn)&&"value"in e;case"property":return"string"==typeof e.property&&sn(e.element)&&"value"in e;case"style":return"string"==typeof e.property&&""!==e.property&&sn(e.element)&&"string"==typeof e.value;case"object-literal":return null!==e.properties&&"object"==typeof e.properties&&Array.isArray(e.targets)&&e.targets.length>0;default:return 0}}},ni(e,"SetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),ei(e,r)})(),e})());function so(t){const e=t.trim();return/^\d+$/.test(e)?parseInt(e,10):/^\d*\.\d+$/.test(e)?parseFloat(e):"true"===e?1:"false"===e?0:"null"===e?null:"undefined"!==e?e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e:void 0}const io=gi((()=>{let t,e,n=[yi({description:"Dispatch events on elements",syntax:["trigger <event> on <target>","trigger <event>(<detail>) on <target>","send <event> to <target>","send <event>(<detail>) to <target>"],examples:["trigger click on #button","trigger customEvent on me","send dataEvent to #target","send myEvent(count: 42) to me"],sideEffects:["event-dispatch"],aliases:["send"]}),mi({name:"trigger",category:"event"})],r=[];return e=class{async parseInput(t,e,n){const r="send"===t.commandName?.toLowerCase()?"send":"trigger",s=r;if(!t.args?.length)throw Error(s+" command requires an event name");const i=t=>t?.type||"unknown",o=t.args[0];let a,c,u;if("functionCall"===i(o)||"callExpression"===i(o)){a=o.name||o.callee?.name;const t=o.args||o.arguments;t?.length&&(c=await this.parseEventDetail(t,e,n))}else if("identifier"===i(o)||"keyword"===i(o))a=o.name;else{const t=await e.evaluate(o,n);a="string"==typeof t?t:t+""}const l=t.modifiers?.on||t.modifiers?.to;if(l)u=await this.resolveTargets([l],e,n,s);else{const r=t.args.findIndex((t,e)=>{if(0===e)return 0;const n=t.name||t.value;return"on"===n||"to"===n});if(-1!==r&&t.args.length-1>r){const i=t.args.slice(r+1),o=i.findIndex(t=>"with"===(t.name||t.value)),a=-1===o?i:i.slice(0,o);u=await this.resolveTargets(a,e,n,s)}else{if(!n.me)throw Error(s+": no target specified and context.me is null");u=[n.me]}}return{eventName:a,detail:c,targets:u,options:await this.parseEventOptions(t.args,e,n),mode:r}}async execute(t,e){const n=function(t,e,n={}){return new CustomEvent(t,{detail:void 0!==e?e:{},bubbles:void 0!==n.bubbles?n.bubbles:1,cancelable:void 0!==n.cancelable?n.cancelable:1,composed:void 0!==n.composed?n.composed:0})}(t.eventName,t.detail,t.options);for(const e of t.targets)e.dispatchEvent(n);e.it=n}async resolveTargets(t,e,n,r){const s=[];for(const r of t){const t=await e.evaluate(r,n);if("window"!==t&&t!==window)if("document"!==t&&t!==document)if("me"===t&&n.me)s.push(n.me);else if("you"===t&&n.you)s.push(n.you);else if("it"===t&&n.it)s.push(n.it);else if(sn(t))s.push(t);else if(t instanceof NodeList)s.push(...Array.from(t).filter(sn));else if(Array.isArray(t))s.push(...t.filter(sn));else{if("string"==typeof t){const e=document.querySelectorAll(t);if(0===e.length)throw Error(`No elements found: "${t}"`);s.push(...Array.from(e).filter(sn));continue}if(!t||"object"!=typeof t||!("addEventListener"in t))throw Error("Invalid target: "+typeof t);s.push(t)}else s.push(document);else s.push(window)}if(!s.length)throw Error(r+": no valid targets");return s}async parseEventDetail(t,e,n){if(!t?.length)return;if(1===t.length){const r=t[0];if("objectLiteral"!==r?.type)return await e.evaluate(r,n)}const r={};for(const s of t){const t=await e.evaluate(s,n);if("object"!=typeof t||null===t||Array.isArray(t)){if("string"==typeof t&&t.includes(":")){const[e,n]=t.split(":",2);r[e.trim()]=so(n.trim())}}else Object.assign(r,t)}return Object.keys(r).length?r:void 0}async parseEventOptions(t,e,n){const r={bubbles:1,cancelable:1,composed:0},s=t.findIndex(t=>"with"===(t.name||t.value));if(-1===s)return r;for(const i of t.slice(s+1)){const t=await e.evaluate(i,n);if("string"==typeof t){const e=t.toLowerCase();"bubbles"===e?r.bubbles=1:"nobubbles"===e?r.bubbles=0:"cancelable"===e?r.cancelable=1:"nocancelable"===e?r.cancelable=0:"composed"===e&&(r.composed=1)}}return r}},ni(e,"EventDispatchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),ei(e,r)})(),e})()),oo=gi((()=>{let t,e,n=[yi({description:"Log values to the console",syntax:"log [<values...>]",examples:['log "Hello World"',"log me.value","log x y z",'log "Result:" result'],sideEffects:["console-output"]}),mi({name:"log",category:"utility"})],r=[];return e=class{async parseInput(t,e,n){return t.args&&0!==t.args.length?{values:await Promise.all(t.args.map(t=>e.evaluate(t,n)))}:{values:[]}}async execute(t,e){const n="undefined"!=typeof window?window.console:console;0===t.values.length?n.log():n.log(...t.values)}validate(t){return"object"!=typeof t||null===t?0:Array.isArray(t.values)}},ni(e,"LogCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),ei(e,r)})(),e})());function ao(t,e,n,r){return t?new Promise(n=>{const s=()=>{i({event:null,timedOut:0,cancelled:1})},i=function(n,i){let a=0;return n=>{a||(a=1,t.removeEventListener(e,o),r&&r.removeEventListener("abort",s),i(n))}}(0,n),o=t=>{i({event:t,timedOut:0,cancelled:0})};r?.aborted?n({event:null,timedOut:0,cancelled:1}):(t.addEventListener(e,o),r&&r.addEventListener("abort",s))}):Promise.reject(Error("waitForEvent: no target provided"))}function co(t){return new Promise(e=>setTimeout(e,t))}const uo=gi((()=>{let t,e,n=[yi({description:"Wait for time delay, event, or race condition",syntax:["wait <time>","wait for <event>","wait for <event> or <condition>"],examples:["wait 2s","wait for click","wait for click or 1s","wait for mousemove(clientX, clientY)"],sideEffects:["time","event-listening"]}),mi({name:"wait",category:"async"})],r=[];return e=class{async parseInput(t,e,n){if(!t.args?.length)throw Error("wait command requires an argument");if(t.modifiers.or)return this.parseRaceCondition(t,e,n);if(t.modifiers.for)return this.parseEventWait(t.modifiers.for,t.modifiers.from,e,n);const r=t.args[0];return"arrayLiteral"===r.type&&r.elements?this.parseEventArrayWait(r.elements,t.args[1],e,n):this.parseTimeWait(t.args[0],e,n)}async execute(t,e){const n=Date.now();if("time"===t.type)return await co(t.milliseconds),{type:"time",result:t.milliseconds,duration:Date.now()-n};if("event"===t.type){const r=t.target??e.me??document,s=(await ao(r,t.eventName)).event;if(Object.assign(e,{it:s}),t.destructure)for(const n of t.destructure)n in s&&e.locals.set(n,s[n]);return{type:"event",result:s,duration:Date.now()-n}}const{result:r,winningCondition:s}=await this.executeRace(t.conditions,e);if(Object.assign(e,{it:r}),r instanceof Event&&"event"===s?.type&&s.destructure)for(const t of s.destructure)t in r&&e.locals.set(t,r[t]);return{type:r instanceof Event?"event":"time",result:r,duration:Date.now()-n}}async parseTimeWait(t,e,n){return{type:"time",milliseconds:Pi(await e.evaluate(t,n))}}async parseEventWait(t,e,n,r){const s=await n.evaluate(t,r);if("string"!=typeof s)throw Error("wait for: event name must be a string");const i=s.match(/^(\w+)\(([^)]+)\)$/),o=i?i[1]:s,a=i?i[2].split(",").map(t=>t.trim()):void 0;let c;if(e){const t=await n.evaluate(e,r);if(!t||"object"!=typeof t||!("addEventListener"in t))throw Error("wait for from: target must be an EventTarget");c=t}else c=r.me??void 0;return{type:"event",eventName:o,target:c,destructure:a}}async parseEventArrayWait(t,e,n,r){const s=[];for(const e of t){const t=e;if("objectLiteral"===t.type&&t.properties){let e="",n=[];for(const r of t.properties){const t=r.key?.name||r.key?.value;"name"===t&&r.value?e=r.value.value||"":"args"===t&&r.value?.elements&&(n=r.value.elements.map(t=>t.value||t.name||""))}e&&s.push({name:e,params:n})}}let i;if(e){const t=await n.evaluate(e,r);t&&"object"==typeof t&&"addEventListener"in t&&(i=t)}return i||(i=r.me??void 0),1===s.length?{type:"event",eventName:s[0].name,target:i,destructure:s[0].params.length>0?s[0].params:void 0}:{type:"race",conditions:s.map(t=>({type:"event",eventName:t.name,target:i,destructure:t.params.length>0?t.params:void 0}))}}async parseRaceCondition(t,e,n){const r=[];t.modifiers.for?r.push(await this.parseEventWait(t.modifiers.for,t.modifiers.from,e,n)):t.args[0]&&r.push(await this.parseTimeWait(t.args[0],e,n));const s=await e.evaluate(t.modifiers.or,n),i=Array.isArray(s)?s:[s];for(const t of i)try{r.push({type:"time",milliseconds:Pi(t)})}catch{if("string"==typeof t){const e=t.match(/^(\w+)\(([^)]+)\)$/);r.push(e?{type:"event",eventName:e[1],target:n.me??void 0,destructure:e[2].split(",").map(t=>t.trim())}:{type:"event",eventName:t,target:n.me??void 0})}}if(2>r.length)throw Error("wait: race requires at least 2 conditions");return{type:"race",conditions:r}}async executeRace(t,e){const n=new AbortController,r=n.signal,s=t.map(t=>"time"===t.type?co(t.milliseconds).then(()=>({result:t.milliseconds,winningCondition:t})):ao(t.target??e.me??document,t.eventName,0,r).then(e=>({result:e.event,winningCondition:t})));try{return await Promise.race(s)}finally{n.abort()}}},ni(e,"WaitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),ei(e,r)})(),e})()),lo=function(t,e){const n=new qr(null);for(const e of t)n.register(e);return new Yr({registry:n,expressionRegistry:e.expressionRegistry,enableAsyncCommands:e.enableAsyncCommands??1,commandTimeout:e.commandTimeout??1e4,enableErrorReporting:e.enableErrorReporting??1,enableResultPattern:e.enableResultPattern??1})}([Li(),Mi(),Xi(),Qi(),eo(),no(),ro(),io(),oo(),uo()],{expressionRegistry:Ks()}),ho={parse:t=>We(t),execute:async(t,e)=>{const n=function(t){if(!t)return rn();if(t.locals instanceof Map&&t.globals instanceof Map&&t.flags)return t;const e=rn(t.me instanceof Element?t.me:null);return void 0!==t.it&&(e.it=t.it),void 0!==t.you&&(e.you=t.you),void 0!==t.result&&(e.result=t.result),void 0!==t.event&&Object.assign(e,{event:t.event}),e}(e),r=We(t);if(!r.success||!r.node)throw Error(r.error?.message||"Parse failed");return await lo.execute(r.node,n)}},fo=function(t){return new Qs(t)}(ho),po={runtime:ho,parse:t=>ho.parse(t),execute:async(t,e)=>ho.execute(t,e),createContext:rn,attributeProcessor:fo,version:"1.1.0-minimal-v2-tree-shakeable",commands:["add","remove","toggle","show","hide","put","set","send","log","wait"],eval:async(t,e)=>ho.execute(t,e),init:()=>{fo.init()}};"undefined"!=typeof window&&(window.hyperfixi=po,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{fo.init()}):fo.init());const mo={String:"string",Number:"number",Boolean:"boolean",Element:"element",ElementList:"element-list",Array:"array",Object:"object",Promise:"promise",Context:"object",Null:"null",Undefined:"undefined",Any:"object"},yo=Fn({collection:_n().describe("Collection to operate on (array, NodeList, or string)")}).strict(),go=Fn({collection:_n().describe("Collection to access"),index:Dn().describe("Index position to access")}).strict(),vo=Fn({collection:_n().describe("Collection to select random item from")}).strict();new class extends Hn{constructor(){super(...arguments),this.name="first",this.category="Positional",this.syntax="first in collection",this.description="Gets the first element from a collection",this.inputSchema=yo,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:r.errors[0]};const s=this.normalizeCollection(e.collection),i=s.length>0?s[0]:void 0,o={success:1,value:i,type:mo[this.inferEvaluationType(i)]};return this.trackPerformance(t,e,o,n),o}catch(r){const s=this.failure("FirstExpressionError","runtime-error","First operation failed: "+(r instanceof Error?r.message:r+""),"FIRST_OPERATION_FAILED");return this.trackPerformance(t,e,s,n),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid first input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends Hn{constructor(){super(...arguments),this.name="last",this.category="Positional",this.syntax="last in collection",this.description="Gets the last element from a collection",this.inputSchema=yo,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:r.errors[0]};const s=this.normalizeCollection(e.collection),i=s.length>0?s[s.length-1]:void 0,o={success:1,value:i,type:mo[this.inferEvaluationType(i)]};return this.trackPerformance(t,e,o,n),o}catch(r){const s=this.failure("LastExpressionError","runtime-error","Last operation failed: "+(r instanceof Error?r.message:r+""),"LAST_OPERATION_FAILED");return this.trackPerformance(t,e,s,n),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid last input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends Hn{constructor(){super(...arguments),this.name="at",this.category="Positional",this.syntax="collection[index] or collection at index",this.description="Gets element at specific index from a collection",this.inputSchema=go,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:r.errors[0]};const s=this.normalizeCollection(e.collection),i=this.normalizeIndex(e.index,s.length),o=i>=0&&s.length>i?s[i]:void 0,a={success:1,value:o,type:mo[this.inferEvaluationType(o)]};return this.trackPerformance(t,e,a,n),a}catch(r){const s=this.failure("AtExpressionError","runtime-error","At operation failed: "+(r instanceof Error?r.message:r+""),"AT_OPERATION_FAILED");return this.trackPerformance(t,e,s,n),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid at input: "+t.message,suggestions:[]}))??[],suggestions:["Provide collection and index parameters","Ensure index is a number"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}normalizeIndex(t,e){return 0>t?e+t:t}},new class extends Hn{constructor(){super(...arguments),this.name="random",this.category="Positional",this.syntax="random in collection",this.description="Gets a random element from a collection",this.inputSchema=vo,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:r.errors[0]};const s=this.normalizeCollection(e.collection);if(0===s.length){const r={success:1,value:void 0,type:"undefined"};return this.trackPerformance(t,e,r,n),r}const i=s[this.getSecureRandomIndex(s.length)],o={success:1,value:i,type:mo[this.inferEvaluationType(i)]};return this.trackPerformance(t,e,o,n),o}catch(r){const s=this.failure("RandomExpressionError","runtime-error","Random operation failed: "+(r instanceof Error?r.message:r+""),"RANDOM_OPERATION_FAILED");return this.trackPerformance(t,e,s,n),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid random input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}getSecureRandomIndex(t){if("undefined"!=typeof crypto&&crypto.getRandomValues){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]%t}return Math.floor(Math.random()*t)}};const bo={name:"first",category:"Reference",evaluatesTo:"Any",operators:["first"],async evaluate(t,e){const n=void 0!==e?e:t.it;return null==n?null:Array.isArray(n)||n instanceof NodeList||n instanceof HTMLCollection?n.length>0?n[0]:null:n instanceof Element?n.children.length>0?n.children[0]:null:ln(n)?n.length>0?n[0]:null:dn(n)&&"length"in n&&hn(n.length)&&n.length>0?n[0]:null},validate:t=>Tn(t,1,"first","collection")},wo={name:"last",category:"Reference",evaluatesTo:"Any",operators:["last"],async evaluate(t,e){const n=void 0!==e?e:t.it;if(null==n)return null;if(Array.isArray(n))return n.length>0?n[n.length-1]:null;if(n instanceof NodeList||n instanceof HTMLCollection)return n.length>0?n[n.length-1]:null;if(n instanceof Element){const t=n.children;return t.length>0?t[t.length-1]:null}return ln(n)?n.length>0?n[n.length-1]:null:dn(n)&&"length"in n&&hn(n.length)&&n.length>0?n[n.length-1]:null},validate:t=>Tn(t,1,"last","collection")},Eo={name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(t,...e){const[n,r]=e;if(!hn(n))throw Error("Index must be a number");const s=n,i=void 0!==r?r:t.it;if(null==i)return null;if(Array.isArray(i)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}if(i instanceof NodeList||i instanceof HTMLCollection){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}if(i instanceof Element){const t=i.children,e=0>s?t.length+s:s;return e>=0&&t.length>e?t[e]:null}if(ln(i)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}if(dn(i)&&"length"in i&&hn(i.length)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}return null},validate:t=>On(t,1,2,"at","index, optional collection")??function(t){return"number"!=typeof t[0]?"at index must be a number":null}(t)};function xo(t,e){let n=t.nextElementSibling;for(;n;){if(n.matches(e))return n;const t=n.querySelector(e);if(t)return t;n=n.nextElementSibling}const r=t.parentElement;return r&&r!==document.documentElement?xo(r,e):null}function ko(t,e){let n=t.previousElementSibling;for(;n;){const t=Array.from(n.querySelectorAll(e)).reverse();if(t.length>0)return t[0];if(n.matches(e))return n;n=n.previousElementSibling}const r=t.parentElement;return r&&r!==document.documentElement?ko(r,e):null}function So(t,e,n,r){if(n.inSearch){if(null==n.inElt)return;return function(t,e,n,r){const s=Array.from(e??[]),i=[];for(const e of s)(e.matches&&e.matches(n)||e===t)&&i.push(e);for(let e=0;i.length-1>e;e++)if(i[e]===t)return i[e+1];if(r){const t=i[0];if(t&&t.matches&&t.matches(n))return t}}(t,r?Array.from(n.inElt):Array.from(n.inElt).reverse(),e,!!n.wrapping)}const s=n.within??("undefined"!=typeof document?document.body:null);if(s)return r?function(t,e,n,r){const s=e.querySelectorAll(n);for(let e=0;s.length>e;e++){const n=s[e];if(2===n.compareDocumentPosition(t))return n}return r?s[0]:void 0}(t,s,e,!!n.wrapping):function(t,e,n,r){const s=e.querySelectorAll(n);for(let e=s.length-1;e>=0;e--){const n=s[e];if(4===n.compareDocumentPosition(t))return n}return r?s[s.length-1]:void 0}(t,s,e,!!n.wrapping)}function Ao(t){let e=0,n=t;for(;n&&n.parentElement;)e+=Array.from(n.parentElement.children).indexOf(n),n=n.parentElement,e+=1e3;return e}const No={first:bo,last:wo,at:Eo,next:{name:"next",category:"Reference",evaluatesTo:"Element",operators:["next"],async evaluate(t,...e){const[n,r,s]=e,i=r||t.me;return i&&i instanceof Element?n?s?So(i,n,s,1):xo(i,n):i.nextElementSibling:null},validate:t=>Tn(t,3,"next","optional selector, optional fromElement, optional modifiers")||(1>t.length||null==t[0]||"string"==typeof t[0]?2>t.length||null==t[1]||t[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},previous:{name:"previous",category:"Reference",evaluatesTo:"Element",operators:["previous","prev"],async evaluate(t,...e){const[n,r,s]=e,i=r||t.me;return i&&i instanceof Element?n?s?So(i,n,s,0):ko(i,n):i.previousElementSibling:null},validate:t=>Tn(t,3,"previous","optional selector, optional fromElement, optional modifiers")||(1>t.length||null==t[0]||"string"==typeof t[0]?2>t.length||null==t[1]||t[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},nextWithin:{name:"nextWithin",category:"Reference",evaluatesTo:"Element",operators:["next within"],async evaluate(t,...e){const[n,r,s]=e,i=s||t.me;if(!(i&&i instanceof Element))return null;const o=i.closest(r);return o?function(t,e,n){const r=Array.from(n.querySelectorAll(e)),s=Ao(t);for(const t of r)if(Ao(t)>s)return t;return null}(i,n,o):null},validate:t=>On(t,2,3,"nextWithin","selector, withinSelector, optional fromElement")||("string"!=typeof t[0]?"selector must be a string":"string"!=typeof t[1]?"withinSelector must be a string":3>t.length||null==t[2]||t[2]instanceof Element?null:"fromElement must be an Element")},previousWithin:{name:"previousWithin",category:"Reference",evaluatesTo:"Element",operators:["previous within"],async evaluate(t,...e){const[n,r,s]=e,i=s||t.me;if(!(i&&i instanceof Element))return null;const o=i.closest(r);return o?function(t,e,n){const r=Array.from(n.querySelectorAll(e)),s=Ao(t);for(let t=r.length-1;t>=0;t--){const e=r[t];if(s>Ao(e))return e}return null}(i,n,o):null},validate:t=>On(t,2,3,"previousWithin","selector, withinSelector, optional fromElement")||("string"!=typeof t[0]?"selector must be a string":"string"!=typeof t[1]?"withinSelector must be a string":3>t.length||null==t[2]||t[2]instanceof Element?null:"fromElement must be an Element")}};class Co{constructor(){this.name="addition",this.category="Special",this.syntax="left + right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=this.validate(e);if(!n.isValid)return{success:0,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e;return{success:1,value:us(as(t,"left operand")+as(n,"right operand"),"addition"),type:"number"}}catch(t){return{success:0,errors:[ps("runtime-error","Addition failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){const e=function(t){if(null==t)return ds([ps("missing-argument","Input is null or undefined")],["Provide an object with left and right operands"]);if("object"!=typeof t)return ds([ps("type-mismatch","Expected object, got "+typeof t)],["Provide an object with left and right operands"]);const e=t;if(!("left"in e)||!("right"in e)){const t=[];return"left"in e||t.push("left"),"right"in e||t.push("right"),ds([ps("missing-argument",`Missing ${t.join(" and ")} operand${t.length>1?"s":""}`)],["Provide { left: value, right: value }"])}return{isValid:1,errors:[],suggestions:[]}}(t);if(!e.isValid)return e;const{left:n,right:r}=t;return ls(n)?ls(r)?{isValid:1,errors:[],suggestions:[]}:{isValid:0,errors:[ps("type-mismatch","Right operand cannot be converted to number: "+r)],suggestions:["Provide a numeric value for right operand"]}:{isValid:0,errors:[ps("type-mismatch","Left operand cannot be converted to number: "+n)],suggestions:["Provide a numeric value for left operand"]}}}const To={addition:new Co,subtraction:new class{constructor(){this.name="subtraction",this.category="Special",this.syntax="left - right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=this.validate(e);if(!n.isValid)return{success:0,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e;return{success:1,value:us(as(t,"left operand")-as(n,"right operand"),"subtraction"),type:"number"}}catch(t){return{success:0,errors:[ps("runtime-error","Subtraction failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new Co).validate(t)}},multiplication:new class{constructor(){this.name="multiplication",this.category="Special",this.syntax="left * right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=this.validate(e);if(!n.isValid)return{success:0,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e;return{success:1,value:us(as(t,"left operand")*as(n,"right operand"),"multiplication"),type:"number"}}catch(t){return{success:0,errors:[ps("runtime-error","Multiplication failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new Co).validate(t)}},division:new class{constructor(){this.name="division",this.category="Special",this.syntax="left / right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=this.validate(e);if(!n.isValid)return{success:0,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=function(t,e,n=1){if(0===e){if(n)return 0===t?NaN:t>0?1/0:-1/0;throw Error("Division by zero")}return t/e}(as(t,"left operand"),as(n,"right operand"),1);return{success:1,value:r,type:"number"}}catch(t){return{success:0,errors:[ps("runtime-error","Division failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new Co).validate(t)}},modulo:new class{constructor(){this.name="modulo",this.category="Special",this.syntax="left mod right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=this.validate(e);if(!n.isValid)return{success:0,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=function(t,e){if(0===e)throw Error("Modulo by zero");return t%e}(as(t,"left operand"),as(n,"right operand"));return{success:1,value:r,type:"number"}}catch(t){return{success:0,errors:[ps("runtime-error","Modulo failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric and divisor is not zero"]}}}validate(t){return(new Co).validate(t)}},power:new class{constructor(){this.name="power",this.category="Special",this.syntax="left ** right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=this.validate(e);if(!n.isValid)return{success:0,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=as(t,"left operand"),s=as(n,"right operand");return{success:1,value:us(Math.pow(r,s),"power"),type:"number"}}catch(t){return{success:0,errors:[ps("runtime-error","Power failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new Co).validate(t)}}};var Oo=Object.freeze({__proto__:null,conversion:nr,conversionExpressions:nr,createCommonRegistry:function(){return Kr(es,zs,Ys,nr,No)},createCoreRegistry:Ks,createExpressionRegistry:Kr,createFullExpressionRegistry:function(){return Kr(es,zs,nr,No,or,Ys,To)},createFullRegistry:function(){return Kr(es,zs,Ys,nr,No,or)},logical:zs,logicalExpressions:zs,positional:No,positionalExpressions:No,properties:or,propertiesExpressions:or,references:es,referencesExpressions:es,special:Ys,specialExpressions:Ys});return po}();
1
+ var hyperfixi=function(){"use strict";const t="then",e="else",n="end",r="and",s="for",i="while",o="until",a="forever",c="times",l="index",u="in",h="to",f="from",d="with",p="of",m="on",y="event",g="behavior",v="global",b="the",w="start",E=new Set(["add","append","async","beep","blur","break","breakpoint","call","clear","close","continue","copy","decrement","default","empty","exit","fetch","focus","for","get","go","halt","hide","open","if","increment","install","js","log","make","measure","morph","pick","process","push","put","remove","render","repeat","replace","reset","return","scroll","select","send","set","settle","show","start","swap","take","tell","throw","toggle","transition","trigger","unless","wait"]),x=new Set(["put","trigger","send","remove","take","toggle","set","show","hide","add","halt","measure","js","go","tell","pick","start","swap","morph","push","replace","process"]),k=(new Set(["if","unless","repeat","wait","for","while"]),"at start of"),S="at end of",A=["into","before","after","at",k,S,"at the start of","at the end of"],N=new Set(["if","else","unless","for","while","until","end","and","or","not","in","to","from","into","with","without","as","matches","contains","then","on","when","every","init","def","behavior","the","of","first","last"]),C=new Set(["hsl","hsla","rgb","rgba","hwb","lab","lch","oklch","oklab","color","color-mix","calc","min","max","clamp","var","url","linear-gradient","radial-gradient","conic-gradient","repeating-linear-gradient","repeating-radial-gradient","repeating-conic-gradient"]),T=new Set(["me","it","you","result","my","its","your"]),O=new Set(["and","or","not","no"]),$=new Set(["==","!=","===","!==","<",">","<=",">=","is","is not","am","is a","is an","is not a","is not an","precedes","does not precede","follows","does not follow","contains","starts with","ends with","does not start with","does not end with","has","have","does not contain","include","includes","does not include","match","matches","exists","does not exist","is empty","is not empty","is in","is not in","is between","is not between","equals","in","is equal to","is really equal to","is not equal to","is not really equal to","is greater than","is less than","is greater than or equal to","is less than or equal to","really equals","am in","am not in","am between","am not between","is really","is not really","is equal","is not equal","contain","do not contain","does not contains","do not match","does not match","ignoring case","sorted by","mapped to","split by","joined by"]),R=new Set(["click","dblclick","mousedown","mouseup","mouseover","mouseout","mousemove","mouseenter","mouseleave","focus","blur","change","input","submit","reset","select","load","unload","resize","scroll","keydown","keyup","keypress","touchstart","touchend","touchmove","touchcancel","drag","drop","dragover","dragenter","dragleave","cut","copy","paste","toggle"]),L=new Set(["on","init","behavior","def","if","else","unless","for","while","until","end","and","or","not","in","to","from","into","with","as","then","when","where","after","before","by","at","between","async","no","start","of","the","new","global","local","equal","equals","greater","less","than","really","catch","finally","throw","return"]);var I;!function(t){t.IDENTIFIER="identifier",t.STRING="string",t.NUMBER="number",t.SELECTOR="selector",t.OPERATOR="operator",t.TIME="time",t.TEMPLATE="template",t.COMMENT="comment",t.SYMBOL="symbol",t.UNKNOWN="unknown"}(I||(I={}));const j=new Set(["+","-","*","/","mod"]),M=new Set(["ms","s","seconds","minutes","hours","days"]);function D(t,e=1){const n=t.position+e;return t.input.length>n?t.input[n]:""}function P(t){const e=t.input[t.position];return t.position++,"\n"===e?(t.line++,t.column=1):"\r"===e?("\n"===(t.input.length>t.position?t.input[t.position]:"")&&t.position++,t.line++,t.column=1):t.column++,e}function F(t){const e=t.input,n=e.length;for(;n>t.position;){const n=e[t.position];if(" "!==n&&"\t"!==n&&"\r"!==n&&"\n"!==n)break;P(t)}}function B(t,e,n,r,s){const i=r??t.position-n.length,o=t.position;let a=t.column-n.length;if(void 0!==r){a=1;let e=-1;for(let n=0;r>n;n++)"\n"!==t.input[n]&&"\r"!==t.input[n]||(e=n);a=r-e}const c={kind:e,value:n,start:i,end:o,line:_(t,i),column:a};t.tokens.push(c)}function _(t,e){let n=1;for(let r=0;e>r&&t.input.length>r;r++){const e=t.input[r];"\n"===e?n++:"\r"===e&&(n++,t.input.length>r+1&&"\n"===t.input[r+1]&&r++)}return n}function V(t){const e=t.position;let n="";for(P(t),P(t);t.input.length>t.position&&"\n"!==t.input[t.position];)n+=P(t);B(t,I.COMMENT,"--"+n,e)}function q(t){const e=t.position,n=P(t);let r=n;for(;t.input.length>t.position;){const e=P(t);if(r+=e,e===n)break;"\\"===e&&t.input.length>t.position&&(r+=P(t))}B(t,I.STRING,r,e)}function H(t){const e=t.position;P(t);let n="";for(;t.input.length>t.position;){const e=t.input[t.position];if("`"===e){P(t);break}if("\\"===e){if(P(t),t.input.length>t.position){const e=P(t);switch(e){case"n":n+="\n";break;case"t":n+="\t";break;case"r":n+="\r";break;case"\\":n+="\\";break;case"`":n+="`";break;default:n+=e}}}else n+=P(t)}if(t.position>=t.input.length&&!t.input.endsWith("`"))throw Error(`Unterminated template literal at line ${t.line}, column ${t.column-n.length}`);B(t,I.TEMPLATE,n,e)}function U(t){const e=t.position;let n=P(t);if(t.input.length>t.position&&"{"===t.input[t.position]){for(n+=P(t);t.input.length>t.position;){const e=t.input[t.position];if(n+=P(t),"}"===e)break}B(t,I.SELECTOR,n,e)}else{for(;t.input.length>t.position;){const e=t.input[t.position];if("\\"===e)P(t),t.input.length>t.position&&(n+=P(t));else{if(!K(e)&&"-"!==e&&"_"!==e&&":"!==e)break;n+=P(t)}}B(t,I.SELECTOR,n,e)}}function W(t){const e=t.position;if(Q(t))return void function(t,e){const n=t.input;let r="",s=0,i="";for(;n.length>t.position;){const e=n[t.position];if(i)r+=P(t),e===i&&(i="");else if('"'!==e&&"'"!==e){if("<"===e){if("/"===n[t.position+1]){for(;n.length>t.position&&">"!==n[t.position];)r+=P(t);if(n.length>t.position&&(r+=P(t)),s--,0>=s)break;continue}let e=0,i="";for(;n.length>t.position;){const s=n[t.position];if(i)r+=P(t),s===i&&(i="");else if('"'!==s&&"'"!==s){if(">"===s){e="/"===n[t.position-1],r+=P(t);break}r+=P(t)}else i=s,r+=P(t)}if(e||s++,0>=s)break;continue}r+=P(t)}else i=e,r+=P(t)}B(t,I.SELECTOR,r,e)}(t,e);let n="";for(n+=P(t);t.input.length-1>t.position;){const e=t.input[t.position],r=t.input[t.position+1];if(n+=P(t),"/"===e&&">"===r){n+=P(t);break}}B(t,I.SELECTOR,n,e)}function z(t){const e=t.position;let n=P(t);for(;t.input.length>t.position;){const e=t.input[t.position];if(!K(e)&&"_"!==e&&"-"!==e)break;n+=P(t)}B(t,I.SYMBOL,n,e)}function J(t){const e=t.position;let n="";const r=t.input[t.position];if(("'"===r||"'"===r)&&"s"===D(t,1))return n="'s",P(t),P(t),void B(t,I.OPERATOR,n,e);const s=t.input.substring(t.position,t.position+2),i=t.input.substring(t.position,t.position+3);["===","!=="].includes(i)?(n=i,P(t),P(t),P(t)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(s)?(n=s,P(t),P(t)):n=P(t),B(t,I.OPERATOR,n,e)}function Z(t){const e=t.position,n=t.input,r=n.length;let s="";for(;r>t.position;){const e=n[t.position];if("0">e||e>"9")break;s+=P(t)}if(r>t.position&&"."===n[t.position]&&(t.position+1>=r||"."!==n[t.position+1]))for(s+=P(t);r>t.position;){const e=n[t.position];if("0">e||e>"9")break;s+=P(t)}if(r>t.position){const e=n[t.position];if("e"===e||"E"===e){const e=r>t.position+1?n[t.position+1]:"",i=r>t.position+2?n[t.position+2]:"";if(e>="0"&&"9">=e||!("+"!==e&&"-"!==e||"0">i||i>"9"))for(s+=P(t),"+"!==n[t.position]&&"-"!==n[t.position]||(s+=P(t));r>t.position;){const e=n[t.position];if("0">e||e>"9")break;s+=P(t)}}}const i=t.position;let o="";for(;r>t.position;){const e=n[t.position];if(("a">e||e>"z")&&("A">e||e>"Z"))break;o+=P(t)}M.has(o)?B(t,I.TIME,s+o,e):(t.position=i,B(t,I.NUMBER,s,e))}function G(t){const e=t.position,n=t.input,r=n.length;let s="";for(;r>t.position;){const e=n[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;s+=P(t)}const i=function(t,e,n){const r=e.toLowerCase(),s=t.position;if("'s"===e||"'s"===e)return 0;const i=t.tokens[t.tokens.length-1];if(i&&(i.kind===I.IDENTIFIER||i.kind===I.SELECTOR)){const e=t.input.length>t.position?t.input[t.position]:"";if("'"===e||"'"===e)return 0}F(t);let o="";for(;t.input.length>t.position;){const e=t.input[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;o+=P(t)}if(o){const e=o.toLowerCase(),s=`${r} ${e}`,i=function(t,e,n,r){const s=e.toLowerCase(),i=n.toLowerCase();if("at"===s){const e=t.position;if("the"===i){F(t);let n="";for(;t.input.length>t.position;){const e=t.input[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;n+=P(t)}const s=n.toLowerCase();if("start"===s||"end"===s){F(t);let e="";for(;t.input.length>t.position;){const n=t.input[t.position];if(("a">n||n>"z")&&("A">n||n>"Z")&&("0">n||n>"9")&&"_"!==n&&"-"!==n)break;e+=P(t)}if("of"===e.toLowerCase())return B(t,I.IDENTIFIER,`at the ${s} of`,r),1}return t.position=e,0}if("start"===i||"end"===i){F(t);let n="";for(;t.input.length>t.position;){const e=t.input[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;n+=P(t)}return"of"===n.toLowerCase()?(B(t,I.IDENTIFIER,`at ${i} of`,r),1):(t.position=e,0)}}return 0}(t,r,e,n);if(i)return 1;const a=function(t,e,n){const r=t.position;let s=`${e} ${n}`,i=t.position;const o=[e,n];for(;8>o.length&&(F(t),t.input.length>t.position);){let e="";for(;t.input.length>t.position;){const n=t.input[t.position];if(("a">n||n>"z")&&("A">n||n>"Z"))break;e+=P(t)}if(!e)break;o.push(e.toLowerCase());const n=o.join(" ");$.has(n)&&(s=n,i=t.position)}return $.has(s)&&s!==`${e} ${n}`?(t.position=i,s):(t.position=r,null)}(t,r,e);if(a)return B(t,I.OPERATOR,a,n),1;if($.has(s))return B(t,I.OPERATOR,s,n),1}return $.has(r)?(t.position=s,B(t,I.OPERATOR,e,n),1):(t.position=s,0)}(t,s,e);if(i)return;const o=function(t){const e=t.toLowerCase();return"include"===e||"includes"===e||O.has(e)||j.has(t)||j.has(e)||$.has(e)?I.OPERATOR:I.IDENTIFIER}(s);B(t,o,s,e)}function X(t){const e=t.position,n=t.input,r=n.length;P(t);let s="$";for(;r>t.position;){const e=n[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e)break;s+=P(t)}B(t,I.IDENTIFIER,s,e)}function Y(t){return/[a-zA-Z]/.test(t)}function K(t){return/[a-zA-Z0-9]/.test(t)}function Q(t){const e=t.input,n=e[t.position+1];if(!n||!/[a-zA-Z]/.test(n))return 0;let r=t.position+1,s="";for(;e.length>r&&/[a-zA-Z0-9-]/.test(e[r]);)s+=e[r],r++;return s.length>0&&-1!==e.indexOf("</"+s+">",r)}function tt(t){if(Q(t))return 1;let e=t.position+1,n=0;for(;t.input.length>e;){const r=t.input[e];if("/"===r&&t.input.length>e+1&&">"===t.input[e+1])return n;if(K(r)||"."===r||"#"===r||"["===r||"]"===r||":"===r||"-"===r||"_"===r||" "===r||"="===r||'"'===r||"'"===r||"("===r||")"===r||"*"===r||"^"===r||"$"===r||"~"===r||"|"===r||">"===r||"+"===r||","===r||"{"===r||"}"===r)n=1,e++;else{if(" "!==r&&"\t"!==r)return 0;e++}if(e-t.position>50)return 0}return 0}function et(t){return"+-*/^%=!<>&|(){}[],.;:?''~$".includes(t)}const nt=function(){if("undefined"!=typeof localStorage)try{const t=localStorage,e=t.getItem("hyperfixi:debug")||t.getItem("lokascript:debug");if("*"===e||"true"===e)return 1}catch{}return"undefined"!=typeof process&&"true"===process.env?.HYPERFIXI_DEBUG?1:0}(),rt=nt,st=nt,it=nt,ot=nt,at=(...t)=>{rt&&console.log("\ud83d\udd27",...t)},ct=(...t)=>{st&&console.log("\ud83c\udfaf",...t)},lt=(...t)=>{it&&console.log("\ud83d\udcdd",...t)},ut=(...t)=>{ot&&console.log("\ud83d\ude80",...t)};let ht=0,ft=null;if("undefined"!=typeof window&&"undefined"!=typeof URLSearchParams)try{"semantic"===new URLSearchParams(window.location.search).get("debug")&&(ht=1,ft=window,console.log("%c[HyperFixi] Semantic debug auto-enabled via URL param","color: #667eea; font-weight: bold"))}catch{}let dt={totalParses:0,semanticSuccesses:0,semanticFallbacks:0,traditionalParses:0,averageConfidence:0,confidenceHistory:[]};class pt{constructor(t){this.analyzer=t.analyzer,this.language=t.language,this.confidenceThreshold=t.confidenceThreshold??.5,this.debugEnabled=t.debug??0}isAvailable(){return this.analyzer.supportsLanguage(this.language)}shouldSkipSemantic(t){const e=t.trim().split(/\s+/)[0]?.toLowerCase();if(pt.SKIP_SEMANTIC_COMMANDS.has(e))return 1;const n=t.toLowerCase();return/\bjs\b/.test(n)||/\btell\b/.test(n)||/\*[a-zA-Z]/.test(t)?1:0}trySemanticParse(t){const e=performance.now();if(this.shouldSkipSemantic(t))return{success:0,confidence:0,errors:["Command skipped for semantic parsing - using traditional parser"]};if(!this.isAvailable())return{success:0,confidence:0,errors:[`Semantic parsing not available for language '${this.language}'`]};try{const r=this.analyzer.analyze(t,this.language),s=performance.now()-e;this.debugEnabled&&console.log("[SemanticIntegration] Analysis result:",{input:t,language:this.language,confidence:r.confidence,command:r.command?.name,threshold:this.confidenceThreshold});const i=r.confidence>=this.confidenceThreshold&&!!r.command,o=!i&&r.confidence>0;if(ht){const e={};if(r.command?.roles)for(const[t,n]of r.command.roles)e[t]=n.value;const a={input:t.substring(0,100),language:this.language,confidence:r.confidence,threshold:this.confidenceThreshold,semanticSuccess:i,fallbackTriggered:o,command:r.command?.name,roles:Object.keys(e).length>0?e:void 0,errors:r.errors,timestamp:Date.now(),duration:s};!function(t){if(!ht)return;const e=t.semanticSuccess?"semantic":t.fallbackTriggered?"fallback":"traditional",n=Math.round(100*t.confidence),r=Math.round(100*t.threshold),s=t.semanticSuccess?"color: #4caf50; font-weight: bold":t.fallbackTriggered?"color: #ff9800; font-weight: bold":"color: #9e9e9e";if(console.groupCollapsed(`%c[Semantic] ${e.toUpperCase()} %c${t.input.substring(0,50)}${t.input.length>50?"...":""}`,s,"color: #888"),console.log(`Confidence: ${n}% (threshold: ${r}%)`),t.command&&console.log("Command: "+t.command),t.roles&&Object.keys(t.roles).length>0&&console.log("Roles:",t.roles),t.duration&&console.log(`Duration: ${t.duration.toFixed(2)}ms`),t.errors?.length&&console.log("Errors:",t.errors),console.groupEnd(),ft){const e=new CustomEvent("lokascript:semantic:parse",{detail:t,bubbles:1});ft.dispatchEvent(e)}}(a),n=a,dt.totalParses++,n.semanticSuccess?dt.semanticSuccesses++:n.fallbackTriggered?dt.semanticFallbacks++:dt.traditionalParses++,dt.confidenceHistory.push(n.confidence),dt.confidenceHistory.length>100&&dt.confidenceHistory.shift(),dt.averageConfidence=dt.confidenceHistory.reduce((t,e)=>t+e,0)/dt.confidenceHistory.length}return i?{success:1,node:this.buildCommandNode(r),confidence:r.confidence,tokensConsumed:r.tokensConsumed}:{success:0,confidence:r.confidence,tokensConsumed:r.tokensConsumed,errors:r.errors}}catch(t){return{success:0,confidence:0,errors:[t instanceof Error?t.message:t+""]}}var n}buildCommandNode(t){const{command:e}=t;if(!e)throw Error("Cannot build command node without command data");if("repeat"===e.name)return this.buildRepeatCommandNode(e);if("for"===e.name)return this.buildRepeatCommandNode(e);if("set"===e.name)return this.buildSetCommandNode(e);if("if"===e.name||"unless"===e.name)return this.buildIfCommandNode(e);const n=[],r={};for(const[t,s]of e.roles){const i=this.semanticValueToExpression(s);switch(t){case"patient":case"event":n.push(i);break;case"destination":"put"===e.name?r.into=i:"add"===e.name||"append"===e.name||"prepend"===e.name?r.to=i:r.on=i;break;case"source":"fetch"===e.name?n.push(i):r.from=i;break;case"quantity":r.by=i;break;case"duration":r.over=i;break;case"responseType":r.as=i;break;case"style":r.with=i;break;case"condition":r.when=i;break;default:r[t]=i}}return{type:"command",name:e.name,args:n,modifiers:Object.keys(r).length>0?r:void 0,isBlocking:0,start:0,end:0,line:1,column:0}}buildRepeatCommandNode(t){const e=[],n={},r=t.roles.get("loopType");r&&e.push({type:"identifier",name:r.value+"",start:0,end:0,line:1,column:0});const s=t.roles.get("patient");"for"==(r?r.value+"":"")&&s&&e.push({type:"identifier",name:"expression"===s.type&&s.raw||s.value+"",start:0,end:0,line:1,column:0});const i=t.roles.get("event");i&&e.push({type:"string",value:i.value+"",start:0,end:0,line:1,column:0});const o=t.roles.get("source");o&&e.push(this.semanticValueToExpression(o));const a=t.roles.get("quantity");a&&e.push(this.semanticValueToExpression(a));const c=t.roles.get("condition");return c&&(n.condition=this.semanticValueToExpression(c)),{type:"command",name:"repeat",args:e,modifiers:Object.keys(n).length>0?n:void 0,isBlocking:0,start:0,end:0,line:1,column:0}}buildSetCommandNode(t){const e=[],n=t.roles.get("destination");if(n)if("property-path"===n.type){const t=n;e.push({type:"possessiveExpression",object:this.semanticValueToExpression(t.object),property:this.createPropertyNode(t.property),start:0,end:0,line:1,column:0})}else e.push(this.semanticValueToExpression(n));e.push({type:"identifier",name:"to",start:0,end:0,line:1,column:0});const r=t.roles.get("patient");return r&&e.push(this.semanticValueToExpression(r)),{type:"command",name:"set",args:e,isBlocking:0,start:0,end:0,line:1,column:0}}createPropertyNode(t){return t.startsWith("*")?{type:"cssProperty",name:t.substring(1),start:0,end:0,line:1,column:0}:{type:"identifier",name:t,start:0,end:0,line:1,column:0}}buildIfCommandNode(t){const e=[],n=t.roles.get("condition");return n&&e.push(this.semanticValueToExpression(n)),{type:"command",name:t.name,args:e,isBlocking:0,start:0,end:0,line:1,column:0}}semanticValueToExpression(t){switch(t.type){case"selector":return{type:"selector",value:t.value,start:0,end:0,line:1,column:0};case"reference":return{type:"identifier",name:t.value,start:0,end:0,line:1,column:0};case"literal":return"string"==typeof t.value&&t.value.includes("${")&&t.value.includes("}")?{type:"templateLiteral",value:t.value,start:0,end:0,line:1,column:0}:{type:"literal",value:t.value,raw:t.raw??t.value,start:0,end:0,line:1,column:0};case"property-path":{const e=t;return{type:"memberExpression",object:this.semanticValueToExpression(e.object),property:{type:"identifier",name:e.property,start:0,end:0,line:1,column:0},computed:0,start:0,end:0,line:1,column:0}}default:return this.parseExpressionString(t.raw||"")}}parseExpressionString(t){let e=0;const n=()=>{for(;t.length>e&&/\s/.test(t[e]);)e++},r=()=>{n();const r=e;for(;t.length>e&&/[a-zA-Z0-9_$]/.test(t[e]);)e++;return t.slice(r,e)},s=()=>{const r=[];if(e++,n(),")"!==t[e])for(r.push(i()),n();","===t[e];)e++,n(),r.push(i()),n();return")"===t[e]&&e++,r},i=()=>{n();const i=r();if(!i)return{type:"identifier",name:t.trim(),start:0,end:0,line:1,column:0};let o={type:"identifier",name:i,start:0,end:0,line:1,column:0};for(;t.length>e;){n();const i=t[e];if("."===i){e++;const t=r();t&&(o={type:"memberExpression",object:o,property:{type:"identifier",name:t,start:0,end:0,line:1,column:0},computed:0,start:0,end:0,line:1,column:0})}else{if("("!==i)break;o={type:"callExpression",callee:o,arguments:s(),start:0,end:0,line:1,column:0}}}return o};return i()}getLanguage(){return this.language}getConfidenceThreshold(){return this.confidenceThreshold}}pt.SKIP_SEMANTIC_COMMANDS=new Set(["swap","morph","js","tell"]);const mt=new Set(["then","end","to","into","on","with","from","in","by","for","while","until","unless","else","catch","finally"]),yt=new Set([")","]","}",","]);function gt(t,e){return{infix:{bp:[t,t+1],handler:e??((e,n,r)=>{const s=r.parseExpr(t+1);return{type:"binaryExpression",operator:n.value,left:e,right:s,start:e.start,end:s.end??n.end,line:e.line??n.line,column:e.column??n.column}})}}}function vt(t,e){return{infix:{bp:[t+1,t],handler:(e,n,r)=>{const s=r.parseExpr(t);return{type:"binaryExpression",operator:n.value,left:e,right:s,start:e.start,end:s.end??n.end,line:e.line??n.line,column:e.column??n.column}}}}}function bt(t,e){return{prefix:{bp:t,handler:e??((e,n)=>{const r=n.parseExpr(t);return{type:"unaryExpression",operator:e.value,operand:r,argument:r,prefix:1,start:e.start,end:r.end??e.end,line:e.line,column:e.column}})}}}function wt(t){return(e,n,r)=>{const s=r.advance();if(!s||!s.value)throw Error(`Type check requires a type name after 'is ${t?"not ":""}a/an', got: <end>`);let i=1;const o=r.peek();return o&&"!"===o.value&&(r.advance(),i=0),{type:"typeCheckExpression",value:e,typeName:s.value,nullOk:i,negated:t,start:e.start,end:s.end}}}const Et=function(...t){const e=new Map;for(const n of t)for(const[t,r]of n){const n=e.get(t);e.set(t,n?{prefix:r.prefix??n.prefix,infix:r.infix??n.infix}:{...r})}return e}(new Map([["or",gt(10)],["||",gt(10)],["and",gt(20)],["&&",gt(20)],["==",gt(30)],["!=",gt(30)],["<",gt(30)],[">",gt(30)],["<=",gt(30)],[">=",gt(30)],["is",gt(30)],["matches",gt(30)],["contains",gt(30)],["starts with",gt(30)],["ends with",gt(30)],["does not start with",gt(30)],["does not end with",gt(30)],["is between",gt(30,(t,e,n)=>{const r=n.parseExpr(31),s=n.peek();if(!s||"and"!==s.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(s?.value??"<end>"));n.advance();const i=n.parseExpr(31);return{type:"betweenExpression",value:t,min:r,max:i,negated:0,start:t.start,end:i.end}})],["is not between",gt(30,(t,e,n)=>{const r=n.parseExpr(31),s=n.peek();if(!s||"and"!==s.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(s?.value??"<end>"));n.advance();const i=n.parseExpr(31);return{type:"betweenExpression",value:t,min:r,max:i,negated:1,start:t.start,end:i.end}})],["am between",gt(30,(t,e,n)=>{const r=n.parseExpr(31),s=n.peek();if(!s||"and"!==s.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(s?.value??"<end>"));n.advance();const i=n.parseExpr(31);return{type:"betweenExpression",value:t,min:r,max:i,negated:0,start:t.start,end:i.end}})],["am not between",gt(30,(t,e,n)=>{const r=n.parseExpr(31),s=n.peek();if(!s||"and"!==s.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(s?.value??"<end>"));n.advance();const i=n.parseExpr(31);return{type:"betweenExpression",value:t,min:r,max:i,negated:1,start:t.start,end:i.end}})],["ignoring case",{infix:{bp:[25,26],handler:(t,e,n)=>(t.ignoringCase=1,t)}}],["where",gt(28,(t,e,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"where",collection:t,right:r,start:t.start,end:r.end}})],["sorted by",gt(28,(t,e,n)=>{const r=n.parseExpr(29);let s="asc";const i=n.peek();if(i&&"string"==typeof i.value){const t=i.value.toLowerCase();"asc"===t||"ascending"===t?(n.advance(),s="asc"):"desc"!==t&&"descending"!==t||(n.advance(),s="desc")}return{type:"collectionExpression",operator:"sorted by",collection:t,right:r,order:s,start:t.start,end:r.end}})],["mapped to",gt(28,(t,e,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"mapped to",collection:t,right:r,start:t.start,end:r.end}})],["split by",gt(28,(t,e,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"split by",collection:t,right:r,start:t.start,end:r.end}})],["joined by",gt(28,(t,e,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"joined by",collection:t,right:r,start:t.start,end:r.end}})],["+",{...gt(40),...bt(80)}],["-",{...gt(40),...bt(80)}],["*",gt(50)],["/",gt(50)],["%",gt(50)],["mod",gt(50)],["^",vt(60)],["**",vt(60)],["as",gt(70,(t,e,n)=>{const r=()=>{const t=n.peek();!t||"a"!==t.value&&"an"!==t.value||n.advance();const e=n.parseExpr(71),r=n.peek();if(r&&":"===r.value&&e&&"identifier"===e.type){n.advance();const t=n.advance();t&&void 0!==t.value&&(e.name=`${e.name}:${t.value}`,e.end=t.end)}return e};let s=r(),i={type:"asExpression",expression:t,targetType:s,start:t.start,end:s.end??e.end,line:t.line??e.line,column:t.column??e.column};for(;n.peek()&&"|"===n.peek().value;){n.advance();const t=r();i={type:"asExpression",expression:i,targetType:t,start:i.start,end:t.end??i.end,line:i.line,column:i.column}}return i})],["not",bt(80)],["!",bt(80)],["no",bt(27)]]),new Map([["===",gt(30)],["!==",gt(30)],["is not",gt(30)],["am",gt(30)],["is in",gt(30)],["is not in",gt(30)],["precedes",gt(30)],["does not precede",gt(30)],["follows",gt(30)],["does not follow",gt(30)],["is a",gt(30,wt(0))],["is an",gt(30,wt(0))],["is not a",gt(30,wt(1))],["is not an",gt(30,wt(1))],["has",gt(30)],["have",gt(30)],["match",gt(30)],["include",gt(30)],["includes",gt(30)],["equals",gt(30)],["does not contain",gt(30)],["does not include",gt(30)],["am in",gt(30)],["am not in",gt(30)],["is really",gt(30)],["is not really",gt(30)],["is equal",gt(30)],["is not equal",gt(30)],["contain",gt(30)],["do not contain",gt(30)],["does not contains",gt(30)],["do not match",gt(30)],["does not match",gt(30)],["is equal to",gt(30)],["is not equal to",gt(30)],["is really equal to",gt(30)],["is not really equal to",gt(30)],["really equals",gt(30)],["is greater than",gt(30)],["is less than",gt(30)],["is greater than or equal to",gt(30)],["is less than or equal to",gt(30)],["in",gt(30)],["of",vt(30)],["really",gt(30)],["exists",{prefix:{bp:80,handler:(t,e)=>({type:"unaryExpression",operator:t.value,operand:e.parseExpr(80),start:t.start})},infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:0,start:t.start})}}],["does not exist",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:0,start:t.start})}}],["is empty",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:0,start:t.start})}}],["is not empty",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:0,start:t.start})}}],["some",bt(80)]]),new Map([["=",vt(5)]])),xt=new Map,kt=new Map,St=new Map,At=new Set,Nt=new Set,Ct=new Set,Tt=new Set;function Ot(t){return xt.get(t.toLowerCase())}function $t(t,e){if(0!==Nt.size)for(const n of Nt)try{n(t,e)}catch(t){void 0!==console&&console.error("[hyperfixi] globalReadHook threw:",t)}}function Rt(t,e,n){if(0!==Ct.size)for(const r of Ct)try{r(t,e,n)}catch(t){void 0!==console&&console.error("[hyperfixi] localWriteHook threw:",t)}}function Lt(t,e){if(0!==Tt.size)for(const n of Tt)try{n(t,e)}catch(t){void 0!==console&&console.error("[hyperfixi] localReadHook threw:",t)}}function It(t,e,n){if(t.globals.set(e,n),0!==At.size)for(const r of At)try{r(e,n,t)}catch(t){void 0!==console&&console.error("[hyperfixi] globalWriteHook threw:",t)}}function jt(t){return t.kind!==I.IDENTIFIER?0:E.has(t.value.toLowerCase())}function Mt(t){return t.kind!==I.IDENTIFIER?0:L.has(t.value.toLowerCase())}function Dt(t){return t.kind!==I.IDENTIFIER?0:R.has(t.value.toLowerCase())}function Pt(t){return t.kind!==I.IDENTIFIER?0:T.has(t.value.toLowerCase())}function Ft(t){return $.has(t.value.toLowerCase())}function Bt(t){return t.kind===I.IDENTIFIER}function _t(t){return t.kind===I.SELECTOR}function Vt(t){return t.kind!==I.SELECTOR?0:!t.value.startsWith("<")}function qt(t){return t.kind===I.STRING||t.kind===I.NUMBER||t.kind===I.TEMPLATE}function Ht(t){return t.kind===I.IDENTIFIER}function Ut(t){return t.kind===I.TIME}function Wt(t){return t.kind===I.SYMBOL}function zt(t){return t.kind===I.COMMENT}function Jt(t){if(t.kind!==I.IDENTIFIER)return 0;const e=t.value.toLowerCase();return!(E.has(e)||L.has(e)||R.has(e)||T.has(e))}function Zt(t){return t.kind===I.STRING}function Gt(t){return t.kind===I.NUMBER}function Xt(t){if(t.kind===I.IDENTIFIER){const e=t.value;return"true"===e||"false"===e||"null"===e||"undefined"===e}return 0}function Yt(t){return t.kind===I.TEMPLATE}function Kt(t){return t.kind===I.SELECTOR&&t.value.startsWith("<")}function Qt(t){return t.kind===I.SELECTOR&&t.value.startsWith("#")}function te(t){return t.kind===I.SELECTOR&&t.value.startsWith(".")}function ee(t){return t.kind!==I.SELECTOR?0:!t.value.startsWith("#")&&!t.value.startsWith(".")}function ne(t){if(t.kind!==I.OPERATOR)return 0;const e=t.value.toLowerCase();return!O.has(e)&&!$.has(e)}function re(t){const e=t.value.toLowerCase();return"then"===e||"and"===e||"else"===e||"end"===e||"on"===e}function se(t,e,n){return{type:"literal",value:t,raw:e,start:n.start,end:n.end,line:n.line,column:n.column}}function ie(t,e){return{type:"identifier",name:t,start:e.start,end:e.end,line:e.line,column:e.column}}function oe(t,e,n,r){return{type:"binaryExpression",operator:t,left:e,right:n,start:r.start,end:r.end,line:r.line,column:r.column}}function ae(t,e){return{type:"block",commands:t,start:e.start,end:e.end,line:e.line,column:e.column}}function ce(t,e){return{type:"string",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}function le(t,e){return{type:"objectLiteral",properties:t,start:e.start,end:e.end,line:e.line,column:e.column}}function ue(t,e){return{type:"arrayLiteral",elements:t,start:e.start,end:e.end,line:e.line,column:e.column}}function he(t,e,n){return{type:"propertyOfExpression",property:t,target:e,start:n.start,end:n.end,line:n.line,column:n.column}}function fe(t,e,n){return{type:"command",name:"__ERROR__",args:[],diagnostics:[{message:e,severity:"error",code:"parse-error",line:t.line,column:t.column,...n&&{source:n}}],start:t.start,end:t.end,line:t.line,column:t.column}}const de=[{command:"append",keywords:["to"],syntax:"append <value> [to <target>]"},{command:"make",keywords:["a","an","from","called"],syntax:"make (a|an) <type> [from <args>] [called <name>]"},{command:"send",keywords:["to"],syntax:"send <event> to <target>"},{command:"throw",keywords:[],syntax:"throw <error>"}];function pe(t,e){return t?e.some(e=>t.value===e||t.value.toLowerCase()===e):0}const me=[t,r,e,n];function ye(t,e=[]){if(t.isAtEnd())return 1;for(const e of me)if(t.check(e))return 1;for(const n of e)if(t.check(n))return 1;return t.checkIsCommand()?1:0}function ge(t,e=[]){if(!ye(t,e))return t.parseExpression()}function ve(t,e,n){return t.check(e)?(t.advance(),n.push(t.createIdentifier(e)),1):0}function be(t,e,n){for(const r of e)if(t.check(r))return t.advance(),n.push(t.createIdentifier(r)),r;return null}function we(t,e){return t.check(e)?(t.advance(),1):0}function Ee(t){const e=t.savePosition();let n;if(t.checkIdentifierLike()){const r=t.peek().value;t.advance(),t.check(":")?(t.advance(),n=r):t.restorePosition(e)}const r=t.parseExpression();return void 0!==n?{name:n,value:r}:{value:r}}class xe{constructor(t){this.args=[],this.isBlocking=0,this.name=t}static from(t){const e=new xe(t.value);return e.startPos={start:t.start??0,end:t.end??0,line:t.line??1,column:t.column??1},e}static fromIdentifier(t){const e=new xe(t.name);return void 0!==t.start&&(e.startPos={start:t.start,end:t.end??0,line:t.line??1,column:t.column??1}),e}static named(t){return new xe(t)}withArgs(...t){return this.args.push(...t),this}withBody(t){return this.body=t,this}withImplicitTarget(t){return this.implicitTarget=t,this}withModifier(t,e){return this.modifiers||(this.modifiers={}),this.modifiers[t]=e,this}withModifiers(t){return this.modifiers={...this.modifiers,...t},this}withName(t){return this.name=t,this}withOriginalCommand(t){return this.originalCmd=t,this}blocking(t=1){return this.isBlocking=t,this}startingAt(t){return this.startPos={start:t.start??0,end:t.end??0,line:t.line??1,column:t.column??1},this}endingAt(t){return this.endPos={start:t.start??this.startPos?.start??0,end:t.end,line:t.line??this.startPos?.line??1,column:t.column??this.startPos?.column??1},this}build(){const t={type:"command",name:this.name,args:this.args,isBlocking:this.isBlocking,start:this.startPos?.start??0,end:this.endPos?.end??this.startPos?.end??0,line:this.startPos?.line??1,column:this.startPos?.column??1};return this.body&&(t.body=this.body),this.implicitTarget&&(t.implicitTarget=this.implicitTarget),this.modifiers&&(t.modifiers=this.modifiers),this.originalCmd&&(t.originalCommand=this.originalCmd),t}clone(){const t=new xe(this.name);return t.args=[...this.args],t.body=this.body?[...this.body]:void 0,t.implicitTarget=this.implicitTarget,t.isBlocking=this.isBlocking,t.modifiers=this.modifiers?{...this.modifiers}:void 0,t.originalCmd=this.originalCmd,t.startPos=this.startPos?{...this.startPos}:void 0,t.endPos=this.endPos?{...this.endPos}:void 0,t}}function ke(t,e){const n=[];let r="";const s=t.peek().start||0,i=t.peek().line||1,o=t.peek().column||1;if(t.checkIdentifierLike()){for(r=t.advance().value;t.check(":")&&!t.isAtEnd();)t.advance(),r+=":",t.checkIdentifierLike()&&(r+=t.advance().value);if(t.check("(")){t.advance();const e=[];for(;!t.isAtEnd()&&!t.check(")");){const{name:n,value:r}=Ee(t);if(e.push(void 0!==n?{type:"objectLiteral",properties:[{key:{type:"identifier",name:n},value:r}],start:r.start,end:r.end,line:r.line,column:r.column}:r),t.check(","))t.advance();else if(!t.check(")"))break}t.check(")")&&t.advance(),n.push({type:"functionCall",name:r,args:e,start:s,end:t.getPosition().end,line:i,column:o})}else n.push({type:"string",value:r,start:s,end:t.getPosition().end,line:i,column:o})}const a=[...n];for(;!ye(t);){if(t.check("on")||t.check("to")){const e=t.advance().value;a.push(t.createIdentifier(e));continue}a.push(t.parsePrimary())}return xe.fromIdentifier(e).withArgs(...a).endingAt(t.getPosition()).build()}function Se(t,e){const n=[];if(t.check(b)){const e=t.advance();if(n.push({type:"identifier",name:b,start:e.start,end:e.end,line:e.line,column:e.column}),t.check(y)){const e=t.advance();n.push({type:"identifier",name:y,start:e.start,end:e.end,line:e.line,column:e.column})}}return xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function Ae(r,s){const i=[];let o=0;const a=r.savePosition();for(let e=0;500>e&&!r.isAtEnd();e++){const e=r.peek();if(e.value===t){o=1;break}if(e.value===n||e.value===g||"def"===e.value||e.value===m)break;r.advance()}r.restorePosition(a);let c=0;if(!o){const t=r.savePosition(),i=s.line,o=100;for(;!r.isAtEnd()&&o>r.current-t;){const t=r.peek(),s=t.value?.toLowerCase();if(s===g||"def"===s||s===m)break;if(s===e||s===n){t.line===i&&(c=1);break}if((r.checkIsCommand()||r.isCommand(s))&&void 0!==t.line&&t.line!==i){c=1;break}r.advance()}r.restorePosition(t)}const l=o||c;let u;if(l)u=r.parseExpression();else{const e=[],n=20;let i=0;for(;!r.isAtEnd()&&!r.checkIsCommand()&&!r.isCommand(r.peek().value)&&!r.check(t)&&n>i;){const t=r.savePosition();e.push(r.parseLogicalAnd()),r.savePosition()===t&&r.advance(),i++}if(0===e.length)throw Error("Expected condition after if/unless");u=1===e.length?e[0]:{type:"expression",tokens:e,start:e[0].start,end:e[e.length-1].end,line:s.line,column:s.column}}if(i.push(u),l){o&&r.advance();const t=[];for(;!r.isAtEnd()&&!r.check(e)&&!r.check(n)&&(r.checkIsCommand()||r.isCommand(r.peek().value));){r.advance();const e=r.parseCommand();e&&t.push(e)}if(0===t.length&&r.isAtEnd())throw Error("Expected command after 'then' in if statement - incomplete conditional");i.push(ae(t,{start:s.start,end:r.getPosition().end,line:s.line,column:s.column}));let a=0;if(r.check(e))if(r.advance(),r.check("if")){const t=r.peek();r.advance();const e=Ae(r,t);i.push(ae([e],{start:t.start,end:r.getPosition().end,line:t.line,column:t.column})),a=1}else{const t=[];for(;!r.isAtEnd()&&!r.check(n)&&(r.checkIsCommand()||r.isCommand(r.peek().value));){r.advance();const e=r.parseCommand();e&&t.push(e)}i.push(ae(t,{start:s.start,end:r.getPosition().end,line:s.line,column:s.column}))}a||r.consume(n,"Expected 'end' after if block")}else{if(!r.checkIsCommand()&&!r.isCommand(r.peek().value))throw Error("Expected command after if condition in single-line form");{r.advance();const t=r.parseCommand();i.push(ae([t],{start:s.start,end:r.getPosition().end,line:s.line,column:s.column}))}}return xe.from(s).withArgs(...i).endingAt(r.getPosition()).build()}function Ne(t,e){const n=[],r={};if(t.checkAnySelector()||t.checkContextVar()||t.match("<")){const e=t.parsePrimary();if(n.push(e),t.match("*")){if(t.checkIdentifierLike()){const e=t.advance();n.push({type:"identifier",name:"*"+e.value,start:e.start-1,end:e.end,line:e.line,column:e.column})}}else if(t.checkIdentifierLike()){const e=t.parsePrimary();n.push(e)}}else if(t.checkIdentifierLike()){const e=t.parsePrimary();n.push(e)}if(t.match("and")&&t.match("set")&&t.checkIdentifierLike()){const e=t.advance();r.set={type:"identifier",name:e.value,start:e.start,end:e.end,line:e.line,column:e.column}}const s=xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition());return Object.keys(r).length>0&&s.withModifiers(r),s.build()}function Ce(t,e){const n=[],r=ge(t,[f]);r&&n.push(r),ve(t,f,n);const s=ge(t);return s&&n.push(s),xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function Te(t,e){const n=[];if(t.check("between")){t.advance(),n.push(t.createIdentifier("between"));const i=ge(t,[r]);if(i&&"binaryExpression"===i.type&&"and"===i.operator)i.left&&n.push(i.left),n.push(t.createIdentifier("and")),i.right&&n.push(i.right);else{i&&n.push(i),ve(t,r,n);const e=ge(t,[f,m,s]);e&&n.push(e)}if(be(t,[f,m],n)){const e=ge(t);e&&n.push(e)}return xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}const i=ge(t,[f,m]);if(i&&n.push(i),be(t,[f,m],n)){const e=ge(t);e&&n.push(e)}return t.check("modal")&&(t.advance(),n.push({type:"literal",value:"modal",raw:"modal"})),xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function Oe(t,e){const r=t.parseExpression();if(!r)return t.addError("Put command requires content expression"),null;const s=t.peek();if(!s||!A.includes(s.value))return t.addError(`Expected operation keyword (${A.join(", ")}) after put expression, got: ${s?.value}`),null;let i=t.advance().value;const o=i.toLowerCase();"at start of"===o||"at the start of"===o?i=k:"at end of"===o||"at the end of"===o?i=S:"at"===i&&(t.check(w)||t.check(b)?(we(t,b),t.check(w)&&(t.advance(),t.check(p)&&(t.advance(),i=k))):t.check(n)&&(t.advance(),t.check(p)&&(t.advance(),i=S)));const a=t.parseExpression();return a?xe.fromIdentifier(e).withArgs(r,t.createIdentifier(i),a).endingAt(t.getPosition()).build():(t.addError("Put command requires target expression after operation keyword"),null)}const $e=["innerhtml","outerhtml","into","over","delete","morph","morphouter"];function Re(s,i){const o=s.savePosition();let a=null,c=[];try{a=function(t){if(!t.check(":"))return null;if(t.advance(),t.check(":")){t.advance();const e=t.advance();return{type:"identifier",name:e.value,scope:"global",start:e.start-2,end:e.end}}const e=t.advance();return{type:"identifier",name:e.value,scope:"element",start:e.start-1,end:e.end}}(s)??function(t){if(!t.check(v)&&!t.check("local"))return null;const e=t.advance(),n=t.advance();return{type:"identifier",name:n.value,scope:e.value,start:e.start,end:n.end}}(s)??function(t){if(!t.check(b))return null;const e=t.savePosition();t.advance();const n=t.parseExpression();if(!n)return t.restorePosition(e),null;if("binaryExpression"===n.type&&n.operator===p){const t=n.left,e=n.right;return he(t,e,{start:t.start??0,end:e.end??0,line:t.line??1,column:t.column??1})}return t.check(h)?n:(t.restorePosition(e),null)}(s),a||(a=s.parseExpression())}catch{s.restorePosition(o),a=null}if(!a){const i=function(s){if(s.match(":")){const t=s.advance();return{expression:{type:"identifier",name:t.value,scope:"element",start:t.start,end:t.end},tokens:[]}}const i=[];for(;!(s.isAtEnd()||s.check(h)||s.check(t)||s.check(r)||s.check(e)||s.check(n));)i.push(s.parsePrimary());if(0===i.length)return{expression:null,tokens:[]};if(i.length>=4){const t=(t,e)=>t[e];if(t(i[0],"value")===b&&t(i[2],"value")===p){const e=i[1],n=i[3];return{expression:he(ie(t(e,"value")||t(e,"name")||"",{start:e.start??0,end:e.end??0,line:e.line??1,column:e.column??1}),{type:"idSelector"===n.type?"idSelector":"cssSelector",value:t(n,"value")||t(n,"name")||"",start:n.start??0,end:n.end??0,line:n.line,column:n.column},{start:i[0].start??0,end:n.end??0,line:i[0].line??1,column:i[0].column??1}),tokens:[]}}}return 1===i.length?{expression:i[0],tokens:[]}:{expression:null,tokens:i}}(s);a=i.expression,c=i.tokens}if(!s.check(h)){const t=s.isAtEnd()?"end of input":s.peek().value;throw Error("Expected 'to' in set command, found: "+t)}s.advance();const l=s.parseExpression()??s.parsePrimary();let u;var f;s.check(m)&&(f=s.peekAt(1))&&("selector"===f.kind||f.value.startsWith("<")||Le.has(f.value))&&(s.advance(),u=ge(s));const d=[];a?d.push(a):c.length>0&&d.push(...c),d.push(s.createIdentifier(h)),l&&d.push(l);const y=xe.fromIdentifier(i).withArgs(...d);return u&&y.withModifier("on",u),y.endingAt(s.getPosition()).build()}const Le=new Set(["me","my","it","its","you","your","yourself"]),Ie=new Set(["to","the","url","of","in","new","window","top","middle","bottom","left","center","right","smoothly","instantly","back","forward"]),je=new Set(["in","then","and","else","end","otherwise","when","where","catch","finally"]);function Me(t){return t.isAtEnd()||je.has(t.peek().value)}function De(t,e){return{type:"string",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}function Pe(t,e){const n=[];for(;!ye(t,["catch","finally"])&&(t.checkIdentifierLike()||t.checkSelector()||t.checkLiteral()||t.checkTimeExpression()||t.match("<"));)n.push(t.parsePrimary());return xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function Fe(t){if(t.isAtEnd())return 1;const e=t.peek().value;return["as","with","{","then","end","else","otherwise",")"].includes(e)||ye(t)}function Be(t){const e=t.peek();if("/"===e.value)return 1;if(t.checkIdentifierLike()){const n=t.peekAt(1);return!!n&&":"===n.value&&n.start===e.end}return 0}function _e(t,e=Fe){const n=t.savePosition();let r="";for(;!t.isAtEnd()&&!e(t);)r+=t.advance().value;return r&&"/"!==r?{type:"literal",value:r,raw:r,start:n,end:t.savePosition()}:(t.restorePosition(n),null)}function Ve(t){if(t.check("{"))return 0;if(!t.checkIdentifierLike())return 0;const e=t.peekAt(1);return null!==e&&":"===e.value}function qe(t){const e=[],n=t.getPosition();do{if(!t.checkIdentifierLike())break;const n=t.advance(),r={type:"identifier",name:n.value,start:n.start,end:n.end,line:n.line,column:n.column};t.consume(":","Expected ':' after property name in fetch named arguments");const s=t.parsePrimary();s&&e.push({key:r,value:s})}while(t.match(",")&&!t.isAtEnd());const r=t.getPosition();return{type:"objectLiteral",properties:e,start:n.start,end:r.end,line:n.line,column:n.column}}const He=new Set(["em","ex","cap","ch","ic","rem","lh","rlh","vw","vh","vi","vb","vmin","vmax","cm","mm","Q","pc","pt","px"]);class Ue{constructor(t,e,n){this.current=0,this.errors=[],this.warnings=[],this.prattCache=new Map,this.tokens=t,this.keywordResolver=e?.keywords,this.registryIntegration=e?.registryIntegration,e?.semanticAnalyzer&&e?.language&&(this.semanticAdapter=new pt({analyzer:e.semanticAnalyzer,language:e.language,confidenceThreshold:e.semanticConfidenceThreshold??.5})),this.originalInput=n||t.map(t=>t.value).join(" ")}resolveKeyword(t){return this.keywordResolver?this.keywordResolver.resolve(t)??t:t}addWarning(t){this.warnings.push(t)}parse(){this.prattCache.clear();const t=this.parseInternal();return this.errors.length>0&&(t.errors=[...this.errors]),t}parseInternal(){try{if(0===this.tokens.length)return this.addError("Cannot parse empty input"),{success:0,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings};if(this.check("behavior")){const t=[];for(;this.check("behavior");){this.advance();const e=this.parseBehaviorDefinition();if(e&&t.push(e),this.error)break}return this.error?{success:0,node:1===t.length?t[0]:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:1,node:1===t.length?t[0]:this.createProgramNode(t),tokens:this.tokens,warnings:this.warnings}}const t=this.peek(),e=t&&Ot(t.value)?t.value:null;if(this.check("init")||this.check("on")||this.check("def")||this.checkComment()||null!==e){const t=[];for(;!this.isAtEnd();)if(this.checkComment())this.advance();else{if(this.check("then")){const t=this.peekAt(1);if(null!==t&&("init"===t.value||"on"===t.value||"def"===t.value||void 0!==Ot(t.value))){this.advance();continue}}if(this.check("init")){this.advance();const e=this.parseTopLevelInitBlock();e&&t.push(e)}else if(this.check("on")){this.advance();const e=this.parseEventHandler();e&&t.push(e)}else{if(!this.check("def")){const e=this.peek(),n=e?Ot(e.value):void 0;if(n){const e=this.advance(),r=n(this.getContext(),e);r&&t.push(r);continue}break}{this.advance();const e=this.parseDefFeature();e&&t.push(e)}}}return this.isAtEnd()?this.error?{success:0,node:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:1,node:this.createProgramNode(t),tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:0,node:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings})}if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){const t=this.parseCommandSequence();if(t){if(!this.isAtEnd()&&this.check("on")){lt("\u2705 PARSER: Found event handlers after command sequence, parsing as program");const e=[t];lt(`\u2705 PARSER: Starting with ${e.length} statement(s) from command sequence`);let n=0;for(;!this.isAtEnd()&&this.check("on");){lt(`\u2705 PARSER: Parsing event handler #${n+1}, current token: ${this.peek().value}`),this.advance();const t=this.parseEventHandler();if(lt("\u2705 PARSER: parseEventHandler returned:",t?`type=${t.type}, event=${t.event}`:"null"),t&&(e.push(t),n++,lt(`\u2705 PARSER: Added event handler, now have ${e.length} statements total`)),lt(`\u2705 PARSER: After parsing event handler, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd=${this.isAtEnd()}, check('on')=${this.check("on")}`),!this.isAtEnd()&&!this.check("on")){if(!this.isAtEnd())return lt("\u26a0\ufe0f PARSER: Unexpected token after event handlers: "+this.peek().value),this.addError("Unexpected token after event handlers: "+this.peek().value),{success:0,node:this.createProgramNode(e),tokens:this.tokens,error:this.error};lt("\u2705 PARSER: No more event handlers, at end of input");break}}return lt(`\u2705 PARSER: Finished parsing, creating Program node with ${e.length} statements`),this.error?{success:0,node:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:1,node:this.createProgramNode(e),tokens:this.tokens,warnings:this.warnings}}return this.isAtEnd()?this.error?{success:0,node:t,tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:1,node:t,tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:0,node:t||this.createErrorNode(),tokens:this.tokens,error:this.error})}}const n=this.parseExpression();if(this.error)return{success:0,node:n||this.createErrorNode(),tokens:this.tokens,error:this.error};if(!this.isAtEnd()){const t=this.peek();return n&&["number","string","identifier"].includes(t.kind)?this.addError(`Unexpected token: ${t.value} (missing operator between values? expected one of +, -, *, /, etc.)`):this.addError("Unexpected token: "+t.value),{success:0,node:n||this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}return{success:1,node:n,tokens:this.tokens,warnings:this.warnings}}catch(t){return this.addError(t instanceof Error?t.message:"Unknown parsing error"),{success:0,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}}parseExpression(){return this.parseExpressionPratt(0)}parseExpressionPratt(t){const e=`${this.current}:${t}`,n=this.prattCache.get(e);if(n)return this.current=n.endPos,n.node;if(this.isAtEnd())return this.addError("Unexpected end of expression"),this.createErrorNode();const r=this.peek(),s=Ue.PRATT_TABLE.get(r.value);let i;if(s?.prefix){const t=this.advance();if(this.isAtEnd())return this.addError(`Expected expression after '${t.value}' operator`),this.createErrorNode();i=s.prefix.handler(t,this.makePrattContext())}else i=this.parseCall();for(;!this.isAtEnd();){const e=this.peek();if(60>=t){const t=this.tryParseStringPostfix(i,e);if(t){i=t;continue}}const n=Ue.PRATT_TABLE.get(e.value);if(!n?.infix){if(mt.has(e.value)||yt.has(e.value))break;break}const[r]=n.infix.bp;if(t>r)break;if("="===e.value&&this.tokens.length>this.current+1&&">"===this.tokens[this.current+1].value){if(this.advance(),this.advance(),this.addError('Arrow functions (=>) are not supported in hyperscript. Use "js ... end" blocks for JavaScript callbacks.'),!this.isAtEnd())try{this.parseExpressionPratt(0)}catch(t){lt("arrow body discarded after error:",t instanceof Error?t.message:t+"")}return this.createErrorNode()}if("+"===e.value||"-"===e.value){const t=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(t&&("+"===t.value||"-"===t.value))return this.addError(`Invalid operator combination: ${e.value}${t.value}`),i}if("*"===e.value||"/"===e.value||"%"===e.value){const t=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(t&&("*"===t.value||"/"===t.value||"%"===t.value||"+"===t.value||"-"===t.value))return this.addError("*"===e.value&&"*"===t.value?"Unexpected token: "+t.value:`Invalid operator combination: ${e.value}${t.value}`),i}const s=this.advance();if(this.isAtEnd()&&!Ue.POSTFIX_UNARY_OPERATORS.has(s.value))return this.addError(`Expected expression after '${s.value}' operator`),i;i=n.infix.handler(i,s,this.makePrattContext())}return this.prattCache.set(e,{node:i,endPos:this.current}),i}tryParseStringPostfix(t,e){const n=e.value;let r=null;if(He.has(n)?r=n:"%"===n&&(this.canStartOperand(this.tokens.length>this.current+1?this.tokens[this.current+1]:null)||(r="%")),null==r)return null;const s=this.advance();return{type:"stringPostfix",expression:t,unit:r,start:t.start,end:s.end,line:t.line,column:t.column}}canStartOperand(t){if(!t)return 0;const e=t.value;return mt.has(e)||yt.has(e)?0:"number"===t.kind||"string"===t.kind||"identifier"===t.kind||"symbol"===t.kind?1:["(","[","{","-","+","!","#",".","<","$","@"].includes(e)}makePrattContext(){const t=this;return{peek:()=>t.tokens.length>t.current?t.tokens[t.current]:void 0,advance:()=>{const e=t.tokens[t.current];return t.current++,e},parseExpr:e=>t.parseExpressionPratt(e),isStopToken:()=>{const e=t.tokens[t.current];return e?mt.has(e.value)||yt.has(e.value):1},atEnd:()=>t.current>=t.tokens.length}}parseLogicalAnd(){return this.parseExpressionPratt(11)}parseImplicitBinary(){let t=this.parseCall();for(;!(this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("and")||this.check("else")||this.check(")")||this.check("]")||this.check(","));){if("identifier"!==t.type){if("literal"===t.type&&(this.checkNumber()||this.checkIdentifier())){const e=this.peek();return this.addError(`Missing operator between '${t.raw||t.value}' and '${e.value}'`),t}break}if(this.isCommand(t.name))if(this.isCompoundCommand(t.name.toLowerCase())){if(!(this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkTimeExpression()||this.checkString()||this.checkNumber()||this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()))break;{const e=this.createCommandFromIdentifier(t);e&&(t=e)}}else if("wait"===t.name.toLowerCase()&&(this.checkTimeExpression()||this.checkNumber()||this.checkIdentifier()||this.checkContextVar()||this.check("("))){const e=this.createCommandFromIdentifier(t);e&&(t=e)}else{if(!this.checkSelector())break;{const e=this.parseCall();t=this.createBinaryExpression(" ",t,e)}}else{if(!this.checkSelector())break;{const e=this.parseCall();t=this.createBinaryExpression(" ",t,e)}}}return t}isCommand(t){return this.keywordResolver?this.keywordResolver.isCommand(t):(t=>E.has(t.toLowerCase()))(t)}isKeyword(t){return this.keywordResolver?this.keywordResolver.isKeyword(t):(t=>N.has(t.toLowerCase()))(t)}createCommandFromIdentifier(t){const e=[],n=this.resolveKeyword(t.name.toLowerCase());if(this.isCompoundCommand(n))return this.parseCompoundCommand(t);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.checkIsCommand())&&(this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()||this.checkEvent()||this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkString()||this.checkNumber()||this.checkTimeExpression()||this.match("<"));)e.push(this.parsePrimary());return{type:"command",name:t.name,args:e,isBlocking:0,...void 0!==t.start&&{start:t.start},end:this.getPosition().end,...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}}}isCompoundCommand(t){return x.has(t.toLowerCase())}parseCompoundCommand(s){return function(s,i){switch(i.name.toLowerCase()){case"put":return Oe(s,i);case"trigger":case"send":return ke(s,i);case"remove":return Ce(s,i);case"toggle":return Te(s,i);case"set":return Re(s,i);case"halt":return Se(s,i);case"measure":return Ne(s,i);case"js":return function(t,e){const r=[];if(t.match("(")){for(;!t.check(")")&&!t.isAtEnd();)t.checkIdentifierLike()&&r.push(t.advance().value),t.match(",");t.consume(")","Expected ) after js parameters")}const s=t.peek().start,i=function(t,e){const n=t.getInputSlice(e);if(!n)return e;let r=0;for(;n.length>r;){const t=n[r];if("'"!==t&&"\u2019"!==t&&"\u2018"!==t)if('"'!==t)if("`"!==t)if("/"===t&&n.length>r+1&&"/"===n[r+1])for(r+=2;n.length>r&&"\n"!==n[r];)r++;else if("/"===t&&n.length>r+1&&"*"===n[r+1]){for(r+=2;n.length>r&&("*"!==n[r]||r+1>=n.length||"/"!==n[r+1]);)r++;r+=2}else{if(!("e"!==t&&"E"!==t||r+3>n.length||"end"!==n.slice(r,r+3).toLowerCase()||0!==r&&/[a-zA-Z0-9_]/.test(n[r-1])||n.length>r+3&&/[a-zA-Z0-9_]/.test(n[r+3])))return e+r;r++}else{for(r++;n.length>r&&"`"!==n[r];)"\\"===n[r]&&r++,r++;r++}else{for(r++;n.length>r&&'"'!==n[r];)"\\"===n[r]&&r++,r++;r++}else{for(r++;n.length>r&&n[r]!==t;)"\\"===n[r]&&r++,r++;r++}}return e+n.length}(t,s);for(;!t.isAtEnd()&&!t.check(n)&&t.peek().start<i;)t.advance();t.consume(n,"Expected end after js code body");const o={type:"literal",value:t.getInputSlice(s,i).trim(),start:e.start,end:t.getPosition().end},a={type:"arrayLiteral",elements:r.map(t=>({type:"literal",value:t,start:e.start,end:e.end})),start:e.start,end:t.getPosition().end};return xe.fromIdentifier(e).withArgs(o,a).endingAt(t.getPosition()).build()}(s,i);case"go":return function(t,e){const n=[];for(;!ye(t,["when","where","catch","finally"]);){const e=t.peek(),r=t.resolveKeyword(e.value).toLowerCase();if(Ie.has(r)){t.advance(),n.push(De(r,e));continue}if(Be(t)){const r=_e(t,Me);if(r){n.push(r);continue}t.advance(),n.push(De(e.value,e));continue}if("+"===e.value||"-"===e.value){t.advance(),n.push(De(e.value,e));continue}if("number"===e.kind){t.advance();const r=t.peek();if(t.isAtEnd()||"px"!==r.value||r.start!==e.end)n.push({type:"literal",value:Number(e.value),raw:e.value,start:e.start,end:e.end,line:e.line,column:e.column});else{const r=t.advance();n.push(De(e.value+"px",{...e,end:r.end}))}continue}const s=t.current;if(n.push(t.parsePrimary()),t.current===s)break}return xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}(s,i);case"tell":return function(s,i){const o=s.parseExpression();if(!o)throw Error("tell command requires a target expression");const a=[];for(;!s.isAtEnd();){if(s.checkIsCommand()){try{s.advance();const t=s.parseCommand();if(!t)break;a.push(t)}catch{break}if(s.match(r))continue;if(s.check(t)||s.check(e)||s.check(n))break;if(s.checkIsCommand())continue;break}break}if(0===a.length)throw Error("tell command requires at least one command after the target");return xe.fromIdentifier(i).withArgs(o,...a).endingAt(s.getPosition()).build()}(s,i);case"pick":return function(t,e){const n=xe.fromIdentifier(e);we(t,b);const r=t.peek().value,s=t=>({type:"literal",value:t,start:e.start,end:e.end}),i=()=>{if(!t.match("of","from"))throw Error("pick: expected 'of' or 'from' before source expression");return t.parseExpression()};if("first"===r){t.advance();const e=t.parsePrimary(),r=i();return n.withArgs(r).withModifier("variant",s("first")).withModifier("count",e).endingAt(t.getPosition()).build()}if("last"===r){t.advance();const e=t.parsePrimary(),r=i();return n.withArgs(r).withModifier("variant",s("last")).withModifier("count",e).endingAt(t.getPosition()).build()}if("random"===r){let e;t.advance(),t.check("of")||t.check("from")||(e=t.parsePrimary());const r=i(),o=n.withArgs(r).withModifier("variant",s("random"));return e&&o.withModifier("count",e),o.endingAt(t.getPosition()).build()}if("item"===r||"items"===r||"character"===r||"characters"===r){let e,r;t.advance(),t.match("at","from"),e=t.match("start")?s("start"):t.parsePrimary();let o=0;(t.match("to")||t.match(".."))&&(t.match("end")?o=1:r=t.parsePrimary());let a="default";t.match("inclusive")?a="inclusive":t.match("exclusive")&&(a="exclusive");const c=i(),l=n.withArgs(c).withModifier("variant",s("range")).withModifier("rangeStart",e).withModifier("rangeMode",s(a));return o?l.withModifier("rangeEnd",s("end")):r&&l.withModifier("rangeEnd",r),l.endingAt(t.getPosition()).build()}if("match"===r||"matches"===r){t.advance(),t.match("of");const e=t.parsePrimary();let o;t.matchOperator("|")&&(o=t.advance().value);const a=i(),c=n.withArgs(a).withModifier("variant",s("match"===r?"match":"matches")).withModifier("regex",e);return o&&c.withModifier("flags",s(o)),c.endingAt(t.getPosition()).build()}return Pe(t,e)}(s,i);case"start":return function(t,e){if(!t.match("view"))throw Error("start: expected 'view transition' (only `start view transition ... end` is supported)");if(!t.match("transition"))throw Error("start view: expected 'transition'");const n={};if(t.match("using")){const e=t.parsePrimary();n.transitionName=e}const r=t.parseCommandListUntilEnd();return xe.fromIdentifier(e).withArgs(...r).withModifiers(n).endingAt(t.getPosition()).build()}(s,i);case"swap":case"morph":return function(t,e){const n=[];let r=null;if(!t.isAtEnd()){const e=t.peek();if(e&&e.value){const s=e.value.toLowerCase();$e.includes(s)&&(r=s,t.advance(),n.push(t.createIdentifier(r)))}}if("delete"===r){const r=t.parseExpression();return r&&n.push(r),xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}!t.isAtEnd()&&t.check(p)&&(t.advance(),n.push(t.createIdentifier("of")));const s=t.parseExpression();if(s&&n.push(s),!t.isAtEnd()&&t.check(d)){t.advance(),n.push(t.createIdentifier("with"));const e=t.parseExpression();e&&n.push(e)}return xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}(s,i);default:return Pe(s,i)}}(this.getContext(),s)}parsePutCommand(t){return Oe(this.getContext(),t)}parseSetCommand(t){return Re(this.getContext(),t)}parseHaltCommand(t){return Se(this.getContext(),t)}parseMeasureCommand(t){return Ne(this.getContext(),t)}parseTriggerCommand(t){return ke(this.getContext(),t)}parseCommandListUntilTerminator(t){const e=[],n=()=>this.check("end")||t.some(t=>this.check(t));for(lt("\ud83d\udd04 parseCommandListUntilTerminator: Starting (extraStops:",t.join(","),")");!this.isAtEnd()&&!n();){lt("\ud83d\udccd Loop iteration, current token:",this.peek().value,"kind:",this.peek().kind);let t=0;const r=this.checkIsCommand(),s=!r&&this.checkIdentifier()&&this.isCommand(this.peek().value);if(r||s){lt(r?"\u2705 Found COMMAND token:":"\u2705 Found IDENTIFIER that is a command:",this.peek().value),this.advance();const n=this.error;try{const r=this.parseCommand();this.error&&this.error!==n&&(lt("\u26a0\ufe0f parseCommandListUntilTerminator: Command parsing added error, restoring. Error was:",this.error.message),this.error=n),r&&(lt("\u2705 Parsed command:",r.name),e.push(r),t=1)}catch(t){lt("\u26a0\ufe0f parseCommandListUntilTerminator: Command parsing threw, restoring:",t instanceof Error?t.message:t+""),this.error=n}}else this.checkIdentifier()&&lt("\u274c IDENTIFIER is not a command:",this.peek().value);if(!t){lt("\u274c No command parsed, breaking. Current token:",this.peek().value);break}for(lt("\ud83d\udccd After parsing command, current token:",this.peek().value);!(this.isAtEnd()||n()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(","));)lt("\u26a0\ufe0f Skipping unexpected token:",this.peek().value),this.advance();if(this.match("then","and",","))lt("\u2705 Found separator, continuing");else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){lt("\ud83d\udccd No separator and no command, breaking. Current token:",this.peek().value);break}lt("\u2705 Next token is a command, continuing without separator")}}let r="end";for(const e of t)if(this.check(e)){r=e;break}return this.check("end")||t.some(t=>this.check(t))||(r=""),lt("\u2705 parseCommandListUntilTerminator: parsed",e.length,"commands (terminator:",r,")"),{commands:e,terminator:r}}parseCommandListUntilEnd(){const{commands:t}=this.parseCommandListUntilTerminator([]);if(lt('\ud83d\udd0d After loop, checking for "end". Current token:',this.peek().value),!this.check("end"))throw lt('\u274c ERROR: Expected "end" but got:',this.peek().value,"at position:",this.peek().start),Error('Expected "end" to close repeat block');return lt('\u2705 Found "end", consuming it'),this.advance(),t}parseCommandListUntilEndOrElse(){const{commands:t,terminator:e}=this.parseCommandListUntilTerminator(["else"]),n="else"===e;if(!n){if(!this.check("end"))throw Error('Expected "end" to close repeat block');this.advance()}return{commands:t,hasElse:n}}parseRepeatBody(){const{commands:t,terminator:e}=this.parseCommandListUntilTerminator(["else","until","while"]);if("end"===e)this.advance();else if(""===e)throw Error('Expected "end", "else", "until", or "while" to close repeat block');return{commands:t,terminator:e}}parseRepeatCommand(t){return function(t,e){const n=[];let r="forever",h=null,p=null,m=null,g=null,v=null,w=null;if(t.check(s)){t.advance(),r=s;const e=t.peek();Bt(e)&&(v=e.value,t.advance()),t.check(u)&&(t.advance(),g=t.parseExpression())}else if(t.check(u))t.advance(),r=s,v="it",g=t.parseExpression();else if(t.check(i))t.advance(),r=i,m=t.parseExpression();else if(t.check(o))if(t.advance(),r=o,t.check(y)){t.advance(),r="until-event";const e=t.peek();if(lt("\ud83d\udccd Parsing event name, current token:",{value:e.value,kind:e.kind}),!Bt(e)&&!Dt(e))throw Error('Expected event name after "event"');if(h=e.value,t.advance(),lt("\u2705 Got event name:",h,"Next token:",t.peek().value),lt('\ud83d\udd0d Checking for "from", current token:',t.peek().value),t.check(f)){lt('\u2705 Found "from", advancing...'),t.advance(),lt('\ud83d\udccd After consuming "from", current token:',t.peek().value),we(t,b)&&lt('\u2705 Found "the", advancing...');const e=t.peek();lt("\ud83d\udd0d Before parsePrimary for event target:",{value:e.value,kind:e.kind,position:e.start}),p=t.parsePrimary(),lt("\u2705 After parsePrimary, eventTarget:",p)}else lt('\u274c No "from" found, skipping target parsing')}else m=t.parseExpression();else t.check(a)?(t.advance(),r=a):(w=t.parseExpression(),t.check(c)&&(t.advance(),r=c));let E,x=null;if(t.check(d)){const e=t.peekAt(1);e&&e.value.toLowerCase()===l&&(t.advance(),t.advance(),x=l)}else if(t.check(l)){t.advance();const e=t.peek();Bt(e)?(x=e.value,t.advance()):x=l}let k=null,S=0;if(r===a){const e=t.parseRepeatBody();if(E=e.commands,"else"===e.terminator)t.advance(),k=t.parseCommandListUntilEnd();else if("until"===e.terminator||"while"===e.terminator){if(S=1,r=e.terminator,t.advance(),m=t.parseExpression(),!t.check("end"))throw Error('Expected "end" to close repeat block');t.advance()}}else{const e=t.parseCommandListUntilEndOrElse();E=e.commands,e.hasElse&&(t.advance(),k=t.parseCommandListUntilEnd())}n.push({type:"identifier",name:r,start:e.start,end:e.end,line:e.line,column:e.column});const A={start:e.start,end:e.end,line:e.line,column:e.column};v&&n.push(ce(v,A)),g&&n.push(g),m&&n.push(m),w&&n.push(w),h&&n.push(ce(h,A)),p&&n.push(p),x&&n.push(ce(x,A)),n.push(ae(E,{...A,end:A.end||0})),null!==k&&n.push(ae(k,{...A,end:A.end||0}));const N=xe.from(e).withArgs(...n);return S&&N.withModifier("bottomTested",{type:"literal",value:1,...A}),N.endingAt(t.getPosition()).build()}(this.getContext(),t)}parseForCommand(t){return function(t,e){const n=[];let r=null,s=null;t.check("each")&&t.advance();const i=t.peek();if(!Bt(i))throw Error('Expected variable name after "for"');if(r=i.value,t.advance(),!t.check(u))throw Error('Expected "in" after variable name in for loop');if(t.advance(),s=t.parseExpression(),!s)throw Error('Expected collection expression after "in"');let o=null;if(t.check(d)){const e=t.peekAt(1);e&&e.value.toLowerCase()===l&&(t.advance(),t.advance(),o=l)}else if(t.check(l)){t.advance();const e=t.peek();Bt(e)?(o=e.value,t.advance()):o=l}const a=t.parseCommandListUntilEnd();n.push({type:"identifier",name:"for",start:e.start,end:e.end,line:e.line,column:e.column});const c={start:e.start,end:e.end,line:e.line,column:e.column};return n.push(ce(r,c)),n.push(s),o&&n.push(ce(o,c)),n.push(ae(a,{...c,end:c.end||0})),xe.from({...e,value:"repeat"}).withArgs(...n).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseWaitCommand(t){return function(t,e){const n=[];if(t.checkTimeExpression()||t.checkLiteral()||t.checkContextVar()||t.check("(")||t.checkIdentifierLike()&&!t.check("for")&&!ye(t)){const r=t.parseExpression();return n.push(r),xe.from(e).withArgs(...n).blocking().endingAt(t.getPosition()).build()}if(t.check("for")){t.advance();const r=[];do{const e=t.peek();if(!Bt(e))throw Error('Expected event name after "for"');const n=e.value;t.advance();const s=[];if(t.check("(")){for(t.advance();!t.isAtEnd()&&!t.check(")");){const e=t.peek();if(!Bt(e))break;s.push(e.value),t.advance(),t.check(",")&&t.advance()}if(!t.check(")"))throw Error('Expected ")" after event parameters');t.advance()}if(r.push({name:n,params:s}),!t.check("or"))break;t.advance()}while(!t.isAtEnd());let s=null;t.check(f)&&(t.advance(),we(t,b),s=t.parsePrimary());const i={start:e.start,end:t.getPosition().end,line:e.line,column:e.column};n.push(ue(r.map(t=>le([{key:ie("name",i),value:se(t.name,`"${t.name}"`,i)},{key:ie("args",i),value:ue(t.params.map(t=>se(t,`"${t}"`,i)),i)}],i)),i)),s&&n.push(s)}return xe.from(e).withArgs(...n).blocking().endingAt(t.getPosition()).build()}(this.getContext(),t)}parseInstallCommand(t){return function(t,e){const n=[];if(!t.checkIdentifierLike())throw Error('Expected behavior name after "install"');const r=t.advance().value,s=t.previous();if(n.push(ie(r,{start:s.start,end:s.end,line:s.line,column:s.column})),t.check("(")){t.advance();const r=[];for(;!t.isAtEnd()&&!t.check(")");)if(r.push(Ee(t)),t.check(","))t.advance();else if(!t.check(")"))break;if(!t.check(")"))throw Error('Expected ")" after behavior parameters');if(t.advance(),r.length>0){const s={start:e.start,end:t.getPosition().end,line:e.line,column:e.column};n.push(le(r.map(t=>({key:t.name?ie(t.name,s):se("_positional","_positional",s),value:t.value})),s))}}return xe.from(e).withArgs(...n).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseTransitionCommand(t){return function(t,e){const n=[],r={};let s=null;const i=t.peek();if(Bt(i)||"*"===i.value){let e="";t.check("*")&&(e="*",t.advance());const n=function(t){if(!t.checkIdentifierLike())return"";let e=t.advance().value;for(;t.check("-")&&!t.isAtEnd();)e+="-",t.advance(),t.checkIdentifierLike()&&(e+=t.advance().value);return e}(t);n&&(e+=n,s={type:"string",value:e,start:i.start||0,end:t.getPosition().end,line:i.line,column:i.column})}if(!s)throw Error("Transition command requires a CSS property");if(n.push(s),!t.check(h))throw Error('Expected "to" keyword after property in transition command');t.advance();const o=t.parsePrimary();if(r.to=o,t.check("over")){t.advance();const e=t.parsePrimary();r.over=e}if(t.check(d)){t.advance();const e=t.parsePrimary();r.with=e}return xe.from(e).withArgs(...n).withModifiers(r).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseAddCommand(t){return function(t,e){const n=[];if(t.match("{"))n.push(t.parseCSSObjectLiteral());else{const e=ge(t,[h]);e&&n.push(e)}if(t.check(h)){t.advance();const e=ge(t);e&&n.push(e)}return xe.from(e).withArgs(...n).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseIfCommand(t){return Ae(this.getContext(),t)}parseRemoveCommand(t){return Ce(this.getContext(),t)}parseToggleCommand(t){return Te(this.getContext(),t)}parseRegularCommand(t){return Pe(this.getContext(),t)}parseCall(){let t=this.parsePrimary();for(;;)if(this.match("("))t=this.finishCall(t);else if(this.match(".")){const e=this.consumeIdentifierLike("Expected property name after '.' - malformed member access");t=this.createMemberExpression(t,this.createIdentifier(e.value),0)}else if(this.match("?.")){const e=this.consumeIdentifierLike("Expected property name after '?.' - malformed optional access"),n=this.createMemberExpression(t,this.createIdentifier(e.value),0);n.optional=1,t=n}else if(this.match("[")){const e=this.parseExpression();this.consume("]","Expected ']' after array index"),t=this.createMemberExpression(t,e,1)}else{if(!this.check("'s"))break;{let e;this.advance(),this.check("*")?(this.advance(),e="*"+this.consumeIdentifier("Expected property name after * in CSS property syntax").value):Wt(this.peek())&&this.peek().value.startsWith("@")?e=this.advance().value:this.check("[")&&this.tokens[this.current+1]?.value?.startsWith("@")?(this.advance(),e=this.advance().value,this.consume("]","Expected ']' after attribute reference")):e=this.consumeIdentifierLike("Expected property name after possessive").value,t=this.createPossessiveExpression(t,this.createIdentifier(e))}}return t}parsePrimary(){if(this.check("*")){const t=this.current;if(this.advance(),!this.isAtEnd()&&Bt(this.peek())){const t=this.advance().value;return this.createSelector("*"+t)}this.current=t}if(this.check("*")||this.check("/")||this.check("%")||this.check("mod")){const t=this.peek();return this.addError(`Binary operator '${t.value}' requires a left operand`),this.createErrorNode()}if(this.matchNumber()){const t=parseFloat(this.previous().value);return this.createLiteral(t,this.previous().value)}if(this.matchString()){const t=this.previous().value;if(2>t.length||t.startsWith('"')&&!t.endsWith('"')||t.startsWith("'")&&!t.endsWith("'"))return this.addError("Unclosed string literal - string not properly closed"),this.createErrorNode();const e=t.slice(1,-1),n=this.processEscapeSequences(e);return this.createLiteral(n,t)}if(this.matchTemplateLiteral()){const t=this.previous();return{type:"templateLiteral",value:t.value,start:t.start||0,end:t.end||0,line:t.line,column:t.column}}if(this.matchBoolean()){const t=this.previous().value;let e;switch(t){case"true":e=1;break;case"false":e=0;break;case"null":e=null;break;case"undefined":e=void 0;break;default:e="true"===t}return this.createLiteral(e,t)}if(this.matchTimeExpression()){const t=this.previous().value;return this.createLiteral(t,t)}if(this.matchQueryReference()){const t=this.previous().value,e=t.slice(1,-2).trim(),n=this.createSelector(e);return n.fromQuery=1,n.raw=t,n}if(this.matchSelector())return this.createSelector(this.previous().value);if(this.match("<"))return this.parseHyperscriptSelector();if(this.match("(")){if(this.isAtEnd())return this.addError("Expected expression inside parentheses"),this.createErrorNode();const t=this.parseExpression();return this.consume(")","Expected closing parenthesis ')' after expression - unclosed parentheses"),t}if(this.match("{"))return this.parseObjectLiteral();if(this.match("["))return this.parseAttributeOrArrayLiteral();if(this.check(":")){if(this.advance(),this.check(":")){this.advance();const t=this.advance();return{type:"identifier",name:t.value,scope:"global",start:t.start-2,end:t.end,line:t.line,column:t.column}}{const t=this.advance();return{type:"identifier",name:t.value,scope:"element",start:t.start-1,end:t.end,line:t.line,column:t.column}}}if(this.matchBasicOperator()){const t=this.previous();return this.createIdentifier(t.value)}const t=this.peek();if((!t||"end"!==t.value&&"else"!==t.value&&"then"!==t.value)&&(this.matchPredicate(Jt)||this.matchPredicate(Mt)||this.matchPredicate(Pt)||this.matchPredicate(jt)||this.matchPredicate(Dt))){const t=this.previous();if("new"===t.value)return this.parseConstructorCall();if("on"===t.value)return this.parseEventHandler();if("if"===t.value)return this.parseConditional();if("closest"===t.value||"first"===t.value||"last"===t.value||"previous"===t.value||"next"===t.value){if(this.check("(")||this.checkCssSelector()||this.checkClassSelector()||this.checkIdSelector()||this.check("<")||this.checkQueryReference())return this.parseNavigationFunction(t.value);if(this.check(".")){const e=this.current;if(this.advance(),this.checkIdentifier()){const e=this.advance().value,n=this.createSelector("."+e);return this.createCallExpression(this.createIdentifier(t.value),[n])}this.current=e}if(this.check("#")){const e=this.current;if(this.advance(),this.checkIdentifier()){const e=this.advance().value,n=this.createSelector("#"+e);return this.createCallExpression(this.createIdentifier(t.value),[n])}this.current=e}return this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||this.check("end")?this.createIdentifier(t.value):this.parseNavigationFunction(t.value)}const e=this.check(".")||this.check("?.");return"my"!==t.value||e?"its"!==t.value||e?"your"!==t.value||e?"the"===t.value?this.parseTheXofY():"values"===t.value&&this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:"values"},target:this.parsePrimary(),line:t.line,column:t.column}):this.createIdentifier(t.value):this.parseContextPropertyAccess("you"):this.parseContextPropertyAccess("it"):this.parseContextPropertyAccess("me")}if(this.match("$"))return this.parseDollarExpression();if("\\"===this.peek().value)return this.parseBlockLiteral();if(Wt(this.peek())&&this.peek().value.startsWith("@")){const t=this.advance();return{type:"attributeAccess",attributeName:t.value.substring(1),start:t.start,end:t.end,line:t.line,column:t.column}}const e=this.peek();return this.addError(`Unexpected token: ${e.value} at line ${e.line}, column ${e.column}`),this.advance(),this.createErrorNode()}parseBlockLiteral(){const t=this.peek().start;this.advance();const e=[];for(;!(this.isAtEnd()||this.check("-")&&">"===this.tokens[this.current+1]?.value);){if(!this.checkIdentifier()){this.addError("Unexpected token in block literal parameters: "+this.peek().value);break}e.push(this.advance().value),this.match(",")}return this.check("-")&&">"===this.tokens[this.current+1]?.value?(this.advance(),this.advance(),{type:"blockLiteral",parameters:e,body:this.parseExpression(),start:t,end:this.previous().end,line:this.previous().line,column:this.previous().column}):(this.addError("Expected '->' in block literal"),this.createErrorNode())}parseDollarExpression(){if(this.checkNumber()){const t=this.advance().value;return this.createLiteral(t,"$"+t)}if(this.checkIdentifier()){const t=this.advance();let e=this.createIdentifier(t.value);for(;this.match(".");){if(!this.checkIdentifier())return this.addError("Expected property name after '.' in dollar expression"),this.createErrorNode();{const t=this.advance();e=this.createMemberExpression(e,this.createIdentifier(t.value),0)}}return{type:"dollarExpression",expression:e,raw:`$${t.value}${this.previous().value||""}`,line:t.line,column:t.column-1}}return this.addError("Expected identifier or number after '$'"),this.createErrorNode()}parseHyperscriptSelector(){let t="";for(;!this.check("/")&&!this.isAtEnd();)t+=this.advance().value;return this.consume("/","Expected '/' in hyperscript selector"),this.consume(">","Expected '>' after '/' in hyperscript selector"),this.createSelector(t)}parseObjectLiteral(){const t=[],e=this.getPosition();if(this.check("}"))return this.advance(),{type:"objectLiteral",properties:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column};do{let e;if(this.check("["))this.advance(),e=this.parseExpression(),this.consume("]","Expected ']' after computed property name in object literal");else if(this.matchString()){const t=this.previous().value,n=t.slice(1,-1);e=this.createLiteral(n,t)}else{if(!this.check("-")&&!this.checkPredicate(Jt))return this.addError("Expected property name in object literal"),this.createErrorNode();{let t="",n=0;for(;this.check("-");)this.advance(),t+="-",n=1;for(this.checkPredicate(Jt)&&(t+=this.advance().value);this.check("-");)this.advance(),t+="-",n=1,this.checkPredicate(Jt)&&(t+=this.advance().value);if(""===t||"-"===t)return this.addError("Expected property name in object literal"),this.createErrorNode();e=n?this.createLiteral(t,t):this.createIdentifier(t)}}this.consume(":","Expected ':' after property name in object literal");const n=this.parseExpression();if(t.push({key:e,value:n}),!this.match(","))break;if(this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after object literal properties"),{type:"objectLiteral",properties:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseCSSObjectLiteral(){const t=this.getPosition(),e=[];do{if(this.check("}"))break;let n;if(this.matchPredicate(Jt))n=this.createIdentifier(this.previous().value);else{if(!this.matchString())return this.addError("Expected CSS property name"),this.createErrorNode();{const t=this.previous().value,e=t.slice(1,-1);n=this.createLiteral(e,t)}}if(!this.consume(":","Expected ':' after CSS property name"))return this.createErrorNode();const r=[];let s=0,i=0,o=-1,a=-1;for(;!this.isAtEnd()&&(0!==i||!this.check(";")&&!this.check("}"));){const t=this.advance();r.push(t.value),0>o&&"number"==typeof t.start&&(o=t.start),"number"==typeof t.end&&(a=t.end),"$"===t.value&&this.check("{")&&(s=1),"{"===t.value&&i++,"}"===t.value&&i--}const c=this.originalInput&&o>=0&&a>o?this.originalInput.slice(o,a):r.join(""),l=s?{type:"templateLiteral",value:c,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}:this.createLiteral(c,c);if(e.push({key:n,value:l}),this.check(";")&&this.advance(),this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after CSS object literal properties"),{type:"objectLiteral",properties:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseConstructorCall(){const t=this.previous();if(!this.checkIdentifier())return this.addError('Expected constructor name after "new"'),this.createErrorNode();const e=this.advance(),n=e.value;if(!this.check("("))return this.addError('Expected "(" after constructor name'),this.createErrorNode();this.advance();const r=[];if(!this.check(")"))do{r.push(this.parseExpression())}while(this.match(","));return this.consume(")","Expected ')' after constructor arguments"),{type:"callExpression",callee:{type:"identifier",name:n,start:e.start,end:e.end,line:e.line,column:e.column},arguments:r,isConstructor:1,start:t.start,end:this.previous().end,line:t.line,column:t.column}}parseTopLevelInitBlock(){const t=this.getPosition(),e=this.parseCommandBlock(["end"]);return this.consume("end","Expected 'end' after init block"),{type:"initBlock",commands:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseDefFeature(){const t=this.getPosition();let e="";if(!this.checkIdentifier())return this.addError("Expected function name after 'def'"),{type:"def",name:"",params:[],body:[],start:t.start,end:this.getPosition().end,line:t.line,column:t.column};for(e=this.advance().value;this.check(".");)this.advance(),this.checkIdentifier()&&(e+="."+this.advance().value);const n=[];if(this.check("(")){if(this.advance(),!this.check(")"))for(this.checkIdentifier()&&n.push(this.advance().value);this.check(",");)this.advance(),this.checkIdentifier()&&n.push(this.advance().value);this.consume(")","Expected ')' after parameter list")}const r=this.parseCommandBlock(["end","catch","finally"]),{errorSymbol:s,errorHandler:i,finallyHandler:o}=this.parseErrorAndFinallyBlocks();return this.consume("end","Expected 'end' after function definition"),{type:"def",name:e,params:n,body:r,...void 0!==s&&{errorSymbol:s},...void 0!==i&&{errorHandler:i},...void 0!==o&&{finallyHandler:o},start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseErrorAndFinallyBlocks(){let t,e,n;return this.check("catch")&&(this.advance(),this.checkIdentifier()&&(t=this.advance().value),e=this.parseCommandBlock(["end","finally"])),this.check("finally")&&(this.advance(),n=this.parseCommandBlock(["end"])),{...void 0!==t&&{errorSymbol:t},...void 0!==e&&{errorHandler:e},...void 0!==n&&{finallyHandler:n}}}parseEventNameWithNamespace(t){let e;e=this.checkEvent()||this.checkIdentifier()||this.checkIsCommand()||this.checkIdentifierLike()?this.advance():this.consumeEvent(t);let n=e.value;return this.check(":")&&(this.advance(),n=`${n}:${this.advance().value}`),n}callExprToCommandNode(t,e){return{type:"command",name:t.callee.name,args:t.arguments,isBlocking:0,...void 0!==e.start&&{start:e.start},...void 0!==e.end&&{end:e.end},...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}}}createPseudoCommandNode(t,e,n,r,s){return{type:"command",name:"pseudo-command",args:[{type:"objectLiteral",properties:[{key:{type:"identifier",name:"methodName"},value:{type:"literal",value:t,raw:`"${t}"`}},{key:{type:"identifier",name:"methodArgs"},value:{type:"literal",value:e.arguments,raw:JSON.stringify(e.arguments)}},...n?[{key:{type:"identifier",name:"preposition"},value:{type:"literal",value:n,raw:`"${n}"`}}]:[],{key:{type:"identifier",name:"targetExpression"},value:r}]}],isBlocking:0,...void 0!==s.start&&{start:s.start},...void 0!==s.end&&{end:s.end},...void 0!==s.line&&{line:s.line},...void 0!==s.column&&{column:s.column}}}tryParsePseudoCommand(t,e){const n=t.callee.name,r=this.peek();if(!(Ue.PSEUDO_COMMAND_PREPOSITIONS.includes(r.value.toLowerCase())||Jt(r)&&!this.isCommand(r.value)||Pt(r)))return{node:this.callExprToCommandNode(t,e),isPseudo:0,targetFailed:0};let s,i;this.isCommand(n)&&this.addWarning({type:"command-shadow",message:`Method '${n}' shadows hyperscript command`,suggestions:[`Rename method to avoid confusion (e.g., '${n}Fn', 'my${n.charAt(0).toUpperCase()+n.slice(1)}')`,`Use 'call' command instead: call ${n}(...)`,"This works but may cause ambiguity"],severity:"warning",code:"PSEUDO_CMD_SHADOW",...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}}),Ue.PSEUDO_COMMAND_PREPOSITIONS.includes(this.peek().value.toLowerCase())&&(s=this.advance().value.toLowerCase());try{i=this.parseExpression()}catch{return{node:this.callExprToCommandNode(t,e),isPseudo:0,targetFailed:1}}return{node:this.createPseudoCommandNode(n,t,s,i,e),isPseudo:1,targetFailed:0}}parseCommandWithErrorRecovery(){this.advance();const t=this.error;try{const e=this.parseCommand();return this.error&&this.error!==t&&(lt("\u26a0\ufe0f Command parsing added error, restoring error state. Error was:",this.error.message),this.error=t),e}catch(e){return lt("\u26a0\ufe0f Command parsing threw exception, restoring error state:",e instanceof Error?e.message:e+""),this.error=t,null}}parseTemporalKeywordModifiers(t){if(!this.check("debounced")&&!this.check("throttled"))return;const e=this.advance().value.toLowerCase(),n="debounced"===e?"debounce":"throttle";if(this.match("at"))if(this.checkTimeExpression()){const s=this.advance(),i=(r=s.value).endsWith("ms")?parseInt(r,10):r.endsWith("seconds")||r.endsWith("s")?1e3*parseFloat(r):r.endsWith("minutes")?6e4*parseFloat(r):r.endsWith("hours")?36e5*parseFloat(r):r.endsWith("days")?864e5*parseFloat(r):parseInt(r,10);t[n]=i,lt(`\ud83d\udd27 parseEventHandler: Parsed '${e} at ${s.value}' (${i}ms)`)}else if(this.matchNumber()){const r=parseInt(this.previous().value,10);t[n]=r,lt(`\ud83d\udd27 parseEventHandler: Parsed '${e} at ${r}'`)}else this.addError(`Expected time expression after '${e} at', got: ${this.peek().value}`);else this.addError(`Expected 'at' after '${e}'`);var r}parseEventHandler(){lt("\ud83d\udd27 parseEventHandler: ENTRY - parsing event handler");const t=[];let e=0;if(this.check("first")&&!this.checkIsCommand()&&this.tokens.length>this.current+1){const t=this.tokens[this.current+1],n=t?.value?.toLowerCase();n&&"of"!==n&&"in"!==n&&"from"!==n&&(this.advance(),e=1,lt("\ud83d\udd27 parseEventHandler: Parsed 'first' as .once alias"))}const n=this.parseEventNameWithNamespace("Expected event name after 'on'");for(t.push(n),lt("\ud83d\udd27 parseEventHandler: Parsed first event name: "+n);this.check("or");){this.advance(),lt("\ud83d\udd27 parseEventHandler: Found 'or', parsing additional event name");const e=this.parseEventNameWithNamespace("Expected event name after 'or'");t.push(e),lt("\ud83d\udd27 parseEventHandler: Parsed additional event name: "+e)}let r;if(lt("\ud83d\udd27 parseEventHandler: Total events parsed: "+t.join(", ")),this.registryIntegration){const e=t[0];if(this.registryIntegration.hasEventSource(e)){const t=this.registryIntegration.getEventSource(e);r=t?.name,lt(`\ud83d\udd27 parseEventHandler: Detected custom event source '${r}' for event '${e}'`)}}const s=[];if(this.match("(")){if(!this.check(")"))do{const t=this.advance();s.push(t.value)}while(this.match(","));this.consume(")","Expected ')' after event parameters"),lt("\ud83d\udd27 parseEventHandler: Parsed event parameters: "+s.join(", "))}const i={};for(;this.check(".");){this.advance();const t=this.advance().value.toLowerCase();if("once"===t)i.once=1,lt("\ud83d\udd27 parseEventHandler: Parsed modifier '.once'");else if("prevent"===t)i.prevent=1,lt("\ud83d\udd27 parseEventHandler: Parsed modifier '.prevent'");else if("stop"===t)i.stop=1,lt("\ud83d\udd27 parseEventHandler: Parsed modifier '.stop'");else if("debounce"===t||"throttle"===t){if(!this.check("("))throw Error(`Expected '(' after '.${t}'`);{this.advance();const e=this.advance(),n=parseInt(e.value,10);if(isNaN(n))throw Error(`Expected number for ${t} delay, got: ${e.value}`);"debounce"===t?(i.debounce=n,lt(`\ud83d\udd27 parseEventHandler: Parsed modifier '.debounce(${n})'`)):(i.throttle=n,lt(`\ud83d\udd27 parseEventHandler: Parsed modifier '.throttle(${n})'`)),this.consume(")",`Expected ')' after ${t} delay`)}}else lt(`\ud83d\udd27 parseEventHandler: Warning - unknown modifier '.${t}'`)}let o,a,c,l;if(this.parseTemporalKeywordModifiers(i),e&&(i.once=1),Object.keys(i).length>0&&lt("\ud83d\udd27 parseEventHandler: Parsed modifiers:",i),this.match("[")&&(o=this.parseExpression(),this.consume("]","Expected ']' after event condition")),this.match("from")){const t=this.advance();a=t.value,lt(`\ud83d\udd27 parseEventHandler: Parsed 'from' target: ${a} (kind: ${t.kind})`),this.parseTemporalKeywordModifiers(i)}if(this.match("of")){const t=this.advance();c=t.value.startsWith("@")?t.value.substring(1):t.value,lt("\ud83d\udd27 parseEventHandler: Parsed attribute name: "+c)}this.match("in")&&(lt("\ud83d\udd27 parseEventHandler: Found 'in' keyword, parsing watch target"),l=this.parseExpression(),lt("\ud83d\udd27 parseEventHandler: Parsed watch target expression"));const u=[];for(lt(`\u2705 parseEventHandler: About to parse commands, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd: ${this.isAtEnd()}`);!this.isAtEnd();){if(lt(`\u2705 parseEventHandler: Loop iteration, current token: ${this.peek().value}, kind: ${this.peek().kind}`),this.check("on")){lt("\u2705 parseEventHandler: Stopping command parsing, found next event handler 'on'");break}if(this.checkComment())lt("\u2705 parseEventHandler: Skipping comment token: "+this.peek().value),this.advance();else{if(this.check("end")){lt("\u2705 parseEventHandler: Stopping command parsing, found 'end' keyword"),this.advance();break}if(this.check("catch")||this.check("finally")){lt(`\u2705 parseEventHandler: Stopping command parsing, found '${this.peek().value}'`);break}if(this.checkIsCommand()){const t="("===this.tokens[this.current+1]?.value,e=this.peek().value.toLowerCase();if(t&&"js"!==e&&"tell"!==e){let t;const e=this.error;try{t=this.parseExpression()}catch(t){this.error=e,this.advance();const n=this.parseCommand();u.push(n);continue}if(t&&"callExpression"===t.type){const e=this.tryParsePseudoCommand(t,t);if(u.push(e.node),e.isPseudo||e.targetFailed)continue}}else{const t=this.parseCommandWithErrorRecovery();t&&(u.push(t),lt("\u2705 parseEventHandler: Parsed command, next token: "+(this.isAtEnd()?"END":this.peek().value)))}}else{if(!this.checkIdentifier())break;{const t=this.peek();if(this.isCommand(t.value)){const t=this.parseCommandWithErrorRecovery();t&&u.push(t)}else{let t;const e=this.error;try{t=this.parseExpression()}catch(t){lt("\u26a0\ufe0f Expression parsing error, restoring error state:",t instanceof Error?t.message:t+""),this.error=e;break}if(t&&"callExpression"===t.type){const e=this.tryParsePseudoCommand(t,t);if(u.push(e.node),e.targetFailed)continue}else{if(!t||"binaryExpression"!==t.type||" "!==t.operator)break;{const e=t;if(!e.left||"identifier"!==e.left.type||!this.isCommand(e.left.name))break;{const n={type:"command",name:e.left.name,args:[e.right],isBlocking:0,...void 0!==t.start&&{start:t.start},...void 0!==t.end&&{end:t.end},...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}};u.push(n)}}}}}}for(;!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(",")||this.check("on")||this.check("catch")||this.check("finally"));)this.advance();if(!this.match("then","and",",")&&!this.checkIsCommand()&&!this.isCommand(this.peek().value))break}}let h,f,d;this.isAtEnd()||!this.check("catch")&&!this.check("finally")||(({errorSymbol:h,errorHandler:f,finallyHandler:d}=this.parseErrorAndFinallyBlocks()),this.check("end")&&this.advance());const p=this.getPosition(),m={type:"eventHandler",event:1===t.length?t[0]:t.join("|"),events:t,commands:u,...void 0!==h&&{errorSymbol:h},...void 0!==f&&{errorHandler:f},...void 0!==d&&{finallyHandler:d},...s.length>0&&{args:s},...o&&{condition:o},...a&&{target:a},...c&&{attributeName:c},...l&&{watchTarget:l},...r&&{customEventSource:r},...Object.keys(i).length>0&&{modifiers:i},start:p.start,end:p.end,line:p.line,column:p.column};return lt(`\ud83d\udd27 parseEventHandler: Created node with events: ${t.join(", ")}, attributeName: ${c||"none"}, watchTarget: ${l?"yes":"none"}`),m}parseBehaviorDefinition(){const t=this.getPosition(),e=this.consumeIdentifier("Expected behavior name after 'behavior' keyword").value;/^[A-Z]/.test(e)||this.addError(`Behavior name must start with uppercase letter (got "${e}")`);const n=[];if(this.match("(")){if(!this.check(")"))do{const t=this.consumeIdentifierLike("Expected parameter name");n.push(t.value)}while(this.match(","));this.consume(")","Expected ')' after behavior parameters")}const r=new Set(n),s=[];let i;for(;!this.isAtEnd()&&!this.check("end");)if(this.match("on")){const t=this.getPosition(),e=this.parseEventNameWithNamespace("Expected event name after 'on'"),n=[];if(this.check("(")){for(this.advance();!this.isAtEnd()&&!this.check(")");){const t=this.peek();Jt(t)?(n.push(t.value),this.advance(),this.check(",")&&this.advance()):this.advance()}this.check(")")&&this.advance()}let i;if(this.check("from")){this.advance();const t=[];if(this.check("the")&&this.advance(),!this.isAtEnd()){const e=this.peek(),n=r.has(e.value);this.checkIsCommand()&&!n||(t.push(e.value),i=e.value,this.advance())}}const{commands:o,terminator:a}=this.parseCommandListUntilTerminator(["catch","finally"]);let c,l,u;if("catch"!==a&&"finally"!==a||({errorSymbol:c,errorHandler:l,finallyHandler:u}=this.parseErrorAndFinallyBlocks()),!this.check("end"))throw Error('Expected "end" to close behavior event handler');this.advance();const h={type:"eventHandler",event:e,commands:o,...void 0!==c&&{errorSymbol:c},...void 0!==l&&{errorHandler:l},...void 0!==u&&{finallyHandler:u},...void 0!==i&&{target:i},...n.length>0&&{args:n},start:t.start,end:this.getPosition().end,line:t.line,column:t.column};s.push(h)}else{if(!this.match("init")){this.addError("Unexpected token in behavior body: "+this.peek().value);break}i={type:"initBlock",commands:this.parseCommandBlock(["end"]),start:t.start,end:this.getPosition().end,line:t.line,column:t.column},this.consume("end","Expected 'end' after init block")}return this.consume("end","Expected 'end' to close behavior definition"),{type:"behavior",name:e,parameters:n,eventHandlers:s,...void 0!==i?{initBlock:i}:{},start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseCommandSequence(){const t=[];for(;!this.isAtEnd();){if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){this.advance();const e=this.error,n=this.parseCommand();for(this.error&&this.error!==e&&(this.error.message.includes("Expected closing parenthesis")||this.error.message.includes("Expected ')'")||this.error.message.includes("unclosed parenthes")||this.error.message.includes("Unclosed parenthes")||(lt("\u26a0\ufe0f parseCommandSequence: Command parsing added non-critical error, restoring error state. Error was:",this.error.message),this.error=e)),t.push(n);!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("on"));)lt("\u26a0\ufe0f parseCommandSequence: Skipping unexpected token:",this.peek().value),this.advance();if(this.check("on")){lt('\u2705 parseCommandSequence: Found "on" token, stopping command sequence to allow event handler parsing');break}if(this.match("then"))continue;if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value))continue;break}{const e=this.peek(),n=this.getPosition(),r="Expected command, got: "+e.value;this.addError(r);const s=fe(n,r,e.value);if(t.push(s),this.synchronizeToCommandBoundary(),this.isAtEnd())break;if(this.match("then"))continue;if(this.check("end")||this.check("on"))break;if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value))continue;break}}return 1===t.length?t[0]:function(t){return{type:"CommandSequence",commands:t,start:t[0]?.start||0,end:t[t.length-1]?.end||0,line:t[0]?.line||1,column:t[0]?.column||1}}(t)}getMultiWordPattern(t){return function(t){return de.find(e=>e.command===t.toLowerCase())||null}(t)}isTokenKeyword(t,e){return pe(t,e)}parseMultiWordCommand(t,e){return function(t,e,n){const r=t.getMultiWordPattern(n);if(!r)return null;const s=[],i={};for(;!ye(t,["catch","finally",...r.keywords])&&!pe(t.peek(),r.keywords);){const e=t.parsePrimary();if(!e)break;if(s.push(e),!t.match(",")&&pe(t.peek(),r.keywords))break}for(;!t.isAtEnd()&&pe(t.peek(),r.keywords);){const e=t.advance().value,n=t.parseExpression();if(n&&(i[e]=n),!pe(t.peek(),r.keywords))break}const o=xe.from(e).withArgs(...s).endingAt(t.getPosition());return Object.keys(i).length>0&&o.withModifiers(i),o.build()}(this.getContext(),t,e)}parseCommandBlock(t){const e=[];for(;!this.isAtEnd()&&!t.some(t=>this.check(t));)if(this.checkComment())this.advance();else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value))break;{this.advance();const t=this.parseCommand();e.push(t)}}return e}trySemanticParse(t){if(!this.semanticAdapter||!this.semanticAdapter.isAvailable())return null;try{const e=this.semanticAdapter.trySemanticParse(t);return e.success&&e.node?(lt(`[Semantic] Successfully parsed with confidence ${e.confidence}:`,e.node.name),e.node):(lt(`[Semantic] Low confidence (${e.confidence}), falling back to traditional parser`),null)}catch(t){return lt("[Semantic] Error during semantic parse:",t),null}}getRemainingInput(){if(!this.originalInput)return this.tokens.slice(this.current>0?this.current-1:0).map(t=>t.value).join(" ");const t=this.current>0?this.tokens[this.current-1]:this.tokens[0];return t&&void 0!==t.start?this.originalInput.slice(t.start):this.originalInput}skipToCommandBoundary(){const t=["then","and","else","end"];for(;!this.isAtEnd();){const e=this.peek(),n=e.value.toLowerCase();if(t.includes(n))break;if(jt(e))break;this.advance()}}parseCommand(){const t=this.parseCommandCore();if(t&&"command"===t.type&&!t.body&&(this.check("when")||this.check("where"))){const e=this.peek().value.toLowerCase();this.advance();const n=this.parseExpression();n&&(t.modifiers={...t.modifiers??{},[e]:n})}return t}parseCommandCore(){const t=this.previous();let e=t.value;if(this.semanticAdapter&&!["install","wait","repeat","for","set","put","increment","decrement","add","append","toggle","if","unless","make","measure","trigger","halt","remove","exit","return","closest","js","tell","fetch"].includes(e.toLowerCase())){const t=this.getRemainingInput(),e=this.trySemanticParse(t);if(e)return this.skipToCommandBoundary(),e}if("beep"===e&&this.check("!")&&(this.advance(),e="beep!"),"fetch"===e)return function(t,e){const n={};let r=null;if(!t.isAtEnd()&&Be(t)&&(r=_e(t)),r||(r=t.parsePrimary()),!r)return t.addError("fetch requires a URL"),xe.from(e).endingAt(t.getPosition()).build();!t.isAtEnd()&&t.check("{")&&(n.with=t.parsePrimary());for(let e=0;3>e&&!t.isAtEnd();e++)if(!t.check("as")||n.as){if(!t.check("with")||n.with){if(t.check("do")&&!n.doNotThrow){const e=t.peekAt(1),r=t.peekAt(2);if("not"===e?.value&&"throw"===r?.value){const e=t.advance();t.advance();const r=t.advance();n.doNotThrow={type:"literal",value:1,start:e.start,end:r.end,line:e.line,column:e.column};continue}}break}t.advance(),n.with=Ve(t)?qe(t):t.parsePrimary()}else t.advance(),t.isAtEnd()||we(t,"a")||we(t,"an"),n.as=t.parsePrimary();const s=xe.from(e).withArgs(r).endingAt(t.getPosition());return Object.keys(n).length>0&&s.withModifiers(n),s.build()}(this.getContext(),t);const n=this.parseMultiWordCommand(t,e);if(n)return n;const r=e.toLowerCase();if("repeat"===r)return this.parseRepeatCommand(t);if("for"===r)return this.parseForCommand(t);if("if"===r||"unless"===r)return this.parseIfCommand(t);if("wait"===r)return this.parseWaitCommand(t);if("install"===r)return this.parseInstallCommand(t);if("transition"===r)return this.parseTransitionCommand(t);if("add"===r)return this.parseAddCommand(t);if(this.isCompoundCommand(r))return this.parseCompoundCommand({type:"identifier",name:r,start:t.start||0,end:t.end||0,line:t.line,column:t.column})||function(t,e){return{type:"command",name:t,args:[],partial:1,start:e.start,end:e.end,line:e.line,column:e.column}}(r,this.getPosition());const s=[];if(("increment"===e||"decrement"===e)&&!this.isAtEnd())return function(t,e){const n=e.value,r="increment"===n?"+":"-";let s=0;t.check(v)&&(s=1,t.advance());const i=t.parseExpression();if(!i)throw Error("Expected variable or expression after "+n);let o;if(t.check("by")){t.advance();const e=t.parseExpression();if(!e)throw Error(`Expected amount after 'by' in ${n} command`);o=e}else o=se(1,"1",{start:e.start,end:t.previous().end,line:e.line,column:e.column});let a=i;s&&"identifier"===i.type&&(a={...i,scope:"global"});const c={start:e.start,end:t.previous().end,line:e.line,column:e.column},l=oe(r,i,o,c);l.coerceNumeric=1;const u=[a,ie(h,c),l];return xe.from(e).withName("set").withArgs(...u).withOriginalCommand(n).endingAt({end:t.previous().end}).build()}(this.getContext(),t);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.check("end")||this.checkIsCommand());){const t=this.parseExpression();if(s.push(t||this.parsePrimary()),this.match(","))continue;const e=["into","from","to","with","by","at","before","after","over"];if(e.some(t=>this.check(t)))continue;const n=s[s.length-1];if(!n||"identifier"!==n.type&&"keyword"!==n.type||!e.includes(n.name??n.value))break}const i=this.getPosition();return{type:"command",name:e,args:s,isBlocking:0,start:i.start,end:i.end,line:i.line,column:i.column}}parseConditional(){const t=this.parseExpression();this.consume("then","Expected 'then' after if condition");const e=this.parseConditionalBranch();let n;this.match("else")&&(n=this.parseConditionalBranch());const r=this.getPosition();return{type:"conditionalExpression",test:t,consequent:e,alternate:n,start:r.start,end:r.end,line:r.line,column:r.column}}parseConditionalBranch(){if(this.checkIsCommand()){const t=this.advance(),e=this.createIdentifier(t.value);return this.createCommandFromIdentifier(e)||e}if(this.checkIdentifier()||this.checkKeyword()){const t=this.peek();if(this.isCommand(t.value)){const t=this.advance(),e=this.createIdentifier(t.value);return this.createCommandFromIdentifier(e)||e}}return this.parseExpression()}parseNavigationFunction(t){const e=[];if(this.match("of"))e.push(this.parseExpression());else{if(this.check("("))return this.finishCall(this.createIdentifier(t));this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||e.push(this.parsePrimary())}const n=this.createCallExpression(this.createIdentifier(t),e);if("next"===t||"previous"===t){const t=this.parseRelativePositionalModifiers();t&&(n.relativePositional=t)}return n}parseRelativePositionalModifiers(){if(!(this.check("from")||this.check("within")||this.check("in")||this.check("with")))return null;let t,e,n,r=0,s=0;return this.match("from")&&(t=this.parseRelativePositionalOperand()),this.match("in")?(r=1,n=this.parseRelativePositionalOperand()):this.match("within")&&(e=this.parseRelativePositionalOperand()),this.match("with")&&(this.match("wrapping"),s=1),{from:t,within:e,inElt:n,inSearch:r,wrapping:s}}parseRelativePositionalOperand(){return this.match("the"),this.parsePrimary()}parseTheXofY(){if(!this.checkIdentifier())return this.createIdentifier("the");const t=this.peek(),e=t.value;return["first","last","next","previous","random","closest"].includes(e)?(this.advance(),this.parseNavigationFunction(e)):(this.advance(),this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:e},target:this.parseCall(),line:t.line,column:t.column}):this.createIdentifier(e))}parseContextPropertyAccess(t){if(this.match("*")){let e="";if(!this.checkIdentifier())return this.addError("Expected property name after 'my *'"),this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(""),0);for(e=this.advance().value;this.check("-")&&!this.isAtEnd();){if(e+="-",this.advance(),!this.checkIdentifier()){this.addError("Expected identifier after hyphen in CSS property name");break}e+=this.advance().value}const n="*"+e;return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(n),0)}{if(this.check("[")&&this.tokens[this.current+1]?.value?.startsWith("@")){this.advance();const e=this.advance();return this.consume("]","Expected ']' after attribute reference"),this.createMemberExpression(this.createIdentifier(t),{type:"attributeAccess",attributeName:e.value.substring(1),start:e.start,end:e.end,line:e.line,column:e.column},1)}if(Wt(this.peek())&&this.peek().value.startsWith("@")){const e=this.advance();return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(e.value),0)}const e=this.consumeIdentifierLike(`Expected property name after '${{me:"my",it:"its",you:"your"}[t]}'`);return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(e.value),0)}}parseMyPropertyAccess(){return this.parseContextPropertyAccess("me")}finishCall(t){const e=[];if(!this.check(")"))do{if(this.check(","))return this.addError("Unexpected token in function arguments"),this.createCallExpression(t,[this.createErrorNode()]);e.push(this.parseExpression())}while(this.match(","));if(!this.check(")")&&"identifier"===t.type){const e=t.name;C.has(e.toLowerCase())&&lt(`\ud83d\udca1 Tip: CSS functions like ${e}() should be quoted for clean parsing. Use '${e}(...)' or \`${e}(...)\` instead.`)}return this.consume(")","Expected ')' after arguments"),this.createCallExpression(t,e)}createLiteral(t,e){return se(t,e,this.getPosition())}createIdentifier(t){return ie(t,this.getPosition())}createBinaryExpression(t,e,n){return oe(t,e,n,this.getPosition())}createUnaryExpression(t,e,n){return function(t,e,n,r){return{type:"unaryExpression",operator:t,argument:e,prefix:n,start:r.start,end:r.end,line:r.line,column:r.column}}(t,e,n,this.getPosition())}createCallExpression(t,e){return function(t,e,n){return{type:"callExpression",callee:t,arguments:e,start:n.start,end:n.end,line:n.line,column:n.column}}(t,e,this.getPosition())}createMemberExpression(t,e,n){return function(t,e,n,r){return{type:"memberExpression",object:t,property:e,computed:n,start:r.start,end:r.end,line:r.line,column:r.column}}(t,e,n,this.getPosition())}createSelector(t){return function(t,e){return{type:"selector",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}(t,this.getPosition())}createPossessiveExpression(t,e){return function(t,e,n){return{type:"possessiveExpression",object:t,property:e,start:n.start,end:n.end,line:n.line,column:n.column}}(t,e,this.getPosition())}createErrorNode(){return{type:"identifier",name:"__ERROR__",start:(t=this.getPosition()).start,end:t.end,line:t.line,column:t.column};var t}processEscapeSequences(t){return t.replace(/\\(.)/g,(t,e)=>{switch(e){case"n":return"\n";case"t":return"\t";case"r":return"\r";case"b":return"\b";case"f":return"\f";case"v":return"\v";case"0":return"\0";case"\\":return"\\";case'"':return'"';case"'":return"'";default:return e}})}createProgramNode(t){return function(t){if(lt(`\u2705 createProgramNode: Called with ${t.length} statements`),0===t.length)return lt("\u2705 createProgramNode: Returning error node (0 statements)"),{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===t.length)return lt(`\u2705 createProgramNode: Returning single statement (type=${t[0].type})`),t[0];const e={type:"Program",statements:t,start:t[0]?.start||0,end:t[t.length-1]?.end||0,line:t[0]?.line||1,column:t[0]?.column||1};return lt(`\u2705 createProgramNode: Returning Program node with ${t.length} statements, type=${e.type}`),e}(t)}match(...t){for(const e of t)if(this.check(e))return this.advance(),1;return 0}matchOperator(t){if(this.isAtEnd())return 0;const e=this.peek();return ne(e)&&e.value===t?(this.advance(),1):0}check(t){if(this.isAtEnd())return 0;const e=this.peek().value;return this.resolveKeyword(e)===t}checkPredicate(t){return this.isAtEnd()?0:t(this.peek())}matchPredicate(t){return this.checkPredicate(t)?(this.advance(),1):0}checkSelector(){return this.checkPredicate(Vt)}matchSelector(){return this.matchPredicate(Vt)}checkAnySelector(){return this.checkPredicate(_t)}checkLiteral(){return this.checkPredicate(qt)}checkIdentifierLike(){return this.checkPredicate(Bt)}checkIsCommand(){return this.checkPredicate(jt)}checkCommandTerminator(){return this.checkPredicate(re)}checkReference(){return this.checkPredicate(Ht)}checkTimeExpression(){return this.checkPredicate(Ut)}checkEvent(){return this.checkPredicate(Dt)}checkContextVar(){return this.checkPredicate(Pt)}checkComment(){return this.checkPredicate(zt)}checkIdentifier(){return this.checkPredicate(Jt)}checkKeyword(){return this.checkPredicate(Mt)}checkString(){return this.checkPredicate(Zt)}matchString(){return this.matchPredicate(Zt)}checkNumber(){return this.checkPredicate(Gt)}matchNumber(){return this.matchPredicate(Gt)}checkBoolean(){return this.checkPredicate(Xt)}matchBoolean(){return this.matchPredicate(Xt)}checkTemplateLiteral(){return this.checkPredicate(Yt)}matchTemplateLiteral(){return this.matchPredicate(Yt)}checkQueryReference(){return this.checkPredicate(Kt)}matchQueryReference(){return this.matchPredicate(Kt)}checkIdSelector(){return this.checkPredicate(Qt)}checkClassSelector(){return this.checkPredicate(te)}checkCssSelector(){return this.checkPredicate(ee)}checkBasicOperator(){return this.checkPredicate(ne)}matchBasicOperator(){return this.matchPredicate(ne)}matchTimeExpression(){return this.matchPredicate(Ut)}matchIdentifierLike(){return this.matchPredicate(Bt)}matchComparisonOperator(){return this.matchPredicate(Ft)}consumePredicate(t,e){return this.checkPredicate(t)?this.advance():(this.addError(e),this.peek())}consumeIdentifier(t){return this.consumePredicate(Jt,t)}consumeIdentifierLike(t){return this.consumePredicate(Bt,t)}consumeEvent(t){return this.consumePredicate(Dt,t)}advance(){return this.isAtEnd()||this.current++,this.previous()}isAtEnd(){return this.current>=this.tokens.length}peek(){return this.isAtEnd()?{kind:"unknown",value:"",start:0,end:0,line:1,column:1}:this.tokens[this.current]}peekAt(t){const e=this.current+t;return e>=0&&this.tokens.length>e?this.tokens[e]:null}previous(){return this.tokens[this.current-1]}consume(t,e){return this.check(t)?this.advance():(this.addError(e),this.peek())}addError(t){const e=this.peek();let n=e.start||0,r=e.line||1,s=e.column||1;if(t.includes("property name after '.'")){const t=this.current>0?this.previous():e;n=t.end||t.start||0,r=t.line||1,s=t.column||1}if(t.includes("parenthes")){const t=this.current>0?this.previous():e;n=t.end||t.start||0,r=t.line||1,s=t.column||1,0===n&&this.current>0&&(n=this.current)}if(t.includes("Expected expression after")){const t=this.current>0?this.previous():e;n=t.start||0,r=t.line||1,s=t.column||1,0===n&&(n=Math.max(1,this.current-1))}if(t.includes("Missing operand")){let t=e;for(let e=this.current-1;e>=0;e--){const n=this.tokens[e];if(n&&("+"===n.value||"-"===n.value)){t=n;break}}n=t.start||0,r=t.line||1,s=t.column||1}this.error={message:t,line:Math.max(1,r),column:Math.max(1,s),position:Math.max(0,n)},this.errors.push(this.error)}synchronizeToCommandBoundary(){for(;!this.isAtEnd();){const t=this.peek();if("then"===t.value||"end"===t.value||"on"===t.value)return;if(this.checkIsCommand()||this.isCommand(t.value)&&!this.isKeyword(t.value))return;lt("\u26a0\ufe0f synchronize: Skipping token:",t.value),this.advance()}}parseAttributeOrArrayLiteral(){const t=this.previous().start,e=this.previous().line,n=this.previous().column;if(!this.isAtEnd()&&this.peek().value.startsWith("@")){const r=[];for(;!this.check("]")&&!this.isAtEnd();){const t=this.advance();r.push(t.value)}this.consume("]","Expected ']' after attribute literal");const s=r.join("");if(!s.includes("="))return{type:"attributeAccess",attributeName:s.replace(/^@/,""),start:t,end:this.previous().end,line:e,column:n};const i="["+s+"]";return{type:"literal",value:i,raw:i,start:t,end:this.previous().end,line:e,column:n}}const r=new Set(["=","~=","|=","^=","$=","*="]),s=this.tokens[this.current],i=this.tokens[this.current+1];if("identifier"===s?.kind&&("]"===i?.value||i&&r.has(i.value)&&"string"===this.tokens[this.current+2]?.kind)){let t="["+this.advance().value;if(this.check("]"))this.advance(),t+="]";else{const e=this.advance().value,n=this.advance().value;t+=e+'"'+(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?n.slice(1,-1):n)+'"',this.consume("]","Expected ']' after attribute selector"),t+="]"}return this.createSelector(t)}const o=[];if(!this.check("]"))do{if(this.check("]"))break;o.push(this.parseExpression())}while(this.match(","));return this.consume("]","Expected ']' after array elements"),{type:"arrayLiteral",elements:o,start:t,end:this.previous().end,line:e,column:n}}getPosition(){const t=this.current>0?this.previous():this.peek();return{start:t.start||0,end:t.end||0,line:t.line||1,column:t.column||1}}getContext(){const t=this,e={tokens:this.tokens,advance:this.advance.bind(this),peek:this.peek.bind(this),previous:this.previous.bind(this),consume:this.consume.bind(this),check:this.check.bind(this),checkIdentifierLike:this.checkIdentifierLike.bind(this),checkSelector:this.checkSelector.bind(this),checkAnySelector:this.checkAnySelector.bind(this),checkLiteral:this.checkLiteral.bind(this),checkReference:this.checkReference.bind(this),checkTimeExpression:this.checkTimeExpression.bind(this),checkEvent:this.checkEvent.bind(this),checkIsCommand:this.checkIsCommand.bind(this),checkContextVar:this.checkContextVar.bind(this),match:this.match.bind(this),matchOperator:this.matchOperator.bind(this),isAtEnd:this.isAtEnd.bind(this),createIdentifier:this.createIdentifier.bind(this),parseExpression:this.parseExpression.bind(this),parsePrimary:this.parsePrimary.bind(this),parseLogicalAnd:this.parseLogicalAnd.bind(this),parseCSSObjectLiteral:this.parseCSSObjectLiteral.bind(this),parseCommand:this.parseCommand.bind(this),parseCommandSequence:this.parseCommandSequence.bind(this),parseCommandListUntilEnd:this.parseCommandListUntilEnd.bind(this),parseCommandListUntilEndOrElse:this.parseCommandListUntilEndOrElse.bind(this),parseRepeatBody:this.parseRepeatBody.bind(this),getPosition:this.getPosition.bind(this),addError:this.addError.bind(this),addWarning:this.addWarning.bind(this),isCommand:this.isCommand.bind(this),isCompoundCommand:this.isCompoundCommand.bind(this),isKeyword:this.isKeyword.bind(this),getMultiWordPattern:this.getMultiWordPattern.bind(this),resolveKeyword:this.resolveKeyword.bind(this),savePosition:()=>t.current,restorePosition:e=>{t.current=e},peekAt:e=>t.peekAt(e),getInputSlice:(t,e)=>this.originalInput?0>t||t>=this.originalInput.length?"":void 0!==e?this.originalInput.slice(t,e):this.originalInput.slice(t):""};return Object.defineProperty(e,"current",{get:()=>t.current,set:e=>{t.current=e},enumerable:1,configurable:1}),e}}function We(t,e){const n=function(t){const e={input:"",position:0,line:1,column:1,tokens:[]};e.input=t;const n=t.length;for(;n>e.position&&(F(e),n>e.position);){const n=t[e.position];if("-"!==n||"-"!==D(e,1))if('"'!==n){if("'"===n||"'"===n){const t=D(e,1),n=e.tokens[e.tokens.length-1];if("s"!==t||!n||/\s/.test(e.input[e.position-1]??" ")||n.kind!==I.IDENTIFIER&&n.kind!==I.SELECTOR&&"]"!==n.value&&")"!==n.value&&"}"!==n.value)q(e);else{const t=e.position;P(e),P(e),B(e,I.OPERATOR,"'s",t)}continue}if("`"!==n)if("<"!==n)if("#"!==n){if("."===n){if("."===D(e,1)){const t=e.position;P(e),P(e),B(e,I.OPERATOR,"..",t);continue}const t=e.tokens[e.tokens.length-1],n=new Set(["from","to","into","on","in","at","between","first","last","next","previous","closest","random","of","some","no"]),r=t&&t.kind===I.IDENTIFIER&&E.has(t.value.toLowerCase()),s=t&&t.kind===I.IDENTIFIER&&n.has(t.value.toLowerCase());if((!t||t.kind===I.OPERATOR&&")"!==t.value&&"]"!==t.value||r||s||"("===t.value||"["===t.value||"{"===t.value||","===t.value||";"===t.value)&&(!t||t.end!==e.position)&&(Y(D(e))||"{"===D(e)||"-"===D(e))){U(e);continue}}if("@"!==n)if("{"!==n)if("}"!==n){if("["===n){const t=e.tokens[e.tokens.length-1],n=t&&t.kind===I.IDENTIFIER&&R.has(t.value)&&e.tokens.length>=2&&"on"===e.tokens[e.tokens.length-2]?.value;(!t||t.kind!==I.IDENTIFIER&&")"!==t.value&&"]"!==t.value||n)&&n?(B(e,I.SYMBOL,"["),P(e)):(B(e,I.OPERATOR,"["),P(e));continue}if("]"!==n){if("$"===n){const t=D(e,1);if(t>="a"&&"z">=t||t>="A"&&"Z">=t||"_"===t){X(e);continue}}et(n)?J(e):"0">n||n>"9"?("a">n||n>"z")&&("A">n||n>"Z")&&"_"!==n?(B(e,I.UNKNOWN,n),P(e)):G(e):Z(e)}else B(e,I.OPERATOR,"]"),P(e)}else B(e,I.OPERATOR,"}"),P(e);else B(e,I.OPERATOR,"{"),P(e);else z(e)}else U(e);else tt(e)?W(e):J(e);else H(e)}else q(e);else V(e)}return e.tokens}(t);return new Ue(n,e,t).parse()}Ue.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty","ignoring case"]),Ue.PRATT_TABLE=Et,Ue.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];class ze{constructor(){this.hooks=new Map,this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}register(t,e){this.unregister(t),this.hooks.set(t,e),e.beforeExecute&&this.beforeExecuteHooks.push(e.beforeExecute),e.afterExecute&&this.afterExecuteHooks.push(e.afterExecute),e.onError&&this.onErrorHooks.push(e.onError),e.interceptCommand&&this.interceptCommandHooks.push(e.interceptCommand)}unregister(t){const e=this.hooks.get(t);if(!e)return 0;if(e.beforeExecute){const t=this.beforeExecuteHooks.indexOf(e.beforeExecute);t>-1&&this.beforeExecuteHooks.splice(t,1)}if(e.afterExecute){const t=this.afterExecuteHooks.indexOf(e.afterExecute);t>-1&&this.afterExecuteHooks.splice(t,1)}if(e.onError){const t=this.onErrorHooks.indexOf(e.onError);t>-1&&this.onErrorHooks.splice(t,1)}if(e.interceptCommand){const t=this.interceptCommandHooks.indexOf(e.interceptCommand);t>-1&&this.interceptCommandHooks.splice(t,1)}return this.hooks.delete(t)}has(t){return this.hooks.has(t)}async runBeforeExecute(t){for(const e of this.beforeExecuteHooks)await e(t)}async runAfterExecute(t,e){for(const n of this.afterExecuteHooks)await n(t,e)}async runOnError(t,e){let n=e;for(const e of this.onErrorHooks){const r=await e(t,n);r instanceof Error&&(n=r)}return n}shouldIntercept(t,e){for(const n of this.interceptCommandHooks)if(n(t,e))return 1;return 0}getRegisteredNames(){return Array.from(this.hooks.keys())}clear(){this.hooks.clear(),this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}}function Je(t){return t instanceof Error&&("isHalt"in t||"isExit"in t||"isBreak"in t||"isContinue"in t||"isReturn"in t)?t:null}function Ze(t){return{ok:1,value:t}}function Ge(t){return{ok:0,error:t}}function Xe(t){return 1==t.ok}const Ye=new Map,Ke=new WeakMap;function Qe(t){let e=Ke.get(t);return e||(e=new Map,Ke.set(t,e)),e}function tn(t){return t.owner||(t.me instanceof Element?t.me:null)}function en(t,e){const n=tn(t);if(n)return Lt(e,t),Qe(n).get(e)}function nn(t,e,n){const r=tn(t);r&&(Qe(r).set(e,n),Rt(e,n,t))}function rn(t,e){return{me:t??null,owner:t??null,it:null,you:null,result:null,locals:new Map,globals:e||Ye,flags:{halted:0,breaking:0,continuing:0,returning:0,async:0}}}function sn(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"tagName"in t&&"string"==typeof t.tagName&&"classList"in t}function on(t){return null!==t&&"object"==typeof t&&"length"in t&&"number"==typeof t.length&&(Symbol.iterator in t||"function"==typeof t.item)}function an(t){if(null==t)return 0;if("number"==typeof t)return isFinite(t)?t:0;if("string"==typeof t)return parseFloat(t);if("boolean"==typeof t)return t?1:0;if(Array.isArray(t))return t.length;if("object"==typeof t){if("length"in t&&"number"==typeof t.length)return t.length;if("function"==typeof t.valueOf){const e=t.valueOf();if("number"==typeof e)return e}return NaN}return 0}function cn(t,e,n,r){if("element"!==r){if("global"===r)return It(n,t,e),void("undefined"!=typeof window&&(window[t]=e));if(t.startsWith("$"))return void It(n,t.slice(1),e);if(n.locals&&n.locals.has(t))return n.locals.set(t,e),void Rt(t,e,n);if(n.globals&&n.globals.has(t))return It(n,t,e),void("undefined"!=typeof window&&t in window&&(window[t]=e));if(n.variables&&n.variables.has(t))n.variables.set(t,e);else{if("undefined"!=typeof window&&t in window)return window[t]=e,void It(n,t,e);n.locals.set(t,e),Rt(t,e,n)}}else nn(n,t,e)}const ln=new class{constructor(t={}){this.types=new Map,this.coercionCache=new Map,this.config={strictMode:0,cacheCoercions:1,...t},this.registerBuiltinTypes()}register(t){this.types.has(t.name)&&console.warn(`ExpressionTypeRegistry: Overwriting existing type '${t.name}'`),this.types.set(t.name,t)}get(t){return this.types.get(t)}has(t){return this.types.has(t)}getTypeNames(){return Array.from(this.types.keys())}inferType(t){for(const[e,n]of this.types)if(n.isType(t))return e;return"Unknown"}getHyperScriptType(t){const e=this.inferType(t),n=this.types.get(e);return n?.hyperscriptType??"unknown"}coerce(t,e,n){const r=this.types.get(e);if(!r){if(this.config.strictMode)throw Error("Unknown target type: "+e);return null}if(r.isType(t))return t;if(this.config.cacheCoercions){const n=`${this.inferType(t)}:${e}:${JSON.stringify(t)}`;if(this.coercionCache.has(n))return this.coercionCache.get(n)}const s=this.inferType(t),i=r.coerceFrom?.[s];if(i){const r=i(t,n);if(this.config.cacheCoercions&&null!==r){const n=`${s}:${e}:${JSON.stringify(t)}`;this.coercionCache.set(n,r)}return r}return r.defaultValue}canCoerce(t,e){const n=this.types.get(e);if(!n)return 0;if(n.isType(t))return 1;const r=this.inferType(t);return void 0!==n.coerceFrom?.[r]}getCoercionInfo(t,e){const n=this.types.get(e);return n&&(t===e||n.coerceFrom?.[t])?{possible:1,direct:1}:{possible:0,direct:0}}clearCache(){this.coercionCache.clear()}getStats(){return{typeCount:this.types.size,cacheSize:this.coercionCache.size,typeNames:this.getTypeNames()}}registerBuiltinTypes(){this.register({name:"String",hyperscriptType:"string",tsType:"string",isType:t=>"string"==typeof t,defaultValue:"",description:"Text string value",examples:["hello","world",""],coerceFrom:{Number:t=>t+"",Boolean:t=>t+"",Null:()=>"",Undefined:()=>"",Array:t=>Array.isArray(t)?t.join(", "):null,Object:t=>{try{return JSON.stringify(t)}catch{return t+""}},Element:t=>t instanceof Element?t.textContent??t.outerHTML:null}}),this.register({name:"Number",hyperscriptType:"number",tsType:"number",isType:t=>"number"==typeof t&&!isNaN(t),defaultValue:0,description:"Numeric value (integer or float)",examples:[0,1,3.14,-42],coerceFrom:{String:t=>{const e=parseFloat(t);return isNaN(e)?null:e},Boolean:t=>t?1:0,Null:()=>0,Undefined:()=>null}}),this.register({name:"Boolean",hyperscriptType:"boolean",tsType:"boolean",isType:t=>"boolean"==typeof t,defaultValue:0,description:"True or false value",examples:[1,0],coerceFrom:{String:t=>{const e=t.toLowerCase().trim();return"true"===e||"yes"===e||"1"===e?1:"false"===e||"no"===e||"0"===e||""===e?0:e.length>0},Number:t=>0!==t,Null:()=>0,Undefined:()=>0,Array:t=>Array.isArray(t)?t.length>0:0,Element:t=>t instanceof Element,ElementList:t=>Array.isArray(t)&&t.length>0}}),this.register({name:"Element",hyperscriptType:"element",tsType:"Element | HTMLElement",isType:t=>t instanceof Element,defaultValue:null,description:"DOM Element",coerceFrom:{String:(t,e)=>{const n=t;if(n.startsWith("#")||n.startsWith(".")||n.match(/^[\w-]+$/))try{return document.querySelector(n)}catch{return null}return null},ElementList:t=>Array.isArray(t)&&t.length>0?t[0]:null,NodeList:t=>t.length>0?t[0]:null}}),this.register({name:"ElementList",hyperscriptType:"element-list",tsType:"Element[]",isType:t=>Array.isArray(t)&&t.length>0&&t.every(t=>t instanceof Element),defaultValue:[],description:"Array of DOM Elements",coerceFrom:{Element:t=>t instanceof Element?[t]:[],NodeList:t=>Array.from(t),String:t=>{try{return Array.from(document.querySelectorAll(t))}catch{return[]}},Array:t=>{const e=t;return e.every(t=>t instanceof Element)?e:[]}}}),this.register({name:"Array",hyperscriptType:"array",tsType:"unknown[]",isType:t=>Array.isArray(t),defaultValue:[],description:"Array of values",coerceFrom:{String:t=>{const e=t;try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map(t=>t.trim())},ElementList:t=>t,NodeList:t=>Array.from(t),Object:t=>Object.values(t)}}),this.register({name:"Object",hyperscriptType:"object",tsType:"Record<string, unknown>",isType:t=>!("object"!=typeof t||null===t||Array.isArray(t)||t instanceof Element),defaultValue:{},description:"Plain JavaScript object",coerceFrom:{String:t=>{try{const e=JSON.parse(t);if("object"==typeof e&&null!==e&&!Array.isArray(e))return e}catch{}return null},Array:t=>{const e={};return t.forEach((t,n)=>{e[n+""]=t}),e}}}),this.register({name:"Null",hyperscriptType:"null",tsType:"null",isType:t=>null===t,defaultValue:null,description:"Null value"}),this.register({name:"Undefined",hyperscriptType:"undefined",tsType:"undefined",isType:t=>void 0===t,defaultValue:void 0,description:"Undefined value"}),this.register({name:"Function",hyperscriptType:"function",tsType:"Function",isType:t=>"function"==typeof t,defaultValue:null,description:"JavaScript function"}),this.register({name:"Event",hyperscriptType:"event",tsType:"Event",isType:t=>t instanceof Event,defaultValue:null,description:"DOM Event"}),this.register({name:"NodeList",hyperscriptType:"element-list",tsType:"NodeList",isType:t=>t instanceof NodeList,defaultValue:null,description:"DOM NodeList (typically from querySelectorAll)",coerceFrom:{Array:t=>null}}),this.register({name:"Unknown",hyperscriptType:"unknown",tsType:"unknown",isType:t=>1,defaultValue:null,description:"Unknown/any value type"})}};function un(t){const e=ln.get("String");return e?e.isType(t):"string"==typeof t}function hn(t){const e=ln.get("Number");return e?e.isType(t):"number"==typeof t}function fn(t){const e=ln.get("Boolean");return e?e.isType(t):"boolean"==typeof t}function dn(t){const e=ln.get("Object");return e?e.isType(t):"object"==typeof t&&null!==t}function pn(t){const e=ln.get("Function");return e?e.isType(t):"function"==typeof t}function mn(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"style"in t}function yn(t){return t instanceof Element}function gn(t){return t instanceof HTMLElement}const vn=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function bn(t,e){return vn.has(e.toLowerCase())?t.hasAttribute(e):t.getAttribute(e)}const wn={id:t=>t.id,classname:t=>t.className,class:t=>t.className,tagname:t=>t.tagName.toLowerCase(),innertext:t=>t.textContent?.trim(),innerHTML:t=>t.innerHTML,outerhtml:t=>t.outerHTML,value:t=>function(t){if(null===t||"object"!=typeof t||!("tagName"in t))return 0;const e=t.tagName;return"INPUT"===e||"SELECT"===e||"TEXTAREA"===e}(t)?t.value:void 0,checked:t=>function(t){return null!==t&&"object"==typeof t&&"tagName"in t&&"INPUT"===t.tagName}(t)?t.checked:void 0,disabled:t=>"disabled"in t?t.disabled:void 0,selected:t=>function(t){return null!=t&&"object"==typeof t&&"tagName"in t&&"OPTION"===t.tagName}(t)?t.selected:void 0,tabindex:t=>mn(t)?t.tabIndex:void 0,hidden:t=>mn(t)?t.hidden:void 0,style:t=>getComputedStyle(t),children:t=>Array.from(t.children),parent:t=>t.parentElement,firstchild:t=>t.firstElementChild,lastchild:t=>t.lastElementChild,nextsibling:t=>t.nextElementSibling,previoussibling:t=>t.previousElementSibling,next:t=>t.nextElementSibling,previous:t=>t.previousElementSibling,values:t=>function(t){if(t instanceof HTMLFormElement)return new FormData(t);const e=new FormData;return t.querySelectorAll("input, select, textarea").forEach(t=>{const n=t.getAttribute("name");n&&"value"in t&&e.append(n,t.value)}),e}(t)};function En(t,e){if(e.startsWith("*"))return function(t,e){if(!gn(t))return;if(e.startsWith("computed-"))return getComputedStyle(t).getPropertyValue(e.slice(9))||"";const n=e.replace(/-([a-z])/g,(t,e)=>e.toUpperCase());return t.style[n]}(t,e.slice(1));if(e.startsWith("computed-")){const n=e.slice(9);return gn(t)?getComputedStyle(t).getPropertyValue(n):void 0}if(e.startsWith("@"))return bn(t,e.slice(1));const n=wn[e.toLowerCase()];if(n)return n(t);if(function(t,e){return t.hasAttribute(e)}(t,e))return bn(t,e);const r=t[e];return pn(r)?r.bind(t):r}const xn={1:"one",2:"two",3:"three",4:"four",5:"five"};function kn(t,e,n,r){return t.length!==e?`${n} requires exactly ${s=e,xn[s]??s+""} argument${1===e?"":"s"}${r?` (${r})`:""}`:null;var s}function Sn(t,e,n,r){return"string"!=typeof t[e]?`${n} ${r||"argument "+(e+1)} must be a string`:null}function An(t,e,n){return kn(t,1,e,n)??Sn(t,0,e,n)}function Nn(t,e){return kn(t,2,e,"left, right")}function Cn(){return null}function Tn(t,e,n,r){return t.length>e?`${n} expression takes at most ${1===e?"one":e+""} argument${1===e?"":"s"}${r?` (${r})`:""}`:null}function On(t,e,n,r,s){return e>t.length||t.length>n?`${r} requires ${e}-${n} arguments${s?` (${s})`:""}`:null}function $n(t,e,n,r=[]){return{type:t,message:e,suggestions:r,...n&&{path:n}}}const Rn=("undefined"!=typeof process?1:0)||"undefined"!=typeof process&&"true"===process.env.HYPERFIXI_SKIP_VALIDATION||"undefined"!=typeof globalThis&&"true"===globalThis.HYPERFIXI_SKIP_VALIDATION;let Ln;function In(){return Ln({validate:t=>({success:1,data:t})})}function jn(t,e){if(Rn)return In();const n=Ln({validate:n=>{if("object"!=typeof n||null===n||Array.isArray(n))return{success:0,error:$n("type-mismatch","Expected object, received "+typeof n)};const r=n,s={};if(e?.strict){const e=Object.keys(t),n=Object.keys(r).filter(t=>!e.includes(t));if(n.length>0)return{success:0,error:$n("runtime-error","Unexpected properties: "+n.join(", "))}}for(const[e,n]of Object.entries(t)){const t=r[e];if(!(e in r)&&!n.t)return{success:0,error:$n("missing-argument",`Required field "${e}" is missing`,e)};const i=n.validate(t);if(!i.success)return{success:0,error:$n("validation-error",i.error.message||`Field "${e}" validation failed`,i.error.path?`${e}.${i.error.path}`:e)};void 0!==i.data&&(s[e]=i.data)}return{success:1,data:s}}});return n.strict=()=>jn(t,{strict:1}),n}Ln=function(t){return t.describe||(t.describe=function(t){return this.description=t,this}),t.safeParse||(t.safeParse=function(t){const e=this.validate(t);return e.success?{success:1,data:e.data}:{success:0,error:{errors:e.error?[e.error]:[]}}}),t.parse||(t.parse=function(t){const e=this.validate(t);if(e.success&&void 0!==e.data)return e.data;throw Error(e.error?.message||"Validation failed")}),t.optional||(t.optional=function(){const t=this.validate.bind(this),e={...this,t:1,validate:e=>null==e?{success:1,data:void 0}:t(e)};return Ln(e)}),t.min||(t.min=function(t){const e=this.validate.bind(this),n={...this,validate:n=>{const r=e(n);return r.success&&"string"==typeof r.data&&t>r.data.length?{success:0,error:$n("runtime-error",`String must be at least ${t} characters long`)}:r}};return Ln(n)}),t.max||(t.max=function(t){const e=this.validate.bind(this),n={...this,validate:n=>{const r=e(n);return r.success&&"string"==typeof r.data&&r.data.length>t?{success:0,error:$n("runtime-error",`String must be at most ${t} characters long`)}:r}};return Ln(n)}),t.default||(t.default=function(t){const e=this.validate.bind(this),n={...this,i:t,o:1,validate:n=>void 0===n?{success:1,data:t}:e(n)};return Ln(n)}),t.rest||(t.rest=function(t){return this}),t.refine||(t.refine=function(t,e){const n=this.validate.bind(this),r={...this,validate:r=>{const s=n(r);return s.success?t(s.data)?s:{success:0,error:$n("runtime-error",e||"Refinement validation failed")}:s}};return Ln(r)}),new Proxy(t,{get:(t,e,n)=>e in t||"string"!=typeof e||e.startsWith("_")||"constructor"===e||"validate"===e||"then"===e?Reflect.get(t,e,n):function(...t){return n}})};const Mn=t=>function(t={}){return Rn?In():Ln({validate:e=>t.optional&&null==e?{success:1,data:void 0}:"string"!=typeof e?{success:0,error:$n("type-mismatch","Expected string, received "+typeof e)}:void 0!==t.minLength&&t.minLength>e.length?{success:0,error:$n("runtime-error",`String must be at least ${t.minLength} characters long`)}:void 0!==t.maxLength&&e.length>t.maxLength?{success:0,error:$n("runtime-error",`String must be at most ${t.maxLength} characters long`)}:t.pattern&&!t.pattern.test(e)?t.pattern.source.startsWith("^")&&t.pattern.source.endsWith("$")?{success:0,error:$n("runtime-error",`Expected "${t.pattern.source.slice(1,-1)}", received "${e}"`)}:{success:0,error:$n("missing-argument","String does not match required pattern")}:{success:1,data:e},...t.description&&{description:t.description}})}(t||{}),Dn=t=>function(t={}){return Rn?In():Ln({validate:e=>{const n=Number(e);return isNaN(n)?{success:0,error:$n("type-mismatch","Expected number, received "+typeof e)}:void 0!==t.min&&t.min>n?{success:0,error:$n("runtime-error","Number must be at least "+t.min)}:void 0!==t.max&&n>t.max?{success:0,error:$n("runtime-error","Number must be at most "+t.max)}:{success:1,data:n}}})}(t||{}),Pn=()=>Rn?In():Ln({validate:t=>"boolean"!=typeof t?{success:0,error:$n("type-mismatch","Expected boolean, received "+typeof t)}:{success:1,data:t}}),Fn=t=>jn(t),Bn=t=>function(t){return Rn?In():Ln({validate:e=>{if(!Array.isArray(e))return{success:0,error:$n("type-mismatch","Expected array, received "+typeof e)};if(e.length!==t.length)return{success:0,error:$n("runtime-error",`Expected tuple of length ${t.length}, received length ${e.length}`)};const n=[];for(let r=0;t.length>r;r++){const s=t[r].validate(e[r]);if(!s.success)return{success:0,error:$n("runtime-error",s.error.message,s.error.path?`${r}.${s.error.path}`:""+r)};n.push(s.data)}return{success:1,data:n}}})}(t),_n=()=>In(),Vn=()=>In(),qn=()=>function(t,e="Custom validation failed"){return Rn?In():Ln({validate:n=>t(n)?{success:1,data:n}:{success:0,error:$n("runtime-error",e)}})}(t=>void 0===t,"Expected undefined");class Hn{trackPerformance(t,e,n,r){t.evaluationHistory&&t.evaluationHistory.push({expressionName:this.name,category:this.category,input:e,output:n.success?n.value:n.error,timestamp:r,duration:Date.now()-r,success:n.success})}trackSimple(t,e,n,r=(n?"success":"error")){t.evaluationHistory&&t.evaluationHistory.push({expressionName:this.name,category:this.category,input:"operation",output:r,timestamp:e,duration:Date.now()-e,success:n})}toBoolean(t){return 0==t||0===t||0n===t||""===t||null==t||hn(t)&&isNaN(t)?0:1}success(t,e){return{success:1,value:t,type:e}}failure(t,e,n,r,s=[]){return{success:0,error:{name:t,type:e,message:n,code:r,suggestions:s}}}validationSuccess(){return{isValid:1,errors:[],suggestions:[]}}validationFailure(t,e,n=[]){return{isValid:0,errors:[{type:t,message:e,suggestions:n}],suggestions:n}}isElement(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"tagName"in t&&"string"==typeof t.tagName}inferType(t){return null===t?"null":void 0===t?"undefined":this.isElement(t)?"element":Array.isArray(t)?"array":dn(t)?"object":typeof t}inferEvaluationType(t){return void 0===t?"Undefined":null===t?"Null":un(t)?"String":hn(t)?"Number":fn(t)?"Boolean":Array.isArray(t)?"Array":this.isElement(t)?"Element":"Object"}normalizeCollection(t){return Array.isArray(t)?t:t instanceof NodeList?Array.from(t):un(t)?t.split(""):null==t?[]:dn(t)&&Symbol.iterator in t?Array.from(t):[]}toNumber(t){if(hn(t)&&Number.isFinite(t))return t;if(un(t)){const e=Number(t);return Number.isFinite(e)?e:null}return fn(t)?t?1:0:null}}function Un(t,e,n,r,s="runtime-error"){return{success:0,error:{name:t+"ConversionError",type:s,message:n,code:e,suggestions:r}}}function Wn(t,e){return{success:1,value:t,type:e}}function zn(t,e){return`${t}: ${e instanceof Error?e.message:e+""}`}const Jn={Array:(t,e)=>{try{return Array.isArray(t)?Wn(t,"array"):t instanceof NodeList?Wn(Array.from(t),"array"):Wn(null==t?[]:[t],"array")}catch(t){return Un("Array","ARRAY_CONVERSION_FAILED",zn("Failed to convert value to Array",t),["Check if value is iterable","Ensure value is not circular reference"])}},String:(t,e)=>{try{return null==t?Wn("","string"):un(t)?Wn(t,"string"):dn(t)?Wn(JSON.stringify(t),"string"):Wn(t+"","string")}catch(t){return Un("String","STRING_CONVERSION_FAILED",zn("Failed to convert value to String",t),["Check if object has circular references","Ensure value is serializable"])}},Boolean:(t,e)=>{try{if(fn(t))return Wn(t,"boolean");if(null==t)return Wn(0,"boolean");if(un(t)){const e=t.toLowerCase().trim();return Wn("false"!==e&&"0"!==e&&""!==e,"boolean")}return hn(t)?Wn(0!==t&&!isNaN(t),"boolean"):Wn(!!t,"boolean")}catch(t){return Un("Boolean","BOOLEAN_CONVERSION_FAILED",zn("Failed to convert value to Boolean",t),["Use explicit true/false values","Check for unexpected data types"])}},Number:(t,e)=>{try{if(hn(t))return Wn(t,"number");if(null==t)return Wn(0,"number");const e=Number(t);return isNaN(e)?Un("Number","INVALID_NUMBER",`Cannot convert "${t}" to a valid number`,["Check if value contains non-numeric characters","Use a valid numeric format"],"invalid-argument"):Wn(e,"number")}catch(t){return Un("Number","NUMBER_CONVERSION_FAILED",zn("Failed to convert value to Number",t),["Ensure value is convertible to number","Check for special characters"])}},Int:(t,e)=>{const n=Jn.Number(t,e);return n.success?Wn(Math.trunc(n.value),"number"):n},Float:(t,e)=>{const n=Jn.Number(t,e);return n.success?Wn(parseFloat(""+n.value),"number"):n},Date:(t,e)=>{try{if(t instanceof Date)return Wn(t,"object");if(null==t)return Wn(new Date(""),"object");if(un(t)&&/^\d{4}-\d{2}-\d{2}$/.test(t)){const[e,n,r]=t.split("-").map(Number);return Wn(new Date(e,n-1,r),"object")}const e=new Date(t);return isNaN(e.getTime())?Un("Date","INVALID_DATE",`Cannot convert "${t}" to a valid date`,["Use ISO 8601 format (YYYY-MM-DD)","Check date string format","Ensure date values are valid"],"invalid-argument"):Wn(e,"object")}catch(t){return Un("Date","DATE_CONVERSION_FAILED",zn("Failed to convert value to Date",t),["Check date format","Ensure value is a valid date string or timestamp"])}},JSON:(t,e)=>{if(!un(t))return Wn(t,"object");try{return Wn(JSON.parse(t),"object")}catch(t){return Un("JSON","JSON_PARSE_FAILED",zn("Failed to parse value as JSON",t),["Check JSON syntax and escaping","Use `as JSONString` to stringify a value instead"],"syntax-error")}},JSONString:(t,e)=>{try{return Wn(JSON.stringify(t),"string")}catch(t){return Un("JSONString","JSON_STRINGIFY_FAILED",zn("Failed to stringify value as JSON",t),["Check for circular references","Ensure all properties are serializable","Remove functions and undefined values"])}},Object:(t,e)=>{try{if(dn(t))return Wn(t,"object");if(un(t))try{return Wn(JSON.parse(t),"object")}catch(t){return Un("Object","JSON_PARSE_FAILED",zn("Cannot parse JSON string",t),["Check JSON syntax","Ensure proper escaping of quotes","Validate JSON format"],"syntax-error")}return Wn({},"object")}catch(t){return Un("Object","OBJECT_CONVERSION_FAILED",zn("Failed to convert value to Object",t),["Ensure value is valid JSON string or object","Check for syntax errors"])}},Values:(t,e)=>{try{if(t instanceof HTMLFormElement)return Wn(Kn(t),"object");if(t instanceof HTMLElement){const e=t.querySelectorAll("input, select, textarea"),n={};return e.forEach(t=>{const e=t;if(e.name){const t=Qn(e);void 0!==t&&(n[e.name]=t)}}),Wn(n,"object")}return Wn({},"object")}catch(t){return Un("FormValues","FORM_VALUES_EXTRACTION_FAILED",zn("Failed to extract form values",t),["Ensure element is a form or contains form inputs","Check form structure","Verify input names are set"])}},FormEncoded:(t,e)=>{try{let n=t;if(t instanceof HTMLElement){const r=Jn.Values(t,e);if(!r.success)return r;n=r.value}if(!dn(n))return Wn("","string");const r=new URLSearchParams;for(const[t,e]of Object.entries(n))if(null!=e)if(Array.isArray(e))for(const n of e)r.append(t,n+"");else r.append(t,e+"");return Wn(""+r,"string")}catch(t){return Un("FormEncoded","FORM_ENCODE_FAILED",zn("Failed to URL-encode values",t),["Ensure input is a form element or plain object of scalar/array values"])}},Set:(t,e)=>{try{return Wn(new Set(t),"object")}catch(t){return Un("Set","SET_CONVERSION_FAILED",zn("Failed to convert to Set",t),["Ensure the value is iterable"])}},Map:(t,e)=>{try{return Wn(new Map(Object.entries(t??{})),"object")}catch(t){return Un("Map","MAP_CONVERSION_FAILED",zn("Failed to convert to Map",t),["Ensure the value is a plain object"])}},Keys:(t,e)=>t instanceof Map?Wn(Array.from(t.keys()),"array"):Wn(Object.keys(t??{}),"array"),Entries:(t,e)=>t instanceof Map?Wn(Array.from(t.entries()),"array"):Wn(Object.entries(t??{}),"array"),Reversed:(t,e)=>{try{return Wn(Array.from(t).reverse(),"array")}catch(t){return Un("Reversed","REVERSED_CONVERSION_FAILED",zn("Failed to reverse value",t),["Ensure the value is array-like"])}},Unique:(t,e)=>{try{return Wn([...new Set(t)],"array")}catch(t){return Un("Unique","UNIQUE_CONVERSION_FAILED",zn("Failed to dedupe value",t),["Ensure the value is iterable"])}},Flat:(t,e)=>{try{return Wn(Array.from(t).flat(),"array")}catch(t){return Un("Flat","FLAT_CONVERSION_FAILED",zn("Failed to flatten value",t),["Ensure the value is array-like"])}}},Zn=Fn({value:Vn(),type:Mn().min(1)}),Gn=Fn({value:Vn(),type:Mn().min(1)});new class extends Hn{constructor(){super(...arguments),this.name="as",this.category="Conversion",this.syntax="value as Type",this.description='Converts values between different types using the "as" keyword',this.outputType="Any",this.inputSchema=Zn,this.metadata={category:"Conversion",complexity:"medium",sideEffects:[],dependencies:[],returnTypes:["Any"],examples:[{input:'"123" as Int',description:"Convert string to integer",expectedOutput:123},{input:"form as Values",description:"Extract form values as object",expectedOutput:{name:"John",age:"25"}},{input:"[1,2,3] as JSONString",description:"Convert array to JSON string (upstream 0.9.90: use JSONString, not JSON)",expectedOutput:"[1,2,3]"},{input:"'{\"a\":1}' as JSON",description:"Parse a JSON string (upstream 0.9.90: as JSON now parses)",expectedOutput:{a:1}},{input:'"2023-12-25" as Date',description:"Parse date string",expectedOutput:new Date(2023,11,25)}],relatedExpressions:["is","Object","Array"],performance:{averageTime:1,complexity:"O(n)"}},this.documentation={summary:'Converts values between different types using the "as" keyword with comprehensive type safety',parameters:[{name:"value",type:"object",description:"The value to convert",optional:0,examples:['"123"',"form","[1,2,3]","true","null"]},{name:"type",type:"string",description:"Target conversion type",optional:0,examples:["Int","String","Boolean","Array","JSON","Object","Date","Values","HTML","Fragment"]}],returns:{type:"object",description:"Structured result with converted value or detailed error information",examples:['{ success: true, value: 123, type: "number" }',"{ success: false, error: { ... } }"]},examples:[{title:"String to number conversion",code:"if my.value as Int > 100",explanation:"Convert form input to integer for comparison",output:"Boolean result"},{title:"Form data extraction",code:"put closest <form /> as Values into result",explanation:"Extract all form values as structured object",output:'{ name: "John", age: "25", ... }'},{title:"Array to JSON serialization",code:"put items as JSONString into storage",explanation:"Convert array to JSON string for storage (upstream 0.9.90: use `as JSONString`)",output:'"[1,2,3]"'},{title:"Date parsing with validation",code:"put my.dateInput as Date into event.detail.date",explanation:"Parse date input with automatic validation",output:"Date object or validation error"},{title:"Boolean conversion with smart parsing",code:'if "false" as Boolean then hide else show',explanation:"Parse string boolean values correctly",output:"false (not true like naive conversion)"}],seeAlso:["is","Values","JSON","Array","Object"],tags:["conversion","types","validation","forms","json","parsing"]}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:{name:"AsExpressionValidationError",type:"validation-error",message:r.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:r.suggestions}};const{value:s,type:i}=e;if(i.startsWith("Fixed")){const r=i.match(/^Fixed:(\d+)$/),o=r?parseInt(r[1],10):0,a=Jn.Number(s,t);if(!a.success)return a;const c={success:1,value:a.value.toFixed(o),type:"string"};return this.trackPerformance(t,e,c,n),c}let o=Jn[i];if(o){const r=o(s,t);return this.trackPerformance(t,e,r,n),r}const a={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON",jsonstring:"JSONString",formencoded:"FormEncoded"}[i.toLowerCase()];if(a&&(o=Jn[a],o)){const r=o(s,t);return this.trackPerformance(t,e,r,n),r}const c={success:0,error:{name:"UnknownConversionTypeError",type:"validation-error",message:"Unknown conversion type: "+i,code:"UNKNOWN_CONVERSION_TYPE",suggestions:["Use supported types: String, Number, Boolean, Array, Object, Date, JSON, Values","Check type spelling and capitalization","See documentation for complete list of conversion types"]}};return this.trackPerformance(t,e,c,n),c}catch(r){const s={success:0,error:{name:"AsExpressionError",type:"runtime-error",message:"Conversion failed: "+(r instanceof Error?r.message:r+""),code:"CONVERSION_FAILED",suggestions:["Check value and type compatibility","Ensure value is convertible to target type"]}};return this.trackPerformance(t,e,s,n),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?{isValid:1,errors:[],suggestions:[]}:{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:t.message,suggestions:["Expected valid input structure, got: "+t.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(t){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}},new class extends Hn{constructor(){super(...arguments),this.name="is",this.category="Conversion",this.syntax="value is Type",this.description="Checks if a value is of a specific type",this.outputType="Boolean",this.inputSchema=Gn,this.metadata={category:"Conversion",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"42 is number",description:"Check if value is a number",expectedOutput:1},{input:"null is empty",description:"Check if value is empty/null",expectedOutput:1},{input:"element is Element",description:"Check if value is DOM element",expectedOutput:1,context:{element:"<div>...</div>"}}],relatedExpressions:["as","empty","exists"],performance:{averageTime:.1,complexity:"O(1)"}},this.documentation={summary:"Checks if a value is of a specific type with comprehensive type detection",parameters:[{name:"value",type:"object",description:"The value to check",optional:0,examples:["42","null","element",'"text"',"[]"]},{name:"type",type:"string",description:"Type name to check against",optional:0,examples:["number","string","boolean","array","object","element","empty","null"]}],returns:{type:"object",description:"Boolean result indicating type match",examples:['{ success: true, value: true, type: "boolean" }']},examples:[{title:"Number validation",code:"if my.age is number then proceed",explanation:"Check if form input is valid number",output:"Boolean result"},{title:"Empty check",code:"if result is empty then show message",explanation:"Check if result is null, undefined, or empty",output:"Boolean result"},{title:"Element validation",code:"if target is element then addClass",explanation:"Ensure target is valid DOM element before manipulation",output:"Boolean result"}],seeAlso:["as","empty","exists","null"],tags:["validation","types","checking","guards"]}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:{name:"IsExpressionValidationError",type:"validation-error",message:r.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:r.suggestions}};const{value:s,type:i}=e,o=i.toLowerCase();let a;switch(o){case"null":a=null===s;break;case"undefined":a=void 0===s;break;case"string":a=un(s);break;case"number":a=hn(s)&&!isNaN(s);break;case"boolean":a=fn(s);break;case"object":a=dn(s);break;case"array":a=Array.isArray(s);break;case"function":a=pn(s);break;case"date":a=s instanceof Date;break;case"element":a=s instanceof Element;break;case"node":a=s instanceof Node;break;case"node-list":a=s instanceof NodeList;break;case"empty":a=null==s||""===s||Array.isArray(s)&&0===s.length||dn(s)&&0===Object.keys(s).length;break;default:a=s?.constructor?.name?.toLowerCase()===o}const c=this.success(a,"boolean");return this.trackPerformance(t,e,c,n),c}catch(r){const s=this.failure("IsExpressionError","type-mismatch","Type check failed: "+(r instanceof Error?r.message:r+""),"TYPE_CHECK_FAILED",["Check type name spelling","Ensure value is accessible"]);return this.trackPerformance(t,e,s,n),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:t.message,suggestions:["Expected valid input structure, got: "+t.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(t){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}};const Xn={conversions:{dynamicResolvers:[]}},Yn={Array:t=>Array.isArray(t)?t:t instanceof NodeList?Array.from(t):null==t?[]:[t],String:t=>null==t?"":un(t)?t:dn(t)?JSON.stringify(t):t+"",Boolean:t=>{if(fn(t))return t;if(null==t)return 0;if(un(t)){const e=t.toLowerCase().trim();return"false"===e||"0"===e||""===e?0:1}return hn(t)?0!==t&&!isNaN(t):!!t},Number:t=>{if(hn(t))return t;if(null==t)return 0;const e=Number(t);return isNaN(e)?0:e},Math:t=>{if(hn(t))return t;if(null==t)return 0;const e=(t+"").trim();if(!e)return 0;try{return function(t){if(t=t.replace(/\s/g,""),!/^[0-9+\-*/().]+$/.test(t))throw Error("Invalid characters in math expression");try{const e=Function(`"use strict"; return (${t})`)();if(!hn(e)||!isFinite(e))throw Error("Expression did not evaluate to a finite number");return e}catch(t){throw Error("Math expression evaluation failed: "+(t instanceof Error?t.message:t+""))}}(e)}catch(t){return console.warn("Math conversion failed:",t),0}},Int:t=>{const e=Yn.Number(t);return Math.trunc(e)},Float:t=>{const e=Yn.Number(t);return parseFloat(""+e)},Date:t=>{if(t instanceof Date)return t;if(null==t)return new Date(NaN);if(un(t)&&/^\d{4}-\d{2}-\d{2}$/.test(t)){const[e,n,r]=t.split("-").map(Number);return new Date(e,n-1,r)}return new Date(t)},JSON:t=>{if(!un(t))return t;try{return JSON.parse(t)}catch{return t}},JSONString:t=>{try{return JSON.stringify(t)}catch{return"{}"}},Object:t=>{if(dn(t))return t;if(un(t))try{return JSON.parse(t)}catch(t){return{}}return{}},Fragment:t=>{const e=document.createDocumentFragment(),n=Array.isArray(t)||t instanceof NodeList?Array.from(t):[t];for(const t of n)if(t instanceof Node)e.append(t);else{const n=document.createElement("template");n.innerHTML=null==t?"":t+"",e.append(n.content)}return e},HTML:t=>un(t)?t:t instanceof NodeList?Array.from(t).map(t=>t instanceof Element?t.outerHTML:t.textContent||"").join(""):Array.isArray(t)?t.map(t=>t instanceof Element?t.outerHTML:Yn.String(t)).join(""):t instanceof Element?t.outerHTML:Yn.String(t),Values:(t,e)=>{if(t instanceof HTMLFormElement)return Kn(t);if(t instanceof HTMLElement){const e=t.querySelectorAll("input, select, textarea"),n={};return e.forEach(t=>{t.name&&(n[t.name]=Qn(t))}),n}return{}},FormEncoded:(t,e)=>{const n=t instanceof HTMLElement?Yn.Values(t,e):t;if(!dn(n))return"";const r=new URLSearchParams;for(const[t,e]of Object.entries(n))if(null!=e)if(Array.isArray(e))for(const n of e)r.append(t,n+"");else r.append(t,e+"");return""+r},Set:t=>new Set(t),Map:t=>new Map(Object.entries(t??{})),Keys:t=>t instanceof Map?Array.from(t.keys()):Object.keys(t??{}),Entries:t=>t instanceof Map?Array.from(t.entries()):Object.entries(t??{}),Reversed:t=>Array.from(t).reverse(),Unique:t=>[...new Set(t)],Flat:t=>Array.from(t).flat(),"Values:Form":(t,e)=>{const n=Yn.Values(t,e);return Yn.FormEncoded(n,e)},"Values:JSON":(t,e)=>{const n=Yn.Values(t,e);return JSON.stringify(n)}};function Kn(t){const e={};return t.querySelectorAll("input, select, textarea").forEach(t=>{const n=t;if(n.name){const t=Qn(n);void 0!==t&&(void 0!==e[n.name]?(Array.isArray(e[n.name])||(e[n.name]=[e[n.name]]),e[n.name].push(t)):e[n.name]=t)}}),e}function Qn(t){if(t instanceof HTMLInputElement)switch(t.type){case"checkbox":return t.checked;case"radio":return t.checked?t.value:void 0;case"number":case"range":return t.valueAsNumber;case"date":case"datetime-local":return t.valueAsDate;case"file":return t.files;default:return t.value}return t instanceof HTMLSelectElement&&t.multiple?Array.from(t.selectedOptions).map(t=>t.value):t.value}const tr={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON",jsonstring:"JSONString",formencoded:"FormEncoded"};function er(t,e,n){if("string"!=typeof e)throw Error("Conversion type must be a string");if(e.startsWith("Fixed")){const{precision:n}=function(t){const e=t.match(/^Fixed(?::(\d+))?$/);return e?{precision:e[1]?parseInt(e[1],10):0}:{}}(e);return Yn.Number(t).toFixed(n??0)}if(null==t)return t;let r=Yn[e];if(r)return r(t,n);const s=tr[e.toLowerCase()];if(s&&(r=Yn[s],r))return r(t,n);const i=Xn.conversions[e];if("function"==typeof i)return i(t,n);for(const n of Xn.conversions.dynamicResolvers){const r=n(e,t);if(void 0!==r)return r}return console.warn("Unknown conversion type: "+e),t}const nr={as:{name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(t,...e){const[n,r]=e;return er(n,r,t)},validate:t=>kn(t,2,"as","value, type")??Sn(t,1,"as","conversion type")},is:{name:"is",category:"Conversion",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is a","is an"],async evaluate(t,...e){const[n,r]=e;if(!un(r))throw Error("Type check requires a string type");switch(r.toLowerCase()){case"null":return null===n;case"undefined":return void 0===n;case"string":return un(n);case"number":return hn(n)&&!isNaN(n);case"boolean":return fn(n);case"object":return dn(n);case"array":return Array.isArray(n);case"function":return pn(n);case"date":return n instanceof Date;case"element":return n instanceof Element;case"node":return n instanceof Node;case"nodelist":return n instanceof NodeList;case"empty":return null==n||""===n||Array.isArray(n)&&0===n.length||dn(n)&&0===Object.keys(n).length;default:return n?.constructor?.name?.toLowerCase()===r.toLowerCase()}},validate:t=>kn(t,2,"is","value, type")??Sn(t,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(t,e)=>e,validate:t=>kn(t,1,"async","expression")}},rr=new Set(["__proto__","constructor","prototype"]);function sr(t,e){if(t instanceof Element)return En(t,e);if(dn(t)){if(rr.has(e))return;return t[e]}return t[e]}function ir(t){let e;if(Array.isArray(t))e=t;else{if(!("undefined"!=typeof NodeList&&t instanceof NodeList||"undefined"!=typeof HTMLCollection&&t instanceof HTMLCollection))return 0;e=Array.from(t)}return 0===e.length?0:e.every(t=>t instanceof Element||null!=t&&"object"==typeof t&&t.constructor!==Object&&!Array.isArray(t))}const or={possessive:{name:"possessive",category:"Reference",evaluatesTo:"Any",operators:["'s","s"],async evaluate(t,...e){const[n,r]=e;if(null!=n){if("string"!=typeof r)throw Error("Property name must be a string");return ir(n)&&!(r in n)?Array.from(n,t=>sr(t,r)):sr(n,r)}},validate:t=>kn(t,2,"possessive","element, property")??Sn(t,1,"possessive","property name")},my:{name:"my",category:"Reference",evaluatesTo:"Any",operators:["my"],async evaluate(t,...e){const[n]=e;if(t.me){if("string"!=typeof n)throw Error("Property name must be a string");if(t.me instanceof Element)return En(t.me,n);if(dn(t.me)){if(rr.has(n))return;return t.me[n]}return t.me[n]}},validate:t=>An(t,"my","property")},its:{name:"its",category:"Reference",evaluatesTo:"Any",operators:["its"],async evaluate(t,...e){const[n]=e;if(null==t.it)return;if("string"!=typeof n)throw Error("Property name must be a string");const r=t.it;if(r instanceof Element)return En(r,n);if(dn(r)){if(rr.has(n))return;return r[n]}return r[n]},validate:t=>An(t,"its","property")},your:{name:"your",category:"Reference",evaluatesTo:"Any",operators:["your"],async evaluate(t,...e){const[n]=e;if(t.you){if("string"!=typeof n)throw Error("Property name must be a string");if(t.you instanceof Element)return En(t.you,n);if(dn(t.you)){if(rr.has(n))return;return t.you[n]}return t.you[n]}},validate:t=>An(t,"your","property")},of:{name:"of",category:"Reference",evaluatesTo:"Any",operators:["of"],async evaluate(t,...e){const[n,r]=e;if(null!=r){if("string"!=typeof n)throw Error("Property name must be a string");if(r instanceof Element)return En(r,n);if(dn(r)){if(rr.has(n))return;return r[n]}return r[n]}},validate:t=>kn(t,2,"of","property, object")??Sn(t,0,"of","property name")},attribute:{name:"attribute",category:"Reference",evaluatesTo:"String",operators:["@"],async evaluate(t,...e){const[n,r]=e;if("string"!=typeof n)throw Error("Attribute name must be a string");const s=r||t.me;return s&&s instanceof Element?s.getAttribute(n):null},validate:t=>On(t,1,2,"attribute","attributeName, optional element")??Sn(t,0,"attribute","attribute name")??(2>t.length||null==t[1]||t[1]instanceof Element?null:"attribute element must be an Element")},attributeWithValue:{name:"attributeWithValue",category:"Reference",evaluatesTo:"Boolean",operators:["@="],async evaluate(t,...e){const[n,r,s]=e;if("string"!=typeof n)throw Error("Attribute name must be a string");if("string"!=typeof r)throw Error("Expected value must be a string");const i=s||t.me;return i&&i instanceof Element?i.getAttribute(n)===r:0},validate:t=>On(t,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??Sn(t,0,"attributeWithValue","attribute name")??Sn(t,1,"attributeWithValue","expected value")??(3>t.length||null==t[2]||t[2]instanceof Element?null:"attributeWithValue element must be an Element")},classReference:{name:"classReference",category:"Reference",evaluatesTo:"Array",operators:["."],async evaluate(t,...e){const[n]=e;if("string"!=typeof n)throw Error("Class name must be a string");const r=n.startsWith(".")?n.slice(1):n,s=document.getElementsByClassName(r);return Array.from(s)},validate:t=>An(t,"classReference","className")},idReference:{name:"idReference",category:"Reference",evaluatesTo:"Element",operators:["#"],async evaluate(t,...e){const[n]=e;if("string"!=typeof n)throw Error("ID value must be a string");const r=n.startsWith("#")?n.slice(1):n;return document.getElementById(r)},validate:t=>An(t,"idReference","idValue")}};function ar(t){return Array.isArray(t)?t:null==t?[]:"string"==typeof t?[t]:t instanceof NodeList||t instanceof HTMLCollection||"number"==typeof t.length?Array.from(t):[t]}function cr(t,e){const n=t.registry?.get(e);if(!n)throw Error(`Expression '${e}' not in ExecutionContext.registry. The bundle's ExpressionRegistry must include this expression's category. Use createExpressionRegistry() with the relevant category objects (referencesExpressions, logicalExpressions, conversionExpressions, positionalExpressions, propertiesExpressions, specialExpressions, mathematicalExpressions).`);return n}function lr(t){if(t&&"object"==typeof t&&"success"in t){if(t.success)return"value"in t?t.value:void 0;const e=t.errors||[];throw Error(e.length>0?e[0].message:"Expression evaluation failed")}return t}async function ur(t,e){if(!t)throw Error("Cannot evaluate null or undefined AST node");if("literal"===t.type)return t.value;if("identifier"===t.type)return gr(t,e);const n=t;switch(t.type){case"literal":return function(t){return t.value}(n);case"identifier":return gr(n,e);case"binaryExpression":return async function(t,e){const n=t.operator,r=t.right,s=t.left;if("="===n){const n=await ur(t.right,e);if("identifier"===s?.type&&"string"==typeof s.name){const t=s.name;return t.startsWith("$")?It(e,t.slice(1),n):"global"===s.scope?It(e,t,n):"element"===s.scope?nn(e,t,n):(e.locals||(e.locals=new Map),e.locals.set(t,n)),n}throw Error(`Assignment target must be a variable identifier (got '${s?.type??"undefined"}')`)}if("has"===n||"have"===n){const n=await ur(t.left,e);return n instanceof Element&&"selector"===r.type&&"string"==typeof r.value&&r.value.startsWith(".")?n.classList.contains(r.value.slice(1)):0}if("in"===n||"is in"===n){const n="callExpression"===s?.type&&"identifier"===s.callee?.type?s.callee.name:null;if(("first"===n||"last"===n)&&Array.isArray(s.arguments)){const r=s.arguments[0];if("selector"===r?.type&&"string"==typeof r.value){const s=await ur(t.right,e);if(s&&"function"==typeof s.querySelectorAll){const t=Array.from(s.querySelectorAll(r.value));return 0===t.length?null:"first"===n?t[0]:t[t.length-1]}}}if("selector"===s?.type&&s.fromQuery&&"string"==typeof s.value){const n=await ur(t.right,e),r=n&&"function"==typeof n.querySelectorAll?n:null;if(r)return Array.from(r.querySelectorAll(s.value))}}if("of"===n&&"selector"===s?.type&&"string"==typeof s.value&&/^\*[a-zA-Z][\w-]*$/.test(s.value)){const n=await ur(t.right,e);return cr(e,"styleRef").evaluate(e,s.value.slice(1),n)}if("of"===n){const n=vr(t.left);if(n){const r=await ur(t.right,e);let s=r;for(const t of n){if(null==s)return;s=yn(s)?En(s,t):s[t]}return"function"==typeof s?s.bind(r):s}}const i=await ur(t.left,e);if("and"===n){if(!i)return i;const n=await ur(t.right,e);return cr(e,"and").evaluate(e,i,n)}if("or"===n){if(i)return i;const n=await ur(t.right,e);return cr(e,"or").evaluate(e,i,n)}const o=await ur(t.right,e),a=t=>"string"==typeof t?t.toLowerCase():t,c=t.ignoringCase?a(i):i,l=t.ignoringCase?a(o):o;switch(n){case"+":{let n=i,r=o;return t.coerceNumeric&&("string"==typeof n&&(n=an(n)),"string"==typeof r&&(r=an(r))),"string"==typeof n||"string"==typeof r?(n??"")+""+(r??""):Array.isArray(n)?Array.isArray(r)?[...n,...r]:[...n,r]:lr(await cr(e,"addition").evaluate(e,{left:n,right:r}))}case"-":return lr(await cr(e,"subtraction").evaluate(e,{left:i,right:o}));case"*":return lr(await cr(e,"multiplication").evaluate(e,{left:i,right:o}));case"/":return lr(await cr(e,"division").evaluate(e,{left:i,right:o}));case"%":case"mod":return lr(await cr(e,"modulo").evaluate(e,{left:i,right:o}));case"^":case"**":return lr(await cr(e,"power").evaluate(e,{left:i,right:o}));case">":case"is greater than":return cr(e,"greaterThan").evaluate(e,i,o);case"<":case"is less than":return cr(e,"lessThan").evaluate(e,i,o);case">=":case"is greater than or equal to":return cr(e,"greaterThanOrEqual").evaluate(e,i,o);case"<=":case"is less than or equal to":return cr(e,"lessThanOrEqual").evaluate(e,i,o);case"==":return cr(e,"equals").evaluate(e,c,l);case"is":case"am":case"equals":case"is equal":case"is equal to":{const n=Er(t,i,o);return void 0!==n?n:cr(e,"equals").evaluate(e,c,l)}case"!=":return cr(e,"notEquals").evaluate(e,c,l);case"is not":case"is not equal":case"is not equal to":{const n=Er(t,i,o);return void 0!==n?!n:cr(e,"notEquals").evaluate(e,c,l)}case"===":case"really equals":case"is really":case"is really equal to":return cr(e,"strictEquals").evaluate(e,c,l);case"!==":case"is not really":case"is not really equal to":return cr(e,"strictNotEquals").evaluate(e,c,l);case"as":return cr(e,"as").evaluate(e,i,kr(o));case"contains":case"contain":case"includes":case"include":return cr(e,"contains").evaluate(e,c,l);case"does not contain":case"do not contain":case"does not contains":case"does not include":return cr(e,"doesNotContain").evaluate(e,c,l);case"starts with":return cr(e,"startsWith").evaluate(e,c,l);case"ends with":return cr(e,"endsWith").evaluate(e,c,l);case"does not start with":return!await cr(e,"startsWith").evaluate(e,c,l);case"does not end with":return!await cr(e,"endsWith").evaluate(e,c,l);case"match":case"matches":return cr(e,"matches").evaluate(e,c,wr(t.right,l));case"does not match":case"do not match":return!await cr(e,"matches").evaluate(e,c,wr(t.right,l));case"in":case"is in":case"am in":return br(i,o);case"is not in":case"am not in":return!br(i,o);case"of":return o&&"object"==typeof o?o[i]:void 0;case"precedes":return xr(i,o,Node.DOCUMENT_POSITION_FOLLOWING);case"does not precede":return!xr(i,o,Node.DOCUMENT_POSITION_FOLLOWING);case"follows":return xr(i,o,Node.DOCUMENT_POSITION_PRECEDING);case"does not follow":return!xr(i,o,Node.DOCUMENT_POSITION_PRECEDING);default:throw Error("Unknown binary operator: "+n)}}(n,e);case"asExpression":return async function(t,e){const n=await ur(t.expression,e),r=kr(t.targetType);return cr(e,"as").evaluate(e,n,r)}(n,e);case"betweenExpression":return async function(t,e){const n=await ur(t.value,e),r=await ur(t.min,e),s=await ur(t.max,e),i=t=>"string"==typeof t?t.toLowerCase():t,[o,a,c]=t.ignoringCase?[i(n),i(r),i(s)]:[n,r,s],l=await cr(e,"between").evaluate(e,o,a,c);return t.negated?!l:l}(n,e);case"typeCheckExpression":return async function(t,e){const n=function(t,e,n){if(null==t&&n)return 1;if(Object.prototype.toString.call(t).slice(8,-1)===e)return 1;const r=globalThis[e];return"function"==typeof r&&t instanceof r}(await ur(t.value,e),t.typeName+"",0!=t.nullOk);return t.negated?!n:n}(n,e);case"collectionExpression":return async function(t,e){const n=await ur(t.collection,e);if(null==n)return n;const r=async(t,n)=>ur(t,{...e,it:n});switch(t.operator){case"where":return async function(t,e,n){const r=ar(t),s=[];for(const t of r)await n(e,t)&&s.push(t);return s}(n,t.right,r);case"sorted by":return async function(t,e,n,r){const s=[...ar(t)],i=await Promise.all(s.map(t=>r(e,t))),o=s.map((t,e)=>e);o.sort((t,e)=>{const n=i[t],r=i[e];return n===r?0:null==n?1:null==r||r>n?-1:1});const a=o.map(t=>s[t]);return"desc"===n?a.reverse():a}(n,t.right,t.order??"asc",r);case"mapped to":return async function(t,e,n){const r=ar(t);return Promise.all(r.map(t=>n(e,t)))}(n,t.right,r);case"split by":return i=await ur(t.right,e),null==(s=n)?[]:(s+"").split(null==i?"":i+"");case"joined by":return function(t,e){const n=null==e?"":e+"";return ar(t).map(t=>null==t?"":t+"").join(n)}(n,await ur(t.right,e));default:throw Error("Unknown collection operator: "+t.operator)}var s,i}(n,e);case"unaryExpression":return async function(t,e){const n=t.operand??t.argument;if(!n)throw Error(`Unary expression has no operand (operator: ${t.operator})`);const r=await ur(n,e);switch(t.operator){case"not":case"!":return cr(e,"not").evaluate(e,r);case"no":return cr(e,"no").evaluate(e,r);case"-":return-r;case"+":return+r;case"exists":case"some":return cr(e,"exists").evaluate(e,r);case"does not exist":return cr(e,"doesNotExist").evaluate(e,r);case"is empty":return cr(e,"isEmpty").evaluate(e,r);case"is not empty":return cr(e,"isNotEmpty").evaluate(e,r);default:throw Error("Unknown unary operator: "+t.operator)}}(n,e);case"memberExpression":return async function(t,e){const n=await ur(t.object,e);if(t.computed){const r=await ur(t.property,e);return Array.isArray(n)&&"number"==typeof r&&0>r?n[n.length+r]:n?.[r]}return Cr(n,t.property.name,e)}(n,e);case"propertyAccess":return async function(t,e){let n=await ur(t.object,e);for(const r of(t.property+"").split(".")){if(null==n)return;n=await Cr(n,r,e)}return n}(n,e);case"callExpression":return async function(t,e){const n=await ur(t.callee,e);if(t.isConstructor&&"function"==typeof n)return new n(...await Promise.all(t.arguments.map(t=>ur(t,e))));if("identifier"===t.callee.type){const r=t.callee.name,s=await async function(t,e,n){return Tr.has(e)?Promise.all(t.map(t=>"identifier"===t.type&&t.name?t.name:"selector"===t.type&&t.value?t.value:ur(t,n))):Promise.all(t.map(t=>ur(t,n)))}(t.arguments,r,e);switch(r){case"closest":return cr(e,"closest").evaluate(e,...s);case"previous":case"next":{const n=t.relativePositional;if(n){const t=n.from?Or(await ur(n.from,e)):e.me,i=n.within?Or(await ur(n.within,e)):void 0,o=n.inElt?await ur(n.inElt,e):void 0;return cr(e,r).evaluate(e,s[0],t,{within:i,inElt:o,inSearch:n.inSearch,wrapping:n.wrapping})}return cr(e,r).evaluate(e,...s)}case"first":return cr(e,"first").evaluate(e,...s);case"last":return cr(e,"last").evaluate(e,...s);default:if("function"==typeof n)return n(...s);throw Error("Cannot call non-function: "+r)}}if("function"==typeof n){const r=await Promise.all(t.arguments.map(t=>ur(t,e)));if("memberExpression"===t.callee.type&&t.callee.object){const s=await ur(t.callee.object,e);return n.apply(s,r)}return n(...r)}throw Error("Cannot call non-function")}(n,e);case"selector":return async function(t,e){let n=t.value;if("string"==typeof n&&!t.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(n))return cr(e,"styleRef").evaluate(e,n.slice(1));if("string"==typeof n&&t.fromQuery&&/\$[^=]/.test(n)){const{selector:r,elements:s}=await async function(t,e){const n=jr(t),r=await Promise.all(n.filter(t=>"expr"in t).map(t=>pr(t.expr,e)));return Mr(n,r)}(n,e),i=Lr(t,r);s.forEach((t,e)=>t.setAttribute("data-hs-query-id",e+""));try{return await cr(e,"elementWithSelector").evaluate(e,i)}finally{s.forEach(t=>t.removeAttribute("data-hs-query-id"))}}"string"==typeof n&&!t.fromQuery&&n.includes("{")&&(n=await function(t,e){return Nr(t,/\{([^}]*)\}/g,async(t,n)=>(await pr(n.trim(),e)??"")+"")}(n,e));const r="string"==typeof n?Lr(t,n):n,s=await cr(e,"elementWithSelector").evaluate(e,r);return!t.fromQuery&&"string"==typeof n&&n.startsWith("#")&&Array.isArray(s)?s[0]??null:s}(n,e);case"contextReference":return async function(t,e){switch(t.contextType){case"me":case"you":case"it":return cr(e,t.contextType).evaluate(e);case"my":case"myself":case"I":return cr(e,"me").evaluate(e);case"your":case"yourself":return cr(e,"you").evaluate(e);case"its":return cr(e,"it").evaluate(e);case"event":return e.event;case"target":return e.target??e.event?.target??cr(e,"me").evaluate(e);case"body":return"undefined"!=typeof document?document.body:void 0;case"document":return cr(e,"document").evaluate(e);case"window":return cr(e,"window").evaluate(e);default:return}}(n,e);case"possessiveExpression":return async function(t,e){const n=await ur(t.object,e),r=t.property.name;return cr(e,"possessive").evaluate(e,n,r)}(n,e);case"eventHandler":return async function(t,e){return{event:t.event,selector:t.selector,commands:t.commands,handler:async n=>{const r={...e,event:n,target:n.target,currentTarget:n.currentTarget};for(const e of t.commands)await ur(e,r)}}}(n,e);case"conditionalExpression":return async function(t,e){return await ur(t.test,e)?ur(t.consequent,e):t.alternate?ur(t.alternate,e):void 0}(n,e);case"string":return n.value;case"arrayLiteral":return async function(t,e){const n=[];for(const r of t.elements)n.push(await ur(r,e));return n}(n,e);case"objectLiteral":return async function(t,e){const n={};for(const r of t.properties){const t=r.key;let s;s="identifier"===t.type?t.name:"literal"===t.type&&"string"===t.valueType?t.value:await ur(t,e)+"",n[s]=await ur(r.value,e)}return n}(n,e);case"attributeAccess":return async function(t,e){const n=t.attributeName;return e.me&&e.me instanceof Element?e.me.getAttribute(n):"@"+n}(n,e);case"propertyOfExpression":return async function(t,e){const n=t.property;if("identifier"!==n?.type)throw Error('Property name must be an identifier in "the X of Y" pattern');const r=n.name,s=await ur(t.target,e);if(null==s)throw Error(`Cannot access property "${r}" of ${s}`);return cr(e,"possessive").evaluate(e,s,r)}(n,e);case"templateLiteral":return async function(t,e){let n=t.value;return n=await Nr(n,/\$([a-zA-Z_$][a-zA-Z0-9_.$]*|\d+)/g,async(t,n)=>{try{if(/^\d+$/.test(n))return n;if(n.includes(".")){const t=n.split(".");let r=Ar(t[0],e);for(let e=1;t.length>e&&null!=r;e++)r=r[t[e]];return(r??"")+""}return(Ar(n,e)??"")+""}catch{return""}}),n=await Nr(n,/\$(?:\{([^}]+)\}|\(([^)]+)\))/g,async(t,n,r)=>{const s=n||r;try{return await pr(s,e)+""}catch{return"undefined"}}),n}(n,e);case"stringPostfix":return async function(t,e){return`${await ur(t.expression,e)}${t.unit}`}(n,e);case"blockLiteral":return Sr(n,e);default:{const n=kt.get(t.type);if(n)return n(t,e);throw Error("Unknown AST node type: "+t.type)}}}class hr extends Error{constructor(t){super(`Expression node "${t}" is not synchronously evaluable`),this.name="NotSyncEvaluable"}}function fr(t,e){const n=t;switch(n?.type){case"literal":case"string":return n.value;case"selector":return function(t,e){const n=t.value;if("string"!=typeof n)throw new hr("selector");if(!t.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(n))throw new hr("selector");if(t.fromQuery&&/\$[^=]/.test(n)){const{selector:r,elements:s}=function(t,e){const n=jr(t),r=n.filter(t=>"expr"in t).map(t=>dr(t.expr,e));return Mr(n,r)}(n,e),i=Lr(t,r),o=e?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!o)throw new hr("selector");s.forEach((t,e)=>t.setAttribute("data-hs-query-id",e+""));try{return Array.from(o.querySelectorAll(i))}finally{s.forEach(t=>t.removeAttribute("data-hs-query-id"))}}const r=!t.fromQuery&&n.includes("{")?function(t,e){return t.replace(/\{([^}]*)\}/g,(t,n)=>(dr(n.trim(),e)??"")+"")}(n,e):n,s=Lr(t,r),i=e?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!i)throw new hr("selector");const o=Array.from(i.querySelectorAll(s));return!t.fromQuery&&r.startsWith("#")?o[0]??null:o}(n,e);case"identifier":return function(t,e,n){return"me"===t||"my"===t||"I"===t?e.me:"you"===t||"your"===t||"yourself"===t?e.you:"it"===t||"its"===t?e.it??e.result:"window"===t?"undefined"!=typeof window?window:globalThis:"document"===t?"undefined"!=typeof document?document:void 0:"element"===n?en(e,t):e.locals?.has(t)?e.locals.get(t):e.globals?.has(t)?e.globals.get(t):t.startsWith("$")&&e.globals?.has(t.slice(1))?e.globals.get(t.slice(1)):void 0!==e[t]?e[t]:"undefined"!=typeof globalThis&&t in globalThis?globalThis[t]:void 0}(n.name,e,n.scope);case"contextReference":return function(t,e){switch(t){case"me":return e.me;case"you":return e.you;case"it":return e.it??e.result;case"event":return e.event;case"target":return e.target??e.event?.target??e.me;default:throw new hr("contextReference")}}(n.contextType,e);case"arrayLiteral":return n.elements.map(t=>fr(t,e));case"objectLiteral":return function(t,e){const n={};for(const r of t.properties){const t=r.key;let s;s="identifier"===t.type?t.name:"literal"===t.type&&"string"===t.valueType?t.value:fr(t,e)+"",n[s]=fr(r.value,e)}return n}(n,e);case"asExpression":return er(fr(n.expression,e),kr(n.targetType),e);case"stringPostfix":return`${fr(n.expression,e)}${n.unit}`;case"blockLiteral":return Sr(n,e);case"memberExpression":{const t=fr(n.object,e);if(null==t)return;if(t instanceof Element||Array.isArray(t)||"undefined"!=typeof Node&&t instanceof Node)throw new hr("memberExpression");const r=t[n.computed?fr(n.property,e)+"":n.property?.name];return"function"==typeof r?r.bind(t):r}default:throw new hr(n?.type??"unknown")}}function dr(t,e){const n=We(t);if(!n.success||!n.node){const t=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(t?.message??"unknown error"))}return fr(n.node,e)}async function pr(t,e){const n=We(t);if(!n.success||!n.node){const t=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(t?.message??"unknown error"))}const r=e.registry?e:{...e,registry:await yr()};return ur(n.node,r)}let mr=null;async function yr(){if(!mr){const t=await Promise.resolve().then(function(){return Oo});mr=t.createFullExpressionRegistry()}return mr}async function gr(t,e){const n=t.name;return"me"===n||"my"===n||"I"===n?cr(e,"me").evaluate(e):"you"===n||"your"===n||"yourself"===n?cr(e,"you").evaluate(e):"it"===n||"its"===n?cr(e,"it").evaluate(e):"window"===n?cr(e,"window").evaluate(e):"document"===n?cr(e,"document").evaluate(e):"global"===t.scope&&e.globals?.has(n)?($t(n,e),e.globals.get(n)):"element"===t.scope?en(e,n):e.locals&&e.locals.has(n)?(Lt(n,e),e.locals.get(n)):e.globals&&e.globals.has(n)?(n.startsWith("$")&&$t(n.slice(1),e),e.globals.get(n)):n.startsWith("$")&&e.globals&&e.globals.has(n.slice(1))?($t(n.slice(1),e),e.globals.get(n.slice(1))):void 0!==e[n]?e[n]:"undefined"!=typeof globalThis&&n in globalThis?globalThis[n]:void 0}function vr(t){const e=t;if(!e)return null;if("identifier"===e.type&&"string"==typeof e.name)return[e.name];if("memberExpression"===e.type&&!e.computed){const t=vr(e.object);if(!t)return null;const n=e.property,r="identifier"===n?.type&&"string"==typeof n.name?n.name:"string"==typeof n?.value?n.value:null;return null==r?null:[...t,r]}return null}function br(t,e){return Array.isArray(e)?e.includes(t):"string"==typeof e?e.includes(t+""):t instanceof Node&&e instanceof Node?t===e||e.contains(t):null!=e&&"object"==typeof e&&t in e}function wr(t,e){return t&&"selector"===t.type&&"string"==typeof t.value?t.value:e}function Er(t,e,n){if(void 0!==n)return;const r=t.right;if(!r||"identifier"!==r.type||"string"!=typeof r.name)return;if(null==e||"object"!=typeof e)return;const s=e[r.name];return"boolean"==typeof s?1==s:void 0}function xr(t,e,n){return t instanceof Node&&e instanceof Node&&0!==(t.compareDocumentPosition(e)&n)}function kr(t){if("string"==typeof t)return t;if(t&&"object"==typeof t){if("string"==typeof t.name)return t.name;if("string"==typeof t.value)return t.value}return t+""}function Sr(t,e){const n=t.parameters??[];return(...r)=>{const s=new Map(e.locals??new Map);n.forEach((t,e)=>s.set(t,r[e]));const i={...e,locals:s};try{return fr(t.body,i)}catch(e){if(e instanceof hr)return ur(t.body,i);throw e}}}function Ar(t,e){return e.locals?.has(t)?(Lt(t,e),e.locals.get(t)):"me"===t&&e.me?e.me:"you"===t&&e.you?e.you:"it"===t&&e.it?e.it:"result"===t&&e.result?e.result:"undefined"!=typeof window&&"window"===t?window:e.globals?.has(t)?e.globals.get(t):void 0}async function Nr(t,e,n){const r=[];let s;for(;null!==(s=e.exec(t));)r.push({index:s.index,length:s[0].length,replacement:await n(s[0],...s.slice(1))});let i=t;for(let t=r.length-1;t>=0;t--){const{index:e,length:n,replacement:s}=r[t];i=i.substring(0,e)+s+i.substring(e+n)}return i}function Cr(t,e,n){if("string"==typeof e&&e.startsWith("@")){const n=e.substring(1);return t&&"function"==typeof t.getAttribute?t.getAttribute(n):void 0}return t instanceof Element&&"string"==typeof e?En(t,e):ir(t)&&!(e in t)?cr(n,"possessive").evaluate(n,t,e):t?.[e]}const Tr=new Set(["closest","previous","next"]);function Or(t){return t instanceof Element?t:Array.isArray(t)&&t[0]instanceof Element?t[0]:void 0}const $r=RegExp("(\\.[a-zA-Z0-9_-]+):(?!(hover|active|focus|visited|link|focus-within|focus-visible|first-child|last-child|only-child|nth-child|nth-last-child|nth-of-type|nth-last-of-type|first-of-type|last-of-type|only-of-type|empty|root|target|lang|dir|not|has|is|where|matches|before|after|first-letter|first-line|selection|placeholder|marker|backdrop|enabled|disabled|checked|indeterminate|required|optional|valid|invalid|in-range|out-of-range|read-only|read-write|default|defined|fullscreen|modal|picture-in-picture|autofill)(?![a-zA-Z0-9_-]))","g"),Rr=/[:&()[\]/]/g;function Lr(t,e){return t.fromQuery||!e.startsWith(".")||e.includes("{")?function(t){return t.replace($r,"$1\\:")}(e):function(t){return t[0]+t.slice(1).replace(Rr,"\\$&")}(e)}const Ir=/\$\{([^}]+)\}|\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g;function jr(t){const e=[];let n,r=0;for(Ir.lastIndex=0;null!==(n=Ir.exec(t));)n.index>r&&e.push({lit:t.slice(r,n.index)}),e.push({expr:n[1]??n[2]}),r=n.index+n[0].length;return t.length>r&&e.push({lit:t.slice(r)}),e}function Mr(t,e){let n="";const r=[];let s=0;for(const i of t){if("lit"in i){n+=i.lit;continue}const t=e[s++];yn(t)?(n+=`[data-hs-query-id='${r.length}']`,r.push(t)):n+=(t??"")+""}return{selector:n,elements:r}}class Dr{constructor(t){this.elementCleanups=new WeakMap,this.elementCount=0,this.typeCounts={listener:0,observer:0,interval:0,timeout:0,custom:0},this.globalCleanups=[],this.debugMode=t?.debug??0}registerListener(t,e,n,r,s){this.addCleanup(t,{type:"listener",target:e,eventName:n,cleanup:()=>{e.removeEventListener(n,r,s),this.debugMode&&ut(`CleanupRegistry: Removed listener '${n}'`)},description:n+" listener"})}registerObserver(t,e){this.addCleanup(t,{type:"observer",cleanup:()=>{e.disconnect(),this.debugMode&&ut("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(t,e){this.addCleanup(t,{type:"interval",cleanup:()=>{clearInterval(e),this.debugMode&&ut("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(t,e){this.addCleanup(t,{type:"timeout",cleanup:()=>{clearTimeout(e),this.debugMode&&ut("CleanupRegistry: Cleared timeout")},description:"Timeout"})}registerCustom(t,e,n){this.addCleanup(t,{type:"custom",cleanup:e,description:n||"Custom cleanup"})}registerGlobal(t,e="custom",n){this.globalCleanups.push({type:e,cleanup:t,description:n||"Global cleanup"}),this.debugMode&&ut("CleanupRegistry: Registered global cleanup: "+(n||e))}addCleanup(t,e){const n=this.elementCleanups.get(t);n?n.push(e):(this.elementCleanups.set(t,[e]),this.elementCount++),this.typeCounts[e.type]++,this.debugMode&&ut(`CleanupRegistry: Registered ${e.type} for element`,t)}cleanupElement(t){const e=this.elementCleanups.get(t);if(!e||0===e.length)return 0;let n=0;for(const t of e){try{t.cleanup(),n++}catch(t){this.debugMode&&ut("CleanupRegistry: Error during cleanup:",t)}this.typeCounts[t.type]--}return this.elementCleanups.delete(t),this.elementCount--,this.debugMode&&ut(`CleanupRegistry: Cleaned up ${n} resources for element`),n}cleanupElementTree(t){let e=this.cleanupElement(t);const n=t.querySelectorAll("*");for(const t of n)e+=this.cleanupElement(t);return e}cleanupGlobal(){let t=0;for(const e of this.globalCleanups)try{e.cleanup(),t++}catch(t){this.debugMode&&ut("CleanupRegistry: Error during global cleanup:",t)}return this.globalCleanups=[],this.debugMode&&ut(`CleanupRegistry: Cleaned up ${t} global resources`),t}cleanupAll(){return this.cleanupGlobal()}hasCleanups(t){const e=this.elementCleanups.get(t);return void 0!==e&&e.length>0}getCleanupCount(t){const e=this.elementCleanups.get(t);return e?.length??0}getStats(){let t=0,e=0,n=0,r=0,s=0;for(const i of this.globalCleanups)switch(i.type){case"listener":t++;break;case"observer":e++;break;case"interval":n++;break;case"timeout":r++;break;case"custom":s++}return{elementsTracked:this.elementCount,listeners:this.typeCounts.listener+t,observers:this.typeCounts.observer+e,intervals:this.typeCounts.interval+n,timeouts:this.typeCounts.timeout+r,custom:this.typeCounts.custom+s,global:this.globalCleanups.length}}setDebugMode(t){this.debugMode=t}}class Pr{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(t,e){const n=t.toLowerCase();this.sources.has(n)&&ut("[EventSourceRegistry] Overwriting existing event source: "+t),this.sources.set(n,e)}unregister(t){const e=t.toLowerCase(),n=this.sources.get(e);if(n){for(const[t,n]of this.subscriptions.entries())n.source===e&&(n.unsubscribe(),this.subscriptions.delete(t));return n.destroy?.(),this.sources.delete(e)}return 0}get(t){return this.sources.get(t.toLowerCase())}has(t){return this.sources.has(t.toLowerCase())}subscribe(t,e,n){const r=this.get(t);if(!r)return void ut("[EventSourceRegistry] Unknown event source: "+t);r.initialize?.();const s=r.subscribe(e,n);return this.subscriptions.set(s.id,s),s}unsubscribe(t){const e=this.subscriptions.get(t);return e?(e.unsubscribe(),this.subscriptions.delete(t)):0}getSourceNames(){return Array.from(this.sources.keys())}getSubscriptions(){return Array.from(this.subscriptions.values())}findSourceForEvent(t){for(const[e,n]of this.sources.entries())if(n.supports?.(t)??n.supportedEvents?.includes(t))return e}generateId(){return`sub_${this.nextId++}_${Date.now().toString(36)}`}destroy(){for(const t of this.subscriptions.values())t.unsubscribe();this.subscriptions.clear();for(const t of this.sources.values())t.destroy?.();this.sources.clear()}}class Fr{constructor(){this.providers=new Map,this.globalProviders=new Map}register(t,e,n){const r=t.toLowerCase();this.providers.set(r,"function"==typeof e?{name:r,provide:e,cache:n?.cache??1,description:n?.description,dependencies:n?.dependencies}:e)}registerGlobal(t,e,n){const r=t.toLowerCase();this.globalProviders.set(r,"function"==typeof e?{name:r,provide:e,cache:n?.cache??1,description:n?.description,dependencies:n?.dependencies}:e)}unregister(t){return this.providers.delete(t.toLowerCase())}unregisterGlobal(t){return this.globalProviders.delete(t.toLowerCase())}get(t){const e=t.toLowerCase();return this.providers.get(e)??this.globalProviders.get(e)}has(t){const e=t.toLowerCase();return this.providers.has(e)||this.globalProviders.has(e)}async resolve(t,e,n){const r=this.get(t);if(!r)return;const s="__provider_"+r.name;if(r.cache&&n?.has(s))return n.get(s);if(r.dependencies)for(const t of r.dependencies)await this.resolve(t,e,n);const i=await r.provide(e);return r.cache&&n&&n.set(s,i),i}resolveSync(t,e,n){const r=this.get(t);if(!r)return;const s="__provider_"+r.name;if(r.cache&&n?.has(s))return n.get(s);const i=r.provide(e);if(i instanceof Promise)throw Error(`Context provider '${t}' is async. Use resolve() instead of resolveSync().`);return r.cache&&n&&n.set(s,i),i}enhance(t){const e=this,n=new Map;return new Proxy(t,{get(t,r,s){if("string"==typeof r&&e.get(r))try{return e.resolveSync(r,t,n)}catch{return e.resolve(r,t,n)}return Reflect.get(t,r,s)},has:(t,n)=>"string"==typeof n&&e.has(n)?1:Reflect.has(t,n)})}async resolveAll(t){const e=new Map,n={},r=[...this.globalProviders.entries(),...this.providers.entries()];for(const[s,i]of r)try{n[s]=await this.resolve(s,t,e)}catch(t){ut(`[ContextProviderRegistry] Failed to resolve '${s}':`,t),n[s]=void 0}return n}getProviderNames(){return[...new Set([...this.globalProviders.keys(),...this.providers.keys()])]}clear(){this.providers.clear(),this.globalProviders.clear()}}const Br={evaluate:(t,e)=>ur(t,e)};class _r{static toTyped(t){return{me:t.me,...void 0!==t.owner&&{owner:t.owner},it:t.it,you:t.you,result:t.result,...void 0!==t.event&&{event:t.event},variables:t.variables||new Map,locals:t.locals||new Map,globals:t.globals||new Map,...void 0!==t.events&&{events:t.events},meta:t.meta||{},...void 0!==t.registry&&{registry:t.registry},expressionStack:[],evaluationDepth:0,validationMode:"strict",evaluationHistory:[]}}static fromTyped(t,e){return{...e,me:t.me,it:t.it,you:t.you,result:t.result,...void 0!==t.event&&{event:t.event},...void 0!==t.variables&&{variables:t.variables},locals:t.locals,globals:t.globals,...void 0!==t.events&&{events:t.events},...void 0!==t.meta&&{meta:t.meta}}}}class Vr{constructor(t,e,n){this.impl=t,this.hookRegistry=n??null}setHookRegistry(t){this.hookRegistry=t}createHookContext(t,e,n={}){return{commandName:this.name,element:t.me instanceof Element?t.me:null,args:e,modifiers:n,event:t.event??void 0,executionContext:t}}get name(){const t=this.impl.name;if(t)return t;const e=this.impl.metadata?.name;return"string"==typeof e?e:""}get metadata(){const t=this.impl.metadata?.syntax;return{description:this.impl.metadata?.description||"",examples:this.impl.metadata?.examples||[],syntax:Array.isArray(t)?t.join(" | "):t||""}}async execute(t,...e){const n=e[0],r=this.createHookContext(t,e,n&&"object"==typeof n&&"modifiers"in n&&n.modifiers||{});try{if(at(`CommandAdapterV2: Executing '${this.name}' with args:`,e),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(r),this.hookRegistry?.shouldIntercept(this.name,r))return void at(`CommandAdapterV2: '${this.name}' intercepted by hook`);const s=_r.toTyped(t);let i,o;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(at(`CommandAdapterV2: '${this.name}' has parseInput(), calling it`),n&&"object"==typeof n&&("args"in n||"modifiers"in n)){const e=n.modifiers,r=e?.when||e?.where;if(r&&!await ur(r,t))return void at(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);i=await this.impl.parseInput({args:n.args||[],modifiers:e||{},commandName:n.commandName},Br,t)}else i=e;else at(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),i=e;if(at("CommandAdapterV2: Calling execute with parsed input:",i),2===this.impl.execute.length)o=await this.impl.execute(i,s);else{const t=Array.isArray(i)?i:[i];o=await this.impl.execute(s,...t)}return at("CommandAdapterV2: Command result:",o),Object.assign(t,_r.fromTyped(s,t)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(r,o),o}catch(t){if(Jr(t)||at(`CommandAdapterV2: Error executing '${this.name}':`,t),this.hookRegistry&&t instanceof Error)throw await this.hookRegistry.runOnError(r,t);throw t}}validate(t){return this.impl.validate?this.impl.validate(t):{isValid:1,errors:[],suggestions:[]}}}class qr{constructor(t,e){this.adapters=new Map,this.implementations=new Map,this.hookRegistry=e}setHookRegistry(t){this.hookRegistry=t;for(const e of this.adapters.values())e.setHookRegistry(t);ut(`CommandRegistryV2: Hook registry set and propagated to ${this.adapters.size} adapters`)}getHookRegistry(){return this.hookRegistry}register(t){const e=t.name||t.metadata?.name;if(!e||"string"!=typeof e)throw Error("Cannot register command: no name found. Provide a 'name' property or 'metadata.name' on the implementation.");const n=e.toLowerCase();ut(`CommandRegistryV2: Registering command '${n}'`),this.implementations.set(n,t);const r=new Vr(t,void 0,this.hookRegistry);this.adapters.set(n,r),E.add(n);const s=t.metadata?.aliases;if(s&&Array.isArray(s))for(const e of s){const n=e.toLowerCase();this.implementations.set(n,t),this.adapters.set(n,r),E.add(n)}}getAdapter(t){return this.adapters.get(t.toLowerCase())}has(t){return this.adapters.has(t.toLowerCase())}getCommandNames(){return Array.from(this.adapters.keys())}getImplementation(t){return this.implementations.get(t.toLowerCase())}getAdapters(){return new Map(this.adapters)}validateCommand(t,e){const n=this.getAdapter(t);return n?n.validate(e):{isValid:0,errors:[{type:"runtime-error",message:"Unknown command: "+t,suggestions:["Available commands: "+this.getCommandNames().join(", ")]}],suggestions:["Available commands: "+this.getCommandNames().join(", ")]}}}let Hr=null;function Ur(){return Hr||(Hr=function(){const t=new qr,e=new Pr,n=new Fr,r=new Set,s={commands:t,eventSources:e,context:n,use(i){if(r.has(i.name))ut(`[LokaScriptRegistry] Plugin '${i.name}' is already installed`);else{if(i.commands)for(const e of i.commands)t.register(e);if(i.eventSources)for(const t of i.eventSources)e.register(t.name,t);if(i.contextProviders)for(const{name:t,provide:e,options:r}of i.contextProviders)n.register(t,e,r);i.setup?.(s),r.add(i.name)}},reset(){r.clear()}};return s}()),Hr}class Wr{constructor(t={}){this.contextCache=new WeakMap;const e=Ur();this.options={enableContextProviders:t.enableContextProviders??1,enableEventSources:t.enableEventSources??1,registry:t.registry??{}},this.contextRegistry=this.options.registry.context??e.context,this.eventSourceRegistry=this.options.registry.eventSources??e.eventSources,ut(`[RegistryIntegration] Initialized (context=${this.options.enableContextProviders}, events=${this.options.enableEventSources})`)}enhanceContext(t){if(!this.options.enableContextProviders)return t;const e=this.contextCache.get(t);if(e)return e;try{const e=this.contextRegistry.enhance(t);return this.contextCache.set(t,e),ut(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),e}catch(e){return ut("[RegistryIntegration] Failed to enhance context: "+(e instanceof Error?e.message:e+"")),t}}getEventSource(t){if(!this.options.enableEventSources)return;const e=this.eventSourceRegistry.get(t);if(e)return ut(`[RegistryIntegration] Found event source for '${t}'`),e;const n=this.eventSourceRegistry.findSourceForEvent(t);if(n){const e=this.eventSourceRegistry.get(n);return ut(`[RegistryIntegration] Found event source '${n}' supporting '${t}'`),e}}hasEventSource(t){return void 0!==this.getEventSource(t)}subscribeToEventSource(t,e,n){if(!this.options.enableEventSources)throw Error("Event sources are disabled in this runtime");const r=this.eventSourceRegistry.subscribe(t,e,n);if(!r)throw Error(`Failed to subscribe to event source '${t}'`);return ut(`[RegistryIntegration] Subscribed to '${t}' event '${e.event}' (id: ${r.id})`),r}getEventSourceNames(){return this.eventSourceRegistry.getSourceNames()}getContextProviderNames(){return this.contextRegistry.getProviderNames()}destroy(){this.eventSourceRegistry.destroy(),this.contextCache=new WeakMap,ut("[RegistryIntegration] Destroyed")}}function zr(t){const e=Error(t.type.toUpperCase()+"_EXECUTION");return e["is"+t.type.charAt(0).toUpperCase()+t.type.slice(1)]=1,"returnValue"in t&&(e.returnValue=t.returnValue),e}function Jr(t){return t instanceof Error?null!==Je(t)||"HALT_EXECUTION"===t.message||"EXIT_COMMAND"===t.message||"EXIT_EXECUTION"===t.message:0}function Zr(t){if(void 0===t)return;let e=t;if(e&&"object"==typeof e){const t=e;if("result"in t&&"wasAsync"in t)e=t.result;else if("result"in t&&"executed"in t){if(e=t.result,t.preserveArrayResult)return void 0!==e?e:void 0}else if("lastResult"in t&&"type"in t)e=t.lastResult;else if("conditionResult"in t&&"executedBranch"in t){if(void 0===t.result)return;e=t.result}else"value"in t&&1===Object.keys(t).length||"value"in t&&"target"in t&&"targetType"in t?e=t.value:"data"in t&&"status"in t&&"headers"in t&&(e=t.data)}return Array.isArray(e)&&e.length>0&&(e=e[0]),e}function Gr(t){return null!==t&&"object"==typeof t&&"command"in t&&"selector"in t}const Xr=new WeakMap;class Yr{constructor(t){this.autoCleanupObserver=null,this.registryIntegration=null,this.runtimeWarnings=[],this.options={commandTimeout:1e4,enableErrorReporting:1,enableResultPattern:1,enableAutoCleanup:1,...t},this.registry=t.registry,this.expressionRegistry=t.expressionRegistry,this.behaviorRegistry=new Map,this.globalVariables=Ye,this.hookRegistry=new ze,t.hooks&&this.hookRegistry.register("default",t.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new Dr,this.options.enableAutoCleanup&&this.setupAutoCleanup(),0!=t.registryIntegration&&(this.registryIntegration=new Wr("object"==typeof t.registryIntegration?t.registryIntegration:{}),ut("RuntimeBase: Registry integration enabled")),this.behaviorAPI={has:t=>this.behaviorRegistry.has(t),get:t=>this.behaviorRegistry.get(t),set:(t,e)=>this.behaviorRegistry.set(t,e),resolve:null,install:async(t,e,n)=>await this.installBehaviorOnElement(t,e,n)}}setupAutoCleanup(){"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.autoCleanupObserver=new MutationObserver(t=>{const e=[];for(const n of t)for(const t of n.removedNodes)t instanceof Element&&e.push(t);e.length>0&&queueMicrotask(()=>{for(const t of e)if(!t.isConnected){const e=this.cleanupRegistry.cleanupElementTree(t);e>0&&ut(`RuntimeBase: Auto-cleaned ${e} resources for removed element`)}})}),document.body?this.autoCleanupObserver.observe(document.body,{childList:1,subtree:1}):document.addEventListener("DOMContentLoaded",()=>{this.autoCleanupObserver?.observe(document.body,{childList:1,subtree:1})},{once:1}))}registerHooks(t,e){this.hookRegistry.register(t,e)}unregisterHooks(t){return this.hookRegistry.unregister(t)}getRegisteredHooks(){return this.hookRegistry.getRegisteredNames()}cleanup(t){return this.cleanupRegistry.cleanupElement(t)}trackListener(t,e,n,r,s){this.cleanupRegistry.registerListener(t,e,n,r,s)}cleanupTree(t){return this.cleanupRegistry.cleanupElementTree(t)}getCleanupStats(){return this.cleanupRegistry.getStats()}getCleanupRegistry(){return this.cleanupRegistry}logError(...t){this.options.enableErrorReporting&&console.error(...t)}logWarn(...t){this.options.enableErrorReporting&&console.warn(...t)}destroy(){this.autoCleanupObserver&&(this.autoCleanupObserver.disconnect(),this.autoCleanupObserver=null),this.cleanupRegistry.cleanupAll(),this.hookRegistry.clear(),this.behaviorRegistry.clear(),ut("RuntimeBase: Destroyed")}hasErrorDiagnostics(t){const e=t.diagnostics;return!!e?.some(t=>"error"===t.severity)}getWarnings(){return this.runtimeWarnings}async execute(t,e){ut(`RUNTIME BASE: execute() called with node type: '${t.type}'`),e.registry||(e.registry=this.expressionRegistry),e.locals.has("_behaviors")||e.locals.set("_behaviors",this.behaviorAPI),e.locals.has("_runtimeExecute")||e.locals.set("_runtimeExecute",(t,n)=>this.execute(t,n||e));try{if(this.hasErrorDiagnostics(t)){const e=t.diagnostics?.[0];return ut("\u26a0\ufe0f RUNTIME: Skipping error node: "+(e?.message||"unknown error")),void this.runtimeWarnings.push(e?.message||"Skipped error node")}switch(t.type){case"command":if(this.options.enableResultPattern){const n=await this.processCommandWithResult(t,e);if(!Xe(n)){if("return"===n.error.type){const t=n.error.returnValue;return void 0!==t&&Object.assign(e,{it:t,result:t}),t}throw zr(n.error)}return n.value}try{return await this.processCommand(t,e)}catch(t){const n=Je(t);if(n?.isReturn){const t=n.returnValue;return void 0!==t&&Object.assign(e,{it:t,result:t}),t}throw t}case"eventHandler":return await this.executeEventHandler(t,e);case"event":{const n={type:"eventHandler",event:t.event,events:[t.event],commands:t.body||[],target:t.filter,modifiers:t.modifiers||{}};return await this.executeEventHandler(n,e)}case"behavior":return await this.executeBehaviorDefinition(t,e);case"Program":return await this.executeProgram(t,e);case"initBlock":case"block":return await this.executeBlock(t,e);case"sequence":case"CommandSequence":if(this.options.enableResultPattern){const n=t,r=await this.executeCommandSequenceWithResult(n.commands||[],e);if(!Xe(r))throw zr(r.error);return r.value}return await this.executeCommandSequence(t,e);case"objectLiteral":return await this.executeObjectLiteral(t,e);default:if(this.options.enableResultPattern){const n=await this.evaluateExpressionWithResult(t,e);if(!Xe(n))throw zr(n.error);return n.value}return await this.evaluateExpression(t,e)}}catch(t){throw t}}async processCommand(t,e){const{name:n,args:r,modifiers:s}=t,i=n.toLowerCase();if(at(`RUNTIME BASE: Processing command '${i}'`),this.registry.has(i)){const t=await this.registry.getAdapter(i);if(!t)throw Error(`Command '${i}' is registered but failed to load adapter.`);try{return await t.execute(e,{args:r||[],modifiers:s||{},commandName:i,runtime:this})}catch(t){throw Jr(t)||this.logError(`Error executing command '${i}':`,t),t}}const o=`Unknown command: ${n}. Ensure it is registered in the Runtime options.`;throw this.logWarn(o),Error(o)}toSignal(t){const e=Je(t);if(e){if(e.isHalt||"HALT_EXECUTION"===e.message)return{type:"halt"};if(e.isExit||"EXIT_COMMAND"===e.message)return{type:"exit",returnValue:e.returnValue};if(e.isBreak)return{type:"break"};if(e.isContinue)return{type:"continue"};if(e.isReturn)return{type:"return",returnValue:e.returnValue}}if(t instanceof Error){if("HALT_EXECUTION"===t.message)return{type:"halt"};if("EXIT_COMMAND"===t.message)return{type:"exit"}}return null}async processCommandWithResult(t,e){const{name:n,args:r,modifiers:s}=t,i=n.toLowerCase();if(at(`RUNTIME BASE (Result): Processing command '${i}'`),!this.registry.has(i)){const t=`Unknown command: ${n}. Ensure it is registered in the Runtime options.`;throw this.logWarn(t),Error(t)}const o=await this.registry.getAdapter(i);if(!o)throw Error(`Command '${i}' is registered but failed to load adapter.`);try{return Ze(await o.execute(e,{args:r||[],modifiers:s||{},commandName:i,runtime:this}))}catch(t){const e=this.toSignal(t);if(e)return Ge(e);throw this.logError(`Error executing command '${i}':`,t),t}}async executeCommandSequenceWithResult(t,e){let n;for(const r of t){if(this.hasErrorDiagnostics(r)){const t=r.diagnostics?.[0];ut("\u26a0\ufe0f RUNTIME: Skipping error node: "+(t?.message||"unknown error")),this.runtimeWarnings.push(t?.message||"Skipped error node");continue}if("command"===r.type){const t=await this.processCommandWithResult(r,e);if(!Xe(t)){const n=t.error;switch(n.type){case"halt":case"exit":case"break":case"continue":return t;case"return":return void 0!==n.returnValue&&Object.assign(e,{it:n.returnValue,result:n.returnValue}),Ze(n.returnValue)}}n=t.value}else{const t=await this.evaluateExpressionWithResult(r,e);if(!Xe(t))return t;n=t.value}}return Ze(n)}async evaluateExpression(t,e){const n=e.registry?e:{...e,registry:this.expressionRegistry},r=await ur(t,n);return Gr(r)?await this.executeCommandFromPattern(r.command,r.selector,e):r}async evaluateExpressionWithResult(t,e){const n=e.registry?e:{...e,registry:this.expressionRegistry},r=await async function(t,e){try{return Ze(await ur(t,e))}catch(t){if(t instanceof Error){const e=t;if(e.isHalt||"HALT_EXECUTION"===e.message)return Ge({type:"halt"});if(e.isExit||"EXIT_COMMAND"===e.message)return Ge({type:"exit",returnValue:e.returnValue});if(e.isBreak)return Ge({type:"break"});if(e.isContinue)return Ge({type:"continue"});if(e.isReturn)return Ge({type:"return",returnValue:e.returnValue})}throw t}}(t,n);if(!Xe(r))return r;const s=r.value;if(Gr(s)){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:s.command,args:[{type:"literal",value:s.selector}]},e);try{return Ze(await this.executeCommandFromPattern(s.command,s.selector,e))}catch(t){const e=this.toSignal(t);if(e)return Ge(e);throw t}}return Ze(s)}async executeCommandFromPattern(t,e,n){return this.processCommand({type:"command",name:t,args:[{type:"literal",value:e}]},n)}async executeProgram(t,e){if(!t.statements||!Array.isArray(t.statements))return;let n;const r=[],s=[],i=[];for(const e of t.statements)"eventHandler"===e.type?r.push(e):"initBlock"===e.type?s.push(e):i.push(e);for(const t of r)try{await this.execute(t,e)}catch(t){if(Jr(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of s)try{n=await this.execute(t,e)}catch(t){if(Jr(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of i)try{n=await this.execute(t,e)}catch(t){if(Jr(t)&&(t.isHalt||t.isExit))break;throw t}return n}async executeBlock(t,e){if(t.commands&&Array.isArray(t.commands))for(const n of t.commands)try{await this.execute(n,e)}catch(t){if(Jr(t)&&t.isHalt)break;throw t}}async executeCommandSequence(t,e){if(!t.commands||!Array.isArray(t.commands))return;let n;for(const r of t.commands)try{n=await this.execute(r,e)}catch(t){if(Jr(t)){if(t.isHalt||t.isExit)break;if(t.isReturn){if(void 0!==t.returnValue)return Object.assign(e,{it:t.returnValue,result:t.returnValue}),t.returnValue;break}if(t.isBreak)throw t}throw t}return n}async executeObjectLiteral(t,e){const n={};if(!t.properties)return n;for(const r of t.properties){let t;t="identifier"===r.key.type?r.key.name:"literal"===r.key.type?r.key.value+"":await this.execute(r.key,e)+"";const s=await this.execute(r.value,e);n[t]=s}return n}enhanceContext(t){return this.registryIntegration?this.registryIntegration.enhanceContext(t):t}async executeBehaviorDefinition(t,e){const{name:n,parameters:r=[],eventHandlers:s=[],initBlock:i}=t,o=t.imperativeInstaller;"function"==typeof o?(this.behaviorRegistry.set(n,{name:n,parameters:r,type:"imperative",install:o}),ut(`RUNTIME BASE: Registered imperative behavior '${n}'`)):(this.behaviorRegistry.set(n,{name:n,parameters:r,eventHandlers:s,initBlock:i}),ut(`RUNTIME BASE: Registered behavior '${n}'`))}async installBehaviorOnElement(t,e,n){ut("BEHAVIOR: installBehaviorOnElement called: "+t);let r=this.behaviorRegistry.get(t);if(!r&&(this.behaviorAPI.resolve&&this.behaviorAPI.resolve(t)&&(r=this.behaviorRegistry.get(t)),!r))throw Error(`Behavior "${t}" not found`);if("imperative"===r.type)return void("function"==typeof r.install&&(ut(`BEHAVIOR: Installing imperative behavior '${t}'`),r.install(e,n),ut(`BEHAVIOR: Finished installing imperative behavior '${t}'`)));ut("BEHAVIOR: Found behavior, eventHandlers count: "+(r.eventHandlers?.length||0));const s={me:e,owner:e,you:null,it:null,result:null,locals:new Map,globals:this.globalVariables,registry:this.expressionRegistry,halted:0,returned:0,broke:0,continued:0,async:0},i=this.enhanceContext(s);if(r.parameters)for(const t of r.parameters)i.locals.set(t,t in n?n[t]:void 0);for(const[t,e]of Object.entries(n))r.parameters?.includes(t)||i.locals.set(t,e);if(r.initBlock){ut("BEHAVIOR: Running init block for "+t);const e=this.options.commandTimeout??1e4;try{await Promise.race([this.execute(r.initBlock,i),new Promise((n,r)=>setTimeout(()=>r(Error(`Behavior "${t}" init block timed out after ${e}ms`)),e))]),ut("BEHAVIOR: Init block completed for "+t)}catch(e){if(ut(`BEHAVIOR: Init block error for ${t}:`,e),!(e instanceof Error&&Jr(e)))throw e}}if(ut(`BEHAVIOR: About to attach ${r.eventHandlers?.length||0} handlers for ${t}`),r.eventHandlers){const e=this.options.commandTimeout??1e4;for(const n of r.eventHandlers)await Promise.race([this.executeEventHandler(n,i),new Promise((n,r)=>setTimeout(()=>r(Error(`Behavior "${t}" handler attachment timed out after ${e}ms`)),e))])}ut("BEHAVIOR: Finished installing "+t)}async executeEventHandler(t,e){const{event:n,events:r,commands:s,target:i,args:o,selector:a,attributeName:c,watchTarget:l,modifiers:u,errorSymbol:h,errorHandler:f,finallyHandler:d}=t,p=r&&r.length>0?r:[n];ut(`BEHAVIOR: executeEventHandler: event='${n}', target='${i}'`);let m=[],y=null;if(i){const t="string"==typeof i?i.toLowerCase():"";if("window"===t||"the window"===t)y=window;else if("document"===t||"the document"===t||"body"===t)y=document;else if("me"===t||"myself"===t)m=e.me?[e.me]:[];else if("string"==typeof i&&e.locals.has(i)){const t=e.locals.get(i);ut(`BEHAVIOR: Target resolution: found local '${i}', isElement: ${this.isElement(t)}`),this.isElement(t)?m=[t]:Array.isArray(t)?m=t.filter(t=>this.isElement(t)):"string"==typeof t&&(m=this.queryElements(t,e))}else ut(`BEHAVIOR: Target resolution: querying for '${i}'`),m=this.queryElements(i,e)}else m=e.me?[e.me]:[];if(0===m.length&&!y)return void ut(`BEHAVIOR: executeEventHandler - No targets found for event '${n}', returning early`);if("mutation"===n&&c)return void this.setupMutationObserver(m,c,s,e);if("change"===n&&l)return void this.setupChangeObserver(l,s,e);const g=t.customEventSource;if(g&&this.registryIntegration){ut(`BEHAVIOR: executeEventHandler - Using custom event source '${g}' for event '${n}'`);const t=async t=>{const r=new Map(e.locals),i={...e,locals:r,it:t,event:t},o=this.enhanceContext(i);ut(`CUSTOM EVENT: Executing commands for event '${n}'`);try{await this.execute({type:"program",commands:s},o)}catch(t){this.logError(`[HyperFixi] Error executing commands for custom event '${n}':`,t)}};try{const r=this.registryIntegration.subscribeToEventSource(g,{event:n,handler:t,target:i,selector:a},e);ut(`BEHAVIOR: Subscribed to custom event source '${g}' (id: ${r.id})`),this.cleanupRegistry.registerGlobal(()=>r.unsubscribe(),"listener",`Custom event source '${g}' subscription ${r.id}`)}catch(t){this.logError(`[HyperFixi] Failed to subscribe to custom event source '${g}':`,t)}return}const v=Yr.createEventHandler(this,s,e,a,o,{errorSymbol:h,errorHandler:f,finallyHandler:d});let b,w=null;if(u){let t=v;if(u.prevent){const e=t;t=async t=>(t.preventDefault(),e(t))}if(u.stop){const e=t;t=async t=>(t.stopPropagation(),e(t))}if(u.debounce){const e=u.debounce;let n;b=r=>{n&&clearTimeout(n),n=setTimeout(()=>t(r),e)},w=()=>{n&&(clearTimeout(n),n=void 0)}}else if(u.throttle){const e=u.throttle;let n=0;b=r=>{const s=Date.now();e>s-n||(n=s,t(r))}}else b=t}else b=v;const E=u?.once?{once:1}:void 0;if(y){for(const t of p)y.addEventListener(t,b,E),m.length>0?this.cleanupRegistry.registerListener(m[0],y,t,b):this.cleanupRegistry.registerGlobal(()=>y.removeEventListener(t,b),"listener",`Global ${t} listener`);w&&(m.length>0?this.cleanupRegistry.registerCustom(m[0],w,"debounce-timeout"):this.cleanupRegistry.registerGlobal(w,"timeout","debounce-timeout"))}else for(const t of m){for(const e of p){if("resize"===e&&"undefined"!=typeof ResizeObserver){const e=new ResizeObserver(t=>{for(const n of t){const t=new CustomEvent("resize",{detail:n,bubbles:0,cancelable:0});if(t.synthetic=1,b(t),E?.once){e.disconnect();break}}});e.observe(t),this.cleanupRegistry.registerCustom(t,()=>e.disconnect(),"resize-observer");continue}t.addEventListener(e,b,E),this.cleanupRegistry.registerListener(t,t,e,b)}w&&this.cleanupRegistry.registerCustom(t,w,"debounce-timeout")}}static createEventHandler(t,e,n,r,s,i){return async o=>{const a=Xr.get(o)??0;if(a>=100)return;if(Xr.set(o,a+1),r&&o.target instanceof Element)try{if(!o.target.matches(r)&&!o.target.closest(r))return}catch{ut(`Event delegation: invalid CSS selector '${r}', skipping filter`)}const c=new Map(n.locals),l={...n,locals:c,it:o,event:o};c.has("target")||l.locals.set("target",o.target);const u=t.enhanceContext(l);if(s&&s.length>0){const t=o,e=t.detail;for(const n of s)u.locals.set(n,t[n]??e?.[n]??null)}const h=async e=>{for(const n of e)try{const e=Zr(await t.execute(n,u));void 0!==e&&Object.assign(u,{it:e,result:e})}catch(e){if(Jr(e)){if(e.isHalt||e.isExit)break;if(e.isReturn){void 0!==e.returnValue&&Object.assign(u,{it:e.returnValue,result:e.returnValue});break}}throw t.logError("COMMAND FAILED:",e),e}},f=i?.errorHandler,d=i?.finallyHandler;if(f||d)try{await h(e)}catch(t){if(!f||Jr(t))throw t;i?.errorSymbol&&u.locals.set(i.errorSymbol,t),await h(f)}finally{d&&await h(d)}else await h(e)}}setupMutationObserver(t,e,n,r){ut(`RUNTIME BASE: Setting up MutationObserver for attribute '${e}' on ${t.length} elements`);for(const s of t){const t=new MutationObserver(async t=>{for(const i of t)if("attributes"===i.type&&i.attributeName===e){ct(`MUTATION DETECTED: attribute '${e}' changed on`,s);const t={...r,me:s,it:i,locals:new Map(r.locals)},o=i.oldValue,a=s.getAttribute(e);t.locals.set("oldValue",o),t.locals.set("newValue",a);const c=this.enhanceContext(t);for(const t of n)try{await this.execute(t,c)}catch(t){if(Jr(t)){if(t.isHalt||t.isExit||t.isReturn)break}else this.logError("Error executing mutation handler command:",t)}}});t.observe(s,{attributes:1,attributeOldValue:1,attributeFilter:[e]}),this.cleanupRegistry.registerObserver(s,t),ut("RUNTIME BASE: MutationObserver attached to",s,`for attribute '${e}'`)}}async setupChangeObserver(t,e,n){ut("RUNTIME BASE: Setting up MutationObserver for content changes on watch target");const r=await this.execute(t,n);let s=[];this.isElement(r)?s=[r]:Array.isArray(r)&&(s=r.filter(t=>this.isElement(t))),ut(`RUNTIME BASE: Watching ${s.length} target elements for content changes`);for(const t of s){const r=new MutationObserver(async r=>{for(const s of r)if("childList"===s.type||"characterData"===s.type){ct("CONTENT CHANGE DETECTED on",t,"mutation type:",s.type);const r={...n,me:n.me,it:s,locals:new Map(n.locals)};r.locals.set("target",t);const i=s.oldValue,o=t.textContent;null!==i&&r.locals.set("oldValue",i),r.locals.set("newValue",o);const a=this.enhanceContext(r);for(const t of e)try{await this.execute(t,a)}catch(t){if(Jr(t)){if(t.isHalt||t.isExit||t.isReturn)break}else this.logError("Error executing change handler command:",t)}}});r.observe(t,{childList:1,characterData:1,subtree:1,characterDataOldValue:1}),this.cleanupRegistry.registerObserver(t,r),ut("RUNTIME BASE: MutationObserver attached to",t,"for content changes")}}queryElements(t,e){const n=e.me,r=(n instanceof Element?n.ownerDocument:null)??("undefined"!=typeof document?document:null);if(!r)return[];let s=t;s.startsWith("<")&&s.endsWith("/>")&&(s=s.slice(1,-2).trim());try{return Array.from(r.querySelectorAll(s))}catch{return ut(`queryElements: invalid CSS selector '${s}'`),[]}}isElement(t){return"undefined"!=typeof HTMLElement&&t instanceof HTMLElement?1:t&&"object"==typeof t?!!t.style&&!!t.classList:0}}function Kr(...t){const e=new Map;for(const n of t)for(const[t,r]of Object.entries(n))e.set(t,r);return e}const Qr=Fn({selector:Mn().min(1),single:Pn().optional().default(0)});function ts(t,e){if(e.startsWith("computed-")){const n=e.substring(9);return getComputedStyle(t).getPropertyValue(n)||""}const n=e.replace(/-([a-z])/g,(t,e)=>e.toUpperCase());return t.style[n]}new class extends Hn{constructor(){super(...arguments),this.name="me",this.category="Reference",this.syntax="me",this.description="References the current element in the execution context",this.inputSchema=qn(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=t.me,s=this.isElement(r)?r:null,i=this.success(s,"element");return this.trackPerformance(t,e,i,n),i}catch(r){const s=this.failure("MeExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "me"',"ME_EVALUATION_FAILED",["Ensure element context is properly set",'Check if "me" is available in current scope']);return this.trackPerformance(t,e,s,n),s}}validate(t){return void 0!==t?this.validationFailure("type-mismatch",'"me" expression takes no arguments',['Use "me" without any parameters']):this.validationSuccess()}},new class extends Hn{constructor(){super(...arguments),this.name="you",this.category="Reference",this.syntax="you",this.description="References the target element (usually event target or command target)",this.inputSchema=qn(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=t.you,s=this.isElement(r)?r:null,i=this.success(s,"element");return this.trackPerformance(t,e,i,n),i}catch(r){const s=this.failure("YouExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "you"',"YOU_EVALUATION_FAILED",["Ensure target element is available in context",'Check if "you" is set by event or command']);return this.trackPerformance(t,e,s,n),s}}validate(t){return void 0!==t?this.validationFailure("type-mismatch",'"you" expression takes no arguments',['Use "you" without any parameters']):this.validationSuccess()}},new class extends Hn{constructor(){super(...arguments),this.name="it",this.category="Reference",this.syntax="it",this.description="References the current context variable (result of previous operation or loop item)",this.inputSchema=qn(),this.outputType="Any",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=t.it,s={success:1,value:r,type:this.inferType(r)};return this.trackPerformance(t,e,s,n),s}catch(r){const s=this.failure("ItExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "it"',"IT_EVALUATION_FAILED",['Ensure "it" is set by previous operation',"Check if context variable is available"]);return this.trackPerformance(t,e,s,n),s}}validate(t){return void 0!==t?this.validationFailure("type-mismatch",'"it" expression takes no arguments',['Use "it" without any parameters']):this.validationSuccess()}},new class extends Hn{constructor(){super(...arguments),this.name="css-selector",this.category="Reference",this.syntax="<selector/> or <selector/> (single)",this.description="Queries DOM elements using CSS selectors with validation",this.inputSchema=Qr,this.outputType="ElementList",this.metadata={category:"Reference",complexity:"medium"}}async evaluate(t,e){const n=Date.now();try{if(!this.isValidCSSSelector(e.selector)){const r=this.failure("CSSSelectorError","invalid-argument",`Invalid CSS selector: "${e.selector}"`,"INVALID_CSS_SELECTOR",["Check selector syntax","Use valid CSS selector patterns like .class, #id, tag[attr]","Avoid special characters that need escaping"]);return this.trackPerformance(t,e,r,n),r}let r;if(e.single)r=document.querySelector(e.selector);else{const t=Array.from(document.querySelectorAll(e.selector));r=t.length>0?t:null}const s={success:1,value:r,type:Array.isArray(r)?"element-list":"element"};return this.trackPerformance(t,e,s,n),s}catch(r){const s=this.failure("CSSSelectorError","runtime-error",r instanceof Error?r.message:"CSS selector evaluation failed","CSS_SELECTOR_EVALUATION_FAILED",["Check if selector is valid CSS","Ensure DOM is ready when query executes","Verify elements exist in document"]);return this.trackPerformance(t,e,s,n),s}}validate(t){try{const e=this.inputSchema.safeParse(t);if(!e.success)return{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid input: "+t.message,suggestions:this.getValidationSuggestion(t.code??"unknown")}))??[],suggestions:["Provide valid CSS selector string","Check selector syntax"]};const{selector:n}=e.data;return this.isValidCSSSelector(n)?this.validationSuccess():this.validationFailure("syntax-error",`Invalid CSS selector syntax: "${n}"`,["Use .class for class selectors","Use #id for ID selectors","Use tag for element selectors","Use [attr] for attribute selectors"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Ensure input matches expected format"])}}isValidCSSSelector(t){try{return document.querySelector(t),1}catch{return 0}}getValidationSuggestion(t){return[{too_small:"CSS selector cannot be empty",invalid_type:"Selector must be a string",required:"CSS selector is required"}[t]||"Check input format and types"]}};const es={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.me??null,validate:Cn},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.you??null,validate:Cn},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it,validate:Cn},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it,validate:Cn},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.result,validate:Cn},querySelector:{name:"querySelector",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){const[n]=e;if("string"!=typeof n)throw Error("querySelector requires a string selector");return document.querySelector(n)},validate:t=>An(t,"querySelector","selector")},querySelectorAll:{name:"querySelectorAll",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const n=e[0];if("string"!=typeof n)throw Error("querySelectorAll requires a string selector");const r=document.querySelectorAll(n);return Array.from(r)},validate:t=>An(t,"querySelectorAll","selector")},getElementById:{name:"getElementById",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){const n=e[0];if("string"!=typeof n)throw Error("getElementById requires a string ID");return document.getElementById(n)},validate:t=>An(t,"getElementById","ID")},getElementsByClassName:{name:"getElementsByClassName",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const n=e[0];if("string"!=typeof n)throw Error("getElementsByClassName requires a string class name");const r=document.getElementsByClassName(n);return Array.from(r)},validate:t=>An(t,"getElementsByClassName","className")},closest:{name:"closest",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){let n=e[0];if(n&&"object"==typeof n&&"type"in n){const t=n;"identifier"===t.type&&t.name?n=t.name:"literal"===t.type&&"string"==typeof t.value&&(n=t.value)}if("string"!=typeof n)throw Error("closest requires a string selector");return t.me?t.me.closest(n):null},validate(t){if(1!==t.length)return"closest requires exactly 1 argument (selector)";const e=t[0];return"string"==typeof e||e&&"object"==typeof e&&"type"in e&&("identifier"===e.type||"literal"===e.type)?null:"closest selector must be a string or identifier"}},parent:{name:"parent",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.me?t.me.parentElement:null,validate:Cn},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async t=>window,validate:Cn},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async t=>document,validate:Cn},elementWithSelector:{name:"elementWithSelector",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const n=e[0];if("string"!=typeof n)throw Error("Selector must be a string");const r=t?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!r)throw Error("DOM not available - cannot resolve element selector");const s=r.querySelectorAll(n);return Array.from(s)},validate:t=>An(t,"elementWithSelector","selector")},styleRef:{name:"styleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const n=e[0],r=e[1];if("string"!=typeof n)throw Error("StyleRef requires a string property name");const s=r||t.me;if(s&&s instanceof HTMLElement)return ts(s,n)},validate:t=>On(t,1,2,"styleRef","property, optional element")??Sn(t,0,"styleRef","property")??(2===t.length&&t[1]&&"object"!=typeof t[1]?"styleRef element must be an HTMLElement":null)},possessiveStyleRef:{name:"possessiveStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const n=e[0],r=e[1];if("string"!=typeof n||"string"!=typeof r)throw Error("Possessive styleRef requires possessor and property strings");let s=null;if("my"===n&&t.me?s=t.me instanceof HTMLElement?t.me:null:"its"===n&&t.it&&(s=t.it instanceof HTMLElement?t.it:null),s)return ts(s,r)},validate:t=>kn(t,2,"possessiveStyleRef","possessor, property")??Sn(t,0,"possessiveStyleRef","possessor")??Sn(t,1,"possessiveStyleRef","property")},ofStyleRef:{name:"ofStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const n=e[0],r=e[1];if("string"!=typeof n||"string"!=typeof r)throw Error("Of styleRef requires property and reference strings");let s=null;if("me"===r&&t.me?s=t.me instanceof HTMLElement?t.me:null:"it"===r&&t.it&&(s=t.it instanceof HTMLElement?t.it:null),s)return ts(s,n)},validate:t=>kn(t,2,"ofStyleRef","property, reference")??Sn(t,0,"ofStyleRef","property")??Sn(t,1,"ofStyleRef","reference")}};class ns{constructor(t=100,e=5e3){this.maxSize=t,this.ttl=e,this.cache=new Map,this.accessOrder=new Map,this.accessCounter=0}get(t){const e=this.cache.get(t);if(e){if(this.ttl>=Date.now()-e.timestamp)return e.accessCount++,this.accessOrder.set(t,++this.accessCounter),e.result;this.delete(t)}}set(t,e){this.maxSize>this.cache.size||this.cache.has(t)||this.evictLRU(),this.cache.set(t,{result:e,timestamp:Date.now(),accessCount:1}),this.accessOrder.set(t,++this.accessCounter)}delete(t){return this.accessOrder.delete(t),this.cache.delete(t)}clear(){this.cache.clear(),this.accessOrder.clear(),this.accessCounter=0}size(){return this.cache.size}evictLRU(){let t,e=1/0;for(const[n,r]of this.accessOrder)e>r&&(e=r,t=n);void 0!==t&&this.delete(t)}getStats(){const t=Array.from(this.cache.values()),e=Date.now();return{size:this.cache.size,maxSize:this.maxSize,hitRate:t.length>0?t.filter(t=>t.accessCount>1).length/t.length:0,avgAge:t.length>0?t.reduce((t,n)=>t+(e-n.timestamp),0)/t.length:0,totalAccesses:t.reduce((t,e)=>t+e.accessCount,0)}}}const rs=new class{constructor(){this.domQueryCache=new ns(200,3e3),this.exprResultCache=new ns(500,2e3),this.cssMatchCache=new ns(100,5e3),this.formValueCache=new ns(50,1e3),this.hits=0,this.misses=0}querySelector(t){const e="querySelector:"+t,n=this.domQueryCache.get(e);if(void 0!==n)return this.hits++,n;this.misses++;const r=document.querySelector(t);return this.domQueryCache.set(e,r),r}querySelectorAll(t){const e="querySelectorAll:"+t,n=this.domQueryCache.get(e);if(void 0!==n)return this.hits++,n;this.misses++;const r=Array.from(document.querySelectorAll(t));return this.domQueryCache.set(e,r),r}getElementById(t){const e="getElementById:"+t,n=this.domQueryCache.get(e);if(void 0!==n)return this.hits++,n;this.misses++;const r=document.getElementById(t);return this.domQueryCache.set(e,r),r}getElementsByClassName(t){const e="getElementsByClassName:"+t,n=this.domQueryCache.get(e);if(void 0!==n)return this.hits++,n;this.misses++;const r=Array.from(document.getElementsByClassName(t));return this.domQueryCache.set(e,r),r}matches(t,e){const n=`matches:${this.getElementCacheKey(t)}:${e}`,r=this.cssMatchCache.get(n);if(void 0!==r)return this.hits++,r;this.misses++;const s=t.matches(e);return this.cssMatchCache.set(n,s),s}getExpressionResult(t){const e=this.exprResultCache.get(t);if(void 0!==e)return this.hits++,e;this.misses++}setExpressionResult(t,e){this.exprResultCache.set(t,e)}getFormValue(t){const e=this.getElementCacheKey(t),n=this.formValueCache.get("formValue:"+e);if(void 0!==n)return this.hits++,n;this.misses++}setFormValue(t,e){const n=this.getElementCacheKey(t);this.formValueCache.set("formValue:"+n,e)}invalidateElementCache(t){const e=this.getElementCacheKey(t);for(const t of[this.domQueryCache,this.cssMatchCache,this.formValueCache])for(const n of Array.from(t.cache.keys()))"string"==typeof n&&n.includes(e)&&t.delete(n)}invalidateAll(){this.domQueryCache.clear(),this.exprResultCache.clear(),this.cssMatchCache.clear(),this.formValueCache.clear(),this.hits=0,this.misses=0}getElementCacheKey(t){if(t.id)return"#"+t.id;const e=Array.from(t.classList).sort().join("."),n=this.getElementPosition(t);return`${t.tagName.toLowerCase()}${e?"."+e:""}@${n}`}getElementPosition(t){return""+Array.from(t.parentElement?.children||[]).indexOf(t)}getPerformanceStats(){const t=this.hits+this.misses;return{hits:this.hits,misses:this.misses,hitRate:Math.round(100*(t>0?this.hits/t*100:0))/100,domQueryCache:this.domQueryCache.getStats(),exprResultCache:this.exprResultCache.getStats(),cssMatchCache:this.cssMatchCache.getStats(),formValueCache:this.formValueCache.getStats()}}cleanup(){const t=Date.now();[this.domQueryCache,this.exprResultCache,this.cssMatchCache,this.formValueCache].forEach(e=>{Array.from(e.cache.entries()).forEach(([n,r])=>{t-r.timestamp>e.ttl&&e.delete(n)})})}};"undefined"!=typeof window&&setInterval(()=>{rs.cleanup()},1e4);const ss=new class{constructor(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0},this.startTimes=new Map}startTimer(t){this.startTimes.set(t,performance.now())}endTimer(t){const e=this.startTimes.get(t);if(e){const n=performance.now()-e;return this.startTimes.delete(t),n}return 0}recordTokenization(t){this.metrics.tokenizationTime+=t}recordEvaluation(t){this.metrics.evaluationTime+=t}updateCacheMetrics(){const t=rs.getPerformanceStats();this.metrics.cacheHitRate=t.hitRate}getMetrics(){return this.updateCacheMetrics(),{...this.metrics}}reset(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0}}};function is(){rs.cleanup(),ss.getMetrics().memoryUsage>52428800&&ss.reset()}let os=null;function as(t,e){if("number"==typeof t){if(!Number.isFinite(t))throw Error(`${e} must be a finite number, got ${t}`);return t}if("string"==typeof t){const n=t.trim();if(""===n)return 0;const r=parseFloat(n);if(isNaN(r))throw Error(`${e} cannot be converted to number: "${t}"`);return r}if("boolean"==typeof t)return t?1:0;if(null==t)return 0;if("object"==typeof t&&null!==t){if(Array.isArray(t)&&1===t.length){const n=t[0];if(Array.isArray(n))throw Error(e+" is a nested array, cannot convert to number");return as(n,e)}if("string"==typeof t.textContent||"value"in t){const e=t.value??t.textContent;if(null!=e){const t=(e+"").trim();if(""===t)return 0;const n=parseFloat(t);if(!isNaN(n))return n}}const n=t.valueOf();if("number"==typeof n&&Number.isFinite(n))return n}throw Error(`${e} cannot be converted to number: ${typeof t}`)}function cs(t){if("number"==typeof t)return Number.isFinite(t)?t:null;if("string"==typeof t){const e=t.trim();if(""===e)return 0;const n=parseFloat(e);return isNaN(n)?null:n}return"boolean"==typeof t?t?1:0:null==t?0:null}function ls(t,e){if(!Number.isFinite(t)){if(Number.isNaN(t))throw Error(e+" resulted in non-finite value: NaN");throw Error(`${e} resulted in non-finite value: ${t>0?"Infinity":"-Infinity"}`)}return t}function us(t){try{return as(t,"_"),1}catch{return 0}}function hs(t,e,n){if("==="===n)return t===e;if("!=="===n)return t!==e;if(null==t||null==e)return function(t,e,n){if(null==t&&null==e)switch(n){case"==":case">=":case"<=":return 1;default:return 0}switch(n){case"==":case">":case"<":case">=":case"<=":default:return 0;case"!=":return 1}}(t,e,n);const[r,s]=function(t,e){if("number"==typeof t&&"number"==typeof e)return[t,e];if("string"==typeof t&&"string"==typeof e){const n=parseFloat(t),r=parseFloat(e);return isNaN(n)||isNaN(r)?[t,e]:[n,r]}const n=cs(t),r=cs(e);return null!==n&&null!==r?[n,r]:[t+"",e+""]}(t,e);switch(n){case">":return r>s;case"<":return s>r;case">=":return r>=s;case"<=":return s>=r;case"==":return fs(t,e);case"!=":return!fs(t,e);default:return 0}}function fs(t,e){if(t===e)return 1;if(typeof t==typeof e)return"string"==typeof t||"number"==typeof t?t===e:0;if("number"==typeof t&&"string"==typeof e){const n=parseFloat(e);return!isNaN(n)&&t===n}if("string"==typeof t&&"number"==typeof e){const n=parseFloat(t);return!isNaN(n)&&n===e}return"boolean"==typeof t?fs(t?1:0,e):"boolean"==typeof e?fs(t,e?1:0):t+""==e+""}function ds(t,e=[]){return{isValid:0,errors:t,suggestions:e}}function ps(t,e,n=[],r="error"){return{type:t,message:e,suggestions:n,severity:r}}function ms(t,e,n,r,s,i=1,o){return e&&"object"==typeof e&&"evaluationHistory"in e&&Array.isArray(e.evaluationHistory)&&e.evaluationHistory.push({expressionName:t.name,category:t.category,input:n,output:r,timestamp:s,duration:Date.now()-s,success:i,...void 0!==o&&{error:o}}),r}"undefined"!=typeof window&&function(t=3e4){os&&clearInterval(os),os=setInterval(is,t)}();const ys=Fn({left:_n().describe("Left operand value"),right:_n().describe("Right operand value")}).strict(),gs=Fn({operand:_n().describe("Operand value to negate")}).strict();function vs(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType}new class extends Hn{constructor(){super(...arguments),this.name="and",this.category="Logical",this.syntax="left and right",this.description="Logical AND operation with comprehensive boolean type coercion",this.inputSchema=ys,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:r.errors[0]};const s=this.toBoolean(e.left);if(!s)return this.trackSimple(t,n,1,"boolean"),this.success(0,"boolean");const i=this.toBoolean(e.right),o=s&&i;return this.trackSimple(t,n,1,"boolean"),this.success(o,"boolean")}catch(e){return this.trackSimple(t,n,0),this.failure("AndExpressionError","runtime-error","Logical AND operation failed: "+(e instanceof Error?e.message:e+""),"AND_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid AND operation input: "+t.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends Hn{constructor(){super(...arguments),this.name="or",this.category="Logical",this.syntax="left or right",this.description="Logical OR operation with comprehensive boolean type coercion",this.inputSchema=ys,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:r.errors[0]};const s=this.toBoolean(e.left);if(s)return this.trackSimple(t,n,1,"boolean"),this.success(1,"boolean");const i=this.toBoolean(e.right),o=s||i;return this.trackSimple(t,n,1,"boolean"),this.success(o,"boolean")}catch(e){return this.trackSimple(t,n,0),this.failure("OrExpressionError","runtime-error","Logical OR operation failed: "+(e instanceof Error?e.message:e+""),"OR_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid OR operation input: "+t.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends Hn{constructor(){super(...arguments),this.name="not",this.category="Logical",this.syntax="not operand",this.description="Logical NOT operation with comprehensive boolean type coercion",this.inputSchema=gs,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:r.errors[0]};const s=!this.toBoolean(e.operand);return this.trackSimple(t,n,1,"boolean"),this.success(s,"boolean")}catch(e){return this.trackSimple(t,n,0),this.failure("NotExpressionError","runtime-error","Logical NOT operation failed: "+(e instanceof Error?e.message:e+""),"NOT_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid NOT operation input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a single operand","Ensure operand is a valid value"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}};const bs=Bn([_n(),_n()]),ws=Bn([_n(),Mn()]),Es={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(t,e,n){const r=Date.now();try{return ms(this,t,[e,n],e==n,r)}catch(s){throw ms(this,t,[e,n],0,r,0,s instanceof Error?s:Error(s+"")),s}},validate:t=>Nn(t,"equals"),inputSchema:bs,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"value is 5",description:"Check if value equals 5 using loose equality",expectedOutput:1,context:{result:5}},{input:'"5" == 5',description:'String "5" equals number 5 with type coercion',expectedOutput:1}],relatedExpressions:["strictEquals","notEquals"],performance:{averageTime:.001,complexity:"O(1)"}},documentation:{summary:"Compares two values for loose equality, allowing type coercion",parameters:[{name:"left",type:"unknown",description:"Left operand for comparison",optional:0,examples:["5",'"hello"',"true","null"]},{name:"right",type:"unknown",description:"Right operand for comparison",optional:0,examples:["5",'"hello"',"true","null"]}],returns:{type:"Boolean",description:"True if values are loosely equal, false otherwise",examples:["true","false"]},examples:[{title:"Basic equality check",code:"if my.value is 10",explanation:"Check if element value equals 10",output:"Boolean result"},{title:"Type coercion",code:'if "5" == 5',explanation:'String "5" equals number 5 with automatic type conversion',output:"true"},{title:"Null checks",code:"if value is null",explanation:"Check if value is null or undefined",output:"Boolean result"}],seeAlso:["strictEquals","notEquals","matches"],tags:["comparison","equality","logic","type-coercion"]}},xs={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],async evaluate(t,e,n){const r=t.evaluationHistory,s=e===n;return r&&ms(this,t,[e,n],s,r?Date.now():0),s},validate:t=>Nn(t,"strictEquals")},ks={name:"notEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=","is not","does not equal"],async evaluate(t,e,n){const r=t.evaluationHistory,s=e!=n;return r&&ms(this,t,[e,n],s,r?Date.now():0),s},validate:t=>Nn(t,"notEquals")},Ss={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],async evaluate(t,e,n){const r=t.evaluationHistory,s=e!==n;return r&&ms(this,t,[e,n],s,r?Date.now():0),s},validate:t=>Nn(t,"strictNotEquals")},As={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0,i=hs(e,n,"<");return r&&ms(this,t,[e,n],i,s),i},validate:t=>Nn(t,"lessThan")},Ns={name:"lessThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<=","is less than or equal to"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0,i=hs(e,n,"<=");return r&&ms(this,t,[e,n],i,s),i},validate:t=>Nn(t,"lessThanOrEqual")},Cs={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0,i=hs(e,n,">");return r&&ms(this,t,[e,n],i,s),i},validate:t=>Nn(t,"greaterThan")},Ts={name:"greaterThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">=","is greater than or equal to"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0,i=hs(e,n,">=");return r&&ms(this,t,[e,n],i,s),i},validate:t=>Nn(t,"greaterThanOrEqual")},Os={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(t,e,n){const r=Date.now();try{return ms(this,t,[e,n],e&&n,r)}catch(s){throw ms(this,t,[e,n],0,r,0,s instanceof Error?s:Error(s+"")),s}},validate:t=>Nn(t,"and"),inputSchema:bs,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"true and false",description:"Logical AND of boolean values",expectedOutput:0},{input:"name and age",description:"Both name and age must be truthy",expectedOutput:1,context:{variables:new Map([["name","John"],["age",25]])}}],relatedExpressions:["or","not"],performance:{averageTime:.001,complexity:"O(1)"}},documentation:{summary:"Logical AND operation that returns true only if both operands are truthy",parameters:[{name:"left",type:"unknown",description:"Left operand (evaluated for truthiness)",optional:0,examples:["true","name","5",'"hello"']},{name:"right",type:"unknown",description:"Right operand (evaluated for truthiness)",optional:0,examples:["false","age","0",'""']}],returns:{type:"Boolean",description:"True if both operands are truthy, false otherwise",examples:["true","false"]},examples:[{title:"Form validation",code:"if name and email",explanation:"Check if both name and email have values",output:"Boolean result"},{title:"Multiple conditions",code:"if age > 18 and hasLicense",explanation:"Combine multiple conditions",output:"Boolean result"},{title:"Short-circuit evaluation",code:"if element and element.value",explanation:"Check element exists before accessing properties",output:"Boolean result"}],seeAlso:["or","not","exists"],tags:["logic","boolean","conditions","validation"]}},$s={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],async evaluate(t,e,n){const r=t.evaluationHistory,s=e||n;return r&&ms(this,t,[e,n],s,r?Date.now():0),s},validate:t=>Nn(t,"or")},Rs={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],async evaluate(t,e){const n=t.evaluationHistory,r=!e;return n&&ms(this,t,[e],r,n?Date.now():0),r},validate:t=>kn(t,1,"not","operand")},Ls={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0;let s;return s=null==e?1:un(e)||Array.isArray(e)||e instanceof NodeList?0===e.length:e instanceof Node||e instanceof Element?0:dn(e)?0===Object.keys(e).length:0,n&&ms(this,t,[e],s,r),s},validate:t=>kn(t,1,"isEmpty","value")},Is={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0;let s;return s=null==e||0==e?1:Array.isArray(e)||e instanceof NodeList?0===e.length:(un(e),0),n&&ms(this,t,[e],s,r),s},validate:t=>kn(t,1,"no","value")},js={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0,s=!await Ls.evaluate(t,e);return n&&ms(this,t,[e],s,r),s},validate:t=>kn(t,1,"isNotEmpty","value")},Ms={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0,s=Ds(e);return n&&ms(this,t,[e],s,r),s},validate:t=>kn(t,1,"exists","value")};function Ds(t){return null==t?0:Array.isArray(t)||"undefined"!=typeof NodeList&&t instanceof NodeList?t.length>0:1}const Ps={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0,s=!Ds(e);return n&&ms(this,t,[e],s,r),s},validate:t=>kn(t,1,"doesNotExist","value")},Fs={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0;let i;if(e&&n){if(vs(e)&&vs(n))return i=e.contains(n),r&&ms(this,t,[e,n],i,s),i;if(un(e)&&e.match(/^[.#][\w-]+$/)){const o=document.querySelector(e);if(o&&vs(n))return i=o.contains(n),r&&ms(this,t,[e,n],i,s),i;if(o&&un(n)&&n.match(/^[.#][\w-]+$/)){const a=document.querySelector(n);return i=a?o.contains(a):0,r&&ms(this,t,[e,n],i,s),i}}if(un(n)&&n.match(/^[.#][\w-]+$/)&&vs(e)){const o=document.querySelector(n);return i=o?e.contains(o):0,r&&ms(this,t,[e,n],i,s),i}}if(un(e)&&un(n))i=e.includes(n);else if(Array.isArray(e)||"undefined"!=typeof NodeList&&e instanceof NodeList){const t=Array.from(e);i=t.includes(n)||n instanceof Node&&t.some(t=>t instanceof Node&&t.contains(n))}else i=dn(e)&&un(n)?n in e:0;return r&&ms(this,t,[e,n],i,s),i},validate:t=>kn(t,2,"contains","container, value")},Bs={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0,i=!await Fs.evaluate(t,e,n);return r&&ms(this,t,[e,n],i,s),i},validate:t=>kn(t,2,"doesNotContain","container, value")},_s={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0,i=null!=e&&null!=n?(e+"").startsWith(n+""):0;return r&&ms(this,t,[e,n],i,s),i},validate:t=>kn(t,2,"startsWith","str, prefix")},Vs={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0,i=null!=e&&null!=n?(e+"").endsWith(n+""):0;return r&&ms(this,t,[e,n],i,s),i},validate:t=>kn(t,2,"endsWith","str, suffix")},qs={name:"between",category:"Logical",evaluatesTo:"Boolean",operators:["is between","between"],async evaluate(t,e,n,r){const s=t.evaluationHistory;let i=n,o=r;if(null!=i&&null!=o&&i>o){const t=i;i=o,o=t}const a=null!=i&&null!=o&&e>=i&&o>=e;return s&&ms(this,t,[e,n,r],a,s?Date.now():0),a},validate:t=>kn(t,3,"between","value, min, max")},Hs={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(t,e,n){const r=Date.now();try{let s;if(e instanceof Element&&un(n)){const t=n;if(t.startsWith(".")||t.startsWith("#")||t.startsWith(":")||t.startsWith("[")||/^[a-zA-Z][\w-]*$/.test(t))try{s=function(t,e){return rs.matches(t,e)}(e,t)}catch(t){s=0}else s=0}else if(un(e)&&un(n)){const t=e,r=n;try{s=(r.startsWith("/")&&r.endsWith("/")?RegExp(r.slice(1,-1)):RegExp(r)).test(t)}catch(e){s=t.includes(r)}}else s=0;return ms(this,t,[e,n],s,r)}catch(s){throw ms(this,t,[e,n],0,r,0,s instanceof Error?s:Error(s+"")),s}},validate:t=>kn(t,2,"matches","element, selector"),inputSchema:ws,metadata:{category:"Logical",complexity:"medium",sideEffects:["dom-query"],dependencies:[],returnTypes:["Boolean"],examples:[{input:'element matches ".active"',description:"Check if element has active class",expectedOutput:1},{input:'text matches "/^hello/"',description:'Check if text starts with "hello" using regex',expectedOutput:1,context:{variables:new Map([["text","hello world"]])}}],relatedExpressions:["contains","startsWith","endsWith"],performance:{averageTime:.5,complexity:"O(n)"}},documentation:{summary:"Tests if element matches CSS selector or string matches regex pattern",parameters:[{name:"element",type:"Element | string",description:"DOM element or string to test",optional:0,examples:["<div>",'"hello world"',"me","target"]},{name:"selector",type:"string",description:"CSS selector or regex pattern to match against",optional:0,examples:['".active"','"#navbar"','"/^hello/"','"\\\\d+"']}],returns:{type:"Boolean",description:"True if element matches selector/pattern",examples:["true","false"]},examples:[{title:"CSS class matching",code:'if me matches ".active"',explanation:'Check if current element has "active" class',output:"Boolean result"},{title:"Attribute matching",code:'if target matches "[data-role=\\"button\\"]"',explanation:"Check if element has specific data attribute",output:"Boolean result"},{title:"Regex pattern matching",code:'if email matches "/^[^@]+@[^@]+\\\\.[^@]+$/"',explanation:"Validate email format with regex",output:"Boolean result"},{title:"Complex CSS selector",code:'if element matches ".card:hover .button"',explanation:"Match complex CSS selector with pseudo-classes",output:"Boolean result"}],seeAlso:["contains","startsWith","endsWith","querySelector"],tags:["pattern","css","regex","validation","dom"]}},Us={name:"has",category:"Logical",evaluatesTo:"Boolean",operators:["has","have"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0;let i=0;if(e instanceof Element&&un(n)){const t=n;t.startsWith(".")?i=e.classList.contains(t.slice(1)):t.startsWith("[")&&t.endsWith("]")&&(i=e.hasAttribute(t.slice(1,-1)))}return r&&ms(this,t,[e,n],i,s),i},validate:t=>kn(t,2,"has","element, selector")},Ws={name:"doesNotHave",category:"Logical",evaluatesTo:"Boolean",operators:["does not have"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0,i=!await Us.evaluate(t,e,n);return r&&ms(this,t,[e,n],i,s),i},validate:t=>kn(t,2,"doesNotHave","element, selector")},zs={equals:Es,strictEquals:xs,notEquals:ks,strictNotEquals:Ss,lessThan:As,lessThanOrEqual:Ns,greaterThan:Cs,greaterThanOrEqual:Ts,and:Os,or:$s,not:Rs,no:Is,isEmpty:Ls,isNotEmpty:js,exists:Ms,doesNotExist:Ps,contains:Fs,doesNotContain:Bs,startsWith:_s,endsWith:Vs,between:qs,matches:Hs,has:Us,doesNotHave:Ws},Js=Fn({value:Mn().describe("String literal value")}).strict(),Zs=Fn({value:Dn().describe("Number literal value")}).strict(),Gs=Fn({value:Pn().describe("Boolean literal value")}).strict(),Xs=Fn({left:_n().describe("Left operand"),right:_n().describe("Right operand")}).strict(),Ys={stringLiteral:new class extends Hn{constructor(){super(...arguments),this.name="stringLiteral",this.category="Special",this.syntax="\"string\" or 'string'",this.description="String literals with template interpolation support",this.outputType="String",this.inputSchema=Js,this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid){const e=this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions);return this.trackSimple(t,n,0),e}let s=e.value;(s.includes("${")||s.includes("$"))&&(s=this.interpolateString(s,t));const i=this.success(s,"string");return this.trackSimple(t,n,1,s),i}catch(e){return this.trackSimple(t,n,0),this.failure("StringEvaluationError","runtime-error","String literal evaluation failed: "+(e instanceof Error?e.message:e+""),"STRING_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid string literal input",["Provide a value parameter","Ensure value is a string"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}interpolateString(t,e){let n=t.replace(/\$\{([^}]+)\}/g,(t,n)=>{try{const t=this.resolveExpression(n.trim(),e);return void 0!==t?t+"":""}catch(t){return""}});return n=n.replace(/\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g,(t,n)=>{try{const t=this.resolveVariable(n,e);return void 0!==t?t+"":""}catch(t){return""}}),n}resolveExpression(t,e){if(t.includes(".")){const n=t.split(".");let r=this.resolveVariable(n[0],e);for(let t=1;n.length>t&&null!=r;t++)r=r[n[t]];return r}return this.resolveVariable(t,e)}resolveVariable(t,e){return"me"===t&&e.me?e.me:"you"===t&&e.you?e.you:"it"===t&&e.it?e.it:"result"===t&&e.result?e.result:e.locals?.has(t)?(Lt(t,e),e.locals.get(t)):e.globals?.has(t)?e.globals.get(t):void 0}},numberLiteral:new class extends Hn{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=Zs,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);return r.isValid?Number.isFinite(e.value)?(this.trackSimple(t,n,1,e.value),this.success(e.value,"number")):(this.trackSimple(t,n,0),this.failure("NumberValidationError","invalid-argument","Number literal must be finite","NUMBER_NOT_FINITE")):(this.trackSimple(t,n,0),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(e){return this.trackSimple(t,n,0),this.failure("NumberEvaluationError","runtime-error","Number literal evaluation failed: "+(e instanceof Error?e.message:e+""),"NUMBER_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?Number.isFinite(e.data.value)?this.validationSuccess():this.validationFailure("invalid-argument","Number literal value must be finite",["Use finite numbers only","Avoid Infinity and NaN values"]):this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid number literal input",["Provide a value parameter","Ensure value is a number"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},booleanLiteral:new class extends Hn{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=Gs,this.outputType="Boolean",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);return r.isValid?(this.trackSimple(t,n,1,e.value),this.success(e.value,"boolean")):(this.trackSimple(t,n,0),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(e){return this.trackSimple(t,n,0),this.failure("BooleanEvaluationError","runtime-error","Boolean literal evaluation failed: "+(e instanceof Error?e.message:e+""),"BOOLEAN_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid boolean literal input",["Provide a value parameter","Ensure value is a boolean"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},addition:new class extends Hn{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=Xs,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return this.trackSimple(t,n,0),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions);const s=as(e.left,"left operand")+as(e.right,"right operand");return this.trackSimple(t,n,1,s),this.success(s,"number")}catch(e){return this.trackSimple(t,n,0),this.failure("AdditionError","runtime-error","Addition failed: "+(e instanceof Error?e.message:e+""),"ADDITION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid addition input",["Provide left and right operands"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},stringConcatenation:new class extends Hn{constructor(){super(...arguments),this.name="stringConcatenation",this.category="Special",this.syntax="left + right (string concatenation)",this.description="Concatenation of two values into a string",this.inputSchema=Xs,this.outputType="String",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return this.trackSimple(t,n,0),this.failure("ValidationError","validation-error",r.errors[0]?.message||"Invalid input","STRING_CONCATENATION_VALIDATION_FAILED",r.suggestions);const s=this.convertToString(e.left)+this.convertToString(e.right);return this.trackSimple(t,n,1,s),this.success(s,"string")}catch(e){return this.trackSimple(t,n,0),this.failure("StringConcatenationError","runtime-error",e instanceof Error?e.message:"String concatenation failed","STRING_CONCATENATION_ERROR",["Check that operands can be converted to strings"])}}validate(t){const e=Xs.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid string concatenation input",["Provide left and right operands for concatenation"])}convertToString(t){if(null===t)return"null";if(void 0===t)return"undefined";if(un(t))return t;if(hn(t))return""+t;if(fn(t))return""+t;if(t instanceof Date)return""+t;try{return t+""}catch{return"[object Object]"}}},multiplication:new class extends Hn{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=Xs,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return this.trackSimple(t,n,0),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions);const s=as(e.left,"left operand")*as(e.right,"right operand");return this.trackSimple(t,n,1,s),this.success(s,"number")}catch(e){return this.trackSimple(t,n,0),this.failure("MultiplicationError","runtime-error","Multiplication failed: "+(e instanceof Error?e.message:e+""),"MULTIPLICATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid multiplication input",["Provide left and right operands"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}};function Ks(){return Kr(es,zs,Ys)}class Qs{constructor(t){this.observer=null,this.initialized=0,this.runtime=t}init(){"undefined"!=typeof document&&(this.initialized||(this.initialized=1,this.scanDocument(),this.observer=new MutationObserver(t=>{for(const e of t)"childList"===e.type?e.addedNodes.forEach(t=>{t.nodeType===Node.ELEMENT_NODE&&(this.processElement(t),this.scanElement(t))}):"attributes"===e.type&&"_"===e.attributeName&&this.processElement(e.target)}),this.observer.observe(document.body,{childList:1,subtree:1,attributes:1,attributeFilter:["_"]})))}destroy(){this.observer&&(this.observer.disconnect(),this.observer=null),this.initialized=0}reset(){this.destroy()}scanAndProcessAll(){this.scanDocument()}scanDocument(){document.body&&this.scanElement(document.body)}scanElement(t){t.hasAttribute("_")&&this.processElement(t),t.querySelectorAll("[_]").forEach(t=>this.processElement(t))}processElement(t){const e=t.getAttribute("_");if(!e)return;const n=rn(t);this.runtime.execute(e,n).catch(n=>{console.error('[HyperFixi] Error executing _="" attribute:',n),console.error("Element:",t),console.error("Code:",e)})}}function ti(t,e,n,r,s,i){function o(t){if(void 0!==t&&"function"!=typeof t)throw new TypeError("Function expected");return t}for(var a,c=r.kind,l="getter"===c?"get":"setter"===c?"set":"value",u=!e&&t?r.static?t:t.prototype:null,h=e||(u?Object.getOwnPropertyDescriptor(u,r.name):{}),f=0,d=n.length-1;d>=0;d--){var p={};for(var m in r)p[m]="access"===m?{}:r[m];for(var m in r.access)p.access[m]=r.access[m];p.addInitializer=function(t){if(f)throw new TypeError("Cannot add initializers after decoration has completed");i.push(o(t||null))};var y=(0,n[d])("accessor"===c?{get:h.get,set:h.set}:h[l],p);if("accessor"===c){if(void 0===y)continue;if(null===y||"object"!=typeof y)throw new TypeError("Object expected");(a=o(y.get))&&(h.get=a),(a=o(y.set))&&(h.set=a),(a=o(y.init))&&s.unshift(a)}else(a=o(y))&&("field"===c?s.unshift(a):h[l]=a)}u&&Object.defineProperty(u,r.name,h),f=1}function ei(t,e,n){for(var r=arguments.length>2,s=0;e.length>s;s++)n=r?e[s].call(t,n):e[s].call(t);return r?n:void 0}function ni(t,e,n){return"symbol"==typeof e&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:1,value:n?"".concat(n," ",e):e})}function ri(t){const e=t.trim();return e.startsWith("[@")&&e.endsWith("]")||e.startsWith("@")?1:0}function si(t){const e=t.trim();if(e.startsWith("[@")&&e.endsWith("]")){const t=e.slice(2,-1),n=t.indexOf("=");if(-1===n)return{name:t.trim()};const r=t.slice(0,n).trim();let s=t.slice(n+1).trim();return(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),{name:r,value:s}}if(e.startsWith("@"))return{name:e.substring(1).trim()};throw Error("Invalid attribute syntax: "+t)}function ii(t,e){for(const n of t)e(n);return t}function oi(t,e,n){for(const r of t)for(const t of e)n(r,t);return t}function ai(t,e,n){const r=t.hasAttribute(e);void 0!==n?r&&t.getAttribute(e)===n?t.removeAttribute(e):t.setAttribute(e,n):r?t.removeAttribute(e):t.setAttribute(e,"")}function ci(t){if(!t)return[];if("string"==typeof t)return t.trim().split(/[\s,]+/).map(t=>{const e=t.trim();return e.startsWith(".")?e.substring(1):e}).filter(t=>t.length>0&&ui(t));if(Array.isArray(t))return t.map(t=>{const e=(t+"").trim();return e.startsWith(".")?e.substring(1):e}).filter(t=>t.length>0&&ui(t));const e=(t+"").trim(),n=e.startsWith(".")?e.substring(1):e;return n.length>0&&ui(n)?[n]:[]}function li(t){const e=t.trim();return/^\{[^}]+\}$/.test(e)}function ui(t){if(!t||0===t.trim().length)return 0;const e=t.trim();return li(e)?1:/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(e)}function hi(t,e){return t.map(t=>{if(li(t)){const n=function(t){const e=t.trim(),n=e.match(/^\{(.+)\}$/);return n?n[1].trim():e}(t),r=e.locals.get(n)??e.globals.get(n);return null!=r?r+"":(at(`Dynamic class variable '${n}' not found in context`),"")}return t}).filter(t=>t.length>0)}"function"==typeof SuppressedError&&SuppressedError;const fi=Symbol("command:name"),di=Symbol("command:category"),pi=Symbol("command:metadata");function mi(t){return function(e,n){const r=e;r[fi]=t.name,r[di]=t.category,Object.defineProperty(e.prototype,"name",{value:t.name,writable:0,enumerable:1})}}function yi(t){return function(e,n){const r=e,s=r[di];if(!s)throw Error("@meta decorator requires @command decorator to be applied first on "+e.name);const i={description:t.description,syntax:t.syntax,examples:t.examples,category:s,sideEffects:t.sideEffects,deprecated:t.deprecated,deprecationMessage:t.deprecationMessage,aliases:t.aliases,relatedCommands:t.relatedCommands,isBlocking:t.isBlocking??0,hasBody:t.hasBody??0,version:"1.0.0",compatibility:t.compatibility};r[pi]=i,Object.defineProperty(e,"metadata",{value:i,writable:0,enumerable:1,configurable:0}),Object.defineProperty(e.prototype,"metadata",{get:()=>i,enumerable:1,configurable:0})}}function gi(t){return()=>new t}function vi(t,e){return e}function bi(t,e,n){if(sn(t))return t;if(!t){const t=e.me;if(!t)throw Error(vi(0,"No target element \u2014 provide explicit target or ensure context.me is set"));return wi(t)}if("string"==typeof t){const n=t.trim();if("me"===n){if(!e.me)throw Error(vi(0,'Context reference "me" is not available'));return wi(e.me)}if("it"===n){if(!sn(e.it))throw Error(vi(0,'Context reference "it" is not an HTMLElement'));return e.it}if("you"===n){if(!e.you)throw Error(vi(0,'Context reference "you" is not available'));return wi(e.you)}const r=e.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!r)throw Error(vi(0,"DOM not available \u2014 cannot resolve element selector"));const s=r.querySelector(n);if(!s)throw Error(vi(0,"Element not found with selector: "+n));if(!sn(s))throw Error(vi(0,"Element found but is not an HTMLElement: "+n));return s}throw Error(vi(0,"Invalid target type: "+typeof t))}function wi(t){if(sn(t))return t;throw Error("Value is not an HTMLElement")}function Ei(t,e,n){switch(t.toLowerCase()){case"my":case"me":if(!e.me)throw Error(vi(0,'No "me" element in context'));if(!sn(e.me))throw Error(vi(0,"context.me is not an HTMLElement"));return e.me;case"its":case"it":if(!e.it)throw Error(vi(0,'No "it" value in context'));if(!sn(e.it))throw Error(vi(0,"context.it is not an HTMLElement"));return e.it;case"your":case"you":if(!e.you)throw Error(vi(0,'No "you" element in context'));if(!sn(e.you))throw Error(vi(0,"context.you is not an HTMLElement"));return e.you;default:throw Error(vi(0,"Unknown possessive: "+t))}}const xi=["on","from","to","in","with","at"];async function ki(t,e,n,r,s={},i){let o=t;if(s.filterPrepositions&&t&&(o=t.filter(t=>{const e=t;return"identifier"===e?.type&&"string"==typeof e.name?!xi.includes(e.name.toLowerCase()):1})),(!o||0===o.length)&&s.fallbackModifierKey&&i){const t=i[s.fallbackModifierKey];t&&(o=[t])}if(!o||0===o.length){if(!n.me)throw Error(r+" command: no target specified and context.me is null");if(!sn(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}const a=[];for(const t of o){const s=await e.evaluate(t,n);if(""!==s&&("string"!=typeof s||""!==s.trim()))if(sn(s))a.push(s);else if(on(s)){const t=Array.from(s).filter(sn);a.push(...t)}else if(Array.isArray(s)){const t=s.filter(sn);a.push(...t)}else{if("string"!=typeof s){if(null==s)continue;throw Error(`Invalid ${r} target: expected HTMLElement or CSS selector, got ${typeof s}`)}try{let t=s;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const e=n.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!e)throw Error("DOM not available - cannot resolve element selector");const r=e.querySelectorAll(t),i=Array.from(r).filter(sn);a.push(...i)}catch(t){throw Error(`Invalid CSS selector: "${s}" - ${t instanceof Error?t.message:t+""}`)}}}if(0===a.length){if(!n.me)throw Error(r+" command: no target specified and context.me is null");if(!sn(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}return a}function Si(t){return"string"==typeof t&&t.trim().startsWith("*")}function Ai(t){const e=function(t){const e=t.trim();if(!e.startsWith("*"))return null;const n=e.substring(1).trim();return n?{property:n}:null}(t);if(!e)return null;const n=e.property.toLowerCase();return["display","visibility","opacity"].includes(n)?n:null}function Ni(t,e,n){t.style.setProperty(e,n)}const Ci=["dialog","details","summary","select"];function Ti(t){return t&&"object"==typeof t?"string"==typeof t.selector?t.selector:"string"==typeof t.value?t.value:"string"==typeof t.name?t.name:null:null}async function Oi(t,e,n){return function(t){if(!t||"object"!=typeof t)return 0;const e=t.type;if("selector"!==e&&"cssSelector"!==e&&"classSelector"!==e)return 0;const n=Ti(t);return"string"==typeof n&&n.startsWith(".")}(t)||function(t){if(!t||"object"!=typeof t)return 0;const e=t.type;if("selector"!==e&&"cssSelector"!==e&&"cssProperty"!==e)return 0;const n=Ti(t);return"string"==typeof n&&n.startsWith("*")}(t)?{value:Ti(t),extractedFromNode:1}:function(t){if(!t||"object"!=typeof t)return 0;if("attributeAccess"===t.type)return 1;if("selector"===t.type||"cssSelector"===t.type){const e=Ti(t);return"string"==typeof e&&e.startsWith("@")}return 0}(t)?{value:(r=t,"attributeAccess"===r.type?"@"+r.attributeName:Ti(r)),extractedFromNode:1}:{value:await e.evaluate(t,n),extractedFromNode:0};var r}class $i{async resolveTargets(t,e,n,r){return ki(t,e,n,this.mode,{filterPrepositions:1,fallbackModifierKey:this.preposition},r)}async evaluateFirst(t,e,n){return Oi(t,e,n)}parseClassNames(t){return ci(t)}isAttribute(t){return ri(t.trim())}isCSSProperty(t){return Si(t.trim())}validateTargets(t){return Array.isArray(t)&&function(t){return Array.isArray(t)&&t.length>0&&t.every(t=>sn(t))}(t)}validateType(t,e){return function(t,e){return"string"==typeof t&&e.includes(t)}(t,e)}validateStringArray(t,e=1){return Array.isArray(t)&&function(t,e=1){return Array.isArray(t)&&t.length>=e&&t.every(t=>"string"==typeof t&&t.length>0)}(t,e)}}let Ri=(()=>{let t,e,n=[yi({description:"Add CSS classes, attributes, or styles to elements",syntax:"add <classes|@attr|{styles}> [to <target>]",examples:["add .active to me",'add "active selected" to <button/>',"add .highlighted to #modal",'add [@data-test="value"] to #element'],sideEffects:["dom-mutation"]}),mi({name:"add",category:"dom"})],r=[],s=$i;return e=class extends s{constructor(){super(...arguments),this.mode="add",this.preposition="to"}async parseInput(t,e,n){if(!t.args||0===t.args.length)throw Error("add command requires an argument");const{value:r}=await this.evaluateFirst(t.args[0],e,n);if("object"==typeof r&&null!==r&&!Array.isArray(r))return{type:"styles",styles:r,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)};if("string"==typeof r){const s=r.trim();if(this.isAttribute(s)){const{name:r,value:i}=function(t){const e=si(t);return{name:e.name,value:e.value??""}}(s);return{type:"attribute",name:r,value:i,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}if(this.isCSSProperty(s)){const r=s.substring(1).trim();if(2>t.args.length)throw Error("add *property requires a value argument");const i=await e.evaluate(t.args[1],n);return{type:"styles",styles:{[r]:i+""},targets:await this.resolveTargets(t.args.slice(2),e,n,t.modifiers)}}}const s=this.parseClassNames(r);if(0===s.length)throw Error("add command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}async execute(t,e){switch(t.type){case"classes":{const n=hi(t.classes,e);n.length>0&&oi(t.targets,n,(t,e)=>{t.classList.contains(e)||t.classList.add(e)});break}case"attribute":n=t.name,r=t.value,ii(t.targets,t=>{t.setAttribute(n,r)});break;case"styles":oi(t.targets,Object.entries(t.styles),(t,[e,n])=>{t.style.setProperty(e,n)})}var n,r}validate(t){if("object"!=typeof t||null===t)return 0;const e=t;if(!this.validateType(e.type,["classes","attribute","styles"]))return 0;if(!this.validateTargets(e.targets))return 0;if("classes"===e.type){if(!this.validateStringArray(t.classes,1))return 0}else if("attribute"===e.type){if("string"!=typeof t.name||0===t.name.length)return 0;if("string"!=typeof t.value)return 0}else if("styles"===e.type){const e=t;if("object"!=typeof e.styles||null===e.styles)return 0;if(Array.isArray(e.styles))return 0;const n=e.styles;if(0===Object.keys(n).length)return 0;if(!Object.values(n).every(t=>"string"==typeof t))return 0}return 1}},ni(e,"AddCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;ti(null,t={value:e},n,{kind:"class",name:e.name,metadata:i},null,r),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:i}),ei(e,r)})(),e})();const Li=gi(Ri);function Ii(t){return t.parentNode?(t.remove(),1):0}let ji=(()=>{let t,e,n=[yi({description:"Remove CSS classes, attributes, styles, or elements from the DOM",syntax:"remove <classes|@attr|*prop|element> [from <target>]",examples:["remove .active from me",'remove "active selected" from <button/>',"remove .highlighted from #modal","remove me","remove closest .item"],sideEffects:["dom-mutation"]}),mi({name:"remove",category:"dom"})],r=[],s=$i;return e=class extends s{constructor(){super(...arguments),this.mode="remove",this.preposition="from"}async parseInput(t,e,n){if(!t.args||0===t.args.length)throw Error("remove command requires an argument");const{value:r}=await this.evaluateFirst(t.args[0],e,n);if(sn(r))return{type:"element",targets:[r]};if(Array.isArray(r)&&r.length>0&&sn(r[0]))return{type:"element",targets:r.filter(t=>sn(t))};if("string"==typeof r){const s=r.trim();if(this.isAttribute(s))return{type:"attribute",name:si(s).name,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)};if(this.isCSSProperty(s))return{type:"styles",properties:[s.substring(1).trim()],targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}const s=this.parseClassNames(r);if(0===s.length)throw Error("remove command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}execute(t,e){switch(t.type){case"classes":{const n=hi(t.classes,e);n.length>0&&oi(t.targets,n,(t,e)=>{t.classList.remove(e)});break}case"attribute":n=t.name,ii(t.targets,t=>{t.removeAttribute(n)});break;case"styles":oi(t.targets,t.properties,(t,e)=>{t.style.removeProperty(e)});break;case"element":for(const e of t.targets)Ii(e)}var n}validate(t){if("object"!=typeof t||null===t)return 0;const e=t;if(!this.validateType(e.type,["classes","attribute","styles","element"]))return 0;if(!this.validateTargets(e.targets))return 0;if("classes"===e.type){if(!this.validateStringArray(t.classes,1))return 0}else if("attribute"===e.type){if("string"!=typeof t.name||0===t.name.length)return 0}else if("styles"===e.type&&!this.validateStringArray(t.properties,1))return 0;return 1}},ni(e,"RemoveCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;ti(null,t={value:e},n,{kind:"class",name:e.name,metadata:i},null,r),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:i}),ei(e,r)})(),e})();const Mi=gi(ji);function Di(t){const e=t.trim().match(/^(\d+(?:\.\d+)?)\s*(s|ms|sec|seconds?|milliseconds?)?$/i);if(!e)return null;const n=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();return"ms"===r||"millisecond"===r||"milliseconds"===r?{number:n,milliseconds:Math.floor(n)}:"s"===r||"sec"===r||"second"===r||"seconds"===r?{number:n,milliseconds:Math.floor(1e3*n)}:null}function Pi(t){if("number"==typeof t){if(0>t)throw Error("Duration must be >= 0");return Math.floor(t)}if("string"==typeof t){const e=Di(t);if(!e)throw Error(`Invalid duration format: "${t}"`);return e.milliseconds}throw Error("Invalid duration type: "+typeof t)}function Fi(t){return 0===t.length?[]:"SUMMARY"===t[0].tagName?t.map(t=>t.closest("details")).filter(t=>null!==t):t}function Bi(t,e,n){return()=>{"class"===e?t.classList.toggle(n):"attribute"===e&&ai(t,n)}}function _i(t,e,n,r){const s=Bi(t,e,n),i=setTimeout(s,r);return()=>{clearTimeout(i)}}function Vi(t,e,n,r){const s=Bi(t,e,n),i=()=>{s(),t.removeEventListener(r,i)};return t.addEventListener(r,i,{once:1}),()=>{t.removeEventListener(r,i)}}function qi(t,e,n){if(e.startsWith("@")){const r=e.substring(1);return void(0==n?t.removeAttribute(r):t.setAttribute(r,1==n?"":n+""))}const r=n+"";switch(e){case"textContent":return void(t.textContent=r);case"innerHTML":return void(t.innerHTML=r);case"innerText":return void(t.innerText=r);case"id":return void(t.id=r);case"className":return void(t.className=r);case"value":return void("value"in t&&(t.value=r));case"checked":return void("checked"in t&&(t.checked=!!n))}if(e.includes(".")){const r=e.split(".");let s=t;for(let t=0;r.length-1>t;t++)if(s=s[r[t]],null==s)return;return void(s[r[r.length-1]]=n)}if(e.includes("-")||e in t.style)t.style.setProperty(e,r);else try{t[e]=n}catch(t){if(!(t instanceof TypeError&&(t.message.includes("only a getter")||t.message.includes("read only"))))throw Error(`Cannot set property '${e}': ${t instanceof Error?t.message:"Unknown error"}`)}}const Hi=/^the\s+(.+?)\s+of\s+(.+)$/i,Ui=new Set(["disabled","checked","hidden","readOnly","readonly","required","multiple","selected","autofocus","autoplay","controls","loop","muted","open","reversed","async","defer","noValidate","novalidate","formNoValidate","formnovalidate","draggable","spellcheck","contentEditable"]);function Wi(t){return"string"==typeof t&&Hi.test(t)}function zi(t,e){const n=t.match(Hi);if(!n)return null;try{return{element:bi(n[2].trim(),e),property:n[1].trim()}}catch{return null}}async function Ji(t,e,n){if(function(t){return t&&"object"==typeof t?"propertyOfExpression"===t.type&&"object"==typeof t.property&&null!==t.property:0}(t))return async function(t,e,n){const r=t.property?.name;if(!r)return null;let s=await e.evaluate(t.target,n);return Array.isArray(s)&&(s=s[0]),sn(s)?{element:s,property:r}:null}(t,e,n);if(function(t){return t&&"object"==typeof t?"propertyAccess"!==t.type?0:"string"==typeof t.property||"object"==typeof t.property&&null!==t.property&&"string"==typeof t.property.name:0}(t))return async function(t,e,n){const r="string"==typeof t.property?t.property:t.property?.name;if(!r)return null;let s=await e.evaluate(t.object,n);return Array.isArray(s)&&(s=s[0]),sn(s)?{element:s,property:r}:null}(t,e,n);const r=t;if("possessiveExpression"===r?.type||"memberExpression"===r?.type){const t=r.object,s=r.property;let i=await e.evaluate(t,n);if(Array.isArray(i)&&(i=i[0]),!sn(i))return null;const o=s?.name||s?.value;return o?{element:i,property:o}:null}return null}function Zi(t,e){const{element:n,property:r}=t;r.startsWith("*")?Ni(n,r.substring(1),e+""):qi(n,r,e)}async function Gi(t,e,n){let r,s;if(t?.for){const s=await e.evaluate(t.for,n);r="number"==typeof s?s:"string"==typeof s?function(t,e=300){if("number"==typeof t)return Math.max(0,Math.floor(t));if("string"==typeof t){const n=Di(t);return n?n.milliseconds:e}return e}(s):void 0}if(t?.until){const r=await e.evaluate(t.until,n);"string"==typeof r&&(s=r)}return{duration:r,untilEvent:s}}const Xi=gi((()=>{let t,e,n=[yi({description:"Toggle classes, attributes, or interactive elements",syntax:["toggle <class> [on <target>]","toggle @attr","toggle <element> [as modal]","toggle <expr> for <duration>"],examples:["toggle .active on me","toggle @disabled","toggle #myDialog as modal","toggle .loading for 2s"],sideEffects:["dom-mutation"]}),mi({name:"toggle",category:"dom"})],r=[];return e=class{async parseInput(t,e,n){if(!t.args?.length)throw Error("toggle command requires an argument");let r=0;if(function(t){if(!t||"asExpression"!==t.type)return 0;const e=t.targetType,n="string"==typeof e?e:e?.name;return"string"==typeof n&&"modal"===n.toLowerCase()}(t.args[0])){r=1;const e=t.args[0].expression;t={...t,args:[e,...t.args.slice(1)]}}const s=t.args[0],i=s?.name;if("between"===i&&t.args.length>=4){const{duration:r,untilEvent:s}=await Gi(t.modifiers,e,n),i=async t=>{const r=t;return"selector"===r?.type?r.value:e.evaluate(t,n)},o=await i(t.args[1]),a=await i(t.args[3]),c=[];for(let e=4;t.args.length>e;e++){const n=t.args[e]?.name;"on"!==n&&"from"!==n&&c.push(t.args[e])}const l={filterPrepositions:1,fallbackModifierKey:"on"},u=await ki(c,e,n,"toggle",l,t.modifiers);return{type:"classes-between",classA:(o+"").replace(/^\./,""),classB:(a+"").replace(/^\./,""),targets:u,duration:r,untilEvent:s}}const o=await Ji(s,e,n);if(o)return{type:"property",target:o};if("selector"===s.type&&"string"==typeof s.value&&s.value.startsWith("*")){let r=s.value,i=1;if("*"===r&&t.args.length>1&&"identifier"===t.args[1].type&&(r="*"+t.args[1].name,i=2),"*"===r&&t.modifiers?.on){const s=t.modifiers.on?.name;if(s&&["display","visibility","opacity"].includes(s)){r="*"+s;const{duration:i,untilEvent:o}=await Gi(t.modifiers,e,n),a=Ai(r);if(a){const t=n.me;return{type:"css-property",property:a,targets:t?[t]:[],duration:i,untilEvent:o}}}}const o=Ai(r);if(o){const{duration:r,untilEvent:s}=await Gi(t.modifiers,e,n),a={filterPrepositions:1,fallbackModifierKey:"on"};return{type:"css-property",property:o,targets:await ki(t.args.slice(i),e,n,"toggle",a,t.modifiers),duration:r,untilEvent:s}}}const{duration:a,untilEvent:c}=await Gi(t.modifiers,e,n),{value:l}=await Oi(s,e,n);if(Wi(l)){const t=zi(l,n);if(t)return{type:"property",target:t}}const{type:u,expression:h}=function(t,e){const n=e?.name,r=function(t){if(!t||"object"!=typeof t)return 0;if("identifier"!==t.type)return 0;const e=t.name;return"string"==typeof e&&function(t){if("string"!=typeof t)return 0;const e=t.toLowerCase();return Ci.includes(e)}(e)}(e);if(sn(t)||Array.isArray(t)&&t.every(t=>sn(t)))return{type:"element",expression:""};if(r&&n)return{type:"element",expression:n};if("string"==typeof t){const e=t.trim();return e.startsWith("@")||e.startsWith("[@")?{type:"attribute",expression:e}:e.startsWith("*")?{type:"css-property",expression:e}:e.startsWith(".")?{type:"class",expression:e}:e.startsWith("#")||function(t){if("string"!=typeof t)return 0;const e=t.toLowerCase();return Ci.some(t=>e.includes(t))}(e)?{type:"element",expression:e}:{type:"class",expression:e}}return{type:"class",expression:""}}(l,s),f={filterPrepositions:1,fallbackModifierKey:"on"};switch(u){case"attribute":{const{name:r,value:s}=si(h);return{type:"attribute",name:r,value:s,targets:await ki(t.args.slice(1),e,n,"toggle",f,t.modifiers),duration:a,untilEvent:c}}case"css-property":{const r=Ai(h);if(!r)throw Error("Invalid CSS property: "+h);return{type:"css-property",property:r,targets:await ki(t.args.slice(1),e,n,"toggle",f,t.modifiers)}}case"element":{let i;if(sn(l))i=[l];else if(Array.isArray(l)&&l.every(t=>sn(t)))i=l;else if(h){const t=document.querySelectorAll(h);i=Array.from(t).filter(t=>sn(t))}else i=await ki([s],e,n,"toggle",f,t.modifiers);const o=function(t){if(0===t.length)return null;const e=t[0].tagName;if(!t.every(t=>t.tagName===e))return null;switch(e){case"DIALOG":return"dialog";case"DETAILS":return"details";case"SELECT":return"select";case"SUMMARY":return t.map(t=>t.closest("details")).filter(t=>null!==t).length>0?"details":null;default:return null}}(i);if("dialog"===o){const s=r?"modal":await async function(t,e,n,r){if(e?.as){const t=await n.evaluate(e.as,r);if("string"==typeof t&&"modal"===t.toLowerCase())return"modal"}if(t.length>=2){const e=await n.evaluate(t[1],r);if("string"==typeof e){const s=e.toLowerCase();if("modal"===s||"as modal"===s)return"modal";if("as"===s&&t.length>=3){const e=await n.evaluate(t[2],r);if("string"==typeof e&&"modal"===e.toLowerCase())return"modal"}}}return"non-modal"}(t.args,t.modifiers,e,n);return{type:"dialog",mode:s,targets:i}}return"details"===o?{type:"details",targets:Fi(i)}:"select"===o?{type:"select",targets:i}:{type:"classes",classes:ci(h),targets:i,duration:a,untilEvent:c}}default:{const r=ci(h||l);if(!r.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:r,targets:await ki(t.args.slice(1),e,n,"toggle",f,t.modifiers),duration:a,untilEvent:c}}}}async execute(t,e){switch(t.type){case"classes":{const n=hi(t.classes,e);if(0===n.length)return[...t.targets];if(oi(t.targets,n,(t,e)=>{t.classList.toggle(e)}),(t.duration||t.untilEvent)&&n.length)for(const e of t.targets)t.duration&&_i(e,"class",n[0],t.duration),t.untilEvent&&Vi(e,"class",n[0],t.untilEvent);return[...t.targets]}case"attribute":if(n=t.name,r=t.value,ii(t.targets,t=>{ai(t,n,r)}),t.duration||t.untilEvent)for(const e of t.targets)t.duration&&_i(e,"attribute",t.name,t.duration),t.untilEvent&&Vi(e,"attribute",t.name,t.untilEvent);return[...t.targets];case"css-property":return ii(t.targets,e=>function(t,e){const n=window.getComputedStyle(t);switch(e){case"display":"none"===n.display?(t.style.display=t.dataset.previousDisplay||"block",delete t.dataset.previousDisplay):(t.dataset.previousDisplay=n.display,t.style.display="none");break;case"visibility":t.style.visibility="hidden"===n.visibility?"visible":"hidden";break;case"opacity":t.style.opacity=0===parseFloat(n.opacity)?"1":"0"}}(e,t.property));case"property":return function(t){const e=function(t){const{element:e,property:n}=t;return n.startsWith("*")?function(t,e){return window.getComputedStyle(t).getPropertyValue(e)}(e,n.substring(1)):En(e,n)}(t),n=t.property,r=n.startsWith("@")?n.substring(1):n;if("boolean"==typeof e||Ui.has(r)||Ui.has(r.toLowerCase())){const n=!e;return Zi(t,n),n}if("number"==typeof e){const n=0===e?1:0;return Zi(t,n),n}if("string"==typeof e){const r="__ht_"+n,s=t.element[r];return""===e&&void 0!==s?(Zi(t,s),s):(t.element[r]=e,Zi(t,""),"")}Zi(t,!e)}(t.target),[t.target.element];case"dialog":return ii(t.targets,e=>{return r=t.mode,void((n=e).open?n.close():"modal"===r?n.showModal():n.show());var n,r});case"details":return ii(t.targets,t=>{var e;(e=t).open=!e.open});case"select":return ii(t.targets,t=>function(t){if(document.activeElement===t)t.blur();else{if(t.focus(),"showPicker"in t&&"function"==typeof t.showPicker)try{return void t.showPicker()}catch{}const e=new MouseEvent("click",{view:window,bubbles:1,cancelable:1});t.dispatchEvent(e)}}(t));case"classes-between":for(const e of t.targets){const n=e.classList.contains(t.classA),r=e.classList.contains(t.classB);n?(e.classList.remove(t.classA),e.classList.add(t.classB)):r?(e.classList.remove(t.classB),e.classList.add(t.classA)):e.classList.add(t.classA)}if(t.duration||t.untilEvent)for(const e of t.targets)t.duration&&_i(e,"class",t.classA,t.duration),t.untilEvent&&Vi(e,"class",t.classA,t.untilEvent);return[...t.targets]}var n,r}},ni(e,"ToggleCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),ei(e,r)})(),e})());class Yi{async parseInput(t,e,n){const{targets:r}=await async function(t,e,n,r){return{targets:await ki(t.args,e,n,r)}}(t,e,n,this.mode);return{targets:r,mode:this.mode,defaultDisplay:"show"===this.mode?"block":void 0}}validate(t){if("object"!=typeof t||null===t)return 0;const e=t;return Array.isArray(e.targets)&&e.targets.every(t=>sn(t))?"show"!==e.mode&&"hide"!==e.mode||"show"===e.mode&&"string"!=typeof e.defaultDisplay?0:1:0}showElement(t,e="block"){const n=t.dataset.originalDisplay;void 0!==n?(t.style.display=n||e,delete t.dataset.originalDisplay):"none"===t.style.display&&(t.style.display=e),t.classList.add("show")}hideElement(t){if(!t.dataset.originalDisplay){const e=t.style.display;t.dataset.originalDisplay="none"===e?"":e}t.style.display="none",t.classList.remove("show")}}let Ki=(()=>{let t,e,n=[yi({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"]}),mi({name:"show",category:"dom"})],r=[],s=Yi;return e=class extends s{constructor(){super(...arguments),this.mode="show"}async execute(t,e){const n=t.defaultDisplay||"block";for(const e of t.targets)this.showElement(e,n)}validate(t){if("object"!=typeof t||null===t)return 0;const e=t;return Array.isArray(e.targets)&&e.targets.every(t=>sn(t))?"string"!=typeof e.defaultDisplay?0:1:0}},ni(e,"ShowCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;ti(null,t={value:e},n,{kind:"class",name:e.name,metadata:i},null,r),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:i}),ei(e,r)})(),e})();const Qi=gi(Ki);let to=(()=>{let t,e,n=[yi({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"]}),mi({name:"hide",category:"dom"})],r=[],s=Yi;return e=class extends s{constructor(){super(...arguments),this.mode="hide"}async execute(t,e){for(const e of t.targets)this.hideElement(e)}validate(t){if("object"!=typeof t||null===t)return 0;const e=t;return Array.isArray(e.targets)&&e.targets.every(t=>sn(t))?1:0}},ni(e,"HideCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;ti(null,t={value:e},n,{kind:"class",name:e.name,metadata:i},null,r),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:i}),ei(e,r)})(),e})();const eo=gi(to),no=gi((()=>{let t,e,n=[yi({description:"Insert content into elements or properties",syntax:["put <value> into <target>","put <value> before <target>","put <value> after <target>"],examples:['put "Hello World" into me',"put <div>Content</div> before #target","put value into #elem's innerHTML"],sideEffects:["dom-mutation"]}),mi({name:"put",category:"dom"})],r=[];return e=class{async parseInput(t,e,n){if(!t.args?.length)throw Error("put requires arguments");const r=t=>t?.type||"unknown",s=["into","before","after","at","at start of","at end of"];let i=-1,o=null;for(let e=0;t.args.length>e;e++){const n=t.args[e],a=r(n),c="literal"===a?n.value:n.name;if(("literal"===a||"identifier"===a)&&s.includes(c)){i=e,o=c;break}}let a=null,c=null;if(-1===i){const e=s.find(e=>t.modifiers[e]);if(e)a=t.args[0],o=e,c=t.modifiers[e];else if(3>t.args.length){if(2>t.args.length)throw Error("put requires content and position");a=t.args[0],o=t.args[1]?.value||t.args[1]?.name||"into"}else a=t.args[0],o=t.args[1]?.value||t.args[1]?.name||null,c=t.args[2]}else a=t.args.slice(0,i)[0]||null,c=t.args.slice(i+1)[0]||null;if(!a)throw Error("put requires content");if(!o)throw Error("put requires position keyword");const l=await e.evaluate(a,n),u=this.mapPosition(o);let h,f,d=null;if(c){const t=r(c),s=await Ji(c,e,n);if(s)return{value:l,targets:[s.element],position:"replace",memberPath:s.property};if("memberExpression"===t){const t=c.object,r=c.property;if("selector"===t?.type)d=t.value;else if("identifier"===t?.type){const s=t.name;if("my"===s||"me"===s||"I"===s){if(n.me&&r?.name)return{value:l,targets:[n.me],position:"replace",memberPath:r.name}}else if("its"===s||"it"===s){const t=await e.evaluate(c,n);"string"==typeof t&&(d=t)}else d=s}if(d&&r?.name)h=r.name;else if(!d&&!h){const t=await e.evaluate(c,n);"string"==typeof t&&(d=t)}}else if("identifier"===t&&"me"===c.name)d=null;else if("selector"===t||"cssSelector"===t)d=c.value||c.selector;else if("literal"===t){const t=c.value;if("string"==typeof t&&Wi(t)){const e=zi(t,n);if(e)return{value:l,targets:[e.element],position:"replace",memberPath:e.property}}"string"==typeof t&&this.looksLikeCss(t)?d=t:f=t+""}else if("identifier"===t){const t=c.name;if(this.looksLikeCss(t))d=t;else{const r=await e.evaluate(c,n),s=this.resolveEvaluatedAsElements(r);if(s)return{value:l,targets:s,position:u,memberPath:h};f=t}}else{const t=await e.evaluate(c,n),r=this.resolveEvaluatedAsElements(t);if(r)return{value:l,targets:r,position:u,memberPath:h};"string"==typeof t&&(this.looksLikeCss(t)?d=t:f=t)}}return f?{value:l,targets:[],position:u,memberPath:h,variableName:f}:{value:l,targets:await this.resolveTargets(d,n),position:u,memberPath:h}}async execute(t,e){const{value:n,targets:r,position:s,memberPath:i,variableName:o}=t;if(o)return e.locals&&e.locals.set(o,n),e[o]=n,void Object.assign(e,{it:n});if(i)for(const t of r)this.setProperty(t,i,n);else for(const t of r){const e=this.parseValue(n);this.insertContent(t,e,s)}return r}mapPosition(t){switch(t){case"into":return"replace";case"before":return"beforebegin";case"after":return"afterend";case"at start of":return"afterbegin";case"at end of":return"beforeend";default:throw Error("Invalid position: "+t)}}async resolveTargets(t,e){if(!t||"me"===t){if(!e.me||!sn(e.me))throw Error("put: no target and context.me is null");return[e.me]}const n=Array.from(document.querySelectorAll(t)).filter(t=>sn(t));if(!n.length)throw Error(`No elements: "${t}"`);return n}parseValue(t){return sn(t)?t:null==t?"":t+""}insertContent(t,e,n){if("replace"!==n)if(sn(e)){const r=e;switch(n){case"beforebegin":t.parentElement?.insertBefore(r,t);break;case"afterbegin":t.insertBefore(r,t.firstChild);break;case"beforeend":t.appendChild(r);break;case"afterend":t.parentElement?.insertBefore(r,t.nextSibling)}}else e.includes("<")&&e.includes(">")?t.insertAdjacentHTML(n,e):t.insertAdjacentText(n,e);else sn(e)?(t.innerHTML="",t.appendChild(e)):e.includes("<")&&e.includes(">")?t.innerHTML=e:t.textContent=e}resolveEvaluatedAsElements(t){if(sn(t))return[t];if(Array.isArray(t)){const e=t.filter(sn);return e.length>0?e:null}if("undefined"!=typeof NodeList&&t instanceof NodeList){const e=Array.from(t).filter(sn);return e.length>0?e:null}return null}looksLikeCss(t){return t?/^[#.\[]/.test(t)||/[>+~\s]/.test(t)&&t.length>1?1:["div","span","p","a","button","input","form","ul","li","ol","table","tr","td","th","img","h1","h2","h3","h4","h5","h6","section","article","header","footer","nav","main","aside","dialog","label","select","option","textarea"].includes(t.toLowerCase()):0}setProperty(t,e,n){const r=e.split(".");let s=t;for(let t=0;r.length-1>t;t++){if(!s[r[t]])throw Error(`Property path "${e}" does not exist`);s=s[r[t]]}s[r[r.length-1]]=n}},ni(e,"PutCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),ei(e,r)})(),e})()),ro=gi((()=>{let t,e,n=[yi({description:"Set values to variables, attributes, or properties",syntax:["set <target> to <value>"],examples:['set myVar to "value"','set @data-theme to "dark"','set my innerHTML to "content"'],sideEffects:["state-mutation","dom-mutation"]}),mi({name:"set",category:"data"})],r=[];return e=class{async parseInput(t,e,n){if(!t.args?.length)throw Error("set command requires a target");const r=t.args[0],s=r?.name||r?.value,i=r?.scope,o=r?.type;if(o){const s=St.get(o);if(s)return{type:"node-write",node:r,value:await this.extractValue(t,e,n),writer:s}}const a=await this.resolveAttributeWriteTarget(r,t,e,n);if(a){const r=await this.extractValue(t,e,n);return{type:"attribute",elements:a.elements,name:a.name,value:r}}const c=await Ji(r,e,n);if(c){const r=await this.extractValue(t,e,n);if(c.property.startsWith("*")){const t=c.property.substring(1);return{type:"style",element:c.element,property:t,value:r+""}}return{type:"property",element:c.element,property:c.property,value:r}}if("memberExpression"===r?.type||"propertyAccess"===r?.type){const s=await this.tryParseMemberExpression(r,t,e,n);if(s)return s}let l;if(l="identifier"!==r?.type&&"variable"!==r?.type||"string"!=typeof s?await e.evaluate(r,n):s,function(t){if("object"!=typeof t||null===t||Array.isArray(t))return 0;if(sn(t)||t instanceof Node)return 0;const e=Object.getPrototypeOf(t);return e===Object.prototype||null===e}(l))return{type:"object-literal",properties:l,targets:await this.resolveTargets(t.modifiers.on,e,n)};if(Wi(l)){const r=zi(l,n);if(r){const s=await this.extractValue(t,e,n);return{type:"property",element:r.element,property:r.property,value:s}}return this.parseTheXofY(l,t,e,n)}if("string"==typeof l&&Si(l)){const r=l.substring(1).trim(),s=await this.extractValue(t,e,n);return{type:"style",element:await this.resolveElement(t.modifiers.on,e,n),property:r,value:s+""}}if("string"==typeof l&&ri(l)){const r=l.substring(1).trim(),s=await this.extractValue(t,e,n);return{type:"attribute",elements:await this.resolveTargets(t.modifiers.on,e,n),name:r,value:s}}if("string"==typeof l){const r=l.match(/^(my|me|its?|your?)\s+(.+)$/i);if(r){const s=Ei(r[1],n),i=await this.extractValue(t,e,n);return{type:"property",element:s,property:r[2],value:i}}}if(sn(l))return{type:"property",element:l,property:"textContent",value:await this.extractValue(t,e,n)};if(Array.isArray(l)&&l.length>0&&sn(l[0])){const r=await this.extractValue(t,e,n);return{type:"property",element:l[0],property:"textContent",value:r}}if("string"!=typeof l)throw Error("set command target must be a string or object literal"+("memberExpression"===r?.type||"propertyAccess"===r?.type?` (a property chain evaluated to ${null===l?"null":typeof l} \u2014 check that all intermediate objects exist)`:""));return{type:"variable",name:l,value:await this.extractValue(t,e,n),scope:"element"===i||"global"===i?i:void 0}}async execute(t,e){switch(t.type){case"variable":return"element"===t.scope?nn(e,t.name,t.value):"global"===t.scope?cn(t.name,t.value,e,"global"):cn(t.name,t.value,e),"result"!==t.name&&"it"!==t.name||Object.assign(e,{[t.name]:t.value}),Object.assign(e,{it:t.value}),{target:t.name,value:t.value,targetType:"variable"};case"attribute":for(const e of t.elements)e.setAttribute(t.name,t.value+"");return Object.assign(e,{it:t.value}),{target:"@"+t.name,value:t.value,targetType:"attribute"};case"property":return qi(t.element,t.property,t.value),Object.assign(e,{it:t.value}),{target:t.element,value:t.value,targetType:"property"};case"style":return Ni(t.element,t.property,t.value),Object.assign(e,{it:t.value}),{target:t.element,value:t.value,targetType:"property"};case"object-literal":for(const e of t.targets)for(const[n,r]of Object.entries(t.properties))qi(e,n,r);return Object.assign(e,{it:t.properties}),{target:t.targets[0]||"unknown",value:t.properties,targetType:"property"};case"member-assignment":return t.container[t.property]=t.value,Object.assign(e,{it:t.value}),{target:t.property,value:t.value,targetType:"property"};case"node-write":return await t.writer(t.node,t.value,e),Object.assign(e,{it:t.value}),{target:t.node.name??"",value:t.value,targetType:"variable"};default:throw Error("Unknown input type: "+t.type)}}async resolveAttributeWriteTarget(t,e,n,r){const s=t;if("attributeAccess"===s?.type)return{elements:await this.resolveTargets(e.modifiers.on,n,r),name:s.attributeName};if("binaryExpression"===s?.type&&"of"===s.operator&&"attributeAccess"===s.left?.type){const t=await this.evaluateToElement(s.right,n,r);if(t)return{elements:[t],name:s.left.attributeName}}if("memberExpression"===s?.type&&"attributeAccess"===s.property?.type){const t=await this.evaluateToElement(s.object,n,r);if(t)return{elements:[t],name:s.property.attributeName}}return null}async evaluateToElement(t,e,n){const r=await e.evaluate(t,n),s=Array.isArray(r)?r[0]:r;return sn(s)?s:null}async tryParseMemberExpression(t,e,n,r){const s=t.object,i=t.property;if(s?.name&&i?.name){const t=s.name.toLowerCase();if(["me","my","it","its","you","your"].includes(t)){const s=Ei(t,r),o=await this.extractValue(e,n,r);return{type:"property",element:s,property:i.name,value:o}}}const o=t.object,a=t.computed;if(o){const s=o;let c;if("memberExpression"===s.type&&!s.computed&&"style"===s.property?.name&&s.object){const t=await n.evaluate(s.object,r);c=(t&&"object"==typeof t&&"style"in t?t.style:void 0)??await n.evaluate(o,r)}else c=await n.evaluate(o,r);if(null!=c&&"object"==typeof c){const s=a?await n.evaluate(t.property,r)+"":i?.name||"";if(s)return{type:"member-assignment",container:c,property:s,value:await this.extractValue(e,n,r)}}}return null}async extractValue(t,e,n){if(t.modifiers.to)return e.evaluate(t.modifiers.to,n);const r=t.args.findIndex(t=>"identifier"===t.type&&"to"===t.name);if(r>=0&&t.args.length>r+1)return e.evaluate(t.args[r+1],n);if(t.args.length>=2)return e.evaluate(t.args[1],n);throw Error('set command requires a value (use "to" keyword)')}async resolveElement(t,e,n){return bi(t?await e.evaluate(t,n):void 0,n)}async resolveTargets(t,e,n){return function(t,e){if(Array.isArray(t))return t.filter(sn);if(on(t))return Array.from(t).filter(sn);if(sn(t))return[t];if(!t){const t=e.me;return t&&sn(t)?[t]:[]}if("string"==typeof t){const n=t.trim();if("me"===n)return e.me&&sn(e.me)?[e.me]:[];if("it"===n)return sn(e.it)?[e.it]:[];if("you"===n)return e.you&&sn(e.you)?[e.you]:[];const r=e.me?.ownerDocument??("undefined"!=typeof document?document:null);if(r){let t=n;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const e=r.querySelectorAll(t);return Array.from(e).filter(sn)}}return[]}(t?await e.evaluate(t,n):void 0,n)}async parseTheXofY(t,e,n,r){const s=t.match(/^the\s+(.+?)\s+of\s+(.+)$/i);if(!s)throw Error('Invalid "the X of Y" syntax');const[,i,o]=s,a=bi(o,r),c=await this.extractValue(e,n,r);return{type:"property",element:a,property:i.trim(),value:c}}validate(t){if(!t||"object"!=typeof t)return 0;const e=t;if(!e.type||"string"!=typeof e.type)return 0;if(!["variable","attribute","property","style","object-literal"].includes(e.type))return 0;switch(e.type){case"variable":return"string"==typeof e.name&&"value"in e;case"attribute":return"string"==typeof e.name&&Array.isArray(e.elements)&&e.elements.every(sn)&&"value"in e;case"property":return"string"==typeof e.property&&sn(e.element)&&"value"in e;case"style":return"string"==typeof e.property&&""!==e.property&&sn(e.element)&&"string"==typeof e.value;case"object-literal":return null!==e.properties&&"object"==typeof e.properties&&Array.isArray(e.targets)&&e.targets.length>0;default:return 0}}},ni(e,"SetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),ei(e,r)})(),e})());function so(t){const e=t.trim();return/^\d+$/.test(e)?parseInt(e,10):/^\d*\.\d+$/.test(e)?parseFloat(e):"true"===e?1:"false"===e?0:"null"===e?null:"undefined"!==e?e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e:void 0}const io=gi((()=>{let t,e,n=[yi({description:"Dispatch events on elements",syntax:["trigger <event> on <target>","trigger <event>(<detail>) on <target>","send <event> to <target>","send <event>(<detail>) to <target>"],examples:["trigger click on #button","trigger customEvent on me","send dataEvent to #target","send myEvent(count: 42) to me"],sideEffects:["event-dispatch"],aliases:["send"]}),mi({name:"trigger",category:"event"})],r=[];return e=class{async parseInput(t,e,n){const r="send"===t.commandName?.toLowerCase()?"send":"trigger",s=r;if(!t.args?.length)throw Error(s+" command requires an event name");const i=t=>t?.type||"unknown",o=t.args[0];let a,c,l;if("functionCall"===i(o)||"callExpression"===i(o)){a=o.name||o.callee?.name;const t=o.args||o.arguments;t?.length&&(c=await this.parseEventDetail(t,e,n))}else if("identifier"===i(o)||"keyword"===i(o))a=o.name;else{const t=await e.evaluate(o,n);a="string"==typeof t?t:t+""}const u=t.modifiers?.on||t.modifiers?.to;if(u)l=await this.resolveTargets([u],e,n,s);else{const r=t.args.findIndex((t,e)=>{if(0===e)return 0;const n=t.name||t.value;return"on"===n||"to"===n});if(-1!==r&&t.args.length-1>r){const i=t.args.slice(r+1),o=i.findIndex(t=>"with"===(t.name||t.value)),a=-1===o?i:i.slice(0,o);l=await this.resolveTargets(a,e,n,s)}else{if(!n.me)throw Error(s+": no target specified and context.me is null");l=[n.me]}}return{eventName:a,detail:c,targets:l,options:await this.parseEventOptions(t.args,e,n),mode:r}}async execute(t,e){const n=function(t,e,n={}){return new CustomEvent(t,{detail:void 0!==e?e:{},bubbles:void 0!==n.bubbles?n.bubbles:1,cancelable:void 0!==n.cancelable?n.cancelable:1,composed:void 0!==n.composed?n.composed:0})}(t.eventName,t.detail,t.options);for(const e of t.targets)e.dispatchEvent(n);e.it=n}async resolveTargets(t,e,n,r){const s=[];for(const r of t){const t=await e.evaluate(r,n);if("window"!==t&&t!==window)if("document"!==t&&t!==document)if("me"===t&&n.me)s.push(n.me);else if("you"===t&&n.you)s.push(n.you);else if("it"===t&&n.it)s.push(n.it);else if(sn(t))s.push(t);else if(t instanceof NodeList)s.push(...Array.from(t).filter(sn));else if(Array.isArray(t))s.push(...t.filter(sn));else{if("string"==typeof t){const e=document.querySelectorAll(t);if(0===e.length)throw Error(`No elements found: "${t}"`);s.push(...Array.from(e).filter(sn));continue}if(!t||"object"!=typeof t||!("addEventListener"in t))throw Error("Invalid target: "+typeof t);s.push(t)}else s.push(document);else s.push(window)}if(!s.length)throw Error(r+": no valid targets");return s}async parseEventDetail(t,e,n){if(!t?.length)return;if(1===t.length){const r=t[0];if("objectLiteral"!==r?.type)return await e.evaluate(r,n)}const r={};for(const s of t){const t=await e.evaluate(s,n);if("object"!=typeof t||null===t||Array.isArray(t)){if("string"==typeof t&&t.includes(":")){const[e,n]=t.split(":",2);r[e.trim()]=so(n.trim())}}else Object.assign(r,t)}return Object.keys(r).length?r:void 0}async parseEventOptions(t,e,n){const r={bubbles:1,cancelable:1,composed:0},s=t.findIndex(t=>"with"===(t.name||t.value));if(-1===s)return r;for(const i of t.slice(s+1)){const t=await e.evaluate(i,n);if("string"==typeof t){const e=t.toLowerCase();"bubbles"===e?r.bubbles=1:"nobubbles"===e?r.bubbles=0:"cancelable"===e?r.cancelable=1:"nocancelable"===e?r.cancelable=0:"composed"===e&&(r.composed=1)}}return r}},ni(e,"EventDispatchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),ei(e,r)})(),e})()),oo=gi((()=>{let t,e,n=[yi({description:"Log values to the console",syntax:"log [<values...>]",examples:['log "Hello World"',"log me.value","log x y z",'log "Result:" result'],sideEffects:["console-output"]}),mi({name:"log",category:"utility"})],r=[];return e=class{async parseInput(t,e,n){return t.args&&0!==t.args.length?{values:await Promise.all(t.args.map(t=>e.evaluate(t,n)))}:{values:[]}}async execute(t,e){const n="undefined"!=typeof window?window.console:console;0===t.values.length?n.log():n.log(...t.values)}validate(t){return"object"!=typeof t||null===t?0:Array.isArray(t.values)}},ni(e,"LogCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),ei(e,r)})(),e})());function ao(t,e,n,r){return t?new Promise(n=>{const s=()=>{i({event:null,timedOut:0,cancelled:1})},i=function(n,i){let a=0;return n=>{a||(a=1,t.removeEventListener(e,o),r&&r.removeEventListener("abort",s),i(n))}}(0,n),o=t=>{i({event:t,timedOut:0,cancelled:0})};r?.aborted?n({event:null,timedOut:0,cancelled:1}):(t.addEventListener(e,o),r&&r.addEventListener("abort",s))}):Promise.reject(Error("waitForEvent: no target provided"))}function co(t){return new Promise(e=>setTimeout(e,t))}const lo=gi((()=>{let t,e,n=[yi({description:"Wait for time delay, event, or race condition",syntax:["wait <time>","wait for <event>","wait for <event> or <condition>"],examples:["wait 2s","wait for click","wait for click or 1s","wait for mousemove(clientX, clientY)"],sideEffects:["time","event-listening"]}),mi({name:"wait",category:"async"})],r=[];return e=class{async parseInput(t,e,n){if(!t.args?.length)throw Error("wait command requires an argument");if(t.modifiers.or)return this.parseRaceCondition(t,e,n);if(t.modifiers.for)return this.parseEventWait(t.modifiers.for,t.modifiers.from,e,n);const r=t.args[0];return"arrayLiteral"===r.type&&r.elements?this.parseEventArrayWait(r.elements,t.args[1],e,n):this.parseTimeWait(t.args[0],e,n)}async execute(t,e){const n=Date.now();if("time"===t.type)return await co(t.milliseconds),{type:"time",result:t.milliseconds,duration:Date.now()-n};if("event"===t.type){const r=t.target??e.me??document,s=(await ao(r,t.eventName)).event;if(Object.assign(e,{it:s}),t.destructure)for(const n of t.destructure)n in s&&e.locals.set(n,s[n]);return{type:"event",result:s,duration:Date.now()-n}}const{result:r,winningCondition:s}=await this.executeRace(t.conditions,e);if(Object.assign(e,{it:r}),r instanceof Event&&"event"===s?.type&&s.destructure)for(const t of s.destructure)t in r&&e.locals.set(t,r[t]);return{type:r instanceof Event?"event":"time",result:r,duration:Date.now()-n}}async parseTimeWait(t,e,n){return{type:"time",milliseconds:Pi(await e.evaluate(t,n))}}async parseEventWait(t,e,n,r){const s=await n.evaluate(t,r);if("string"!=typeof s)throw Error("wait for: event name must be a string");const i=s.match(/^(\w+)\(([^)]+)\)$/),o=i?i[1]:s,a=i?i[2].split(",").map(t=>t.trim()):void 0;let c;if(e){const t=await n.evaluate(e,r);if(!t||"object"!=typeof t||!("addEventListener"in t))throw Error("wait for from: target must be an EventTarget");c=t}else c=r.me??void 0;return{type:"event",eventName:o,target:c,destructure:a}}async parseEventArrayWait(t,e,n,r){const s=[];for(const e of t){const t=e;if("objectLiteral"===t.type&&t.properties){let e="",n=[];for(const r of t.properties){const t=r.key?.name||r.key?.value;"name"===t&&r.value?e=r.value.value||"":"args"===t&&r.value?.elements&&(n=r.value.elements.map(t=>t.value||t.name||""))}e&&s.push({name:e,params:n})}}let i;if(e){const t=await n.evaluate(e,r);t&&"object"==typeof t&&"addEventListener"in t&&(i=t)}return i||(i=r.me??void 0),1===s.length?{type:"event",eventName:s[0].name,target:i,destructure:s[0].params.length>0?s[0].params:void 0}:{type:"race",conditions:s.map(t=>({type:"event",eventName:t.name,target:i,destructure:t.params.length>0?t.params:void 0}))}}async parseRaceCondition(t,e,n){const r=[];t.modifiers.for?r.push(await this.parseEventWait(t.modifiers.for,t.modifiers.from,e,n)):t.args[0]&&r.push(await this.parseTimeWait(t.args[0],e,n));const s=await e.evaluate(t.modifiers.or,n),i=Array.isArray(s)?s:[s];for(const t of i)try{r.push({type:"time",milliseconds:Pi(t)})}catch{if("string"==typeof t){const e=t.match(/^(\w+)\(([^)]+)\)$/);r.push(e?{type:"event",eventName:e[1],target:n.me??void 0,destructure:e[2].split(",").map(t=>t.trim())}:{type:"event",eventName:t,target:n.me??void 0})}}if(2>r.length)throw Error("wait: race requires at least 2 conditions");return{type:"race",conditions:r}}async executeRace(t,e){const n=new AbortController,r=n.signal,s=t.map(t=>"time"===t.type?co(t.milliseconds).then(()=>({result:t.milliseconds,winningCondition:t})):ao(t.target??e.me??document,t.eventName,0,r).then(e=>({result:e.event,winningCondition:t})));try{return await Promise.race(s)}finally{n.abort()}}},ni(e,"WaitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),ei(e,r)})(),e})()),uo=function(t,e){const n=new qr(null);for(const e of t)n.register(e);return new Yr({registry:n,expressionRegistry:e.expressionRegistry,enableAsyncCommands:e.enableAsyncCommands??1,commandTimeout:e.commandTimeout??1e4,enableErrorReporting:e.enableErrorReporting??1,enableResultPattern:e.enableResultPattern??1})}([Li(),Mi(),Xi(),Qi(),eo(),no(),ro(),io(),oo(),lo()],{expressionRegistry:Ks()}),ho={parse:t=>We(t),execute:async(t,e)=>{const n=function(t){if(!t)return rn();if(t.locals instanceof Map&&t.globals instanceof Map&&t.flags)return t;const e=rn(t.me instanceof Element?t.me:null);return void 0!==t.it&&(e.it=t.it),void 0!==t.you&&(e.you=t.you),void 0!==t.result&&(e.result=t.result),void 0!==t.event&&Object.assign(e,{event:t.event}),e}(e),r=We(t);if(!r.success||!r.node)throw Error(r.error?.message||"Parse failed");return await uo.execute(r.node,n)}},fo=function(t){return new Qs(t)}(ho),po={runtime:ho,parse:t=>ho.parse(t),execute:async(t,e)=>ho.execute(t,e),createContext:rn,attributeProcessor:fo,version:"1.1.0-minimal-v2-tree-shakeable",commands:["add","remove","toggle","show","hide","put","set","send","log","wait"],eval:async(t,e)=>ho.execute(t,e),init:()=>{fo.init()}};"undefined"!=typeof window&&(window.hyperfixi=po,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{fo.init()}):fo.init());const mo={String:"string",Number:"number",Boolean:"boolean",Element:"element",ElementList:"element-list",Array:"array",Object:"object",Promise:"promise",Context:"object",Null:"null",Undefined:"undefined",Any:"object"},yo=Fn({collection:_n().describe("Collection to operate on (array, NodeList, or string)")}).strict(),go=Fn({collection:_n().describe("Collection to access"),index:Dn().describe("Index position to access")}).strict(),vo=Fn({collection:_n().describe("Collection to select random item from")}).strict();new class extends Hn{constructor(){super(...arguments),this.name="first",this.category="Positional",this.syntax="first in collection",this.description="Gets the first element from a collection",this.inputSchema=yo,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:r.errors[0]};const s=this.normalizeCollection(e.collection),i=s.length>0?s[0]:void 0,o={success:1,value:i,type:mo[this.inferEvaluationType(i)]};return this.trackPerformance(t,e,o,n),o}catch(r){const s=this.failure("FirstExpressionError","runtime-error","First operation failed: "+(r instanceof Error?r.message:r+""),"FIRST_OPERATION_FAILED");return this.trackPerformance(t,e,s,n),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid first input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends Hn{constructor(){super(...arguments),this.name="last",this.category="Positional",this.syntax="last in collection",this.description="Gets the last element from a collection",this.inputSchema=yo,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:r.errors[0]};const s=this.normalizeCollection(e.collection),i=s.length>0?s[s.length-1]:void 0,o={success:1,value:i,type:mo[this.inferEvaluationType(i)]};return this.trackPerformance(t,e,o,n),o}catch(r){const s=this.failure("LastExpressionError","runtime-error","Last operation failed: "+(r instanceof Error?r.message:r+""),"LAST_OPERATION_FAILED");return this.trackPerformance(t,e,s,n),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid last input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends Hn{constructor(){super(...arguments),this.name="at",this.category="Positional",this.syntax="collection[index] or collection at index",this.description="Gets element at specific index from a collection",this.inputSchema=go,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:r.errors[0]};const s=this.normalizeCollection(e.collection),i=this.normalizeIndex(e.index,s.length),o=i>=0&&s.length>i?s[i]:void 0,a={success:1,value:o,type:mo[this.inferEvaluationType(o)]};return this.trackPerformance(t,e,a,n),a}catch(r){const s=this.failure("AtExpressionError","runtime-error","At operation failed: "+(r instanceof Error?r.message:r+""),"AT_OPERATION_FAILED");return this.trackPerformance(t,e,s,n),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid at input: "+t.message,suggestions:[]}))??[],suggestions:["Provide collection and index parameters","Ensure index is a number"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}normalizeIndex(t,e){return 0>t?e+t:t}},new class extends Hn{constructor(){super(...arguments),this.name="random",this.category="Positional",this.syntax="random in collection",this.description="Gets a random element from a collection",this.inputSchema=vo,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:r.errors[0]};const s=this.normalizeCollection(e.collection);if(0===s.length){const r={success:1,value:void 0,type:"undefined"};return this.trackPerformance(t,e,r,n),r}const i=s[this.getSecureRandomIndex(s.length)],o={success:1,value:i,type:mo[this.inferEvaluationType(i)]};return this.trackPerformance(t,e,o,n),o}catch(r){const s=this.failure("RandomExpressionError","runtime-error","Random operation failed: "+(r instanceof Error?r.message:r+""),"RANDOM_OPERATION_FAILED");return this.trackPerformance(t,e,s,n),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid random input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}getSecureRandomIndex(t){if("undefined"!=typeof crypto&&crypto.getRandomValues){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]%t}return Math.floor(Math.random()*t)}};const bo={name:"first",category:"Reference",evaluatesTo:"Any",operators:["first"],async evaluate(t,e){const n=void 0!==e?e:t.it;return null==n?null:Array.isArray(n)||n instanceof NodeList||n instanceof HTMLCollection?n.length>0?n[0]:null:n instanceof Element?n.children.length>0?n.children[0]:null:un(n)?n.length>0?n[0]:null:dn(n)&&"length"in n&&hn(n.length)&&n.length>0?n[0]:null},validate:t=>Tn(t,1,"first","collection")},wo={name:"last",category:"Reference",evaluatesTo:"Any",operators:["last"],async evaluate(t,e){const n=void 0!==e?e:t.it;if(null==n)return null;if(Array.isArray(n))return n.length>0?n[n.length-1]:null;if(n instanceof NodeList||n instanceof HTMLCollection)return n.length>0?n[n.length-1]:null;if(n instanceof Element){const t=n.children;return t.length>0?t[t.length-1]:null}return un(n)?n.length>0?n[n.length-1]:null:dn(n)&&"length"in n&&hn(n.length)&&n.length>0?n[n.length-1]:null},validate:t=>Tn(t,1,"last","collection")},Eo={name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(t,...e){const[n,r]=e;if(!hn(n))throw Error("Index must be a number");const s=n,i=void 0!==r?r:t.it;if(null==i)return null;if(Array.isArray(i)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}if(i instanceof NodeList||i instanceof HTMLCollection){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}if(i instanceof Element){const t=i.children,e=0>s?t.length+s:s;return e>=0&&t.length>e?t[e]:null}if(un(i)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}if(dn(i)&&"length"in i&&hn(i.length)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}return null},validate:t=>On(t,1,2,"at","index, optional collection")??function(t){return"number"!=typeof t[0]?"at index must be a number":null}(t)};function xo(t,e){let n=t.nextElementSibling;for(;n;){if(n.matches(e))return n;const t=n.querySelector(e);if(t)return t;n=n.nextElementSibling}const r=t.parentElement;return r&&r!==document.documentElement?xo(r,e):null}function ko(t,e){let n=t.previousElementSibling;for(;n;){const t=Array.from(n.querySelectorAll(e)).reverse();if(t.length>0)return t[0];if(n.matches(e))return n;n=n.previousElementSibling}const r=t.parentElement;return r&&r!==document.documentElement?ko(r,e):null}function So(t,e,n,r){if(n.inSearch){if(null==n.inElt)return;return function(t,e,n,r){const s=Array.from(e??[]),i=[];for(const e of s)(e.matches&&e.matches(n)||e===t)&&i.push(e);for(let e=0;i.length-1>e;e++)if(i[e]===t)return i[e+1];if(r){const t=i[0];if(t&&t.matches&&t.matches(n))return t}}(t,r?Array.from(n.inElt):Array.from(n.inElt).reverse(),e,!!n.wrapping)}const s=n.within??("undefined"!=typeof document?document.body:null);if(s)return r?function(t,e,n,r){const s=e.querySelectorAll(n);for(let e=0;s.length>e;e++){const n=s[e];if(2===n.compareDocumentPosition(t))return n}return r?s[0]:void 0}(t,s,e,!!n.wrapping):function(t,e,n,r){const s=e.querySelectorAll(n);for(let e=s.length-1;e>=0;e--){const n=s[e];if(4===n.compareDocumentPosition(t))return n}return r?s[s.length-1]:void 0}(t,s,e,!!n.wrapping)}function Ao(t){let e=0,n=t;for(;n&&n.parentElement;)e+=Array.from(n.parentElement.children).indexOf(n),n=n.parentElement,e+=1e3;return e}const No={first:bo,last:wo,at:Eo,next:{name:"next",category:"Reference",evaluatesTo:"Element",operators:["next"],async evaluate(t,...e){const[n,r,s]=e,i=r||t.me;return i&&i instanceof Element?n?s?So(i,n,s,1):xo(i,n):i.nextElementSibling:null},validate:t=>Tn(t,3,"next","optional selector, optional fromElement, optional modifiers")||(1>t.length||null==t[0]||"string"==typeof t[0]?2>t.length||null==t[1]||t[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},previous:{name:"previous",category:"Reference",evaluatesTo:"Element",operators:["previous","prev"],async evaluate(t,...e){const[n,r,s]=e,i=r||t.me;return i&&i instanceof Element?n?s?So(i,n,s,0):ko(i,n):i.previousElementSibling:null},validate:t=>Tn(t,3,"previous","optional selector, optional fromElement, optional modifiers")||(1>t.length||null==t[0]||"string"==typeof t[0]?2>t.length||null==t[1]||t[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},nextWithin:{name:"nextWithin",category:"Reference",evaluatesTo:"Element",operators:["next within"],async evaluate(t,...e){const[n,r,s]=e,i=s||t.me;if(!(i&&i instanceof Element))return null;const o=i.closest(r);return o?function(t,e,n){const r=Array.from(n.querySelectorAll(e)),s=Ao(t);for(const t of r)if(Ao(t)>s)return t;return null}(i,n,o):null},validate:t=>On(t,2,3,"nextWithin","selector, withinSelector, optional fromElement")||("string"!=typeof t[0]?"selector must be a string":"string"!=typeof t[1]?"withinSelector must be a string":3>t.length||null==t[2]||t[2]instanceof Element?null:"fromElement must be an Element")},previousWithin:{name:"previousWithin",category:"Reference",evaluatesTo:"Element",operators:["previous within"],async evaluate(t,...e){const[n,r,s]=e,i=s||t.me;if(!(i&&i instanceof Element))return null;const o=i.closest(r);return o?function(t,e,n){const r=Array.from(n.querySelectorAll(e)),s=Ao(t);for(let t=r.length-1;t>=0;t--){const e=r[t];if(s>Ao(e))return e}return null}(i,n,o):null},validate:t=>On(t,2,3,"previousWithin","selector, withinSelector, optional fromElement")||("string"!=typeof t[0]?"selector must be a string":"string"!=typeof t[1]?"withinSelector must be a string":3>t.length||null==t[2]||t[2]instanceof Element?null:"fromElement must be an Element")}};class Co{constructor(){this.name="addition",this.category="Special",this.syntax="left + right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=this.validate(e);if(!n.isValid)return{success:0,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e;return{success:1,value:ls(as(t,"left operand")+as(n,"right operand"),"addition"),type:"number"}}catch(t){return{success:0,errors:[ps("runtime-error","Addition failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){const e=function(t){if(null==t)return ds([ps("missing-argument","Input is null or undefined")],["Provide an object with left and right operands"]);if("object"!=typeof t)return ds([ps("type-mismatch","Expected object, got "+typeof t)],["Provide an object with left and right operands"]);const e=t;if(!("left"in e)||!("right"in e)){const t=[];return"left"in e||t.push("left"),"right"in e||t.push("right"),ds([ps("missing-argument",`Missing ${t.join(" and ")} operand${t.length>1?"s":""}`)],["Provide { left: value, right: value }"])}return{isValid:1,errors:[],suggestions:[]}}(t);if(!e.isValid)return e;const{left:n,right:r}=t;return us(n)?us(r)?{isValid:1,errors:[],suggestions:[]}:{isValid:0,errors:[ps("type-mismatch","Right operand cannot be converted to number: "+r)],suggestions:["Provide a numeric value for right operand"]}:{isValid:0,errors:[ps("type-mismatch","Left operand cannot be converted to number: "+n)],suggestions:["Provide a numeric value for left operand"]}}}const To={addition:new Co,subtraction:new class{constructor(){this.name="subtraction",this.category="Special",this.syntax="left - right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=this.validate(e);if(!n.isValid)return{success:0,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e;return{success:1,value:ls(as(t,"left operand")-as(n,"right operand"),"subtraction"),type:"number"}}catch(t){return{success:0,errors:[ps("runtime-error","Subtraction failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new Co).validate(t)}},multiplication:new class{constructor(){this.name="multiplication",this.category="Special",this.syntax="left * right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=this.validate(e);if(!n.isValid)return{success:0,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e;return{success:1,value:ls(as(t,"left operand")*as(n,"right operand"),"multiplication"),type:"number"}}catch(t){return{success:0,errors:[ps("runtime-error","Multiplication failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new Co).validate(t)}},division:new class{constructor(){this.name="division",this.category="Special",this.syntax="left / right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=this.validate(e);if(!n.isValid)return{success:0,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=function(t,e,n=1){if(0===e){if(n)return 0===t?NaN:t>0?1/0:-1/0;throw Error("Division by zero")}return t/e}(as(t,"left operand"),as(n,"right operand"),1);return{success:1,value:r,type:"number"}}catch(t){return{success:0,errors:[ps("runtime-error","Division failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new Co).validate(t)}},modulo:new class{constructor(){this.name="modulo",this.category="Special",this.syntax="left mod right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=this.validate(e);if(!n.isValid)return{success:0,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=function(t,e){if(0===e)throw Error("Modulo by zero");return t%e}(as(t,"left operand"),as(n,"right operand"));return{success:1,value:r,type:"number"}}catch(t){return{success:0,errors:[ps("runtime-error","Modulo failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric and divisor is not zero"]}}}validate(t){return(new Co).validate(t)}},power:new class{constructor(){this.name="power",this.category="Special",this.syntax="left ** right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=this.validate(e);if(!n.isValid)return{success:0,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=as(t,"left operand"),s=as(n,"right operand");return{success:1,value:ls(Math.pow(r,s),"power"),type:"number"}}catch(t){return{success:0,errors:[ps("runtime-error","Power failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new Co).validate(t)}}};var Oo=Object.freeze({__proto__:null,conversion:nr,conversionExpressions:nr,createCommonRegistry:function(){return Kr(es,zs,Ys,nr,No)},createCoreRegistry:Ks,createExpressionRegistry:Kr,createFullExpressionRegistry:function(){return Kr(es,zs,nr,No,or,Ys,To)},createFullRegistry:function(){return Kr(es,zs,Ys,nr,No,or)},logical:zs,logicalExpressions:zs,positional:No,positionalExpressions:No,properties:or,propertiesExpressions:or,references:es,referencesExpressions:es,special:Ys,specialExpressions:Ys});return po}();