@lokascript/core 1.1.2 → 1.1.3
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/chunks/bridge-qXDe7P1g.js +2 -0
- package/dist/chunks/bridge-qXDe7P1g.js.map +1 -0
- package/dist/chunks/browser-modular-DfWTWK1K.js +2 -0
- package/dist/chunks/browser-modular-DfWTWK1K.js.map +1 -0
- package/dist/chunks/feature-eventsource-VXpBMoKs.js +2 -0
- package/dist/chunks/feature-eventsource-VXpBMoKs.js.map +1 -0
- package/dist/chunks/feature-sockets-CFuglALU.js +2 -0
- package/dist/chunks/feature-sockets-CFuglALU.js.map +1 -0
- package/dist/chunks/feature-webworker-JSaX8ZKW.js +2 -0
- package/dist/chunks/feature-webworker-JSaX8ZKW.js.map +1 -0
- package/dist/hyperfixi-browser-classic-i18n.js +2 -0
- package/dist/hyperfixi-browser-classic-i18n.js.map +1 -0
- package/dist/hyperfixi-browser-minimal.js +1 -0
- package/dist/hyperfixi-browser-standard.js +2 -0
- package/dist/hyperfixi-browser-standard.js.map +1 -0
- package/dist/hyperfixi-browser.js +2 -0
- package/dist/hyperfixi-browser.js.map +1 -0
- package/dist/hyperfixi-hybrid-complete.js +1 -0
- package/dist/hyperfixi-hybrid-hx.js +1 -0
- package/dist/hyperfixi-lite-plus.js +1 -0
- package/dist/hyperfixi-lite.js +1 -0
- package/dist/hyperfixi.mjs +2 -0
- package/dist/hyperfixi.mjs.map +1 -0
- package/dist/lokascript-browser-classic-i18n.js +2 -0
- package/dist/lokascript-browser-classic-i18n.js.map +1 -0
- package/dist/lokascript-browser-minimal.js +1 -0
- package/dist/lokascript-browser-standard.js +2 -0
- package/dist/lokascript-browser-standard.js.map +1 -0
- package/dist/lokascript-browser.js +2 -0
- package/dist/lokascript-browser.js.map +1 -0
- package/dist/lokascript-hybrid-complete.js +1 -0
- package/dist/lokascript-hybrid-hx.js +1 -0
- package/dist/lokascript-lite-plus.js +1 -0
- package/dist/lokascript-lite.js +1 -0
- package/dist/lokascript-multilingual.js +2 -0
- package/dist/lokascript-multilingual.js.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var lokascript=function(){"use strict";const e="then",t="else",r="end",n="and",s="for",i="while",o="until",a="forever",c="times",l="index",u="in",h="to",f="from",d="with",p="of",m="on",y="event",v="behavior",g="global",b="the",E="start",w=new Set(["add","append","async","beep","break","call","continue","copy","decrement","default","exit","fetch","for","get","go","halt","hide","if","increment","install","js","log","make","measure","morph","pick","process","push","put","remove","render","repeat","replace","return","send","set","settle","show","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","swap","morph","push","replace","process"]),k=(new Set(["if","unless","repeat","wait","for","while"]),"at start of"),A="at end of",S=["into","before","after","at",k,A,"at the start of","at the end of"],C=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"]),T=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"]),N=new Set(["me","it","you","result","my","its","your"]),O=new Set(["and","or","not","no"]),L=new Set(["==","!=","===","!==","<",">","<=",">=","is","is not","is a","is an","is not a","is not an","contains","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","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"]),$=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"]),R=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,j;function M(e){switch(e){case j.KEYWORD:case j.COMMAND:case j.EXPRESSION:case j.CONTEXT_VAR:case j.GLOBAL_VAR:case j.EVENT:case j.IDENTIFIER:return I.IDENTIFIER;case j.STRING:return I.STRING;case j.NUMBER:return I.NUMBER;case j.BOOLEAN:return I.IDENTIFIER;case j.TEMPLATE_LITERAL:return I.TEMPLATE;case j.CSS_SELECTOR:case j.ID_SELECTOR:case j.CLASS_SELECTOR:case j.QUERY_REFERENCE:return I.SELECTOR;case j.OPERATOR:case j.LOGICAL_OPERATOR:case j.COMPARISON_OPERATOR:return I.OPERATOR;case j.TIME_EXPRESSION:return I.TIME;case j.COMMENT:return I.COMMENT;case j.SYMBOL:return I.SYMBOL;default:return I.UNKNOWN}}!function(e){e.IDENTIFIER="identifier",e.STRING="string",e.NUMBER="number",e.SELECTOR="selector",e.OPERATOR="operator",e.TIME="time",e.TEMPLATE="template",e.COMMENT="comment",e.SYMBOL="symbol",e.UNKNOWN="unknown"}(I||(I={})),function(e){e.KEYWORD="keyword",e.COMMAND="command",e.EXPRESSION="expression",e.STRING="string",e.NUMBER="number",e.BOOLEAN="boolean",e.TEMPLATE_LITERAL="template_literal",e.CSS_SELECTOR="css_selector",e.ID_SELECTOR="id_selector",e.CLASS_SELECTOR="class_selector",e.QUERY_REFERENCE="query_reference",e.CONTEXT_VAR="context_var",e.GLOBAL_VAR="global_var",e.EVENT="event",e.OPERATOR="operator",e.LOGICAL_OPERATOR="logical_operator",e.COMPARISON_OPERATOR="comparison_operator",e.TIME_EXPRESSION="time_expression",e.OBJECT_LITERAL="object_literal",e.ARRAY_LITERAL="array_literal",e.SYMBOL="symbol",e.COMMENT="comment",e.IDENTIFIER="identifier",e.UNKNOWN="unknown"}(j||(j={}));const D=R,V=new Set(["+","-","*","/","mod"]),B=new Set(["ms","s","seconds","minutes","hours","days"]);function P(e,t=1){const r=e.position+t;return e.input.length>r?e.input[r]:""}function _(e){const t=e.input[e.position];return e.position++,"\n"===t?(e.line++,e.column=1):"\r"===t?("\n"===(e.input.length>e.position?e.input[e.position]:"")&&e.position++,e.line++,e.column=1):e.column++,t}function F(e){const t=e.input,r=t.length;for(;r>e.position;){const r=t[e.position];if(" "!==r&&"\t"!==r&&"\r"!==r&&"\n"!==r)break;_(e)}}function q(e,t,r,n,s){const i=n??e.position-r.length,o=e.position;let a=e.column-r.length;if(void 0!==n){a=1;let t=-1;for(let r=0;n>r;r++)"\n"!==e.input[r]&&"\r"!==e.input[r]||(t=r);a=n-t}const c={kind:M(t),value:r,start:i,end:o,line:U(e,i),column:a};e.tokens.push(c)}function U(e,t){let r=1;for(let n=0;t>n&&e.input.length>n;n++){const t=e.input[n];"\n"===t?r++:"\r"===t&&(r++,e.input.length>n+1&&"\n"===e.input[n+1]&&n++)}return r}function H(e){const t=e.position;let r="";for(_(e),_(e);e.input.length>e.position&&"\n"!==e.input[e.position];)r+=_(e);q(e,j.COMMENT,"--"+r,t)}function W(e){const t=e.position,r=_(e);let n=r;for(;e.input.length>e.position;){const t=_(e);if(n+=t,t===r)break;"\\"===t&&e.input.length>e.position&&(n+=_(e))}q(e,j.STRING,n,t)}function z(e){const t=e.position;_(e);let r="";for(;e.input.length>e.position;){const t=e.input[e.position];if("`"===t){_(e);break}if("\\"===t){if(_(e),e.input.length>e.position){const t=_(e);switch(t){case"n":r+="\n";break;case"t":r+="\t";break;case"r":r+="\r";break;case"\\":r+="\\";break;case"`":r+="`";break;default:r+=t}}}else r+=_(e)}if(e.position>=e.input.length&&!e.input.endsWith("`"))throw Error(`Unterminated template literal at line ${e.line}, column ${e.column-r.length}`);q(e,j.TEMPLATE_LITERAL,r,t)}function J(e){const t=e.position,r=_(e);let n=r;for(;e.input.length>e.position;){const t=e.input[e.position];if(!te(t)&&"-"!==t&&"_"!==t&&":"!==t)break;n+=_(e)}q(e,"#"===r?j.ID_SELECTOR:j.CLASS_SELECTOR,n,t)}function Z(e){const t=e.position;let r="";for(r+=_(e);e.input.length-1>e.position;){const t=e.input[e.position],n=e.input[e.position+1];if(r+=_(e),"/"===t&&">"===n){r+=_(e);break}}q(e,j.QUERY_REFERENCE,r,t)}function G(e){const t=e.position;let r=_(e);for(;e.input.length>e.position;){const t=e.input[e.position];if(!te(t)&&"_"!==t&&"-"!==t)break;r+=_(e)}q(e,j.SYMBOL,r,t)}function Y(e){const t=e.position;let r="";const n=e.input[e.position];if(("'"===n||"'"===n)&&"s"===P(e,1))return r="'s",_(e),_(e),void q(e,j.OPERATOR,r,t);const s=e.input.substring(e.position,e.position+2),i=e.input.substring(e.position,e.position+3);["===","!=="].includes(i)?(r=i,_(e),_(e),_(e)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(s)?(r=s,_(e),_(e)):r=_(e);let o=j.OPERATOR;L.has(r)?o=j.COMPARISON_OPERATOR:["&&","||"].includes(r)?o=j.LOGICAL_OPERATOR:V.has(r)&&(o=j.OPERATOR),q(e,o,r,t)}function X(e){const t=e.position,r=e.input,n=r.length;let s="";for(;n>e.position;){const t=r[e.position];if("0">t||t>"9")break;s+=_(e)}if(n>e.position&&"."===r[e.position]&&(e.position+1>=n||"."!==r[e.position+1]))for(s+=_(e);n>e.position;){const t=r[e.position];if("0">t||t>"9")break;s+=_(e)}if(n>e.position){const t=r[e.position];if("e"===t||"E"===t){const t=n>e.position+1?r[e.position+1]:"",i=n>e.position+2?r[e.position+2]:"";if(t>="0"&&"9">=t||!("+"!==t&&"-"!==t||"0">i||i>"9"))for(s+=_(e),"+"!==r[e.position]&&"-"!==r[e.position]||(s+=_(e));n>e.position;){const t=r[e.position];if("0">t||t>"9")break;s+=_(e)}}}const i=e.position;let o="";for(;n>e.position;){const t=r[e.position];if(("a">t||t>"z")&&("A">t||t>"Z"))break;o+=_(e)}B.has(o)?q(e,j.TIME_EXPRESSION,s+o,t):(e.position=i,q(e,j.NUMBER,s,t))}function K(e){const t=e.position,r=e.input,n=r.length;let s="";for(;n>e.position;){const t=r[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;s+=_(e)}const i=function(e,t,r){const n=t.toLowerCase(),s=e.position;if("'s"===t||"'s"===t)return 0;const i=e.tokens[e.tokens.length-1];if(i&&("identifier"===i.kind||"id_selector"===i.kind||"class_selector"===i.kind||"context_var"===i.kind)){const t=e.input.length>e.position?e.input[e.position]:"";if("'"===t||"'"===t)return 0}F(e);let o="";for(;e.input.length>e.position;){const t=e.input[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;o+=_(e)}if(o){const t=o.toLowerCase(),s=`${n} ${t}`,i=function(e,t,r,n){const s=t.toLowerCase(),i=r.toLowerCase();if("at"===s){const t=e.position;if("the"===i){F(e);let r="";for(;e.input.length>e.position;){const t=e.input[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;r+=_(e)}const s=r.toLowerCase();if("start"===s||"end"===s){F(e);let t="";for(;e.input.length>e.position;){const r=e.input[e.position];if(("a">r||r>"z")&&("A">r||r>"Z")&&("0">r||r>"9")&&"_"!==r&&"-"!==r)break;t+=_(e)}if("of"===t.toLowerCase())return q(e,j.KEYWORD,`at the ${s} of`,n),1}return e.position=t,0}if("start"===i||"end"===i){F(e);let r="";for(;e.input.length>e.position;){const t=e.input[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;r+=_(e)}return"of"===r.toLowerCase()?(q(e,j.KEYWORD,`at ${i} of`,n),1):(e.position=t,0)}}return 0}(e,n,t,r);if(i)return 1;const a=function(e,t,r){const n=e.position;let s=`${t} ${r}`,i=e.position;const o=[t,r];for(;8>o.length&&(F(e),e.input.length>e.position);){let t="";for(;e.input.length>e.position;){const r=e.input[e.position];if(("a">r||r>"z")&&("A">r||r>"Z"))break;t+=_(e)}if(!t)break;o.push(t.toLowerCase());const r=o.join(" ");L.has(r)&&(s=r,i=e.position)}return L.has(s)&&s!==`${t} ${r}`?(e.position=i,s):(e.position=n,null)}(e,n,t);if(a)return q(e,j.COMPARISON_OPERATOR,a,r),1;if(L.has(s))return q(e,j.COMPARISON_OPERATOR,s,r),1}return L.has(n)?(e.position=s,q(e,j.COMPARISON_OPERATOR,t,r),1):(e.position=s,0)}(e,s,t);if(i)return;const o=function(e){const t=e.toLowerCase();return"include"===t||"includes"===t?j.COMPARISON_OPERATOR:O.has(t)?j.LOGICAL_OPERATOR:V.has(e)||V.has(t)?j.OPERATOR:L.has(t)?j.COMPARISON_OPERATOR:"I"===e||N.has(t)?j.CONTEXT_VAR:w.has(t)?j.COMMAND:$.has(t)?j.EVENT:["true","false","null","undefined"].includes(t)?j.BOOLEAN:D.has(t)?j.KEYWORD:j.IDENTIFIER}(s);q(e,o,s,t)}function Q(e){const t=e.position,r=e.input,n=r.length;_(e);let s="$";for(;n>e.position;){const t=r[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t)break;s+=_(e)}q(e,j.GLOBAL_VAR,s,t)}function ee(e){return/[a-zA-Z]/.test(e)}function te(e){return/[a-zA-Z0-9]/.test(e)}function re(e){let t=e.position+1,r=0;for(;e.input.length>t;){const n=e.input[t];if("/"===n&&e.input.length>t+1&&">"===e.input[t+1])return r;if(te(n)||"."===n||"#"===n||"["===n||"]"===n||":"===n||"-"===n||"_"===n||" "===n||"="===n||'"'===n||"'"===n||"("===n||")"===n||"*"===n||"^"===n||"$"===n||"~"===n||"|"===n||">"===n||"+"===n||","===n)r=1,t++;else{if(" "!==n&&"\t"!==n)return 0;t++}if(t-e.position>50)return 0}return 0}function ne(e){return"+-*/^%=!<>&|(){}[],.;:?''~$".includes(e)}const se=function(){if("undefined"!=typeof localStorage)try{const e=localStorage.getItem("lokascript:debug");if("*"===e||"true"===e)return 1}catch{}return"undefined"!=typeof process&&"true"===process.env?.HYPERFIXI_DEBUG?1:0}(),ie=se,oe=se,ae=se,ce=se,le=se,ue=(...e)=>{ie&&console.log("🔧",...e)},he=(...e)=>{oe&&console.log("🎯",...e)},fe=(...e)=>{ae&&console.log("📝",...e)},de=(...e)=>{ce&&console.log("🔍",...e)},pe=(...e)=>{ce&&console.log("🔍",...e)},me=(...e)=>{le&&console.log("🚀",...e)};let ye=0,ve=null;if("undefined"!=typeof window&&"undefined"!=typeof URLSearchParams)try{"semantic"===new URLSearchParams(window.location.search).get("debug")&&(ye=1,ve=window,console.log("%c[HyperFixi] Semantic debug auto-enabled via URL param","color: #667eea; font-weight: bold"))}catch{}let ge={totalParses:0,semanticSuccesses:0,semanticFallbacks:0,traditionalParses:0,averageConfidence:0,confidenceHistory:[]};class be{constructor(e){this.analyzer=e.analyzer,this.language=e.language,this.confidenceThreshold=e.confidenceThreshold??.5,this.debugEnabled=e.debug??0}isAvailable(){return this.analyzer.supportsLanguage(this.language)}shouldSkipSemantic(e){const t=e.trim().split(/\s+/)[0]?.toLowerCase();if(be.SKIP_SEMANTIC_COMMANDS.has(t))return 1;const r=e.toLowerCase();return/\bjs\b/.test(r)||/\btell\b/.test(r)?1:0}trySemanticParse(e){const t=performance.now();if(this.shouldSkipSemantic(e))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 n=this.analyzer.analyze(e,this.language),s=performance.now()-t;this.debugEnabled&&console.log("[SemanticIntegration] Analysis result:",{input:e,language:this.language,confidence:n.confidence,command:n.command?.name,threshold:this.confidenceThreshold});const i=n.confidence>=this.confidenceThreshold&&!!n.command,o=!i&&n.confidence>0;if(ye){const t={};if(n.command?.roles)for(const[e,r]of n.command.roles)t[e]=r.value;const a={input:e.substring(0,100),language:this.language,confidence:n.confidence,threshold:this.confidenceThreshold,semanticSuccess:i,fallbackTriggered:o,command:n.command?.name,roles:Object.keys(t).length>0?t:void 0,errors:n.errors,timestamp:Date.now(),duration:s};!function(e){if(!ye)return;const t=e.semanticSuccess?"semantic":e.fallbackTriggered?"fallback":"traditional",r=Math.round(100*e.confidence),n=Math.round(100*e.threshold),s=e.semanticSuccess?"color: #4caf50; font-weight: bold":e.fallbackTriggered?"color: #ff9800; font-weight: bold":"color: #9e9e9e";if(console.groupCollapsed(`%c[Semantic] ${t.toUpperCase()} %c${e.input.substring(0,50)}${e.input.length>50?"...":""}`,s,"color: #888"),console.log(`Confidence: ${r}% (threshold: ${n}%)`),e.command&&console.log("Command: "+e.command),e.roles&&Object.keys(e.roles).length>0&&console.log("Roles:",e.roles),e.duration&&console.log(`Duration: ${e.duration.toFixed(2)}ms`),e.errors?.length&&console.log("Errors:",e.errors),console.groupEnd(),ve){const t=new CustomEvent("lokascript:semantic:parse",{detail:e,bubbles:1});ve.dispatchEvent(t)}}(a),r=a,ge.totalParses++,r.semanticSuccess?ge.semanticSuccesses++:r.fallbackTriggered?ge.semanticFallbacks++:ge.traditionalParses++,ge.confidenceHistory.push(r.confidence),ge.confidenceHistory.length>100&&ge.confidenceHistory.shift(),ge.averageConfidence=ge.confidenceHistory.reduce((e,t)=>e+t,0)/ge.confidenceHistory.length}return i?{success:1,node:this.buildCommandNode(n),confidence:n.confidence,tokensConsumed:n.tokensConsumed}:{success:0,confidence:n.confidence,tokensConsumed:n.tokensConsumed,errors:n.errors}}catch(e){return{success:0,confidence:0,errors:[e instanceof Error?e.message:e+""]}}var r}buildCommandNode(e){const{command:t}=e;if(!t)throw Error("Cannot build command node without command data");if("repeat"===t.name)return this.buildRepeatCommandNode(t);if("for"===t.name)return this.buildRepeatCommandNode(t);if("set"===t.name)return this.buildSetCommandNode(t);if("if"===t.name||"unless"===t.name)return this.buildIfCommandNode(t);const r=[],n={};for(const[e,s]of t.roles){const i=this.semanticValueToExpression(s);switch(e){case"patient":case"event":r.push(i);break;case"destination":"put"===t.name?n.into=i:"add"===t.name||"append"===t.name||"prepend"===t.name?n.to=i:n.on=i;break;case"source":"fetch"===t.name?r.push(i):n.from=i;break;case"quantity":n.by=i;break;case"duration":n.over=i;break;case"responseType":n.as=i;break;case"method":n.method=i;break;case"style":n.with=i;break;case"condition":n.when=i;break;default:n[e]=i}}return{type:"command",name:t.name,args:r,modifiers:Object.keys(n).length>0?n:void 0,isBlocking:0,start:0,end:0,line:1,column:0}}buildRepeatCommandNode(e){const t=[],r={},n=e.roles.get("loopType");n&&t.push({type:"identifier",name:n.value+"",start:0,end:0,line:1,column:0});const s=e.roles.get("patient");"for"==(n?n.value+"":"")&&s&&t.push({type:"identifier",name:"expression"===s.type&&s.raw||s.value+"",start:0,end:0,line:1,column:0});const i=e.roles.get("event");i&&t.push({type:"string",value:i.value+"",start:0,end:0,line:1,column:0});const o=e.roles.get("source");o&&t.push(this.semanticValueToExpression(o));const a=e.roles.get("quantity");a&&t.push(this.semanticValueToExpression(a));const c=e.roles.get("condition");return c&&(r.condition=this.semanticValueToExpression(c)),{type:"command",name:"repeat",args:t,modifiers:Object.keys(r).length>0?r:void 0,isBlocking:0,start:0,end:0,line:1,column:0}}buildSetCommandNode(e){const t=[],r=e.roles.get("destination");if(r)if("property-path"===r.type){const e=r;t.push({type:"possessiveExpression",object:this.semanticValueToExpression(e.object),property:this.createPropertyNode(e.property),start:0,end:0,line:1,column:0})}else t.push(this.semanticValueToExpression(r));t.push({type:"identifier",name:"to",start:0,end:0,line:1,column:0});const n=e.roles.get("patient");return n&&t.push(this.semanticValueToExpression(n)),{type:"command",name:"set",args:t,isBlocking:0,start:0,end:0,line:1,column:0}}createPropertyNode(e){return e.startsWith("*")?{type:"cssProperty",name:e.substring(1),start:0,end:0,line:1,column:0}:{type:"identifier",name:e,start:0,end:0,line:1,column:0}}buildIfCommandNode(e){const t=[],r=e.roles.get("condition");return r&&t.push(this.semanticValueToExpression(r)),{type:"command",name:e.name,args:t,isBlocking:0,start:0,end:0,line:1,column:0}}semanticValueToExpression(e){switch(e.type){case"selector":return{type:"selector",value:e.value,start:0,end:0,line:1,column:0};case"reference":return{type:"identifier",name:e.value,start:0,end:0,line:1,column:0};case"literal":return"string"==typeof e.value&&e.value.includes("${")&&e.value.includes("}")?{type:"templateLiteral",value:e.value,start:0,end:0,line:1,column:0}:{type:"literal",value:e.value,raw:e.raw??e.value,start:0,end:0,line:1,column:0};case"property-path":{const t=e;return{type:"memberExpression",object:this.semanticValueToExpression(t.object),property:{type:"identifier",name:t.property,start:0,end:0,line:1,column:0},computed:0,start:0,end:0,line:1,column:0}}default:return this.parseExpressionString(e.raw||"")}}parseExpressionString(e){let t=0;const r=()=>{for(;e.length>t&&/\s/.test(e[t]);)t++},n=()=>{r();const n=t;for(;e.length>t&&/[a-zA-Z0-9_$]/.test(e[t]);)t++;return e.slice(n,t)},s=()=>{const n=[];if(t++,r(),")"!==e[t])for(n.push(i()),r();","===e[t];)t++,r(),n.push(i()),r();return")"===e[t]&&t++,n},i=()=>{r();const i=n();if(!i)return{type:"identifier",name:e.trim(),start:0,end:0,line:1,column:0};let o={type:"identifier",name:i,start:0,end:0,line:1,column:0};for(;e.length>t;){r();const i=e[t];if("."===i){t++;const e=n();e&&(o={type:"memberExpression",object:o,property:{type:"identifier",name:e,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}}function Ee(e){return e.kind!==I.IDENTIFIER?0:w.has(e.value.toLowerCase())}function we(e){return e.kind!==I.IDENTIFIER?0:R.has(e.value.toLowerCase())}function xe(e){return e.kind!==I.IDENTIFIER?0:$.has(e.value.toLowerCase())}function ke(e){return e.kind!==I.IDENTIFIER?0:N.has(e.value.toLowerCase())}function Ae(e){return L.has(e.value.toLowerCase())}function Se(e){return e.kind===I.IDENTIFIER}function Ce(e){return e.kind===I.SELECTOR}function Te(e){return e.kind!==I.SELECTOR?0:!e.value.startsWith("<")}function Ne(e){return e.kind===I.STRING||e.kind===I.NUMBER||e.kind===I.TEMPLATE}function Oe(e){return e.kind===I.IDENTIFIER}function Le(e){return e.kind===I.TIME}function $e(e){return e.kind===I.COMMENT}function Re(e){if(e.kind!==I.IDENTIFIER)return 0;const t=e.value.toLowerCase();return!(w.has(t)||R.has(t)||$.has(t)||N.has(t))}function Ie(e){return e.kind===I.STRING}function je(e){return e.kind===I.NUMBER}function Me(e){if(e.kind===I.IDENTIFIER){const t=e.value;return"true"===t||"false"===t||"null"===t||"undefined"===t}return 0}function De(e){return e.kind===I.TEMPLATE}function Ve(e){return e.kind===I.SELECTOR&&e.value.startsWith("<")}function Be(e){return e.kind===I.SELECTOR&&e.value.startsWith("#")}function Pe(e){return e.kind===I.SELECTOR&&e.value.startsWith(".")}function _e(e){return e.kind!==I.SELECTOR?0:!e.value.startsWith("#")&&!e.value.startsWith(".")}function Fe(e){if(e.kind!==I.OPERATOR)return 0;const t=e.value.toLowerCase();return!O.has(t)&&!L.has(t)}function qe(e){const t=e.value.toLowerCase();return"then"===t||"and"===t||"else"===t||"end"===t||"on"===t}function Ue(e,t,r){return{type:"literal",value:e,raw:t,start:r.start,end:r.end,line:r.line,column:r.column}}function He(e,t){return{type:"identifier",name:e,start:t.start,end:t.end,line:t.line,column:t.column}}function We(e,t,r,n){return{type:"binaryExpression",operator:e,left:t,right:r,start:n.start,end:n.end,line:n.line,column:n.column}}be.SKIP_SEMANTIC_COMMANDS=new Set(["swap","morph","js","tell"]);const ze=[{command:"append",keywords:["to"],syntax:"append <value> [to <target>]"},{command:"fetch",keywords:["as","with"],syntax:"fetch <url> [as <type>] [with <options>]"},{command:"make",keywords:["a","an"],syntax:"make (a|an) <type>"},{command:"send",keywords:["to"],syntax:"send <event> to <target>"},{command:"throw",keywords:[],syntax:"throw <error>"}];function Je(e,t){return e?t.some(t=>e.value===t||e.value.toLowerCase()===t):0}const Ze=[e,n,t,r];function Ge(e,t=[]){if(e.isAtEnd())return 1;for(const t of Ze)if(e.check(t))return 1;for(const r of t)if(e.check(r))return 1;return e.checkIsCommand()?1:0}function Ye(e,t=[]){if(!Ge(e,t))return e.parseExpression()}function Xe(e,t,r){return e.check(t)?(e.advance(),r.push(e.createIdentifier(t)),1):0}function Ke(e,t,r){for(const n of t)if(e.check(n))return e.advance(),r.push(e.createIdentifier(n)),n;return null}class Qe{constructor(e){this.args=[],this.isBlocking=0,this.name=e}static from(e){const t=new Qe(e.value);return t.startPos={start:e.start??0,end:e.end??0,line:e.line??1,column:e.column??1},t}static fromIdentifier(e){const t=new Qe(e.name);return void 0!==e.start&&(t.startPos={start:e.start,end:e.end??0,line:e.line??1,column:e.column??1}),t}static named(e){return new Qe(e)}withArgs(...e){return this.args.push(...e),this}withBody(e){return this.body=e,this}withImplicitTarget(e){return this.implicitTarget=e,this}withModifier(e,t){return this.modifiers||(this.modifiers={}),this.modifiers[e]=t,this}withModifiers(e){return this.modifiers={...this.modifiers,...e},this}blocking(e=1){return this.isBlocking=e,this}startingAt(e){return this.startPos={start:e.start??0,end:e.end??0,line:e.line??1,column:e.column??1},this}endingAt(e){return this.endPos={start:e.start??this.startPos?.start??0,end:e.end,line:e.line??this.startPos?.line??1,column:e.column??this.startPos?.column??1},this}build(){const e={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&&(e.body=this.body),this.implicitTarget&&(e.implicitTarget=this.implicitTarget),this.modifiers&&(e.modifiers=this.modifiers),e}clone(){const e=new Qe(this.name);return e.args=[...this.args],e.body=this.body?[...this.body]:void 0,e.implicitTarget=this.implicitTarget,e.isBlocking=this.isBlocking,e.modifiers=this.modifiers?{...this.modifiers}:void 0,e.startPos=this.startPos?{...this.startPos}:void 0,e.endPos=this.endPos?{...this.endPos}:void 0,e}}function et(e,t){const r=[];let n="";const s=e.peek().start||0,i=e.peek().line||1,o=e.peek().column||1;if(e.checkIdentifierLike()){for(n=e.advance().value;e.check(":")&&!e.isAtEnd();)e.advance(),n+=":",e.checkIdentifierLike()&&(n+=e.advance().value);r.push({type:"string",value:n,start:s,end:e.getPosition().end,line:i,column:o})}for(;!Ge(e);)r.push(e.parsePrimary());let a=-1,c="on";for(let e=0;r.length>e;e++){const t=r[e],n=t.name||t.value;if(!("identifier"!==t.type&&"literal"!==t.type&&"keyword"!==t.type||"on"!==n&&"to"!==n)){a=e,c=n;break}}const l=[];if(-1===a)l.push(...r);else{const t=r.slice(0,a),n=r.slice(a+1);l.push(...t),l.push(e.createIdentifier(c)),l.push(...n)}return Qe.fromIdentifier(t).withArgs(...l).endingAt(e.getPosition()).build()}function tt(e,t){const r=[];if(e.check(b)){const t=e.advance();if(r.push({type:"identifier",name:b,start:t.start,end:t.end,line:t.line,column:t.column}),e.check(y)){const t=e.advance();r.push({type:"identifier",name:y,start:t.start,end:t.end,line:t.line,column:t.column})}}return Qe.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}function rt(n,s){const i=[];let o=0;const a=n.current;for(let t=0;500>t&&!n.isAtEnd();t++){const t=n.peek();if(t.value===e){o=1;break}if(t.value===r||t.value===v||"def"===t.value||t.value===m)break;n.advance()}n.current=a;let c=0;if(!o){const e=n.current,i=s.line,o=100;for(;!n.isAtEnd()&&o>n.current-e;){const e=n.peek(),s=e.value?.toLowerCase();if(s===v||"def"===s||s===m)break;if(s===t||s===r){e.line===i&&(c=1);break}if((n.checkIsCommand()||n.isCommand(s))&&void 0!==e.line&&e.line!==i){c=1;break}n.advance()}n.current=e}const l=o||c;let u;if(l)u=n.parseExpression();else{const t=[],r=20;let i=0;for(;!n.isAtEnd()&&!n.checkIsCommand()&&!n.isCommand(n.peek().value)&&!n.check(e)&&r>i;){const e=n.current;t.push(n.parseLogicalAnd()),n.current===e&&n.advance(),i++}if(0===t.length)throw Error("Expected condition after if/unless");u=1===t.length?t[0]:{type:"expression",tokens:t,start:t[0].start,end:t[t.length-1].end,line:s.line,column:s.column}}if(i.push(u),l){o&&n.advance();const e=[];for(;!n.isAtEnd()&&!n.check(t)&&!n.check(r)&&(n.checkIsCommand()||n.isCommand(n.peek().value));){n.advance();const t=n.parseCommand();t&&e.push(t)}if(0===e.length&&n.isAtEnd())throw Error("Expected command after 'then' in if statement - incomplete conditional");i.push({type:"block",commands:e,start:s.start,end:n.getPosition().end,line:s.line,column:s.column});let a=0;if(n.check(t))if(n.advance(),n.check("if")){const e=n.peek();n.advance();const t=rt(n,e);i.push({type:"block",commands:[t],start:e.start,end:n.getPosition().end,line:e.line,column:e.column}),a=1}else{const e=[];for(;!n.isAtEnd()&&!n.check(r)&&(n.checkIsCommand()||n.isCommand(n.peek().value));){n.advance();const t=n.parseCommand();t&&e.push(t)}i.push({type:"block",commands:e,start:s.start,end:n.getPosition().end,line:s.line,column:s.column})}a||n.consume(r,"Expected 'end' after if block")}else{if(!n.checkIsCommand()&&!n.isCommand(n.peek().value))throw Error("Expected command after if condition in single-line form");{n.advance();const e=n.parseCommand();i.push({type:"block",commands:[e],start:s.start,end:n.getPosition().end,line:s.line,column:s.column})}}return Qe.from(s).withArgs(...i).endingAt(n.getPosition()).build()}function nt(e,t){const r=[],n={};if(e.checkAnySelector()||e.checkContextVar()||e.match("<")){const t=e.parsePrimary();if(r.push(t),e.match("*")){if(e.checkIdentifierLike()){const t=e.advance();r.push({type:"identifier",name:"*"+t.value,start:t.start-1,end:t.end,line:t.line,column:t.column})}}else if(e.checkIdentifierLike()){const t=e.parsePrimary();r.push(t)}}else if(e.checkIdentifierLike()){const t=e.parsePrimary();r.push(t)}if(e.match("and")&&e.match("set")&&e.checkIdentifierLike()){const t=e.advance();n.set={type:"identifier",name:t.value,start:t.start,end:t.end,line:t.line,column:t.column}}const s=Qe.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition());return Object.keys(n).length>0&&s.withModifiers(n),s.build()}function st(e,t){const r=[],n=Ye(e,[f]);n&&r.push(n),Xe(e,f,r);const s=Ye(e);return s&&r.push(s),Qe.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}function it(e,t){const r=[];if(e.check("between")){e.advance(),r.push(e.createIdentifier("between"));const i=Ye(e,[n]);i&&r.push(i),Xe(e,n,r);const o=Ye(e,[f,m,s]);if(o&&r.push(o),Ke(e,[f,m],r)){const t=Ye(e);t&&r.push(t)}return Qe.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}const i=Ye(e,[f,m]);if(i&&r.push(i),Ke(e,[f,m],r)){const t=Ye(e);t&&r.push(t)}return Qe.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}function ot(e,t){const n=e.parseExpression();if(!n)return e.addError("Put command requires content expression"),null;const s=e.peek();if(!s||!S.includes(s.value))return e.addError(`Expected operation keyword (${S.join(", ")}) after put expression, got: ${s?.value}`),null;let i=e.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=A:"at"===i&&(e.check(E)||e.check(b)?(e.check(b)&&e.advance(),e.check(E)&&(e.advance(),e.check(p)&&(e.advance(),i=k))):e.check(r)&&(e.advance(),e.check(p)&&(e.advance(),i=A)));const a=e.parseExpression();return a?Qe.fromIdentifier(t).withArgs(n,e.createIdentifier(i),a).endingAt(e.getPosition()).build():(e.addError("Put command requires target expression after operation keyword"),null)}const at=["innerhtml","outerhtml","into","over","delete","morph","morphouter"];function ct(s,i){const o=s.current;let a=null;try{if(s.check(":"))if(s.advance(),s.check(":")){s.advance();const e=s.advance();a={type:"identifier",name:e.value,scope:"global",start:e.start-2,end:e.end}}else{const e=s.advance();a={type:"identifier",name:e.value,scope:"local",start:e.start-1,end:e.end}}else if(s.check(g)||s.check("local")){const e=s.advance(),t=s.advance();a={type:"identifier",name:t.value,scope:e.value,start:e.start,end:t.end}}else if(s.check(b)){const e=s.current;s.advance();const t=s.peek(),r=s.tokens.length>s.current+1?s.tokens[s.current+1]:null;if(t&&r&&r.value===p){const e=s.advance();if(s.check(p)){s.advance();const t=s.advance(),r=t.value.startsWith("#");a={type:"propertyOfExpression",property:{type:"identifier",name:e.value,start:e.start,end:e.end},target:{type:r?"idSelector":"cssSelector",value:t.value,start:t.start,end:t.end},start:o,end:s.current}}else s.current=o,a=null}else if(t&&r&&r.value===h){const e=s.advance();a={type:"identifier",name:e.value,start:e.start,end:e.end}}else s.current=e,a=null}else a=s.parseExpression()}catch(e){s.current=o,a=null}const c=[];if(!a){if(s.match(":")){const e=s.advance();a={type:"identifier",name:e.value,scope:"local",start:e.start,end:e.end}}else for(;!(s.isAtEnd()||s.check(h)||s.check(e)||s.check(n)||s.check(t)||s.check(r));){const e=s.parsePrimary();c.push(e)}c.length>0&&(a=4>c.length||c[0].value!==b||c[2].value!==p?1===c.length?c[0]:null:{type:"propertyOfExpression",property:{type:"identifier",name:c[1].value||c[1].name,start:c[1].start,end:c[1].end},target:{type:"idSelector"===c[3].type?"idSelector":"cssSelector",value:c[3].value||c[3].name,start:c[3].start,end:c[3].end},start:c[0].start,end:c[3].end})}if(!s.check(h)){const e=s.isAtEnd()?"end of input":s.peek().value;throw Error("Expected 'to' in set command, found: "+e)}s.advance();const l=[],u=s.parseExpression();if(u)l.push(u);else{const e=s.parsePrimary();e&&l.push(e)}const f=[];return a?f.push(a):c.length>0&&f.push(...c),f.push(s.createIdentifier(h)),l.length>0&&f.push(...l),{type:"command",name:i.name,args:f,isBlocking:0,start:i.start||0,end:s.getPosition().end,line:i.line||1,column:i.column||1}}function lt(e,t){const r=[];for(;!Ge(e,["catch","finally"])&&(e.checkIdentifierLike()||e.checkSelector()||e.checkLiteral()||e.checkTimeExpression()||e.match("<"));)r.push(e.parsePrimary());return Qe.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}class ut{constructor(e,t,r){this.current=0,this.warnings=[],this.tokens=e,this.keywordResolver=t?.keywords,this.registryIntegration=t?.registryIntegration,t?.semanticAnalyzer&&t?.language&&(this.semanticAdapter=new be({analyzer:t.semanticAnalyzer,language:t.language,confidenceThreshold:t.semanticConfidenceThreshold??.5})),this.originalInput=r||e.map(e=>e.value).join(" ")}resolveKeyword(e){return this.keywordResolver?this.keywordResolver.resolve(e)??e:e}addWarning(e){this.warnings.push(e)}parse(){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 e=[];for(;this.check("behavior");){this.advance();const t=this.parseBehaviorDefinition();if(t&&e.push(t),this.error)break}return this.error?{success:0,node:1===e.length?e[0]:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:1,node:1===e.length?e[0]:this.createProgramNode(e),tokens:this.tokens,warnings:this.warnings}}if(this.check("init")||this.check("on")||this.check("def")||this.checkComment()){const e=[];for(;!this.isAtEnd();)if(this.checkComment())this.advance();else if(this.check("init")){this.advance();const t=this.parseTopLevelInitBlock();t&&e.push(t)}else if(this.check("on")){this.advance();const t=this.parseEventHandler();t&&e.push(t)}else{if(!this.check("def"))break;{this.advance();const t=this.parseDefFeature();t&&e.push(t)}}return this.isAtEnd()?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}:(this.addError("Unexpected token: "+this.peek().value),{success:0,node:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings})}if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){const e=this.parseCommandSequence();if(e){if(!this.isAtEnd()&&this.check("on")){fe("✅ PARSER: Found event handlers after command sequence, parsing as program");const t=[e];fe(`✅ PARSER: Starting with ${t.length} statement(s) from command sequence`);let r=0;for(;!this.isAtEnd()&&this.check("on");){fe(`✅ PARSER: Parsing event handler #${r+1}, current token: ${this.peek().value}`),this.advance();const e=this.parseEventHandler();if(fe("✅ PARSER: parseEventHandler returned:",e?`type=${e.type}, event=${e.event}`:"null"),e&&(t.push(e),r++,fe(`✅ PARSER: Added event handler, now have ${t.length} statements total`)),fe(`✅ 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 fe("⚠️ PARSER: Unexpected token after event handlers: "+this.peek().value),this.addError("Unexpected token after event handlers: "+this.peek().value),{success:0,node:this.createProgramNode(t),tokens:this.tokens,error:this.error};fe("✅ PARSER: No more event handlers, at end of input");break}}return fe(`✅ PARSER: Finished parsing, creating Program node with ${t.length} statements`),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}}return this.isAtEnd()?this.error?{success:0,node:e,tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:1,node:e,tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:0,node:e||this.createErrorNode(),tokens:this.tokens,error:this.error})}}const e=this.parseExpression();return this.error?{success:0,node:e||this.createErrorNode(),tokens:this.tokens,error:this.error}:this.isAtEnd()?{success:1,node:e,tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:0,node:e||this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings})}catch(e){return this.addError(e instanceof Error?e.message:"Unknown parsing error"),{success:0,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}}parseExpression(){return this.parseAssignment()}parseAssignment(){let e=this.parseLogicalOr();if(this.match("=")){const t=this.previous().value,r=this.parseAssignment();e=this.createBinaryExpression(t,e,r)}return e}parseLogicalOr(){let e=this.parseLogicalAnd();for(;this.match("or");){const t=this.previous().value,r=this.parseLogicalAnd();e=this.createBinaryExpression(t,e,r)}return e}parseLogicalAnd(){let e=this.parseEquality();for(;this.match("and");){const t=this.previous().value,r=this.parseEquality();e=this.createBinaryExpression(t,e,r)}return e}parseEquality(){let e=this.parseComparison();for(;this.matchComparisonOperator()||this.match("is","match","matches","contains","include","includes","in","of","as","really");){const t=this.previous().value;if(ut.POSTFIX_UNARY_OPERATORS.has(t)){e=this.createUnaryExpression(t,e,0);continue}const r=this.parseComparison();e=this.createBinaryExpression(t,e,r)}return e}parseComparison(){let e=this.parseAddition();for(;this.matchComparisonOperator();){const t=this.previous().value;if(ut.POSTFIX_UNARY_OPERATORS.has(t)){e=this.createUnaryExpression(t,e,0);continue}const r=this.parseAddition();e=this.createBinaryExpression(t,e,r)}return e}parseAddition(){let e=this.parseMultiplication();for(;this.match("+","-")||this.matchOperator("+")||this.matchOperator("-");){const t=this.previous().value;if(this.check("+")||this.check("-"))return this.addError(`Invalid operator combination: ${t}${this.peek().value}`),e;if(this.isAtEnd())return this.addError(`Expected expression after '${t}' operator`),e;const r=this.parseMultiplication();e=this.createBinaryExpression(t,e,r)}return e}parseMultiplication(){let e=this.parseUnary();for(;this.match("*","/","%","mod");){const t=this.previous().value;if(this.check("*")||this.check("/")||this.check("%")||this.check("+")||this.check("-")){const r=this.peek().value;return this.addError("*"===t&&"*"===r?"Unexpected token: "+r:`Invalid operator combination: ${t}${r}`),e}if(this.isAtEnd())return this.addError(`Expected expression after '${t}' operator`),e;const r=this.parseUnary();e=this.createBinaryExpression(t,e,r)}return e}parseUnary(){if(this.match("not","no","exists","some","-","+")){const e=this.previous().value;if(this.isAtEnd())return this.addError(`Expected expression after '${e}' operator`),this.createErrorNode();const t=this.parseUnary();return this.createUnaryExpression(e,t,1)}if(this.check("does")&&this.tokens.length>this.current+1&&"not"===this.tokens[this.current+1].value&&this.tokens.length>this.current+2&&"exist"===this.tokens[this.current+2].value){if(this.advance(),this.advance(),this.advance(),this.isAtEnd())return this.addError("Expected expression after 'does not exist' operator"),this.createErrorNode();const e=this.parseUnary();return this.createUnaryExpression("does not exist",e,1)}return this.parseImplicitBinary()}parseImplicitBinary(){let e=this.parseCall();for(;!(this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("and")||this.check("else")||this.check(")")||this.check("]")||this.check(","));){if("identifier"!==e.type){if("literal"===e.type&&(this.checkNumber()||this.checkIdentifier())){const t=this.peek();return this.addError(`Missing operator between '${e.raw||e.value}' and '${t.value}'`),e}break}if(this.isCommand(e.name))if(this.isCompoundCommand(e.name.toLowerCase())){if(!(this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkTimeExpression()||this.checkString()||this.checkNumber()||this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()))break;{const t=this.createCommandFromIdentifier(e);t&&(e=t)}}else if("wait"===e.name.toLowerCase()&&this.checkTimeExpression()){const t=this.createCommandFromIdentifier(e);t&&(e=t)}else{if(!this.checkSelector())break;{const t=this.parseCall();e=this.createBinaryExpression(" ",e,t)}}else{if(!this.checkSelector())break;{const t=this.parseCall();e=this.createBinaryExpression(" ",e,t)}}}return e}isCommand(e){return this.keywordResolver?this.keywordResolver.isCommand(e):(e=>w.has(e.toLowerCase()))(e)}isKeyword(e){return this.keywordResolver?this.keywordResolver.isKeyword(e):(e=>C.has(e.toLowerCase()))(e)}createCommandFromIdentifier(e){const t=[],r=this.resolveKeyword(e.name.toLowerCase());if(this.isCompoundCommand(r))return this.parseCompoundCommand(e);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("<"));)t.push(this.parsePrimary());return{type:"command",name:e.name,args:t,isBlocking:0,...void 0!==e.start&&{start:e.start},end:this.getPosition().end,...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}}}isCompoundCommand(e){return x.has(e.toLowerCase())}parseCompoundCommand(s){return function(s,i){switch(i.name.toLowerCase()){case"put":return ot(s,i);case"trigger":case"send":return et(s,i);case"remove":return st(s,i);case"toggle":return it(s,i);case"set":return ct(s,i);case"halt":return tt(s,i);case"measure":return nt(s,i);case"js":return function(e,t){const n=[];if(e.match("(")){for(;!e.check(")")&&!e.isAtEnd();)e.checkIdentifierLike()&&n.push(e.advance().value),e.match(",");e.consume(")","Expected ) after js parameters")}const s=e.peek().start;for(;!e.check(r)&&!e.isAtEnd();)e.advance();const i=e.peek().start;e.consume(r,"Expected end after js code body");const o={type:"literal",value:e.getInputSlice(s,i).trim(),start:t.start,end:e.getPosition().end},a={type:"arrayLiteral",elements:n.map(e=>({type:"literal",value:e,start:t.start,end:t.end})),start:t.start,end:e.getPosition().end};return Qe.fromIdentifier(t).withArgs(o,a).endingAt(e.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 e=s.parseCommand();if(!e)break;a.push(e)}catch{break}if(s.match(n))continue;if(s.check(e)||s.check(t)||s.check(r))break;if(s.checkIsCommand())continue;break}break}if(0===a.length)throw Error("tell command requires at least one command after the target");return Qe.fromIdentifier(i).withArgs(o,...a).endingAt(s.getPosition()).build()}(s,i);case"swap":case"morph":return function(e,t){console.log("[PARSER DEBUG] parseSwapCommand called");const r=[];let n=null;if(!e.isAtEnd()){const t=e.peek();if(t&&t.value){const s=t.value.toLowerCase();at.includes(s)&&(n=s,e.advance(),r.push(e.createIdentifier(n)))}}if("delete"===n){const n=e.parseExpression();return n&&r.push(n),Qe.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}!e.isAtEnd()&&e.check(p)&&(e.advance(),r.push(e.createIdentifier("of")));const s=e.parseExpression();if(s&&r.push(s),!e.isAtEnd()&&e.check(d)){e.advance(),r.push(e.createIdentifier("with"));const t=e.parseExpression();t&&r.push(t)}return Qe.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}(s,i);default:return lt(s,i)}}(this.getContext(),s)}parsePutCommand(e){return ot(this.getContext(),e)}parseSetCommand(e){return ct(this.getContext(),e)}parseHaltCommand(e){return tt(this.getContext(),e)}parseMeasureCommand(e){return nt(this.getContext(),e)}parseTriggerCommand(e){return et(this.getContext(),e)}parseCommandListUntilEnd(){const e=[];for(fe("🔄 parseCommandListUntilEnd: Starting to parse command list");!this.isAtEnd()&&!this.check("end");){fe("📍 Loop iteration, current token:",this.peek().value,"kind:",this.peek().kind);let t=0;if(this.checkIsCommand()){fe("✅ Found COMMAND token:",this.peek().value),this.advance();const r=this.error;try{const n=this.parseCommand();this.error&&this.error!==r&&(fe("⚠️ parseCommandListUntilEnd: Command parsing added error, restoring error state. Error was:",this.error.message),this.error=r),n&&(fe("✅ Parsed command:",n.name),e.push(n),t=1)}catch(e){fe("⚠️ parseCommandListUntilEnd: Command parsing threw exception, restoring error state:",e instanceof Error?e.message:e+""),this.error=r}}else if(this.checkIdentifier()){const r=this.peek();if(this.isCommand(r.value)){fe("✅ Found IDENTIFIER that is a command:",r.value),this.advance();const n=this.error;try{const r=this.parseCommand();this.error&&this.error!==n&&(fe("⚠️ parseCommandListUntilEnd: Command parsing added error, restoring error state. Error was:",this.error.message),this.error=n),r&&(fe("✅ Parsed command:",r.name),e.push(r),t=1)}catch(e){fe("⚠️ parseCommandListUntilEnd: Command parsing threw exception, restoring error state:",e instanceof Error?e.message:e+""),this.error=n}}else fe("❌ IDENTIFIER is not a command:",r.value)}if(!t){fe("❌ No command parsed, breaking. Current token:",this.peek().value);break}for(fe("📍 After parsing command, current token:",this.peek().value);!(this.isAtEnd()||this.check("end")||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(","));)fe("⚠️ Skipping unexpected token:",this.peek().value),this.advance();if(this.match("then","and",","))fe("✅ Found separator, continuing");else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){fe("📍 No separator and no command, breaking. Current token:",this.peek().value);break}fe("✅ Next token is a command, continuing without separator")}}if(fe('🔍 After loop, checking for "end". Current token:',this.peek().value),!this.check("end"))throw fe('❌ ERROR: Expected "end" but got:',this.peek().value,"at position:",this.peek().start),Error('Expected "end" to close repeat block');return fe('✅ Found "end", consuming it'),this.advance(),fe("✅ parseCommandListUntilEnd: Successfully parsed",e.length,"commands"),e}parseRepeatCommand(e){return function(e,t){const r=[];let n="forever",h=null,p=null,m=null,v=null,g=null,E=null;if(e.check(s)){e.advance(),n=s;const t=e.peek();Se(t)&&(g=t.value,e.advance()),e.check(u)&&(e.advance(),v=e.parseExpression())}else if(e.check(u))e.advance(),n=s,g="it",v=e.parseExpression();else if(e.check(i))e.advance(),n=i,m=e.parseExpression();else if(e.check(o))if(e.advance(),n=o,e.check(y)){e.advance(),n="until-event";const t=e.peek();if(fe("📍 Parsing event name, current token:",{value:t.value,kind:t.kind}),!Se(t)&&!xe(t))throw Error('Expected event name after "event"');if(h=t.value,e.advance(),fe("✅ Got event name:",h,"Next token:",e.peek().value),fe('🔍 Checking for "from", current token:',e.peek().value),e.check(f)){fe('✅ Found "from", advancing...'),e.advance(),fe('📍 After consuming "from", current token:',e.peek().value),e.check(b)&&(fe('✅ Found "the", advancing...'),e.advance());const t=e.peek();fe("🔍 Before parsePrimary for event target:",{value:t.value,kind:t.kind,position:t.start}),p=e.parsePrimary(),fe("✅ After parsePrimary, eventTarget:",p)}else fe('❌ No "from" found, skipping target parsing')}else m=e.parseExpression();else e.check(a)?(e.advance(),n=a):(E=e.parseExpression(),e.check(c)&&(e.advance(),n=c));let w=null;if(e.check(d)){const t=e.tokens.length>e.current+1?e.tokens[e.current+1]:null;t&&t.value.toLowerCase()===l&&(e.advance(),e.advance(),w=l)}else if(e.check(l)){e.advance();const t=e.peek();Se(t)?(w=t.value,e.advance()):w=l}const x=e.parseCommandListUntilEnd();return r.push({type:"identifier",name:n,start:t.start,end:t.end,line:t.line,column:t.column}),g&&r.push({type:"string",value:g,start:t.start,end:t.end,line:t.line,column:t.column}),v&&r.push(v),m&&r.push(m),E&&r.push(E),h&&r.push({type:"string",value:h,start:t.start,end:t.end,line:t.line,column:t.column}),p&&r.push(p),w&&r.push({type:"string",value:w,start:t.start,end:t.end,line:t.line,column:t.column}),r.push({type:"block",commands:x,start:t.start,end:t.end||0,line:t.line,column:t.column}),Qe.from(t).withArgs(...r).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseForCommand(e){return function(e,t){const r=[];let n=null,s=null;e.check("each")&&e.advance();const i=e.peek();if(!Se(i))throw Error('Expected variable name after "for"');if(n=i.value,e.advance(),!e.check(u))throw Error('Expected "in" after variable name in for loop');if(e.advance(),s=e.parseExpression(),!s)throw Error('Expected collection expression after "in"');let o=null;if(e.check(d)){const t=e.tokens.length>e.current+1?e.tokens[e.current+1]:null;t&&t.value.toLowerCase()===l&&(e.advance(),e.advance(),o=l)}else if(e.check(l)){e.advance();const t=e.peek();Se(t)?(o=t.value,e.advance()):o=l}const a=e.parseCommandListUntilEnd();return r.push({type:"identifier",name:"for",start:t.start,end:t.end,line:t.line,column:t.column}),r.push({type:"string",value:n,start:t.start,end:t.end,line:t.line,column:t.column}),r.push(s),o&&r.push({type:"string",value:o,start:t.start,end:t.end,line:t.line,column:t.column}),r.push({type:"block",commands:a,start:t.start,end:t.end||0,line:t.line,column:t.column}),Qe.from({...t,value:"repeat"}).withArgs(...r).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseWaitCommand(e){return function(e,t){const r=[];if(e.checkTimeExpression()||e.checkLiteral()){const n=e.parsePrimary();return r.push(n),{type:"command",name:"wait",args:r,isBlocking:1,start:t.start||0,end:e.getPosition().end,line:t.line||1,column:t.column||1}}if(e.check("for")){e.advance();const n=[];do{const t=e.peek();if(!Se(t))throw Error('Expected event name after "for"');const r=t.value;e.advance();const s=[];if(e.check("(")){for(e.advance();!e.isAtEnd()&&!e.check(")");){const t=e.peek();if(!Se(t))break;s.push(t.value),e.advance(),e.check(",")&&e.advance()}if(!e.check(")"))throw Error('Expected ")" after event parameters');e.advance()}if(n.push({name:r,params:s}),!e.check("or"))break;e.advance()}while(!e.isAtEnd());let s=null;e.check(f)&&(e.advance(),e.check(b)&&e.advance(),s=e.parsePrimary()),r.push({type:"arrayLiteral",elements:n.map(e=>({type:"objectLiteral",properties:[{key:{type:"identifier",name:"name"},value:{type:"literal",value:e.name,raw:`"${e.name}"`}},{key:{type:"identifier",name:"args"},value:{type:"arrayLiteral",elements:e.params.map(e=>({type:"literal",value:e,raw:`"${e}"`}))}}]})),start:t.start,end:e.getPosition().end,line:t.line,column:t.column}),s&&r.push(s)}return Qe.from(t).withArgs(...r).blocking().endingAt(e.getPosition()).build()}(this.getContext(),e)}parseInstallCommand(e){return function(e,t){const r=[];if(!e.checkIdentifierLike())throw Error('Expected behavior name after "install"');const n=e.advance().value,s=e.previous();if(r.push({type:"identifier",name:n,start:s.start,end:s.end,line:s.line,column:s.column}),e.check("(")){e.advance();const n=[];for(;!e.isAtEnd()&&!e.check(")");){const t=e.current;let r;if(e.checkIdentifierLike()){const n=e.peek().value;e.advance(),e.check(":")?(e.advance(),r=n):e.current=t}const s=e.parseExpression();if(n.push(void 0!==r?{name:r,value:s}:{value:s}),e.check(","))e.advance();else if(!e.check(")"))break}if(!e.check(")"))throw Error('Expected ")" after behavior parameters');e.advance(),n.length>0&&r.push({type:"objectLiteral",properties:n.map(e=>({key:e.name?{type:"identifier",name:e.name}:{type:"literal",value:"_positional"},value:e.value})),start:t.start,end:e.getPosition().end,line:t.line,column:t.column})}return Qe.from(t).withArgs(...r).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseTransitionCommand(e){return function(e,t){const r=[],n={};let s=null;const i=e.peek();if(Se(i)||"*"===i.value){let t="";if(e.check("*")&&(t="*",e.advance()),e.checkIdentifierLike()){for(t+=e.peek().value,e.advance();e.check("-")&&!e.isAtEnd();)t+="-",e.advance(),e.checkIdentifierLike()&&(t+=e.peek().value,e.advance());s={type:"string",value:t,start:i.start||0,end:e.getPosition().end,line:i.line,column:i.column}}}if(!s)throw Error("Transition command requires a CSS property");if(r.push(s),!e.check(h))throw Error('Expected "to" keyword after property in transition command');e.advance();const o=e.parsePrimary();if(n.to=o,e.check("over")){e.advance();const t=e.parsePrimary();n.over=t}if(e.check(d)){e.advance();const t=e.parsePrimary();n.with=t}return Qe.from(t).withArgs(...r).withModifiers(n).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseAddCommand(e){return function(e,t){const r=[];if(e.match("{"))r.push(e.parseCSSObjectLiteral());else{const t=Ye(e,[h]);t&&r.push(t)}if(e.check(h)){e.advance();const t=Ye(e);t&&r.push(t)}return Qe.from(t).withArgs(...r).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseIfCommand(e){return rt(this.getContext(),e)}parseRemoveCommand(e){return st(this.getContext(),e)}parseToggleCommand(e){return it(this.getContext(),e)}parseRegularCommand(e){return lt(this.getContext(),e)}parseCall(){let e=this.parsePrimary();for(;;)if(this.match("("))e=this.finishCall(e);else if(this.match(".")){const t=this.consumeIdentifier("Expected property name after '.' - malformed member access");e=this.createMemberExpression(e,this.createIdentifier(t.value),0)}else if(this.match("[")){const t=this.parseExpression();this.consume("]","Expected ']' after array index"),e=this.createMemberExpression(e,t,1)}else{if(!this.check("'s"))break;{let t;this.advance(),this.check("*")?(this.advance(),t="*"+this.consumeIdentifier("Expected property name after * in CSS property syntax").value):t=this.consumeIdentifier("Expected property name after possessive").value,e=this.createPossessiveExpression(e,this.createIdentifier(t))}}return e}parsePrimary(){if(this.check("*")){const e=this.current;if(this.advance(),!this.isAtEnd()&&Se(this.peek())){const e=this.advance().value;return this.createSelector("*"+e)}this.current=e}if(this.check("*")||this.check("/")||this.check("%")||this.check("mod")){const e=this.peek();return this.addError(`Binary operator '${e.value}' requires a left operand`),this.createErrorNode()}if(this.matchNumber()){const e=parseFloat(this.previous().value);return this.createLiteral(e,this.previous().value)}if(this.matchString()){const e=this.previous().value;if(2>e.length||e.startsWith('"')&&!e.endsWith('"')||e.startsWith("'")&&!e.endsWith("'"))return this.addError("Unclosed string literal - string not properly closed"),this.createErrorNode();const t=e.slice(1,-1),r=this.processEscapeSequences(t);return this.createLiteral(r,e)}if(this.matchTemplateLiteral()){const e=this.previous();return{type:"templateLiteral",value:e.value,start:e.start||0,end:e.end||0,line:e.line,column:e.column}}if(this.matchBoolean()){const e=this.previous().value;let t;switch(e){case"true":t=1;break;case"false":t=0;break;case"null":t=null;break;case"undefined":t=void 0;break;default:t="true"===e}return this.createLiteral(t,e)}if(this.matchTimeExpression()){const e=this.previous().value;return this.createLiteral(e,e)}if(this.matchQueryReference()){const e=this.previous().value.slice(1,-2).trim();return this.createSelector(e)}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 e=this.parseExpression();return this.consume(")","Expected closing parenthesis ')' after expression - unclosed parentheses"),e}if(this.match("{"))return this.parseObjectLiteral();if(this.match("["))return this.parseAttributeOrArrayLiteral();if(this.check(":")){if(this.advance(),this.check(":")){this.advance();const e=this.advance();return{type:"identifier",name:e.value,scope:"global",start:e.start-2,end:e.end,line:e.line,column:e.column}}{const e=this.advance();return{type:"identifier",name:e.value,scope:"local",start:e.start-1,end:e.end,line:e.line,column:e.column}}}if(this.matchBasicOperator()){const e=this.previous();return this.createIdentifier(e.value)}const e=this.peek();if((!e||"end"!==e.value&&"else"!==e.value&&"then"!==e.value)&&(this.matchPredicate(Re)||this.matchPredicate(we)||this.matchPredicate(ke)||this.matchPredicate(Ee)||this.matchPredicate(xe))){const e=this.previous();if("new"===e.value)return this.parseConstructorCall();if("on"===e.value)return this.parseEventHandler();if("if"===e.value)return this.parseConditional();if("closest"===e.value||"first"===e.value||"last"===e.value||"previous"===e.value||"next"===e.value){if(this.check("(")||this.checkCssSelector()||this.checkClassSelector()||this.checkIdSelector()||this.check("<")||this.checkQueryReference())return this.parseNavigationFunction(e.value);if(this.check(".")){const t=this.current;if(this.advance(),this.checkIdentifier()){const t=this.advance().value,r=this.createSelector("."+t);return this.createCallExpression(this.createIdentifier(e.value),[r])}this.current=t}if(this.check("#")){const t=this.current;if(this.advance(),this.checkIdentifier()){const t=this.advance().value,r=this.createSelector("#"+t);return this.createCallExpression(this.createIdentifier(e.value),[r])}this.current=t}return this.createIdentifier(e.value)}return"my"!==e.value||this.check(".")?"its"!==e.value||this.check(".")?"your"!==e.value||this.check(".")?"the"===e.value?this.parseTheXofY():this.createIdentifier(e.value):this.parseContextPropertyAccess("you"):this.parseContextPropertyAccess("it"):this.parseContextPropertyAccess("me")}if(this.match("$"))return this.parseDollarExpression();const t=this.peek();return this.addError(`Unexpected token: ${t.value} at line ${t.line}, column ${t.column}`),this.createErrorNode()}parseDollarExpression(){if(this.checkNumber()){const e=this.advance().value;return this.createLiteral(e,"$"+e)}if(this.checkIdentifier()){const e=this.advance();let t=this.createIdentifier(e.value);for(;this.match(".");){if(!this.checkIdentifier())return this.addError("Expected property name after '.' in dollar expression"),this.createErrorNode();{const e=this.advance();t=this.createMemberExpression(t,this.createIdentifier(e.value),0)}}return{type:"dollarExpression",expression:t,raw:`$${e.value}${this.previous().raw||this.previous().value||""}`,line:e.line,column:e.column-1}}return this.addError("Expected identifier or number after '$'"),this.createErrorNode()}parseHyperscriptSelector(){let e="";for(;!this.check("/")&&!this.isAtEnd();)e+=this.advance().value;return this.consume("/","Expected '/' in hyperscript selector"),this.consume(">","Expected '>' after '/' in hyperscript selector"),this.createSelector(e)}parseObjectLiteral(){const e=[],t=this.getPosition();if(this.check("}"))return this.advance(),{type:"objectLiteral",properties:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column};do{let t;if(this.matchPredicate(Re))t=this.createIdentifier(this.previous().value);else{if(!this.matchString())return this.addError("Expected property name in object literal"),this.createErrorNode();{const e=this.previous().value,r=e.slice(1,-1);t=this.createLiteral(r,e)}}this.consume(":","Expected ':' after property name in object literal");const r=this.parseExpression();if(e.push({key:t,value:r}),!this.match(","))break;if(this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after object literal properties"),{type:"objectLiteral",properties:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseCSSObjectLiteral(){const e=this.getPosition(),t=[];do{if(this.check("}"))break;let r;if(this.matchPredicate(Re))r=this.createIdentifier(this.previous().value);else{if(!this.matchString())return this.addError("Expected CSS property name"),this.createErrorNode();{const e=this.previous().value,t=e.slice(1,-1);r=this.createLiteral(t,e)}}if(!this.consume(":","Expected ':' after CSS property name"))return this.createErrorNode();const n=[];let s=0,i=0;for(;!this.isAtEnd()&&(0!==i||!this.check(";")&&!this.check("}"));){const e=this.advance();n.push(e.value),"$"===e.value&&this.check("{")&&(s=1),"{"===e.value&&i++,"}"===e.value&&i--}const o=n.join(""),a=s?{type:"templateLiteral",value:o,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}:this.createLiteral(o,o);if(t.push({key:r,value:a}),this.check(";")&&this.advance(),this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after CSS object literal properties"),{type:"objectLiteral",properties:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseConstructorCall(){const e=this.previous();if(!this.checkIdentifier())return this.addError('Expected constructor name after "new"'),this.createErrorNode();const t=this.advance(),r=t.value;if(!this.check("("))return this.addError('Expected "(" after constructor name'),this.createErrorNode();if(this.advance(),this.check(")"))this.advance();else{let e=1;for(;e>0&&!this.isAtEnd();){const t=this.advance();"("===t.value&&e++,")"===t.value&&e--}}return{type:"callExpression",callee:{type:"identifier",name:r,start:t.start,end:t.end,line:t.line,column:t.column},arguments:[],isConstructor:1,start:e.start,end:this.previous().end,line:e.line,column:e.column}}parseTopLevelInitBlock(){const e=this.getPosition(),t=this.parseCommandBlock(["end"]);return this.consume("end","Expected 'end' after init block"),{type:"initBlock",commands:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseDefFeature(){const e=this.getPosition();let t="";if(!this.checkIdentifier())return this.addError("Expected function name after 'def'"),{type:"def",name:"",params:[],body:[],start:e.start,end:this.getPosition().end,line:e.line,column:e.column};for(t=this.advance().value;this.check(".");)this.advance(),this.checkIdentifier()&&(t+="."+this.advance().value);const r=[];if(this.check("(")){if(this.advance(),!this.check(")"))for(this.checkIdentifier()&&r.push(this.advance().value);this.check(",");)this.advance(),this.checkIdentifier()&&r.push(this.advance().value);this.consume(")","Expected ')' after parameter list")}const n=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:t,params:r,body:n,...void 0!==s&&{errorSymbol:s},...void 0!==i&&{errorHandler:i},...void 0!==o&&{finallyHandler:o},start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseEventNameWithNamespace(e){let t;t=this.checkEvent()||this.checkIdentifier()?this.advance():this.consumeEvent(e);let r=t.value;return this.check(":")&&(this.advance(),r=`${r}:${this.advance().value}`),r}parseEventHandler(){fe("🔧 parseEventHandler: ENTRY - parsing event handler");const e=[],t=this.parseEventNameWithNamespace("Expected event name after 'on'");for(e.push(t),fe("🔧 parseEventHandler: Parsed first event name: "+t);this.check("or");){this.advance(),fe("🔧 parseEventHandler: Found 'or', parsing additional event name");const t=this.parseEventNameWithNamespace("Expected event name after 'or'");e.push(t),fe("🔧 parseEventHandler: Parsed additional event name: "+t)}let r;if(fe("🔧 parseEventHandler: Total events parsed: "+e.join(", ")),this.registryIntegration){const t=e[0];if(this.registryIntegration.hasEventSource(t)){const e=this.registryIntegration.getEventSource(t);r=e?.name,fe(`🔧 parseEventHandler: Detected custom event source '${r}' for event '${t}'`)}}const n=[];if(this.match("(")){if(!this.check(")"))do{const e=this.advance();n.push(e.value)}while(this.match(","));this.consume(")","Expected ')' after event parameters"),fe("🔧 parseEventHandler: Parsed event parameters: "+n.join(", "))}const s={};for(;this.check(".");){this.advance();const e=this.advance().value.toLowerCase();if("once"===e)s.once=1,fe("🔧 parseEventHandler: Parsed modifier '.once'");else if("prevent"===e)s.prevent=1,fe("🔧 parseEventHandler: Parsed modifier '.prevent'");else if("stop"===e)s.stop=1,fe("🔧 parseEventHandler: Parsed modifier '.stop'");else if("debounce"===e||"throttle"===e){if(!this.check("("))throw Error(`Expected '(' after '.${e}'`);{this.advance();const t=this.advance(),r=parseInt(t.value,10);if(isNaN(r))throw Error(`Expected number for ${e} delay, got: ${t.value}`);"debounce"===e?(s.debounce=r,fe(`🔧 parseEventHandler: Parsed modifier '.debounce(${r})'`)):(s.throttle=r,fe(`🔧 parseEventHandler: Parsed modifier '.throttle(${r})'`)),this.consume(")",`Expected ')' after ${e} delay`)}}else fe(`🔧 parseEventHandler: Warning - unknown modifier '.${e}'`)}let i,o,a,c;if(Object.keys(s).length>0&&fe("🔧 parseEventHandler: Parsed modifiers:",s),this.match("[")&&(i=this.parseExpression(),this.consume("]","Expected ']' after event condition")),this.match("from")){const e=this.advance();o=e.value,fe(`🔧 parseEventHandler: Parsed 'from' target: ${o} (kind: ${e.kind})`)}if(this.match("of")){const e=this.advance();a=e.value.startsWith("@")?e.value.substring(1):e.value,fe("🔧 parseEventHandler: Parsed attribute name: "+a)}this.match("in")&&(fe("🔧 parseEventHandler: Found 'in' keyword, parsing watch target"),c=this.parseExpression(),fe("🔧 parseEventHandler: Parsed watch target expression"));const l=[];for(fe(`✅ parseEventHandler: About to parse commands, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd: ${this.isAtEnd()}`);!this.isAtEnd();){if(fe(`✅ parseEventHandler: Loop iteration, current token: ${this.peek().value}, kind: ${this.peek().kind}`),this.check("on")){fe("✅ parseEventHandler: Stopping command parsing, found next event handler 'on'");break}if(this.checkComment())fe("✅ parseEventHandler: Skipping comment token: "+this.peek().value),this.advance();else{if(this.check("end")){fe("✅ parseEventHandler: Stopping command parsing, found 'end' keyword"),this.advance();break}if(this.checkIsCommand()){const e="("===this.tokens[this.current+1]?.value,t=this.peek().value.toLowerCase();if(e&&"js"!==t&&"tell"!==t){let e;const t=this.error;try{e=this.parseExpression()}catch(e){this.error=t,this.advance();const r=this.parseCommand();l.push(r);continue}if(e&&"callExpression"===e.type){const t=e,r=t.callee.name,n=["from","on","with","into","at","to"],s=this.peek();if(n.includes(s.value.toLowerCase())||Re(s)&&!this.isCommand(s.value)||ke(s)){let s,i;this.isCommand(r)&&this.addWarning({type:"command-shadow",message:`Method '${r}' shadows hyperscript command`,suggestions:[`Rename method to avoid confusion (e.g., '${r}Fn', 'my${r.charAt(0).toUpperCase()+r.slice(1)}')`,`Use 'call' command instead: call ${r}(...)`,"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}}),n.includes(this.peek().value.toLowerCase())&&(s=this.advance().value.toLowerCase());try{i=this.parseExpression()}catch(n){const s={type:"command",name:r,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}};l.push(s);continue}const o={type:"command",name:"pseudo-command",args:[{type:"objectLiteral",properties:[{key:{type:"identifier",name:"methodName"},value:{type:"literal",value:r,raw:`"${r}"`}},{key:{type:"identifier",name:"methodArgs"},value:{type:"literal",value:t.arguments,raw:JSON.stringify(t.arguments)}},...s?[{key:{type:"identifier",name:"preposition"},value:{type:"literal",value:s,raw:`"${s}"`}}]:[],{key:{type:"identifier",name:"targetExpression"},value:i}]}],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}};l.push(o);continue}}if(e&&"callExpression"===e.type){const t={type:"command",name:e.callee.name,args:e.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}};l.push(t)}}else{this.advance();const e=this.error;try{const t=this.parseCommand();this.error&&this.error!==e&&(fe("⚠️ Command parsing added error, restoring error state. Error was:",this.error.message),this.error=e),l.push(t),fe("✅ parseEventHandler: Parsed command, next token: "+(this.isAtEnd()?"END":this.peek().value))}catch(t){fe("⚠️ Command parsing threw exception, restoring error state:",t instanceof Error?t.message:t+""),this.error=e}}}else{if(!this.checkIdentifier())break;{const e=this.peek();if(this.isCommand(e.value)){this.advance();const e=this.error;try{const t=this.parseCommand();this.error&&this.error!==e&&(fe("⚠️ Command parsing added error, restoring error state. Error was:",this.error.message),this.error=e),l.push(t)}catch(t){fe("⚠️ Command parsing threw exception, restoring error state:",t instanceof Error?t.message:t+""),this.error=e}}else{let e;const t=this.error;try{e=this.parseExpression()}catch(e){fe("⚠️ Expression parsing error, restoring error state:",e instanceof Error?e.message:e+""),this.error=t;break}if(e&&"callExpression"===e.type){const t=e,r=t.callee.name,n=["from","on","with","into","at","to"],s=this.peek();if(n.includes(s.value.toLowerCase())||Re(s)&&!this.isCommand(s.value)||ke(s)){let s,i;this.isCommand(r)&&this.addWarning({type:"command-shadow",message:`Method '${r}' shadows hyperscript command`,suggestions:[`Rename method to avoid confusion (e.g., '${r}Fn', 'my${r.charAt(0).toUpperCase()+r.slice(1)}')`,`Use 'call' command instead: call ${r}(...)`,"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}}),n.includes(this.peek().value.toLowerCase())&&(s=this.advance().value.toLowerCase());try{i=this.parseExpression()}catch(n){const s={type:"command",name:r,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}};l.push(s);continue}const o={type:"command",name:"pseudo-command",args:[{type:"objectLiteral",properties:[{key:{type:"identifier",name:"methodName"},value:{type:"literal",value:r,raw:`"${r}"`}},{key:{type:"identifier",name:"methodArgs"},value:{type:"literal",value:t.arguments,raw:JSON.stringify(t.arguments)}},...s?[{key:{type:"identifier",name:"preposition"},value:{type:"literal",value:s,raw:`"${s}"`}}]:[],{key:{type:"identifier",name:"targetExpression"},value:i}]}],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}};l.push(o)}else{const n={type:"command",name:r,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}};l.push(n)}}else{if(!e||"binaryExpression"!==e.type||" "!==e.operator)break;{const t=e;if(!t.left||"identifier"!==t.left.type||!this.isCommand(t.left.name))break;{const r={type:"command",name:t.left.name,args:[t.right],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}};l.push(r)}}}}}}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 u=this.getPosition(),h={type:"eventHandler",event:1===e.length?e[0]:e.join("|"),events:e,commands:l,...n.length>0&&{params:n},...i&&{condition:i},...o&&{target:o},...a&&{attributeName:a},...c&&{watchTarget:c},...r&&{customEventSource:r},...Object.keys(s).length>0&&{modifiers:s},start:u.start,end:u.end,line:u.line,column:u.column};return fe(`🔧 parseEventHandler: Created node with events: ${e.join(", ")}, attributeName: ${a||"none"}, watchTarget: ${c?"yes":"none"}`),h}parseBehaviorDefinition(){const e=this.getPosition(),t=this.consumeIdentifier("Expected behavior name after 'behavior' keyword").value;/^[A-Z]/.test(t)||this.addError(`Behavior name must start with uppercase letter (got "${t}")`);const r=[];if(this.match("(")){if(!this.check(")"))do{const e=this.consumeIdentifierLike("Expected parameter name");r.push(e.value)}while(this.match(","));this.consume(")","Expected ')' after behavior parameters")}const n=new Set(r),s=[];let i;for(;!this.isAtEnd()&&!this.check("end");)if(this.match("on")){const e=this.getPosition(),t=this.peek().value;this.advance();const r=[];if(this.check("(")){for(this.advance();!this.isAtEnd()&&!this.check(")");){const e=this.peek();Re(e)?(r.push(e.value),this.advance(),this.check(",")&&this.advance()):this.advance()}this.check(")")&&this.advance()}let i;if(this.check("from")){this.advance();const e=[];if(this.check("the")&&this.advance(),!this.isAtEnd()){const t=this.peek(),r=n.has(t.value);this.checkIsCommand()&&!r||(e.push(t.value),i=t.value,this.advance())}}const o=[];for(;!this.isAtEnd()&&!this.check("end");){if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){this.check("end")||this.addError("Unexpected token in event handler: "+this.peek().value);break}{this.advance();const e=this.error;try{const t=this.parseCommand();for(this.error&&this.error!==e&&(this.error=e),o.push(t);!(this.isAtEnd()||this.check("end")||this.checkIsCommand()||this.isCommand(this.peek().value));)this.advance()}catch(t){this.error=e;break}}}const a={type:"eventHandler",event:t,commands:o,...void 0!==i&&{target:i},...r.length>0&&{args:r},start:e.start,end:this.getPosition().end,line:e.line,column:e.column};s.push(a),this.consume("end","Expected 'end' after event handler body")}else{if(!this.match("init")){this.addError("Unexpected token in behavior body: "+this.peek().value);break}i={type:"initBlock",commands:this.parseCommandBlock(["end"]),start:e.start,end:this.getPosition().end,line:e.line,column:e.column},this.consume("end","Expected 'end' after init block")}return this.consume("end","Expected 'end' to close behavior definition"),{type:"behavior",name:t,parameters:r,eventHandlers:s,...void 0!==i?{initBlock:i}:{},start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseCommandSequence(){const e=[];for(;!this.isAtEnd();){if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){this.advance();const t=this.error,r=this.parseCommand();for(this.error&&this.error!==t&&(this.error.message.includes("Expected closing parenthesis")||this.error.message.includes("Expected ')'")||this.error.message.includes("unclosed parenthes")||this.error.message.includes("Unclosed parenthes")||(fe("⚠️ parseCommandSequence: Command parsing added non-critical error, restoring error state. Error was:",this.error.message),this.error=t)),e.push(r);!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("on"));)fe("⚠️ parseCommandSequence: Skipping unexpected token:",this.peek().value),this.advance();if(this.check("on")){fe('✅ 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}this.addError("Expected command, got: "+this.peek().value);break}return 1===e.length?e[0]:{type:"CommandSequence",commands:e,start:e[0]?.start||0,end:e[e.length-1]?.end||0,line:e[0]?.line||1,column:e[0]?.column||1}}getMultiWordPattern(e){return function(e){return ze.find(t=>t.command===e.toLowerCase())||null}(e)}isTokenKeyword(e,t){return Je(e,t)}parseMultiWordCommand(e,t){return function(e,t,r){const n=e.getMultiWordPattern(r);if(!n)return null;const s=[],i={};for(;!Ge(e,["catch","finally",...n.keywords])&&!Je(e.peek(),n.keywords);){const t=e.parsePrimary();if(!t)break;if(s.push(t),!e.match(",")&&Je(e.peek(),n.keywords))break}for(;!e.isAtEnd()&&Je(e.peek(),n.keywords);){const t=e.advance().value,r=e.parseExpression();if(r&&(i[t]=r),!Je(e.peek(),n.keywords))break}const o=Qe.from(t).withArgs(...s).endingAt(e.getPosition());return Object.keys(i).length>0&&o.withModifiers(i),o.build()}(this.getContext(),e,t)}parseCommandBlock(e){const t=[];for(;!this.isAtEnd()&&!e.some(e=>this.check(e));)if(this.checkComment())this.advance();else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value))break;{this.advance();const e=this.parseCommand();t.push(e)}}return t}trySemanticParse(e){if(!this.semanticAdapter||!this.semanticAdapter.isAvailable())return null;try{const t=this.semanticAdapter.trySemanticParse(e);return t.success&&t.node?(fe(`[Semantic] Successfully parsed with confidence ${t.confidence}:`,t.node.name),t.node):(fe(`[Semantic] Low confidence (${t.confidence}), falling back to traditional parser`),null)}catch(e){return fe("[Semantic] Error during semantic parse:",e),null}}getRemainingInput(){if(!this.originalInput)return this.tokens.slice(this.current>0?this.current-1:0).map(e=>e.value).join(" ");const e=this.current>0?this.tokens[this.current-1]:this.tokens[0];return e&&void 0!==e.start?this.originalInput.slice(e.start):this.originalInput}skipToCommandBoundary(){const e=["then","and","else","end"];for(;!this.isAtEnd();){const t=this.peek(),r=t.value.toLowerCase();if(e.includes(r))break;if(Ee(t))break;this.advance()}}parseCommand(){const e=this.previous();let t=e.value;if(this.semanticAdapter&&!["install","wait","repeat","for","set","put","add","if","unless","make","measure","trigger","halt","remove","exit","return","closest","js","tell"].includes(t.toLowerCase())){const e=this.getRemainingInput(),t=this.trySemanticParse(e);if(t)return this.skipToCommandBoundary(),t}"beep"===t&&this.check("!")&&(this.advance(),t="beep!");const r=this.parseMultiWordCommand(e,t);if(r)return r;const n=t.toLowerCase();if("repeat"===n)return this.parseRepeatCommand(e);if("for"===n)return this.parseForCommand(e);if("if"===n||"unless"===n)return this.parseIfCommand(e);if("wait"===n)return this.parseWaitCommand(e);if("install"===n)return this.parseInstallCommand(e);if("transition"===n)return this.parseTransitionCommand(e);if("add"===n)return this.parseAddCommand(e);if(this.isCompoundCommand(n))return this.parseCompoundCommand({type:"identifier",name:n,start:e.start||0,end:e.end||0,line:e.line,column:e.column})||this.createErrorNode();const s=[];if(("increment"===t||"decrement"===t)&&!this.isAtEnd())return function(e,t){const r=t.value,n="increment"===r?"+":"-";let s=0;e.check(g)&&(s=1,e.advance());const i=e.parseExpression();if(!i)throw Error("Expected variable or expression after "+r);let o;if(e.check("by")){e.advance();const t=e.parseExpression();if(!t)throw Error(`Expected amount after 'by' in ${r} command`);o=t}else o=Ue(1,"1",{start:t.start,end:e.previous().end,line:t.line,column:t.column});let a=i;s&&"identifier"===i.type&&(a={...i,scope:"global"});const c={start:t.start,end:e.previous().end,line:t.line,column:t.column},l=We(n,i,o,c);return{type:"command",name:"set",args:[a,He(h,c),l],isBlocking:0,start:t.start,end:e.previous().end,line:t.line,column:t.column,originalCommand:r}}(this.getContext(),e);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.check("end")||this.checkIsCommand());){const e=this.parseExpression();if(s.push(e||this.parsePrimary()),this.match(","))continue;const t=["into","from","to","with","by","at","before","after","over"];if(t.some(e=>this.check(e)))continue;const r=s[s.length-1];if(!r||"identifier"!==r.type&&"keyword"!==r.type||!t.includes(r.name||r.value))break}const i=this.getPosition();return{type:"command",name:t,args:s,isBlocking:0,start:i.start,end:i.end,line:i.line,column:i.column}}parseConditional(){const e=this.parseExpression();this.consume("then","Expected 'then' after if condition");const t=this.parseConditionalBranch();let r;this.match("else")&&(r=this.parseConditionalBranch());const n=this.getPosition();return{type:"conditionalExpression",test:e,consequent:t,alternate:r,start:n.start,end:n.end,line:n.line,column:n.column}}parseConditionalBranch(){if(this.checkIsCommand()){const e=this.advance(),t=this.createIdentifier(e.value);return this.createCommandFromIdentifier(t)||t}if(this.checkIdentifier()||this.checkKeyword()){const e=this.peek();if(this.isCommand(e.value)){const e=this.advance(),t=this.createIdentifier(e.value);return this.createCommandFromIdentifier(t)||t}}return this.parseExpression()}parseNavigationFunction(e){const t=[];if(this.match("of"))t.push(this.parseExpression());else{if(this.check("("))return this.finishCall(this.createIdentifier(e));this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||t.push(this.parsePrimary())}return this.createCallExpression(this.createIdentifier(e),t)}parseTheXofY(){if(!this.checkIdentifier())return this.createIdentifier("the");const e=this.peek(),t=e.value;if(["first","last","next","previous","random","closest"].includes(t))return this.advance(),this.parseNavigationFunction(t);const r=this.current;return this.advance(),this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:t},target:this.parsePrimary(),line:e.line,column:e.column}):(this.current=r,this.createIdentifier("the"))}parseContextPropertyAccess(e){if("me"===e&&this.match("*")){let t="";if(!this.checkIdentifier())return this.addError("Expected property name after 'my *'"),this.createMemberExpression(this.createIdentifier(e),this.createIdentifier(""),0);for(t=this.advance().value;this.check("-")&&!this.isAtEnd();){if(t+="-",this.advance(),!this.checkIdentifier()){this.addError("Expected identifier after hyphen in CSS property name");break}t+=this.advance().value}const r="computed-"+t;return this.createMemberExpression(this.createIdentifier(e),this.createIdentifier(r),0)}{const t=this.consumeIdentifier(`Expected property name after '${{me:"my",it:"its",you:"your"}[e]}'`);return this.createMemberExpression(this.createIdentifier(e),this.createIdentifier(t.value),0)}}parseMyPropertyAccess(){return this.parseContextPropertyAccess("me")}finishCall(e){const t=[];if(!this.check(")"))do{if(this.check(","))return this.addError("Unexpected token in function arguments"),this.createCallExpression(e,[this.createErrorNode()]);t.push(this.parseExpression())}while(this.match(","));if(!this.check(")")&&"identifier"===e.type){const t=e.name;T.has(t.toLowerCase())&&fe(`💡 Tip: CSS functions like ${t}() should be quoted for clean parsing. Use '${t}(...)' or \`${t}(...)\` instead.`)}return this.consume(")","Expected ')' after arguments"),this.createCallExpression(e,t)}createLiteral(e,t){return Ue(e,t,this.getPosition())}createIdentifier(e){return He(e,this.getPosition())}createBinaryExpression(e,t,r){return We(e,t,r,this.getPosition())}createUnaryExpression(e,t,r){return function(e,t,r,n){return{type:"unaryExpression",operator:e,argument:t,prefix:r,start:n.start,end:n.end,line:n.line,column:n.column}}(e,t,r,this.getPosition())}createCallExpression(e,t){return function(e,t,r){return{type:"callExpression",callee:e,arguments:t,start:r.start,end:r.end,line:r.line,column:r.column}}(e,t,this.getPosition())}createMemberExpression(e,t,r){return function(e,t,r,n){return{type:"memberExpression",object:e,property:t,computed:r,start:n.start,end:n.end,line:n.line,column:n.column}}(e,t,r,this.getPosition())}createSelector(e){return function(e,t){return{type:"selector",value:e,start:t.start,end:t.end,line:t.line,column:t.column}}(e,this.getPosition())}createPossessiveExpression(e,t){return function(e,t,r){return{type:"possessiveExpression",object:e,property:t,start:r.start,end:r.end,line:r.line,column:r.column}}(e,t,this.getPosition())}createErrorNode(){return{type:"identifier",name:"__ERROR__",start:(e=this.getPosition()).start,end:e.end,line:e.line,column:e.column};var e}processEscapeSequences(e){return e.replace(/\\(.)/g,(e,t)=>{switch(t){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 t}})}createProgramNode(e){return function(e){if(fe(`✅ createProgramNode: Called with ${e.length} statements`),0===e.length)return fe("✅ createProgramNode: Returning error node (0 statements)"),{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===e.length)return fe(`✅ createProgramNode: Returning single statement (type=${e[0].type})`),e[0];const t={type:"Program",statements:e,start:e[0]?.start||0,end:e[e.length-1]?.end||0,line:e[0]?.line||1,column:e[0]?.column||1};return fe(`✅ createProgramNode: Returning Program node with ${e.length} statements, type=${t.type}`),t}(e)}match(...e){for(const t of e)if(this.check(t))return this.advance(),1;return 0}matchOperator(e){if(this.isAtEnd())return 0;const t=this.peek();return Fe(t)&&t.value===e?(this.advance(),1):0}check(e){if(this.isAtEnd())return 0;const t=this.peek().value;return this.resolveKeyword(t)===e}checkPredicate(e){return this.isAtEnd()?0:e(this.peek())}matchPredicate(e){return this.checkPredicate(e)?(this.advance(),1):0}checkSelector(){return this.checkPredicate(Te)}matchSelector(){return this.matchPredicate(Te)}checkAnySelector(){return this.checkPredicate(Ce)}checkLiteral(){return this.checkPredicate(Ne)}checkIdentifierLike(){return this.checkPredicate(Se)}checkIsCommand(){return this.checkPredicate(Ee)}checkCommandTerminator(){return this.checkPredicate(qe)}checkReference(){return this.checkPredicate(Oe)}checkTimeExpression(){return this.checkPredicate(Le)}checkEvent(){return this.checkPredicate(xe)}checkContextVar(){return this.checkPredicate(ke)}checkComment(){return this.checkPredicate($e)}checkIdentifier(){return this.checkPredicate(Re)}checkKeyword(){return this.checkPredicate(we)}checkString(){return this.checkPredicate(Ie)}matchString(){return this.matchPredicate(Ie)}checkNumber(){return this.checkPredicate(je)}matchNumber(){return this.matchPredicate(je)}checkBoolean(){return this.checkPredicate(Me)}matchBoolean(){return this.matchPredicate(Me)}checkTemplateLiteral(){return this.checkPredicate(De)}matchTemplateLiteral(){return this.matchPredicate(De)}checkQueryReference(){return this.checkPredicate(Ve)}matchQueryReference(){return this.matchPredicate(Ve)}checkIdSelector(){return this.checkPredicate(Be)}checkClassSelector(){return this.checkPredicate(Pe)}checkCssSelector(){return this.checkPredicate(_e)}checkBasicOperator(){return this.checkPredicate(Fe)}matchBasicOperator(){return this.matchPredicate(Fe)}matchTimeExpression(){return this.matchPredicate(Le)}matchIdentifierLike(){return this.matchPredicate(Se)}matchComparisonOperator(){return this.matchPredicate(Ae)}consumePredicate(e,t){return this.checkPredicate(e)?this.advance():(this.addError(t),this.peek())}consumeIdentifier(e){return this.consumePredicate(Re,e)}consumeIdentifierLike(e){return this.consumePredicate(Se,e)}consumeEvent(e){return this.consumePredicate(xe,e)}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(e,t){return this.check(e)?this.advance():(this.addError(t),this.peek())}addError(e){const t=this.peek();let r=t.start||0,n=t.line||1,s=t.column||1;if(e.includes("property name after '.'")){const e=this.current>0?this.previous():t;r=e.end||e.start||0,n=e.line||1,s=e.column||1}if(e.includes("parenthes")){const e=this.current>0?this.previous():t;r=e.end||e.start||0,n=e.line||1,s=e.column||1,0===r&&this.current>0&&(r=this.current)}if(e.includes("Expected expression after")){const e=this.current>0?this.previous():t;r=e.start||0,n=e.line||1,s=e.column||1,0===r&&(r=Math.max(1,this.current-1))}if(e.includes("Missing operand")){let e=t;for(let t=this.current-1;t>=0;t--){const r=this.tokens[t];if(r&&("+"===r.value||"-"===r.value)){e=r;break}}r=e.start||0,n=e.line||1,s=e.column||1}this.error={message:e,line:Math.max(1,n),column:Math.max(1,s),position:Math.max(0,r)}}parseAttributeOrArrayLiteral(){const e=this.previous().start,t=this.previous().line,r=this.previous().column;if(!this.isAtEnd()&&this.peek().value.startsWith("@")){const n=[];for(;!this.check("]")&&!this.isAtEnd();){const e=this.advance();n.push(e.value)}this.consume("]","Expected ']' after attribute literal");const s="["+n.join("")+"]";return{type:"literal",value:s,raw:s,start:e,end:this.previous().end,line:t,column:r}}const n=[];if(!this.check("]"))do{if(this.check("]"))break;n.push(this.parseExpression())}while(this.match(","));return this.consume("]","Expected ']' after array elements"),{type:"arrayLiteral",elements:n,start:e,end:this.previous().end,line:t,column:r}}getPosition(){const e=this.current>0?this.previous():this.peek();return{start:e.start||0,end:e.end||0,line:e.line||1,column:e.column||1}}getContext(){const e=this,t={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),createLiteral:this.createLiteral.bind(this),createSelector:this.createSelector.bind(this),createBinaryExpression:this.createBinaryExpression.bind(this),createUnaryExpression:this.createUnaryExpression.bind(this),createMemberExpression:this.createMemberExpression.bind(this),createPossessiveExpression:this.createPossessiveExpression.bind(this),createCallExpression:this.createCallExpression.bind(this),createErrorNode:this.createErrorNode.bind(this),createProgramNode:this.createProgramNode.bind(this),createCommandFromIdentifier:this.createCommandFromIdentifier.bind(this),parseExpression:this.parseExpression.bind(this),parsePrimary:this.parsePrimary.bind(this),parseCall:this.parseCall.bind(this),parseAssignment:this.parseAssignment.bind(this),parseLogicalOr:this.parseLogicalOr.bind(this),parseLogicalAnd:this.parseLogicalAnd.bind(this),parseEquality:this.parseEquality.bind(this),parseComparison:this.parseComparison.bind(this),parseAddition:this.parseAddition.bind(this),parseMultiplication:this.parseMultiplication.bind(this),parseImplicitBinary:this.parseImplicitBinary.bind(this),parseConditional:this.parseConditional.bind(this),parseConditionalBranch:this.parseConditionalBranch.bind(this),parseEventHandler:this.parseEventHandler.bind(this),parseBehaviorDefinition:this.parseBehaviorDefinition.bind(this),parseNavigationFunction:this.parseNavigationFunction.bind(this),parseMyPropertyAccess:this.parseMyPropertyAccess.bind(this),parseDollarExpression:this.parseDollarExpression.bind(this),parseHyperscriptSelector:this.parseHyperscriptSelector.bind(this),parseAttributeOrArrayLiteral:this.parseAttributeOrArrayLiteral.bind(this),parseObjectLiteral:this.parseObjectLiteral.bind(this),parseCSSObjectLiteral:this.parseCSSObjectLiteral.bind(this),parseCommand:this.parseCommand.bind(this),parseCommandSequence:this.parseCommandSequence.bind(this),parseCommandListUntilEnd:this.parseCommandListUntilEnd.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),getInputSlice:(e,t)=>this.originalInput?0>e||e>=this.originalInput.length?"":void 0!==t?this.originalInput.slice(e,t):this.originalInput.slice(e):""};return Object.defineProperty(t,"current",{get:()=>e.current,set:t=>{e.current=t},enumerable:1,configurable:1}),t}}function ht(e,t){const r=function(e){const t={input:"",position:0,line:1,column:1,tokens:[]};t.input=e;const r=e.length;for(;r>t.position&&(F(t),r>t.position);){const r=e[t.position];if("-"!==r||"-"!==P(t,1))if('"'!==r){if("'"===r||"'"===r){const e=P(t,1),r=t.tokens[t.tokens.length-1];if("s"!==e||!r||r.kind!==I.IDENTIFIER&&r.kind!==I.SELECTOR&&"]"!==r.value&&")"!==r.value&&"}"!==r.value)W(t);else{const e=t.position;_(t),_(t),q(t,j.OPERATOR,"'s",e)}continue}if("`"!==r)if("<"!==r)if("#"!==r){if("."===r){if("."===P(t,1)){const e=t.position;_(t),_(t),q(t,j.OPERATOR,"..",e);continue}const e=t.tokens[t.tokens.length-1],r=new Set(["from","to","into","on","in","at"]),n=e&&e.kind===I.IDENTIFIER&&w.has(e.value.toLowerCase()),s=e&&e.kind===I.IDENTIFIER&&r.has(e.value.toLowerCase());if((!e||e.kind===I.OPERATOR&&")"!==e.value&&"]"!==e.value||n||s||"("===e.value||"["===e.value||"{"===e.value||","===e.value||";"===e.value)&&ee(P(t))){J(t);continue}}if("@"!==r)if("{"!==r)if("}"!==r){if("["===r){const e=t.tokens[t.tokens.length-1],r=e&&(e.kind===j.EVENT||e.kind===j.IDENTIFIER&&$.has(e.value))&&t.tokens.length>=2&&"on"===t.tokens[t.tokens.length-2]?.value;(!e||e.kind!==j.IDENTIFIER&&e.kind!==j.CONTEXT_VAR&&")"!==e.value&&"]"!==e.value||r)&&r?(q(t,j.SYMBOL,"["),_(t)):(q(t,j.OPERATOR,"["),_(t));continue}if("]"!==r){if("$"===r){const e=P(t,1);if(e>="a"&&"z">=e||e>="A"&&"Z">=e||"_"===e){Q(t);continue}}ne(r)?Y(t):"0">r||r>"9"?("a">r||r>"z")&&("A">r||r>"Z")&&"_"!==r?(q(t,j.UNKNOWN,r),_(t)):K(t):X(t)}else q(t,j.OPERATOR,"]"),_(t)}else q(t,j.OPERATOR,"}"),_(t);else q(t,j.OPERATOR,"{"),_(t);else G(t)}else J(t);else re(t)?Z(t):Y(t);else z(t)}else W(t);else H(t)}return t.tokens}(e);return new ut(r,t,e).parse()}ut.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty"]);class ft{constructor(){this.hooks=new Map,this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}register(e,t){this.unregister(e),this.hooks.set(e,t),t.beforeExecute&&this.beforeExecuteHooks.push(t.beforeExecute),t.afterExecute&&this.afterExecuteHooks.push(t.afterExecute),t.onError&&this.onErrorHooks.push(t.onError),t.interceptCommand&&this.interceptCommandHooks.push(t.interceptCommand)}unregister(e){const t=this.hooks.get(e);if(!t)return 0;if(t.beforeExecute){const e=this.beforeExecuteHooks.indexOf(t.beforeExecute);e>-1&&this.beforeExecuteHooks.splice(e,1)}if(t.afterExecute){const e=this.afterExecuteHooks.indexOf(t.afterExecute);e>-1&&this.afterExecuteHooks.splice(e,1)}if(t.onError){const e=this.onErrorHooks.indexOf(t.onError);e>-1&&this.onErrorHooks.splice(e,1)}if(t.interceptCommand){const e=this.interceptCommandHooks.indexOf(t.interceptCommand);e>-1&&this.interceptCommandHooks.splice(e,1)}return this.hooks.delete(e)}has(e){return this.hooks.has(e)}async runBeforeExecute(e){for(const t of this.beforeExecuteHooks)await t(e)}async runAfterExecute(e,t){for(const r of this.afterExecuteHooks)await r(e,t)}async runOnError(e,t){let r=t;for(const t of this.onErrorHooks){const n=await t(e,r);n instanceof Error&&(r=n)}return r}shouldIntercept(e,t){for(const r of this.interceptCommandHooks)if(r(e,t))return 1;return 0}getRegisteredNames(){return Array.from(this.hooks.keys())}clear(){this.hooks.clear(),this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}}function dt(e){return{ok:1,value:e}}function pt(e){return{ok:0,error:e}}function mt(e){return 1==e.ok}class yt{constructor(e){this.elementCleanups=new WeakMap,this.trackedElements=new Set,this.globalCleanups=[],this.debugMode=e?.debug??0}registerListener(e,t,r,n,s){this.addCleanup(e,{type:"listener",target:t,eventName:r,cleanup:()=>{t.removeEventListener(r,n,s),this.debugMode&&me(`CleanupRegistry: Removed listener '${r}'`)},description:r+" listener"})}registerObserver(e,t){this.addCleanup(e,{type:"observer",cleanup:()=>{t.disconnect(),this.debugMode&&me("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(e,t){this.addCleanup(e,{type:"interval",cleanup:()=>{clearInterval(t),this.debugMode&&me("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(e,t){this.addCleanup(e,{type:"timeout",cleanup:()=>{clearTimeout(t),this.debugMode&&me("CleanupRegistry: Cleared timeout")},description:"Timeout"})}registerCustom(e,t,r){this.addCleanup(e,{type:"custom",cleanup:t,description:r||"Custom cleanup"})}registerGlobal(e,t="custom",r){this.globalCleanups.push({type:t,cleanup:e,description:r||"Global cleanup"}),this.debugMode&&me("CleanupRegistry: Registered global cleanup: "+(r||t))}addCleanup(e,t){const r=this.elementCleanups.get(e)||[];r.push(t),this.elementCleanups.set(e,r),this.trackedElements.add(e),this.debugMode&&me(`CleanupRegistry: Registered ${t.type} for element`,e)}cleanupElement(e){const t=this.elementCleanups.get(e);if(!t||0===t.length)return 0;let r=0;for(const e of t)try{e.cleanup(),r++}catch(e){this.debugMode&&me("CleanupRegistry: Error during cleanup:",e)}return this.elementCleanups.delete(e),this.trackedElements.delete(e),this.debugMode&&me(`CleanupRegistry: Cleaned up ${r} resources for element`),r}cleanupElementTree(e){let t=this.cleanupElement(e);const r=e.querySelectorAll("*");for(const e of r)t+=this.cleanupElement(e);return t}cleanupGlobal(){let e=0;for(const t of this.globalCleanups)try{t.cleanup(),e++}catch(e){this.debugMode&&me("CleanupRegistry: Error during global cleanup:",e)}return this.globalCleanups=[],this.debugMode&&me(`CleanupRegistry: Cleaned up ${e} global resources`),e}cleanupAll(){return this.cleanupGlobal()}hasCleanups(e){const t=this.elementCleanups.get(e);return void 0!==t&&t.length>0}getCleanupCount(e){const t=this.elementCleanups.get(e);return t?.length??0}getStats(){let e=0,t=0,r=0,n=0,s=0;for(const i of this.trackedElements){const o=this.elementCleanups.get(i);if(o)for(const i of o)switch(i.type){case"listener":e++;break;case"observer":t++;break;case"interval":r++;break;case"timeout":n++;break;case"custom":s++}}for(const i of this.globalCleanups)switch(i.type){case"listener":e++;break;case"observer":t++;break;case"interval":r++;break;case"timeout":n++;break;case"custom":s++}return{elementsTracked:this.trackedElements.size,listeners:e,observers:t,intervals:r,timeouts:n,custom:s,global:this.globalCleanups.length}}setDebugMode(e){this.debugMode=e}}const vt=new Map;function gt(e,t){return{me:e||null,it:null,you:null,result:null,locals:new Map,globals:t||vt,flags:{halted:0,breaking:0,continuing:0,returning:0,async:0}}}class bt{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(e,t){const r=e.toLowerCase();this.sources.has(r)&&console.warn("[EventSourceRegistry] Overwriting existing event source: "+e),this.sources.set(r,t)}unregister(e){const t=e.toLowerCase(),r=this.sources.get(t);if(r){for(const[e,r]of this.subscriptions.entries())r.source===t&&(r.unsubscribe(),this.subscriptions.delete(e));return r.destroy?.(),this.sources.delete(t)}return 0}get(e){return this.sources.get(e.toLowerCase())}has(e){return this.sources.has(e.toLowerCase())}subscribe(e,t,r){const n=this.get(e);if(!n)return void console.warn("[EventSourceRegistry] Unknown event source: "+e);n.initialize?.();const s=n.subscribe(t,r);return this.subscriptions.set(s.id,s),s}unsubscribe(e){const t=this.subscriptions.get(e);return t?(t.unsubscribe(),this.subscriptions.delete(e)):0}getSourceNames(){return Array.from(this.sources.keys())}getSubscriptions(){return Array.from(this.subscriptions.values())}findSourceForEvent(e){for(const[t,r]of this.sources.entries())if(r.supports?.(e)??r.supportedEvents?.includes(e))return t}generateId(){return`sub_${this.nextId++}_${Date.now().toString(36)}`}destroy(){for(const e of this.subscriptions.values())e.unsubscribe();this.subscriptions.clear();for(const e of this.sources.values())e.destroy?.();this.sources.clear()}}class Et{constructor(){this.providers=new Map,this.globalProviders=new Map}register(e,t,r){const n=e.toLowerCase();this.providers.set(n,"function"==typeof t?{name:n,provide:t,cache:r?.cache??1,description:r?.description,dependencies:r?.dependencies}:t)}registerGlobal(e,t,r){const n=e.toLowerCase();this.globalProviders.set(n,"function"==typeof t?{name:n,provide:t,cache:r?.cache??1,description:r?.description,dependencies:r?.dependencies}:t)}unregister(e){return this.providers.delete(e.toLowerCase())}unregisterGlobal(e){return this.globalProviders.delete(e.toLowerCase())}get(e){const t=e.toLowerCase();return this.providers.get(t)??this.globalProviders.get(t)}has(e){const t=e.toLowerCase();return this.providers.has(t)||this.globalProviders.has(t)}async resolve(e,t,r){const n=this.get(e);if(!n)return;const s="__provider_"+n.name;if(n.cache&&r?.has(s))return r.get(s);if(n.dependencies)for(const e of n.dependencies)await this.resolve(e,t,r);const i=await n.provide(t);return n.cache&&r&&r.set(s,i),i}resolveSync(e,t,r){const n=this.get(e);if(!n)return;const s="__provider_"+n.name;if(n.cache&&r?.has(s))return r.get(s);const i=n.provide(t);if(i instanceof Promise)throw Error(`Context provider '${e}' is async. Use resolve() instead of resolveSync().`);return n.cache&&r&&r.set(s,i),i}enhance(e){const t=this,r=new Map;return new Proxy(e,{get(e,n,s){if("string"==typeof n&&t.get(n))try{return t.resolveSync(n,e,r)}catch{return t.resolve(n,e,r)}return Reflect.get(e,n,s)},has:(e,r)=>"string"==typeof r&&t.has(r)?1:Reflect.has(e,r)})}async resolveAll(e){const t=new Map,r={},n=[...this.globalProviders.entries(),...this.providers.entries()];for(const[s,i]of n)try{r[s]=await this.resolve(s,e,t)}catch(e){console.warn(`[ContextProviderRegistry] Failed to resolve '${s}':`,e),r[s]=void 0}return r}getProviderNames(){return[...new Set([...this.globalProviders.keys(),...this.providers.keys()])]}clear(){this.providers.clear(),this.globalProviders.clear()}}const wt=new class{constructor(e={}){this.types=new Map,this.coercionCache=new Map,this.config={strictMode:0,cacheCoercions:1,...e},this.registerBuiltinTypes()}register(e){this.types.has(e.name)&&console.warn(`ExpressionTypeRegistry: Overwriting existing type '${e.name}'`),this.types.set(e.name,e)}get(e){return this.types.get(e)}has(e){return this.types.has(e)}getTypeNames(){return Array.from(this.types.keys())}inferType(e){for(const[t,r]of this.types)if(r.isType(e))return t;return"Unknown"}getHyperScriptType(e){const t=this.inferType(e),r=this.types.get(t);return r?.hyperscriptType??"unknown"}coerce(e,t,r){const n=this.types.get(t);if(!n){if(this.config.strictMode)throw Error("Unknown target type: "+t);return null}if(n.isType(e))return e;if(this.config.cacheCoercions){const r=`${this.inferType(e)}:${t}:${JSON.stringify(e)}`;if(this.coercionCache.has(r))return this.coercionCache.get(r)}const s=this.inferType(e),i=n.coerceFrom?.[s];if(i){const n=i(e,r);if(this.config.cacheCoercions&&null!==n){const r=`${s}:${t}:${JSON.stringify(e)}`;this.coercionCache.set(r,n)}return n}return n.defaultValue}canCoerce(e,t){const r=this.types.get(t);if(!r)return 0;if(r.isType(e))return 1;const n=this.inferType(e);return void 0!==r.coerceFrom?.[n]}getCoercionInfo(e,t){const r=this.types.get(t);return r&&(e===t||r.coerceFrom?.[e])?{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:e=>"string"==typeof e,defaultValue:"",description:"Text string value",examples:["hello","world",""],coerceFrom:{Number:e=>e+"",Boolean:e=>e+"",Null:()=>"",Undefined:()=>"",Array:e=>Array.isArray(e)?e.join(", "):null,Object:e=>{try{return JSON.stringify(e)}catch{return e+""}},Element:e=>e instanceof Element?e.textContent??e.outerHTML:null}}),this.register({name:"Number",hyperscriptType:"number",tsType:"number",isType:e=>"number"==typeof e&&!isNaN(e),defaultValue:0,description:"Numeric value (integer or float)",examples:[0,1,3.14,-42],coerceFrom:{String:e=>{const t=parseFloat(e);return isNaN(t)?null:t},Boolean:e=>e?1:0,Null:()=>0,Undefined:()=>null}}),this.register({name:"Boolean",hyperscriptType:"boolean",tsType:"boolean",isType:e=>"boolean"==typeof e,defaultValue:0,description:"True or false value",examples:[1,0],coerceFrom:{String:e=>{const t=e.toLowerCase().trim();return"true"===t||"yes"===t||"1"===t?1:"false"===t||"no"===t||"0"===t||""===t?0:t.length>0},Number:e=>0!==e,Null:()=>0,Undefined:()=>0,Array:e=>Array.isArray(e)?e.length>0:0,Element:e=>e instanceof Element,ElementList:e=>Array.isArray(e)&&e.length>0}}),this.register({name:"Element",hyperscriptType:"element",tsType:"Element | HTMLElement",isType:e=>e instanceof Element,defaultValue:null,description:"DOM Element",coerceFrom:{String:(e,t)=>{const r=e;if(r.startsWith("#")||r.startsWith(".")||r.match(/^[\w-]+$/))try{return document.querySelector(r)}catch{return null}return null},ElementList:e=>Array.isArray(e)&&e.length>0?e[0]:null,NodeList:e=>e.length>0?e[0]:null}}),this.register({name:"ElementList",hyperscriptType:"element-list",tsType:"Element[]",isType:e=>Array.isArray(e)&&e.length>0&&e.every(e=>e instanceof Element),defaultValue:[],description:"Array of DOM Elements",coerceFrom:{Element:e=>e instanceof Element?[e]:[],NodeList:e=>Array.from(e),String:e=>{try{return Array.from(document.querySelectorAll(e))}catch{return[]}},Array:e=>{const t=e;return t.every(e=>e instanceof Element)?t:[]}}}),this.register({name:"Array",hyperscriptType:"array",tsType:"unknown[]",isType:e=>Array.isArray(e),defaultValue:[],description:"Array of values",coerceFrom:{String:e=>{const t=e;try{const e=JSON.parse(t);if(Array.isArray(e))return e}catch{}return t.split(",").map(e=>e.trim())},ElementList:e=>e,NodeList:e=>Array.from(e),Object:e=>Object.values(e)}}),this.register({name:"Object",hyperscriptType:"object",tsType:"Record<string, unknown>",isType:e=>!("object"!=typeof e||null===e||Array.isArray(e)||e instanceof Element),defaultValue:{},description:"Plain JavaScript object",coerceFrom:{String:e=>{try{const t=JSON.parse(e);if("object"==typeof t&&null!==t&&!Array.isArray(t))return t}catch{}return null},Array:e=>{const t={};return e.forEach((e,r)=>{t[r+""]=e}),t}}}),this.register({name:"Null",hyperscriptType:"null",tsType:"null",isType:e=>null===e,defaultValue:null,description:"Null value"}),this.register({name:"Undefined",hyperscriptType:"undefined",tsType:"undefined",isType:e=>void 0===e,defaultValue:void 0,description:"Undefined value"}),this.register({name:"Function",hyperscriptType:"function",tsType:"Function",isType:e=>"function"==typeof e,defaultValue:null,description:"JavaScript function"}),this.register({name:"Event",hyperscriptType:"event",tsType:"Event",isType:e=>e instanceof Event,defaultValue:null,description:"DOM Event"}),this.register({name:"NodeList",hyperscriptType:"element-list",tsType:"NodeList",isType:e=>e instanceof NodeList,defaultValue:null,description:"DOM NodeList (typically from querySelectorAll)",coerceFrom:{Array:e=>null}}),this.register({name:"Unknown",hyperscriptType:"unknown",tsType:"unknown",isType:e=>1,defaultValue:null,description:"Unknown/any value type"})}};function xt(e){const t=wt.get("String");return t?t.isType(e):"string"==typeof e}function kt(e){const t=wt.get("Number");return t?t.isType(e):"number"==typeof e}function At(e){const t=wt.get("Boolean");return t?t.isType(e):"boolean"==typeof e}function St(e){const t=wt.get("Object");return t?t.isType(e):"object"==typeof e&&null!==e}function Ct(e){const t=wt.get("Function");return t?t.isType(e):"function"==typeof e}function Tt(e){if(null===e||"object"!=typeof e||!("tagName"in e))return 0;const t=e.tagName;return"INPUT"===t||"SELECT"===t||"TEXTAREA"===t}function Nt(e){return e instanceof Element}const Ot={id:e=>e.id,classname:e=>e.className,class:e=>e.className,tagname:e=>e.tagName.toLowerCase(),innertext:e=>e.textContent?.trim(),innerHTML:e=>e.innerHTML,outerhtml:e=>e.outerHTML,value:e=>Tt(e)?e.value:void 0,checked:e=>function(e){return null!==e&&"object"==typeof e&&"tagName"in e&&"INPUT"===e.tagName}(e)?e.checked:void 0,disabled:e=>Tt(e)?e.disabled:void 0,selected:e=>function(e){return null!=e&&"object"==typeof e&&"tagName"in e&&"OPTION"===e.tagName}(e)?e.selected:void 0,hidden:e=>function(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"style"in e}(e)?e.hidden:void 0,style:e=>getComputedStyle(e),children:e=>Array.from(e.children),parent:e=>e.parentElement,firstchild:e=>e.firstElementChild,lastchild:e=>e.lastElementChild,nextsibling:e=>e.nextElementSibling,previoussibling:e=>e.previousElementSibling};function Lt(e,t){if(t.startsWith("computed-")){const r=t.slice(9);return function(e){return e instanceof HTMLElement}(e)?getComputedStyle(e).getPropertyValue(r):void 0}const r=Ot[t.toLowerCase()];if(r)return r(e);if(function(e,t){return e.hasAttribute(t)}(e,t))return function(e,t){return e.getAttribute(t)}(e,t);const n=e[t];return Ct(n)?n.bind(e):n}class $t{constructor(){this.expressionRegistry=new Map}registerCategory(e){Object.entries(e).forEach(([e,t])=>{this.expressionRegistry.set(e,t)})}unwrapSelectorResult(e){if(e instanceof NodeList&&e.length>0)return e[0];if(Array.isArray(e)&&e.length>0){const t=e[0];return"index"in e&&"input"in e?e:t instanceof Element||t instanceof Node?t:e}return e}async evaluate(e,t){if(!e)return pe("EVALUATOR: Received null/undefined node, returning null"),null;if(!e.type)throw console.error("EVALUATOR: Node missing type property:",e),Error("Node missing type property: "+JSON.stringify(e));switch(e.type){case"identifier":return this.evaluateIdentifier(e,t);case"literal":return this.evaluateLiteral(e,t);case"string":return e.value||e.content||"";case"memberExpression":return this.evaluateMemberExpression(e,t);case"binaryExpression":return this.evaluateBinaryExpression(e,t);case"unaryExpression":return this.evaluateUnaryExpression(e,t);case"callExpression":return this.evaluateCallExpression(e,t);case"selector":return this.evaluateSelector(e,t);case"dollarExpression":return this.evaluateDollarExpression(e,t);case"possessiveExpression":return this.evaluatePossessiveExpression(e,t);case"templateLiteral":return this.evaluateTemplateLiteral(e,t);case"arrayLiteral":return this.evaluateArrayLiteral(e,t);case"objectLiteral":return this.evaluateObjectLiteral(e,t);case"conditionalExpression":return this.evaluateConditionalExpression(e,t);case"cssSelector":return this.evaluateCSSSelector(e,t);case"propertyAccess":return this.evaluatePropertyAccess(e,t);case"propertyOfExpression":return this.evaluatePropertyOfExpression(e,t);case"contextReference":return this.evaluateContextReference(e,t);case"queryReference":return this.evaluateQueryReference(e,t);case"idSelector":return this.evaluateIdSelector(e,t);default:throw Error("Unsupported AST node type for evaluation: "+e.type)}}async evaluateWithResult(e,t){try{return dt(await this.evaluate(e,t))}catch(e){if(e instanceof Error){const t=e;if(t.isHalt||"HALT_EXECUTION"===t.message)return pt({type:"halt"});if(t.isExit||"EXIT_COMMAND"===t.message)return pt({type:"exit",returnValue:t.returnValue});if(t.isBreak)return pt({type:"break"});if(t.isContinue)return pt({type:"continue"});if(t.isReturn)return pt({type:"return",returnValue:t.returnValue})}throw e}}async evaluateArrayLiteral(e,t){const r=e.elements||[],n=[];for(const e of r){const r=await this.evaluate(e,t);n.push(r)}return n}async evaluateObjectLiteral(e,t){const r=e.properties||[],n={};for(const e of r){let r;r="identifier"===e.key.type?e.key.name:"literal"===e.key.type?e.key.value+"":await this.evaluate(e.key,t)+"";const s=await this.evaluate(e.value,t);n[r]=s}return n}async evaluateConditionalExpression(e,t){return await this.evaluate(e.test,t)?this.evaluate(e.consequent,t):e.alternate?this.evaluate(e.alternate,t):void 0}async evaluateTemplateLiteral(e,t){let r=e.value||"";pe("TEMPLATE LITERAL: Evaluating",{template:r,node:e});const n=/\$([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)/g,s=[];let i;for(;null!==(i=n.exec(r));)"{"!==r[i.index+1]&&s.push({match:i[0],varName:i[1],index:i.index});for(let e=s.length-1;e>=0;e--){const{match:n,varName:i,index:o}=s[e],a=await this.resolveTemplateVariable(i,t);pe(`TEMPLATE: $${i} resolved to`,a),r=r.slice(0,o)+((a??"")+"")+r.slice(o+n.length)}let o="",a=0;for(;r.length>a;){const e=r.indexOf("${",a);if(-1===e){o+=r.slice(a);break}o+=r.slice(a,e);const n=r.indexOf("}",e);if(-1===n)throw Error("Unterminated template expression in: "+r);const s=r.slice(e+2,n);let i;pe("TEMPLATE: Evaluating expression:",s);const c=s.trim();t.locals.has(c)?(i=t.locals.get(c),pe(`TEMPLATE: Found in locals: ${c} =`,i)):t.variables&&t.variables.has(c)?(i=t.variables.get(c),pe(`TEMPLATE: Found in variables: ${c} =`,i)):t.globals&&t.globals.has(c)?(i=t.globals.get(c),pe(`TEMPLATE: Found in globals: ${c} =`,i)):(i=await this.evaluateSimpleExpression(s,t),pe(`TEMPLATE: Evaluated expression "${s}" =`,i)),o+=i+"",a=n+1}return o}async resolveTemplateVariable(e,t){if(e.includes(".")){const r=e.split(".");let n=this.lookupTemplateVariable(r[0],t);for(let e=1;r.length>e&&null!=n;e++)n=n[r[e]];return n}return this.lookupTemplateVariable(e,t)}lookupTemplateVariable(e,t){return t.locals?.has(e)?t.locals.get(e):t.variables?.has(e)?t.variables.get(e):t.globals?.has(e)?t.globals.get(e):"me"===e?t.me:"it"===e?t.it:"result"===e?t.result:void 0}async evaluateSimpleExpression(e,t){pe("EVAL: Evaluating expression:",e);const r=e.match(/^(.+?)\s*\?\s*(.+?)\s*:\s*(.+)$/);if(r){const[,e,n,s]=r;pe("EVAL: Parsed ternary:",{conditionExpr:e,trueExpr:n,falseExpr:s});const i=await this.resolveValue(e.trim(),t);if(pe("EVAL: Ternary condition value:",i),i){const e=await this.resolveValue(n.trim(),t);return pe("EVAL: Ternary returned true branch:",e),e}{const e=await this.resolveValue(s.trim(),t);return pe("EVAL: Ternary returned false branch:",e),e}}const n=e.match(/^([a-zA-Z_$][a-zA-Z0-9_$]*|\d+(?:\.\d+)?)\s*([\+\-\*\/\%])\s*([a-zA-Z_$][a-zA-Z0-9_$]*|\d+(?:\.\d+)?)$/);if(n){const[,e,r,s]=n;pe("EVAL: Parsed arithmetic:",{left:e,operator:r,right:s});const i=await this.resolveValue(e.trim(),t),o=await this.resolveValue(s.trim(),t);pe("EVAL: Resolved values:",{leftValue:i,rightValue:o});const a=Number(i),c=Number(o);if(!isNaN(a)&&!isNaN(c)){let e;switch(r){case"+":e=a+c;break;case"-":e=a-c;break;case"*":e=a*c;break;case"/":e=a/c;break;case"%":e=a%c;break;default:e=a}return pe("EVAL: Arithmetic result:",e),e}}const s=await this.resolveValue(e.trim(),t);return pe("EVAL: Fallback result:",s),s}async resolveValue(e,t){if(pe(`RESOLVE: Looking for '${e}' in context`,{hasInLocals:t.locals.has(e),localsKeys:Array.from(t.locals.keys()),value:t.locals.get(e)}),t.locals.has(e)){const r=t.locals.get(e);return pe(`RESOLVE: Found '${e}' in locals:`,r),r}if(t.variables&&t.variables.has(e)){const r=t.variables.get(e);return pe(`RESOLVE: Found '${e}' in variables:`,r),r}if(t.globals&&t.globals.has(e)){const r=t.globals.get(e);return pe(`RESOLVE: Found '${e}' in globals:`,r),r}const r=Number(e);if(!isNaN(r))return r;if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);if(e.includes(".")){const r=e.split("."),n=r[0];let s=null;if(t.locals.has(n)?s=t.locals.get(n):t.variables&&t.variables.has(n)?s=t.variables.get(n):t.globals&&t.globals.has(n)&&(s=t.globals.get(n)),null!=s){for(let e=1;r.length>e;e++){if(null==s)return void pe(`RESOLVE: Property access failed at '${r[e-1]}'`);s=s[r[e]]}return pe(`RESOLVE: Property access '${e}' =`,s),s}}return e}async evaluateIdentifier(e,t){const{name:r,scope:n}=e;if("me"===r||"my"===r||"I"===r)return t.me;if("you"===r||"your"===r)return t.you;if("it"===r||"its"===r)return t.it;if("result"===r)return t.result;const s=this.expressionRegistry.get(r);return s?s.evaluate(t):"local"===n?t.locals?.has(r)?t.locals.get(r):void 0:"global"===n?t.globals?.has(r)?t.globals.get(r):"undefined"!=typeof window&&r in window?window[r]:void 0:t.locals?.has(r)?t.locals.get(r):t.globals?.has(r)?t.globals.get(r):t.variables?.has(r)?t.variables.get(r):"undefined"!=typeof globalThis&&r in globalThis?globalThis[r]:"undefined"!=typeof window&&r in window?window[r]:void 0}async evaluateLiteral(e,t){return e.value}async evaluateContextReference(e,t){const{contextType:r}=e;switch(r){case"me":return t.me;case"it":return t.result;case"you":return t.you;case"event":return t.event;case"body":return t.meta?.ownerDocument?.body||document?.body;case"detail":return t.event?.detail;case"target":return t.you||t.event?.target;case"sender":return t.event?.target;default:return t.locals&&t.locals.has(r)?t.locals.get(r):void pe("Unknown context reference type: "+r)}}async evaluateMemberExpression(e,t){const{object:r,property:n,computed:s}=e;if("identifier"===r.type&&["add","remove"].includes(r.name)){const e=r.name,s=n.name||n;if(!t.me)throw Error('Context element "me" is null');return void("add"===e?t.me.classList.add(s):"remove"===e&&t.me.classList.remove(s))}let i=await this.evaluate(r,t);if(s)return i[await this.evaluate(n,t)];{i=this.unwrapSelectorResult(i);const e=n.name||n;if("string"==typeof e){if(e.startsWith("computed-")){const t=e.substring(9);return i&&"undefined"!=typeof window&&i instanceof Element?window.getComputedStyle(i).getPropertyValue(t):void 0}if(e.startsWith("@")){const t=e.substring(1);return i&&"function"==typeof i.getAttribute?i.getAttribute(t):void 0}if(i&&i instanceof Element){if("previous"===e||"prev"===e)return i.previousElementSibling;if("next"===e)return i.nextElementSibling}}const t=i?.[e];return"function"==typeof t?t.bind(i):t}}async evaluateBinaryExpression(e,t){const{operator:r,left:n,right:s}=e;if("in"===r&&"selector"===n.type){let e=n.value;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const r=this.unwrapSelectorResult(await this.evaluate(s,t));if(!r||"function"!=typeof r.querySelector)throw Error(`'in' operator requires a DOM element as the right operand (got: ${typeof r})`);const i=r.querySelectorAll(e);return Array.from(i)}if("in"===r&&"queryReference"===n.type){let e=n.selector;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const r=this.unwrapSelectorResult(await this.evaluate(s,t));if(!r||"function"!=typeof r.querySelector)throw Error(`'in' operator requires a DOM element as the right operand (got: ${typeof r})`);const i=r.querySelectorAll(e);return Array.from(i)}if("in"===r){let e=null,r=null;if("positionalExpression"===n.type){e=n.operator;const s=n.argument;"cssSelector"===s?.type?r=s.selector:"selector"===s?.type?r=s.value:"classSelector"===s?.type?r="."+s.className:"idSelector"===s?.type?r="#"+s.id:s&&(r=await this.evaluate(s,t)+"")}else if("memberExpression"!==n.type||"identifier"!==n.object?.type||"first"!==n.object.name&&"last"!==n.object.name){if("callExpression"===n.type&&"identifier"===n.callee?.type&&("first"===n.callee.name||"last"===n.callee.name)){e=n.callee.name;const s=n.arguments?.[0];"selector"===s?.type?r=s.value:"cssSelector"===s?.type?r=s.selector:"classSelector"===s?.type?r="."+s.className:"idSelector"===s?.type?r="#"+s.id:s&&(r=await this.evaluate(s,t)+"")}}else e=n.object.name,"identifier"===n.property?.type&&n.property.name&&(r="."+n.property.name);if(e&&r){const n=this.unwrapSelectorResult(await this.evaluate(s,t));if(!n||"function"!=typeof n.querySelectorAll)return;const i=n.querySelectorAll(r),o=Array.from(i);return"first"===e?o.length>0?o[0]:void 0:"last"===e?o.length>0?o[o.length-1]:void 0:o}}if("matches"===r&&("selector"===s.type||"cssSelector"===s.type||"classSelector"===s.type)){const e=await this.evaluate(n,t),r=s.value||s.selector;if(e&&"function"==typeof e.matches)try{return e.matches(r)}catch{return 0}return 0}const i=await this.evaluate(n,t),o=await this.evaluate(s,t);if("has"===r||"have"===r){if(i instanceof Element&&("cssSelector"===s.type&&"class"===s.selectorType||"selector"===s.type&&s.value?.startsWith("."))){const e=s.selector?.slice(1)||s.value?.slice(1)||"";return i.classList.contains(e)}return 0}switch(r){case">":case"is greater than":return i>o;case"<":case"is less than":return o>i;case">=":case"is greater than or equal to":return i>=o;case"<=":case"is less than or equal to":return o>=i;case"==":case"equals":case"is equal to":return i==o;case"===":case"is really equal to":case"really equals":return i===o;case"!=":case"is not equal to":return i!=o;case"!==":case"is not really equal to":return i!==o;case"+":if("string"==typeof i||"string"==typeof o){const e=this.expressionRegistry.get("stringConcatenation");if(e){pe("Using string concatenation for:",{leftValue:i,rightValue:o});const r=await e.evaluate(t,{left:i,right:o});return r.success?r.value:i+o}}else{const e=this.expressionRegistry.get("addition");if(e){pe("Using numeric addition for:",{leftValue:i,rightValue:o});const r=await e.evaluate(t,{left:i,right:o});return r.success?r.value:i+o}}return i+o;case"-":return i-o;case"*":return i*o;case"/":return i/o;case"%":case"mod":return i%o;case"as":const e="string"==typeof o?o:"identifier"===s.type?s.name:"literal"===s.type?s.value:o+"",a=this.expressionRegistry.get("as");return a?a.evaluate(t,i,e):i;case"&&":case"and":return i&&o;case"||":case"or":return i||o;case"is":return i===o;case"is not":return i!==o;case"is a":case"is an":switch("identifier"===s.type?s.name.toLowerCase():(o+"").toLowerCase()){case"string":return"string"==typeof i;case"number":return"number"==typeof i;case"boolean":return"boolean"==typeof i;case"object":return"object"==typeof i&&null!==i;case"array":return Array.isArray(i);case"function":return"function"==typeof i;case"null":return null===i;case"undefined":return void 0===i;default:const e="identifier"===s.type?s.name:o+"";return null!=i&&i.constructor?.name===e}case"is not a":case"is not an":switch("identifier"===s.type?s.name.toLowerCase():(o+"").toLowerCase()){case"string":return"string"!=typeof i;case"number":return"number"!=typeof i;case"boolean":return"boolean"!=typeof i;case"object":return!("object"==typeof i&&null!==i);case"array":return!Array.isArray(i);case"function":return"function"!=typeof i;case"null":return null!==i;case"undefined":return void 0!==i;default:const e="identifier"===s.type?s.name:o+"";return!(null!=i&&i.constructor?.name===e)}case"=":if("identifier"===n.type){const e=n.name;return"result"===e?Object.assign(t,{result:o}):"it"===e?Object.assign(t,{it:o}):"you"===e?t.you=o:(t.variables||Object.assign(t,{variables:new Map}),t.variables.set(e,o)),o}throw Error("Left side of assignment must be an identifier");case"contains":case"include":case"includes":return Array.isArray(i)?i.includes(o):"string"==typeof i?i.includes(o+""):i&&"function"==typeof i.matches?i.matches(o+""):0;case"match":case"matches":if(i&&"function"==typeof i.matches){const e="string"==typeof o?o:o+"";try{return i.matches(e)}catch{return 0}}return 0;case"in":const c="string"==typeof i?i:i+"",l=o;if(!l||"function"!=typeof l.querySelector){if(Array.isArray(l))return l.includes(i);if("object"==typeof l&&null!==l)return c in l;throw Error(`'in' operator requires a DOM element, array, or object as the right operand (got: ${typeof l})`)}return l.querySelector(c);case" ":return"string"==typeof i&&"string"==typeof o?{command:i,selector:o}:"identifier"===n.type&&"selector"===s.type?{command:n.name,selector:s.value}:o;default:throw Error(`Unsupported binary operator: "${r}" (length: ${r.length})`)}}async evaluateUnaryExpression(e,t){const{operator:r,argument:n}=e,s=await this.evaluate(n,t);switch(r){case"not":case"!":const e=this.expressionRegistry.get("not");return e?e.evaluate(t,s):!s;case"no":const n=this.expressionRegistry.get("no");return n?n.evaluate(t,s):0;case"some":return null==s?0:"string"==typeof s||Array.isArray(s)||s instanceof NodeList||s instanceof HTMLCollection?s.length>0:"object"==typeof s?Object.keys(s).length>0:1;case"exists":const i=this.expressionRegistry.get("exists");return i?i.evaluate(t,s):null!=s;case"does not exist":const o=this.expressionRegistry.get("doesNotExist");return o?o.evaluate(t,s):null==s;case"-":return-s;case"+":return+s;default:throw Error("Unsupported unary operator: "+r)}}async evaluateCallExpression(e,t){const{callee:r,arguments:n,isConstructor:s}=e;if(s){const e=r.name,s=t.globals?.get(e)||window[e];if("function"==typeof s)return new s(...await Promise.all(n.map(e=>this.evaluate(e,t))));throw Error("Unknown constructor: "+e)}if("memberExpression"===r.type||"propertyAccess"===r.type)return await this.evaluateMethodCall(r,n,t);const i=r.name||r,o=this.expressionRegistry.get(i);if(o){const e=["first","last","random","at"],r=["closest","previous","next"].includes(i),s=e.includes(i),a=await Promise.all(n.map(e=>r&&e&&"selector"===e.type&&"string"==typeof e.value?e.value:r&&e&&"identifier"===e.type&&"string"==typeof e.name?e.name:s&&e&&"selector"===e.type&&"string"==typeof e.value?this.evaluateSelector(e,t):this.evaluate(e,t)));return o.evaluate(t,...a)}const a=t.globals?.get(i)||window[i];if("function"==typeof a)return a(...await Promise.all(n.map(e=>this.evaluate(e,t))));throw Error("Unknown function: "+i)}async evaluateMethodCall(e,t,r){try{const n=await this.evaluate(e.object,r),s=this.unwrapSelectorResult(n);if(null==s)throw Error("Cannot call method on null or undefined");const i=e.property?.name||e.property?.value||e.property;if(!i||"string"!=typeof i)throw Error("Invalid method name: "+i);const o=s[i];if("function"!=typeof o)throw Error(`Property "${i}" is not a function on ${s.constructor?.name||typeof s}`);const a=await Promise.all(t.map(e=>this.evaluate(e,r)));return o.apply(s,a)}catch(e){if(e instanceof Error)throw e;throw Error("Failed to evaluate method call: "+e)}}async evaluateSelector(e,t){let r=e.value;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());const n=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!n)return[];const s=n.querySelectorAll(r);return Array.from(s).filter(e=>e&&"object"==typeof e&&1===e.nodeType&&"string"==typeof e.tagName)}getAvailableExpressions(){return Array.from(this.expressionRegistry.keys())}async evaluateDollarExpression(e,t){const r=await this.evaluate(e.expression,t);if("identifier"===e.expression.type){const r=e.expression.name;return/^\d+$/.test(r)?r:t.locals?.has(r)?t.locals.get(r):"me"===r&&t.me?t.me:"you"===r&&t.you?t.you:"it"===r&&t.it?t.it:"result"===r&&t.result?t.result:"undefined"!=typeof window&&"window"===r?window:t.globals?.has(r)?t.globals.get(r):""}return r}async evaluatePossessiveExpression(e,t){const{object:r,property:n}=e,s=this.unwrapSelectorResult(await this.evaluate(r,t));if(!s)return;const i=n.name||n.value||n;if("string"==typeof i){if(i.startsWith("@")){const e=i.substring(1);if(s&&"function"==typeof s.getAttribute)return s.getAttribute(e)}if(i.startsWith("computed-")){const e=i.substring(9);if(s&&"undefined"!=typeof window&&s instanceof Element)return window.getComputedStyle(s).getPropertyValue(e)}if(i.startsWith("style.")){const e=i.substring(6);if(s&&s.style)return s.style[e]}return s[i]}return s[i]}hasExpression(e){return this.expressionRegistry.has(e)}async evaluateCSSSelector(e,t){let r=e.selector;if(r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim()),"id"===e.selectorType){const e=r.startsWith("#")?r.slice(1):r;return document.getElementById(e)}if("class"===e.selectorType){const e=r.replace(/:/g,"\\:"),t=document.querySelectorAll(e);return Array.from(t).filter(e=>e instanceof HTMLElement)}const n=document.querySelectorAll(r);return Array.from(n).filter(e=>e instanceof HTMLElement)}async evaluateIdSelector(e,t){const r=e.value.startsWith("#")?e.value.slice(1):e.value;return document.getElementById(r)}async evaluateQueryReference(e,t){let r=e.selector;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());try{return document.querySelectorAll(r)}catch{return document.createDocumentFragment().childNodes}}async evaluatePropertyAccess(e,t){const r=await this.evaluate(e.object,t),n=e.property;if(null==r)throw Error(`Cannot access property "${n.name||n.value}" of ${r}`);const s=n.name||n.value;if(!s)throw Error("Property name must be an identifier");try{let e;return e=Nt(r)?Lt(r,s):r[s],"function"==typeof e?e.bind(r):e}catch(e){throw Error(`Error accessing property "${s}": ${e}`)}}async evaluatePropertyOfExpression(e,t){const r=e.property,n=r.name||r.value;if(!n)throw Error('Property name must be an identifier in "the X of Y" pattern');const s=this.unwrapSelectorResult(await this.evaluate(e.target,t));if(null==s)throw Error(`Cannot access property "${n}" of ${s}`);try{let e;return e=Nt(s)?Lt(s,n):s[n],"function"==typeof e?e.bind(s):e}catch(e){throw Error(`Failed to access property "${n}" on target: ${e}`)}}}const Rt={1:"one",2:"two",3:"three",4:"four",5:"five"};function It(e,t,r,n){return e.length!==t?`${r} requires exactly ${s=t,Rt[s]??s+""} argument${1===t?"":"s"}${n?` (${n})`:""}`:null;var s}function jt(e,t,r,n){return"string"!=typeof e[t]?`${r} ${n||"argument "+(t+1)} must be a string`:null}function Mt(e,t,r){return It(e,1,t,r)??jt(e,0,t,r)}function Dt(e,t){return It(e,2,t,"left, right")}function Vt(){return null}function Bt(e,t,r,n){return e.length>t?`${r} expression takes at most ${1===t?"one":t+""} argument${1===t?"":"s"}${n?` (${n})`:""}`:null}function Pt(e,t,r,n,s){return t>e.length||e.length>r?`${n} requires ${t}-${r} arguments${s?` (${s})`:""}`:null}function _t(e,t,r,n=[]){return{type:e,message:t,suggestions:n,...r&&{path:r}}}const Ft=("undefined"!=typeof process?1:0)||"undefined"!=typeof process&&"true"===process.env.HYPERFIXI_SKIP_VALIDATION||"undefined"!=typeof globalThis&&"true"===globalThis.HYPERFIXI_SKIP_VALIDATION;let qt;function Ut(){return qt({validate:e=>({success:1,data:e})})}function Ht(e,t){if(Ft)return Ut();const r=qt({validate:r=>{if("object"!=typeof r||null===r||Array.isArray(r))return{success:0,error:_t("type-mismatch","Expected object, received "+typeof r)};const n=r,s={};if(t?.strict){const t=Object.keys(e),r=Object.keys(n).filter(e=>!t.includes(e));if(r.length>0)return{success:0,error:_t("runtime-error","Unexpected properties: "+r.join(", "))}}for(const[t,r]of Object.entries(e)){const e=t in n,i=r.validate(n[t]);if(!i.success)return{success:0,error:_t("validation-error",i.error.message||`Field "${t}" validation failed`,i.error.path?`${t}.${i.error.path}`:t)};if(!e&&void 0===i.data&&!r.t)return{success:0,error:_t("missing-argument",`Required field "${t}" is missing`,t)};void 0!==i.data&&(s[t]=i.data)}return{success:1,data:s}}});return r.strict=()=>Ht(e,{strict:1}),r}qt=function(e){return e.describe||(e.describe=function(e){return this.description=e,this}),e.safeParse||(e.safeParse=function(e){const t=this.validate(e);return t.success?{success:1,data:t.data}:{success:0,error:{errors:t.error?[t.error]:[]}}}),e.parse||(e.parse=function(e){const t=this.validate(e);if(t.success&&void 0!==t.data)return t.data;throw Error(t.error?.message||"Validation failed")}),e.optional||(e.optional=function(){const e=this.validate.bind(this),t={...this,t:1,validate:t=>null==t?{success:1,data:void 0}:e(t)};return qt(t)}),e.min||(e.min=function(e){const t=this.validate.bind(this),r={...this,validate:r=>{const n=t(r);return n.success&&"string"==typeof n.data&&e>n.data.length?{success:0,error:_t("runtime-error",`String must be at least ${e} characters long`)}:n}};return qt(r)}),e.max||(e.max=function(e){const t=this.validate.bind(this),r={...this,validate:r=>{const n=t(r);return n.success&&"string"==typeof n.data&&n.data.length>e?{success:0,error:_t("runtime-error",`String must be at most ${e} characters long`)}:n}};return qt(r)}),e.default||(e.default=function(e){const t=this.validate.bind(this),r={...this,i:e,o:1,validate:r=>void 0===r?{success:1,data:e}:t(r)};return qt(r)}),e.rest||(e.rest=function(e){return this}),e.refine||(e.refine=function(e,t){return this}),new Proxy(e,{get:(e,t,r)=>t in e||"string"!=typeof t||t.startsWith("_")||"constructor"===t||"validate"===t||"then"===t?Reflect.get(e,t,r):function(...e){return r}})};const Wt=e=>qt(function(e={}){return Ft?Ut():qt({validate:t=>e.optional&&null==t?{success:1,data:void 0}:"string"!=typeof t?{success:0,error:_t("type-mismatch","Expected string, received "+typeof t)}:void 0!==e.minLength&&e.minLength>t.length?{success:0,error:_t("runtime-error",`String must be at least ${e.minLength} characters long`)}:void 0!==e.maxLength&&t.length>e.maxLength?{success:0,error:_t("runtime-error",`String must be at most ${e.maxLength} characters long`)}:e.pattern&&!e.pattern.test(t)?e.pattern.source.startsWith("^")&&e.pattern.source.endsWith("$")?{success:0,error:_t("runtime-error",`Expected "${e.pattern.source.slice(1,-1)}", received "${t}"`)}:{success:0,error:_t("missing-argument","String does not match required pattern")}:{success:1,data:t},...e.description&&{description:e.description}})}(e||{})),zt=e=>qt(function(e={}){return Ft?Ut():qt({validate:t=>{const r=Number(t);return isNaN(r)?{success:0,error:_t("type-mismatch","Expected number, received "+typeof t)}:void 0!==e.min&&e.min>r?{success:0,error:_t("runtime-error","Number must be at least "+e.min)}:void 0!==e.max&&r>e.max?{success:0,error:_t("runtime-error","Number must be at most "+e.max)}:{success:1,data:r}}})}(e||{})),Jt=()=>qt(Ft?Ut():qt({validate:e=>"boolean"!=typeof e?{success:0,error:_t("type-mismatch","Expected boolean, received "+typeof e)}:{success:1,data:e}})),Zt=e=>qt(Ht(e)),Gt=e=>qt(function(e){return Ft?Ut():qt({validate:t=>{if(!Array.isArray(t))return{success:0,error:_t("type-mismatch","Expected array, received "+typeof t)};if(t.length!==e.length)return{success:0,error:_t("runtime-error",`Expected tuple of length ${e.length}, received length ${t.length}`)};const r=[];for(let n=0;e.length>n;n++){const s=e[n].validate(t[n]);if(!s.success)return{success:0,error:_t("runtime-error",s.error.message,s.error.path?`${n}.${s.error.path}`:""+n)};r.push(s.data)}return{success:1,data:r}}})}(e)),Yt=()=>qt(Ut()),Xt=()=>qt(Ut()),Kt=()=>qt(function(e,t="Custom validation failed"){return Ft?Ut():qt({validate:r=>e(r)?{success:1,data:r}:{success:0,error:_t("runtime-error",t)}})}(e=>void 0===e,"Expected undefined"));class Qt{trackPerformance(e,t,r,n){e.evaluationHistory&&e.evaluationHistory.push({expressionName:this.name,category:this.category,input:t,output:r.success?r.value:r.error,timestamp:n,duration:Date.now()-n,success:r.success})}trackSimple(e,t,r,n=(r?"success":"error")){e.evaluationHistory&&e.evaluationHistory.push({expressionName:this.name,category:this.category,input:"operation",output:n,timestamp:t,duration:Date.now()-t,success:r})}toBoolean(e){return 0==e||0===e||0n===e||""===e||null==e||kt(e)&&isNaN(e)?0:1}success(e,t){return{success:1,value:e,type:t}}failure(e,t,r,n,s=[]){return{success:0,error:{name:e,type:t,message:r,code:n,suggestions:s}}}validationSuccess(){return{isValid:1,errors:[],suggestions:[]}}validationFailure(e,t,r=[]){return{isValid:0,errors:[{type:e,message:t,suggestions:r}],suggestions:r}}isElement(e){return null!=e&&St(e)&&1===e.nodeType}inferType(e){return null===e?"null":void 0===e?"undefined":this.isElement(e)?"element":Array.isArray(e)?"array":St(e)?"object":typeof e}normalizeCollection(e){return Array.isArray(e)?e:e instanceof NodeList?Array.from(e):xt(e)?e.split(""):null==e?[]:St(e)&&Symbol.iterator in e?Array.from(e):[]}toNumber(e){if(kt(e)&&Number.isFinite(e))return e;if(xt(e)){const t=Number(e);return Number.isFinite(t)?t:null}return At(e)?e?1:0:null}}const er=Zt({selector:Wt().min(1),single:Jt().optional().default(0)});new class extends Qt{constructor(){super(...arguments),this.name="me",this.category="Reference",this.syntax="me",this.description="References the current element in the execution context",this.inputSchema=Kt(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=e.me,s=this.isElement(n)?n:null,i=this.success(s,"element");return this.trackPerformance(e,t,i,r),i}catch(n){const s=this.failure("MeExpressionError","runtime-error",n instanceof Error?n.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(e,t,s,r),s}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"me" expression takes no arguments',['Use "me" without any parameters']):this.validationSuccess()}},new class extends Qt{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=Kt(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=e.you,s=this.isElement(n)?n:null,i=this.success(s,"element");return this.trackPerformance(e,t,i,r),i}catch(n){const s=this.failure("YouExpressionError","runtime-error",n instanceof Error?n.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(e,t,s,r),s}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"you" expression takes no arguments',['Use "you" without any parameters']):this.validationSuccess()}},new class extends Qt{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=Kt(),this.outputType="Any",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=e.it,s={success:1,value:n,type:this.inferType(n)};return this.trackPerformance(e,t,s,r),s}catch(n){const s=this.failure("ItExpressionError","runtime-error",n instanceof Error?n.message:'Failed to evaluate "it"',"IT_EVALUATION_FAILED",['Ensure "it" is set by previous operation',"Check if context variable is available"]);return this.trackPerformance(e,t,s,r),s}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"it" expression takes no arguments',['Use "it" without any parameters']):this.validationSuccess()}},new class extends Qt{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=er,this.outputType="ElementList",this.metadata={category:"Reference",complexity:"medium"}}async evaluate(e,t){const r=Date.now();try{if(!this.isValidCSSSelector(t.selector)){const n=this.failure("CSSSelectorError","invalid-argument",`Invalid CSS selector: "${t.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(e,t,n,r),n}let n;if(t.single)n=document.querySelector(t.selector);else{const e=Array.from(document.querySelectorAll(t.selector));n=e.length>0?e:null}const s={success:1,value:n,type:Array.isArray(n)?"element-list":"element"};return this.trackPerformance(e,t,s,r),s}catch(n){const s=this.failure("CSSSelectorError","runtime-error",n instanceof Error?n.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(e,t,s,r),s}}validate(e){try{const t=this.inputSchema.safeParse(e);if(!t.success)return{isValid:0,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid input: "+e.message,suggestions:this.getValidationSuggestion(e.code??"unknown")}))??[],suggestions:["Provide valid CSS selector string","Check selector syntax"]};const{selector:r}=t.data;return this.isValidCSSSelector(r)?this.validationSuccess():this.validationFailure("syntax-error",`Invalid CSS selector syntax: "${r}"`,["Use .class for class selectors","Use #id for ID selectors","Use tag for element selectors","Use [attr] for attribute selectors"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Ensure input matches expected format"])}}isValidCSSSelector(e){try{return document.querySelector(e),1}catch{return 0}}getValidationSuggestion(e){return[{too_small:"CSS selector cannot be empty",invalid_type:"Selector must be a string",required:"CSS selector is required"}[e]||"Check input format and types"]}};const tr={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me instanceof HTMLElement?e.me:null,validate:Vt},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.you instanceof HTMLElement?e.you:null,validate:Vt},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:Vt},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:Vt},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.result,validate:Vt},querySelector:{name:"querySelector",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){const[r]=t;if("string"!=typeof r)throw Error("querySelector requires a string selector");return document.querySelector(r)},validate:e=>Mt(e,"querySelector","selector")},querySelectorAll:{name:"querySelectorAll",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const r=t[0];if("string"!=typeof r)throw Error("querySelectorAll requires a string selector");const n=document.querySelectorAll(r);return Array.from(n)},validate:e=>Mt(e,"querySelectorAll","selector")},getElementById:{name:"getElementById",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){const r=t[0];if("string"!=typeof r)throw Error("getElementById requires a string ID");return document.getElementById(r)},validate:e=>Mt(e,"getElementById","ID")},getElementsByClassName:{name:"getElementsByClassName",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const r=t[0];if("string"!=typeof r)throw Error("getElementsByClassName requires a string class name");const n=document.getElementsByClassName(r);return Array.from(n)},validate:e=>Mt(e,"getElementsByClassName","className")},closest:{name:"closest",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){let r=t[0];if(r&&"object"==typeof r&&"type"in r){const e=r;"identifier"===e.type&&e.name?r=e.name:"literal"===e.type&&"string"==typeof e.value&&(r=e.value)}if("string"!=typeof r)throw Error("closest requires a string selector");return e.me?e.me.closest(r):null},validate(e){if(1!==e.length)return"closest requires exactly 1 argument (selector)";const t=e[0];return"string"==typeof t||t&&"object"==typeof t&&"type"in t&&("identifier"===t.type||"literal"===t.type)?null:"closest selector must be a string or identifier"}},parent:{name:"parent",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me?e.me.parentElement:null,validate:Vt},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async e=>window,validate:Vt},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async e=>document,validate:Vt},elementWithSelector:{name:"elementWithSelector",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const r=t[0];if("string"!=typeof r)throw Error("Selector must be a string");const n=document.querySelectorAll(r);return Array.from(n)},validate:e=>Mt(e,"elementWithSelector","selector")},styleRef:{name:"styleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const r=t[0],n=t[1];if("string"!=typeof r)throw Error("StyleRef requires a string property name");const s=n||e.me;if(s&&s instanceof HTMLElement){if(r.startsWith("computed-")){const e=r.substring(9);return getComputedStyle(s).getPropertyValue(e)||""}return s.style.getPropertyValue(r)||void 0}},validate:e=>Pt(e,1,2,"styleRef","property, optional element")??jt(e,0,"styleRef","property")??(2===e.length&&e[1]&&"object"!=typeof e[1]?"styleRef element must be an HTMLElement":null)},possessiveStyleRef:{name:"possessiveStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const r=t[0],n=t[1];if("string"!=typeof r||"string"!=typeof n)throw Error("Possessive styleRef requires possessor and property strings");let s=null;if("my"===r&&e.me?s=e.me instanceof HTMLElement?e.me:null:"its"===r&&e.result&&(s=e.result),s){if(n.startsWith("computed-")){const e=n.substring(9);return getComputedStyle(s).getPropertyValue(e)||""}return s.style.getPropertyValue(n)||void 0}},validate:e=>It(e,2,"possessiveStyleRef","possessor, property")??jt(e,0,"possessiveStyleRef","possessor")??jt(e,1,"possessiveStyleRef","property")},ofStyleRef:{name:"ofStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const r=t[0],n=t[1];if("string"!=typeof r||"string"!=typeof n)throw Error("Of styleRef requires property and reference strings");let s=null;if("me"===n&&e.me?s=e.me instanceof HTMLElement?e.me:null:"it"===n&&e.result&&(s=e.result),s){if(r.startsWith("computed-")){const e=r.substring(9);return getComputedStyle(s).getPropertyValue(e)||""}return s.style.getPropertyValue(r)||void 0}},validate:e=>It(e,2,"ofStyleRef","property, reference")??jt(e,0,"ofStyleRef","property")??jt(e,1,"ofStyleRef","reference")}};class rr{constructor(e=100,t=5e3){this.maxSize=e,this.ttl=t,this.cache=new Map,this.accessOrder=new Map,this.accessCounter=0}get(e){const t=this.cache.get(e);if(t){if(Date.now()-t.timestamp<=this.ttl)return t.accessCount++,this.accessOrder.set(e,++this.accessCounter),t.result;this.delete(e)}}set(e,t){this.maxSize>this.cache.size||this.cache.has(e)||this.evictLRU();const r={result:t,timestamp:Date.now(),accessCount:1};this.cache.set(e,r),this.accessOrder.set(e,++this.accessCounter)}delete(e){return this.accessOrder.delete(e),this.cache.delete(e)}clear(){this.cache.clear(),this.accessOrder.clear(),this.accessCounter=0}size(){return this.cache.size}evictLRU(){let e,t=1/0;for(const[r,n]of this.accessOrder)t>n&&(t=n,e=r);void 0!==e&&this.delete(e)}getStats(){const e=Array.from(this.cache.values()),t=Date.now();return{size:this.cache.size,maxSize:this.maxSize,hitRate:e.length>0?e.filter(e=>e.accessCount>1).length/e.length:0,avgAge:e.length>0?e.reduce((e,r)=>e+(t-r.timestamp),0)/e.length:0,totalAccesses:e.reduce((e,t)=>e+t.accessCount,0)}}}const nr=new class{constructor(){this.domQueryCache=new rr(200,3e3),this.exprResultCache=new rr(500,2e3),this.cssMatchCache=new rr(100,5e3),this.formValueCache=new rr(50,1e3),this.hits=0,this.misses=0}querySelector(e){const t="querySelector:"+e,r=this.domQueryCache.get(t);if(void 0!==r)return this.hits++,r;this.misses++;const n=document.querySelector(e);return this.domQueryCache.set(t,n),n}querySelectorAll(e){const t="querySelectorAll:"+e,r=this.domQueryCache.get(t);if(void 0!==r)return this.hits++,r;this.misses++;const n=Array.from(document.querySelectorAll(e));return this.domQueryCache.set(t,n),n}getElementById(e){const t="getElementById:"+e,r=this.domQueryCache.get(t);if(void 0!==r)return this.hits++,r;this.misses++;const n=document.getElementById(e);return this.domQueryCache.set(t,n),n}getElementsByClassName(e){const t="getElementsByClassName:"+e,r=this.domQueryCache.get(t);if(void 0!==r)return this.hits++,r;this.misses++;const n=Array.from(document.getElementsByClassName(e));return this.domQueryCache.set(t,n),n}matches(e,t){const r=`matches:${this.getElementCacheKey(e)}:${t}`,n=this.cssMatchCache.get(r);if(void 0!==n)return this.hits++,n;this.misses++;const s=e.matches(t);return this.cssMatchCache.set(r,s),s}getExpressionResult(e){const t=this.exprResultCache.get(e);if(void 0!==t)return this.hits++,t;this.misses++}setExpressionResult(e,t){this.exprResultCache.set(e,t)}getFormValue(e){const t=this.getElementCacheKey(e),r=this.formValueCache.get("formValue:"+t);if(void 0!==r)return this.hits++,r;this.misses++}setFormValue(e,t){const r=this.getElementCacheKey(e);this.formValueCache.set("formValue:"+r,t)}invalidateElementCache(e){const t=this.getElementCacheKey(e);for(const e of[this.domQueryCache,this.cssMatchCache,this.formValueCache])for(const r of Array.from(e.cache.keys()))"string"==typeof r&&r.includes(t)&&e.delete(r)}invalidateAll(){this.domQueryCache.clear(),this.exprResultCache.clear(),this.cssMatchCache.clear(),this.formValueCache.clear(),this.hits=0,this.misses=0}getElementCacheKey(e){if(e.id)return"#"+e.id;const t=Array.from(e.classList).sort().join("."),r=this.getElementPosition(e);return`${e.tagName.toLowerCase()}${t?"."+t:""}@${r}`}getElementPosition(e){return""+Array.from(e.parentElement?.children||[]).indexOf(e)}getPerformanceStats(){const e=this.hits+this.misses;return{hits:this.hits,misses:this.misses,hitRate:Math.round(100*(e>0?this.hits/e*100:0))/100,domQueryCache:this.domQueryCache.getStats(),exprResultCache:this.exprResultCache.getStats(),cssMatchCache:this.cssMatchCache.getStats(),formValueCache:this.formValueCache.getStats()}}cleanup(){const e=Date.now();[this.domQueryCache,this.exprResultCache,this.cssMatchCache,this.formValueCache].forEach(t=>{Array.from(t.cache.entries()).forEach(([r,n])=>{e-n.timestamp>t.ttl&&t.delete(r)})})}};"undefined"!=typeof window&&setInterval(()=>{nr.cleanup()},1e4);const sr=new class{constructor(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0},this.startTimes=new Map}startTimer(e){this.startTimes.set(e,performance.now())}endTimer(e){const t=this.startTimes.get(e);if(t){const r=performance.now()-t;return this.startTimes.delete(e),r}return 0}recordTokenization(e){this.metrics.tokenizationTime+=e}recordEvaluation(e){this.metrics.evaluationTime+=e}updateCacheMetrics(){const e=nr.getPerformanceStats();this.metrics.cacheHitRate=e.hitRate}getMetrics(){return this.updateCacheMetrics(),{...this.metrics}}reset(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0}}};function ir(){nr.cleanup(),sr.getMetrics().memoryUsage>52428800&&sr.reset()}let or=null;function ar(e,t){if("number"==typeof e){if(!Number.isFinite(e))throw Error(`${t} must be a finite number, got ${e}`);return e}if("string"==typeof e){const r=e.trim();if(""===r)return 0;const n=parseFloat(r);if(isNaN(n))throw Error(`${t} cannot be converted to number: "${e}"`);return n}if("boolean"==typeof e)return e?1:0;if(null==e)return 0;if("object"==typeof e&&null!==e){const t=e.valueOf();if("number"==typeof t&&Number.isFinite(t))return t}throw Error(`${t} cannot be converted to number: ${typeof e}`)}function cr(e,t,r,n,s,i=1,o){return t&&"object"==typeof t&&"evaluationHistory"in t&&Array.isArray(t.evaluationHistory)&&t.evaluationHistory.push({expressionName:e.name,category:e.category,input:r,output:n,timestamp:s,duration:Date.now()-s,success:i,...void 0!==o&&{error:o}}),n}"undefined"!=typeof window&&function(e=3e4){or&&clearInterval(or),or=setInterval(ir,e)}();const lr=Zt({left:Yt().describe("Left operand value"),right:Yt().describe("Right operand value")}).strict(),ur=Zt({operand:Yt().describe("Operand value to negate")}).strict();new class extends Qt{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=lr,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:0,error:n.errors[0]};const s=this.toBoolean(t.left);if(!s)return this.trackSimple(e,r,1,"boolean"),this.success(0,"boolean");const i=this.toBoolean(t.right),o=s&&i;return this.trackSimple(e,r,1,"boolean"),this.success(o,"boolean")}catch(t){return this.trackSimple(e,r,0),this.failure("AndExpressionError","runtime-error","Logical AND operation failed: "+(t instanceof Error?t.message:t+""),"AND_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:0,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid AND operation input: "+e.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends Qt{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=lr,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:0,error:n.errors[0]};const s=this.toBoolean(t.left);if(s)return this.trackSimple(e,r,1,"boolean"),this.success(1,"boolean");const i=this.toBoolean(t.right),o=s||i;return this.trackSimple(e,r,1,"boolean"),this.success(o,"boolean")}catch(t){return this.trackSimple(e,r,0),this.failure("OrExpressionError","runtime-error","Logical OR operation failed: "+(t instanceof Error?t.message:t+""),"OR_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:0,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid OR operation input: "+e.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends Qt{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=ur,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:0,error:n.errors[0]};const s=!this.toBoolean(t.operand);return this.trackSimple(e,r,1,"boolean"),this.success(s,"boolean")}catch(t){return this.trackSimple(e,r,0),this.failure("NotExpressionError","runtime-error","Logical NOT operation failed: "+(t instanceof Error?t.message:t+""),"NOT_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:0,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid NOT operation input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a single operand","Ensure operand is a valid value"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}};const hr=Gt([Yt(),Yt()]),fr=Gt([Yt(),Wt()]),dr={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(e,t,r){const n=Date.now();try{return cr(this,e,[t,r],t==r,n)}catch(s){throw cr(this,e,[t,r],0,n,0,s instanceof Error?s:Error(s+"")),s}},validate:e=>Dt(e,"equals"),inputSchema:hr,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"]}},pr={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],evaluate:async(e,t,r)=>t===r,validate:e=>Dt(e,"strictEquals")},mr={name:"notEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=","is not","does not equal"],evaluate:async(e,t,r)=>t!=r,validate:e=>Dt(e,"notEquals")},yr={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],evaluate:async(e,t,r)=>t!==r,validate:e=>Dt(e,"strictNotEquals")},vr={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],evaluate:async(e,t,r)=>r>t,validate:e=>Dt(e,"lessThan")},gr={name:"lessThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<=","is less than or equal to"],evaluate:async(e,t,r)=>r>=t,validate:e=>Dt(e,"lessThanOrEqual")},br={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],evaluate:async(e,t,r)=>t>r,validate:e=>Dt(e,"greaterThan")},Er={name:"greaterThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">=","is greater than or equal to"],evaluate:async(e,t,r)=>t>=r,validate:e=>Dt(e,"greaterThanOrEqual")},wr={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(e,t,r){const n=Date.now();try{return cr(this,e,[t,r],t&&r,n)}catch(s){throw cr(this,e,[t,r],0,n,0,s instanceof Error?s:Error(s+"")),s}},validate:e=>Dt(e,"and"),inputSchema:hr,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"]}},xr={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],evaluate:async(e,t,r)=>t||r,validate:e=>Dt(e,"or")},kr={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],evaluate:async(e,t)=>!t,validate:e=>It(e,1,"not","operand")},Ar={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],evaluate:async(e,t)=>null==t?1:xt(t)||Array.isArray(t)||t instanceof NodeList?0===t.length:t instanceof Node||t instanceof Element?0:St(t)?0===Object.keys(t).length:0,validate:e=>It(e,1,"isEmpty","value")},Sr={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],evaluate:async(e,t)=>null==t||0==t?1:Array.isArray(t)||t instanceof NodeList?0===t.length:xt(t)||t instanceof Node||t instanceof Element?0:St(t)?0===Object.keys(t).length:0,validate:e=>It(e,1,"no","value")},Cr={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],evaluate:async(e,t)=>!await Ar.evaluate(e,t),validate:e=>It(e,1,"isNotEmpty","value")},Tr={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],evaluate:async(e,t)=>null!=t,validate:e=>It(e,1,"exists","value")},Nr={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],evaluate:async(e,t)=>null==t,validate:e=>It(e,1,"doesNotExist","value")},Or={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(e,t,r){if(t&&r){if(1===t.nodeType&&1===r.nodeType)return t.contains(r);if(xt(t)&&t.match(/^[.#][\w-]+$/)){const e=document.querySelector(t);if(e&&1===r.nodeType)return e.contains(r);if(e&&xt(r)&&r.match(/^[.#][\w-]+$/)){const t=document.querySelector(r);return t?e.contains(t):0}}if(xt(r)&&r.match(/^[.#][\w-]+$/)&&1===t.nodeType){const e=document.querySelector(r);return e?t.contains(e):0}}return xt(t)&&xt(r)||Array.isArray(t)?t.includes(r):"undefined"!=typeof NodeList&&t instanceof NodeList?Array.from(t).includes(r):St(t)&&xt(r)?r in t:0},validate:e=>It(e,2,"contains","container, value")},Lr={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],evaluate:async(e,t,r)=>!await Or.evaluate(e,t,r),validate:e=>It(e,2,"doesNotContain","container, value")},$r={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],evaluate:async(e,t,r)=>xt(t)&&xt(r)?t.startsWith(r):0,validate:e=>It(e,2,"startsWith","str, prefix")},Rr={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],evaluate:async(e,t,r)=>xt(t)&&xt(r)?t.endsWith(r):0,validate:e=>It(e,2,"endsWith","str, suffix")},Ir={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(e,t,r){const n=Date.now();try{let s;if(t instanceof Element&&xt(r)){const e=r;if(e.startsWith(".")||e.startsWith("#")||e.startsWith(":")||e.startsWith("[")||/^[a-zA-Z][\w-]*$/.test(e))try{s=function(e,t){return nr.matches(e,t)}(t,e)}catch(e){s=0}else s=0}else if(xt(t)&&xt(r)){const e=t,n=r;try{s=(n.startsWith("/")&&n.endsWith("/")?RegExp(n.slice(1,-1)):RegExp(n)).test(e)}catch(t){s=e.includes(n)}}else s=0;return cr(this,e,[t,r],s,n)}catch(s){throw cr(this,e,[t,r],0,n,0,s instanceof Error?s:Error(s+"")),s}},validate:e=>It(e,2,"matches","element, selector"),inputSchema:fr,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"]}},jr={equals:dr,strictEquals:pr,notEquals:mr,strictNotEquals:yr,lessThan:vr,lessThanOrEqual:gr,greaterThan:br,greaterThanOrEqual:Er,and:wr,or:xr,not:kr,no:Sr,isEmpty:Ar,isNotEmpty:Cr,exists:Tr,doesNotExist:Nr,contains:Or,doesNotContain:Lr,startsWith:$r,endsWith:Rr,matches:Ir};function Mr(e,t,r,n,s="runtime-error"){return{success:0,error:{name:e+"ConversionError",type:s,message:r,code:t,suggestions:n}}}function Dr(e,t){return{success:1,value:e,type:t}}function Vr(e,t){return`${e}: ${t instanceof Error?t.message:t+""}`}const Br={Array:(e,t)=>{try{return Array.isArray(e)?Dr(e,"array"):e instanceof NodeList?Dr(Array.from(e),"array"):Dr(null==e?[]:[e],"array")}catch(e){return Mr("Array","ARRAY_CONVERSION_FAILED",Vr("Failed to convert value to Array",e),["Check if value is iterable","Ensure value is not circular reference"])}},String:(e,t)=>{try{return null==e?Dr("","string"):xt(e)?Dr(e,"string"):St(e)?Dr(JSON.stringify(e),"string"):Dr(e+"","string")}catch(e){return Mr("String","STRING_CONVERSION_FAILED",Vr("Failed to convert value to String",e),["Check if object has circular references","Ensure value is serializable"])}},Boolean:(e,t)=>{try{if(At(e))return Dr(e,"boolean");if(null==e)return Dr(0,"boolean");if(xt(e)){const t=e.toLowerCase().trim();return Dr("false"!==t&&"0"!==t&&""!==t,"boolean")}return kt(e)?Dr(0!==e&&!isNaN(e),"boolean"):Dr(!!e,"boolean")}catch(e){return Mr("Boolean","BOOLEAN_CONVERSION_FAILED",Vr("Failed to convert value to Boolean",e),["Use explicit true/false values","Check for unexpected data types"])}},Number:(e,t)=>{try{if(kt(e))return Dr(e,"number");if(null==e)return Dr(0,"number");const t=Number(e);return isNaN(t)?Mr("Number","INVALID_NUMBER",`Cannot convert "${e}" to a valid number`,["Check if value contains non-numeric characters","Use a valid numeric format"],"invalid-argument"):Dr(t,"number")}catch(e){return Mr("Number","NUMBER_CONVERSION_FAILED",Vr("Failed to convert value to Number",e),["Ensure value is convertible to number","Check for special characters"])}},Int:(e,t)=>{const r=Br.Number(e,t);return r.success?Dr(Math.trunc(r.value),"number"):r},Float:(e,t)=>{const r=Br.Number(e,t);return r.success?Dr(parseFloat(""+r.value),"number"):r},Date:(e,t)=>{try{if(e instanceof Date)return Dr(e,"object");if(null==e)return Dr(new Date(""),"object");if(xt(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,r,n]=e.split("-").map(Number);return Dr(new Date(t,r-1,n),"object")}const t=new Date(e);return isNaN(t.getTime())?Mr("Date","INVALID_DATE",`Cannot convert "${e}" to a valid date`,["Use ISO 8601 format (YYYY-MM-DD)","Check date string format","Ensure date values are valid"],"invalid-argument"):Dr(t,"object")}catch(e){return Mr("Date","DATE_CONVERSION_FAILED",Vr("Failed to convert value to Date",e),["Check date format","Ensure value is a valid date string or timestamp"])}},JSON:(e,t)=>{try{return Dr(JSON.stringify(e),"string")}catch(e){return Mr("JSON","JSON_STRINGIFY_FAILED",Vr("Failed to convert value to JSON",e),["Check for circular references","Ensure all properties are serializable","Remove functions and undefined values"])}},Object:(e,t)=>{try{if(St(e))return Dr(e,"object");if(xt(e))try{return Dr(JSON.parse(e),"object")}catch(e){return Mr("Object","JSON_PARSE_FAILED",Vr("Cannot parse JSON string",e),["Check JSON syntax","Ensure proper escaping of quotes","Validate JSON format"],"syntax-error")}return Dr({},"object")}catch(e){return Mr("Object","OBJECT_CONVERSION_FAILED",Vr("Failed to convert value to Object",e),["Ensure value is valid JSON string or object","Check for syntax errors"])}},Values:(e,t)=>{try{if(e instanceof HTMLFormElement)return Dr(function(e){const t={};return e.querySelectorAll("input, select, textarea").forEach(e=>{const r=e;if(r.name){const e=Fr(r);void 0!==e&&(void 0!==t[r.name]?(Array.isArray(t[r.name])||(t[r.name]=[t[r.name]]),t[r.name].push(e)):t[r.name]=e)}}),t}(e),"object");if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),r={};return t.forEach(e=>{const t=e;if(t.name){const e=Fr(t);void 0!==e&&(r[t.name]=e)}}),Dr(r,"object")}return Dr({},"object")}catch(e){return Mr("FormValues","FORM_VALUES_EXTRACTION_FAILED",Vr("Failed to extract form values",e),["Ensure element is a form or contains form inputs","Check form structure","Verify input names are set"])}}},Pr=Zt({value:Xt(),type:Wt().min(1)}),_r=Zt({value:Xt(),type:Wt().min(1)});function Fr(e){if(e instanceof HTMLInputElement)switch(e.type){case"checkbox":return e.checked;case"radio":return e.checked?e.value:void 0;case"number":case"range":return e.valueAsNumber;case"date":case"datetime-local":return e.valueAsDate;case"file":return e.files;default:return e.value}return e instanceof HTMLSelectElement&&e.multiple?Array.from(e.selectedOptions).map(e=>e.value):e.value}new class extends Qt{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=Pr,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 JSON",description:"Convert array to JSON string",expectedOutput:"[1,2,3]"},{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 JSON into storage",explanation:"Convert array to JSON string for storage",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(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:0,error:{name:"AsExpressionValidationError",type:"validation-error",message:n.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:n.suggestions}};const{value:s,type:i}=t;if(i.startsWith("Fixed")){const n=i.match(/^Fixed:(\d+)$/),o=n?parseInt(n[1],10):2,a=Br.Number(s,e);if(!a.success)return a;const c={success:1,value:a.value.toFixed(o),type:"string"};return this.trackPerformance(e,t,c,r),c}let o=Br[i];if(o){const n=o(s,e);return this.trackPerformance(e,t,n,r),n}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"}[i.toLowerCase()];if(a&&(o=Br[a],o)){const n=o(s,e);return this.trackPerformance(e,t,n,r),n}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(e,t,c,r),c}catch(n){const s={success:0,error:{name:"AsExpressionError",type:"runtime-error",message:"Conversion failed: "+(n instanceof Error?n.message:n+""),code:"CONVERSION_FAILED",suggestions:["Check value and type compatibility","Ensure value is convertible to target type"]}};return this.trackPerformance(e,t,s,r),s}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?{isValid:1,errors:[],suggestions:[]}:{isValid:0,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:e.message,suggestions:["Expected valid input structure, got: "+e.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(e){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}},new class extends Qt{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=_r,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(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:0,error:{name:"IsExpressionValidationError",type:"validation-error",message:n.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:n.suggestions}};const{value:s,type:i}=t,o=i.toLowerCase();let a;switch(o){case"null":a=null===s;break;case"undefined":a=void 0===s;break;case"string":a=xt(s);break;case"number":a=kt(s)&&!isNaN(s);break;case"boolean":a=At(s);break;case"object":a=St(s);break;case"array":a=Array.isArray(s);break;case"function":a=Ct(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||St(s)&&0===Object.keys(s).length;break;default:a=s?.constructor?.name?.toLowerCase()===o}const c=this.success(a,"boolean");return this.trackPerformance(e,t,c,r),c}catch(n){const s=this.failure("IsExpressionError","type-mismatch","Type check failed: "+(n instanceof Error?n.message:n+""),"TYPE_CHECK_FAILED",["Check type name spelling","Ensure value is accessible"]);return this.trackPerformance(e,t,s,r),s}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:0,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:e.message,suggestions:["Expected valid input structure, got: "+e.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(e){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}};const qr={Array:e=>Array.isArray(e)?e:e instanceof NodeList?Array.from(e):null==e?[]:[e],String:e=>null==e?"":xt(e)?e:St(e)?JSON.stringify(e):e+"",Boolean:e=>{if(At(e))return e;if(null==e)return 0;if(xt(e)){const t=e.toLowerCase().trim();return"false"===t||"0"===t||""===t?0:1}return kt(e)?0!==e&&!isNaN(e):!!e},Number:e=>{if(kt(e))return e;if(null==e)return 0;const t=Number(e);return isNaN(t)?0:t},Math:e=>{if(kt(e))return e;if(null==e)return 0;const t=(e+"").trim();if(!t)return 0;try{return function(e){if(e=e.replace(/\s/g,""),!/^[0-9+\-*/().]+$/.test(e))throw Error("Invalid characters in math expression");try{const t=Function(`"use strict"; return (${e})`)();if(!kt(t)||!isFinite(t))throw Error("Expression did not evaluate to a finite number");return t}catch(e){throw Error("Math expression evaluation failed: "+(e instanceof Error?e.message:e+""))}}(t)}catch(e){return console.warn("Math conversion failed:",e),0}},Int:e=>{const t=qr.Number(e);return Math.trunc(t)},Float:e=>{const t=qr.Number(e);return parseFloat(""+t)},Date:e=>{if(e instanceof Date)return e;if(null==e)return new Date(NaN);if(xt(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,r,n]=e.split("-").map(Number);return new Date(t,r-1,n)}return new Date(e)},JSON:e=>{try{return JSON.stringify(e)}catch(e){return"{}"}},Object:e=>{if(St(e))return e;if(xt(e))try{return JSON.parse(e)}catch(e){return{}}return{}},Fragment:e=>{xt(e)||(e=qr.String(e));const t=document.createElement("template");return t.innerHTML=e+"",t.content},HTML:e=>xt(e)?e:e instanceof NodeList?Array.from(e).map(e=>e instanceof Element?e.outerHTML:e.textContent||"").join(""):Array.isArray(e)?e.map(e=>e instanceof Element?e.outerHTML:qr.String(e)).join(""):e instanceof Element?e.outerHTML:qr.String(e),Values:(e,t)=>{if(e instanceof HTMLFormElement)return function(e){const t={};return e.querySelectorAll("input, select, textarea").forEach(e=>{const r=e;if(r.name){const e=Ur(r);void 0!==e&&(void 0!==t[r.name]?(Array.isArray(t[r.name])||(t[r.name]=[t[r.name]]),t[r.name].push(e)):t[r.name]=e)}}),t}(e);if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),r={};return t.forEach(e=>{e.name&&(r[e.name]=Ur(e))}),r}return{}},"Values:Form":(e,t)=>{const r=qr.Values(e,t);return""+new URLSearchParams(r)},"Values:JSON":(e,t)=>{const r=qr.Values(e,t);return JSON.stringify(r)}};function Ur(e){if(e instanceof HTMLInputElement)switch(e.type){case"checkbox":return e.checked;case"radio":return e.checked?e.value:void 0;case"number":case"range":return e.valueAsNumber;case"date":case"datetime-local":return e.valueAsDate;case"file":return e.files;default:return e.value}return e instanceof HTMLSelectElement&&e.multiple?Array.from(e.selectedOptions).map(e=>e.value):e.value}const Hr={as:{name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(e,...t){const[r,n]=t;if("string"!=typeof n)throw Error("Conversion type must be a string");if(n.startsWith("Fixed")){const{precision:e}=function(e){const t=e.match(/^Fixed(?::(\d+))?$/);return t?{precision:t[1]?parseInt(t[1],10):2}:{}}(n);return qr.Number(r).toFixed(e||2)}let s=qr[n];if(s)return s(r,e);const i={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"}[n.toLowerCase()];return i&&(s=qr[i],s)?s(r,e):(console.warn("Unknown conversion type: "+n),r)},validate:e=>It(e,2,"as","value, type")??jt(e,1,"as","conversion type")},is:{name:"is",category:"Conversion",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is a","is an"],async evaluate(e,...t){const[r,n]=t;if(!xt(n))throw Error("Type check requires a string type");switch(n.toLowerCase()){case"null":return null===r;case"undefined":return void 0===r;case"string":return xt(r);case"number":return kt(r)&&!isNaN(r);case"boolean":return At(r);case"object":return St(r);case"array":return Array.isArray(r);case"function":return Ct(r);case"date":return r instanceof Date;case"element":return r instanceof Element;case"node":return r instanceof Node;case"nodelist":return r instanceof NodeList;case"empty":return null==r||""===r||Array.isArray(r)&&0===r.length||St(r)&&0===Object.keys(r).length;default:return r?.constructor?.name?.toLowerCase()===n.toLowerCase()}},validate:e=>It(e,2,"is","value, type")??jt(e,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(e,t)=>t,validate:e=>It(e,1,"async","expression")}},Wr={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"},zr=Zt({collection:Yt().describe("Collection to operate on (array, NodeList, or string)")}).strict(),Jr=Zt({collection:Yt().describe("Collection to access"),index:zt().describe("Index position to access")}).strict(),Zr=Zt({collection:Yt().describe("Collection to select random item from")}).strict();function Gr(e,t){let r=e.nextElementSibling;for(;r;){if(r.matches(t))return r;const e=r.querySelector(t);if(e)return e;r=r.nextElementSibling}const n=e.parentElement;return n&&n!==document.documentElement?Gr(n,t):null}function Yr(e,t){let r=e.previousElementSibling;for(;r;){const e=Array.from(r.querySelectorAll(t)).reverse();if(e.length>0)return e[0];if(r.matches(t))return r;r=r.previousElementSibling}const n=e.parentElement;return n&&n!==document.documentElement?Yr(n,t):null}function Xr(e){let t=0,r=e;for(;r&&r.parentElement;)t+=Array.from(r.parentElement.children).indexOf(r),r=r.parentElement,t+=1e3;return t}new class extends Qt{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=zr,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:0,error:n.errors[0]};const s=this.normalizeCollection(t.collection),i=s.length>0?s[0]:void 0,o={success:1,value:i,type:Wr[this.inferResultTypeLocal(i)]};return this.trackPerformance(e,t,o,r),o}catch(n){const s=this.failure("FirstExpressionError","runtime-error","First operation failed: "+(n instanceof Error?n.message:n+""),"FIRST_OPERATION_FAILED");return this.trackPerformance(e,t,s,r),s}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:0,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid first input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}inferResultTypeLocal(e){return void 0===e?"Undefined":null===e?"Null":xt(e)?"String":kt(e)?"Number":At(e)?"Boolean":Array.isArray(e)?"Array":e instanceof HTMLElement?"Element":"Object"}},new class extends Qt{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=zr,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:0,error:n.errors[0]};const s=this.normalizeCollection(t.collection),i=s.length>0?s[s.length-1]:void 0,o={success:1,value:i,type:Wr[this.inferResultTypeLocal(i)]};return this.trackPerformance(e,t,o,r),o}catch(n){const s=this.failure("LastExpressionError","runtime-error","Last operation failed: "+(n instanceof Error?n.message:n+""),"LAST_OPERATION_FAILED");return this.trackPerformance(e,t,s,r),s}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:0,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid last input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}inferResultTypeLocal(e){return void 0===e?"Undefined":null===e?"Null":xt(e)?"String":kt(e)?"Number":At(e)?"Boolean":Array.isArray(e)?"Array":e instanceof HTMLElement?"Element":"Object"}},new class extends Qt{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=Jr,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:0,error:n.errors[0]};const s=this.normalizeCollection(t.collection),i=this.normalizeIndex(t.index,s.length),o=i>=0&&s.length>i?s[i]:void 0,a={success:1,value:o,type:Wr[this.inferResultTypeLocal(o)]};return this.trackPerformance(e,t,a,r),a}catch(n){const s=this.failure("AtExpressionError","runtime-error","At operation failed: "+(n instanceof Error?n.message:n+""),"AT_OPERATION_FAILED");return this.trackPerformance(e,t,s,r),s}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:0,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid at input: "+e.message,suggestions:[]}))??[],suggestions:["Provide collection and index parameters","Ensure index is a number"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}normalizeIndex(e,t){return 0>e?t+e:e}inferResultTypeLocal(e){return void 0===e?"Undefined":null===e?"Null":xt(e)?"String":kt(e)?"Number":At(e)?"Boolean":Array.isArray(e)?"Array":e instanceof HTMLElement?"Element":"Object"}},new class extends Qt{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=Zr,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:0,error:n.errors[0]};const s=this.normalizeCollection(t.collection);if(0===s.length){const n={success:1,value:void 0,type:"undefined"};return this.trackPerformance(e,t,n,r),n}const i=s[this.getSecureRandomIndex(s.length)],o={success:1,value:i,type:Wr[this.inferResultTypeLocal(i)]};return this.trackPerformance(e,t,o,r),o}catch(n){const s=this.failure("RandomExpressionError","runtime-error","Random operation failed: "+(n instanceof Error?n.message:n+""),"RANDOM_OPERATION_FAILED");return this.trackPerformance(e,t,s,r),s}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:0,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid random input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}getSecureRandomIndex(e){if("undefined"!=typeof crypto&&crypto.getRandomValues){const t=new Uint32Array(1);return crypto.getRandomValues(t),t[0]%e}return Math.floor(Math.random()*e)}inferResultTypeLocal(e){return void 0===e?"Undefined":null===e?"Null":xt(e)?"String":kt(e)?"Number":At(e)?"Boolean":Array.isArray(e)?"Array":e instanceof HTMLElement?"Element":"Object"}};const Kr={first:{name:"first",category:"Reference",evaluatesTo:"Any",operators:["first"],async evaluate(e,t){const r=void 0!==t?t:e.it;return null==r?null:Array.isArray(r)||r instanceof NodeList||r instanceof HTMLCollection?r.length>0?r[0]:null:r instanceof Element?r.children.length>0?r.children[0]:null:xt(r)?r.length>0?r[0]:null:St(r)&&"length"in r&&kt(r.length)&&r.length>0?r[0]:null},validate:e=>Bt(e,1,"first","collection")},last:{name:"last",category:"Reference",evaluatesTo:"Any",operators:["last"],async evaluate(e,t){const r=void 0!==t?t:e.it;if(null==r)return null;if(Array.isArray(r))return r.length>0?r[r.length-1]:null;if(r instanceof NodeList||r instanceof HTMLCollection)return r.length>0?r[r.length-1]:null;if(r instanceof Element){const e=r.children;return e.length>0?e[e.length-1]:null}return xt(r)?r.length>0?r[r.length-1]:null:St(r)&&"length"in r&&kt(r.length)&&r.length>0?r[r.length-1]:null},validate:e=>Bt(e,1,"last","collection")},at:{name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(e,...t){const[r,n]=t;if(!kt(r))throw Error("Index must be a number");const s=r,i=void 0!==n?n:e.it;if(null==i)return null;if(Array.isArray(i)){const e=0>s?i.length+s:s;return e>=0&&i.length>e?i[e]:null}if(i instanceof NodeList||i instanceof HTMLCollection){const e=0>s?i.length+s:s;return e>=0&&i.length>e?i[e]:null}if(i instanceof Element){const e=i.children,t=0>s?e.length+s:s;return t>=0&&e.length>t?e[t]:null}if(xt(i)){const e=0>s?i.length+s:s;return e>=0&&i.length>e?i[e]:null}if(St(i)&&"length"in i&&kt(i.length)){const e=0>s?i.length+s:s;return e>=0&&i.length>e?i[e]:null}return null},validate:e=>Pt(e,1,2,"at","index, optional collection")??function(e){return"number"!=typeof e[0]?"at index must be a number":null}(e)},next:{name:"next",category:"Reference",evaluatesTo:"Element",operators:["next"],async evaluate(e,...t){const[r,n]=t,s=n||e.me;return s&&s instanceof Element?r?Gr(s,r):s.nextElementSibling:null},validate:e=>Bt(e,2,"next","optional selector, optional fromElement")||(1>e.length||null==e[0]||"string"==typeof e[0]?2>e.length||null==e[1]||e[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(e,...t){const[r,n]=t,s=n||e.me;return s&&s instanceof Element?r?Yr(s,r):s.previousElementSibling:null},validate:e=>Bt(e,2,"previous","optional selector, optional fromElement")||(1>e.length||null==e[0]||"string"==typeof e[0]?2>e.length||null==e[1]||e[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(e,...t){const[r,n,s]=t,i=s||e.me;if(!(i&&i instanceof Element))return null;const o=i.closest(n);return o?function(e,t,r){const n=Array.from(r.querySelectorAll(t)),s=Xr(e);for(const e of n)if(Xr(e)>s)return e;return null}(i,r,o):null},validate:e=>Pt(e,2,3,"nextWithin","selector, withinSelector, optional fromElement")||("string"!=typeof e[0]?"selector must be a string":"string"!=typeof e[1]?"withinSelector must be a string":3>e.length||null==e[2]||e[2]instanceof Element?null:"fromElement must be an Element")},previousWithin:{name:"previousWithin",category:"Reference",evaluatesTo:"Element",operators:["previous within"],async evaluate(e,...t){const[r,n,s]=t,i=s||e.me;if(!(i&&i instanceof Element))return null;const o=i.closest(n);return o?function(e,t,r){const n=Array.from(r.querySelectorAll(t)),s=Xr(e);for(let e=n.length-1;e>=0;e--){const t=n[e];if(s>Xr(t))return t}return null}(i,r,o):null},validate:e=>Pt(e,2,3,"previousWithin","selector, withinSelector, optional fromElement")||("string"!=typeof e[0]?"selector must be a string":"string"!=typeof e[1]?"withinSelector must be a string":3>e.length||null==e[2]||e[2]instanceof Element?null:"fromElement must be an Element")}},Qr={possessive:{name:"possessive",category:"Reference",evaluatesTo:"Any",operators:["'s","s"],async evaluate(e,...t){const[r,n]=t;if(null!=r){if("string"!=typeof n)throw Error("Property name must be a string");return r instanceof Element?Lt(r,n):(St(r),r[n])}},validate:e=>It(e,2,"possessive","element, property")??jt(e,1,"possessive","property name")},my:{name:"my",category:"Reference",evaluatesTo:"Any",operators:["my"],async evaluate(e,...t){const[r]=t;if(e.me){if("string"!=typeof r)throw Error("Property name must be a string");return e.me instanceof Element?Lt(e.me,r):(St(e.me),e.me[r])}},validate:e=>Mt(e,"my","property")},its:{name:"its",category:"Reference",evaluatesTo:"Any",operators:["its"],async evaluate(e,...t){const[r]=t;if(null==e.it)return;if("string"!=typeof r)throw Error("Property name must be a string");const n=e.it;return n instanceof Element?Lt(n,r):(St(n),n[r])},validate:e=>Mt(e,"its","property")},your:{name:"your",category:"Reference",evaluatesTo:"Any",operators:["your"],async evaluate(e,...t){const[r]=t;if(e.you){if("string"!=typeof r)throw Error("Property name must be a string");return e.you instanceof Element?Lt(e.you,r):(St(e.you),e.you[r])}},validate:e=>Mt(e,"your","property")},of:{name:"of",category:"Reference",evaluatesTo:"Any",operators:["of"],async evaluate(e,...t){const[r,n]=t;if(null!=n){if("string"!=typeof r)throw Error("Property name must be a string");return n instanceof Element?Lt(n,r):(St(n),n[r])}},validate:e=>It(e,2,"of","property, object")??jt(e,0,"of","property name")},attribute:{name:"attribute",category:"Reference",evaluatesTo:"String",operators:["@"],async evaluate(e,...t){const[r,n]=t;if("string"!=typeof r)throw Error("Attribute name must be a string");const s=n||e.me;return s&&s instanceof Element?s.getAttribute(r):null},validate:e=>Pt(e,1,2,"attribute","attributeName, optional element")??jt(e,0,"attribute","attribute name")??(2>e.length||null==e[1]||e[1]instanceof Element?null:"attribute element must be an Element")},attributeWithValue:{name:"attributeWithValue",category:"Reference",evaluatesTo:"Boolean",operators:["@="],async evaluate(e,...t){const[r,n,s]=t;if("string"!=typeof r)throw Error("Attribute name must be a string");if("string"!=typeof n)throw Error("Expected value must be a string");const i=s||e.me;return i&&i instanceof Element?i.getAttribute(r)===n:0},validate:e=>Pt(e,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??jt(e,0,"attributeWithValue","attribute name")??jt(e,1,"attributeWithValue","expected value")??(3>e.length||null==e[2]||e[2]instanceof Element?null:"attributeWithValue element must be an Element")},classReference:{name:"classReference",category:"Reference",evaluatesTo:"Array",operators:["."],async evaluate(e,...t){const[r]=t;if("string"!=typeof r)throw Error("Class name must be a string");const n=r.startsWith(".")?r.slice(1):r,s=document.getElementsByClassName(n);return Array.from(s)},validate:e=>Mt(e,"classReference","className")},idReference:{name:"idReference",category:"Reference",evaluatesTo:"Element",operators:["#"],async evaluate(e,...t){const[r]=t;if("string"!=typeof r)throw Error("ID value must be a string");const n=r.startsWith("#")?r.slice(1):r;return document.getElementById(n)},validate:e=>Mt(e,"idReference","idValue")}},en=Zt({value:Wt().describe("String literal value")}).strict(),tn=Zt({value:zt().describe("Number literal value")}).strict(),rn=Zt({value:Jt().describe("Boolean literal value")}).strict(),nn=Zt({left:Yt().describe("Left operand"),right:Yt().describe("Right operand")}).strict(),sn={stringLiteral:new class extends Qt{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=en,this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid){const t=this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions);return this.trackSimple(e,r,0),t}let s=t.value;(s.includes("${")||s.includes("$"))&&(s=this.interpolateString(s,e));const i=this.success(s,"string");return this.trackSimple(e,r,1,s),i}catch(t){return this.trackSimple(e,r,0),this.failure("StringEvaluationError","runtime-error","String literal evaluation failed: "+(t instanceof Error?t.message:t+""),"STRING_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid string literal input",["Provide a value parameter","Ensure value is a string"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}interpolateString(e,t){let r=e.replace(/\$\{([^}]+)\}/g,(e,r)=>{try{const e=this.resolveExpression(r.trim(),t);return void 0!==e?e+"":""}catch(e){return""}});return r=r.replace(/\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g,(e,r)=>{try{const e=this.resolveVariable(r,t);return void 0!==e?e+"":""}catch(e){return""}}),r}resolveExpression(e,t){if(e.includes(".")){const r=e.split(".");let n=this.resolveVariable(r[0],t);for(let e=1;r.length>e&&null!=n;e++)n=n[r[e]];return n}return this.resolveVariable(e,t)}resolveVariable(e,t){return"me"===e&&t.me?t.me:"you"===e&&t.you?t.you:"it"===e&&t.it?t.it:"result"===e&&t.result?t.result:t.locals?.has(e)?t.locals.get(e):t.globals?.has(e)?t.globals.get(e):void 0}},numberLiteral:new class extends Qt{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=tn,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);return n.isValid?isFinite(t.value)?(this.trackSimple(e,r,1,t.value),this.success(t.value,"number")):(this.trackSimple(e,r,0),this.failure("NumberValidationError","invalid-argument","Number literal must be finite","NUMBER_NOT_FINITE")):(this.trackSimple(e,r,0),this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions))}catch(t){return this.trackSimple(e,r,0),this.failure("NumberEvaluationError","runtime-error","Number literal evaluation failed: "+(t instanceof Error?t.message:t+""),"NUMBER_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?isFinite(t.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",t.error?.errors.map(e=>e.message).join(", ")||"Invalid number literal input",["Provide a value parameter","Ensure value is a number"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},booleanLiteral:new class extends Qt{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=rn,this.outputType="Boolean",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);return n.isValid?(this.trackSimple(e,r,1,t.value),this.success(t.value,"boolean")):(this.trackSimple(e,r,0),this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions))}catch(t){return this.trackSimple(e,r,0),this.failure("BooleanEvaluationError","runtime-error","Boolean literal evaluation failed: "+(t instanceof Error?t.message:t+""),"BOOLEAN_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid boolean literal input",["Provide a value parameter","Ensure value is a boolean"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},addition:new class extends Qt{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=nn,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return this.trackSimple(e,r,0),this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions);const s=ar(t.left,"left operand")+ar(t.right,"right operand");return this.trackSimple(e,r,1,s),this.success(s,"number")}catch(t){return this.trackSimple(e,r,0),this.failure("AdditionError","runtime-error","Addition failed: "+(t instanceof Error?t.message:t+""),"ADDITION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid addition input",["Provide left and right operands"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},stringConcatenation:new class extends Qt{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=nn,this.outputType="String",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return this.trackSimple(e,r,0),this.failure("ValidationError","validation-error",n.errors[0]?.message||"Invalid input","STRING_CONCATENATION_VALIDATION_FAILED",n.suggestions);const s=this.convertToString(t.left)+this.convertToString(t.right);return this.trackSimple(e,r,1,s),this.success(s,"string")}catch(t){return this.trackSimple(e,r,0),this.failure("StringConcatenationError","runtime-error",t instanceof Error?t.message:"String concatenation failed","STRING_CONCATENATION_ERROR",["Check that operands can be converted to strings"])}}validate(e){const t=nn.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid string concatenation input",["Provide left and right operands for concatenation"])}convertToString(e){if(null===e)return"null";if(void 0===e)return"undefined";if(xt(e))return e;if(kt(e))return""+e;if(At(e))return""+e;if(e instanceof Date)return""+e;try{return e+""}catch{return"[object Object]"}}},multiplication:new class extends Qt{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=nn,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return this.trackSimple(e,r,0),this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions);const s=ar(t.left,"left operand")*ar(t.right,"right operand");return this.trackSimple(e,r,1,s),this.success(s,"number")}catch(t){return this.trackSimple(e,r,0),this.failure("MultiplicationError","runtime-error","Multiplication failed: "+(t instanceof Error?t.message:t+""),"MULTIPLICATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid multiplication input",["Provide left and right operands"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}};class on extends $t{constructor(){super(),this.registerExpressions()}registerExpressions(){this.registerCategory(tr),this.registerCategory(jr),this.registerCategory(Hr),this.registerCategory(Kr),de("About to register properties expressions:",Object.keys(Qr)),this.registerCategory(Qr),de("Total expressions registered:",this.expressionRegistry.size),de('Registry has "possessive":',this.expressionRegistry.has("possessive")),de('Registry has "my":',this.expressionRegistry.has("my")),this.registerCategory(sn)}}class an{static toTyped(e){return{me:e.me,it:e.it,you:e.you,result:e.result,...void 0!==e.event&&{event:e.event},variables:e.variables||new Map,locals:e.locals||new Map,globals:e.globals||new Map,...void 0!==e.events&&{events:e.events},meta:e.meta||{},expressionStack:[],evaluationDepth:0,validationMode:"strict",evaluationHistory:[]}}static fromTyped(e,t){return{...t,me:e.me,it:e.it,you:e.you,result:e.result,...void 0!==e.event&&{event:e.event},...void 0!==e.variables&&{variables:e.variables},locals:e.locals,globals:e.globals,...void 0!==e.events&&{events:e.events},...void 0!==e.meta&&{meta:e.meta}}}}class cn{constructor(e,t,r){this.impl=e,this.expressionEvaluator=t??new on,this.hookRegistry=r??null}createHookContext(e,t,r={}){return{commandName:this.name,element:e.me instanceof Element?e.me:null,args:t,modifiers:r,event:e.event??void 0,executionContext:e}}get name(){return this.impl.name||this.impl.metadata?.name}get metadata(){return{description:this.impl.metadata?.description||"",examples:this.impl.metadata?.examples||[],syntax:this.impl.metadata?.syntax||""}}async execute(e,...t){const r=t[0],n=this.createHookContext(e,t,r&&"object"==typeof r&&"modifiers"in r&&r.modifiers||{});try{if(ue(`CommandAdapterV2: Executing '${this.name}' with args:`,t),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(n),this.hookRegistry?.shouldIntercept(this.name,n))return void ue(`CommandAdapterV2: '${this.name}' intercepted by hook`);e.locals||(e.locals=new Map),e.locals.set("__evaluator",this.expressionEvaluator);const s=an.toTyped(e);let i,o;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(ue(`CommandAdapterV2: '${this.name}' has parseInput(), calling it`),r&&"object"==typeof r&&("args"in r||"modifiers"in r)){const t=r.modifiers?.when||r.modifiers?.where;if(t&&!await this.expressionEvaluator.evaluate(t,e))return void ue(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);i=await this.impl.parseInput({args:r.args||[],modifiers:r.modifiers||{},commandName:r.commandName},this.expressionEvaluator,e)}else i=t;else ue(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),i=t;return ue("CommandAdapterV2: Calling execute with parsed input:",i),o=2===this.impl.execute.length?await this.impl.execute(i,s):await this.impl.execute(s,...i),ue("CommandAdapterV2: Command result:",o),Object.assign(e,an.fromTyped(s,e)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(n,o),o}catch(e){if(ue(`CommandAdapterV2: Error executing '${this.name}':`,e),this.hookRegistry&&e instanceof Error)throw await this.hookRegistry.runOnError(n,e);throw e}}validate(e){return this.impl.validate?this.impl.validate(e):{isValid:1,errors:[],suggestions:[]}}}class ln{constructor(e,t){this.adapters=new Map,this.implementations=new Map,this.sharedEvaluator=e,this.hookRegistry=t}setHookRegistry(e){this.hookRegistry=e,me("CommandRegistryV2: Hook registry set")}getHookRegistry(){return this.hookRegistry}register(e){const t=(e.name||e.metadata?.name).toLowerCase();me(`CommandRegistryV2: Registering command '${t}'`),this.implementations.set(t,e);const r=new cn(e,this.sharedEvaluator,this.hookRegistry);this.adapters.set(t,r);const n=e.metadata?.aliases;if(n&&Array.isArray(n))for(const t of n){const n=t.toLowerCase();this.implementations.set(n,e),this.adapters.set(n,r)}}getAdapter(e){return this.adapters.get(e.toLowerCase())}has(e){return this.adapters.has(e.toLowerCase())}getCommandNames(){return Array.from(this.adapters.keys())}getImplementation(e){return this.implementations.get(e.toLowerCase())}getAdapters(){return new Map(this.adapters)}validateCommand(e,t){const r=this.getAdapter(e);return r?r.validate(t):{isValid:0,errors:[{type:"runtime-error",message:"Unknown command: "+e,suggestions:["Available commands: "+this.getCommandNames().join(", ")]}],suggestions:["Available commands: "+this.getCommandNames().join(", ")]}}}let un=null;function hn(){return un||(un=function(){const e=new ln,t=new bt,r=new Et,n=new Set,s={commands:e,eventSources:t,context:r,use(i){if(n.has(i.name))console.warn(`[LokaScriptRegistry] Plugin '${i.name}' is already installed`);else{if(i.commands)for(const t of i.commands)e.register(t);if(i.eventSources)for(const e of i.eventSources)t.register(e.name,e);if(i.contextProviders)for(const{name:e,provide:t,options:n}of i.contextProviders)r.register(e,t,n);i.setup?.(s),n.add(i.name)}},reset(){n.clear()}};return s}()),un}class fn{constructor(e={}){this.contextCache=new WeakMap;const t=hn();this.options={enableContextProviders:e.enableContextProviders??1,enableEventSources:e.enableEventSources??1,registry:e.registry??{}},this.contextRegistry=this.options.registry.context??t.context,this.eventSourceRegistry=this.options.registry.eventSources??t.eventSources,me(`[RegistryIntegration] Initialized (context=${this.options.enableContextProviders}, events=${this.options.enableEventSources})`)}enhanceContext(e){if(!this.options.enableContextProviders)return e;const t=this.contextCache.get(e);if(t)return t;try{const t=this.contextRegistry.enhance(e);return this.contextCache.set(e,t),me(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),t}catch(t){return me("[RegistryIntegration] Failed to enhance context: "+(t instanceof Error?t.message:t+"")),e}}getEventSource(e){if(!this.options.enableEventSources)return;const t=this.eventSourceRegistry.get(e);if(t)return me(`[RegistryIntegration] Found event source for '${e}'`),t;const r=this.eventSourceRegistry.findSourceForEvent(e);if(r){const t=this.eventSourceRegistry.get(r);return me(`[RegistryIntegration] Found event source '${r}' supporting '${e}'`),t}}hasEventSource(e){return void 0!==this.getEventSource(e)}subscribeToEventSource(e,t,r){if(!this.options.enableEventSources)throw Error("Event sources are disabled in this runtime");const n=this.eventSourceRegistry.subscribe(e,t,r);if(!n)throw Error(`Failed to subscribe to event source '${e}'`);return me(`[RegistryIntegration] Subscribed to '${e}' event '${t.event}' (id: ${n.id})`),n}getEventSourceNames(){return this.eventSourceRegistry.getSourceNames()}getContextProviderNames(){return this.contextRegistry.getProviderNames()}destroy(){this.eventSourceRegistry.destroy(),this.contextCache=new WeakMap,me("[RegistryIntegration] Destroyed")}}class dn{constructor(e){this.autoCleanupObserver=null,this.registryIntegration=null,this.options={commandTimeout:1e4,enableErrorReporting:1,enableResultPattern:1,enableAutoCleanup:1,...e},this.registry=e.registry,this.expressionEvaluator=e.expressionEvaluator,this.behaviorRegistry=new Map,this.globalVariables=vt,this.hookRegistry=new ft,e.hooks&&this.hookRegistry.register("default",e.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new yt,this.options.enableAutoCleanup&&this.setupAutoCleanup(),0!=e.registryIntegration&&(this.registryIntegration=new fn("object"==typeof e.registryIntegration?e.registryIntegration:{}),me("RuntimeBase: Registry integration enabled")),this.behaviorAPI={has:e=>this.behaviorRegistry.has(e),get:e=>this.behaviorRegistry.get(e),install:async(e,t,r)=>await this.installBehaviorOnElement(e,t,r)}}setupAutoCleanup(){"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.autoCleanupObserver=new MutationObserver(e=>{for(const t of e)for(const e of t.removedNodes)if(e instanceof Element){const t=this.cleanupRegistry.cleanupElementTree(e);t>0&&me(`RuntimeBase: Auto-cleaned ${t} 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(e,t){this.hookRegistry.register(e,t)}unregisterHooks(e){return this.hookRegistry.unregister(e)}getRegisteredHooks(){return this.hookRegistry.getRegisteredNames()}cleanup(e){return this.cleanupRegistry.cleanupElement(e)}cleanupTree(e){return this.cleanupRegistry.cleanupElementTree(e)}getCleanupStats(){return this.cleanupRegistry.getStats()}destroy(){this.autoCleanupObserver&&(this.autoCleanupObserver.disconnect(),this.autoCleanupObserver=null),this.cleanupRegistry.cleanupAll(),this.hookRegistry.clear(),this.behaviorRegistry.clear(),me("RuntimeBase: Destroyed")}async execute(e,t){me(`RUNTIME BASE: execute() called with node type: '${e.type}'`),t.locals.has("_behaviors")||t.locals.set("_behaviors",this.behaviorAPI),t.locals.has("_runtimeExecute")||t.locals.set("_runtimeExecute",(e,r)=>this.execute(e,r||t));try{switch(e.type){case"command":if(this.options.enableResultPattern)try{const r=await this.processCommandWithResult(e,t);if(!mt(r)){const e=r.error,t=Error(e.type.toUpperCase()+"_EXECUTION");throw t["is"+e.type.charAt(0).toUpperCase()+e.type.slice(1)]=1,"returnValue"in e&&(t.returnValue=e.returnValue),t}return r.value}catch(e){throw e}return await this.processCommand(e,t);case"eventHandler":return await this.executeEventHandler(e,t);case"event":{const r={type:"eventHandler",event:e.event,events:[e.event],commands:e.body||[],target:e.filter,modifiers:e.modifiers||{}};return await this.executeEventHandler(r,t)}case"behavior":return await this.executeBehaviorDefinition(e,t);case"Program":return await this.executeProgram(e,t);case"initBlock":case"block":return await this.executeBlock(e,t);case"sequence":case"CommandSequence":if(this.options.enableResultPattern){const r=e,n=await this.executeCommandSequenceWithResult(r.commands||[],t);if(!mt(n)){const e=n.error,t=Error(e.type.toUpperCase()+"_EXECUTION");throw t["is"+e.type.charAt(0).toUpperCase()+e.type.slice(1)]=1,"returnValue"in e&&(t.returnValue=e.returnValue),t}return n.value}return await this.executeCommandSequence(e,t);case"objectLiteral":return await this.executeObjectLiteral(e,t);default:if(this.options.enableResultPattern){const r=await this.evaluateExpressionWithResult(e,t);if(!mt(r)){const e=r.error,t=Error(e.type.toUpperCase()+"_EXECUTION");throw t["is"+e.type.charAt(0).toUpperCase()+e.type.slice(1)]=1,"returnValue"in e&&(t.returnValue=e.returnValue),t}return r.value}return await this.evaluateExpression(e,t)}}catch(e){throw e}}async processCommand(e,t){const{name:r,args:n,modifiers:s}=e,i=r.toLowerCase();if(ue(`RUNTIME BASE: Processing command '${i}'`),console.log("[RUNTIME DEBUG] executeCommand called with:",i),this.registry.has(i)){console.log("[RUNTIME DEBUG] Found command:",i);const e=await this.registry.getAdapter(i);if(!e)throw Error(`Command '${i}' is registered but failed to load adapter.`);try{return await e.execute(t,{args:n||[],modifiers:s||{},commandName:i,runtime:this})}catch(e){throw e instanceof Error&&(1==e.isHalt||1==e.isExit||"HALT_EXECUTION"===e.message||"EXIT_COMMAND"===e.message)||console.error(`Error executing command '${i}':`,e),e}}const o=`Unknown command: ${r}. Ensure it is registered in the Runtime options.`;throw this.options.enableErrorReporting&&console.warn(o),Error(o)}toSignal(e){if(e instanceof Error){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}}return null}async processCommandWithResult(e,t){const{name:r,args:n,modifiers:s}=e,i=r.toLowerCase();if(ue(`RUNTIME BASE (Result): Processing command '${i}'`),!this.registry.has(i)){const e=`Unknown command: ${r}. Ensure it is registered in the Runtime options.`;throw this.options.enableErrorReporting&&console.warn(e),Error(e)}const o=await this.registry.getAdapter(i);if(!o)throw Error(`Command '${i}' is registered but failed to load adapter.`);try{return dt(await o.execute(t,{args:n||[],modifiers:s||{},commandName:i,runtime:this}))}catch(e){const t=this.toSignal(e);if(t)return pt(t);throw console.error(`Error executing command '${i}':`,e),e}}async executeCommandSequenceWithResult(e,t){let r;for(const n of e)if("command"===n.type){const e=await this.processCommandWithResult(n,t);if(!mt(e)){const r=e.error;switch(r.type){case"halt":case"exit":case"break":case"continue":return e;case"return":return void 0!==r.returnValue&&Object.assign(t,{it:r.returnValue,result:r.returnValue}),dt(r.returnValue)}}r=e.value}else{const e=await this.evaluateExpressionWithResult(n,t);if(!mt(e))return e;r=e.value}return dt(r)}async evaluateExpression(e,t){const r=await this.expressionEvaluator.evaluate(e,t);return r&&"object"==typeof r&&r.command&&r.selector?await this.executeCommandFromPattern(r.command,r.selector,t):r}async evaluateExpressionWithResult(e,t){const r=await this.expressionEvaluator.evaluateWithResult(e,t);if(!mt(r))return r;const n=r.value;if(n&&"object"==typeof n&&n.command&&n.selector){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:n.command,args:[{type:"literal",value:n.selector}]},t);try{return dt(await this.executeCommandFromPattern(n.command,n.selector,t))}catch(e){const t=this.toSignal(e);if(t)return pt(t);throw e}}return dt(n)}async executeCommandFromPattern(e,t,r){return this.processCommand({type:"command",name:e,args:[{type:"literal",value:t}]},r)}async executeProgram(e,t){if(!e.statements||!Array.isArray(e.statements))return;let r;const n=[],s=[],i=[];for(const t of e.statements)"eventHandler"===t.type?n.push(t):"initBlock"===t.type?s.push(t):i.push(t);for(const e of n)try{await this.execute(e,t)}catch(e){if(e instanceof Error&&(e.isHalt||e.isExit))break;throw e}for(const e of s)try{r=await this.execute(e,t)}catch(e){if(e instanceof Error&&(e.isHalt||e.isExit))break;throw e}for(const e of i)try{r=await this.execute(e,t)}catch(e){if(e instanceof Error&&(e.isHalt||e.isExit))break;throw e}return r}async executeBlock(e,t){if(e.commands&&Array.isArray(e.commands))for(const r of e.commands)try{await this.execute(r,t)}catch(e){if(e instanceof Error&&e.isHalt)break;throw e}}async executeCommandSequence(e,t){if(!e.commands||!Array.isArray(e.commands))return;let r;for(const n of e.commands)try{r=await this.execute(n,t)}catch(e){const r=e;if(r.isHalt||r.isExit)break;if(r.isReturn){if(void 0!==r.returnValue)return Object.assign(t,{it:r.returnValue,result:r.returnValue}),r.returnValue;break}if(r.isBreak)throw e;throw e}return r}async executeObjectLiteral(e,t){const r={};if(!e.properties)return r;for(const n of e.properties){let e;e="identifier"===n.key.type?n.key.name:"literal"===n.key.type?n.key.value+"":await this.execute(n.key,t)+"";const s=await this.execute(n.value,t);r[e]=s}return r}enhanceContext(e){return this.registryIntegration?this.registryIntegration.enhanceContext(e):e}async executeBehaviorDefinition(e,t){const{name:r,parameters:n,eventHandlers:s,initBlock:i}=e;this.behaviorRegistry.set(r,{name:r,parameters:n,eventHandlers:s,initBlock:i}),me(`RUNTIME BASE: Registered behavior '${r}'`)}async installBehaviorOnElement(e,t,r){me("BEHAVIOR: installBehaviorOnElement called: "+e);const n=this.behaviorRegistry.get(e);if(!n)throw Error(`Behavior "${e}" not found`);me("BEHAVIOR: Found behavior, eventHandlers count: "+(n.eventHandlers?.length||0));const s={me:t,you:null,it:null,result:null,locals:new Map,globals:this.globalVariables,halted:0,returned:0,broke:0,continued:0,async:0},i=this.enhanceContext(s);if(n.parameters)for(const e of n.parameters)i.locals.set(e,e in r?r[e]:void 0);for(const[e,t]of Object.entries(r))n.parameters?.includes(e)||i.locals.set(e,t);if(n.initBlock){me("BEHAVIOR: Running init block for "+e);try{await this.execute(n.initBlock,i),me("BEHAVIOR: Init block completed for "+e)}catch(t){if(me(`BEHAVIOR: Init block error for ${e}:`,t),!(t instanceof Error&&t.isHalt))throw t}}if(me(`BEHAVIOR: About to attach ${n.eventHandlers?.length||0} handlers for ${e}`),n.eventHandlers)for(const e of n.eventHandlers)await this.executeEventHandler(e,i);me("BEHAVIOR: Finished installing "+e)}async executeEventHandler(e,t){const{event:r,events:n,commands:s,target:i,args:o,selector:a,attributeName:c,watchTarget:l,modifiers:u}=e,h=n&&n.length>0?n:[r];me(`BEHAVIOR: executeEventHandler: event='${r}', target='${i}'`);let f=[],d=null;if(i){const e="string"==typeof i?i.toLowerCase():"";if("window"===e||"the window"===e)d=window;else if("document"===e||"the document"===e||"body"===e)d=document;else if("me"===e||"myself"===e)f=t.me?[t.me]:[];else if("string"==typeof i&&t.locals.has(i)){const e=t.locals.get(i);me(`BEHAVIOR: Target resolution: found local '${i}', isElement: ${this.isElement(e)}`),this.isElement(e)?f=[e]:Array.isArray(e)?f=e.filter(e=>this.isElement(e)):"string"==typeof e&&(f=this.queryElements(e,t))}else me(`BEHAVIOR: Target resolution: querying for '${i}'`),f=this.queryElements(i,t)}else f=t.me?[t.me]:[];if(0===f.length&&!d)return void me(`BEHAVIOR: executeEventHandler - No targets found for event '${r}', returning early`);if("mutation"===r&&c)return void this.setupMutationObserver(f,c,s,t);if("change"===r&&l)return void this.setupChangeObserver(l,s,t);const p=e.customEventSource;if(p&&this.registryIntegration){me(`BEHAVIOR: executeEventHandler - Using custom event source '${p}' for event '${r}'`);const e=async e=>{const n=new Map(t.locals),i={...t,locals:n,it:e,event:e},o=this.enhanceContext(i);me(`CUSTOM EVENT: Executing commands for event '${r}'`);try{await this.execute({type:"program",commands:s},o)}catch(e){console.error(`[HyperFixi] Error executing commands for custom event '${r}':`,e)}};try{const n=this.registryIntegration.subscribeToEventSource(p,{event:r,handler:e,target:i,selector:a},t);me(`BEHAVIOR: Subscribed to custom event source '${p}' (id: ${n.id})`),this.cleanupRegistry.registerGlobal(()=>n.unsubscribe(),"listener",`Custom event source '${p}' subscription ${n.id}`)}catch(e){console.error(`[HyperFixi] Failed to subscribe to custom event source '${p}':`,e)}return}const m=async e=>{const r=e.l||0;if(r>=100)return;if(e.l=r+1,a&&e.target instanceof Element&&!e.target.matches(a)&&!e.target.closest(a))return;const n=new Map(t.locals),i={...t,locals:n,it:e,event:e};n.has("target")||i.locals.set("target",e.target);const c=this.enhanceContext(i);if(o&&o.length>0)for(const t of o)c.locals.set(t,e[t]||e.detail?.[t]||null);for(const e of s)try{const t=await this.execute(e,c);if(void 0!==t){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){void 0!==e&&Object.assign(c,{it:e,result:e});continue}}else if("lastResult"in t&&"type"in t)e=t.lastResult;else if("conditionResult"in t&&"executedBranch"in t){if(void 0===t.result)continue;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)}Array.isArray(e)&&e.length>0&&(e=e[0]),Object.assign(c,{it:e,result:e})}}catch(e){const t=e;if(t.isHalt||t.isExit)break;if(t.isReturn){void 0!==t.returnValue&&Object.assign(c,{it:t.returnValue,result:t.returnValue});break}throw console.error("COMMAND FAILED:",e),e}};let y;if(u){let e=m;if(u.prevent){const t=e;e=async e=>(e.preventDefault(),t(e))}if(u.stop){const t=e;e=async e=>(e.stopPropagation(),t(e))}if(u.debounce){const t=u.debounce;let r;y=n=>{r&&clearTimeout(r),r=setTimeout(()=>e(n),t)}}else if(u.throttle){const t=u.throttle;let r=0;y=n=>{const s=Date.now();t>s-r||(r=s,e(n))}}else y=e}else y=m;const v=u?.once?{once:1}:void 0;if(d)for(const e of h)d.addEventListener(e,y,v),f.length>0?this.cleanupRegistry.registerListener(f[0],d,e,y):this.cleanupRegistry.registerGlobal(()=>d.removeEventListener(e,y),"listener",`Global ${e} listener`);else for(const e of f)for(const t of h)e.addEventListener(t,y,v),this.cleanupRegistry.registerListener(e,e,t,y)}setupMutationObserver(e,t,r,n){me(`RUNTIME BASE: Setting up MutationObserver for attribute '${t}' on ${e.length} elements`);for(const s of e){const e=new MutationObserver(async e=>{for(const i of e)if("attributes"===i.type&&i.attributeName===t){he(`MUTATION DETECTED: attribute '${t}' changed on`,s);const e={...n,me:s,it:i,locals:new Map(n.locals)},o=i.oldValue,a=s.getAttribute(t);e.locals.set("oldValue",o),e.locals.set("newValue",a);const c=this.enhanceContext(e);for(const e of r)try{await this.execute(e,c)}catch(e){console.error("❌ Error executing mutation handler command:",e)}}});e.observe(s,{attributes:1,attributeOldValue:1,attributeFilter:[t]}),this.cleanupRegistry.registerObserver(s,e),me("RUNTIME BASE: MutationObserver attached to",s,`for attribute '${t}'`)}}async setupChangeObserver(e,t,r){me("RUNTIME BASE: Setting up MutationObserver for content changes on watch target");const n=await this.execute(e,r);let s=[];this.isElement(n)?s=[n]:Array.isArray(n)&&(s=n.filter(e=>this.isElement(e))),me(`RUNTIME BASE: Watching ${s.length} target elements for content changes`);for(const e of s){const n=new MutationObserver(async n=>{for(const s of n)if("childList"===s.type||"characterData"===s.type){he("CONTENT CHANGE DETECTED on",e,"mutation type:",s.type);const n={...r,me:r.me,it:s,locals:new Map(r.locals)};n.locals.set("target",e);const i=s.oldValue,o=e.textContent;null!==i&&n.locals.set("oldValue",i),n.locals.set("newValue",o);const a=this.enhanceContext(n);for(const e of t)try{await this.execute(e,a)}catch(e){console.error("❌ Error executing change handler command:",e)}}});n.observe(e,{childList:1,characterData:1,subtree:1,characterDataOldValue:1}),this.cleanupRegistry.registerObserver(e,n),me("RUNTIME BASE: MutationObserver attached to",e,"for content changes")}}queryElements(e,t){const r=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!r)return[];let n=e;return n.startsWith("<")&&n.endsWith("/>")&&(n=n.slice(1,-2).trim()),Array.from(r.querySelectorAll(n))}isElement(e){return"undefined"!=typeof HTMLElement&&e instanceof HTMLElement?1:e&&"object"==typeof e&&e.style&&e.classList}}class pn{constructor(e){this.observer=null,this.initialized=0,this.runtime=e}init(){"undefined"!=typeof document&&(this.initialized||(this.initialized=1,this.scanDocument(),this.observer=new MutationObserver(e=>{for(const t of e)"childList"===t.type?t.addedNodes.forEach(e=>{e.nodeType===Node.ELEMENT_NODE&&(this.processElement(e),this.scanElement(e))}):"attributes"===t.type&&"_"===t.attributeName&&this.processElement(t.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(e){e.hasAttribute("_")&&this.processElement(e),e.querySelectorAll("[_]").forEach(e=>this.processElement(e))}processElement(e){const t=e.getAttribute("_");if(!t)return;const r=gt(e);this.runtime.execute(t,r).catch(r=>{console.error('[HyperFixi] Error executing _="" attribute:',r),console.error("Element:",e),console.error("Code:",t)})}}function mn(e,t,r,n,s,i){function o(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var a,c=n.kind,l="getter"===c?"get":"setter"===c?"set":"value",u=!t&&e?n.static?e:e.prototype:null,h=t||(u?Object.getOwnPropertyDescriptor(u,n.name):{}),f=0,d=r.length-1;d>=0;d--){var p={};for(var m in n)p[m]="access"===m?{}:n[m];for(var m in n.access)p.access[m]=n.access[m];p.addInitializer=function(e){if(f)throw new TypeError("Cannot add initializers after decoration has completed");i.push(o(e||null))};var y=(0,r[d])("accessor"===c?{get:h.get,set:h.set}:h[l],p);if("accessor"===c){if(void 0===y)continue;if(null===y||"object"!=typeof y)throw new TypeError("Object expected");(a=o(y.get))&&(h.get=a),(a=o(y.set))&&(h.set=a),(a=o(y.init))&&s.unshift(a)}else(a=o(y))&&("field"===c?s.unshift(a):h[l]=a)}u&&Object.defineProperty(u,n.name,h),f=1}function yn(e,t,r){for(var n=arguments.length>2,s=0;t.length>s;s++)r=n?t[s].call(e,r):t[s].call(e);return n?r:void 0}function vn(e,t,r){return"symbol"==typeof t&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:1,value:r?"".concat(r," ",t):t})}function gn(e){const t=e.trim();return t.startsWith("[@")&&t.endsWith("]")||t.startsWith("@")?1:0}function bn(e){const t=e.trim();if(t.startsWith("[@")&&t.endsWith("]")){const e=t.slice(2,-1),r=e.indexOf("=");if(-1===r)return{name:e.trim()};const n=e.slice(0,r).trim();let s=e.slice(r+1).trim();return(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),{name:n,value:s}}if(t.startsWith("@"))return{name:t.substring(1).trim()};throw Error("Invalid attribute syntax: "+e)}function En(e,t){for(const r of e)t(r);return e}function wn(e,t,r){for(const n of e)for(const e of t)r(n,e);return e}function xn(e,t,r){const n=e.hasAttribute(t);void 0!==r?n&&e.getAttribute(t)===r?e.removeAttribute(t):e.setAttribute(t,r):n?e.removeAttribute(t):e.setAttribute(t,"")}function kn(e){if(!e)return[];if("string"==typeof e)return e.trim().split(/[\s,]+/).map(e=>{const t=e.trim();return t.startsWith(".")?t.substring(1):t}).filter(e=>e.length>0&&Sn(e));if(Array.isArray(e))return e.map(e=>{const t=(e+"").trim();return t.startsWith(".")?t.substring(1):t}).filter(e=>e.length>0&&Sn(e));const t=(e+"").trim(),r=t.startsWith(".")?t.substring(1):t;return r.length>0&&Sn(r)?[r]:[]}function An(e){const t=e.trim();return/^\{[^}]+\}$/.test(t)}function Sn(e){if(!e||0===e.trim().length)return 0;const t=e.trim();return An(t)?1:/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(t)}function Cn(e,t){return e.map(e=>{if(An(e)){const r=function(e){const t=e.trim(),r=t.match(/^\{(.+)\}$/);return r?r[1].trim():t}(e),n=t.locals.get(r)??t.globals.get(r);return null!=n?n+"":(console.warn(`Dynamic class variable '${r}' not found in context`),"")}return e}).filter(e=>e.length>0)}"function"==typeof SuppressedError&&SuppressedError;const Tn=Symbol("command:name"),Nn=Symbol("command:category"),On=Symbol("command:metadata");function Ln(e){return function(t,r){const n=t;n[Tn]=e.name,n[Nn]=e.category,Object.defineProperty(t.prototype,"name",{value:e.name,writable:0,enumerable:1})}}function $n(e){return function(t,r){const n=t,s=n[Nn];if(!s)throw Error("@meta decorator requires @command decorator to be applied first on "+t.name);const i={description:e.description,syntax:e.syntax,examples:e.examples,category:s,sideEffects:e.sideEffects,deprecated:e.deprecated,deprecationMessage:e.deprecationMessage,aliases:e.aliases,relatedCommands:e.relatedCommands,isBlocking:e.isBlocking??0,hasBody:e.hasBody??0,version:"1.0.0"};n[On]=i,Object.defineProperty(t,"metadata",{value:i,writable:0,enumerable:1,configurable:0}),Object.defineProperty(t.prototype,"metadata",{get:()=>i,enumerable:1,configurable:0})}}function Rn(e){return()=>new e}function In(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"tagName"in e&&"string"==typeof e.tagName&&"classList"in e}function jn(e,t){if(In(e))return e;if(!e){const e=t.me;if(!e)throw Error("No target element - provide explicit target or ensure context.me is set");return Mn(e)}if("string"==typeof e){const r=e.trim();if("me"===r){if(!t.me)throw Error('Context reference "me" is not available');return Mn(t.me)}if("it"===r){if(!In(t.it))throw Error('Context reference "it" is not an HTMLElement');return t.it}if("you"===r){if(!t.you)throw Error('Context reference "you" is not available');return Mn(t.you)}const n=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!n)throw Error("DOM not available - cannot resolve element selector");const s=n.querySelector(r);if(!s)throw Error("Element not found with selector: "+r);if(!In(s))throw Error("Element found but is not an HTMLElement: "+r);return s}throw Error("Invalid target type: "+typeof e)}function Mn(e){if(In(e))return e;throw Error("Value is not an HTMLElement")}function Dn(e,t){switch(e.toLowerCase()){case"my":case"me":if(!t.me)throw Error('No "me" element in context');if(!In(t.me))throw Error("context.me is not an HTMLElement");return t.me;case"its":case"it":if(!t.it)throw Error('No "it" value in context');if(!In(t.it))throw Error("context.it is not an HTMLElement");return t.it;case"your":case"you":if(!t.you)throw Error('No "you" element in context');if(!In(t.you))throw Error("context.you is not an HTMLElement");return t.you;default:throw Error("Unknown possessive: "+e)}}const Vn=["on","from","to","in","with","at"];async function Bn(e,t,r,n,s={},i){let o=e;if(s.filterPrepositions&&e&&(o=e.filter(e=>{const t=e;return"identifier"===t?.type&&"string"==typeof t.name?!Vn.includes(t.name.toLowerCase()):1})),(!o||0===o.length)&&s.fallbackModifierKey&&i){const e=i[s.fallbackModifierKey];e&&(o=[e])}if(!o||0===o.length){if(!r.me)throw Error(n+" command: no target specified and context.me is null");if(!In(r.me))throw Error(n+" command: context.me must be an HTMLElement");return[r.me]}const a=[];for(const e of o){const s=await t.evaluate(e,r);if(""!==s&&("string"!=typeof s||""!==s.trim()))if(In(s))a.push(s);else if(s instanceof NodeList){const e=Array.from(s).filter(In);a.push(...e)}else if(Array.isArray(s)){const e=s.filter(In);a.push(...e)}else{if("string"!=typeof s)throw Error(`Invalid ${n} target: expected HTMLElement or CSS selector, got ${typeof s}`);try{let e=s;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const t=r.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!t)throw Error("DOM not available - cannot resolve element selector");const n=t.querySelectorAll(e),i=Array.from(n).filter(In);a.push(...i)}catch(e){throw Error(`Invalid CSS selector: "${s}" - ${e instanceof Error?e.message:e+""}`)}}}if(0===a.length){if(!r.me)throw Error(n+" command: no target specified and context.me is null");if(!In(r.me))throw Error(n+" command: context.me must be an HTMLElement");return[r.me]}return a}function Pn(e){return"string"==typeof e&&e.trim().startsWith("*")}function _n(e,t,r){e.style.setProperty(t,r)}const Fn=["dialog","details","summary","select"];function qn(e){return e&&"object"==typeof e?"string"==typeof e.selector?e.selector:"string"==typeof e.value?e.value:"string"==typeof e.name?e.name:null:null}async function Un(e,t,r){return function(e){if(!e||"object"!=typeof e)return 0;const t=e.type;if("selector"!==t&&"cssSelector"!==t&&"classSelector"!==t)return 0;const r=qn(e);return"string"==typeof r&&r.startsWith(".")}(e)||function(e){if(!e||"object"!=typeof e)return 0;const t=e.type;if("selector"!==t&&"cssSelector"!==t&&"cssProperty"!==t)return 0;const r=qn(e);return"string"==typeof r&&r.startsWith("*")}(e)?{value:qn(e),extractedFromNode:1}:{value:await t.evaluate(e,r),extractedFromNode:0}}class Hn{async resolveTargets(e,t,r,n){return Bn(e,t,r,this.mode,{filterPrepositions:1,fallbackModifierKey:this.preposition},n)}async evaluateFirst(e,t,r){return Un(e,t,r)}parseClassNames(e){return kn(e)}isAttribute(e){return gn(e.trim())}isCSSProperty(e){return Pn(e.trim())}validateTargets(e){return Array.isArray(e)&&function(e){return Array.isArray(e)&&e.length>0&&e.every(e=>In(e))}(e)}validateType(e,t){return function(e,t){return"string"==typeof e&&t.includes(e)}(e,t)}validateStringArray(e,t=1){return Array.isArray(e)&&function(e,t=1){return Array.isArray(e)&&e.length>=t&&e.every(e=>"string"==typeof e&&e.length>0)}(e,t)}}let Wn=(()=>{let e,t,r=[$n({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"]}),Ln({name:"add",category:"dom"})],n=[],s=Hn;return t=class extends s{constructor(){super(...arguments),this.mode="add",this.preposition="to"}async parseInput(e,t,r){if(!e.args||0===e.args.length)throw Error("add command requires an argument");const{value:n}=await this.evaluateFirst(e.args[0],t,r);if("object"==typeof n&&null!==n&&!Array.isArray(n))return{type:"styles",styles:n,targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)};if("string"==typeof n){const s=n.trim();if(this.isAttribute(s)){const{name:n,value:i}=function(e){const t=bn(e);return{name:t.name,value:t.value??""}}(s);return{type:"attribute",name:n,value:i,targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)}}if(this.isCSSProperty(s)){const n=s.substring(1).trim();if(2>e.args.length)throw Error("add *property requires a value argument");const i=await t.evaluate(e.args[1],r);return{type:"styles",styles:{[n]:i+""},targets:await this.resolveTargets(e.args.slice(2),t,r,e.modifiers)}}}const s=this.parseClassNames(n);if(0===s.length)throw Error("add command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)}}async execute(e,t){switch(e.type){case"classes":{const r=Cn(e.classes,t);r.length>0&&wn(e.targets,r,(e,t)=>{e.classList.contains(t)||e.classList.add(t)});break}case"attribute":r=e.name,n=e.value,En(e.targets,e=>{e.setAttribute(r,n)});break;case"styles":wn(e.targets,Object.entries(e.styles),(e,[t,r])=>{e.style.setProperty(t,r)})}var r,n}validate(e){if("object"!=typeof e||null===e)return 0;const t=e;if(!this.validateType(t.type,["classes","attribute","styles"]))return 0;if(!this.validateTargets(t.targets))return 0;if("classes"===t.type){if(!this.validateStringArray(e.classes,1))return 0}else if("attribute"===t.type){if("string"!=typeof e.name||0===e.name.length)return 0;if("string"!=typeof e.value)return 0}else if("styles"===t.type){const t=e;if("object"!=typeof t.styles||null===t.styles)return 0;if(Array.isArray(t.styles))return 0;const r=t.styles;if(0===Object.keys(r).length)return 0;if(!Object.values(r).every(e=>"string"==typeof e))return 0}return 1}},vn(t,"AddCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;mn(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:i}),yn(t,n)})(),t})();const zn=Rn(Wn);function Jn(e){return e.parentNode?(e.remove(),1):0}let Zn=(()=>{let e,t,r=[$n({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"]}),Ln({name:"remove",category:"dom"})],n=[],s=Hn;return t=class extends s{constructor(){super(...arguments),this.mode="remove",this.preposition="from"}async parseInput(e,t,r){if(!e.args||0===e.args.length)throw Error("remove command requires an argument");const{value:n}=await this.evaluateFirst(e.args[0],t,r);if(In(n))return{type:"element",targets:[n]};if(Array.isArray(n)&&n.length>0&&In(n[0]))return{type:"element",targets:n.filter(e=>In(e))};if("string"==typeof n){const s=n.trim();if(this.isAttribute(s))return{type:"attribute",name:bn(s).name,targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)};if(this.isCSSProperty(s))return{type:"styles",properties:[s.substring(1).trim()],targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)}}const s=this.parseClassNames(n);if(0===s.length)throw Error("remove command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)}}execute(e,t){switch(e.type){case"classes":{const r=Cn(e.classes,t);r.length>0&&wn(e.targets,r,(e,t)=>{e.classList.remove(t)});break}case"attribute":r=e.name,En(e.targets,e=>{e.removeAttribute(r)});break;case"styles":wn(e.targets,e.properties,(e,t)=>{e.style.removeProperty(t)});break;case"element":for(const t of e.targets)Jn(t)}var r}validate(e){if("object"!=typeof e||null===e)return 0;const t=e;if(!this.validateType(t.type,["classes","attribute","styles","element"]))return 0;if(!this.validateTargets(t.targets))return 0;if("classes"===t.type){if(!this.validateStringArray(e.classes,1))return 0}else if("attribute"===t.type){if("string"!=typeof e.name||0===e.name.length)return 0}else if("styles"===t.type&&!this.validateStringArray(e.properties,1))return 0;return 1}},vn(t,"RemoveCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;mn(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:i}),yn(t,n)})(),t})();const Gn=Rn(Zn);function Yn(e){const t=e.trim().match(/^(\d+(?:\.\d+)?)\s*(s|ms|sec|seconds?|milliseconds?)?$/i);if(!t)return null;const r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();return"ms"===n||"millisecond"===n||"milliseconds"===n?{number:r,milliseconds:Math.floor(r)}:"s"===n||"sec"===n||"second"===n||"seconds"===n?{number:r,milliseconds:Math.floor(1e3*r)}:null}function Xn(e){if("number"==typeof e){if(0>e)throw Error("Duration must be >= 0");return Math.floor(e)}if("string"==typeof e){const t=Yn(e);if(!t)throw Error(`Invalid duration format: "${e}"`);return t.milliseconds}throw Error("Invalid duration type: "+typeof e)}function Kn(e){return 0===e.length?[]:"SUMMARY"===e[0].tagName?e.map(e=>e.closest("details")).filter(e=>null!==e):e}function Qn(e,t,r){return()=>{"class"===t?e.classList.toggle(r):"attribute"===t&&xn(e,r)}}function es(e,t,r,n){const s=Qn(e,t,r),i=setTimeout(s,n);return()=>{clearTimeout(i)}}function ts(e,t,r,n){const s=Qn(e,t,r),i=()=>{s(),e.removeEventListener(n,i)};return e.addEventListener(n,i,{once:1}),()=>{e.removeEventListener(n,i)}}function rs(e,t,r){if(t.startsWith("@"))return void e.setAttribute(t.substring(1),r+"");const n=r+"";switch(t){case"textContent":return void(e.textContent=n);case"innerHTML":return void(e.innerHTML=n);case"innerText":return void(e.innerText=n);case"id":return void(e.id=n);case"className":return void(e.className=n);case"value":return void("value"in e&&(e.value=n));case"checked":return void("checked"in e&&(e.checked=!!r))}if(t.includes(".")){const n=t.split(".");let s=e;for(let e=0;n.length-1>e;e++)if(s=s[n[e]],null==s)return;return void(s[n[n.length-1]]=r)}if(t.includes("-")||t in e.style)e.style.setProperty(t,n);else try{e[t]=r}catch(e){if(!(e instanceof TypeError&&(e.message.includes("only a getter")||e.message.includes("read only"))))throw Error(`Cannot set property '${t}': ${e instanceof Error?e.message:"Unknown error"}`)}}const ns=/^the\s+(.+?)\s+of\s+(.+)$/i,ss=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 is(e){return"string"==typeof e&&ns.test(e)}function os(e,t){const r=e.match(ns);if(!r)return null;try{return{element:jn(r[2].trim(),t),property:r[1].trim()}}catch{return null}}async function as(e,t,r){if(function(e){return e&&"object"==typeof e?"propertyOfExpression"===e.type&&"object"==typeof e.property&&null!==e.property:0}(e))return async function(e,t,r){const n=e.property?.name;if(!n)return null;let s=await t.evaluate(e.target,r);return Array.isArray(s)&&(s=s[0]),In(s)?{element:s,property:n}:null}(e,t,r);if(function(e){return e&&"object"==typeof e?"propertyAccess"===e.type&&"string"==typeof e.property:0}(e))return async function(e,t,r){const n=e.property;if(!n)return null;let s=await t.evaluate(e.object,r);return Array.isArray(s)&&(s=s[0]),In(s)?{element:s,property:n}:null}(e,t,r);const n=e;if("possessiveExpression"===n?.type){const e=n.object,s=n.property;let i=await t.evaluate(e,r);if(Array.isArray(i)&&(i=i[0]),!In(i))return null;const o=s?.name||s?.value;return o?{element:i,property:o}:null}return null}function cs(e,t){const{element:r,property:n}=e;n.startsWith("*")?_n(r,n.substring(1),t+""):rs(r,n,t)}async function ls(e,t,r){let n,s;if(e?.for){const s=await t.evaluate(e.for,r);n="number"==typeof s?s:"string"==typeof s?function(e,t=300){if("number"==typeof e)return Math.max(0,Math.floor(e));if("string"==typeof e){const r=Yn(e);return r?r.milliseconds:t}return t}(s):void 0}if(e?.until){const n=await t.evaluate(e.until,r);"string"==typeof n&&(s=n)}return{duration:n,untilEvent:s}}const us=Rn((()=>{let e,t,r=[$n({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"]}),Ln({name:"toggle",category:"dom"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("toggle command requires an argument");const n=e.args[0],s=n?.name;if("between"===s&&e.args.length>=4){const{duration:n,untilEvent:s}=await ls(e.modifiers,t,r),i=await t.evaluate(e.args[1],r),o=await t.evaluate(e.args[3],r),a=[];for(let t=4;e.args.length>t;t++){const r=e.args[t]?.name;"on"!==r&&"from"!==r&&a.push(e.args[t])}const c={filterPrepositions:1,fallbackModifierKey:"on"},l=await Bn(a,t,r,"toggle",c,e.modifiers);return{type:"classes-between",classA:(i+"").replace(/^\./,""),classB:(o+"").replace(/^\./,""),targets:l,duration:n,untilEvent:s}}const i=await as(n,t,r);if(i)return{type:"property",target:i};const{duration:o,untilEvent:a}=await ls(e.modifiers,t,r),{value:c}=await Un(n,t,r);if(is(c)){const e=os(c,r);if(e)return{type:"property",target:e}}const{type:l,expression:u}=function(e,t){const r=t?.name,n=function(e){if(!e||"object"!=typeof e)return 0;if("identifier"!==e.type)return 0;const t=e.name;return"string"==typeof t&&function(e){if("string"!=typeof e)return 0;const t=e.toLowerCase();return Fn.includes(t)}(t)}(t);if(In(e)||Array.isArray(e)&&e.every(e=>In(e)))return{type:"element",expression:""};if(n&&r)return{type:"element",expression:r};if("string"==typeof e){const t=e.trim();return t.startsWith("@")||t.startsWith("[@")?{type:"attribute",expression:t}:t.startsWith("*")?{type:"css-property",expression:t}:t.startsWith(".")?{type:"class",expression:t}:t.startsWith("#")||function(e){if("string"!=typeof e)return 0;const t=e.toLowerCase();return Fn.some(e=>t.includes(e))}(t)?{type:"element",expression:t}:{type:"class",expression:t}}return{type:"class",expression:""}}(c,n),h={filterPrepositions:1,fallbackModifierKey:"on"};switch(l){case"attribute":{const{name:n,value:s}=bn(u);return{type:"attribute",name:n,value:s,targets:await Bn(e.args.slice(1),t,r,"toggle",h,e.modifiers),duration:o,untilEvent:a}}case"css-property":{const n=function(e){const t=function(e){const t=e.trim();if(!t.startsWith("*"))return null;const r=t.substring(1).trim();return r?{property:r}:null}(e);if(!t)return null;const r=t.property.toLowerCase();return["display","visibility","opacity"].includes(r)?r:null}(u);if(!n)throw Error("Invalid CSS property: "+u);return{type:"css-property",property:n,targets:await Bn(e.args.slice(1),t,r,"toggle",h,e.modifiers)}}case"element":{let s;if(In(c))s=[c];else if(Array.isArray(c)&&c.every(e=>In(e)))s=c;else if(u){const e=document.querySelectorAll(u);s=Array.from(e).filter(e=>In(e))}else s=await Bn([n],t,r,"toggle",h,e.modifiers);const i=function(e){if(0===e.length)return null;const t=e[0].tagName;if(!e.every(e=>e.tagName===t))return null;switch(t){case"DIALOG":return"dialog";case"DETAILS":return"details";case"SELECT":return"select";case"SUMMARY":return e.map(e=>e.closest("details")).filter(e=>null!==e).length>0?"details":null;default:return null}}(s);if("dialog"===i){const n=await async function(e,t,r,n){if(t?.as){const e=await r.evaluate(t.as,n);if("string"==typeof e&&"modal"===e.toLowerCase())return"modal"}if(e.length>=2){const t=await r.evaluate(e[1],n);if("string"==typeof t){const s=t.toLowerCase();if("modal"===s||"as modal"===s)return"modal";if("as"===s&&e.length>=3){const t=await r.evaluate(e[2],n);if("string"==typeof t&&"modal"===t.toLowerCase())return"modal"}}}return"non-modal"}(e.args,e.modifiers,t,r);return{type:"dialog",mode:n,targets:s}}return"details"===i?{type:"details",targets:Kn(s)}:"select"===i?{type:"select",targets:s}:{type:"classes",classes:kn(u),targets:s,duration:o,untilEvent:a}}default:{const n=kn(u||c);if(!n.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:n,targets:await Bn(e.args.slice(1),t,r,"toggle",h,e.modifiers),duration:o,untilEvent:a}}}}async execute(e,t){switch(e.type){case"classes":{const r=Cn(e.classes,t);if(0===r.length)return[...e.targets];if(wn(e.targets,r,(e,t)=>{e.classList.toggle(t)}),(e.duration||e.untilEvent)&&r.length)for(const t of e.targets)e.duration&&es(t,"class",r[0],e.duration),e.untilEvent&&ts(t,"class",r[0],e.untilEvent);return[...e.targets]}case"attribute":if(r=e.name,n=e.value,En(e.targets,e=>{xn(e,r,n)}),e.duration||e.untilEvent)for(const t of e.targets)e.duration&&es(t,"attribute",e.name,e.duration),e.untilEvent&&ts(t,"attribute",e.name,e.untilEvent);return[...e.targets];case"css-property":return En(e.targets,t=>function(e,t){const r=window.getComputedStyle(e);switch(t){case"display":"none"===r.display?(e.style.display=e.dataset.previousDisplay||"block",delete e.dataset.previousDisplay):(e.dataset.previousDisplay=r.display,e.style.display="none");break;case"visibility":e.style.visibility="hidden"===r.visibility?"visible":"hidden";break;case"opacity":e.style.opacity=0===parseFloat(r.opacity)?"1":"0"}}(t,e.property));case"property":return function(e){const t=function(e){const{element:t,property:r}=e;return r.startsWith("*")?function(e,t){return window.getComputedStyle(e).getPropertyValue(t)}(t,r.substring(1)):function(e,t){if(t.startsWith("@"))return e.getAttribute(t.substring(1));switch(t){case"textContent":return e.textContent;case"innerHTML":return e.innerHTML;case"innerText":return e.innerText;case"id":return e.id;case"className":return e.className;case"value":return"value"in e?e.value:void 0;case"checked":return"checked"in e?e.checked:void 0}if(t.includes(".")){const r=t.split(".");let n=e;for(const e of r){if(null==n)break;n=n[e]}return n}return t.includes("-")||t in e.style?e.style.getPropertyValue(t)||e.style[t]:e[t]}(t,r)}(e),r=e.property;if("boolean"==typeof t||ss.has(r)||ss.has(r.toLowerCase())){const r=!t;return cs(e,r),r}if("number"==typeof t){const r=0===t?1:0;return cs(e,r),r}if("string"==typeof t){const n="__ht_"+r,s=e.element[n];return""===t&&void 0!==s?(cs(e,s),s):(e.element[n]=t,cs(e,""),"")}cs(e,!t)}(e.target),[e.target.element];case"dialog":return En(e.targets,t=>{return n=e.mode,void((r=t).open?r.close():"modal"===n?r.showModal():r.show());var r,n});case"details":return En(e.targets,e=>{var t;(t=e).open=!t.open});case"select":return En(e.targets,e=>function(e){if(document.activeElement===e)e.blur();else{if(e.focus(),"showPicker"in e&&"function"==typeof e.showPicker)try{return void e.showPicker()}catch{}const t=new MouseEvent("click",{view:window,bubbles:1,cancelable:1});e.dispatchEvent(t)}}(e));case"classes-between":for(const t of e.targets){const r=t.classList.contains(e.classA),n=t.classList.contains(e.classB);r?(t.classList.remove(e.classA),t.classList.add(e.classB)):n?(t.classList.remove(e.classB),t.classList.add(e.classA)):t.classList.add(e.classA)}if(e.duration||e.untilEvent)for(const t of e.targets)e.duration&&es(t,"class",e.classA,e.duration),e.untilEvent&&ts(t,"class",e.classA,e.untilEvent);return[...e.targets]}var r,n}},vn(t,"ToggleCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mn(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),yn(t,n)})(),t})());class hs{async parseInput(e,t,r){const{targets:n}=await async function(e,t,r,n){return{targets:await Bn(e.args,t,r,n)}}(e,t,r,this.mode);return{targets:n,mode:this.mode,defaultDisplay:"show"===this.mode?"block":void 0}}validate(e){if("object"!=typeof e||null===e)return 0;const t=e;return Array.isArray(t.targets)&&t.targets.every(e=>In(e))?"show"!==t.mode&&"hide"!==t.mode||"show"===t.mode&&"string"!=typeof t.defaultDisplay?0:1:0}showElement(e,t="block"){const r=e.dataset.originalDisplay;void 0!==r?(e.style.display=r||t,delete e.dataset.originalDisplay):"none"===e.style.display&&(e.style.display=t),e.classList.add("show")}hideElement(e){if(!e.dataset.originalDisplay){const t=e.style.display;e.dataset.originalDisplay="none"===t?"":t}e.style.display="none",e.classList.remove("show")}}let fs=(()=>{let e,t,r=[$n({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"]}),Ln({name:"show",category:"dom"})],n=[],s=hs;return t=class extends s{constructor(){super(...arguments),this.mode="show"}async execute(e,t){const r=e.defaultDisplay||"block";for(const t of e.targets)this.showElement(t,r)}validate(e){if("object"!=typeof e||null===e)return 0;const t=e;return Array.isArray(t.targets)&&t.targets.every(e=>In(e))?"string"!=typeof t.defaultDisplay?0:1:0}},vn(t,"ShowCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;mn(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:i}),yn(t,n)})(),t})();const ds=Rn(fs);let ps=(()=>{let e,t,r=[$n({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"]}),Ln({name:"hide",category:"dom"})],n=[],s=hs;return t=class extends s{constructor(){super(...arguments),this.mode="hide"}async execute(e,t){for(const t of e.targets)this.hideElement(t)}validate(e){if("object"!=typeof e||null===e)return 0;const t=e;return Array.isArray(t.targets)&&t.targets.every(e=>In(e))?1:0}},vn(t,"HideCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;mn(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:i}),yn(t,n)})(),t})();const ms=Rn(ps),ys=Rn((()=>{let e,t,r=[$n({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"]}),Ln({name:"put",category:"dom"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("put requires arguments");const n=e=>e?.type||"unknown",s=["into","before","after","at","at start of","at end of"];let i=-1,o=null;for(let t=0;e.args.length>t;t++){const r=e.args[t],a=n(r),c="literal"===a?r.value:r.name;if(("literal"===a||"identifier"===a)&&s.includes(c)){i=t,o=c;break}}let a=null,c=null;if(-1===i)if(e.modifiers.into||e.modifiers.before||e.modifiers.after){const t=e.modifiers.into?"into":e.modifiers.before?"before":"after";a=e.args[0],o=t,c=e.modifiers[t]}else if(3>e.args.length){if(2>e.args.length)throw Error("put requires content and position");a=e.args[0],o=e.args[1]?.value||e.args[1]?.name||"into"}else a=e.args[0],o=e.args[1]?.value||e.args[1]?.name||null,c=e.args[2];else a=e.args.slice(0,i)[0]||null,c=e.args.slice(i+1)[0]||null;if(!a)throw Error("put requires content");if(!o)throw Error("put requires position keyword");const l=await t.evaluate(a,r),u=this.mapPosition(o);let h,f,d=null;if(c){const e=n(c),s=await as(c,t,r);if(s)return{value:l,targets:[s.element],position:"replace",memberPath:s.property};if("memberExpression"===e){const e=c.object,n=c.property;if("selector"===e?.type?d=e.value:"identifier"===e?.type&&(d=e.name),d&&n?.name)h=n.name;else{const e=await t.evaluate(c,r);"string"==typeof e&&(d=e)}}else if("identifier"===e&&"me"===c.name)d=null;else if("selector"===e||"cssSelector"===e)d=c.value||c.selector;else if("literal"===e){const e=c.value;if("string"==typeof e&&is(e)){const t=os(e,r);if(t)return{value:l,targets:[t.element],position:"replace",memberPath:t.property}}"string"==typeof e&&this.looksLikeCss(e)?d=e:f=e+""}else if("identifier"===e){const e=c.name;this.looksLikeCss(e)?d=e:f=e}else{const e=await t.evaluate(c,r);"string"==typeof e&&(this.looksLikeCss(e)?d=e:f=e)}}return f?{value:l,targets:[],position:u,memberPath:h,variableName:f}:{value:l,targets:await this.resolveTargets(d,r),position:u,memberPath:h}}async execute(e,t){const{value:r,targets:n,position:s,memberPath:i,variableName:o}=e;if(o)return t.locals&&t.locals.set(o,r),t[o]=r,[];if(i)for(const e of n)this.setProperty(e,i,r);else for(const e of n){const t=this.parseValue(r);this.insertContent(e,t,s)}return n}mapPosition(e){switch(e){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: "+e)}}async resolveTargets(e,t){if(!e||"me"===e){if(!t.me||!In(t.me))throw Error("put: no target and context.me is null");return[t.me]}const r=Array.from(document.querySelectorAll(e)).filter(e=>In(e));if(!r.length)throw Error(`No elements: "${e}"`);return r}parseValue(e){return In(e)?e:null==e?"":e+""}insertContent(e,t,r){if("replace"!==r)if(In(t)){const n=t;switch(r){case"beforebegin":e.parentElement?.insertBefore(n,e);break;case"afterbegin":e.insertBefore(n,e.firstChild);break;case"beforeend":e.appendChild(n);break;case"afterend":e.parentElement?.insertBefore(n,e.nextSibling)}}else t.includes("<")&&t.includes(">")?e.insertAdjacentHTML(r,t):e.insertAdjacentText(r,t);else In(t)?(e.innerHTML="",e.appendChild(t)):t.includes("<")&&t.includes(">")?e.innerHTML=t:e.textContent=t}looksLikeCss(e){return e?/^[#.\[]/.test(e)||/[>+~\s]/.test(e)&&e.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(e.toLowerCase()):0}setProperty(e,t,r){const n=t.split(".");let s=e;for(let e=0;n.length-1>e;e++){if(!s[n[e]])throw Error(`Property path "${t}" does not exist`);s=s[n[e]]}s[n[n.length-1]]=r}},vn(t,"PutCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mn(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),yn(t,n)})(),t})()),vs=Rn((()=>{let e,t,r=[$n({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"]}),Ln({name:"set",category:"data"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("set command requires a target");const n=e.args[0],s=n?.name||n?.value,i=await as(n,t,r);if(i){const n=await this.extractValue(e,t,r);if(i.property.startsWith("*")){const e=i.property.substring(1);return{type:"style",element:i.element,property:e,value:n+""}}return{type:"property",element:i.element,property:i.property,value:n}}if("memberExpression"===n?.type){const s=await this.tryParseMemberExpression(n,e,t,r);if(s)return s}let o;if(o="identifier"!==n?.type&&"variable"!==n?.type||"string"!=typeof s?await t.evaluate(n,r):s,function(e){if("object"!=typeof e||null===e||Array.isArray(e))return 0;if(In(e)||e instanceof Node)return 0;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}(o))return{type:"object-literal",properties:o,targets:await this.resolveTargets(e.modifiers.on,t,r)};if(is(o)){const n=os(o,r);if(n){const s=await this.extractValue(e,t,r);return{type:"property",element:n.element,property:n.property,value:s}}return this.parseTheXofY(o,e,t,r)}if("string"==typeof o&&Pn(o)){const n=o.substring(1).trim(),s=await this.extractValue(e,t,r);return{type:"style",element:await this.resolveElement(e.modifiers.on,t,r),property:n,value:s+""}}if("string"==typeof o&&gn(o)){const n=o.substring(1).trim(),s=await this.extractValue(e,t,r);return{type:"attribute",element:await this.resolveElement(e.modifiers.on,t,r),name:n,value:s}}if("string"==typeof o){const n=o.match(/^(my|me|its?|your?)\s+(.+)$/i);if(n){const s=Dn(n[1],r),i=await this.extractValue(e,t,r);return{type:"property",element:s,property:n[2],value:i}}}if(In(o))return{type:"property",element:o,property:"textContent",value:await this.extractValue(e,t,r)};if(Array.isArray(o)&&o.length>0&&In(o[0])){const n=await this.extractValue(e,t,r);return{type:"property",element:o[0],property:"textContent",value:n}}if("string"!=typeof o)throw Error("set command target must be a string or object literal");return{type:"variable",name:o,value:await this.extractValue(e,t,r)}}async execute(e,t){switch(e.type){case"variable":return t.locals.set(e.name,e.value),"result"!==e.name&&"it"!==e.name||Object.assign(t,{[e.name]:e.value}),Object.assign(t,{it:e.value}),{target:e.name,value:e.value,targetType:"variable"};case"attribute":return e.element.setAttribute(e.name,e.value+""),Object.assign(t,{it:e.value}),{target:"@"+e.name,value:e.value,targetType:"attribute"};case"property":return rs(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"style":return _n(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"object-literal":for(const t of e.targets)for(const[r,n]of Object.entries(e.properties))rs(t,r,n);return Object.assign(t,{it:e.properties}),{target:e.targets[0]||"unknown",value:e.properties,targetType:"property"};default:throw Error("Unknown input type: "+e.type)}}async tryParseMemberExpression(e,t,r,n){const s=e.object,i=e.property;if(s?.name&&i?.name){const e=s.name.toLowerCase();if(["me","my","it","its","you","your"].includes(e)){const s=Dn(e,n),o=await this.extractValue(t,r,n);return{type:"property",element:s,property:i.name,value:o}}}return null}async extractValue(e,t,r){if(e.modifiers.to)return t.evaluate(e.modifiers.to,r);const n=e.args.findIndex(e=>"identifier"===e.type&&"to"===e.name);if(n>=0&&e.args.length>n+1)return t.evaluate(e.args[n+1],r);if(e.args.length>=2)return t.evaluate(e.args[1],r);throw Error('set command requires a value (use "to" keyword)')}async resolveElement(e,t,r){return jn(e?await t.evaluate(e,r):void 0,r)}async resolveTargets(e,t,r){return function(e,t){if(Array.isArray(e))return e.filter(In);if(e instanceof NodeList)return Array.from(e).filter(In);if(In(e))return[e];if(!e){const e=t.me;return e&&In(e)?[e]:[]}if("string"==typeof e){const r=e.trim();if("me"===r)return t.me&&In(t.me)?[t.me]:[];if("it"===r)return In(t.it)?[t.it]:[];if("you"===r)return t.you&&In(t.you)?[t.you]:[];const n=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(n){let e=r;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const t=n.querySelectorAll(e);return Array.from(t).filter(In)}}return[]}(e?await t.evaluate(e,r):void 0,r)}async parseTheXofY(e,t,r,n){const s=e.match(/^the\s+(.+?)\s+of\s+(.+)$/i);if(!s)throw Error('Invalid "the X of Y" syntax');const[,i,o]=s,a=jn(o,n),c=await this.extractValue(t,r,n);return{type:"property",element:a,property:i.trim(),value:c}}validate(e){if(!e||"object"!=typeof e)return 0;const t=e;if(!t.type||"string"!=typeof t.type)return 0;if(!["variable","attribute","property","style","object-literal"].includes(t.type))return 0;switch(t.type){case"variable":return"string"==typeof t.name&&"value"in t;case"attribute":return"string"==typeof t.name&&In(t.element)&&"value"in t;case"property":return"string"==typeof t.property&&In(t.element)&&"value"in t;case"style":return"string"==typeof t.property&&""!==t.property&&In(t.element)&&"string"==typeof t.value;case"object-literal":return null!==t.properties&&"object"==typeof t.properties&&Array.isArray(t.targets)&&t.targets.length>0;default:return 0}}},vn(t,"SetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mn(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),yn(t,n)})(),t})());function gs(e){const t=e.trim();return/^\d+$/.test(t)?parseInt(t,10):/^\d*\.\d+$/.test(t)?parseFloat(t):"true"===t?1:"false"===t?0:"null"===t?null:"undefined"!==t?t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t:void 0}const bs=Rn((()=>{let e,t,r=[$n({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"]}),Ln({name:"trigger",category:"event"})],n=[];return t=class{async parseInput(e,t,r){const n="send"===e.commandName?.toLowerCase()?"send":"trigger",s=n;if(!e.args?.length)throw Error(s+" command requires an event name");const i=e=>e?.type||"unknown",o=e.args[0];let a,c,l;if("functionCall"===i(o))a=o.name,o.args?.length&&(c=await this.parseEventDetail(o.args,t,r));else if("identifier"===i(o)||"keyword"===i(o))a=o.name;else{const e=await t.evaluate(o,r);a="string"==typeof e?e:e+""}const u=e.modifiers?.on||e.modifiers?.to;if(u)l=await this.resolveTargets([u],t,r,s);else{const n=e.args.findIndex((e,t)=>{if(0===t)return 0;const r=e.name||e.value;return"on"===r||"to"===r});if(-1!==n&&e.args.length-1>n){const i=e.args.slice(n+1),o=i.findIndex(e=>"with"===(e.name||e.value)),a=-1===o?i:i.slice(0,o);l=await this.resolveTargets(a,t,r,s)}else{if(!r.me)throw Error(s+": no target specified and context.me is null");l=[r.me]}}return{eventName:a,detail:c,targets:l,options:await this.parseEventOptions(e.args,t,r),mode:n}}async execute(e,t){const r=function(e,t,r={}){return new CustomEvent(e,{detail:void 0!==t?t:{},bubbles:void 0!==r.bubbles?r.bubbles:1,cancelable:void 0!==r.cancelable?r.cancelable:1,composed:void 0!==r.composed?r.composed:0})}(e.eventName,e.detail,e.options);for(const t of e.targets)t.dispatchEvent(r);t.it=r}async resolveTargets(e,t,r,n){const s=[];for(const n of e){const e=await t.evaluate(n,r);if("window"!==e&&e!==window)if("document"!==e&&e!==document)if("me"===e&&r.me)s.push(r.me);else if("you"===e&&r.you)s.push(r.you);else if("it"===e&&r.it)s.push(r.it);else if(In(e))s.push(e);else if(e instanceof NodeList)s.push(...Array.from(e).filter(In));else if(Array.isArray(e))s.push(...e.filter(In));else{if("string"==typeof e){const t=document.querySelectorAll(e);if(0===t.length)throw Error(`No elements found: "${e}"`);s.push(...Array.from(t).filter(In));continue}if(!e||"object"!=typeof e||!("addEventListener"in e))throw Error("Invalid target: "+typeof e);s.push(e)}else s.push(document);else s.push(window)}if(!s.length)throw Error(n+": no valid targets");return s}async parseEventDetail(e,t,r){if(!e?.length)return;if(1===e.length)return await t.evaluate(e[0],r);const n={};for(const s of e){const e=await t.evaluate(s,r);if("object"!=typeof e||null===e||Array.isArray(e)){if("string"==typeof e&&e.includes(":")){const[t,r]=e.split(":",2);n[t.trim()]=gs(r.trim())}}else Object.assign(n,e)}return Object.keys(n).length?n:void 0}async parseEventOptions(e,t,r){const n={bubbles:1,cancelable:1,composed:0},s=e.findIndex(e=>"with"===(e.name||e.value));if(-1===s)return n;for(const i of e.slice(s+1)){const e=await t.evaluate(i,r);if("string"==typeof e){const t=e.toLowerCase();"bubbles"===t?n.bubbles=1:"nobubbles"===t?n.bubbles=0:"cancelable"===t?n.cancelable=1:"nocancelable"===t?n.cancelable=0:"composed"===t&&(n.composed=1)}}return n}},vn(t,"EventDispatchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mn(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),yn(t,n)})(),t})()),Es=Rn((()=>{let e,t,r=[$n({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"]}),Ln({name:"log",category:"utility"})],n=[];return t=class{async parseInput(e,t,r){return e.args&&0!==e.args.length?{values:await Promise.all(e.args.map(e=>t.evaluate(e,r)))}:{values:[]}}async execute(e,t){const r="undefined"!=typeof window?window.console:console;0===e.values.length?r.log():r.log(...e.values)}validate(e){return"object"!=typeof e||null===e?0:Array.isArray(e.values)}},vn(t,"LogCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mn(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),yn(t,n)})(),t})());function ws(e,t,r){return e?new Promise(r=>{const n=function(r,n){let i=0;return r=>{i||(i=1,e.removeEventListener(t,s),n(r))}}(0,r),s=e=>{n({event:e,timedOut:0,cancelled:0})};e.addEventListener(t,s)}):Promise.reject(Error("waitForEvent: no target provided"))}function xs(e){return new Promise(t=>setTimeout(t,e))}const ks=Rn((()=>{let e,t,r=[$n({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"]}),Ln({name:"wait",category:"async"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("wait command requires an argument");if(e.modifiers.or)return this.parseRaceCondition(e,t,r);if(e.modifiers.for)return this.parseEventWait(e.modifiers.for,e.modifiers.from,t,r);const n=e.args[0];return"arrayLiteral"===n.type&&n.elements?this.parseEventArrayWait(n.elements,e.args[1],t,r):this.parseTimeWait(e.args[0],t,r)}async execute(e,t){const r=Date.now();if("time"===e.type)return await xs(e.milliseconds),{type:"time",result:e.milliseconds,duration:Date.now()-r};if("event"===e.type){const n=e.target??t.me??document,s=(await ws(n,e.eventName)).event;if(Object.assign(t,{it:s}),e.destructure)for(const r of e.destructure)r in s&&t.locals.set(r,s[r]);return{type:"event",result:s,duration:Date.now()-r}}const{result:n,winningCondition:s}=await this.executeRace(e.conditions,t);if(Object.assign(t,{it:n}),n instanceof Event&&"event"===s?.type&&s.destructure)for(const e of s.destructure)e in n&&t.locals.set(e,n[e]);return{type:n instanceof Event?"event":"time",result:n,duration:Date.now()-r}}async parseTimeWait(e,t,r){return{type:"time",milliseconds:Xn(await t.evaluate(e,r))}}async parseEventWait(e,t,r,n){const s=await r.evaluate(e,n);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(e=>e.trim()):void 0;let c;if(t){const e=await r.evaluate(t,n);if(!e||"object"!=typeof e||!("addEventListener"in e))throw Error("wait for from: target must be an EventTarget");c=e}else c=n.me??void 0;return{type:"event",eventName:o,target:c,destructure:a}}async parseEventArrayWait(e,t,r,n){const s=[];for(const t of e){const e=t;if("objectLiteral"===e.type&&e.properties){let t="",r=[];for(const n of e.properties){const e=n.key?.name||n.key?.value;"name"===e&&n.value?t=n.value.value||"":"args"===e&&n.value?.elements&&(r=n.value.elements.map(e=>e.value||e.name||""))}t&&s.push({name:t,params:r})}}let i;if(t){const e=await r.evaluate(t,n);e&&"object"==typeof e&&"addEventListener"in e&&(i=e)}return i||(i=n.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(e=>({type:"event",eventName:e.name,target:i,destructure:e.params.length>0?e.params:void 0}))}}async parseRaceCondition(e,t,r){const n=[];e.modifiers.for?n.push(await this.parseEventWait(e.modifiers.for,e.modifiers.from,t,r)):e.args[0]&&n.push(await this.parseTimeWait(e.args[0],t,r));const s=await t.evaluate(e.modifiers.or,r),i=Array.isArray(s)?s:[s];for(const e of i)try{n.push({type:"time",milliseconds:Xn(e)})}catch{if("string"==typeof e){const t=e.match(/^(\w+)\(([^)]+)\)$/);n.push(t?{type:"event",eventName:t[1],target:r.me??void 0,destructure:t[2].split(",").map(e=>e.trim())}:{type:"event",eventName:e,target:r.me??void 0})}}if(2>n.length)throw Error("wait: race requires at least 2 conditions");return{type:"race",conditions:n}}async executeRace(e,t){const r=e.map(e=>"time"===e.type?xs(e.milliseconds).then(()=>({result:e.milliseconds,winningCondition:e})):ws(e.target??t.me??document,e.eventName).then(t=>({result:t.event,winningCondition:e})));return Promise.race(r)}},vn(t,"WaitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mn(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),yn(t,n)})(),t})()),As=function(e,t){const r=new ln(t.expressionEvaluator);for(const t of e)r.register(t);return new dn({registry:r,expressionEvaluator:t.expressionEvaluator,enableAsyncCommands:t.enableAsyncCommands??1,commandTimeout:t.commandTimeout??1e4,enableErrorReporting:t.enableErrorReporting??1,enableResultPattern:t.enableResultPattern??1})}([zn(),Gn(),us(),ds(),ms(),ys(),vs(),bs(),Es(),ks()],{expressionEvaluator:new class extends $t{constructor(e){super();for(const t of e)this.registerCategory(t)}}([tr,jr,sn])}),Ss={parse:e=>ht(e),execute:async(e,t)=>{const r=function(e){if(!e)return gt();if(e.locals instanceof Map&&e.globals instanceof Map&&e.flags)return e;const t=gt(e.me instanceof Element?e.me:null);return void 0!==e.it&&Object.assign(t,{it:e.it}),void 0!==e.you&&(t.you=e.you),void 0!==e.result&&Object.assign(t,{result:e.result}),void 0!==e.event&&Object.assign(t,{event:e.event}),t}(t),n=ht(e);if(!n.success||!n.node)throw Error(n.error?.message||"Parse failed");return await As.execute(n.node,r)}},Cs=function(e){return new pn(e)}(Ss),Ts={runtime:Ss,parse:e=>Ss.parse(e),execute:async(e,t)=>Ss.execute(e,t),createContext:gt,attributeProcessor:Cs,version:"1.1.0-minimal-v2-tree-shakeable",commands:["add","remove","toggle","show","hide","put","set","send","log","wait"],eval:async(e,t)=>Ss.execute(e,t),init:()=>{Cs.init()}};return"undefined"!=typeof window&&(window.hyperfixi=Ts,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{Cs.init()}):Cs.init()),Ts}();
|