@hyperfixi/core 2.6.0 → 2.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/hyperscript-api.d.ts +6 -0
- package/dist/ast-utils/index.js +8 -8
- package/dist/ast-utils/index.mjs +8 -8
- package/dist/bundle-generator/index.js +12 -4
- package/dist/bundle-generator/index.mjs +12 -4
- package/dist/chunks/{bridge-fFLEvCQs.js → bridge-lZbOVRDD.js} +2 -2
- package/dist/chunks/browser-modular-DegkWQ8d.js +2 -0
- package/dist/chunks/{index-BRgVy8nY.js → index-i_j9Z-1e.js} +2 -2
- package/dist/commands/data/set.d.ts +1 -0
- package/dist/commands/index.js +156 -47
- package/dist/commands/index.mjs +156 -47
- package/dist/core/context.d.ts +4 -0
- package/dist/dom/attribute-processor.d.ts +1 -0
- package/dist/hyperfixi-browser-classic-i18n.js +1 -1
- package/dist/hyperfixi-browser-minimal.js +1 -1
- package/dist/hyperfixi-browser-standard.js +1 -1
- package/dist/hyperfixi-browser.js +1 -1
- package/dist/hyperfixi-classic-i18n.js +1 -1
- package/dist/hyperfixi-hx-v4.js +1 -1
- package/dist/hyperfixi-hx.js +1 -1
- package/dist/hyperfixi-hybrid-complete.js +1 -1
- package/dist/hyperfixi-hybrid-hx.js +1 -1
- package/dist/hyperfixi-lite-plus.js +1 -1
- package/dist/hyperfixi-lite.js +1 -1
- package/dist/hyperfixi-minimal.js +1 -1
- package/dist/hyperfixi-multilingual.js +1 -1
- package/dist/hyperfixi-standard.js +1 -1
- package/dist/hyperfixi.js +1 -1
- package/dist/hyperfixi.mjs +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +694 -459
- package/dist/index.min.js +1 -1
- package/dist/index.mjs +691 -460
- package/dist/lokascript-browser-classic-i18n.js +1 -1
- package/dist/lokascript-browser-minimal.js +1 -1
- package/dist/lokascript-browser-standard.js +1 -1
- package/dist/lokascript-browser.js +1 -1
- package/dist/lokascript-hybrid-complete.js +1 -1
- package/dist/lokascript-hybrid-hx.js +1 -1
- package/dist/lokascript-lite-plus.js +1 -1
- package/dist/lokascript-lite.js +1 -1
- package/dist/lokascript-multilingual.js +1 -1
- package/dist/parser/full-parser.js +70 -35
- package/dist/parser/full-parser.mjs +70 -35
- package/dist/parser/parser-types.d.ts +1 -1
- package/dist/parser/parser.d.ts +2 -0
- package/dist/parser/regex-parser.js +23 -14
- package/dist/parser/regex-parser.mjs +23 -14
- package/dist/registry/index.js +178 -45
- package/dist/registry/index.mjs +178 -45
- package/dist/types/core-context.d.ts +1 -0
- package/package.json +6 -6
- package/dist/chunks/browser-modular-BK3IOo93.js +0 -2
- package/dist/compatibility/browser-bundle.d.ts +0 -164
|
@@ -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","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"method":r.method=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:"local",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:"local",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(),l=[];return a?l.push(a):c.length>0&&l.push(...c),l.push(s.createIdentifier(h)),u&&l.push(u),xe.fromIdentifier(i).withArgs(...l).endingAt(s.getPosition()).build()}function Le(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 Ie(t){if(t.isAtEnd())return 1;const e=t.peek().value;return["as","with","{","then","end","else","otherwise",")"].includes(e)||ye(t)}function je(t){if(t.check("{"))return 0;if(!t.checkIdentifierLike())return 0;const e=t.peekAt(1);return null!==e&&":"===e.value}function Me(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 De=new Set(["em","ex","cap","ch","ic","rem","lh","rlh","vw","vh","vi","vb","vmin","vmax","cm","mm","Q","pc","pt","px"]);class Pe{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("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=Pe.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=Pe.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()&&!Pe.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(De.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"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 Le(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 Le(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 Le(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:"local",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(!(Pe.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}}),Pe.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}}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}'`)}if(this.check("debounced")||this.check("throttled")){const t=this.advance().value.toLowerCase(),e="debounced"===t?"debounce":"throttle";if(this.match("at"))if(this.checkTimeExpression()){const n=this.advance(),r=(o=n.value).endsWith("ms")?parseInt(o,10):o.endsWith("seconds")||o.endsWith("s")?1e3*parseFloat(o):o.endsWith("minutes")?6e4*parseFloat(o):o.endsWith("hours")?36e5*parseFloat(o):o.endsWith("days")?864e5*parseFloat(o):parseInt(o,10);i[e]=r,ut(`🔧 parseEventHandler: Parsed '${t} at ${n.value}' (${r}ms)`)}else if(this.matchNumber()){const n=parseInt(this.previous().value,10);i[e]=n,ut(`🔧 parseEventHandler: Parsed '${t} at ${n}'`)}else this.addError(`Expected time expression after '${t} at', got: ${this.peek().value}`);else this.addError(`Expected 'at' after '${t}'`)}var o;let a,c,u,l;if(e&&(i.once=1),Object.keys(i).length>0&&ut("🔧 parseEventHandler: Parsed modifiers:",i),this.match("[")&&(a=this.parseExpression(),this.consume("]","Expected ']' after event condition")),this.match("from")){const t=this.advance();c=t.value,ut(`🔧 parseEventHandler: Parsed 'from' target: ${c} (kind: ${t.kind})`)}if(this.match("of")){const t=this.advance();u=t.value.startsWith("@")?t.value.substring(1):t.value,ut("🔧 parseEventHandler: Parsed attribute name: "+u)}this.match("in")&&(ut("🔧 parseEventHandler: Found 'in' keyword, parsing watch target"),l=this.parseExpression(),ut("🔧 parseEventHandler: Parsed watch target expression"));const h=[];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();h.push(n);continue}if(t&&"callExpression"===t.type){const e=this.tryParsePseudoCommand(t,t);if(h.push(e.node),e.isPseudo||e.targetFailed)continue}}else{const t=this.parseCommandWithErrorRecovery();t&&(h.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&&h.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(h.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}};h.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 f=this.getPosition(),d={type:"eventHandler",event:1===t.length?t[0]:t.join("|"),events:t,commands:h,...s.length>0&&{args:s},...a&&{condition:a},...c&&{target:c},...u&&{attributeName:u},...l&&{watchTarget:l},...r&&{customEventSource:r},...Object.keys(i).length>0&&{modifiers:i},start:f.start,end:f.end,line:f.line,column:f.column};return ut(`🔧 parseEventHandler: Created node with events: ${t.join(", ")}, attributeName: ${u||"none"}, watchTarget: ${l?"yes":"none"}`),d}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"].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=function(t){const e=t.savePosition();let n="";for(;!t.isAtEnd()&&!Ie(t);)n+=t.advance().value;return n&&"/"!==n?{type:"literal",value:n,raw:n,start:e,end:t.savePosition()}:(t.restorePosition(e),null)}(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=je(t)?Me(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),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]}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=>{const n=t.current+e;return n>=0&&t.tokens.length>n?t.tokens[n]:null},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 Fe(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 Pe(n,e,t).parse()}Pe.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty","ignoring case"]),Pe.PRATT_TABLE=Et,Pe.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];class Be{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 _e(t){return t instanceof Error&&("isHalt"in t||"isExit"in t||"isBreak"in t||"isContinue"in t||"isReturn"in t)?t:null}function Ve(t){return{ok:1,value:t}}function qe(t){return{ok:0,error:t}}function He(t){return 1==t.ok}const Ue=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 We(t){const e=Ue.get("String");return e?e.isType(t):"string"==typeof t}function ze(t){const e=Ue.get("Number");return e?e.isType(t):"number"==typeof t}function Je(t){const e=Ue.get("Boolean");return e?e.isType(t):"boolean"==typeof t}function Ze(t){const e=Ue.get("Object");return e?e.isType(t):"object"==typeof t&&null!==t}function Ge(t){const e=Ue.get("Function");return e?e.isType(t):"function"==typeof t}function Xe(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"style"in t}function Ye(t){return t instanceof Element}function Ke(t){return t instanceof HTMLElement}const Qe=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function tn(t,e){return Qe.has(e.toLowerCase())?t.hasAttribute(e):t.getAttribute(e)}const en={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=>Xe(t)?t.tabIndex:void 0,hidden:t=>Xe(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 nn(t,e){if(e.startsWith("*"))return function(t,e){if(!Ke(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 Ke(t)?getComputedStyle(t).getPropertyValue(n):void 0}if(e.startsWith("@"))return tn(t,e.slice(1));const n=en[e.toLowerCase()];if(n)return n(t);if(function(t,e){return t.hasAttribute(e)}(t,e))return tn(t,e);const r=t[e];return Ge(r)?r.bind(t):r}const rn={1:"one",2:"two",3:"three",4:"four",5:"five"};function sn(t,e,n,r){return t.length!==e?`${n} requires exactly ${s=e,rn[s]??s+""} argument${1===e?"":"s"}${r?` (${r})`:""}`:null;var s}function on(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 sn(t,1,e,n)??on(t,0,e,n)}function cn(t,e){return sn(t,2,e,"left, right")}function un(){return null}function ln(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 hn(t,e,n,r,s){return e>t.length||t.length>n?`${r} requires ${e}-${n} arguments${s?` (${s})`:""}`:null}function fn(t,e,n,r=[]){return{type:t,message:e,suggestions:r,...n&&{path:n}}}const dn=("undefined"!=typeof process?1:0)||"undefined"!=typeof process&&"true"===process.env.HYPERFIXI_SKIP_VALIDATION||"undefined"!=typeof globalThis&&"true"===globalThis.HYPERFIXI_SKIP_VALIDATION;let pn;function mn(){return pn({validate:t=>({success:1,data:t})})}function yn(t,e){if(dn)return mn();const n=pn({validate:n=>{if("object"!=typeof n||null===n||Array.isArray(n))return{success:0,error:fn("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:fn("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:fn("missing-argument",`Required field "${e}" is missing`,e)};const i=n.validate(t);if(!i.success)return{success:0,error:fn("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=()=>yn(t,{strict:1}),n}pn=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 pn(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:fn("runtime-error",`String must be at least ${t} characters long`)}:r}};return pn(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:fn("runtime-error",`String must be at most ${t} characters long`)}:r}};return pn(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 pn(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:fn("runtime-error",e||"Refinement validation failed")}:s}};return pn(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 gn=t=>function(t={}){return dn?mn():pn({validate:e=>t.optional&&null==e?{success:1,data:void 0}:"string"!=typeof e?{success:0,error:fn("type-mismatch","Expected string, received "+typeof e)}:void 0!==t.minLength&&t.minLength>e.length?{success:0,error:fn("runtime-error",`String must be at least ${t.minLength} characters long`)}:void 0!==t.maxLength&&e.length>t.maxLength?{success:0,error:fn("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:fn("runtime-error",`Expected "${t.pattern.source.slice(1,-1)}", received "${e}"`)}:{success:0,error:fn("missing-argument","String does not match required pattern")}:{success:1,data:e},...t.description&&{description:t.description}})}(t||{}),vn=t=>function(t={}){return dn?mn():pn({validate:e=>{const n=Number(e);return isNaN(n)?{success:0,error:fn("type-mismatch","Expected number, received "+typeof e)}:void 0!==t.min&&t.min>n?{success:0,error:fn("runtime-error","Number must be at least "+t.min)}:void 0!==t.max&&n>t.max?{success:0,error:fn("runtime-error","Number must be at most "+t.max)}:{success:1,data:n}}})}(t||{}),bn=()=>dn?mn():pn({validate:t=>"boolean"!=typeof t?{success:0,error:fn("type-mismatch","Expected boolean, received "+typeof t)}:{success:1,data:t}}),wn=t=>yn(t),En=t=>function(t){return dn?mn():pn({validate:e=>{if(!Array.isArray(e))return{success:0,error:fn("type-mismatch","Expected array, received "+typeof e)};if(e.length!==t.length)return{success:0,error:fn("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:fn("runtime-error",s.error.message,s.error.path?`${r}.${s.error.path}`:""+r)};n.push(s.data)}return{success:1,data:n}}})}(t),xn=()=>mn(),kn=()=>mn(),Sn=()=>function(t,e="Custom validation failed"){return dn?mn():pn({validate:n=>t(n)?{success:1,data:n}:{success:0,error:fn("runtime-error",e)}})}(t=>void 0===t,"Expected undefined");class An{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||ze(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":Ze(t)?"object":typeof t}inferEvaluationType(t){return void 0===t?"Undefined":null===t?"Null":We(t)?"String":ze(t)?"Number":Je(t)?"Boolean":Array.isArray(t)?"Array":this.isElement(t)?"Element":"Object"}normalizeCollection(t){return Array.isArray(t)?t:t instanceof NodeList?Array.from(t):We(t)?t.split(""):null==t?[]:Ze(t)&&Symbol.iterator in t?Array.from(t):[]}toNumber(t){if(ze(t)&&Number.isFinite(t))return t;if(We(t)){const e=Number(t);return Number.isFinite(e)?e:null}return Je(t)?t?1:0:null}}function Nn(t,e,n,r,s="runtime-error"){return{success:0,error:{name:t+"ConversionError",type:s,message:n,code:e,suggestions:r}}}function Cn(t,e){return{success:1,value:t,type:e}}function Tn(t,e){return`${t}: ${e instanceof Error?e.message:e+""}`}const On={Array:(t,e)=>{try{return Array.isArray(t)?Cn(t,"array"):t instanceof NodeList?Cn(Array.from(t),"array"):Cn(null==t?[]:[t],"array")}catch(t){return Nn("Array","ARRAY_CONVERSION_FAILED",Tn("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?Cn("","string"):We(t)?Cn(t,"string"):Ze(t)?Cn(JSON.stringify(t),"string"):Cn(t+"","string")}catch(t){return Nn("String","STRING_CONVERSION_FAILED",Tn("Failed to convert value to String",t),["Check if object has circular references","Ensure value is serializable"])}},Boolean:(t,e)=>{try{if(Je(t))return Cn(t,"boolean");if(null==t)return Cn(0,"boolean");if(We(t)){const e=t.toLowerCase().trim();return Cn("false"!==e&&"0"!==e&&""!==e,"boolean")}return ze(t)?Cn(0!==t&&!isNaN(t),"boolean"):Cn(!!t,"boolean")}catch(t){return Nn("Boolean","BOOLEAN_CONVERSION_FAILED",Tn("Failed to convert value to Boolean",t),["Use explicit true/false values","Check for unexpected data types"])}},Number:(t,e)=>{try{if(ze(t))return Cn(t,"number");if(null==t)return Cn(0,"number");const e=Number(t);return isNaN(e)?Nn("Number","INVALID_NUMBER",`Cannot convert "${t}" to a valid number`,["Check if value contains non-numeric characters","Use a valid numeric format"],"invalid-argument"):Cn(e,"number")}catch(t){return Nn("Number","NUMBER_CONVERSION_FAILED",Tn("Failed to convert value to Number",t),["Ensure value is convertible to number","Check for special characters"])}},Int:(t,e)=>{const n=On.Number(t,e);return n.success?Cn(Math.trunc(n.value),"number"):n},Float:(t,e)=>{const n=On.Number(t,e);return n.success?Cn(parseFloat(""+n.value),"number"):n},Date:(t,e)=>{try{if(t instanceof Date)return Cn(t,"object");if(null==t)return Cn(new Date(""),"object");if(We(t)&&/^\d{4}-\d{2}-\d{2}$/.test(t)){const[e,n,r]=t.split("-").map(Number);return Cn(new Date(e,n-1,r),"object")}const e=new Date(t);return isNaN(e.getTime())?Nn("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"):Cn(e,"object")}catch(t){return Nn("Date","DATE_CONVERSION_FAILED",Tn("Failed to convert value to Date",t),["Check date format","Ensure value is a valid date string or timestamp"])}},JSON:(t,e)=>{if(!We(t))return Cn(t,"object");try{return Cn(JSON.parse(t),"object")}catch(t){return Nn("JSON","JSON_PARSE_FAILED",Tn("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 Cn(JSON.stringify(t),"string")}catch(t){return Nn("JSONString","JSON_STRINGIFY_FAILED",Tn("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(Ze(t))return Cn(t,"object");if(We(t))try{return Cn(JSON.parse(t),"object")}catch(t){return Nn("Object","JSON_PARSE_FAILED",Tn("Cannot parse JSON string",t),["Check JSON syntax","Ensure proper escaping of quotes","Validate JSON format"],"syntax-error")}return Cn({},"object")}catch(t){return Nn("Object","OBJECT_CONVERSION_FAILED",Tn("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 Cn(jn(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=Mn(e);void 0!==t&&(n[e.name]=t)}}),Cn(n,"object")}return Cn({},"object")}catch(t){return Nn("FormValues","FORM_VALUES_EXTRACTION_FAILED",Tn("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=On.Values(t,e);if(!r.success)return r;n=r.value}if(!Ze(n))return Cn("","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 Cn(""+r,"string")}catch(t){return Nn("FormEncoded","FORM_ENCODE_FAILED",Tn("Failed to URL-encode values",t),["Ensure input is a form element or plain object of scalar/array values"])}},Set:(t,e)=>{try{return Cn(new Set(t),"object")}catch(t){return Nn("Set","SET_CONVERSION_FAILED",Tn("Failed to convert to Set",t),["Ensure the value is iterable"])}},Map:(t,e)=>{try{return Cn(new Map(Object.entries(t??{})),"object")}catch(t){return Nn("Map","MAP_CONVERSION_FAILED",Tn("Failed to convert to Map",t),["Ensure the value is a plain object"])}},Keys:(t,e)=>t instanceof Map?Cn(Array.from(t.keys()),"array"):Cn(Object.keys(t??{}),"array"),Entries:(t,e)=>t instanceof Map?Cn(Array.from(t.entries()),"array"):Cn(Object.entries(t??{}),"array"),Reversed:(t,e)=>{try{return Cn(Array.from(t).reverse(),"array")}catch(t){return Nn("Reversed","REVERSED_CONVERSION_FAILED",Tn("Failed to reverse value",t),["Ensure the value is array-like"])}},Unique:(t,e)=>{try{return Cn([...new Set(t)],"array")}catch(t){return Nn("Unique","UNIQUE_CONVERSION_FAILED",Tn("Failed to dedupe value",t),["Ensure the value is iterable"])}},Flat:(t,e)=>{try{return Cn(Array.from(t).flat(),"array")}catch(t){return Nn("Flat","FLAT_CONVERSION_FAILED",Tn("Failed to flatten value",t),["Ensure the value is array-like"])}}},$n=wn({value:kn(),type:gn().min(1)}),Rn=wn({value:kn(),type:gn().min(1)});new class extends An{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=$n,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=On.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=On[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=On[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 An{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=Rn,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=We(s);break;case"number":a=ze(s)&&!isNaN(s);break;case"boolean":a=Je(s);break;case"object":a=Ze(s);break;case"array":a=Array.isArray(s);break;case"function":a=Ge(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||Ze(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 Ln={conversions:{dynamicResolvers:[]}},In={Array:t=>Array.isArray(t)?t:t instanceof NodeList?Array.from(t):null==t?[]:[t],String:t=>null==t?"":We(t)?t:Ze(t)?JSON.stringify(t):t+"",Boolean:t=>{if(Je(t))return t;if(null==t)return 0;if(We(t)){const e=t.toLowerCase().trim();return"false"===e||"0"===e||""===e?0:1}return ze(t)?0!==t&&!isNaN(t):!!t},Number:t=>{if(ze(t))return t;if(null==t)return 0;const e=Number(t);return isNaN(e)?0:e},Math:t=>{if(ze(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(!ze(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=In.Number(t);return Math.trunc(e)},Float:t=>{const e=In.Number(t);return parseFloat(""+e)},Date:t=>{if(t instanceof Date)return t;if(null==t)return new Date(NaN);if(We(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(!We(t))return t;try{return JSON.parse(t)}catch{return t}},JSONString:t=>{try{return JSON.stringify(t)}catch{return"{}"}},Object:t=>{if(Ze(t))return t;if(We(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=>We(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:In.String(t)).join(""):t instanceof Element?t.outerHTML:In.String(t),Values:(t,e)=>{if(t instanceof HTMLFormElement)return jn(t);if(t instanceof HTMLElement){const e=t.querySelectorAll("input, select, textarea"),n={};return e.forEach(t=>{t.name&&(n[t.name]=Mn(t))}),n}return{}},FormEncoded:(t,e)=>{const n=t instanceof HTMLElement?In.Values(t,e):t;if(!Ze(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=In.Values(t,e);return In.FormEncoded(n,e)},"Values:JSON":(t,e)=>{const n=In.Values(t,e);return JSON.stringify(n)}};function jn(t){const e={};return t.querySelectorAll("input, select, textarea").forEach(t=>{const n=t;if(n.name){const t=Mn(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 Mn(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 Dn={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 Pn(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 In.Number(t).toFixed(n??0)}if(null==t)return t;let r=In[e];if(r)return r(t,n);const s=Dn[e.toLowerCase()];if(s&&(r=In[s],r))return r(t,n);const i=Ln.conversions[e];if("function"==typeof i)return i(t,n);for(const n of Ln.conversions.dynamicResolvers){const r=n(e,t);if(void 0!==r)return r}return console.warn("Unknown conversion type: "+e),t}const Fn={as:{name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(t,...e){const[n,r]=e;return Pn(n,r,t)},validate:t=>sn(t,2,"as","value, type")??on(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(!We(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 We(n);case"number":return ze(n)&&!isNaN(n);case"boolean":return Je(n);case"object":return Ze(n);case"array":return Array.isArray(n);case"function":return Ge(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||Ze(n)&&0===Object.keys(n).length;default:return n?.constructor?.name?.toLowerCase()===r.toLowerCase()}},validate:t=>sn(t,2,"is","value, type")??on(t,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(t,e)=>e,validate:t=>sn(t,1,"async","expression")}},Bn=new Set(["__proto__","constructor","prototype"]);function _n(t,e){if(t instanceof Element)return nn(t,e);if(Ze(t)){if(Bn.has(e))return;return t[e]}return t[e]}function Vn(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 qn={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 Vn(n)&&!(r in n)?Array.from(n,t=>_n(t,r)):_n(n,r)}},validate:t=>sn(t,2,"possessive","element, property")??on(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 nn(t.me,n);if(Ze(t.me)){if(Bn.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 nn(r,n);if(Ze(r)){if(Bn.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 nn(t.you,n);if(Ze(t.you)){if(Bn.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 nn(r,n);if(Ze(r)){if(Bn.has(n))return;return r[n]}return r[n]}},validate:t=>sn(t,2,"of","property, object")??on(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=>hn(t,1,2,"attribute","attributeName, optional element")??on(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=>hn(t,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??on(t,0,"attributeWithValue","attribute name")??on(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 Hn(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 Un(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 Wn(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 zn(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 Qn(t,e);const n=t;switch(t.type){case"literal":return function(t){return t.value}(n);case"identifier":return Qn(n,e);case"binaryExpression":return async function(t,e){const n=t.operator,r=t.right,s=t.left;if("="===n){const n=await zn(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):(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 zn(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 zn(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 zn(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 zn(t.right,e);return Un(e,"styleRef").evaluate(e,s.value.slice(1),n)}if("of"===n){const n=tr(t.left);if(n){const r=await zn(t.right,e);let s=r;for(const t of n){if(null==s)return;s=Ye(s)?nn(s,t):s[t]}return"function"==typeof s?s.bind(r):s}}const i=await zn(t.left,e);if("and"===n){if(!i)return i;const n=await zn(t.right,e);return Un(e,"and").evaluate(e,i,n)}if("or"===n){if(i)return i;const n=await zn(t.right,e);return Un(e,"or").evaluate(e,i,n)}const o=await zn(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"+":return"string"==typeof i||"string"==typeof o?(i??"")+""+(o??""):Array.isArray(i)?Array.isArray(o)?[...i,...o]:[...i,o]:Wn(await Un(e,"addition").evaluate(e,{left:i,right:o}));case"-":return Wn(await Un(e,"subtraction").evaluate(e,{left:i,right:o}));case"*":return Wn(await Un(e,"multiplication").evaluate(e,{left:i,right:o}));case"/":return Wn(await Un(e,"division").evaluate(e,{left:i,right:o}));case"%":case"mod":return Wn(await Un(e,"modulo").evaluate(e,{left:i,right:o}));case"^":case"**":return Wn(await Un(e,"power").evaluate(e,{left:i,right:o}));case">":case"is greater than":return Un(e,"greaterThan").evaluate(e,i,o);case"<":case"is less than":return Un(e,"lessThan").evaluate(e,i,o);case">=":case"is greater than or equal to":return Un(e,"greaterThanOrEqual").evaluate(e,i,o);case"<=":case"is less than or equal to":return Un(e,"lessThanOrEqual").evaluate(e,i,o);case"==":return Un(e,"equals").evaluate(e,c,u);case"is":case"am":case"equals":case"is equal":case"is equal to":{const n=rr(t,i,o);return void 0!==n?n:Un(e,"equals").evaluate(e,c,u)}case"!=":return Un(e,"notEquals").evaluate(e,c,u);case"is not":case"is not equal":case"is not equal to":{const n=rr(t,i,o);return void 0!==n?!n:Un(e,"notEquals").evaluate(e,c,u)}case"===":case"really equals":case"is really":case"is really equal to":return Un(e,"strictEquals").evaluate(e,c,u);case"!==":case"is not really":case"is not really equal to":return Un(e,"strictNotEquals").evaluate(e,c,u);case"as":return Un(e,"as").evaluate(e,i,ir(o));case"contains":case"contain":case"includes":case"include":return Un(e,"contains").evaluate(e,c,u);case"does not contain":case"do not contain":case"does not contains":case"does not include":return Un(e,"doesNotContain").evaluate(e,c,u);case"starts with":return Un(e,"startsWith").evaluate(e,c,u);case"ends with":return Un(e,"endsWith").evaluate(e,c,u);case"does not start with":return!await Un(e,"startsWith").evaluate(e,c,u);case"does not end with":return!await Un(e,"endsWith").evaluate(e,c,u);case"match":case"matches":return Un(e,"matches").evaluate(e,c,nr(t.right,u));case"does not match":case"do not match":return!await Un(e,"matches").evaluate(e,c,nr(t.right,u));case"in":case"is in":case"am in":return er(i,o);case"is not in":case"am not in":return!er(i,o);case"of":return o&&"object"==typeof o?o[i]:void 0;case"precedes":return sr(i,o,Node.DOCUMENT_POSITION_FOLLOWING);case"does not precede":return!sr(i,o,Node.DOCUMENT_POSITION_FOLLOWING);case"follows":return sr(i,o,Node.DOCUMENT_POSITION_PRECEDING);case"does not follow":return!sr(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 zn(t.expression,e),r=ir(t.targetType);return Un(e,"as").evaluate(e,n,r)}(n,e);case"betweenExpression":return async function(t,e){const n=await zn(t.value,e),r=await zn(t.min,e),s=await zn(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 Un(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 zn(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 zn(t.collection,e);if(null==n)return n;const r=async(t,n)=>zn(t,{...e,it:n});switch(t.operator){case"where":return async function(t,e,n){const r=Hn(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=[...Hn(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=Hn(t);return Promise.all(r.map(t=>n(e,t)))}(n,t.right,r);case"split by":return i=await zn(t.right,e),null==(s=n)?[]:(s+"").split(null==i?"":i+"");case"joined by":return function(t,e){const n=null==e?"":e+"";return Hn(t).map(t=>null==t?"":t+"").join(n)}(n,await zn(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 zn(n,e);switch(t.operator){case"not":case"!":return Un(e,"not").evaluate(e,r);case"no":return Un(e,"no").evaluate(e,r);case"-":return-r;case"+":return+r;case"exists":case"some":return Un(e,"exists").evaluate(e,r);case"does not exist":return Un(e,"doesNotExist").evaluate(e,r);case"is empty":return Un(e,"isEmpty").evaluate(e,r);case"is not empty":return Un(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 zn(t.object,e);if(t.computed){const r=await zn(t.property,e);return Array.isArray(n)&&"number"==typeof r&&0>r?n[n.length+r]:n?.[r]}return ur(n,t.property.name,e)}(n,e);case"propertyAccess":return async function(t,e){let n=await zn(t.object,e);for(const r of(t.property+"").split(".")){if(null==n)return;n=await ur(n,r,e)}return n}(n,e);case"callExpression":return async function(t,e){const n=await zn(t.callee,e);if(t.isConstructor&&"function"==typeof n)return new n(...await Promise.all(t.arguments.map(t=>zn(t,e))));if("identifier"===t.callee.type){const r=t.callee.name,s=await async function(t,e,n){return lr.has(e)?Promise.all(t.map(t=>"identifier"===t.type&&t.name?t.name:"selector"===t.type&&t.value?t.value:zn(t,n))):Promise.all(t.map(t=>zn(t,n)))}(t.arguments,r,e);switch(r){case"closest":return Un(e,"closest").evaluate(e,...s);case"previous":case"next":{const n=t.relativePositional;if(n){const t=n.from?hr(await zn(n.from,e)):e.me,i=n.within?hr(await zn(n.within,e)):void 0,o=n.inElt?await zn(n.inElt,e):void 0;return Un(e,r).evaluate(e,s[0],t,{within:i,inElt:o,inSearch:n.inSearch,wrapping:n.wrapping})}return Un(e,r).evaluate(e,...s)}case"first":return Un(e,"first").evaluate(e,...s);case"last":return Un(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=>zn(t,e)));if("memberExpression"===t.callee.type&&t.callee.object){const s=await zn(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 Un(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=yr(t),r=await Promise.all(n.filter(t=>"expr"in t).map(t=>Xn(t.expr,e)));return gr(n,r)}(n,e),i=pr(t,r);s.forEach((t,e)=>t.setAttribute("data-hs-query-id",e+""));try{return await Un(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 cr(t,/\{([^}]*)\}/g,async(t,n)=>(await Xn(n.trim(),e)??"")+"")}(n,e));const r="string"==typeof n?pr(t,n):n,s=await Un(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 Un(e,t.contextType).evaluate(e);case"my":case"myself":case"I":return Un(e,"me").evaluate(e);case"your":case"yourself":return Un(e,"you").evaluate(e);case"its":return Un(e,"it").evaluate(e);case"event":return e.event;case"target":return e.target??e.event?.target??Un(e,"me").evaluate(e);case"body":return"undefined"!=typeof document?document.body:void 0;case"document":return Un(e,"document").evaluate(e);case"window":return Un(e,"window").evaluate(e);default:return}}(n,e);case"possessiveExpression":return async function(t,e){const n=await zn(t.object,e),r=t.property.name;return Un(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 zn(e,r)}}}(n,e);case"conditionalExpression":return async function(t,e){return await zn(t.test,e)?zn(t.consequent,e):t.alternate?zn(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 zn(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 zn(t,e)+"",n[s]=await zn(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 zn(t.target,e);if(null==s)throw Error(`Cannot access property "${r}" of ${s}`);return Un(e,"possessive").evaluate(e,s,r)}(n,e);case"templateLiteral":return async function(t,e){let n=t.value;return n=await cr(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 cr(n,/\$(?:\{([^}]+)\}|\(([^)]+)\))/g,async(t,n,r)=>{const s=n||r;try{return await Xn(s,e)+""}catch{return"undefined"}}),n}(n,e);case"stringPostfix":return async function(t,e){return`${await zn(t.expression,e)}${t.unit}`}(n,e);case"blockLiteral":return or(n,e);default:{const n=kt.get(t.type);if(n)return n(t,e);throw Error("Unknown AST node type: "+t.type)}}}class Jn extends Error{constructor(t){super(`Expression node "${t}" is not synchronously evaluable`),this.name="NotSyncEvaluable"}}function Zn(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 Jn("selector");if(!t.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(n))throw new Jn("selector");if(t.fromQuery&&/\$[^=]/.test(n)){const{selector:r,elements:s}=function(t,e){const n=yr(t),r=n.filter(t=>"expr"in t).map(t=>Gn(t.expr,e));return gr(n,r)}(n,e),i=pr(t,r),o=e?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!o)throw new Jn("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)=>(Gn(n.trim(),e)??"")+"")}(n,e):n,s=pr(t,r),i=e?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!i)throw new Jn("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){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: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);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 Jn("contextReference")}}(n.contextType,e);case"arrayLiteral":return n.elements.map(t=>Zn(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:Zn(t,e)+"",n[s]=Zn(r.value,e)}return n}(n,e);case"asExpression":return Pn(Zn(n.expression,e),ir(n.targetType),e);case"stringPostfix":return`${Zn(n.expression,e)}${n.unit}`;case"blockLiteral":return or(n,e);case"memberExpression":{const t=Zn(n.object,e);if(null==t)return;if(t instanceof Element||Array.isArray(t)||"undefined"!=typeof Node&&t instanceof Node)throw new Jn("memberExpression");const r=t[n.computed?Zn(n.property,e)+"":n.property?.name];return"function"==typeof r?r.bind(t):r}default:throw new Jn(n?.type??"unknown")}}function Gn(t,e){const n=Fe(t);if(!n.success||!n.node){const t=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(t?.message??"unknown error"))}return Zn(n.node,e)}async function Xn(t,e){const n=Fe(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 Kn()};return zn(n.node,r)}let Yn=null;async function Kn(){if(!Yn){const t=await Promise.resolve().then(function(){return mo});Yn=t.createFullExpressionRegistry()}return Yn}async function Qn(t,e){const n=t.name;return"me"===n||"my"===n||"I"===n?Un(e,"me").evaluate(e):"you"===n||"your"===n||"yourself"===n?Un(e,"you").evaluate(e):"it"===n||"its"===n?Un(e,"it").evaluate(e):"window"===n?Un(e,"window").evaluate(e):"document"===n?Un(e,"document").evaluate(e):"global"===t.scope&&e.globals?.has(n)?($t(n,e),e.globals.get(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 tr(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=tr(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 er(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 nr(t,e){return t&&"selector"===t.type&&"string"==typeof t.value?t.value:e}function rr(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 sr(t,e,n){return t instanceof Node&&e instanceof Node&&0!==(t.compareDocumentPosition(e)&n)}function ir(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 or(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 Zn(t.body,i)}catch(e){if(e instanceof Jn)return zn(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 cr(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 ur(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?nn(t,e):Vn(t)&&!(e in t)?Un(n,"possessive").evaluate(n,t,e):t?.[e]}const lr=new Set(["closest","previous","next"]);function hr(t){return t instanceof Element?t:Array.isArray(t)&&t[0]instanceof Element?t[0]:void 0}const fr=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"),dr=/[:&()[\]/]/g;function pr(t,e){return t.fromQuery||!e.startsWith(".")||e.includes("{")?function(t){return t.replace(fr,"$1\\:")}(e):function(t){return t[0]+t.slice(1).replace(dr,"\\$&")}(e)}const mr=/\$\{([^}]+)\}|\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g;function yr(t){const e=[];let n,r=0;for(mr.lastIndex=0;null!==(n=mr.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 gr(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++];Ye(t)?(n+=`[data-hs-query-id='${r.length}']`,r.push(t)):n+=(t??"")+""}return{selector:n,elements:r}}class vr{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&<(`CleanupRegistry: Removed listener '${n}'`)},description:n+" listener"})}registerObserver(t,e){this.addCleanup(t,{type:"observer",cleanup:()=>{e.disconnect(),this.debugMode&<("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(t,e){this.addCleanup(t,{type:"interval",cleanup:()=>{clearInterval(e),this.debugMode&<("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(t,e){this.addCleanup(t,{type:"timeout",cleanup:()=>{clearTimeout(e),this.debugMode&<("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&<("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&<(`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&<("CleanupRegistry: Error during cleanup:",t)}this.typeCounts[t.type]--}return this.elementCleanups.delete(t),this.elementCount--,this.debugMode&<(`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&<("CleanupRegistry: Error during global cleanup:",t)}return this.globalCleanups=[],this.debugMode&<(`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}}const br=new Map;function wr(t,e){return{me:t??null,it:null,you:null,result:null,locals:new Map,globals:e||br,flags:{halted:0,breaking:0,continuing:0,returning:0,async:0}}}class Er{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(t,e){const n=t.toLowerCase();this.sources.has(n)&<("[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 xr{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 kr={evaluate:(t,e)=>zn(t,e)};class Sr{static toTyped(t){return{me:t.me,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 Ar{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=Sr.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 zn(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},kr,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,Sr.fromTyped(s,t)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(r,o),o}catch(t){if(Rr(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 Nr{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 Ar(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 Cr=null;function Tr(){return Cr||(Cr=function(){const t=new Nr,e=new Er,n=new xr,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}()),Cr}class Or{constructor(t={}){this.contextCache=new WeakMap;const e=Tr();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 $r(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 Rr(t){return t instanceof Error?null!==_e(t)||"HALT_EXECUTION"===t.message||"EXIT_COMMAND"===t.message||"EXIT_EXECUTION"===t.message:0}function Lr(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 Ir(t){return null!==t&&"object"==typeof t&&"command"in t&&"selector"in t}const jr=new WeakMap;class Mr{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=br,this.hookRegistry=new Be,t.hooks&&this.hookRegistry.register("default",t.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new vr,this.options.enableAutoCleanup&&this.setupAutoCleanup(),0!=t.registryIntegration&&(this.registryIntegration=new Or("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&<(`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(!He(n)){if("return"===n.error.type){const t=n.error.returnValue;return void 0!==t&&Object.assign(e,{it:t,result:t}),t}throw $r(n.error)}return n.value}try{return await this.processCommand(t,e)}catch(t){const n=_e(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(!He(r))throw $r(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(!He(n))throw $r(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 Rr(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=_e(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 Ve(await o.execute(e,{args:r||[],modifiers:s||{},commandName:i,runtime:this}))}catch(t){const e=this.toSignal(t);if(e)return qe(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(!He(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}),Ve(n.returnValue)}}n=t.value}else{const t=await this.evaluateExpressionWithResult(r,e);if(!He(t))return t;n=t.value}}return Ve(n)}async evaluateExpression(t,e){const n=e.registry?e:{...e,registry:this.expressionRegistry},r=await zn(t,n);return Ir(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 Ve(await zn(t,e))}catch(t){if(t instanceof Error){const e=t;if(e.isHalt||"HALT_EXECUTION"===e.message)return qe({type:"halt"});if(e.isExit||"EXIT_COMMAND"===e.message)return qe({type:"exit",returnValue:e.returnValue});if(e.isBreak)return qe({type:"break"});if(e.isContinue)return qe({type:"continue"});if(e.isReturn)return qe({type:"return",returnValue:e.returnValue})}throw t}}(t,n);if(!He(r))return r;const s=r.value;if(Ir(s)){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:s.command,args:[{type:"literal",value:s.selector}]},e);try{return Ve(await this.executeCommandFromPattern(s.command,s.selector,e))}catch(t){const e=this.toSignal(t);if(e)return qe(e);throw t}}return Ve(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(Rr(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of s)try{n=await this.execute(t,e)}catch(t){if(Rr(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of i)try{n=await this.execute(t,e)}catch(t){if(Rr(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(Rr(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(Rr(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,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&&Rr(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=Mr.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=jr.get(i)??0;if(o>=100)return;if(jr.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=Lr(await t.execute(n,u));void 0!==e&&Object.assign(u,{it:e,result:e})}catch(e){if(Rr(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(Rr(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(Rr(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 Dr(...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 Pr=wn({selector:gn().min(1),single:bn().optional().default(0)});function Fr(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 An{constructor(){super(...arguments),this.name="me",this.category="Reference",this.syntax="me",this.description="References the current element in the execution context",this.inputSchema=Sn(),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 An{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=Sn(),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 An{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=Sn(),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 An{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=Pr,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 Br={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.me??null,validate:un},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.you??null,validate:un},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it,validate:un},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it,validate:un},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.result,validate:un},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:un},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async t=>window,validate:un},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async t=>document,validate:un},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 Fr(s,n)},validate:t=>hn(t,1,2,"styleRef","property, optional element")??on(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 Fr(s,r)},validate:t=>sn(t,2,"possessiveStyleRef","possessor, property")??on(t,0,"possessiveStyleRef","possessor")??on(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 Fr(s,n)},validate:t=>sn(t,2,"ofStyleRef","property, reference")??on(t,0,"ofStyleRef","property")??on(t,1,"ofStyleRef","reference")}};class _r{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 Vr=new class{constructor(){this.domQueryCache=new _r(200,3e3),this.exprResultCache=new _r(500,2e3),this.cssMatchCache=new _r(100,5e3),this.formValueCache=new _r(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(()=>{Vr.cleanup()},1e4);const qr=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=Vr.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 Hr(){Vr.cleanup(),qr.getMetrics().memoryUsage>52428800&&qr.reset()}let Ur=null;function Wr(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 Wr(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 zr(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 Jr(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 Zr(t){try{return Wr(t,"_"),1}catch{return 0}}function Gr(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=zr(t),r=zr(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 Xr(t,e);case"!=":return!Xr(t,e);default:return 0}}function Xr(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?Xr(t?1:0,e):"boolean"==typeof e?Xr(t,e?1:0):t+""==e+""}function Yr(t,e=[]){return{isValid:0,errors:t,suggestions:e}}function Kr(t,e,n=[],r="error"){return{type:t,message:e,suggestions:n,severity:r}}function Qr(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){Ur&&clearInterval(Ur),Ur=setInterval(Hr,t)}();const ts=wn({left:xn().describe("Left operand value"),right:xn().describe("Right operand value")}).strict(),es=wn({operand:xn().describe("Operand value to negate")}).strict();function ns(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType}new class extends An{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=ts,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 An{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=ts,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 An{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=es,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 rs=En([xn(),xn()]),ss=En([xn(),gn()]),is={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(t,e,n){const r=Date.now();try{return Qr(this,t,[e,n],e==n,r)}catch(s){throw Qr(this,t,[e,n],0,r,0,s instanceof Error?s:Error(s+"")),s}},validate:t=>cn(t,"equals"),inputSchema:rs,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"]}},os={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&&Qr(this,t,[e,n],s,r?Date.now():0),s},validate:t=>cn(t,"strictEquals")},as={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&&Qr(this,t,[e,n],s,r?Date.now():0),s},validate:t=>cn(t,"notEquals")},cs={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&&Qr(this,t,[e,n],s,r?Date.now():0),s},validate:t=>cn(t,"strictNotEquals")},us={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=Gr(e,n,"<");return r&&Qr(this,t,[e,n],i,s),i},validate:t=>cn(t,"lessThan")},ls={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=Gr(e,n,"<=");return r&&Qr(this,t,[e,n],i,s),i},validate:t=>cn(t,"lessThanOrEqual")},hs={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=Gr(e,n,">");return r&&Qr(this,t,[e,n],i,s),i},validate:t=>cn(t,"greaterThan")},fs={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=Gr(e,n,">=");return r&&Qr(this,t,[e,n],i,s),i},validate:t=>cn(t,"greaterThanOrEqual")},ds={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(t,e,n){const r=Date.now();try{return Qr(this,t,[e,n],e&&n,r)}catch(s){throw Qr(this,t,[e,n],0,r,0,s instanceof Error?s:Error(s+"")),s}},validate:t=>cn(t,"and"),inputSchema:rs,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"]}},ps={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&&Qr(this,t,[e,n],s,r?Date.now():0),s},validate:t=>cn(t,"or")},ms={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],async evaluate(t,e){const n=t.evaluationHistory,r=!e;return n&&Qr(this,t,[e],r,n?Date.now():0),r},validate:t=>sn(t,1,"not","operand")},ys={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:We(e)||Array.isArray(e)||e instanceof NodeList?0===e.length:e instanceof Node||e instanceof Element?0:Ze(e)?0===Object.keys(e).length:0,n&&Qr(this,t,[e],s,r),s},validate:t=>sn(t,1,"isEmpty","value")},gs={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:(We(e),0),n&&Qr(this,t,[e],s,r),s},validate:t=>sn(t,1,"no","value")},vs={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 ys.evaluate(t,e);return n&&Qr(this,t,[e],s,r),s},validate:t=>sn(t,1,"isNotEmpty","value")},bs={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0,s=ws(e);return n&&Qr(this,t,[e],s,r),s},validate:t=>sn(t,1,"exists","value")};function ws(t){return null==t?0:Array.isArray(t)||"undefined"!=typeof NodeList&&t instanceof NodeList?t.length>0:1}const Es={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=!ws(e);return n&&Qr(this,t,[e],s,r),s},validate:t=>sn(t,1,"doesNotExist","value")},xs={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(ns(e)&&ns(n))return i=e.contains(n),r&&Qr(this,t,[e,n],i,s),i;if(We(e)&&e.match(/^[.#][\w-]+$/)){const o=document.querySelector(e);if(o&&ns(n))return i=o.contains(n),r&&Qr(this,t,[e,n],i,s),i;if(o&&We(n)&&n.match(/^[.#][\w-]+$/)){const a=document.querySelector(n);return i=a?o.contains(a):0,r&&Qr(this,t,[e,n],i,s),i}}if(We(n)&&n.match(/^[.#][\w-]+$/)&&ns(e)){const o=document.querySelector(n);return i=o?e.contains(o):0,r&&Qr(this,t,[e,n],i,s),i}}if(We(e)&&We(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=Ze(e)&&We(n)?n in e:0;return r&&Qr(this,t,[e,n],i,s),i},validate:t=>sn(t,2,"contains","container, value")},ks={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 xs.evaluate(t,e,n);return r&&Qr(this,t,[e,n],i,s),i},validate:t=>sn(t,2,"doesNotContain","container, value")},Ss={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&&Qr(this,t,[e,n],i,s),i},validate:t=>sn(t,2,"startsWith","str, prefix")},As={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&&Qr(this,t,[e,n],i,s),i},validate:t=>sn(t,2,"endsWith","str, suffix")},Ns={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&&Qr(this,t,[e,n,r],a,s?Date.now():0),a},validate:t=>sn(t,3,"between","value, min, max")},Cs={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(t,e,n){const r=Date.now();try{let s;if(e instanceof Element&&We(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 Vr.matches(t,e)}(e,t)}catch(t){s=0}else s=0}else if(We(e)&&We(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 Qr(this,t,[e,n],s,r)}catch(s){throw Qr(this,t,[e,n],0,r,0,s instanceof Error?s:Error(s+"")),s}},validate:t=>sn(t,2,"matches","element, selector"),inputSchema:ss,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"]}},Ts={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&&We(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&&Qr(this,t,[e,n],i,s),i},validate:t=>sn(t,2,"has","element, selector")},Os={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 Ts.evaluate(t,e,n);return r&&Qr(this,t,[e,n],i,s),i},validate:t=>sn(t,2,"doesNotHave","element, selector")},$s={equals:is,strictEquals:os,notEquals:as,strictNotEquals:cs,lessThan:us,lessThanOrEqual:ls,greaterThan:hs,greaterThanOrEqual:fs,and:ds,or:ps,not:ms,no:gs,isEmpty:ys,isNotEmpty:vs,exists:bs,doesNotExist:Es,contains:xs,doesNotContain:ks,startsWith:Ss,endsWith:As,between:Ns,matches:Cs,has:Ts,doesNotHave:Os},Rs=wn({value:gn().describe("String literal value")}).strict(),Ls=wn({value:vn().describe("Number literal value")}).strict(),Is=wn({value:bn().describe("Boolean literal value")}).strict(),js=wn({left:xn().describe("Left operand"),right:xn().describe("Right operand")}).strict(),Ms={stringLiteral:new class extends An{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=Rs,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 An{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=Ls,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 An{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=Is,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 An{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=js,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=Wr(e.left,"left operand")+Wr(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 An{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=js,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=js.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(We(t))return t;if(ze(t))return""+t;if(Je(t))return""+t;if(t instanceof Date)return""+t;try{return t+""}catch{return"[object Object]"}}},multiplication:new class extends An{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=js,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=Wr(e.left,"left operand")*Wr(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 Ds(){return Dr(Br,$s,Ms)}class Ps{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=wr(t);this.runtime.execute(e,n).catch(n=>{console.error('[HyperFixi] Error executing _="" attribute:',n),console.error("Element:",t),console.error("Code:",e)})}}function Fs(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 Bs(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 _s(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 Vs(t){const e=t.trim();return e.startsWith("[@")&&e.endsWith("]")||e.startsWith("@")?1:0}function qs(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 Hs(t,e){for(const n of t)e(n);return t}function Us(t,e,n){for(const r of t)for(const t of e)n(r,t);return t}function Ws(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 zs(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&&Zs(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&&Zs(t));const e=(t+"").trim(),n=e.startsWith(".")?e.substring(1):e;return n.length>0&&Zs(n)?[n]:[]}function Js(t){const e=t.trim();return/^\{[^}]+\}$/.test(e)}function Zs(t){if(!t||0===t.trim().length)return 0;const e=t.trim();return Js(e)?1:/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(e)}function Gs(t,e){return t.map(t=>{if(Js(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 Xs=Symbol("command:name"),Ys=Symbol("command:category"),Ks=Symbol("command:metadata");function Qs(t){return function(e,n){const r=e;r[Xs]=t.name,r[Ys]=t.category,Object.defineProperty(e.prototype,"name",{value:t.name,writable:0,enumerable:1})}}function ti(t){return function(e,n){const r=e,s=r[Ys];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[Ks]=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 ei(t){return()=>new t}function ni(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"tagName"in t&&"string"==typeof t.tagName&&"classList"in t}function ri(t){return null!==t&&"object"==typeof t&&"length"in t&&"number"==typeof t.length&&(Symbol.iterator in t||"function"==typeof t.item)}function si(t,e){return e}function ii(t,e,n){if(ni(t))return t;if(!t){const t=e.me;if(!t)throw Error(si(0,"No target element — provide explicit target or ensure context.me is set"));return oi(t)}if("string"==typeof t){const n=t.trim();if("me"===n){if(!e.me)throw Error(si(0,'Context reference "me" is not available'));return oi(e.me)}if("it"===n){if(!ni(e.it))throw Error(si(0,'Context reference "it" is not an HTMLElement'));return e.it}if("you"===n){if(!e.you)throw Error(si(0,'Context reference "you" is not available'));return oi(e.you)}const r=e.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!r)throw Error(si(0,"DOM not available — cannot resolve element selector"));const s=r.querySelector(n);if(!s)throw Error(si(0,"Element not found with selector: "+n));if(!ni(s))throw Error(si(0,"Element found but is not an HTMLElement: "+n));return s}throw Error(si(0,"Invalid target type: "+typeof t))}function oi(t){if(ni(t))return t;throw Error("Value is not an HTMLElement")}function ai(t,e,n){switch(t.toLowerCase()){case"my":case"me":if(!e.me)throw Error(si(0,'No "me" element in context'));if(!ni(e.me))throw Error(si(0,"context.me is not an HTMLElement"));return e.me;case"its":case"it":if(!e.it)throw Error(si(0,'No "it" value in context'));if(!ni(e.it))throw Error(si(0,"context.it is not an HTMLElement"));return e.it;case"your":case"you":if(!e.you)throw Error(si(0,'No "you" element in context'));if(!ni(e.you))throw Error(si(0,"context.you is not an HTMLElement"));return e.you;default:throw Error(si(0,"Unknown possessive: "+t))}}const ci=["on","from","to","in","with","at"];async function ui(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?!ci.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(!ni(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(ni(s))a.push(s);else if(ri(s)){const t=Array.from(s).filter(ni);a.push(...t)}else if(Array.isArray(s)){const t=s.filter(ni);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(ni);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(!ni(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}return a}function li(t){return"string"==typeof t&&t.trim().startsWith("*")}function hi(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 fi(t,e,n){t.style.setProperty(e,n)}const di=["dialog","details","summary","select"];function pi(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 mi(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=pi(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=pi(t);return"string"==typeof n&&n.startsWith("*")}(t)?{value:pi(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=pi(t);return"string"==typeof e&&e.startsWith("@")}return 0}(t)?{value:(r=t,"attributeAccess"===r.type?"@"+r.attributeName:pi(r)),extractedFromNode:1}:{value:await e.evaluate(t,n),extractedFromNode:0};var r}class yi{async resolveTargets(t,e,n,r){return ui(t,e,n,this.mode,{filterPrepositions:1,fallbackModifierKey:this.preposition},r)}async evaluateFirst(t,e,n){return mi(t,e,n)}parseClassNames(t){return zs(t)}isAttribute(t){return Vs(t.trim())}isCSSProperty(t){return li(t.trim())}validateTargets(t){return Array.isArray(t)&&function(t){return Array.isArray(t)&&t.length>0&&t.every(t=>ni(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 gi=(()=>{let t,e,n=[ti({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"]}),Qs({name:"add",category:"dom"})],r=[],s=yi;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=qs(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=Gs(t.classes,e);n.length>0&&Us(t.targets,n,(t,e)=>{t.classList.contains(e)||t.classList.add(e)});break}case"attribute":n=t.name,r=t.value,Hs(t.targets,t=>{t.setAttribute(n,r)});break;case"styles":Us(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}},_s(e,"AddCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Fs(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}),Bs(e,r)})(),e})();const vi=ei(gi);function bi(t){return t.parentNode?(t.remove(),1):0}let wi=(()=>{let t,e,n=[ti({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"]}),Qs({name:"remove",category:"dom"})],r=[],s=yi;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(ni(r))return{type:"element",targets:[r]};if(Array.isArray(r)&&r.length>0&&ni(r[0]))return{type:"element",targets:r.filter(t=>ni(t))};if("string"==typeof r){const s=r.trim();if(this.isAttribute(s))return{type:"attribute",name:qs(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=Gs(t.classes,e);n.length>0&&Us(t.targets,n,(t,e)=>{t.classList.remove(e)});break}case"attribute":n=t.name,Hs(t.targets,t=>{t.removeAttribute(n)});break;case"styles":Us(t.targets,t.properties,(t,e)=>{t.style.removeProperty(e)});break;case"element":for(const e of t.targets)bi(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}},_s(e,"RemoveCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Fs(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}),Bs(e,r)})(),e})();const Ei=ei(wi);function xi(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 ki(t){if("number"==typeof t){if(0>t)throw Error("Duration must be >= 0");return Math.floor(t)}if("string"==typeof t){const e=xi(t);if(!e)throw Error(`Invalid duration format: "${t}"`);return e.milliseconds}throw Error("Invalid duration type: "+typeof t)}function Si(t){return 0===t.length?[]:"SUMMARY"===t[0].tagName?t.map(t=>t.closest("details")).filter(t=>null!==t):t}function Ai(t,e,n){return()=>{"class"===e?t.classList.toggle(n):"attribute"===e&&Ws(t,n)}}function Ni(t,e,n,r){const s=Ai(t,e,n),i=setTimeout(s,r);return()=>{clearTimeout(i)}}function Ci(t,e,n,r){const s=Ai(t,e,n),i=()=>{s(),t.removeEventListener(r,i)};return t.addEventListener(r,i,{once:1}),()=>{t.removeEventListener(r,i)}}function Ti(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 Oi=/^the\s+(.+?)\s+of\s+(.+)$/i,$i=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 Ri(t){return"string"==typeof t&&Oi.test(t)}function Li(t,e){const n=t.match(Oi);if(!n)return null;try{return{element:ii(n[2].trim(),e),property:n[1].trim()}}catch{return null}}async function Ii(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]),ni(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]),ni(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]),!ni(i))return null;const o=s?.name||s?.value;return o?{element:i,property:o}:null}return null}function ji(t,e){const{element:n,property:r}=t;r.startsWith("*")?fi(n,r.substring(1),e+""):Ti(n,r,e)}async function Mi(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=xi(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 Di=ei((()=>{let t,e,n=[ti({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"]}),Qs({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 Mi(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 ui(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 Ii(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 Mi(t.modifiers,e,n),a=hi(r);if(a){const t=n.me;return{type:"css-property",property:a,targets:t?[t]:[],duration:i,untilEvent:o}}}}const o=hi(r);if(o){const{duration:r,untilEvent:s}=await Mi(t.modifiers,e,n),a={filterPrepositions:1,fallbackModifierKey:"on"};return{type:"css-property",property:o,targets:await ui(t.args.slice(i),e,n,"toggle",a,t.modifiers),duration:r,untilEvent:s}}}const{duration:a,untilEvent:c}=await Mi(t.modifiers,e,n),{value:u}=await mi(s,e,n);if(Ri(u)){const t=Li(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 di.includes(e)}(e)}(e);if(ni(t)||Array.isArray(t)&&t.every(t=>ni(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 di.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}=qs(h);return{type:"attribute",name:r,value:s,targets:await ui(t.args.slice(1),e,n,"toggle",f,t.modifiers),duration:a,untilEvent:c}}case"css-property":{const r=hi(h);if(!r)throw Error("Invalid CSS property: "+h);return{type:"css-property",property:r,targets:await ui(t.args.slice(1),e,n,"toggle",f,t.modifiers)}}case"element":{let i;if(ni(u))i=[u];else if(Array.isArray(u)&&u.every(t=>ni(t)))i=u;else if(h){const t=document.querySelectorAll(h);i=Array.from(t).filter(t=>ni(t))}else i=await ui([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:Si(i)}:"select"===o?{type:"select",targets:i}:{type:"classes",classes:zs(h),targets:i,duration:a,untilEvent:c}}default:{const r=zs(h||u);if(!r.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:r,targets:await ui(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=Gs(t.classes,e);if(0===n.length)return[...t.targets];if(Us(t.targets,n,(t,e)=>{t.classList.toggle(e)}),(t.duration||t.untilEvent)&&n.length)for(const e of t.targets)t.duration&&Ni(e,"class",n[0],t.duration),t.untilEvent&&Ci(e,"class",n[0],t.untilEvent);return[...t.targets]}case"attribute":if(n=t.name,r=t.value,Hs(t.targets,t=>{Ws(t,n,r)}),t.duration||t.untilEvent)for(const e of t.targets)t.duration&&Ni(e,"attribute",t.name,t.duration),t.untilEvent&&Ci(e,"attribute",t.name,t.untilEvent);return[...t.targets];case"css-property":return Hs(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)):nn(e,n)}(t),n=t.property,r=n.startsWith("@")?n.substring(1):n;if("boolean"==typeof e||$i.has(r)||$i.has(r.toLowerCase())){const n=!e;return ji(t,n),n}if("number"==typeof e){const n=0===e?1:0;return ji(t,n),n}if("string"==typeof e){const r="__ht_"+n,s=t.element[r];return""===e&&void 0!==s?(ji(t,s),s):(t.element[r]=e,ji(t,""),"")}ji(t,!e)}(t.target),[t.target.element];case"dialog":return Hs(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 Hs(t.targets,t=>{var e;(e=t).open=!e.open});case"select":return Hs(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&&Ni(e,"class",t.classA,t.duration),t.untilEvent&&Ci(e,"class",t.classA,t.untilEvent);return[...t.targets]}var n,r}},_s(e,"ToggleCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Fs(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}),Bs(e,r)})(),e})());class Pi{async parseInput(t,e,n){const{targets:r}=await async function(t,e,n,r){return{targets:await ui(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=>ni(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 Fi=(()=>{let t,e,n=[ti({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"]}),Qs({name:"show",category:"dom"})],r=[],s=Pi;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=>ni(t))?"string"!=typeof e.defaultDisplay?0:1:0}},_s(e,"ShowCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Fs(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}),Bs(e,r)})(),e})();const Bi=ei(Fi);let _i=(()=>{let t,e,n=[ti({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"]}),Qs({name:"hide",category:"dom"})],r=[],s=Pi;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=>ni(t))?1:0}},_s(e,"HideCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Fs(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}),Bs(e,r)})(),e})();const Vi=ei(_i),qi=ei((()=>{let t,e,n=[ti({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"]}),Qs({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 Ii(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&&Ri(t)){const e=Li(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||!ni(e.me))throw Error("put: no target and context.me is null");return[e.me]}const n=Array.from(document.querySelectorAll(t)).filter(t=>ni(t));if(!n.length)throw Error(`No elements: "${t}"`);return n}parseValue(t){return ni(t)?t:null==t?"":t+""}insertContent(t,e,n){if("replace"!==n)if(ni(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 ni(e)?(t.innerHTML="",t.appendChild(e)):e.includes("<")&&e.includes(">")?t.innerHTML=e:t.textContent=e}resolveEvaluatedAsElements(t){if(ni(t))return[t];if(Array.isArray(t)){const e=t.filter(ni);return e.length>0?e:null}if("undefined"!=typeof NodeList&&t instanceof NodeList){const e=Array.from(t).filter(ni);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}},_s(e,"PutCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Fs(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}),Bs(e,r)})(),e})()),Hi=ei((()=>{let t,e,n=[ti({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"]}),Qs({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?.type;if(i){const s=St.get(i);if(s)return{type:"node-write",node:r,value:await this.extractValue(t,e,n),writer:s}}const o=await this.resolveAttributeWriteTarget(r,t,e,n);if(o){const r=await this.extractValue(t,e,n);return{type:"attribute",elements:o.elements,name:o.name,value:r}}const a=await Ii(r,e,n);if(a){const r=await this.extractValue(t,e,n);if(a.property.startsWith("*")){const t=a.property.substring(1);return{type:"style",element:a.element,property:t,value:r+""}}return{type:"property",element:a.element,property:a.property,value:r}}if("memberExpression"===r?.type||"propertyAccess"===r?.type){const s=await this.tryParseMemberExpression(r,t,e,n);if(s)return s}let c;if(c="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(ni(t)||t instanceof Node)return 0;const e=Object.getPrototypeOf(t);return e===Object.prototype||null===e}(c))return{type:"object-literal",properties:c,targets:await this.resolveTargets(t.modifiers.on,e,n)};if(Ri(c)){const r=Li(c,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(c,t,e,n)}if("string"==typeof c&&li(c)){const r=c.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 c&&Vs(c)){const r=c.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 c){const r=c.match(/^(my|me|its?|your?)\s+(.+)$/i);if(r){const s=ai(r[1],n),i=await this.extractValue(t,e,n);return{type:"property",element:s,property:r[2],value:i}}}if(ni(c))return{type:"property",element:c,property:"textContent",value:await this.extractValue(t,e,n)};if(Array.isArray(c)&&c.length>0&&ni(c[0])){const r=await this.extractValue(t,e,n);return{type:"property",element:c[0],property:"textContent",value:r}}if("string"!=typeof c)throw Error("set command target must be a string or object literal"+("memberExpression"===r?.type||"propertyAccess"===r?.type?` (a property chain evaluated to ${null===c?"null":typeof c} — check that all intermediate objects exist)`:""));return{type:"variable",name:c,value:await this.extractValue(t,e,n)}}async execute(t,e){switch(t.type){case"variable":return function(t,e,n){if(t.startsWith("$"))It(n,t.slice(1),e);else{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)}}}(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 Ti(t.element,t.property,t.value),Object.assign(e,{it:t.value}),{target:t.element,value:t.value,targetType:"property"};case"style":return fi(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))Ti(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 ni(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=ai(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 ii(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(ni);if(ri(t))return Array.from(t).filter(ni);if(ni(t))return[t];if(!t){const t=e.me;return t&&ni(t)?[t]:[]}if("string"==typeof t){const n=t.trim();if("me"===n)return e.me&&ni(e.me)?[e.me]:[];if("it"===n)return ni(e.it)?[e.it]:[];if("you"===n)return e.you&&ni(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(ni)}}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=ii(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(ni)&&"value"in e;case"property":return"string"==typeof e.property&&ni(e.element)&&"value"in e;case"style":return"string"==typeof e.property&&""!==e.property&&ni(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}}},_s(e,"SetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Fs(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}),Bs(e,r)})(),e})());function Ui(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 Wi=ei((()=>{let t,e,n=[ti({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"]}),Qs({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(ni(t))s.push(t);else if(t instanceof NodeList)s.push(...Array.from(t).filter(ni));else if(Array.isArray(t))s.push(...t.filter(ni));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(ni));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()]=Ui(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}},_s(e,"EventDispatchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Fs(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}),Bs(e,r)})(),e})()),zi=ei((()=>{let t,e,n=[ti({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"]}),Qs({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)}},_s(e,"LogCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Fs(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}),Bs(e,r)})(),e})());function Ji(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 Zi(t){return new Promise(e=>setTimeout(e,t))}const Gi=ei((()=>{let t,e,n=[ti({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"]}),Qs({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 Zi(t.milliseconds),{type:"time",result:t.milliseconds,duration:Date.now()-n};if("event"===t.type){const r=t.target??e.me??document,s=(await Ji(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:ki(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:ki(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?Zi(t.milliseconds).then(()=>({result:t.milliseconds,winningCondition:t})):Ji(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()}}},_s(e,"WaitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Fs(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}),Bs(e,r)})(),e})()),Xi=function(t,e){const n=new Nr(null);for(const e of t)n.register(e);return new Mr({registry:n,expressionRegistry:e.expressionRegistry,enableAsyncCommands:e.enableAsyncCommands??1,commandTimeout:e.commandTimeout??1e4,enableErrorReporting:e.enableErrorReporting??1,enableResultPattern:e.enableResultPattern??1})}([vi(),Ei(),Di(),Bi(),Vi(),qi(),Hi(),Wi(),zi(),Gi()],{expressionRegistry:Ds()}),Yi={parse:t=>Fe(t),execute:async(t,e)=>{const n=function(t){if(!t)return wr();if(t.locals instanceof Map&&t.globals instanceof Map&&t.flags)return t;const e=wr(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=Fe(t);if(!r.success||!r.node)throw Error(r.error?.message||"Parse failed");return await Xi.execute(r.node,n)}},Ki=function(t){return new Ps(t)}(Yi),Qi={runtime:Yi,parse:t=>Yi.parse(t),execute:async(t,e)=>Yi.execute(t,e),createContext:wr,attributeProcessor:Ki,version:"1.1.0-minimal-v2-tree-shakeable",commands:["add","remove","toggle","show","hide","put","set","send","log","wait"],eval:async(t,e)=>Yi.execute(t,e),init:()=>{Ki.init()}};"undefined"!=typeof window&&(window.hyperfixi=Qi,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{Ki.init()}):Ki.init());const to={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"},eo=wn({collection:xn().describe("Collection to operate on (array, NodeList, or string)")}).strict(),no=wn({collection:xn().describe("Collection to access"),index:vn().describe("Index position to access")}).strict(),ro=wn({collection:xn().describe("Collection to select random item from")}).strict();new class extends An{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=eo,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:to[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 An{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=eo,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:to[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 An{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=no,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:to[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 An{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=ro,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:to[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 so={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:We(n)?n.length>0?n[0]:null:Ze(n)&&"length"in n&&ze(n.length)&&n.length>0?n[0]:null},validate:t=>ln(t,1,"first","collection")},io={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 We(n)?n.length>0?n[n.length-1]:null:Ze(n)&&"length"in n&&ze(n.length)&&n.length>0?n[n.length-1]:null},validate:t=>ln(t,1,"last","collection")},oo={name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(t,...e){const[n,r]=e;if(!ze(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(We(i)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}if(Ze(i)&&"length"in i&&ze(i.length)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}return null},validate:t=>hn(t,1,2,"at","index, optional collection")??function(t){return"number"!=typeof t[0]?"at index must be a number":null}(t)};function ao(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?ao(r,e):null}function co(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?co(r,e):null}function uo(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 lo(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 ho={first:so,last:io,at:oo,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?uo(i,n,s,1):ao(i,n):i.nextElementSibling:null},validate:t=>ln(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?uo(i,n,s,0):co(i,n):i.previousElementSibling:null},validate:t=>ln(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=lo(t);for(const t of r)if(lo(t)>s)return t;return null}(i,n,o):null},validate:t=>hn(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=lo(t);for(let t=r.length-1;t>=0;t--){const e=r[t];if(s>lo(e))return e}return null}(i,n,o):null},validate:t=>hn(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 fo{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:Jr(Wr(t,"left operand")+Wr(n,"right operand"),"addition"),type:"number"}}catch(t){return{success:0,errors:[Kr("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 Yr([Kr("missing-argument","Input is null or undefined")],["Provide an object with left and right operands"]);if("object"!=typeof t)return Yr([Kr("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"),Yr([Kr("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 Zr(n)?Zr(r)?{isValid:1,errors:[],suggestions:[]}:{isValid:0,errors:[Kr("type-mismatch","Right operand cannot be converted to number: "+r)],suggestions:["Provide a numeric value for right operand"]}:{isValid:0,errors:[Kr("type-mismatch","Left operand cannot be converted to number: "+n)],suggestions:["Provide a numeric value for left operand"]}}}const po={addition:new fo,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:Jr(Wr(t,"left operand")-Wr(n,"right operand"),"subtraction"),type:"number"}}catch(t){return{success:0,errors:[Kr("runtime-error","Subtraction failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new fo).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:Jr(Wr(t,"left operand")*Wr(n,"right operand"),"multiplication"),type:"number"}}catch(t){return{success:0,errors:[Kr("runtime-error","Multiplication failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new fo).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}(Wr(t,"left operand"),Wr(n,"right operand"),1);return{success:1,value:r,type:"number"}}catch(t){return{success:0,errors:[Kr("runtime-error","Division failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new fo).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}(Wr(t,"left operand"),Wr(n,"right operand"));return{success:1,value:r,type:"number"}}catch(t){return{success:0,errors:[Kr("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 fo).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=Wr(t,"left operand"),s=Wr(n,"right operand");return{success:1,value:Jr(Math.pow(r,s),"power"),type:"number"}}catch(t){return{success:0,errors:[Kr("runtime-error","Power failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new fo).validate(t)}}};var mo=Object.freeze({__proto__:null,conversion:Fn,conversionExpressions:Fn,createCommonRegistry:function(){return Dr(Br,$s,Ms,Fn,ho)},createCoreRegistry:Ds,createExpressionRegistry:Dr,createFullExpressionRegistry:function(){return Dr(Br,$s,Fn,ho,qn,Ms,po)},createFullRegistry:function(){return Dr(Br,$s,Ms,Fn,ho,qn)},logical:$s,logicalExpressions:$s,positional:ho,positionalExpressions:ho,properties:qn,propertiesExpressions:qn,references:Br,referencesExpressions:Br,special:Ms,specialExpressions:Ms});return Qi}();
|
|
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","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"method":r.method=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"]);function Ie(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 je(t){if(t.isAtEnd())return 1;const e=t.peek().value;return["as","with","{","then","end","else","otherwise",")"].includes(e)||ye(t)}function Me(t){if(t.check("{"))return 0;if(!t.checkIdentifierLike())return 0;const e=t.peekAt(1);return null!==e&&":"===e.value}function De(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 Pe=new Set(["em","ex","cap","ch","ic","rem","lh","rlh","vw","vh","vi","vb","vmin","vmax","cm","mm","Q","pc","pt","px"]);class Fe{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=Fe.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=Fe.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()&&!Fe.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(Pe.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"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 Ie(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 Ie(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 Ie(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(!(Fe.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}}),Fe.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"].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=function(t){const e=t.savePosition();let n="";for(;!t.isAtEnd()&&!je(t);)n+=t.advance().value;return n&&"/"!==n?{type:"literal",value:n,raw:n,start:e,end:t.savePosition()}:(t.restorePosition(e),null)}(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=Me(t)?De(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 Be(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 Fe(n,e,t).parse()}Fe.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty","ignoring case"]),Fe.PRATT_TABLE=Et,Fe.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];class _e{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 Ve(t){return t instanceof Error&&("isHalt"in t||"isExit"in t||"isBreak"in t||"isContinue"in t||"isReturn"in t)?t:null}function qe(t){return{ok:1,value:t}}function He(t){return{ok:0,error:t}}function Ue(t){return 1==t.ok}const We=new Map,ze=new WeakMap;function Je(t){let e=ze.get(t);return e||(e=new Map,ze.set(t,e)),e}function Ze(t){return t.owner||(t.me instanceof Element?t.me:null)}function Ge(t,e){const n=Ze(t);if(n)return Lt(e,t),Je(n).get(e)}function Xe(t,e,n){const r=Ze(t);r&&(Je(r).set(e,n),Rt(e,n,t))}function Ye(t,e){return{me:t??null,owner:t??null,it:null,you:null,result:null,locals:new Map,globals:e||We,flags:{halted:0,breaking:0,continuing:0,returning:0,async:0}}}function Ke(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"tagName"in t&&"string"==typeof t.tagName&&"classList"in t}function Qe(t){return null!==t&&"object"==typeof t&&"length"in t&&"number"==typeof t.length&&(Symbol.iterator in t||"function"==typeof t.item)}function tn(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 en(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 Xe(n,t,e)}const nn=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 rn(t){const e=nn.get("String");return e?e.isType(t):"string"==typeof t}function sn(t){const e=nn.get("Number");return e?e.isType(t):"number"==typeof t}function on(t){const e=nn.get("Boolean");return e?e.isType(t):"boolean"==typeof t}function an(t){const e=nn.get("Object");return e?e.isType(t):"object"==typeof t&&null!==t}function cn(t){const e=nn.get("Function");return e?e.isType(t):"function"==typeof t}function un(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"style"in t}function ln(t){return t instanceof Element}function hn(t){return t instanceof HTMLElement}const fn=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function dn(t,e){return fn.has(e.toLowerCase())?t.hasAttribute(e):t.getAttribute(e)}const pn={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=>un(t)?t.tabIndex:void 0,hidden:t=>un(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 mn(t,e){if(e.startsWith("*"))return function(t,e){if(!hn(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 hn(t)?getComputedStyle(t).getPropertyValue(n):void 0}if(e.startsWith("@"))return dn(t,e.slice(1));const n=pn[e.toLowerCase()];if(n)return n(t);if(function(t,e){return t.hasAttribute(e)}(t,e))return dn(t,e);const r=t[e];return cn(r)?r.bind(t):r}const yn={1:"one",2:"two",3:"three",4:"four",5:"five"};function gn(t,e,n,r){return t.length!==e?`${n} requires exactly ${s=e,yn[s]??s+""} argument${1===e?"":"s"}${r?` (${r})`:""}`:null;var s}function vn(t,e,n,r){return"string"!=typeof t[e]?`${n} ${r||"argument "+(e+1)} must be a string`:null}function bn(t,e,n){return gn(t,1,e,n)??vn(t,0,e,n)}function wn(t,e){return gn(t,2,e,"left, right")}function En(){return null}function xn(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 kn(t,e,n,r,s){return e>t.length||t.length>n?`${r} requires ${e}-${n} arguments${s?` (${s})`:""}`:null}function Sn(t,e,n,r=[]){return{type:t,message:e,suggestions:r,...n&&{path:n}}}const An=("undefined"!=typeof process?1:0)||"undefined"!=typeof process&&"true"===process.env.HYPERFIXI_SKIP_VALIDATION||"undefined"!=typeof globalThis&&"true"===globalThis.HYPERFIXI_SKIP_VALIDATION;let Nn;function Cn(){return Nn({validate:t=>({success:1,data:t})})}function Tn(t,e){if(An)return Cn();const n=Nn({validate:n=>{if("object"!=typeof n||null===n||Array.isArray(n))return{success:0,error:Sn("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:Sn("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:Sn("missing-argument",`Required field "${e}" is missing`,e)};const i=n.validate(t);if(!i.success)return{success:0,error:Sn("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=()=>Tn(t,{strict:1}),n}Nn=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 Nn(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:Sn("runtime-error",`String must be at least ${t} characters long`)}:r}};return Nn(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:Sn("runtime-error",`String must be at most ${t} characters long`)}:r}};return Nn(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 Nn(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:Sn("runtime-error",e||"Refinement validation failed")}:s}};return Nn(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 On=t=>function(t={}){return An?Cn():Nn({validate:e=>t.optional&&null==e?{success:1,data:void 0}:"string"!=typeof e?{success:0,error:Sn("type-mismatch","Expected string, received "+typeof e)}:void 0!==t.minLength&&t.minLength>e.length?{success:0,error:Sn("runtime-error",`String must be at least ${t.minLength} characters long`)}:void 0!==t.maxLength&&e.length>t.maxLength?{success:0,error:Sn("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:Sn("runtime-error",`Expected "${t.pattern.source.slice(1,-1)}", received "${e}"`)}:{success:0,error:Sn("missing-argument","String does not match required pattern")}:{success:1,data:e},...t.description&&{description:t.description}})}(t||{}),$n=t=>function(t={}){return An?Cn():Nn({validate:e=>{const n=Number(e);return isNaN(n)?{success:0,error:Sn("type-mismatch","Expected number, received "+typeof e)}:void 0!==t.min&&t.min>n?{success:0,error:Sn("runtime-error","Number must be at least "+t.min)}:void 0!==t.max&&n>t.max?{success:0,error:Sn("runtime-error","Number must be at most "+t.max)}:{success:1,data:n}}})}(t||{}),Rn=()=>An?Cn():Nn({validate:t=>"boolean"!=typeof t?{success:0,error:Sn("type-mismatch","Expected boolean, received "+typeof t)}:{success:1,data:t}}),Ln=t=>Tn(t),In=t=>function(t){return An?Cn():Nn({validate:e=>{if(!Array.isArray(e))return{success:0,error:Sn("type-mismatch","Expected array, received "+typeof e)};if(e.length!==t.length)return{success:0,error:Sn("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:Sn("runtime-error",s.error.message,s.error.path?`${r}.${s.error.path}`:""+r)};n.push(s.data)}return{success:1,data:n}}})}(t),jn=()=>Cn(),Mn=()=>Cn(),Dn=()=>function(t,e="Custom validation failed"){return An?Cn():Nn({validate:n=>t(n)?{success:1,data:n}:{success:0,error:Sn("runtime-error",e)}})}(t=>void 0===t,"Expected undefined");class Pn{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||sn(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":an(t)?"object":typeof t}inferEvaluationType(t){return void 0===t?"Undefined":null===t?"Null":rn(t)?"String":sn(t)?"Number":on(t)?"Boolean":Array.isArray(t)?"Array":this.isElement(t)?"Element":"Object"}normalizeCollection(t){return Array.isArray(t)?t:t instanceof NodeList?Array.from(t):rn(t)?t.split(""):null==t?[]:an(t)&&Symbol.iterator in t?Array.from(t):[]}toNumber(t){if(sn(t)&&Number.isFinite(t))return t;if(rn(t)){const e=Number(t);return Number.isFinite(e)?e:null}return on(t)?t?1:0:null}}function Fn(t,e,n,r,s="runtime-error"){return{success:0,error:{name:t+"ConversionError",type:s,message:n,code:e,suggestions:r}}}function Bn(t,e){return{success:1,value:t,type:e}}function _n(t,e){return`${t}: ${e instanceof Error?e.message:e+""}`}const Vn={Array:(t,e)=>{try{return Array.isArray(t)?Bn(t,"array"):t instanceof NodeList?Bn(Array.from(t),"array"):Bn(null==t?[]:[t],"array")}catch(t){return Fn("Array","ARRAY_CONVERSION_FAILED",_n("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?Bn("","string"):rn(t)?Bn(t,"string"):an(t)?Bn(JSON.stringify(t),"string"):Bn(t+"","string")}catch(t){return Fn("String","STRING_CONVERSION_FAILED",_n("Failed to convert value to String",t),["Check if object has circular references","Ensure value is serializable"])}},Boolean:(t,e)=>{try{if(on(t))return Bn(t,"boolean");if(null==t)return Bn(0,"boolean");if(rn(t)){const e=t.toLowerCase().trim();return Bn("false"!==e&&"0"!==e&&""!==e,"boolean")}return sn(t)?Bn(0!==t&&!isNaN(t),"boolean"):Bn(!!t,"boolean")}catch(t){return Fn("Boolean","BOOLEAN_CONVERSION_FAILED",_n("Failed to convert value to Boolean",t),["Use explicit true/false values","Check for unexpected data types"])}},Number:(t,e)=>{try{if(sn(t))return Bn(t,"number");if(null==t)return Bn(0,"number");const e=Number(t);return isNaN(e)?Fn("Number","INVALID_NUMBER",`Cannot convert "${t}" to a valid number`,["Check if value contains non-numeric characters","Use a valid numeric format"],"invalid-argument"):Bn(e,"number")}catch(t){return Fn("Number","NUMBER_CONVERSION_FAILED",_n("Failed to convert value to Number",t),["Ensure value is convertible to number","Check for special characters"])}},Int:(t,e)=>{const n=Vn.Number(t,e);return n.success?Bn(Math.trunc(n.value),"number"):n},Float:(t,e)=>{const n=Vn.Number(t,e);return n.success?Bn(parseFloat(""+n.value),"number"):n},Date:(t,e)=>{try{if(t instanceof Date)return Bn(t,"object");if(null==t)return Bn(new Date(""),"object");if(rn(t)&&/^\d{4}-\d{2}-\d{2}$/.test(t)){const[e,n,r]=t.split("-").map(Number);return Bn(new Date(e,n-1,r),"object")}const e=new Date(t);return isNaN(e.getTime())?Fn("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"):Bn(e,"object")}catch(t){return Fn("Date","DATE_CONVERSION_FAILED",_n("Failed to convert value to Date",t),["Check date format","Ensure value is a valid date string or timestamp"])}},JSON:(t,e)=>{if(!rn(t))return Bn(t,"object");try{return Bn(JSON.parse(t),"object")}catch(t){return Fn("JSON","JSON_PARSE_FAILED",_n("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 Bn(JSON.stringify(t),"string")}catch(t){return Fn("JSONString","JSON_STRINGIFY_FAILED",_n("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(an(t))return Bn(t,"object");if(rn(t))try{return Bn(JSON.parse(t),"object")}catch(t){return Fn("Object","JSON_PARSE_FAILED",_n("Cannot parse JSON string",t),["Check JSON syntax","Ensure proper escaping of quotes","Validate JSON format"],"syntax-error")}return Bn({},"object")}catch(t){return Fn("Object","OBJECT_CONVERSION_FAILED",_n("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 Bn(zn(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=Jn(e);void 0!==t&&(n[e.name]=t)}}),Bn(n,"object")}return Bn({},"object")}catch(t){return Fn("FormValues","FORM_VALUES_EXTRACTION_FAILED",_n("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=Vn.Values(t,e);if(!r.success)return r;n=r.value}if(!an(n))return Bn("","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 Bn(""+r,"string")}catch(t){return Fn("FormEncoded","FORM_ENCODE_FAILED",_n("Failed to URL-encode values",t),["Ensure input is a form element or plain object of scalar/array values"])}},Set:(t,e)=>{try{return Bn(new Set(t),"object")}catch(t){return Fn("Set","SET_CONVERSION_FAILED",_n("Failed to convert to Set",t),["Ensure the value is iterable"])}},Map:(t,e)=>{try{return Bn(new Map(Object.entries(t??{})),"object")}catch(t){return Fn("Map","MAP_CONVERSION_FAILED",_n("Failed to convert to Map",t),["Ensure the value is a plain object"])}},Keys:(t,e)=>t instanceof Map?Bn(Array.from(t.keys()),"array"):Bn(Object.keys(t??{}),"array"),Entries:(t,e)=>t instanceof Map?Bn(Array.from(t.entries()),"array"):Bn(Object.entries(t??{}),"array"),Reversed:(t,e)=>{try{return Bn(Array.from(t).reverse(),"array")}catch(t){return Fn("Reversed","REVERSED_CONVERSION_FAILED",_n("Failed to reverse value",t),["Ensure the value is array-like"])}},Unique:(t,e)=>{try{return Bn([...new Set(t)],"array")}catch(t){return Fn("Unique","UNIQUE_CONVERSION_FAILED",_n("Failed to dedupe value",t),["Ensure the value is iterable"])}},Flat:(t,e)=>{try{return Bn(Array.from(t).flat(),"array")}catch(t){return Fn("Flat","FLAT_CONVERSION_FAILED",_n("Failed to flatten value",t),["Ensure the value is array-like"])}}},qn=Ln({value:Mn(),type:On().min(1)}),Hn=Ln({value:Mn(),type:On().min(1)});new class extends Pn{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=qn,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=Vn.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=Vn[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=Vn[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 Pn{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=Hn,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=rn(s);break;case"number":a=sn(s)&&!isNaN(s);break;case"boolean":a=on(s);break;case"object":a=an(s);break;case"array":a=Array.isArray(s);break;case"function":a=cn(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||an(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 Un={conversions:{dynamicResolvers:[]}},Wn={Array:t=>Array.isArray(t)?t:t instanceof NodeList?Array.from(t):null==t?[]:[t],String:t=>null==t?"":rn(t)?t:an(t)?JSON.stringify(t):t+"",Boolean:t=>{if(on(t))return t;if(null==t)return 0;if(rn(t)){const e=t.toLowerCase().trim();return"false"===e||"0"===e||""===e?0:1}return sn(t)?0!==t&&!isNaN(t):!!t},Number:t=>{if(sn(t))return t;if(null==t)return 0;const e=Number(t);return isNaN(e)?0:e},Math:t=>{if(sn(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(!sn(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=Wn.Number(t);return Math.trunc(e)},Float:t=>{const e=Wn.Number(t);return parseFloat(""+e)},Date:t=>{if(t instanceof Date)return t;if(null==t)return new Date(NaN);if(rn(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(!rn(t))return t;try{return JSON.parse(t)}catch{return t}},JSONString:t=>{try{return JSON.stringify(t)}catch{return"{}"}},Object:t=>{if(an(t))return t;if(rn(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=>rn(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:Wn.String(t)).join(""):t instanceof Element?t.outerHTML:Wn.String(t),Values:(t,e)=>{if(t instanceof HTMLFormElement)return zn(t);if(t instanceof HTMLElement){const e=t.querySelectorAll("input, select, textarea"),n={};return e.forEach(t=>{t.name&&(n[t.name]=Jn(t))}),n}return{}},FormEncoded:(t,e)=>{const n=t instanceof HTMLElement?Wn.Values(t,e):t;if(!an(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=Wn.Values(t,e);return Wn.FormEncoded(n,e)},"Values:JSON":(t,e)=>{const n=Wn.Values(t,e);return JSON.stringify(n)}};function zn(t){const e={};return t.querySelectorAll("input, select, textarea").forEach(t=>{const n=t;if(n.name){const t=Jn(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 Jn(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 Zn={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 Gn(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 Wn.Number(t).toFixed(n??0)}if(null==t)return t;let r=Wn[e];if(r)return r(t,n);const s=Zn[e.toLowerCase()];if(s&&(r=Wn[s],r))return r(t,n);const i=Un.conversions[e];if("function"==typeof i)return i(t,n);for(const n of Un.conversions.dynamicResolvers){const r=n(e,t);if(void 0!==r)return r}return console.warn("Unknown conversion type: "+e),t}const Xn={as:{name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(t,...e){const[n,r]=e;return Gn(n,r,t)},validate:t=>gn(t,2,"as","value, type")??vn(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(!rn(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 rn(n);case"number":return sn(n)&&!isNaN(n);case"boolean":return on(n);case"object":return an(n);case"array":return Array.isArray(n);case"function":return cn(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||an(n)&&0===Object.keys(n).length;default:return n?.constructor?.name?.toLowerCase()===r.toLowerCase()}},validate:t=>gn(t,2,"is","value, type")??vn(t,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(t,e)=>e,validate:t=>gn(t,1,"async","expression")}},Yn=new Set(["__proto__","constructor","prototype"]);function Kn(t,e){if(t instanceof Element)return mn(t,e);if(an(t)){if(Yn.has(e))return;return t[e]}return t[e]}function Qn(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 tr={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 Qn(n)&&!(r in n)?Array.from(n,t=>Kn(t,r)):Kn(n,r)}},validate:t=>gn(t,2,"possessive","element, property")??vn(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 mn(t.me,n);if(an(t.me)){if(Yn.has(n))return;return t.me[n]}return t.me[n]}},validate:t=>bn(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 mn(r,n);if(an(r)){if(Yn.has(n))return;return r[n]}return r[n]},validate:t=>bn(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 mn(t.you,n);if(an(t.you)){if(Yn.has(n))return;return t.you[n]}return t.you[n]}},validate:t=>bn(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 mn(r,n);if(an(r)){if(Yn.has(n))return;return r[n]}return r[n]}},validate:t=>gn(t,2,"of","property, object")??vn(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=>kn(t,1,2,"attribute","attributeName, optional element")??vn(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=>kn(t,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??vn(t,0,"attributeWithValue","attribute name")??vn(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=>bn(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=>bn(t,"idReference","idValue")}};function er(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 nr(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 rr(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 sr(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 hr(t,e);const n=t;switch(t.type){case"literal":return function(t){return t.value}(n);case"identifier":return hr(n,e);case"binaryExpression":return async function(t,e){const n=t.operator,r=t.right,s=t.left;if("="===n){const n=await sr(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?Xe(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 sr(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 sr(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 sr(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 sr(t.right,e);return nr(e,"styleRef").evaluate(e,s.value.slice(1),n)}if("of"===n){const n=fr(t.left);if(n){const r=await sr(t.right,e);let s=r;for(const t of n){if(null==s)return;s=ln(s)?mn(s,t):s[t]}return"function"==typeof s?s.bind(r):s}}const i=await sr(t.left,e);if("and"===n){if(!i)return i;const n=await sr(t.right,e);return nr(e,"and").evaluate(e,i,n)}if("or"===n){if(i)return i;const n=await sr(t.right,e);return nr(e,"or").evaluate(e,i,n)}const o=await sr(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=tn(n)),"string"==typeof r&&(r=tn(r))),"string"==typeof n||"string"==typeof r?(n??"")+""+(r??""):Array.isArray(n)?Array.isArray(r)?[...n,...r]:[...n,r]:rr(await nr(e,"addition").evaluate(e,{left:n,right:r}))}case"-":return rr(await nr(e,"subtraction").evaluate(e,{left:i,right:o}));case"*":return rr(await nr(e,"multiplication").evaluate(e,{left:i,right:o}));case"/":return rr(await nr(e,"division").evaluate(e,{left:i,right:o}));case"%":case"mod":return rr(await nr(e,"modulo").evaluate(e,{left:i,right:o}));case"^":case"**":return rr(await nr(e,"power").evaluate(e,{left:i,right:o}));case">":case"is greater than":return nr(e,"greaterThan").evaluate(e,i,o);case"<":case"is less than":return nr(e,"lessThan").evaluate(e,i,o);case">=":case"is greater than or equal to":return nr(e,"greaterThanOrEqual").evaluate(e,i,o);case"<=":case"is less than or equal to":return nr(e,"lessThanOrEqual").evaluate(e,i,o);case"==":return nr(e,"equals").evaluate(e,c,u);case"is":case"am":case"equals":case"is equal":case"is equal to":{const n=mr(t,i,o);return void 0!==n?n:nr(e,"equals").evaluate(e,c,u)}case"!=":return nr(e,"notEquals").evaluate(e,c,u);case"is not":case"is not equal":case"is not equal to":{const n=mr(t,i,o);return void 0!==n?!n:nr(e,"notEquals").evaluate(e,c,u)}case"===":case"really equals":case"is really":case"is really equal to":return nr(e,"strictEquals").evaluate(e,c,u);case"!==":case"is not really":case"is not really equal to":return nr(e,"strictNotEquals").evaluate(e,c,u);case"as":return nr(e,"as").evaluate(e,i,gr(o));case"contains":case"contain":case"includes":case"include":return nr(e,"contains").evaluate(e,c,u);case"does not contain":case"do not contain":case"does not contains":case"does not include":return nr(e,"doesNotContain").evaluate(e,c,u);case"starts with":return nr(e,"startsWith").evaluate(e,c,u);case"ends with":return nr(e,"endsWith").evaluate(e,c,u);case"does not start with":return!await nr(e,"startsWith").evaluate(e,c,u);case"does not end with":return!await nr(e,"endsWith").evaluate(e,c,u);case"match":case"matches":return nr(e,"matches").evaluate(e,c,pr(t.right,u));case"does not match":case"do not match":return!await nr(e,"matches").evaluate(e,c,pr(t.right,u));case"in":case"is in":case"am in":return dr(i,o);case"is not in":case"am not in":return!dr(i,o);case"of":return o&&"object"==typeof o?o[i]:void 0;case"precedes":return yr(i,o,Node.DOCUMENT_POSITION_FOLLOWING);case"does not precede":return!yr(i,o,Node.DOCUMENT_POSITION_FOLLOWING);case"follows":return yr(i,o,Node.DOCUMENT_POSITION_PRECEDING);case"does not follow":return!yr(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 sr(t.expression,e),r=gr(t.targetType);return nr(e,"as").evaluate(e,n,r)}(n,e);case"betweenExpression":return async function(t,e){const n=await sr(t.value,e),r=await sr(t.min,e),s=await sr(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 nr(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 sr(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 sr(t.collection,e);if(null==n)return n;const r=async(t,n)=>sr(t,{...e,it:n});switch(t.operator){case"where":return async function(t,e,n){const r=er(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=[...er(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=er(t);return Promise.all(r.map(t=>n(e,t)))}(n,t.right,r);case"split by":return i=await sr(t.right,e),null==(s=n)?[]:(s+"").split(null==i?"":i+"");case"joined by":return function(t,e){const n=null==e?"":e+"";return er(t).map(t=>null==t?"":t+"").join(n)}(n,await sr(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 sr(n,e);switch(t.operator){case"not":case"!":return nr(e,"not").evaluate(e,r);case"no":return nr(e,"no").evaluate(e,r);case"-":return-r;case"+":return+r;case"exists":case"some":return nr(e,"exists").evaluate(e,r);case"does not exist":return nr(e,"doesNotExist").evaluate(e,r);case"is empty":return nr(e,"isEmpty").evaluate(e,r);case"is not empty":return nr(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 sr(t.object,e);if(t.computed){const r=await sr(t.property,e);return Array.isArray(n)&&"number"==typeof r&&0>r?n[n.length+r]:n?.[r]}return Er(n,t.property.name,e)}(n,e);case"propertyAccess":return async function(t,e){let n=await sr(t.object,e);for(const r of(t.property+"").split(".")){if(null==n)return;n=await Er(n,r,e)}return n}(n,e);case"callExpression":return async function(t,e){const n=await sr(t.callee,e);if(t.isConstructor&&"function"==typeof n)return new n(...await Promise.all(t.arguments.map(t=>sr(t,e))));if("identifier"===t.callee.type){const r=t.callee.name,s=await async function(t,e,n){return xr.has(e)?Promise.all(t.map(t=>"identifier"===t.type&&t.name?t.name:"selector"===t.type&&t.value?t.value:sr(t,n))):Promise.all(t.map(t=>sr(t,n)))}(t.arguments,r,e);switch(r){case"closest":return nr(e,"closest").evaluate(e,...s);case"previous":case"next":{const n=t.relativePositional;if(n){const t=n.from?kr(await sr(n.from,e)):e.me,i=n.within?kr(await sr(n.within,e)):void 0,o=n.inElt?await sr(n.inElt,e):void 0;return nr(e,r).evaluate(e,s[0],t,{within:i,inElt:o,inSearch:n.inSearch,wrapping:n.wrapping})}return nr(e,r).evaluate(e,...s)}case"first":return nr(e,"first").evaluate(e,...s);case"last":return nr(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=>sr(t,e)));if("memberExpression"===t.callee.type&&t.callee.object){const s=await sr(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 nr(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=Tr(t),r=await Promise.all(n.filter(t=>"expr"in t).map(t=>cr(t.expr,e)));return Or(n,r)}(n,e),i=Nr(t,r);s.forEach((t,e)=>t.setAttribute("data-hs-query-id",e+""));try{return await nr(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 wr(t,/\{([^}]*)\}/g,async(t,n)=>(await cr(n.trim(),e)??"")+"")}(n,e));const r="string"==typeof n?Nr(t,n):n,s=await nr(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 nr(e,t.contextType).evaluate(e);case"my":case"myself":case"I":return nr(e,"me").evaluate(e);case"your":case"yourself":return nr(e,"you").evaluate(e);case"its":return nr(e,"it").evaluate(e);case"event":return e.event;case"target":return e.target??e.event?.target??nr(e,"me").evaluate(e);case"body":return"undefined"!=typeof document?document.body:void 0;case"document":return nr(e,"document").evaluate(e);case"window":return nr(e,"window").evaluate(e);default:return}}(n,e);case"possessiveExpression":return async function(t,e){const n=await sr(t.object,e),r=t.property.name;return nr(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 sr(e,r)}}}(n,e);case"conditionalExpression":return async function(t,e){return await sr(t.test,e)?sr(t.consequent,e):t.alternate?sr(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 sr(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 sr(t,e)+"",n[s]=await sr(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 sr(t.target,e);if(null==s)throw Error(`Cannot access property "${r}" of ${s}`);return nr(e,"possessive").evaluate(e,s,r)}(n,e);case"templateLiteral":return async function(t,e){let n=t.value;return n=await wr(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=br(t[0],e);for(let e=1;t.length>e&&null!=r;e++)r=r[t[e]];return(r??"")+""}return(br(n,e)??"")+""}catch{return""}}),n=await wr(n,/\$(?:\{([^}]+)\}|\(([^)]+)\))/g,async(t,n,r)=>{const s=n||r;try{return await cr(s,e)+""}catch{return"undefined"}}),n}(n,e);case"stringPostfix":return async function(t,e){return`${await sr(t.expression,e)}${t.unit}`}(n,e);case"blockLiteral":return vr(n,e);default:{const n=kt.get(t.type);if(n)return n(t,e);throw Error("Unknown AST node type: "+t.type)}}}class ir extends Error{constructor(t){super(`Expression node "${t}" is not synchronously evaluable`),this.name="NotSyncEvaluable"}}function or(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 ir("selector");if(!t.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(n))throw new ir("selector");if(t.fromQuery&&/\$[^=]/.test(n)){const{selector:r,elements:s}=function(t,e){const n=Tr(t),r=n.filter(t=>"expr"in t).map(t=>ar(t.expr,e));return Or(n,r)}(n,e),i=Nr(t,r),o=e?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!o)throw new ir("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)=>(ar(n.trim(),e)??"")+"")}(n,e):n,s=Nr(t,r),i=e?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!i)throw new ir("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?Ge(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 ir("contextReference")}}(n.contextType,e);case"arrayLiteral":return n.elements.map(t=>or(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:or(t,e)+"",n[s]=or(r.value,e)}return n}(n,e);case"asExpression":return Gn(or(n.expression,e),gr(n.targetType),e);case"stringPostfix":return`${or(n.expression,e)}${n.unit}`;case"blockLiteral":return vr(n,e);case"memberExpression":{const t=or(n.object,e);if(null==t)return;if(t instanceof Element||Array.isArray(t)||"undefined"!=typeof Node&&t instanceof Node)throw new ir("memberExpression");const r=t[n.computed?or(n.property,e)+"":n.property?.name];return"function"==typeof r?r.bind(t):r}default:throw new ir(n?.type??"unknown")}}function ar(t,e){const n=Be(t);if(!n.success||!n.node){const t=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(t?.message??"unknown error"))}return or(n.node,e)}async function cr(t,e){const n=Be(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 lr()};return sr(n.node,r)}let ur=null;async function lr(){if(!ur){const t=await Promise.resolve().then(function(){return ko});ur=t.createFullExpressionRegistry()}return ur}async function hr(t,e){const n=t.name;return"me"===n||"my"===n||"I"===n?nr(e,"me").evaluate(e):"you"===n||"your"===n||"yourself"===n?nr(e,"you").evaluate(e):"it"===n||"its"===n?nr(e,"it").evaluate(e):"window"===n?nr(e,"window").evaluate(e):"document"===n?nr(e,"document").evaluate(e):"global"===t.scope&&e.globals?.has(n)?($t(n,e),e.globals.get(n)):"element"===t.scope?Ge(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 fr(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=fr(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 dr(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 pr(t,e){return t&&"selector"===t.type&&"string"==typeof t.value?t.value:e}function mr(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 yr(t,e,n){return t instanceof Node&&e instanceof Node&&0!==(t.compareDocumentPosition(e)&n)}function gr(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 vr(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 or(t.body,i)}catch(e){if(e instanceof ir)return sr(t.body,i);throw e}}}function br(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 wr(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 Er(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?mn(t,e):Qn(t)&&!(e in t)?nr(n,"possessive").evaluate(n,t,e):t?.[e]}const xr=new Set(["closest","previous","next"]);function kr(t){return t instanceof Element?t:Array.isArray(t)&&t[0]instanceof Element?t[0]:void 0}const Sr=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"),Ar=/[:&()[\]/]/g;function Nr(t,e){return t.fromQuery||!e.startsWith(".")||e.includes("{")?function(t){return t.replace(Sr,"$1\\:")}(e):function(t){return t[0]+t.slice(1).replace(Ar,"\\$&")}(e)}const Cr=/\$\{([^}]+)\}|\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g;function Tr(t){const e=[];let n,r=0;for(Cr.lastIndex=0;null!==(n=Cr.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 Or(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++];ln(t)?(n+=`[data-hs-query-id='${r.length}']`,r.push(t)):n+=(t??"")+""}return{selector:n,elements:r}}class $r{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&<(`CleanupRegistry: Removed listener '${n}'`)},description:n+" listener"})}registerObserver(t,e){this.addCleanup(t,{type:"observer",cleanup:()=>{e.disconnect(),this.debugMode&<("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(t,e){this.addCleanup(t,{type:"interval",cleanup:()=>{clearInterval(e),this.debugMode&<("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(t,e){this.addCleanup(t,{type:"timeout",cleanup:()=>{clearTimeout(e),this.debugMode&<("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&<("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&<(`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&<("CleanupRegistry: Error during cleanup:",t)}this.typeCounts[t.type]--}return this.elementCleanups.delete(t),this.elementCount--,this.debugMode&<(`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&<("CleanupRegistry: Error during global cleanup:",t)}return this.globalCleanups=[],this.debugMode&<(`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 Rr{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(t,e){const n=t.toLowerCase();this.sources.has(n)&<("[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 Lr{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 Ir={evaluate:(t,e)=>sr(t,e)};class jr{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 Mr{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=jr.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 sr(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},Ir,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,jr.fromTyped(s,t)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(r,o),o}catch(t){if(Vr(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 Dr{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 Mr(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 Pr=null;function Fr(){return Pr||(Pr=function(){const t=new Dr,e=new Rr,n=new Lr,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}()),Pr}class Br{constructor(t={}){this.contextCache=new WeakMap;const e=Fr();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 _r(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 Vr(t){return t instanceof Error?null!==Ve(t)||"HALT_EXECUTION"===t.message||"EXIT_COMMAND"===t.message||"EXIT_EXECUTION"===t.message:0}function qr(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 Hr(t){return null!==t&&"object"==typeof t&&"command"in t&&"selector"in t}const Ur=new WeakMap;class Wr{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=We,this.hookRegistry=new _e,t.hooks&&this.hookRegistry.register("default",t.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new $r,this.options.enableAutoCleanup&&this.setupAutoCleanup(),0!=t.registryIntegration&&(this.registryIntegration=new Br("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&<(`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(!Ue(n)){if("return"===n.error.type){const t=n.error.returnValue;return void 0!==t&&Object.assign(e,{it:t,result:t}),t}throw _r(n.error)}return n.value}try{return await this.processCommand(t,e)}catch(t){const n=Ve(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(!Ue(r))throw _r(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(!Ue(n))throw _r(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 Vr(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=Ve(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 qe(await o.execute(e,{args:r||[],modifiers:s||{},commandName:i,runtime:this}))}catch(t){const e=this.toSignal(t);if(e)return He(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(!Ue(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}),qe(n.returnValue)}}n=t.value}else{const t=await this.evaluateExpressionWithResult(r,e);if(!Ue(t))return t;n=t.value}}return qe(n)}async evaluateExpression(t,e){const n=e.registry?e:{...e,registry:this.expressionRegistry},r=await sr(t,n);return Hr(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 qe(await sr(t,e))}catch(t){if(t instanceof Error){const e=t;if(e.isHalt||"HALT_EXECUTION"===e.message)return He({type:"halt"});if(e.isExit||"EXIT_COMMAND"===e.message)return He({type:"exit",returnValue:e.returnValue});if(e.isBreak)return He({type:"break"});if(e.isContinue)return He({type:"continue"});if(e.isReturn)return He({type:"return",returnValue:e.returnValue})}throw t}}(t,n);if(!Ue(r))return r;const s=r.value;if(Hr(s)){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:s.command,args:[{type:"literal",value:s.selector}]},e);try{return qe(await this.executeCommandFromPattern(s.command,s.selector,e))}catch(t){const e=this.toSignal(t);if(e)return He(e);throw t}}return qe(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(Vr(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of s)try{n=await this.execute(t,e)}catch(t){if(Vr(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of i)try{n=await this.execute(t,e)}catch(t){if(Vr(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(Vr(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(Vr(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&&Vr(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=Wr.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=Ur.get(i)??0;if(o>=100)return;if(Ur.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=qr(await t.execute(n,u));void 0!==e&&Object.assign(u,{it:e,result:e})}catch(e){if(Vr(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(Vr(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(Vr(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 zr(...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 Jr=Ln({selector:On().min(1),single:Rn().optional().default(0)});function Zr(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 Pn{constructor(){super(...arguments),this.name="me",this.category="Reference",this.syntax="me",this.description="References the current element in the execution context",this.inputSchema=Dn(),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 Pn{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=Dn(),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 Pn{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=Dn(),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 Pn{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=Jr,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 Gr={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.me??null,validate:En},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.you??null,validate:En},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it,validate:En},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it,validate:En},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.result,validate:En},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=>bn(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=>bn(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=>bn(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=>bn(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:En},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async t=>window,validate:En},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async t=>document,validate:En},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=>bn(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 Zr(s,n)},validate:t=>kn(t,1,2,"styleRef","property, optional element")??vn(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 Zr(s,r)},validate:t=>gn(t,2,"possessiveStyleRef","possessor, property")??vn(t,0,"possessiveStyleRef","possessor")??vn(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 Zr(s,n)},validate:t=>gn(t,2,"ofStyleRef","property, reference")??vn(t,0,"ofStyleRef","property")??vn(t,1,"ofStyleRef","reference")}};class Xr{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 Yr=new class{constructor(){this.domQueryCache=new Xr(200,3e3),this.exprResultCache=new Xr(500,2e3),this.cssMatchCache=new Xr(100,5e3),this.formValueCache=new Xr(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(()=>{Yr.cleanup()},1e4);const Kr=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=Yr.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 Qr(){Yr.cleanup(),Kr.getMetrics().memoryUsage>52428800&&Kr.reset()}let ts=null;function es(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 es(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 ns(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 rs(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 ss(t){try{return es(t,"_"),1}catch{return 0}}function is(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=ns(t),r=ns(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 os(t,e);case"!=":return!os(t,e);default:return 0}}function os(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?os(t?1:0,e):"boolean"==typeof e?os(t,e?1:0):t+""==e+""}function as(t,e=[]){return{isValid:0,errors:t,suggestions:e}}function cs(t,e,n=[],r="error"){return{type:t,message:e,suggestions:n,severity:r}}function us(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){ts&&clearInterval(ts),ts=setInterval(Qr,t)}();const ls=Ln({left:jn().describe("Left operand value"),right:jn().describe("Right operand value")}).strict(),hs=Ln({operand:jn().describe("Operand value to negate")}).strict();function fs(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType}new class extends Pn{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=ls,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 Pn{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=ls,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 Pn{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=hs,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 ds=In([jn(),jn()]),ps=In([jn(),On()]),ms={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(t,e,n){const r=Date.now();try{return us(this,t,[e,n],e==n,r)}catch(s){throw us(this,t,[e,n],0,r,0,s instanceof Error?s:Error(s+"")),s}},validate:t=>wn(t,"equals"),inputSchema:ds,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"]}},ys={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&&us(this,t,[e,n],s,r?Date.now():0),s},validate:t=>wn(t,"strictEquals")},gs={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&&us(this,t,[e,n],s,r?Date.now():0),s},validate:t=>wn(t,"notEquals")},vs={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&&us(this,t,[e,n],s,r?Date.now():0),s},validate:t=>wn(t,"strictNotEquals")},bs={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=is(e,n,"<");return r&&us(this,t,[e,n],i,s),i},validate:t=>wn(t,"lessThan")},ws={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=is(e,n,"<=");return r&&us(this,t,[e,n],i,s),i},validate:t=>wn(t,"lessThanOrEqual")},Es={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=is(e,n,">");return r&&us(this,t,[e,n],i,s),i},validate:t=>wn(t,"greaterThan")},xs={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=is(e,n,">=");return r&&us(this,t,[e,n],i,s),i},validate:t=>wn(t,"greaterThanOrEqual")},ks={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(t,e,n){const r=Date.now();try{return us(this,t,[e,n],e&&n,r)}catch(s){throw us(this,t,[e,n],0,r,0,s instanceof Error?s:Error(s+"")),s}},validate:t=>wn(t,"and"),inputSchema:ds,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"]}},Ss={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&&us(this,t,[e,n],s,r?Date.now():0),s},validate:t=>wn(t,"or")},As={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],async evaluate(t,e){const n=t.evaluationHistory,r=!e;return n&&us(this,t,[e],r,n?Date.now():0),r},validate:t=>gn(t,1,"not","operand")},Ns={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:rn(e)||Array.isArray(e)||e instanceof NodeList?0===e.length:e instanceof Node||e instanceof Element?0:an(e)?0===Object.keys(e).length:0,n&&us(this,t,[e],s,r),s},validate:t=>gn(t,1,"isEmpty","value")},Cs={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:(rn(e),0),n&&us(this,t,[e],s,r),s},validate:t=>gn(t,1,"no","value")},Ts={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 Ns.evaluate(t,e);return n&&us(this,t,[e],s,r),s},validate:t=>gn(t,1,"isNotEmpty","value")},Os={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0,s=$s(e);return n&&us(this,t,[e],s,r),s},validate:t=>gn(t,1,"exists","value")};function $s(t){return null==t?0:Array.isArray(t)||"undefined"!=typeof NodeList&&t instanceof NodeList?t.length>0:1}const Rs={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=!$s(e);return n&&us(this,t,[e],s,r),s},validate:t=>gn(t,1,"doesNotExist","value")},Ls={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(fs(e)&&fs(n))return i=e.contains(n),r&&us(this,t,[e,n],i,s),i;if(rn(e)&&e.match(/^[.#][\w-]+$/)){const o=document.querySelector(e);if(o&&fs(n))return i=o.contains(n),r&&us(this,t,[e,n],i,s),i;if(o&&rn(n)&&n.match(/^[.#][\w-]+$/)){const a=document.querySelector(n);return i=a?o.contains(a):0,r&&us(this,t,[e,n],i,s),i}}if(rn(n)&&n.match(/^[.#][\w-]+$/)&&fs(e)){const o=document.querySelector(n);return i=o?e.contains(o):0,r&&us(this,t,[e,n],i,s),i}}if(rn(e)&&rn(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=an(e)&&rn(n)?n in e:0;return r&&us(this,t,[e,n],i,s),i},validate:t=>gn(t,2,"contains","container, value")},Is={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 Ls.evaluate(t,e,n);return r&&us(this,t,[e,n],i,s),i},validate:t=>gn(t,2,"doesNotContain","container, value")},js={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&&us(this,t,[e,n],i,s),i},validate:t=>gn(t,2,"startsWith","str, prefix")},Ms={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&&us(this,t,[e,n],i,s),i},validate:t=>gn(t,2,"endsWith","str, suffix")},Ds={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&&us(this,t,[e,n,r],a,s?Date.now():0),a},validate:t=>gn(t,3,"between","value, min, max")},Ps={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(t,e,n){const r=Date.now();try{let s;if(e instanceof Element&&rn(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 Yr.matches(t,e)}(e,t)}catch(t){s=0}else s=0}else if(rn(e)&&rn(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 us(this,t,[e,n],s,r)}catch(s){throw us(this,t,[e,n],0,r,0,s instanceof Error?s:Error(s+"")),s}},validate:t=>gn(t,2,"matches","element, selector"),inputSchema:ps,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"]}},Fs={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&&rn(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&&us(this,t,[e,n],i,s),i},validate:t=>gn(t,2,"has","element, selector")},Bs={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 Fs.evaluate(t,e,n);return r&&us(this,t,[e,n],i,s),i},validate:t=>gn(t,2,"doesNotHave","element, selector")},_s={equals:ms,strictEquals:ys,notEquals:gs,strictNotEquals:vs,lessThan:bs,lessThanOrEqual:ws,greaterThan:Es,greaterThanOrEqual:xs,and:ks,or:Ss,not:As,no:Cs,isEmpty:Ns,isNotEmpty:Ts,exists:Os,doesNotExist:Rs,contains:Ls,doesNotContain:Is,startsWith:js,endsWith:Ms,between:Ds,matches:Ps,has:Fs,doesNotHave:Bs},Vs=Ln({value:On().describe("String literal value")}).strict(),qs=Ln({value:$n().describe("Number literal value")}).strict(),Hs=Ln({value:Rn().describe("Boolean literal value")}).strict(),Us=Ln({left:jn().describe("Left operand"),right:jn().describe("Right operand")}).strict(),Ws={stringLiteral:new class extends Pn{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=Vs,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 Pn{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=qs,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 Pn{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=Hs,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 Pn{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=Us,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=es(e.left,"left operand")+es(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 Pn{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=Us,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=Us.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(rn(t))return t;if(sn(t))return""+t;if(on(t))return""+t;if(t instanceof Date)return""+t;try{return t+""}catch{return"[object Object]"}}},multiplication:new class extends Pn{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=Us,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=es(e.left,"left operand")*es(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 zs(){return zr(Gr,_s,Ws)}class Js{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=Ye(t);this.runtime.execute(e,n).catch(n=>{console.error('[HyperFixi] Error executing _="" attribute:',n),console.error("Element:",t),console.error("Code:",e)})}}function Zs(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 Gs(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 Xs(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 Ys(t){const e=t.trim();return e.startsWith("[@")&&e.endsWith("]")||e.startsWith("@")?1:0}function Ks(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 Qs(t,e){for(const n of t)e(n);return t}function ti(t,e,n){for(const r of t)for(const t of e)n(r,t);return t}function ei(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 ni(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&&si(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&&si(t));const e=(t+"").trim(),n=e.startsWith(".")?e.substring(1):e;return n.length>0&&si(n)?[n]:[]}function ri(t){const e=t.trim();return/^\{[^}]+\}$/.test(e)}function si(t){if(!t||0===t.trim().length)return 0;const e=t.trim();return ri(e)?1:/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(e)}function ii(t,e){return t.map(t=>{if(ri(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 oi=Symbol("command:name"),ai=Symbol("command:category"),ci=Symbol("command:metadata");function ui(t){return function(e,n){const r=e;r[oi]=t.name,r[ai]=t.category,Object.defineProperty(e.prototype,"name",{value:t.name,writable:0,enumerable:1})}}function li(t){return function(e,n){const r=e,s=r[ai];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[ci]=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 hi(t){return()=>new t}function fi(t,e){return e}function di(t,e,n){if(Ke(t))return t;if(!t){const t=e.me;if(!t)throw Error(fi(0,"No target element — provide explicit target or ensure context.me is set"));return pi(t)}if("string"==typeof t){const n=t.trim();if("me"===n){if(!e.me)throw Error(fi(0,'Context reference "me" is not available'));return pi(e.me)}if("it"===n){if(!Ke(e.it))throw Error(fi(0,'Context reference "it" is not an HTMLElement'));return e.it}if("you"===n){if(!e.you)throw Error(fi(0,'Context reference "you" is not available'));return pi(e.you)}const r=e.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!r)throw Error(fi(0,"DOM not available — cannot resolve element selector"));const s=r.querySelector(n);if(!s)throw Error(fi(0,"Element not found with selector: "+n));if(!Ke(s))throw Error(fi(0,"Element found but is not an HTMLElement: "+n));return s}throw Error(fi(0,"Invalid target type: "+typeof t))}function pi(t){if(Ke(t))return t;throw Error("Value is not an HTMLElement")}function mi(t,e,n){switch(t.toLowerCase()){case"my":case"me":if(!e.me)throw Error(fi(0,'No "me" element in context'));if(!Ke(e.me))throw Error(fi(0,"context.me is not an HTMLElement"));return e.me;case"its":case"it":if(!e.it)throw Error(fi(0,'No "it" value in context'));if(!Ke(e.it))throw Error(fi(0,"context.it is not an HTMLElement"));return e.it;case"your":case"you":if(!e.you)throw Error(fi(0,'No "you" element in context'));if(!Ke(e.you))throw Error(fi(0,"context.you is not an HTMLElement"));return e.you;default:throw Error(fi(0,"Unknown possessive: "+t))}}const yi=["on","from","to","in","with","at"];async function gi(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?!yi.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(!Ke(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(Ke(s))a.push(s);else if(Qe(s)){const t=Array.from(s).filter(Ke);a.push(...t)}else if(Array.isArray(s)){const t=s.filter(Ke);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(Ke);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(!Ke(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}return a}function vi(t){return"string"==typeof t&&t.trim().startsWith("*")}function bi(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 wi(t,e,n){t.style.setProperty(e,n)}const Ei=["dialog","details","summary","select"];function xi(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 ki(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=xi(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=xi(t);return"string"==typeof n&&n.startsWith("*")}(t)?{value:xi(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=xi(t);return"string"==typeof e&&e.startsWith("@")}return 0}(t)?{value:(r=t,"attributeAccess"===r.type?"@"+r.attributeName:xi(r)),extractedFromNode:1}:{value:await e.evaluate(t,n),extractedFromNode:0};var r}class Si{async resolveTargets(t,e,n,r){return gi(t,e,n,this.mode,{filterPrepositions:1,fallbackModifierKey:this.preposition},r)}async evaluateFirst(t,e,n){return ki(t,e,n)}parseClassNames(t){return ni(t)}isAttribute(t){return Ys(t.trim())}isCSSProperty(t){return vi(t.trim())}validateTargets(t){return Array.isArray(t)&&function(t){return Array.isArray(t)&&t.length>0&&t.every(t=>Ke(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 Ai=(()=>{let t,e,n=[li({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"]}),ui({name:"add",category:"dom"})],r=[],s=Si;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=Ks(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=ii(t.classes,e);n.length>0&&ti(t.targets,n,(t,e)=>{t.classList.contains(e)||t.classList.add(e)});break}case"attribute":n=t.name,r=t.value,Qs(t.targets,t=>{t.setAttribute(n,r)});break;case"styles":ti(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}},Xs(e,"AddCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Zs(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}),Gs(e,r)})(),e})();const Ni=hi(Ai);function Ci(t){return t.parentNode?(t.remove(),1):0}let Ti=(()=>{let t,e,n=[li({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"]}),ui({name:"remove",category:"dom"})],r=[],s=Si;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(Ke(r))return{type:"element",targets:[r]};if(Array.isArray(r)&&r.length>0&&Ke(r[0]))return{type:"element",targets:r.filter(t=>Ke(t))};if("string"==typeof r){const s=r.trim();if(this.isAttribute(s))return{type:"attribute",name:Ks(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=ii(t.classes,e);n.length>0&&ti(t.targets,n,(t,e)=>{t.classList.remove(e)});break}case"attribute":n=t.name,Qs(t.targets,t=>{t.removeAttribute(n)});break;case"styles":ti(t.targets,t.properties,(t,e)=>{t.style.removeProperty(e)});break;case"element":for(const e of t.targets)Ci(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}},Xs(e,"RemoveCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Zs(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}),Gs(e,r)})(),e})();const Oi=hi(Ti);function $i(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 Ri(t){if("number"==typeof t){if(0>t)throw Error("Duration must be >= 0");return Math.floor(t)}if("string"==typeof t){const e=$i(t);if(!e)throw Error(`Invalid duration format: "${t}"`);return e.milliseconds}throw Error("Invalid duration type: "+typeof t)}function Li(t){return 0===t.length?[]:"SUMMARY"===t[0].tagName?t.map(t=>t.closest("details")).filter(t=>null!==t):t}function Ii(t,e,n){return()=>{"class"===e?t.classList.toggle(n):"attribute"===e&&ei(t,n)}}function ji(t,e,n,r){const s=Ii(t,e,n),i=setTimeout(s,r);return()=>{clearTimeout(i)}}function Mi(t,e,n,r){const s=Ii(t,e,n),i=()=>{s(),t.removeEventListener(r,i)};return t.addEventListener(r,i,{once:1}),()=>{t.removeEventListener(r,i)}}function Di(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 Pi=/^the\s+(.+?)\s+of\s+(.+)$/i,Fi=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 Bi(t){return"string"==typeof t&&Pi.test(t)}function _i(t,e){const n=t.match(Pi);if(!n)return null;try{return{element:di(n[2].trim(),e),property:n[1].trim()}}catch{return null}}async function Vi(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]),Ke(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]),Ke(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]),!Ke(i))return null;const o=s?.name||s?.value;return o?{element:i,property:o}:null}return null}function qi(t,e){const{element:n,property:r}=t;r.startsWith("*")?wi(n,r.substring(1),e+""):Di(n,r,e)}async function Hi(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=$i(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 Ui=hi((()=>{let t,e,n=[li({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"]}),ui({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 Hi(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 gi(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 Vi(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 Hi(t.modifiers,e,n),a=bi(r);if(a){const t=n.me;return{type:"css-property",property:a,targets:t?[t]:[],duration:i,untilEvent:o}}}}const o=bi(r);if(o){const{duration:r,untilEvent:s}=await Hi(t.modifiers,e,n),a={filterPrepositions:1,fallbackModifierKey:"on"};return{type:"css-property",property:o,targets:await gi(t.args.slice(i),e,n,"toggle",a,t.modifiers),duration:r,untilEvent:s}}}const{duration:a,untilEvent:c}=await Hi(t.modifiers,e,n),{value:u}=await ki(s,e,n);if(Bi(u)){const t=_i(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 Ei.includes(e)}(e)}(e);if(Ke(t)||Array.isArray(t)&&t.every(t=>Ke(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 Ei.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}=Ks(h);return{type:"attribute",name:r,value:s,targets:await gi(t.args.slice(1),e,n,"toggle",f,t.modifiers),duration:a,untilEvent:c}}case"css-property":{const r=bi(h);if(!r)throw Error("Invalid CSS property: "+h);return{type:"css-property",property:r,targets:await gi(t.args.slice(1),e,n,"toggle",f,t.modifiers)}}case"element":{let i;if(Ke(u))i=[u];else if(Array.isArray(u)&&u.every(t=>Ke(t)))i=u;else if(h){const t=document.querySelectorAll(h);i=Array.from(t).filter(t=>Ke(t))}else i=await gi([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:Li(i)}:"select"===o?{type:"select",targets:i}:{type:"classes",classes:ni(h),targets:i,duration:a,untilEvent:c}}default:{const r=ni(h||u);if(!r.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:r,targets:await gi(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=ii(t.classes,e);if(0===n.length)return[...t.targets];if(ti(t.targets,n,(t,e)=>{t.classList.toggle(e)}),(t.duration||t.untilEvent)&&n.length)for(const e of t.targets)t.duration&&ji(e,"class",n[0],t.duration),t.untilEvent&&Mi(e,"class",n[0],t.untilEvent);return[...t.targets]}case"attribute":if(n=t.name,r=t.value,Qs(t.targets,t=>{ei(t,n,r)}),t.duration||t.untilEvent)for(const e of t.targets)t.duration&&ji(e,"attribute",t.name,t.duration),t.untilEvent&&Mi(e,"attribute",t.name,t.untilEvent);return[...t.targets];case"css-property":return Qs(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)):mn(e,n)}(t),n=t.property,r=n.startsWith("@")?n.substring(1):n;if("boolean"==typeof e||Fi.has(r)||Fi.has(r.toLowerCase())){const n=!e;return qi(t,n),n}if("number"==typeof e){const n=0===e?1:0;return qi(t,n),n}if("string"==typeof e){const r="__ht_"+n,s=t.element[r];return""===e&&void 0!==s?(qi(t,s),s):(t.element[r]=e,qi(t,""),"")}qi(t,!e)}(t.target),[t.target.element];case"dialog":return Qs(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 Qs(t.targets,t=>{var e;(e=t).open=!e.open});case"select":return Qs(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&&ji(e,"class",t.classA,t.duration),t.untilEvent&&Mi(e,"class",t.classA,t.untilEvent);return[...t.targets]}var n,r}},Xs(e,"ToggleCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Zs(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}),Gs(e,r)})(),e})());class Wi{async parseInput(t,e,n){const{targets:r}=await async function(t,e,n,r){return{targets:await gi(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=>Ke(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 zi=(()=>{let t,e,n=[li({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"]}),ui({name:"show",category:"dom"})],r=[],s=Wi;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=>Ke(t))?"string"!=typeof e.defaultDisplay?0:1:0}},Xs(e,"ShowCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Zs(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}),Gs(e,r)})(),e})();const Ji=hi(zi);let Zi=(()=>{let t,e,n=[li({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"]}),ui({name:"hide",category:"dom"})],r=[],s=Wi;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=>Ke(t))?1:0}},Xs(e,"HideCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Zs(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}),Gs(e,r)})(),e})();const Gi=hi(Zi),Xi=hi((()=>{let t,e,n=[li({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"]}),ui({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 Vi(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&&Bi(t)){const e=_i(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||!Ke(e.me))throw Error("put: no target and context.me is null");return[e.me]}const n=Array.from(document.querySelectorAll(t)).filter(t=>Ke(t));if(!n.length)throw Error(`No elements: "${t}"`);return n}parseValue(t){return Ke(t)?t:null==t?"":t+""}insertContent(t,e,n){if("replace"!==n)if(Ke(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 Ke(e)?(t.innerHTML="",t.appendChild(e)):e.includes("<")&&e.includes(">")?t.innerHTML=e:t.textContent=e}resolveEvaluatedAsElements(t){if(Ke(t))return[t];if(Array.isArray(t)){const e=t.filter(Ke);return e.length>0?e:null}if("undefined"!=typeof NodeList&&t instanceof NodeList){const e=Array.from(t).filter(Ke);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}},Xs(e,"PutCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Zs(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}),Gs(e,r)})(),e})()),Yi=hi((()=>{let t,e,n=[li({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"]}),ui({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 Vi(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(Ke(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(Bi(u)){const r=_i(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&&vi(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&&Ys(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=mi(r[1],n),i=await this.extractValue(t,e,n);return{type:"property",element:s,property:r[2],value:i}}}if(Ke(u))return{type:"property",element:u,property:"textContent",value:await this.extractValue(t,e,n)};if(Array.isArray(u)&&u.length>0&&Ke(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?Xe(e,t.name,t.value):"global"===t.scope?en(t.name,t.value,e,"global"):en(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 Di(t.element,t.property,t.value),Object.assign(e,{it:t.value}),{target:t.element,value:t.value,targetType:"property"};case"style":return wi(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))Di(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 Ke(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=mi(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 di(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(Ke);if(Qe(t))return Array.from(t).filter(Ke);if(Ke(t))return[t];if(!t){const t=e.me;return t&&Ke(t)?[t]:[]}if("string"==typeof t){const n=t.trim();if("me"===n)return e.me&&Ke(e.me)?[e.me]:[];if("it"===n)return Ke(e.it)?[e.it]:[];if("you"===n)return e.you&&Ke(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(Ke)}}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=di(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(Ke)&&"value"in e;case"property":return"string"==typeof e.property&&Ke(e.element)&&"value"in e;case"style":return"string"==typeof e.property&&""!==e.property&&Ke(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}}},Xs(e,"SetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Zs(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}),Gs(e,r)})(),e})());function Ki(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 Qi=hi((()=>{let t,e,n=[li({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"]}),ui({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(Ke(t))s.push(t);else if(t instanceof NodeList)s.push(...Array.from(t).filter(Ke));else if(Array.isArray(t))s.push(...t.filter(Ke));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(Ke));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()]=Ki(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}},Xs(e,"EventDispatchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Zs(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}),Gs(e,r)})(),e})()),to=hi((()=>{let t,e,n=[li({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"]}),ui({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)}},Xs(e,"LogCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Zs(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}),Gs(e,r)})(),e})());function eo(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 no(t){return new Promise(e=>setTimeout(e,t))}const ro=hi((()=>{let t,e,n=[li({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"]}),ui({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 no(t.milliseconds),{type:"time",result:t.milliseconds,duration:Date.now()-n};if("event"===t.type){const r=t.target??e.me??document,s=(await eo(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:Ri(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:Ri(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?no(t.milliseconds).then(()=>({result:t.milliseconds,winningCondition:t})):eo(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()}}},Xs(e,"WaitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Zs(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}),Gs(e,r)})(),e})()),so=function(t,e){const n=new Dr(null);for(const e of t)n.register(e);return new Wr({registry:n,expressionRegistry:e.expressionRegistry,enableAsyncCommands:e.enableAsyncCommands??1,commandTimeout:e.commandTimeout??1e4,enableErrorReporting:e.enableErrorReporting??1,enableResultPattern:e.enableResultPattern??1})}([Ni(),Oi(),Ui(),Ji(),Gi(),Xi(),Yi(),Qi(),to(),ro()],{expressionRegistry:zs()}),io={parse:t=>Be(t),execute:async(t,e)=>{const n=function(t){if(!t)return Ye();if(t.locals instanceof Map&&t.globals instanceof Map&&t.flags)return t;const e=Ye(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=Be(t);if(!r.success||!r.node)throw Error(r.error?.message||"Parse failed");return await so.execute(r.node,n)}},oo=function(t){return new Js(t)}(io),ao={runtime:io,parse:t=>io.parse(t),execute:async(t,e)=>io.execute(t,e),createContext:Ye,attributeProcessor:oo,version:"1.1.0-minimal-v2-tree-shakeable",commands:["add","remove","toggle","show","hide","put","set","send","log","wait"],eval:async(t,e)=>io.execute(t,e),init:()=>{oo.init()}};"undefined"!=typeof window&&(window.hyperfixi=ao,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{oo.init()}):oo.init());const co={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"},uo=Ln({collection:jn().describe("Collection to operate on (array, NodeList, or string)")}).strict(),lo=Ln({collection:jn().describe("Collection to access"),index:$n().describe("Index position to access")}).strict(),ho=Ln({collection:jn().describe("Collection to select random item from")}).strict();new class extends Pn{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=uo,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:co[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 Pn{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=uo,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:co[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 Pn{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=lo,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:co[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 Pn{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=ho,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:co[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 fo={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:rn(n)?n.length>0?n[0]:null:an(n)&&"length"in n&&sn(n.length)&&n.length>0?n[0]:null},validate:t=>xn(t,1,"first","collection")},po={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 rn(n)?n.length>0?n[n.length-1]:null:an(n)&&"length"in n&&sn(n.length)&&n.length>0?n[n.length-1]:null},validate:t=>xn(t,1,"last","collection")},mo={name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(t,...e){const[n,r]=e;if(!sn(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(rn(i)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}if(an(i)&&"length"in i&&sn(i.length)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}return null},validate:t=>kn(t,1,2,"at","index, optional collection")??function(t){return"number"!=typeof t[0]?"at index must be a number":null}(t)};function yo(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?yo(r,e):null}function go(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?go(r,e):null}function vo(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 bo(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 wo={first:fo,last:po,at:mo,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?vo(i,n,s,1):yo(i,n):i.nextElementSibling:null},validate:t=>xn(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?vo(i,n,s,0):go(i,n):i.previousElementSibling:null},validate:t=>xn(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=bo(t);for(const t of r)if(bo(t)>s)return t;return null}(i,n,o):null},validate:t=>kn(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=bo(t);for(let t=r.length-1;t>=0;t--){const e=r[t];if(s>bo(e))return e}return null}(i,n,o):null},validate:t=>kn(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 Eo{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:rs(es(t,"left operand")+es(n,"right operand"),"addition"),type:"number"}}catch(t){return{success:0,errors:[cs("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 as([cs("missing-argument","Input is null or undefined")],["Provide an object with left and right operands"]);if("object"!=typeof t)return as([cs("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"),as([cs("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 ss(n)?ss(r)?{isValid:1,errors:[],suggestions:[]}:{isValid:0,errors:[cs("type-mismatch","Right operand cannot be converted to number: "+r)],suggestions:["Provide a numeric value for right operand"]}:{isValid:0,errors:[cs("type-mismatch","Left operand cannot be converted to number: "+n)],suggestions:["Provide a numeric value for left operand"]}}}const xo={addition:new Eo,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:rs(es(t,"left operand")-es(n,"right operand"),"subtraction"),type:"number"}}catch(t){return{success:0,errors:[cs("runtime-error","Subtraction failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new Eo).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:rs(es(t,"left operand")*es(n,"right operand"),"multiplication"),type:"number"}}catch(t){return{success:0,errors:[cs("runtime-error","Multiplication failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new Eo).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}(es(t,"left operand"),es(n,"right operand"),1);return{success:1,value:r,type:"number"}}catch(t){return{success:0,errors:[cs("runtime-error","Division failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new Eo).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}(es(t,"left operand"),es(n,"right operand"));return{success:1,value:r,type:"number"}}catch(t){return{success:0,errors:[cs("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 Eo).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=es(t,"left operand"),s=es(n,"right operand");return{success:1,value:rs(Math.pow(r,s),"power"),type:"number"}}catch(t){return{success:0,errors:[cs("runtime-error","Power failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new Eo).validate(t)}}};var ko=Object.freeze({__proto__:null,conversion:Xn,conversionExpressions:Xn,createCommonRegistry:function(){return zr(Gr,_s,Ws,Xn,wo)},createCoreRegistry:zs,createExpressionRegistry:zr,createFullExpressionRegistry:function(){return zr(Gr,_s,Xn,wo,tr,Ws,xo)},createFullRegistry:function(){return zr(Gr,_s,Ws,Xn,wo,tr)},logical:_s,logicalExpressions:_s,positional:wo,positionalExpressions:wo,properties:tr,propertiesExpressions:tr,references:Gr,referencesExpressions:Gr,special:Ws,specialExpressions:Ws});return ao}();
|