@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,2 @@
|
|
|
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=e=>w.has(e.toLowerCase()),N=e=>x.has(e.toLowerCase()),O=e=>C.has(e.toLowerCase()),L=e=>R.has(e.toLowerCase()),R=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"]),$=new Set(["me","it","you","result","my","its","your"]),I=new Set(["and","or","not","no"]),j=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"]),M=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"]),D=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 V,B;function P(e){switch(e){case B.KEYWORD:case B.COMMAND:case B.EXPRESSION:case B.CONTEXT_VAR:case B.GLOBAL_VAR:case B.EVENT:case B.IDENTIFIER:return V.IDENTIFIER;case B.STRING:return V.STRING;case B.NUMBER:return V.NUMBER;case B.BOOLEAN:return V.IDENTIFIER;case B.TEMPLATE_LITERAL:return V.TEMPLATE;case B.CSS_SELECTOR:case B.ID_SELECTOR:case B.CLASS_SELECTOR:case B.QUERY_REFERENCE:return V.SELECTOR;case B.OPERATOR:case B.LOGICAL_OPERATOR:case B.COMPARISON_OPERATOR:return V.OPERATOR;case B.TIME_EXPRESSION:return V.TIME;case B.COMMENT:return V.COMMENT;case B.SYMBOL:return V.SYMBOL;default:return V.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"}(V||(V={})),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"}(B||(B={}));const _=D,F=new Set(["+","-","*","/","mod"]),U=new Set(["ms","s","seconds","minutes","hours","days"]);function q(e,t=1){const r=e.position+t;return e.input.length>r?e.input[r]:""}function H(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 W(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;H(e)}}function z(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:P(t),value:r,start:i,end:o,line:J(e,i),column:a};e.tokens.push(c)}function J(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 Z(e){const t=e.position;let r="";for(H(e),H(e);e.input.length>e.position&&"\n"!==e.input[e.position];)r+=H(e);z(e,B.COMMENT,"--"+r,t)}function G(e){const t=e.position,r=H(e);let n=r;for(;e.input.length>e.position;){const t=H(e);if(n+=t,t===r)break;"\\"===t&&e.input.length>e.position&&(n+=H(e))}z(e,B.STRING,n,t)}function Y(e){const t=e.position;H(e);let r="";for(;e.input.length>e.position;){const t=e.input[e.position];if("`"===t){H(e);break}if("\\"===t){if(H(e),e.input.length>e.position){const t=H(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+=H(e)}if(e.position>=e.input.length&&!e.input.endsWith("`"))throw Error(`Unterminated template literal at line ${e.line}, column ${e.column-r.length}`);z(e,B.TEMPLATE_LITERAL,r,t)}function X(e){const t=e.position,r=H(e);let n=r;for(;e.input.length>e.position;){const t=e.input[e.position];if(!ie(t)&&"-"!==t&&"_"!==t&&":"!==t)break;n+=H(e)}z(e,"#"===r?B.ID_SELECTOR:B.CLASS_SELECTOR,n,t)}function K(e){const t=e.position;let r="";for(r+=H(e);e.input.length-1>e.position;){const t=e.input[e.position],n=e.input[e.position+1];if(r+=H(e),"/"===t&&">"===n){r+=H(e);break}}z(e,B.QUERY_REFERENCE,r,t)}function Q(e){const t=e.position;let r=H(e);for(;e.input.length>e.position;){const t=e.input[e.position];if(!ie(t)&&"_"!==t&&"-"!==t)break;r+=H(e)}z(e,B.SYMBOL,r,t)}function ee(e){const t=e.position;let r="";const n=e.input[e.position];if(("'"===n||"'"===n)&&"s"===q(e,1))return r="'s",H(e),H(e),void z(e,B.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,H(e),H(e),H(e)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(s)?(r=s,H(e),H(e)):r=H(e);let o=B.OPERATOR;j.has(r)?o=B.COMPARISON_OPERATOR:["&&","||"].includes(r)?o=B.LOGICAL_OPERATOR:F.has(r)&&(o=B.OPERATOR),z(e,o,r,t)}function te(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+=H(e)}if(n>e.position&&"."===r[e.position]&&(e.position+1>=n||"."!==r[e.position+1]))for(s+=H(e);n>e.position;){const t=r[e.position];if("0">t||t>"9")break;s+=H(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+=H(e),"+"!==r[e.position]&&"-"!==r[e.position]||(s+=H(e));n>e.position;){const t=r[e.position];if("0">t||t>"9")break;s+=H(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+=H(e)}U.has(o)?z(e,B.TIME_EXPRESSION,s+o,t):(e.position=i,z(e,B.NUMBER,s,t))}function re(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+=H(e)}const i=function(e,t,r){const n=t.toLowerCase(),s=e.position;if("'s"===t||"'s"===t)return!1;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!1}W(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+=H(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){W(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+=H(e)}const s=r.toLowerCase();if("start"===s||"end"===s){W(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+=H(e)}if("of"===t.toLowerCase())return z(e,B.KEYWORD,`at the ${s} of`,n),!0}return e.position=t,!1}if("start"===i||"end"===i){W(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+=H(e)}return"of"===r.toLowerCase()?(z(e,B.KEYWORD,`at ${i} of`,n),!0):(e.position=t,!1)}}return!1}(e,n,t,r);if(i)return!0;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&&(W(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+=H(e)}if(!t)break;o.push(t.toLowerCase());const r=o.join(" ");j.has(r)&&(s=r,i=e.position)}return j.has(s)&&s!==`${t} ${r}`?(e.position=i,s):(e.position=n,null)}(e,n,t);if(a)return z(e,B.COMPARISON_OPERATOR,a,r),!0;if(j.has(s))return z(e,B.COMPARISON_OPERATOR,s,r),!0}return j.has(n)?(e.position=s,z(e,B.COMPARISON_OPERATOR,t,r),!0):(e.position=s,!1)}(e,s,t);if(i)return;const o=function(e){const t=e.toLowerCase();return"include"===t||"includes"===t?B.COMPARISON_OPERATOR:I.has(t)?B.LOGICAL_OPERATOR:F.has(e)||F.has(t)?B.OPERATOR:j.has(t)?B.COMPARISON_OPERATOR:"I"===e||$.has(t)?B.CONTEXT_VAR:w.has(t)?B.COMMAND:M.has(t)?B.EVENT:["true","false","null","undefined"].includes(t)?B.BOOLEAN:_.has(t)?B.KEYWORD:B.IDENTIFIER}(s);z(e,o,s,t)}function ne(e){const t=e.position,r=e.input,n=r.length;H(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+=H(e)}z(e,B.GLOBAL_VAR,s,t)}function se(e){return/[a-zA-Z]/.test(e)}function ie(e){return/[a-zA-Z0-9]/.test(e)}function oe(e){let t=e.position+1,r=!1;for(;e.input.length>t;){const n=e.input[t];if("/"===n&&e.input.length>t+1&&">"===e.input[t+1])return r;if(ie(n)||"."===n||"#"===n||"["===n||"]"===n||":"===n||"-"===n||"_"===n||" "===n||"="===n||'"'===n||"'"===n||"("===n||")"===n||"*"===n||"^"===n||"$"===n||"~"===n||"|"===n||">"===n||"+"===n||","===n)r=!0,t++;else{if(" "!==n&&"\t"!==n)return!1;t++}if(t-e.position>50)return!1}return!1}function ae(e){return"+-*/^%=!<>&|(){}[],.;:?''~$".includes(e)}const ce=function(){if("undefined"!=typeof localStorage)try{const e=localStorage.getItem("lokascript:debug");if("*"===e||"true"===e)return!0}catch{}return!("undefined"==typeof window||!window.__HYPERFIXI_DEBUG__)||"undefined"!=typeof process&&"true"===process.env?.HYPERFIXI_DEBUG}(),le=ce,ue=ce,he=ce,fe=ce,de=ce,pe=(...e)=>{le&&console.log("🔧",...e)},me=(...e)=>{ue&&console.log("🎯",...e)},ye=(...e)=>{he&&console.log("📝",...e)},ve=(...e)=>{fe&&console.log("🔍",...e)},ge=(...e)=>{fe&&console.log("🔍",...e)},be=(...e)=>{de&&console.log("🚀",...e)};let Ee=!1,we=null;if("undefined"!=typeof window&&"undefined"!=typeof URLSearchParams)try{"semantic"===new URLSearchParams(window.location.search).get("debug")&&(Ee=!0,we=window,console.log("%c[HyperFixi] Semantic debug auto-enabled via URL param","color: #667eea; font-weight: bold"))}catch{}let xe={totalParses:0,semanticSuccesses:0,semanticFallbacks:0,traditionalParses:0,averageConfidence:0,confidenceHistory:[]};class ke{constructor(e){this.analyzer=e.analyzer,this.language=e.language,this.confidenceThreshold=e.confidenceThreshold??.5,this.debugEnabled=e.debug??!1}isAvailable(){return this.analyzer.supportsLanguage(this.language)}shouldSkipSemantic(e){const t=e.trim().split(/\s+/)[0]?.toLowerCase();if(ke.SKIP_SEMANTIC_COMMANDS.has(t))return!0;const r=e.toLowerCase();return!!/\bjs\b/.test(r)||!!/\btell\b/.test(r)}trySemanticParse(e){const t=performance.now();if(this.shouldSkipSemantic(e))return{success:!1,confidence:0,errors:["Command skipped for semantic parsing - using traditional parser"]};if(!this.isAvailable())return{success:!1,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(Ee){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(!Ee)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(),we){const t=new CustomEvent("lokascript:semantic:parse",{detail:e,bubbles:!0});we.dispatchEvent(t)}}(a),r=a,xe.totalParses++,r.semanticSuccess?xe.semanticSuccesses++:r.fallbackTriggered?xe.semanticFallbacks++:xe.traditionalParses++,xe.confidenceHistory.push(r.confidence),xe.confidenceHistory.length>100&&xe.confidenceHistory.shift(),xe.averageConfidence=xe.confidenceHistory.reduce((e,t)=>e+t,0)/xe.confidenceHistory.length}return i?{success:!0,node:this.buildCommandNode(n),confidence:n.confidence,tokensConsumed:n.tokensConsumed}:{success:!1,confidence:n.confidence,tokensConsumed:n.tokensConsumed,errors:n.errors}}catch(e){return{success:!1,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:!1,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:!1,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:!1,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:!1,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:!1,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:!1,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 Ae(e){return e.kind===V.IDENTIFIER&&w.has(e.value.toLowerCase())}function Se(e){return e.kind===V.IDENTIFIER&&D.has(e.value.toLowerCase())}function Ce(e){return e.kind===V.IDENTIFIER&&M.has(e.value.toLowerCase())}function Te(e){return e.kind===V.IDENTIFIER&&$.has(e.value.toLowerCase())}function Ne(e){return j.has(e.value.toLowerCase())}function Oe(e){return e.kind===V.IDENTIFIER}function Le(e){return e.kind===V.SELECTOR}function Re(e){return e.kind===V.SELECTOR&&!e.value.startsWith("<")}function $e(e){return e.kind===V.STRING||e.kind===V.NUMBER||e.kind===V.TEMPLATE}function Ie(e){return e.kind===V.IDENTIFIER}function je(e){return e.kind===V.TIME}function Me(e){return e.kind===V.COMMENT}function De(e){if(e.kind!==V.IDENTIFIER)return!1;const t=e.value.toLowerCase();return!(w.has(t)||D.has(t)||M.has(t)||$.has(t))}function Ve(e){return e.kind===V.STRING}function Be(e){return e.kind===V.NUMBER}function Pe(e){if(e.kind===V.IDENTIFIER){const t=e.value;return"true"===t||"false"===t||"null"===t||"undefined"===t}return!1}function _e(e){return e.kind===V.TEMPLATE}function Fe(e){return e.kind===V.SELECTOR&&e.value.startsWith("<")}function Ue(e){return e.kind===V.SELECTOR&&e.value.startsWith("#")}function qe(e){return e.kind===V.SELECTOR&&e.value.startsWith(".")}function He(e){return e.kind===V.SELECTOR&&!e.value.startsWith("#")&&!e.value.startsWith(".")}function We(e){if(e.kind!==V.OPERATOR)return!1;const t=e.value.toLowerCase();return!I.has(t)&&!j.has(t)}function ze(e){const t=e.value.toLowerCase();return"then"===t||"and"===t||"else"===t||"end"===t||"on"===t}function Je(e,t,r){return{type:"literal",value:e,raw:t,start:r.start,end:r.end,line:r.line,column:r.column}}function Ze(e,t){return{type:"identifier",name:e,start:t.start,end:t.end,line:t.line,column:t.column}}function Ge(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}}ke.SKIP_SEMANTIC_COMMANDS=new Set(["swap","morph","js","tell"]);const Ye=[{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 Xe(e,t){return!!e&&t.some(t=>e.value===t||e.value.toLowerCase()===t)}const Ke=[e,n,t,r];function Qe(e,t=[]){if(e.isAtEnd())return!0;for(const t of Ke)if(e.check(t))return!0;for(const r of t)if(e.check(r))return!0;return!!e.checkIsCommand()}function et(e,t=[]){if(!Qe(e,t))return e.parseExpression()}function tt(e,t,r){return!!e.check(t)&&(e.advance(),r.push(e.createIdentifier(t)),!0)}function rt(e,t,r){for(const n of t)if(e.check(n))return e.advance(),r.push(e.createIdentifier(n)),n;return null}class nt{constructor(e){this.args=[],this.isBlocking=!1,this.name=e}static from(e){const t=new nt(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 nt(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 nt(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=!0){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 nt(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 st(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(;!Qe(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 nt.fromIdentifier(t).withArgs(...l).endingAt(e.getPosition()).build()}function it(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 nt.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}function ot(n,s){const i=[];let o=!1;const a=n.current;for(let t=0;500>t&&!n.isAtEnd();t++){const t=n.peek();if(t.value===e){o=!0;break}if(t.value===r||t.value===v||"def"===t.value||t.value===m)break;n.advance()}n.current=a;let c=!1;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=!0);break}if((n.checkIsCommand()||n.isCommand(s))&&void 0!==e.line&&e.line!==i){c=!0;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=!1;if(n.check(t))if(n.advance(),n.check("if")){const e=n.peek();n.advance();const t=ot(n,e);i.push({type:"block",commands:[t],start:e.start,end:n.getPosition().end,line:e.line,column:e.column}),a=!0}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 nt.from(s).withArgs(...i).endingAt(n.getPosition()).build()}function at(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=nt.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition());return Object.keys(n).length>0&&s.withModifiers(n),s.build()}function ct(e,t){const r=[],n=et(e,[f]);n&&r.push(n),tt(e,f,r);const s=et(e);return s&&r.push(s),nt.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}function lt(e,t){const r=[];if(e.check("between")){e.advance(),r.push(e.createIdentifier("between"));const i=et(e,[n]);i&&r.push(i),tt(e,n,r);const o=et(e,[f,m,s]);if(o&&r.push(o),rt(e,[f,m],r)){const t=et(e);t&&r.push(t)}return nt.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}const i=et(e,[f,m]);if(i&&r.push(i),rt(e,[f,m],r)){const t=et(e);t&&r.push(t)}return nt.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}function ut(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?nt.fromIdentifier(t).withArgs(n,e.createIdentifier(i),a).endingAt(e.getPosition()).build():(e.addError("Put command requires target expression after operation keyword"),null)}const ht=["innerhtml","outerhtml","into","over","delete","morph","morphouter"];function ft(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:!1,start:i.start||0,end:s.getPosition().end,line:i.line||1,column:i.column||1}}function dt(e,t){const r=[];for(;!Qe(e,["catch","finally"])&&(e.checkIdentifierLike()||e.checkSelector()||e.checkLiteral()||e.checkTimeExpression()||e.match("<"));)r.push(e.parsePrimary());return nt.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}class pt{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 ke({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:!1,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:!1,node:1===e.length?e[0]:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,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:!1,node:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:this.createProgramNode(e),tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:!1,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")){ye("✅ PARSER: Found event handlers after command sequence, parsing as program");const t=[e];ye(`✅ PARSER: Starting with ${t.length} statement(s) from command sequence`);let r=0;for(;!this.isAtEnd()&&this.check("on");){ye(`✅ PARSER: Parsing event handler #${r+1}, current token: ${this.peek().value}`),this.advance();const e=this.parseEventHandler();if(ye("✅ PARSER: parseEventHandler returned:",e?`type=${e.type}, event=${e.event}`:"null"),e&&(t.push(e),r++,ye(`✅ PARSER: Added event handler, now have ${t.length} statements total`)),ye(`✅ 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 ye("⚠️ PARSER: Unexpected token after event handlers: "+this.peek().value),this.addError("Unexpected token after event handlers: "+this.peek().value),{success:!1,node:this.createProgramNode(t),tokens:this.tokens,error:this.error};ye("✅ PARSER: No more event handlers, at end of input");break}}return ye(`✅ PARSER: Finished parsing, creating Program node with ${t.length} statements`),this.error?{success:!1,node:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:this.createProgramNode(t),tokens:this.tokens,warnings:this.warnings}}return this.isAtEnd()?this.error?{success:!1,node:e,tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:e,tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:!1,node:e||this.createErrorNode(),tokens:this.tokens,error:this.error})}}const e=this.parseExpression();return this.error?{success:!1,node:e||this.createErrorNode(),tokens:this.tokens,error:this.error}:this.isAtEnd()?{success:!0,node:e,tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:!1,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:!1,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(pt.POSTFIX_UNARY_OPERATORS.has(t)){e=this.createUnaryExpression(t,e,!1);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(pt.POSTFIX_UNARY_OPERATORS.has(t)){e=this.createUnaryExpression(t,e,!1);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,!0)}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,!0)}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):T(e)}isKeyword(e){return this.keywordResolver?this.keywordResolver.isKeyword(e):O(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:!1,...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 N(e)}parseCompoundCommand(s){return function(s,i){switch(i.name.toLowerCase()){case"put":return ut(s,i);case"trigger":case"send":return st(s,i);case"remove":return ct(s,i);case"toggle":return lt(s,i);case"set":return ft(s,i);case"halt":return it(s,i);case"measure":return at(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 nt.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 nt.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();ht.includes(s)&&(n=s,e.advance(),r.push(e.createIdentifier(n)))}}if("delete"===n){const n=e.parseExpression();return n&&r.push(n),nt.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 nt.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}(s,i);default:return dt(s,i)}}(this.getContext(),s)}parsePutCommand(e){return ut(this.getContext(),e)}parseSetCommand(e){return ft(this.getContext(),e)}parseHaltCommand(e){return it(this.getContext(),e)}parseMeasureCommand(e){return at(this.getContext(),e)}parseTriggerCommand(e){return st(this.getContext(),e)}parseCommandListUntilEnd(){const e=[];for(ye("🔄 parseCommandListUntilEnd: Starting to parse command list");!this.isAtEnd()&&!this.check("end");){ye("📍 Loop iteration, current token:",this.peek().value,"kind:",this.peek().kind);let t=!1;if(this.checkIsCommand()){ye("✅ Found COMMAND token:",this.peek().value),this.advance();const r=this.error;try{const n=this.parseCommand();this.error&&this.error!==r&&(ye("⚠️ parseCommandListUntilEnd: Command parsing added error, restoring error state. Error was:",this.error.message),this.error=r),n&&(ye("✅ Parsed command:",n.name),e.push(n),t=!0)}catch(e){ye("⚠️ 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)){ye("✅ Found IDENTIFIER that is a command:",r.value),this.advance();const n=this.error;try{const r=this.parseCommand();this.error&&this.error!==n&&(ye("⚠️ parseCommandListUntilEnd: Command parsing added error, restoring error state. Error was:",this.error.message),this.error=n),r&&(ye("✅ Parsed command:",r.name),e.push(r),t=!0)}catch(e){ye("⚠️ parseCommandListUntilEnd: Command parsing threw exception, restoring error state:",e instanceof Error?e.message:e+""),this.error=n}}else ye("❌ IDENTIFIER is not a command:",r.value)}if(!t){ye("❌ No command parsed, breaking. Current token:",this.peek().value);break}for(ye("📍 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(","));)ye("⚠️ Skipping unexpected token:",this.peek().value),this.advance();if(this.match("then","and",","))ye("✅ Found separator, continuing");else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){ye("📍 No separator and no command, breaking. Current token:",this.peek().value);break}ye("✅ Next token is a command, continuing without separator")}}if(ye('🔍 After loop, checking for "end". Current token:',this.peek().value),!this.check("end"))throw ye('❌ ERROR: Expected "end" but got:',this.peek().value,"at position:",this.peek().start),Error('Expected "end" to close repeat block');return ye('✅ Found "end", consuming it'),this.advance(),ye("✅ 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();Oe(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(ye("📍 Parsing event name, current token:",{value:t.value,kind:t.kind}),!Oe(t)&&!Ce(t))throw Error('Expected event name after "event"');if(h=t.value,e.advance(),ye("✅ Got event name:",h,"Next token:",e.peek().value),ye('🔍 Checking for "from", current token:',e.peek().value),e.check(f)){ye('✅ Found "from", advancing...'),e.advance(),ye('📍 After consuming "from", current token:',e.peek().value),e.check(b)&&(ye('✅ Found "the", advancing...'),e.advance());const t=e.peek();ye("🔍 Before parsePrimary for event target:",{value:t.value,kind:t.kind,position:t.start}),p=e.parsePrimary(),ye("✅ After parsePrimary, eventTarget:",p)}else ye('❌ 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();Oe(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}),nt.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(!Oe(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();Oe(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}),nt.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:!0,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(!Oe(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(!Oe(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 nt.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 nt.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(Oe(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 nt.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=et(e,[h]);t&&r.push(t)}if(e.check(h)){e.advance();const t=et(e);t&&r.push(t)}return nt.from(t).withArgs(...r).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseIfCommand(e){return ot(this.getContext(),e)}parseRemoveCommand(e){return ct(this.getContext(),e)}parseToggleCommand(e){return lt(this.getContext(),e)}parseRegularCommand(e){return dt(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),!1)}else if(this.match("[")){const t=this.parseExpression();this.consume("]","Expected ']' after array index"),e=this.createMemberExpression(e,t,!0)}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()&&Oe(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=!0;break;case"false":t=!1;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(De)||this.matchPredicate(Se)||this.matchPredicate(Te)||this.matchPredicate(Ae)||this.matchPredicate(Ce))){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),!1)}}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(De))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(De))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=!1,i=0;for(;!this.isAtEnd()&&(0!==i||!this.check(";")&&!this.check("}"));){const e=this.advance();n.push(e.value),"$"===e.value&&this.check("{")&&(s=!0),"{"===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:!0,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(){ye("🔧 parseEventHandler: ENTRY - parsing event handler");const e=[],t=this.parseEventNameWithNamespace("Expected event name after 'on'");for(e.push(t),ye("🔧 parseEventHandler: Parsed first event name: "+t);this.check("or");){this.advance(),ye("🔧 parseEventHandler: Found 'or', parsing additional event name");const t=this.parseEventNameWithNamespace("Expected event name after 'or'");e.push(t),ye("🔧 parseEventHandler: Parsed additional event name: "+t)}let r;if(ye("🔧 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,ye(`🔧 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"),ye("🔧 parseEventHandler: Parsed event parameters: "+n.join(", "))}const s={};for(;this.check(".");){this.advance();const e=this.advance().value.toLowerCase();if("once"===e)s.once=!0,ye("🔧 parseEventHandler: Parsed modifier '.once'");else if("prevent"===e)s.prevent=!0,ye("🔧 parseEventHandler: Parsed modifier '.prevent'");else if("stop"===e)s.stop=!0,ye("🔧 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,ye(`🔧 parseEventHandler: Parsed modifier '.debounce(${r})'`)):(s.throttle=r,ye(`🔧 parseEventHandler: Parsed modifier '.throttle(${r})'`)),this.consume(")",`Expected ')' after ${e} delay`)}}else ye(`🔧 parseEventHandler: Warning - unknown modifier '.${e}'`)}let i,o,a,c;if(Object.keys(s).length>0&&ye("🔧 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,ye(`🔧 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,ye("🔧 parseEventHandler: Parsed attribute name: "+a)}this.match("in")&&(ye("🔧 parseEventHandler: Found 'in' keyword, parsing watch target"),c=this.parseExpression(),ye("🔧 parseEventHandler: Parsed watch target expression"));const l=[];for(ye(`✅ parseEventHandler: About to parse commands, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd: ${this.isAtEnd()}`);!this.isAtEnd();){if(ye(`✅ parseEventHandler: Loop iteration, current token: ${this.peek().value}, kind: ${this.peek().kind}`),this.check("on")){ye("✅ parseEventHandler: Stopping command parsing, found next event handler 'on'");break}if(this.checkComment())ye("✅ parseEventHandler: Skipping comment token: "+this.peek().value),this.advance();else{if(this.check("end")){ye("✅ 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())||De(s)&&!this.isCommand(s.value)||Te(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:!1,...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:!1,...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:!1,...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&&(ye("⚠️ Command parsing added error, restoring error state. Error was:",this.error.message),this.error=e),l.push(t),ye("✅ parseEventHandler: Parsed command, next token: "+(this.isAtEnd()?"END":this.peek().value))}catch(t){ye("⚠️ 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&&(ye("⚠️ Command parsing added error, restoring error state. Error was:",this.error.message),this.error=e),l.push(t)}catch(t){ye("⚠️ 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){ye("⚠️ 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())||De(s)&&!this.isCommand(s.value)||Te(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:!1,...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:!1,...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:!1,...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:!1,...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 ye(`🔧 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();De(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")||(ye("⚠️ 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"));)ye("⚠️ parseCommandSequence: Skipping unexpected token:",this.peek().value),this.advance();if(this.check("on")){ye('✅ 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 Ye.find(t=>t.command===e.toLowerCase())||null}(e)}isTokenKeyword(e,t){return Xe(e,t)}parseMultiWordCommand(e,t){return function(e,t,r){const n=e.getMultiWordPattern(r);if(!n)return null;const s=[],i={};for(;!Qe(e,["catch","finally",...n.keywords])&&!Xe(e.peek(),n.keywords);){const t=e.parsePrimary();if(!t)break;if(s.push(t),!e.match(",")&&Xe(e.peek(),n.keywords))break}for(;!e.isAtEnd()&&Xe(e.peek(),n.keywords);){const t=e.advance().value,r=e.parseExpression();if(r&&(i[t]=r),!Xe(e.peek(),n.keywords))break}const o=nt.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?(ye(`[Semantic] Successfully parsed with confidence ${t.confidence}:`,t.node.name),t.node):(ye(`[Semantic] Low confidence (${t.confidence}), falling back to traditional parser`),null)}catch(e){return ye("[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(Ae(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=!1;e.check(g)&&(s=!0,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=Je(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=Ge(n,i,o,c);return{type:"command",name:"set",args:[a,Ze(h,c),l],isBlocking:!1,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:!1,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(""),!1);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),!1)}{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),!1)}}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;L(t)&&ye(`💡 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 Je(e,t,this.getPosition())}createIdentifier(e){return Ze(e,this.getPosition())}createBinaryExpression(e,t,r){return Ge(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(ye(`✅ createProgramNode: Called with ${e.length} statements`),0===e.length)return ye("✅ createProgramNode: Returning error node (0 statements)"),{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===e.length)return ye(`✅ 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 ye(`✅ 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(),!0;return!1}matchOperator(e){if(this.isAtEnd())return!1;const t=this.peek();return!(!We(t)||t.value!==e||(this.advance(),0))}check(e){if(this.isAtEnd())return!1;const t=this.peek().value;return this.resolveKeyword(t)===e}checkPredicate(e){return!this.isAtEnd()&&e(this.peek())}matchPredicate(e){return!!this.checkPredicate(e)&&(this.advance(),!0)}checkSelector(){return this.checkPredicate(Re)}matchSelector(){return this.matchPredicate(Re)}checkAnySelector(){return this.checkPredicate(Le)}checkLiteral(){return this.checkPredicate($e)}checkIdentifierLike(){return this.checkPredicate(Oe)}checkIsCommand(){return this.checkPredicate(Ae)}checkCommandTerminator(){return this.checkPredicate(ze)}checkReference(){return this.checkPredicate(Ie)}checkTimeExpression(){return this.checkPredicate(je)}checkEvent(){return this.checkPredicate(Ce)}checkContextVar(){return this.checkPredicate(Te)}checkComment(){return this.checkPredicate(Me)}checkIdentifier(){return this.checkPredicate(De)}checkKeyword(){return this.checkPredicate(Se)}checkString(){return this.checkPredicate(Ve)}matchString(){return this.matchPredicate(Ve)}checkNumber(){return this.checkPredicate(Be)}matchNumber(){return this.matchPredicate(Be)}checkBoolean(){return this.checkPredicate(Pe)}matchBoolean(){return this.matchPredicate(Pe)}checkTemplateLiteral(){return this.checkPredicate(_e)}matchTemplateLiteral(){return this.matchPredicate(_e)}checkQueryReference(){return this.checkPredicate(Fe)}matchQueryReference(){return this.matchPredicate(Fe)}checkIdSelector(){return this.checkPredicate(Ue)}checkClassSelector(){return this.checkPredicate(qe)}checkCssSelector(){return this.checkPredicate(He)}checkBasicOperator(){return this.checkPredicate(We)}matchBasicOperator(){return this.matchPredicate(We)}matchTimeExpression(){return this.matchPredicate(je)}matchIdentifierLike(){return this.matchPredicate(Oe)}matchComparisonOperator(){return this.matchPredicate(Ne)}consumePredicate(e,t){return this.checkPredicate(e)?this.advance():(this.addError(t),this.peek())}consumeIdentifier(e){return this.consumePredicate(De,e)}consumeIdentifierLike(e){return this.consumePredicate(Oe,e)}consumeEvent(e){return this.consumePredicate(Ce,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:!0,configurable:!0}),t}}function mt(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&&(W(t),r>t.position);){const r=e[t.position];if("-"!==r||"-"!==q(t,1))if('"'!==r){if("'"===r||"'"===r){const e=q(t,1),r=t.tokens[t.tokens.length-1];if("s"!==e||!r||r.kind!==V.IDENTIFIER&&r.kind!==V.SELECTOR&&"]"!==r.value&&")"!==r.value&&"}"!==r.value)G(t);else{const e=t.position;H(t),H(t),z(t,B.OPERATOR,"'s",e)}continue}if("`"!==r)if("<"!==r)if("#"!==r){if("."===r){if("."===q(t,1)){const e=t.position;H(t),H(t),z(t,B.OPERATOR,"..",e);continue}const e=t.tokens[t.tokens.length-1],r=new Set(["from","to","into","on","in","at"]),n=e&&e.kind===V.IDENTIFIER&&w.has(e.value.toLowerCase()),s=e&&e.kind===V.IDENTIFIER&&r.has(e.value.toLowerCase());if((!e||e.kind===V.OPERATOR&&")"!==e.value&&"]"!==e.value||n||s||"("===e.value||"["===e.value||"{"===e.value||","===e.value||";"===e.value)&&se(q(t))){X(t);continue}}if("@"!==r)if("{"!==r)if("}"!==r){if("["===r){const e=t.tokens[t.tokens.length-1],r=e&&(e.kind===B.EVENT||e.kind===B.IDENTIFIER&&M.has(e.value))&&t.tokens.length>=2&&"on"===t.tokens[t.tokens.length-2]?.value;(!e||e.kind!==B.IDENTIFIER&&e.kind!==B.CONTEXT_VAR&&")"!==e.value&&"]"!==e.value||r)&&r?(z(t,B.SYMBOL,"["),H(t)):(z(t,B.OPERATOR,"["),H(t));continue}if("]"!==r){if("$"===r){const e=q(t,1);if(e>="a"&&"z">=e||e>="A"&&"Z">=e||"_"===e){ne(t);continue}}ae(r)?ee(t):"0">r||r>"9"?("a">r||r>"z")&&("A">r||r>"Z")&&"_"!==r?(z(t,B.UNKNOWN,r),H(t)):re(t):te(t)}else z(t,B.OPERATOR,"]"),H(t)}else z(t,B.OPERATOR,"}"),H(t);else z(t,B.OPERATOR,"{"),H(t);else Q(t)}else X(t);else oe(t)?K(t):ee(t);else Y(t)}else G(t);else Z(t)}return t.tokens}(e);return new pt(r,t,e).parse()}pt.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty"]);class yt{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!1;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!0;return!1}getRegisteredNames(){return Array.from(this.hooks.keys())}clear(){this.hooks.clear(),this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}}function vt(e){return{ok:!0,value:e}}function gt(e){return{ok:!1,error:e}}function bt(e){return!0===e.ok}class Et{constructor(e){this.elementCleanups=new WeakMap,this.trackedElements=new Set,this.globalCleanups=[],this.debugMode=e?.debug??!1}registerListener(e,t,r,n,s){this.addCleanup(e,{type:"listener",target:t,eventName:r,cleanup:()=>{t.removeEventListener(r,n,s),this.debugMode&&be(`CleanupRegistry: Removed listener '${r}'`)},description:r+" listener"})}registerObserver(e,t){this.addCleanup(e,{type:"observer",cleanup:()=>{t.disconnect(),this.debugMode&&be("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(e,t){this.addCleanup(e,{type:"interval",cleanup:()=>{clearInterval(t),this.debugMode&&be("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(e,t){this.addCleanup(e,{type:"timeout",cleanup:()=>{clearTimeout(t),this.debugMode&&be("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&&be("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&&be(`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&&be("CleanupRegistry: Error during cleanup:",e)}return this.elementCleanups.delete(e),this.trackedElements.delete(e),this.debugMode&&be(`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&&be("CleanupRegistry: Error during global cleanup:",e)}return this.globalCleanups=[],this.debugMode&&be(`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 wt=new Map;function xt(e,t){return{me:e||null,it:null,you:null,result:null,locals:new Map,globals:t||wt,flags:{halted:!1,breaking:!1,continuing:!1,returning:!1,async:!1}}}class kt{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!1}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))}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 At{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??!0,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??!0,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))||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 St=new class{constructor(e={}){this.types=new Map,this.coercionCache=new Map,this.config={strictMode:!1,cacheCoercions:!0,...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!1;if(r.isType(e))return!0;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:!0,direct:!0}:{possible:!1,direct:!1}}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:!1,description:"True or false value",examples:[!0,!1],coerceFrom:{String:e=>{const t=e.toLowerCase().trim();return"true"===t||"yes"===t||"1"===t||"false"!==t&&"no"!==t&&"0"!==t&&""!==t&&t.length>0},Number:e=>0!==e,Null:()=>!1,Undefined:()=>!1,Array:e=>!!Array.isArray(e)&&e.length>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=>!0,defaultValue:null,description:"Unknown/any value type"})}};function Ct(e){const t=St.get("String");return t?t.isType(e):"string"==typeof e}function Tt(e){const t=St.get("Number");return t?t.isType(e):"number"==typeof e}function Nt(e){const t=St.get("Boolean");return t?t.isType(e):"boolean"==typeof e}function Ot(e){const t=St.get("Object");return t?t.isType(e):"object"==typeof e&&null!==e}function Lt(e){const t=St.get("Function");return t?t.isType(e):"function"==typeof e}function Rt(e){if(null===e||"object"!=typeof e||!("tagName"in e))return!1;const t=e.tagName;return"INPUT"===t||"SELECT"===t||"TEXTAREA"===t}function $t(e){return e instanceof Element}const It={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=>Rt(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=>Rt(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 jt(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=It[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 Lt(n)?n.bind(e):n}class Mt{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 ge("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 vt(await this.evaluate(e,t))}catch(e){if(e instanceof Error){const t=e;if(t.isHalt||"HALT_EXECUTION"===t.message)return gt({type:"halt"});if(t.isExit||"EXIT_COMMAND"===t.message)return gt({type:"exit",returnValue:t.returnValue});if(t.isBreak)return gt({type:"break"});if(t.isContinue)return gt({type:"continue"});if(t.isReturn)return gt({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||"";ge("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);ge(`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;ge("TEMPLATE: Evaluating expression:",s);const c=s.trim();t.locals.has(c)?(i=t.locals.get(c),ge(`TEMPLATE: Found in locals: ${c} =`,i)):t.variables&&t.variables.has(c)?(i=t.variables.get(c),ge(`TEMPLATE: Found in variables: ${c} =`,i)):t.globals&&t.globals.has(c)?(i=t.globals.get(c),ge(`TEMPLATE: Found in globals: ${c} =`,i)):(i=await this.evaluateSimpleExpression(s,t),ge(`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){ge("EVAL: Evaluating expression:",e);const r=e.match(/^(.+?)\s*\?\s*(.+?)\s*:\s*(.+)$/);if(r){const[,e,n,s]=r;ge("EVAL: Parsed ternary:",{conditionExpr:e,trueExpr:n,falseExpr:s});const i=await this.resolveValue(e.trim(),t);if(ge("EVAL: Ternary condition value:",i),i){const e=await this.resolveValue(n.trim(),t);return ge("EVAL: Ternary returned true branch:",e),e}{const e=await this.resolveValue(s.trim(),t);return ge("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;ge("EVAL: Parsed arithmetic:",{left:e,operator:r,right:s});const i=await this.resolveValue(e.trim(),t),o=await this.resolveValue(s.trim(),t);ge("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 ge("EVAL: Arithmetic result:",e),e}}const s=await this.resolveValue(e.trim(),t);return ge("EVAL: Fallback result:",s),s}async resolveValue(e,t){if(ge(`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 ge(`RESOLVE: Found '${e}' in locals:`,r),r}if(t.variables&&t.variables.has(e)){const r=t.variables.get(e);return ge(`RESOLVE: Found '${e}' in variables:`,r),r}if(t.globals&&t.globals.has(e)){const r=t.globals.get(e);return ge(`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 ge(`RESOLVE: Property access failed at '${r[e-1]}'`);s=s[r[e]]}return ge(`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 ge("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!1}return!1}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!1}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){ge("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){ge("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+"");case"match":case"matches":if(i&&"function"==typeof i.matches){const e="string"==typeof o?o:o+"";try{return i.matches(e)}catch{return!1}}return!1;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);case"some":return null!=s&&("string"==typeof s||Array.isArray(s)||s instanceof NodeList||s instanceof HTMLCollection?s.length>0:"object"!=typeof s||Object.keys(s).length>0);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=$t(r)?jt(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=$t(s)?jt(s,n):s[n],"function"==typeof e?e.bind(s):e}catch(e){throw Error(`Failed to access property "${n}" on target: ${e}`)}}}const Dt={1:"one",2:"two",3:"three",4:"four",5:"five"};function Vt(e,t,r,n){if(e.length!==t){return`${r} requires exactly ${s=t,Dt[s]??s+""} argument${1===t?"":"s"}${n?` (${n})`:""}`}var s;return null}function Bt(e,t,r,n){return"string"!=typeof e[t]?`${r} ${n||"argument "+(t+1)} must be a string`:null}function Pt(e,t,r){return Vt(e,1,t,r)??Bt(e,0,t,r)}function _t(e,t){return Vt(e,2,t,"left, right")}function Ft(){return null}function Ut(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 qt(e,t,r,n,s){return t>e.length||e.length>r?`${n} requires ${t}-${r} arguments${s?` (${s})`:""}`:null}function Ht(e,t,r,n=[]){return{type:e,message:t,suggestions:n,...r&&{path:r}}}const Wt="undefined"!=typeof process&&"production"===process.env.NODE_ENV||"undefined"!=typeof process&&"true"===process.env.HYPERFIXI_SKIP_VALIDATION||"undefined"!=typeof globalThis&&"true"===globalThis.HYPERFIXI_SKIP_VALIDATION;let zt;function Jt(){return zt({validate:e=>({success:!0,data:e})})}function Zt(e,t){if(Wt)return Jt();const r=zt({validate:r=>{if("object"!=typeof r||null===r||Array.isArray(r))return{success:!1,error:Ht("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:!1,error:Ht("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:!1,error:Ht("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:!1,error:Ht("missing-argument",`Required field "${t}" is missing`,t)};void 0!==i.data&&(s[t]=i.data)}return{success:!0,data:s}}});return r.strict=()=>Zt(e,{strict:!0}),r}zt=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:!0,data:t.data}:{success:!1,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:!0,validate:t=>null==t?{success:!0,data:void 0}:e(t)};return zt(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:!1,error:Ht("runtime-error",`String must be at least ${e} characters long`)}:n}};return zt(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:!1,error:Ht("runtime-error",`String must be at most ${e} characters long`)}:n}};return zt(r)}),e.default||(e.default=function(e){const t=this.validate.bind(this),r={...this,i:e,o:!0,validate:r=>void 0===r?{success:!0,data:e}:t(r)};return zt(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 Gt=e=>zt(function(e={}){return Wt?Jt():zt({validate:t=>e.optional&&null==t?{success:!0,data:void 0}:"string"!=typeof t?{success:!1,error:Ht("type-mismatch","Expected string, received "+typeof t)}:void 0!==e.minLength&&e.minLength>t.length?{success:!1,error:Ht("runtime-error",`String must be at least ${e.minLength} characters long`)}:void 0!==e.maxLength&&t.length>e.maxLength?{success:!1,error:Ht("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:!1,error:Ht("runtime-error",`Expected "${e.pattern.source.slice(1,-1)}", received "${t}"`)}:{success:!1,error:Ht("missing-argument","String does not match required pattern")}:{success:!0,data:t},...e.description&&{description:e.description}})}(e||{})),Yt=e=>zt(function(e={}){return Wt?Jt():zt({validate:t=>{const r=Number(t);return isNaN(r)?{success:!1,error:Ht("type-mismatch","Expected number, received "+typeof t)}:void 0!==e.min&&e.min>r?{success:!1,error:Ht("runtime-error","Number must be at least "+e.min)}:void 0!==e.max&&r>e.max?{success:!1,error:Ht("runtime-error","Number must be at most "+e.max)}:{success:!0,data:r}}})}(e||{})),Xt=()=>zt(Wt?Jt():zt({validate:e=>"boolean"!=typeof e?{success:!1,error:Ht("type-mismatch","Expected boolean, received "+typeof e)}:{success:!0,data:e}})),Kt=e=>zt(Zt(e)),Qt=e=>zt(function(e){return Wt?Jt():zt({validate:t=>{if(!Array.isArray(t))return{success:!1,error:Ht("type-mismatch","Expected array, received "+typeof t)};if(t.length!==e.length)return{success:!1,error:Ht("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:!1,error:Ht("runtime-error",s.error.message,s.error.path?`${n}.${s.error.path}`:""+n)};r.push(s.data)}return{success:!0,data:r}}})}(e)),er=()=>zt(Jt()),tr=()=>zt(Jt()),rr=()=>zt(function(e,t="Custom validation failed"){return Wt?Jt():zt({validate:r=>e(r)?{success:!0,data:r}:{success:!1,error:Ht("runtime-error",t)}})}(e=>void 0===e,"Expected undefined"));class nr{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!(!1===e||0===e||0n===e||""===e||null==e||Tt(e)&&isNaN(e))}success(e,t){return{success:!0,value:e,type:t}}failure(e,t,r,n,s=[]){return{success:!1,error:{name:e,type:t,message:r,code:n,suggestions:s}}}validationSuccess(){return{isValid:!0,errors:[],suggestions:[]}}validationFailure(e,t,r=[]){return{isValid:!1,errors:[{type:e,message:t,suggestions:r}],suggestions:r}}isElement(e){return null!=e&&Ot(e)&&1===e.nodeType}inferType(e){return null===e?"null":void 0===e?"undefined":this.isElement(e)?"element":Array.isArray(e)?"array":Ot(e)?"object":typeof e}normalizeCollection(e){return Array.isArray(e)?e:e instanceof NodeList?Array.from(e):Ct(e)?e.split(""):null==e?[]:Ot(e)&&Symbol.iterator in e?Array.from(e):[]}toNumber(e){if(Tt(e)&&Number.isFinite(e))return e;if(Ct(e)){const t=Number(e);return Number.isFinite(t)?t:null}return Nt(e)?e?1:0:null}}const sr=Kt({selector:Gt().min(1),single:Xt().optional().default(!1)});new class extends nr{constructor(){super(...arguments),this.name="me",this.category="Reference",this.syntax="me",this.description="References the current element in the execution context",this.inputSchema=rr(),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 nr{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=rr(),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 nr{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=rr(),this.outputType="Any",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=e.it,s={success:!0,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 nr{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=sr,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:!0,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:!1,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),!0}catch{return!1}}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 ir={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me instanceof HTMLElement?e.me:null,validate:Ft},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.you instanceof HTMLElement?e.you:null,validate:Ft},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:Ft},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:Ft},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.result,validate:Ft},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=>Pt(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=>Pt(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=>Pt(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=>Pt(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:Ft},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async e=>window,validate:Ft},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async e=>document,validate:Ft},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=>Pt(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=>qt(e,1,2,"styleRef","property, optional element")??Bt(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=>Vt(e,2,"possessiveStyleRef","possessor, property")??Bt(e,0,"possessiveStyleRef","possessor")??Bt(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=>Vt(e,2,"ofStyleRef","property, reference")??Bt(e,0,"ofStyleRef","property")??Bt(e,1,"ofStyleRef","reference")}};class or{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 ar=new class{constructor(){this.domQueryCache=new or(200,3e3),this.exprResultCache=new or(500,2e3),this.cssMatchCache=new or(100,5e3),this.formValueCache=new or(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(()=>{ar.cleanup()},1e4);const cr=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=ar.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 lr(){ar.cleanup(),cr.getMetrics().memoryUsage>52428800&&cr.reset()}let ur=null;function hr(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 fr(e,t,r,n,s,i=!0,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){ur&&clearInterval(ur),ur=setInterval(lr,e)}();const dr=Kt({left:er().describe("Left operand value"),right:er().describe("Right operand value")}).strict(),pr=Kt({operand:er().describe("Operand value to negate")}).strict();new class extends nr{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=dr,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:!1,error:n.errors[0]};const s=this.toBoolean(t.left);if(!s)return this.trackSimple(e,r,!0,"boolean"),this.success(!1,"boolean");const i=this.toBoolean(t.right),o=s&&i;return this.trackSimple(e,r,!0,"boolean"),this.success(o,"boolean")}catch(t){return this.trackSimple(e,r,!1),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:!1,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 nr{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=dr,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:!1,error:n.errors[0]};const s=this.toBoolean(t.left);if(s)return this.trackSimple(e,r,!0,"boolean"),this.success(!0,"boolean");const i=this.toBoolean(t.right),o=s||i;return this.trackSimple(e,r,!0,"boolean"),this.success(o,"boolean")}catch(t){return this.trackSimple(e,r,!1),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:!1,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 nr{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=pr,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:!1,error:n.errors[0]};const s=!this.toBoolean(t.operand);return this.trackSimple(e,r,!0,"boolean"),this.success(s,"boolean")}catch(t){return this.trackSimple(e,r,!1),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:!1,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 mr=Qt([er(),er()]),yr=Qt([er(),Gt()]),vr={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(e,t,r){const n=Date.now();try{return fr(this,e,[t,r],t==r,n)}catch(s){throw fr(this,e,[t,r],!1,n,!1,s instanceof Error?s:Error(s+"")),s}},validate:e=>_t(e,"equals"),inputSchema:mr,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"value is 5",description:"Check if value equals 5 using loose equality",expectedOutput:!0,context:{result:5}},{input:'"5" == 5',description:'String "5" equals number 5 with type coercion',expectedOutput:!0}],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:!1,examples:["5",'"hello"',"true","null"]},{name:"right",type:"unknown",description:"Right operand for comparison",optional:!1,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"]}},gr={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],evaluate:async(e,t,r)=>t===r,validate:e=>_t(e,"strictEquals")},br={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=>_t(e,"notEquals")},Er={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],evaluate:async(e,t,r)=>t!==r,validate:e=>_t(e,"strictNotEquals")},wr={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],evaluate:async(e,t,r)=>r>t,validate:e=>_t(e,"lessThan")},xr={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=>_t(e,"lessThanOrEqual")},kr={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],evaluate:async(e,t,r)=>t>r,validate:e=>_t(e,"greaterThan")},Ar={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=>_t(e,"greaterThanOrEqual")},Sr={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(e,t,r){const n=Date.now();try{return fr(this,e,[t,r],t&&r,n)}catch(s){throw fr(this,e,[t,r],!1,n,!1,s instanceof Error?s:Error(s+"")),s}},validate:e=>_t(e,"and"),inputSchema:mr,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"true and false",description:"Logical AND of boolean values",expectedOutput:!1},{input:"name and age",description:"Both name and age must be truthy",expectedOutput:!0,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:!1,examples:["true","name","5",'"hello"']},{name:"right",type:"unknown",description:"Right operand (evaluated for truthiness)",optional:!1,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"]}},Cr={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],evaluate:async(e,t,r)=>t||r,validate:e=>_t(e,"or")},Tr={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],evaluate:async(e,t)=>!t,validate:e=>Vt(e,1,"not","operand")},Nr={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],evaluate:async(e,t)=>null==t||(Ct(t)||Array.isArray(t)||t instanceof NodeList?0===t.length:!(t instanceof Node||t instanceof Element||!Ot(t)||0!==Object.keys(t).length)),validate:e=>Vt(e,1,"isEmpty","value")},Or={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],evaluate:async(e,t)=>null==t||!1===t||(Array.isArray(t)||t instanceof NodeList?0===t.length:!(Ct(t)||t instanceof Node||t instanceof Element||!Ot(t)||0!==Object.keys(t).length)),validate:e=>Vt(e,1,"no","value")},Lr={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],evaluate:async(e,t)=>!await Nr.evaluate(e,t),validate:e=>Vt(e,1,"isNotEmpty","value")},Rr={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],evaluate:async(e,t)=>null!=t,validate:e=>Vt(e,1,"exists","value")},$r={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],evaluate:async(e,t)=>null==t,validate:e=>Vt(e,1,"doesNotExist","value")},Ir={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(Ct(t)&&t.match(/^[.#][\w-]+$/)){const e=document.querySelector(t);if(e&&1===r.nodeType)return e.contains(r);if(e&&Ct(r)&&r.match(/^[.#][\w-]+$/)){const t=document.querySelector(r);return!!t&&e.contains(t)}}if(Ct(r)&&r.match(/^[.#][\w-]+$/)&&1===t.nodeType){const e=document.querySelector(r);return!!e&&t.contains(e)}}return Ct(t)&&Ct(r)||Array.isArray(t)?t.includes(r):"undefined"!=typeof NodeList&&t instanceof NodeList?Array.from(t).includes(r):!(!Ot(t)||!Ct(r))&&r in t},validate:e=>Vt(e,2,"contains","container, value")},jr={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],evaluate:async(e,t,r)=>!await Ir.evaluate(e,t,r),validate:e=>Vt(e,2,"doesNotContain","container, value")},Mr={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],evaluate:async(e,t,r)=>!(!Ct(t)||!Ct(r))&&t.startsWith(r),validate:e=>Vt(e,2,"startsWith","str, prefix")},Dr={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],evaluate:async(e,t,r)=>!(!Ct(t)||!Ct(r))&&t.endsWith(r),validate:e=>Vt(e,2,"endsWith","str, suffix")},Vr={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(e,t,r){const n=Date.now();try{let s;if(t instanceof Element&&Ct(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 ar.matches(e,t)}(t,e)}catch(e){s=!1}else s=!1}else if(Ct(t)&&Ct(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=!1;return fr(this,e,[t,r],s,n)}catch(s){throw fr(this,e,[t,r],!1,n,!1,s instanceof Error?s:Error(s+"")),s}},validate:e=>Vt(e,2,"matches","element, selector"),inputSchema:yr,metadata:{category:"Logical",complexity:"medium",sideEffects:["dom-query"],dependencies:[],returnTypes:["Boolean"],examples:[{input:'element matches ".active"',description:"Check if element has active class",expectedOutput:!0},{input:'text matches "/^hello/"',description:'Check if text starts with "hello" using regex',expectedOutput:!0,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:!1,examples:["<div>",'"hello world"',"me","target"]},{name:"selector",type:"string",description:"CSS selector or regex pattern to match against",optional:!1,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"]}},Br={equals:vr,strictEquals:gr,notEquals:br,strictNotEquals:Er,lessThan:wr,lessThanOrEqual:xr,greaterThan:kr,greaterThanOrEqual:Ar,and:Sr,or:Cr,not:Tr,no:Or,isEmpty:Nr,isNotEmpty:Lr,exists:Rr,doesNotExist:$r,contains:Ir,doesNotContain:jr,startsWith:Mr,endsWith:Dr,matches:Vr};function Pr(e,t,r,n,s="runtime-error"){return{success:!1,error:{name:e+"ConversionError",type:s,message:r,code:t,suggestions:n}}}function _r(e,t){return{success:!0,value:e,type:t}}function Fr(e,t){return`${e}: ${t instanceof Error?t.message:t+""}`}const Ur={Array:(e,t)=>{try{return Array.isArray(e)?_r(e,"array"):e instanceof NodeList?_r(Array.from(e),"array"):_r(null==e?[]:[e],"array")}catch(e){return Pr("Array","ARRAY_CONVERSION_FAILED",Fr("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?_r("","string"):Ct(e)?_r(e,"string"):Ot(e)?_r(JSON.stringify(e),"string"):_r(e+"","string")}catch(e){return Pr("String","STRING_CONVERSION_FAILED",Fr("Failed to convert value to String",e),["Check if object has circular references","Ensure value is serializable"])}},Boolean:(e,t)=>{try{if(Nt(e))return _r(e,"boolean");if(null==e)return _r(!1,"boolean");if(Ct(e)){const t=e.toLowerCase().trim();return _r("false"!==t&&"0"!==t&&""!==t,"boolean")}return Tt(e)?_r(0!==e&&!isNaN(e),"boolean"):_r(!!e,"boolean")}catch(e){return Pr("Boolean","BOOLEAN_CONVERSION_FAILED",Fr("Failed to convert value to Boolean",e),["Use explicit true/false values","Check for unexpected data types"])}},Number:(e,t)=>{try{if(Tt(e))return _r(e,"number");if(null==e)return _r(0,"number");const t=Number(e);return isNaN(t)?Pr("Number","INVALID_NUMBER",`Cannot convert "${e}" to a valid number`,["Check if value contains non-numeric characters","Use a valid numeric format"],"invalid-argument"):_r(t,"number")}catch(e){return Pr("Number","NUMBER_CONVERSION_FAILED",Fr("Failed to convert value to Number",e),["Ensure value is convertible to number","Check for special characters"])}},Int:(e,t)=>{const r=Ur.Number(e,t);return r.success?_r(Math.trunc(r.value),"number"):r},Float:(e,t)=>{const r=Ur.Number(e,t);return r.success?_r(parseFloat(""+r.value),"number"):r},Date:(e,t)=>{try{if(e instanceof Date)return _r(e,"object");if(null==e)return _r(new Date(""),"object");if(Ct(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,r,n]=e.split("-").map(Number);return _r(new Date(t,r-1,n),"object")}const t=new Date(e);return isNaN(t.getTime())?Pr("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"):_r(t,"object")}catch(e){return Pr("Date","DATE_CONVERSION_FAILED",Fr("Failed to convert value to Date",e),["Check date format","Ensure value is a valid date string or timestamp"])}},JSON:(e,t)=>{try{return _r(JSON.stringify(e),"string")}catch(e){return Pr("JSON","JSON_STRINGIFY_FAILED",Fr("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(Ot(e))return _r(e,"object");if(Ct(e))try{return _r(JSON.parse(e),"object")}catch(e){return Pr("Object","JSON_PARSE_FAILED",Fr("Cannot parse JSON string",e),["Check JSON syntax","Ensure proper escaping of quotes","Validate JSON format"],"syntax-error")}return _r({},"object")}catch(e){return Pr("Object","OBJECT_CONVERSION_FAILED",Fr("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 _r(function(e){const t={};return e.querySelectorAll("input, select, textarea").forEach(e=>{const r=e;if(r.name){const e=Wr(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=Wr(t);void 0!==e&&(r[t.name]=e)}}),_r(r,"object")}return _r({},"object")}catch(e){return Pr("FormValues","FORM_VALUES_EXTRACTION_FAILED",Fr("Failed to extract form values",e),["Ensure element is a form or contains form inputs","Check form structure","Verify input names are set"])}}},qr=Kt({value:tr(),type:Gt().min(1)}),Hr=Kt({value:tr(),type:Gt().min(1)});function Wr(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 nr{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=qr,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:!1,examples:['"123"',"form","[1,2,3]","true","null"]},{name:"type",type:"string",description:"Target conversion type",optional:!1,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:!1,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=Ur.Number(s,e);if(!a.success)return a;const c={success:!0,value:a.value.toFixed(o),type:"string"};return this.trackPerformance(e,t,c,r),c}let o=Ur[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=Ur[a],o)){const n=o(s,e);return this.trackPerformance(e,t,n,r),n}const c={success:!1,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:!1,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:!0,errors:[],suggestions:[]}:{isValid:!1,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 nr{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=Hr,this.metadata={category:"Conversion",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"42 is number",description:"Check if value is a number",expectedOutput:!0},{input:"null is empty",description:"Check if value is empty/null",expectedOutput:!0},{input:"element is Element",description:"Check if value is DOM element",expectedOutput:!0,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:!1,examples:["42","null","element",'"text"',"[]"]},{name:"type",type:"string",description:"Type name to check against",optional:!1,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:!1,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=Ct(s);break;case"number":a=Tt(s)&&!isNaN(s);break;case"boolean":a=Nt(s);break;case"object":a=Ot(s);break;case"array":a=Array.isArray(s);break;case"function":a=Lt(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||Ot(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:!1,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 zr={Array:e=>Array.isArray(e)?e:e instanceof NodeList?Array.from(e):null==e?[]:[e],String:e=>null==e?"":Ct(e)?e:Ot(e)?JSON.stringify(e):e+"",Boolean:e=>{if(Nt(e))return e;if(null==e)return!1;if(Ct(e)){const t=e.toLowerCase().trim();return"false"!==t&&"0"!==t&&""!==t}return Tt(e)?0!==e&&!isNaN(e):!!e},Number:e=>{if(Tt(e))return e;if(null==e)return 0;const t=Number(e);return isNaN(t)?0:t},Math:e=>{if(Tt(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(!Tt(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=zr.Number(e);return Math.trunc(t)},Float:e=>{const t=zr.Number(e);return parseFloat(""+t)},Date:e=>{if(e instanceof Date)return e;if(null==e)return new Date(NaN);if(Ct(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(Ot(e))return e;if(Ct(e))try{return JSON.parse(e)}catch(e){return{}}return{}},Fragment:e=>{Ct(e)||(e=zr.String(e));const t=document.createElement("template");return t.innerHTML=e+"",t.content},HTML:e=>Ct(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:zr.String(e)).join(""):e instanceof Element?e.outerHTML:zr.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=Jr(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]=Jr(e))}),r}return{}},"Values:Form":(e,t)=>{const r=zr.Values(e,t);return""+new URLSearchParams(r)},"Values:JSON":(e,t)=>{const r=zr.Values(e,t);return JSON.stringify(r)}};function Jr(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 Zr={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 zr.Number(r).toFixed(e||2)}let s=zr[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=zr[i],s)?s(r,e):(console.warn("Unknown conversion type: "+n),r)},validate:e=>Vt(e,2,"as","value, type")??Bt(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(!Ct(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 Ct(r);case"number":return Tt(r)&&!isNaN(r);case"boolean":return Nt(r);case"object":return Ot(r);case"array":return Array.isArray(r);case"function":return Lt(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||Ot(r)&&0===Object.keys(r).length;default:return r?.constructor?.name?.toLowerCase()===n.toLowerCase()}},validate:e=>Vt(e,2,"is","value, type")??Bt(e,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(e,t)=>t,validate:e=>Vt(e,1,"async","expression")}},Gr={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"},Yr=Kt({collection:er().describe("Collection to operate on (array, NodeList, or string)")}).strict(),Xr=Kt({collection:er().describe("Collection to access"),index:Yt().describe("Index position to access")}).strict(),Kr=Kt({collection:er().describe("Collection to select random item from")}).strict();function Qr(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?Qr(n,t):null}function en(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?en(n,t):null}function tn(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 nr{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=Yr,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:!1,error:n.errors[0]};const s=this.normalizeCollection(t.collection),i=s.length>0?s[0]:void 0,o={success:!0,value:i,type:Gr[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:!1,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":Ct(e)?"String":Tt(e)?"Number":Nt(e)?"Boolean":Array.isArray(e)?"Array":e instanceof HTMLElement?"Element":"Object"}},new class extends nr{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=Yr,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:!1,error:n.errors[0]};const s=this.normalizeCollection(t.collection),i=s.length>0?s[s.length-1]:void 0,o={success:!0,value:i,type:Gr[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:!1,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":Ct(e)?"String":Tt(e)?"Number":Nt(e)?"Boolean":Array.isArray(e)?"Array":e instanceof HTMLElement?"Element":"Object"}},new class extends nr{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=Xr,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:!1,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:!0,value:o,type:Gr[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:!1,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":Ct(e)?"String":Tt(e)?"Number":Nt(e)?"Boolean":Array.isArray(e)?"Array":e instanceof HTMLElement?"Element":"Object"}},new class extends nr{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=Kr,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:!1,error:n.errors[0]};const s=this.normalizeCollection(t.collection);if(0===s.length){const n={success:!0,value:void 0,type:"undefined"};return this.trackPerformance(e,t,n,r),n}const i=s[this.getSecureRandomIndex(s.length)],o={success:!0,value:i,type:Gr[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:!1,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":Ct(e)?"String":Tt(e)?"Number":Nt(e)?"Boolean":Array.isArray(e)?"Array":e instanceof HTMLElement?"Element":"Object"}};const rn={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:Ct(r)?r.length>0?r[0]:null:Ot(r)&&"length"in r&&Tt(r.length)&&r.length>0?r[0]:null},validate:e=>Ut(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 Ct(r)?r.length>0?r[r.length-1]:null:Ot(r)&&"length"in r&&Tt(r.length)&&r.length>0?r[r.length-1]:null},validate:e=>Ut(e,1,"last","collection")},at:{name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(e,...t){const[r,n]=t;if(!Tt(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(Ct(i)){const e=0>s?i.length+s:s;return e>=0&&i.length>e?i[e]:null}if(Ot(i)&&"length"in i&&Tt(i.length)){const e=0>s?i.length+s:s;return e>=0&&i.length>e?i[e]:null}return null},validate:e=>qt(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?Qr(s,r):s.nextElementSibling:null},validate:e=>Ut(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?en(s,r):s.previousElementSibling:null},validate:e=>Ut(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=tn(e);for(const e of n)if(tn(e)>s)return e;return null}(i,r,o):null},validate:e=>qt(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=tn(e);for(let e=n.length-1;e>=0;e--){const t=n[e];if(s>tn(t))return t}return null}(i,r,o):null},validate:e=>qt(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")}},nn={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?jt(r,n):(Ot(r),r[n])}},validate:e=>Vt(e,2,"possessive","element, property")??Bt(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?jt(e.me,r):(Ot(e.me),e.me[r])}},validate:e=>Pt(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?jt(n,r):(Ot(n),n[r])},validate:e=>Pt(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?jt(e.you,r):(Ot(e.you),e.you[r])}},validate:e=>Pt(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?jt(n,r):(Ot(n),n[r])}},validate:e=>Vt(e,2,"of","property, object")??Bt(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=>qt(e,1,2,"attribute","attributeName, optional element")??Bt(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},validate:e=>qt(e,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??Bt(e,0,"attributeWithValue","attribute name")??Bt(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=>Pt(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=>Pt(e,"idReference","idValue")}},sn=Kt({value:Gt().describe("String literal value")}).strict(),on=Kt({value:Yt().describe("Number literal value")}).strict(),an=Kt({value:Xt().describe("Boolean literal value")}).strict(),cn=Kt({left:er().describe("Left operand"),right:er().describe("Right operand")}).strict();const ln={stringLiteral:new class extends nr{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=sn,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,!1),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,!0,s),i}catch(t){return this.trackSimple(e,r,!1),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 nr{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=on,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,!0,t.value),this.success(t.value,"number")):(this.trackSimple(e,r,!1),this.failure("NumberValidationError","invalid-argument","Number literal must be finite","NUMBER_NOT_FINITE")):(this.trackSimple(e,r,!1),this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions))}catch(t){return this.trackSimple(e,r,!1),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 nr{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=an,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,!0,t.value),this.success(t.value,"boolean")):(this.trackSimple(e,r,!1),this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions))}catch(t){return this.trackSimple(e,r,!1),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 nr{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=cn,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,!1),this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions);const s=hr(t.left,"left operand")+hr(t.right,"right operand");return this.trackSimple(e,r,!0,s),this.success(s,"number")}catch(t){return this.trackSimple(e,r,!1),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 nr{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=cn,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,!1),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,!0,s),this.success(s,"string")}catch(t){return this.trackSimple(e,r,!1),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=cn.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(Ct(e))return e;if(Tt(e))return""+e;if(Nt(e))return""+e;if(e instanceof Date)return""+e;try{return e+""}catch{return"[object Object]"}}},multiplication:new class extends nr{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=cn,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,!1),this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions);const s=hr(t.left,"left operand")*hr(t.right,"right operand");return this.trackSimple(e,r,!0,s),this.success(s,"number")}catch(t){return this.trackSimple(e,r,!1),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 un extends Mt{constructor(){super(),this.registerExpressions()}registerExpressions(){this.registerCategory(ir),this.registerCategory(Br),this.registerCategory(Zr),this.registerCategory(rn),ve("About to register properties expressions:",Object.keys(nn)),this.registerCategory(nn),ve("Total expressions registered:",this.expressionRegistry.size),ve('Registry has "possessive":',this.expressionRegistry.has("possessive")),ve('Registry has "my":',this.expressionRegistry.has("my")),this.registerCategory(ln)}}class hn{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 fn{constructor(e,t,r){this.impl=e,this.expressionEvaluator=t??new un,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(pe(`CommandAdapterV2: Executing '${this.name}' with args:`,t),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(n),this.hookRegistry?.shouldIntercept(this.name,n))return void pe(`CommandAdapterV2: '${this.name}' intercepted by hook`);e.locals||(e.locals=new Map),e.locals.set("__evaluator",this.expressionEvaluator);const s=hn.toTyped(e);let i,o;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(pe(`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 pe(`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 pe(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),i=t;return pe("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),pe("CommandAdapterV2: Command result:",o),Object.assign(e,hn.fromTyped(s,e)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(n,o),o}catch(e){if(pe(`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:!0,errors:[],suggestions:[]}}}class dn{constructor(e,t){this.adapters=new Map,this.implementations=new Map,this.sharedEvaluator=e,this.hookRegistry=t}setHookRegistry(e){this.hookRegistry=e,be("CommandRegistryV2: Hook registry set")}getHookRegistry(){return this.hookRegistry}register(e){const t=(e.name||e.metadata?.name).toLowerCase();be(`CommandRegistryV2: Registering command '${t}'`),this.implementations.set(t,e);const r=new fn(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:!1,errors:[{type:"runtime-error",message:"Unknown command: "+e,suggestions:["Available commands: "+this.getCommandNames().join(", ")]}],suggestions:["Available commands: "+this.getCommandNames().join(", ")]}}}let pn=null;function mn(){return pn||(pn=function(e){const t=e?.commands??new dn,r=e?.eventSources??new kt,n=e?.context??new At,s=new Set,i={commands:t,eventSources:r,context:n,use(e){if(s.has(e.name))console.warn(`[LokaScriptRegistry] Plugin '${e.name}' is already installed`);else{if(e.commands)for(const r of e.commands)t.register(r);if(e.eventSources)for(const t of e.eventSources)r.register(t.name,t);if(e.contextProviders)for(const{name:t,provide:r,options:s}of e.contextProviders)n.register(t,r,s);e.setup?.(i),s.add(e.name)}},reset(){s.clear()}};return i}()),pn}class yn{constructor(e={}){this.contextCache=new WeakMap;const t=mn();this.options={enableContextProviders:e.enableContextProviders??!0,enableEventSources:e.enableEventSources??!0,registry:e.registry??{}},this.contextRegistry=this.options.registry.context??t.context,this.eventSourceRegistry=this.options.registry.eventSources??t.eventSources,be(`[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),be(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),t}catch(t){return be("[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 be(`[RegistryIntegration] Found event source for '${e}'`),t;const r=this.eventSourceRegistry.findSourceForEvent(e);if(r){const t=this.eventSourceRegistry.get(r);return be(`[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 be(`[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,be("[RegistryIntegration] Destroyed")}}class vn{constructor(e){this.autoCleanupObserver=null,this.registryIntegration=null,this.options={commandTimeout:1e4,enableErrorReporting:!0,enableResultPattern:!0,enableAutoCleanup:!0,...e},this.registry=e.registry,this.expressionEvaluator=e.expressionEvaluator,this.behaviorRegistry=new Map,this.globalVariables=wt,this.hookRegistry=new yt,e.hooks&&this.hookRegistry.register("default",e.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new Et,this.options.enableAutoCleanup&&this.setupAutoCleanup(),!1!==e.registryIntegration&&(this.registryIntegration=new yn("object"==typeof e.registryIntegration?e.registryIntegration:{}),be("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&&be(`RuntimeBase: Auto-cleaned ${t} resources for removed element`)}}),document.body?this.autoCleanupObserver.observe(document.body,{childList:!0,subtree:!0}):document.addEventListener("DOMContentLoaded",()=>{this.autoCleanupObserver?.observe(document.body,{childList:!0,subtree:!0})},{once:!0}))}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(),be("RuntimeBase: Destroyed")}async execute(e,t){be(`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(!bt(r)){const e=r.error,t=Error(e.type.toUpperCase()+"_EXECUTION");throw t["is"+e.type.charAt(0).toUpperCase()+e.type.slice(1)]=!0,"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(!bt(n)){const e=n.error,t=Error(e.type.toUpperCase()+"_EXECUTION");throw t["is"+e.type.charAt(0).toUpperCase()+e.type.slice(1)]=!0,"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(!bt(r)){const e=r.error,t=Error(e.type.toUpperCase()+"_EXECUTION");throw t["is"+e.type.charAt(0).toUpperCase()+e.type.slice(1)]=!0,"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(pe(`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&&(!0===e.isHalt||!0===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(pe(`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 vt(await o.execute(t,{args:n||[],modifiers:s||{},commandName:i,runtime:this}))}catch(e){const t=this.toSignal(e);if(t)return gt(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(!bt(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}),vt(r.returnValue)}}r=e.value}else{const e=await this.evaluateExpressionWithResult(n,t);if(!bt(e))return e;r=e.value}return vt(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(!bt(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 vt(await this.executeCommandFromPattern(n.command,n.selector,t))}catch(e){const t=this.toSignal(e);if(t)return gt(t);throw e}}return vt(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}),be(`RUNTIME BASE: Registered behavior '${r}'`)}async installBehaviorOnElement(e,t,r){be("BEHAVIOR: installBehaviorOnElement called: "+e);const n=this.behaviorRegistry.get(e);if(!n)throw Error(`Behavior "${e}" not found`);be("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:!1,returned:!1,broke:!1,continued:!1,async:!1},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){be("BEHAVIOR: Running init block for "+e);try{await this.execute(n.initBlock,i),be("BEHAVIOR: Init block completed for "+e)}catch(t){if(be(`BEHAVIOR: Init block error for ${e}:`,t),!(t instanceof Error&&t.isHalt))throw t}}if(be(`BEHAVIOR: About to attach ${n.eventHandlers?.length||0} handlers for ${e}`),n.eventHandlers)for(const e of n.eventHandlers)await this.executeEventHandler(e,i);be("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];be(`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);be(`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 be(`BEHAVIOR: Target resolution: querying for '${i}'`),f=this.queryElements(i,t)}else f=t.me?[t.me]:[];if(0===f.length&&!d)return void be(`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){be(`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);be(`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);be(`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:!0}: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){be(`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){me(`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:!0,attributeOldValue:!0,attributeFilter:[t]}),this.cleanupRegistry.registerObserver(s,e),be("RUNTIME BASE: MutationObserver attached to",s,`for attribute '${t}'`)}}async setupChangeObserver(e,t,r){be("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))),be(`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){me("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:!0,characterData:!0,subtree:!0,characterDataOldValue:!0}),this.cleanupRegistry.registerObserver(e,n),be("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||e&&"object"==typeof e&&e.style&&e.classList}}class gn{constructor(e){this.observer=null,this.initialized=!1,this.runtime=e}init(){"undefined"!=typeof document&&(this.initialized||(this.initialized=!0,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:!0,subtree:!0,attributes:!0,attributeFilter:["_"]})))}destroy(){this.observer&&(this.observer.disconnect(),this.observer=null),this.initialized=!1}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=xt(e);this.runtime.execute(t,r).catch(r=>{console.error('[HyperFixi] Error executing _="" attribute:',r),console.error("Element:",e),console.error("Code:",t)})}}function bn(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=!1,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=!0}function En(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 wn(e,t,r){return"symbol"==typeof t&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:r?"".concat(r," ",t):t})}function xn(e){const t=e.trim();return!(!t.startsWith("[@")||!t.endsWith("]"))||!!t.startsWith("@")}function kn(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 An(e,t){for(const r of e)t(r);return e}function Sn(e,t,r){for(const n of e)for(const e of t)r(n,e);return e}function Cn(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 Tn(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&&On(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&&On(e));const t=(e+"").trim(),r=t.startsWith(".")?t.substring(1):t;return r.length>0&&On(r)?[r]:[]}function Nn(e){const t=e.trim();return/^\{[^}]+\}$/.test(t)}function On(e){if(!e||0===e.trim().length)return!1;const t=e.trim();return!!Nn(t)||/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(t)}function Ln(e,t){return e.map(e=>{if(Nn(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 Rn=Symbol("command:name"),$n=Symbol("command:category"),In=Symbol("command:metadata");function jn(e){return function(t,r){const n=t;n[Rn]=e.name,n[$n]=e.category,Object.defineProperty(t.prototype,"name",{value:e.name,writable:!1,enumerable:!0})}}function Mn(e){return function(t,r){const n=t,s=n[$n];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??!1,hasBody:e.hasBody??!1,version:"1.0.0"};n[In]=i,Object.defineProperty(t,"metadata",{value:i,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(t.prototype,"metadata",{get:()=>i,enumerable:!0,configurable:!1})}}function Dn(e){return()=>new e}function Vn(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"tagName"in e&&"string"==typeof e.tagName&&"classList"in e}function Bn(e,t){if(Vn(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 _n(e)}if("string"==typeof e){const r=e.trim();if("me"===r){if(!t.me)throw Error('Context reference "me" is not available');return _n(t.me)}if("it"===r){if(!Vn(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 _n(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(!Vn(s))throw Error("Element found but is not an HTMLElement: "+r);return s}throw Error("Invalid target type: "+typeof e)}function Pn(e,t){if(Array.isArray(e))return e.filter(Vn);if(e instanceof NodeList)return Array.from(e).filter(Vn);if(Vn(e))return[e];if(!e){const e=t.me;return e&&Vn(e)?[e]:[]}if("string"==typeof e){const r=e.trim();if("me"===r)return t.me&&Vn(t.me)?[t.me]:[];if("it"===r)return Vn(t.it)?[t.it]:[];if("you"===r)return t.you&&Vn(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(Vn)}}return[]}function _n(e){if(Vn(e))return e;throw Error("Value is not an HTMLElement")}function Fn(e,t){switch(e.toLowerCase()){case"my":case"me":if(!t.me)throw Error('No "me" element in context');if(!Vn(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(!Vn(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(!Vn(t.you))throw Error("context.you is not an HTMLElement");return t.you;default:throw Error("Unknown possessive: "+e)}}const Un=["on","from","to","in","with","at"];async function qn(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||!Un.includes(t.name.toLowerCase())})),(!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(!Vn(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(Vn(s))a.push(s);else if(s instanceof NodeList){const e=Array.from(s).filter(Vn);a.push(...e)}else if(Array.isArray(s)){const e=s.filter(Vn);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(Vn);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(!Vn(r.me))throw Error(n+" command: context.me must be an HTMLElement");return[r.me]}return a}function Hn(e){return"string"==typeof e&&e.trim().startsWith("*")}function Wn(e,t,r){e.style.setProperty(t,r)}const zn=["dialog","details","summary","select"];function Jn(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 Zn(e,t,r){return function(e){if(!e||"object"!=typeof e)return!1;const t=e.type;if("selector"!==t&&"cssSelector"!==t&&"classSelector"!==t)return!1;const r=Jn(e);return"string"==typeof r&&r.startsWith(".")}(e)||function(e){if(!e||"object"!=typeof e)return!1;const t=e.type;if("selector"!==t&&"cssSelector"!==t&&"cssProperty"!==t)return!1;const r=Jn(e);return"string"==typeof r&&r.startsWith("*")}(e)?{value:Jn(e),extractedFromNode:!0}:{value:await t.evaluate(e,r),extractedFromNode:!1}}class Gn{async resolveTargets(e,t,r,n){return qn(e,t,r,this.mode,{filterPrepositions:!0,fallbackModifierKey:this.preposition},n)}async evaluateFirst(e,t,r){return Zn(e,t,r)}parseClassNames(e){return Tn(e)}isAttribute(e){return xn(e.trim())}isCSSProperty(e){return Hn(e.trim())}validateTargets(e){return Array.isArray(e)&&function(e){return Array.isArray(e)&&e.length>0&&e.every(e=>Vn(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 Yn=(()=>{let e,t,r=[Mn({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"]}),jn({name:"add",category:"dom"})],n=[],s=Gn;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=kn(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=Ln(e.classes,t);r.length>0&&Sn(e.targets,r,(e,t)=>{e.classList.contains(t)||e.classList.add(t)});break}case"attribute":r=e.name,n=e.value,An(e.targets,e=>{e.setAttribute(r,n)});break;case"styles":!function(e,t){Sn(e,Object.entries(t),(e,[t,r])=>{e.style.setProperty(t,r)})}(e.targets,e.styles)}var r,n}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!this.validateType(t.type,["classes","attribute","styles"]))return!1;if(!this.validateTargets(t.targets))return!1;if("classes"===t.type){if(!this.validateStringArray(e.classes,1))return!1}else if("attribute"===t.type){if("string"!=typeof e.name||0===e.name.length)return!1;if("string"!=typeof e.value)return!1}else if("styles"===t.type){const t=e;if("object"!=typeof t.styles||null===t.styles)return!1;if(Array.isArray(t.styles))return!1;const r=t.styles;if(0===Object.keys(r).length)return!1;if(!Object.values(r).every(e=>"string"==typeof e))return!1}return!0}},wn(t,"AddCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;bn(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),En(t,n)})(),t})();const Xn=Dn(Yn);function Kn(e){return!!e.parentNode&&(e.remove(),!0)}let Qn=(()=>{let e,t,r=[Mn({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"]}),jn({name:"remove",category:"dom"})],n=[],s=Gn;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(Vn(n))return{type:"element",targets:[n]};if(Array.isArray(n)&&n.length>0&&Vn(n[0]))return{type:"element",targets:n.filter(e=>Vn(e))};if("string"==typeof n){const s=n.trim();if(this.isAttribute(s))return{type:"attribute",name:kn(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=Ln(e.classes,t);r.length>0&&Sn(e.targets,r,(e,t)=>{e.classList.remove(t)});break}case"attribute":r=e.name,An(e.targets,e=>{e.removeAttribute(r)});break;case"styles":!function(e,t){Sn(e,t,(e,t)=>{e.style.removeProperty(t)})}(e.targets,e.properties);break;case"element":for(const t of e.targets)Kn(t)}var r}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!this.validateType(t.type,["classes","attribute","styles","element"]))return!1;if(!this.validateTargets(t.targets))return!1;if("classes"===t.type){if(!this.validateStringArray(e.classes,1))return!1}else if("attribute"===t.type){if("string"!=typeof e.name||0===e.name.length)return!1}else if("styles"===t.type&&!this.validateStringArray(e.properties,1))return!1;return!0}},wn(t,"RemoveCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;bn(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),En(t,n)})(),t})();const es=Dn(Qn);function ts(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 rs(e){if("number"==typeof e){if(0>e)throw Error("Duration must be >= 0");return Math.floor(e)}if("string"==typeof e){const t=ts(e);if(!t)throw Error(`Invalid duration format: "${e}"`);return t.milliseconds}throw Error("Invalid duration type: "+typeof e)}function ns(e){return 0===e.length?[]:"SUMMARY"===e[0].tagName?e.map(e=>e.closest("details")).filter(e=>null!==e):e}function ss(e,t,r){return()=>{"class"===t?e.classList.toggle(r):"attribute"===t&&Cn(e,r)}}function is(e,t,r,n){const s=ss(e,t,r),i=setTimeout(s,n);return()=>{clearTimeout(i)}}function os(e,t,r,n){const s=ss(e,t,r),i=()=>{s(),e.removeEventListener(n,i)};return e.addEventListener(n,i,{once:!0}),()=>{e.removeEventListener(n,i)}}function as(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 cs=/^the\s+(.+?)\s+of\s+(.+)$/i,ls=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 us(e){return"string"==typeof e&&cs.test(e)}function hs(e,t){const r=e.match(cs);if(!r)return null;try{return{element:Bn(r[2].trim(),t),property:r[1].trim()}}catch{return null}}async function fs(e,t,r){if(function(e){return!(!e||"object"!=typeof e)&&"propertyOfExpression"===e.type&&"object"==typeof e.property&&null!==e.property}(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]),Vn(s)?{element:s,property:n}:null}(e,t,r);if(function(e){return!(!e||"object"!=typeof e)&&"propertyAccess"===e.type&&"string"==typeof e.property}(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]),Vn(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]),!Vn(i))return null;const o=s?.name||s?.value;return o?{element:i,property:o}:null}return null}function ds(e,t){const{element:r,property:n}=e;n.startsWith("*")?Wn(r,n.substring(1),t+""):as(r,n,t)}async function ps(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=ts(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}}function ms(e,t){const r=t?.name,n=function(e){if(!e||"object"!=typeof e)return!1;if("identifier"!==e.type)return!1;const t=e.name;return"string"==typeof t&&function(e){if("string"!=typeof e)return!1;const t=e.toLowerCase();return zn.includes(t)}(t)}(t);if(Vn(e)||Array.isArray(e)&&e.every(e=>Vn(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!1;const t=e.toLowerCase();return zn.some(e=>t.includes(e))}(t)?{type:"element",expression:t}:{type:"class",expression:t}}return{type:"class",expression:""}}const ys=Dn((()=>{let e,t,r=[Mn({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"]}),jn({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 ps(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:!0,fallbackModifierKey:"on"},l=await qn(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 fs(n,t,r);if(i)return{type:"property",target:i};const{duration:o,untilEvent:a}=await ps(e.modifiers,t,r),{value:c}=await Zn(n,t,r);if(us(c)){const e=hs(c,r);if(e)return{type:"property",target:e}}const{type:l,expression:u}=ms(c,n),h={filterPrepositions:!0,fallbackModifierKey:"on"};switch(l){case"attribute":{const{name:n,value:s}=kn(u);return{type:"attribute",name:n,value:s,targets:await qn(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 qn(e.args.slice(1),t,r,"toggle",h,e.modifiers)}}case"element":{let s;if(Vn(c))s=[c];else if(Array.isArray(c)&&c.every(e=>Vn(e)))s=c;else if(u){const e=document.querySelectorAll(u);s=Array.from(e).filter(e=>Vn(e))}else s=await qn([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:ns(s)}:"select"===i?{type:"select",targets:s}:{type:"classes",classes:Tn(u),targets:s,duration:o,untilEvent:a}}default:{const n=Tn(u||c);if(!n.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:n,targets:await qn(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=Ln(e.classes,t);if(0===r.length)return[...e.targets];if(Sn(e.targets,r,(e,t)=>{e.classList.toggle(t)}),(e.duration||e.untilEvent)&&r.length)for(const t of e.targets)e.duration&&is(t,"class",r[0],e.duration),e.untilEvent&&os(t,"class",r[0],e.untilEvent);return[...e.targets]}case"attribute":if(r=e.name,n=e.value,An(e.targets,e=>{Cn(e,r,n)}),e.duration||e.untilEvent)for(const t of e.targets)e.duration&&is(t,"attribute",e.name,e.duration),e.untilEvent&&os(t,"attribute",e.name,e.untilEvent);return[...e.targets];case"css-property":return An(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||ls.has(r)||ls.has(r.toLowerCase())){const r=!t;return ds(e,r),r}if("number"==typeof t){const r=0===t?1:0;return ds(e,r),r}if("string"==typeof t){const n="__ht_"+r,s=e.element[n];return""===t&&void 0!==s?(ds(e,s),s):(e.element[n]=t,ds(e,""),"")}ds(e,!t)}(e.target),[e.target.element];case"dialog":return An(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 An(e.targets,e=>{var t;(t=e).open=!t.open});case"select":return An(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:!0,cancelable:!0});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&&is(t,"class",e.classA,e.duration),e.untilEvent&&os(t,"class",e.classA,e.untilEvent);return[...e.targets]}var r,n}},wn(t,"ToggleCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;bn(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),En(t,n)})(),t})());class vs{async parseInput(e,t,r){const{targets:n}=await async function(e,t,r,n){return{targets:await qn(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!1;const t=e;return!(!Array.isArray(t.targets)||!t.targets.every(e=>Vn(e))||"show"!==t.mode&&"hide"!==t.mode||"show"===t.mode&&"string"!=typeof t.defaultDisplay)}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 gs=(()=>{let e,t,r=[Mn({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"]}),jn({name:"show",category:"dom"})],n=[],s=vs;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!1;const t=e;return!!Array.isArray(t.targets)&&!!t.targets.every(e=>Vn(e))&&"string"==typeof t.defaultDisplay}},wn(t,"ShowCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;bn(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),En(t,n)})(),t})();const bs=Dn(gs);let Es=(()=>{let e,t,r=[Mn({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"]}),jn({name:"hide",category:"dom"})],n=[],s=vs;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!1;const t=e;return!!Array.isArray(t.targets)&&!!t.targets.every(e=>Vn(e))}},wn(t,"HideCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;bn(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),En(t,n)})(),t})();const ws=Dn(Es);const xs=Dn((()=>{let e,t,r=[Mn({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"]}),jn({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 fs(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&&us(e)){const t=hs(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||!Vn(t.me))throw Error("put: no target and context.me is null");return[t.me]}const r=Array.from(document.querySelectorAll(e)).filter(e=>Vn(e));if(!r.length)throw Error(`No elements: "${e}"`);return r}parseValue(e){return Vn(e)?e:null==e?"":e+""}insertContent(e,t,r){if("replace"!==r)if(Vn(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 Vn(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)||1>=e.length)||["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())))}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}},wn(t,"PutCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;bn(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),En(t,n)})(),t})());function ks(e){if(null==e)return 0;if("number"==typeof e)return isFinite(e)?e:0;if("string"==typeof e)return parseFloat(e);if("boolean"==typeof e)return e?1:0;if(Array.isArray(e))return e.length;if("object"==typeof e){if("length"in e&&"number"==typeof e.length)return e.length;if("function"==typeof e.valueOf){const t=e.valueOf();if("number"==typeof t)return t}return NaN}return 0}function As(e,t,r){return"global"===r&&t.globals&&t.globals.has(e)?t.globals.get(e):"global"!==r&&t.locals&&t.locals.has(e)?t.locals.get(e):t.globals&&t.globals.has(e)?t.globals.get(e):t.variables&&t.variables.has(e)?t.variables.get(e):"global"===r&&t.locals&&t.locals.has(e)?t.locals.get(e):"undefined"!=typeof window&&e in window?window[e]:"undefined"!=typeof globalThis&&e in globalThis?globalThis[e]:void 0}function Ss(e,t,r,n){if("global"===n)return r.globals.set(e,t),void("undefined"!=typeof window&&(window[e]=t));if(r.locals&&r.locals.has(e))r.locals.set(e,t);else{if(r.globals&&r.globals.has(e))return r.globals.set(e,t),void("undefined"!=typeof window&&e in window&&(window[e]=t));if(!r.variables||!r.variables.has(e))return"undefined"!=typeof window&&e in window?(window[e]=t,void r.globals.set(e,t)):void r.locals.set(e,t);r.variables.set(e,t)}}function Cs(e,t){return"me"===e?t.me:"it"===e?t.it:"you"===e?t.you:As(e,t)}const Ts=Dn((()=>{let e,t,r=[Mn({description:"Create DOM elements or class instances",syntax:["make a <tag#id.class1.class2/>","make a <ClassName> from <args> called <identifier>"],examples:["make an <a.navlink/> called linkElement",'make a URL from "/path/", "https://origin.example.com"'],sideEffects:["dom-creation","data-mutation"]}),jn({name:"make",category:"dom"})],n=[];return t=class{async parseInput(e,t,r){const n=e.args.length>0?await t.evaluate(e.args[0],r):void 0;if(!n)throw Error("Make command requires class name or DOM element expression");const s=void 0!==e.modifiers.an?"an":"a",i=await async function(e,t,r){if(!e)return[];if("arrayLiteral"===e.type&&Array.isArray(e.args)){const n=[];for(const s of e.args)n.push(await t.evaluate(s,r));return n}const n=await t.evaluate(e,r);return Array.isArray(n)?n:[n]}(e.modifiers.from,t,r),o=await async function(e,t,r){if(!e)return;if("symbol"===e.type&&"string"==typeof e.name)return e.name;const n=await t.evaluate(e,r);return"string"==typeof n?n:n+""}(e.modifiers.called,t,r);return{article:s,expression:n,constructorArgs:i,variableName:o}}async execute(e,t){const{expression:r,constructorArgs:n=[],variableName:s}=e,i="string"==typeof r&&r.startsWith("<")&&r.endsWith("/>")?function(e){const t=e.slice(1,-2);let r="div",n=t;const s=t.match(/^([a-zA-Z][a-zA-Z0-9]*)/);s&&(r=s[1],n=t.slice(s[0].length));const i=document.createElement(r),o=n.split(/(?=[.#])/);for(const e of o)if(e.startsWith("#")){const t=e.slice(1);t&&(i.id=t)}else if(e.startsWith(".")){const t=e.slice(1);t&&i.classList.add(t)}return i}(r):function(e,t,r){if(Vn(e))return e;const n=e+"";let s;if("undefined"!=typeof window&&(s=window[n]),s||"undefined"==typeof global||(s=global[n]),!s&&r.variables?.has(n)&&(s=r.variables.get(n)),!s||"function"!=typeof s)throw Error(`Constructor '${n}' not found or is not a function`);return 0===t.length?new s:new s(...t)}(r,n,t);return Object.assign(t,{it:i}),s&&Ss(s,i,t),i}},wn(t,"MakeCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;bn(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),En(t,n)})(),t})()),Ns=Dn((()=>{let e,t,r=[Mn({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"]}),jn({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 fs(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!1;if(Vn(e)||e instanceof Node)return!1;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(us(o)){const n=hs(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&&Hn(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&&xn(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=Fn(n[1],r),i=await this.extractValue(e,t,r);return{type:"property",element:s,property:n[2],value:i}}}if(Vn(o))return{type:"property",element:o,property:"textContent",value:await this.extractValue(e,t,r)};if(Array.isArray(o)&&o.length>0&&Vn(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 as(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"style":return Wn(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))as(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=Fn(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 Bn(e?await t.evaluate(e,r):void 0,r)}async resolveTargets(e,t,r){return Pn(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=Bn(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!1;const t=e;if(!t.type||"string"!=typeof t.type)return!1;if(!["variable","attribute","property","style","object-literal"].includes(t.type))return!1;switch(t.type){case"variable":return"string"==typeof t.name&&"value"in t;case"attribute":return"string"==typeof t.name&&Vn(t.element)&&"value"in t;case"property":return"string"==typeof t.property&&Vn(t.element)&&"value"in t;case"style":return"string"==typeof t.property&&""!==t.property&&Vn(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!1}}},wn(t,"SetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;bn(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),En(t,n)})(),t})());let Os=(()=>{let e,t,r=[Mn({description:"Modify a variable or property by a specified amount (default: 1)",syntax:["increment <target> [by <number>]","decrement <target> [by <number>]"],examples:["increment counter","increment counter by 5","decrement counter","decrement counter by 5"],sideEffects:["data-mutation","context-modification"],aliases:["decrement"]}),jn({name:"increment",category:"data"})],n=[];return t=class{async parseInput(e,t,r){const n="decrement"===e.commandName?.toLowerCase()?"decrement":"increment",s=await async function(e,t,r,n){if(!e.args||0===e.args.length)throw Error(n+" command requires a target");const s=e.args[0];let i,o;const a=(c=s)&&"object"==typeof c&&c.type||"unknown";var c;if("identifier"===a)i=s.name,s.scope&&(o=s.scope);else if("literal"===a)i=s.value;else{const e=await t.evaluate(s,r);i=Array.isArray(e)&&e.length>0?e[0]:e}let l=1,u=o;for(let n=1;e.args.length>n;n++){const s=e.args[n];if(s&&"literal"===s.type){const e=s.value;"global"===e?u="global":"number"==typeof e&&(l=e)}else if(s&&"literal"!==s.type){const e=await t.evaluate(s,r);"number"==typeof e&&(l=e)}}return{target:i,amount:l,...u&&{scope:u}}}(e,t,r,n);return{...s,operation:n}}async execute(e,t){const{target:r,property:n,scope:s,amount:i=1,operation:o="increment"}=e,a=function(e,t,r,n){if("number"==typeof e)return e;if(Vn(e)){const r=e;return t?t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)?ks(r.getAttribute(t)):ks(r[t]):ks(r.value||r.textContent)}return"string"==typeof e?"global"===r?ks(As(e,n,"global")):e.includes(".")?function(e,t){const r=e.split("."),n=r[1],s=Cs(r[0],t);return s?ks(s[n]):0}(e,n):ks("me"===e&&n.me?n.me.value||0:"it"===e?n.it||0:"you"===e&&n.you?n.you.value||0:As(e,n)):ks(e)}(r,n,s,t);let c;if(isNaN(a))c=NaN;else{const e=isFinite(i)?i:1;c="increment"===o?a+e:a-e}return function(e,t,r,n,s){if(Vn(e)){const r=e;return void(t?t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)?r.setAttribute(t,n+""):r[t]=n:"value"in r&&void 0!==r.value?r.value=n+"":r.textContent=n+"")}if("string"==typeof e){if("global"===r)return void Ss(e,n,s,"global");if(e.includes("."))return void function(e,t,r){const n=e.split("."),s=n[1],i=Cs(n[0],r);i&&(i[s]=t)}(e,n,s);if("me"===e&&s.me)return void(s.me.value=n);if("it"===e)return void Object.assign(s,{it:n});if("you"===e&&s.you)return void(s.you.value=n);Ss(e,n,s)}}(r,n,s,c,t),Object.assign(t,{it:c}),c}},wn(t,"NumericModifyCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;bn(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),En(t,n)})(),t})();const Ls=Dn(Os),Rs=Dn(Os);function $s(e){const t=e.trim();return/^\d+$/.test(t)?parseInt(t,10):/^\d*\.\d+$/.test(t)?parseFloat(t):"true"===t||"false"!==t&&("null"===t?null:"undefined"!==t?t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t:void 0)}let Is=(()=>{let e,t,r=[Mn({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"]}),jn({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!1;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,cancelable:void 0===r.cancelable||r.cancelable,composed:void 0!==r.composed&&r.composed})}(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(Vn(e))s.push(e);else if(e instanceof NodeList)s.push(...Array.from(e).filter(Vn));else if(Array.isArray(e))s.push(...e.filter(Vn));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(Vn));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()]=$s(r.trim())}}else Object.assign(n,e)}return Object.keys(n).length?n:void 0}async parseEventOptions(e,t,r){const n={bubbles:!0,cancelable:!0,composed:!1},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=!0:"nobubbles"===t?n.bubbles=!1:"cancelable"===t?n.cancelable=!0:"nocancelable"===t?n.cancelable=!1:"composed"===t&&(n.composed=!0)}}return n}},wn(t,"EventDispatchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;bn(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),En(t,n)})(),t})();const js=Dn(Is),Ms=Dn(Is);function Ds(e,t,r){return e?new Promise(r=>{const n=function(r,n){let i=!1;return r=>{i||(i=!0,e.removeEventListener(t,s),n(r))}}(0,r),s=e=>{n({event:e,timedOut:!1,cancelled:!1})};e.addEventListener(t,s)}):Promise.reject(Error("waitForEvent: no target provided"))}function Vs(e){return new Promise(t=>setTimeout(t,e))}const Bs=Dn((()=>{let e,t,r=[Mn({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"]}),jn({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 Vs(e.milliseconds),{type:"time",result:e.milliseconds,duration:Date.now()-r};if("event"===e.type){const n=e.target??t.me??document,s=(await Ds(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:rs(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:rs(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?Vs(e.milliseconds).then(()=>({result:e.milliseconds,winningCondition:e})):Ds(e.target??t.me??document,e.eventName).then(t=>({result:t.event,winningCondition:e})));return Promise.race(r)}},wn(t,"WaitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;bn(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),En(t,n)})(),t})());const Ps=Dn((()=>{let e,t,r=[Mn({description:"Make HTTP requests with lifecycle event support",syntax:["fetch <url>","fetch <url> as <type>","fetch <url> with <options>"],examples:['fetch "/api/data"','fetch "/api/users" as json','fetch "/api/save" with { method:"POST" }'],sideEffects:["network","event-dispatching"]}),jn({name:"fetch",category:"async"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("fetch requires a URL");return{url:await this.parseURL(e.args[0],t,r),responseType:this.parseResponseType(e.modifiers.as),options:await this.parseRequestOptions(e.modifiers.with,t,r)}}async execute(e,t){const r=Date.now(),{url:n,responseType:s,options:i}=e,o=new AbortController;let a;t.me&&(a=()=>o.abort(),t.me.addEventListener("fetch:abort",a,{once:!0}));const c={...i,signal:o.signal};if(t.me){const e={...c,sender:t.me,headers:c.headers||{}};this.dispatchEvent(t.me,"fetch:beforeRequest",e),c.headers=e.headers}let l;i.timeout&&(l=setTimeout(()=>o.abort(),i.timeout));try{let e=await fetch(n,c);if(t.me){const r={response:e};this.dispatchEvent(t.me,"fetch:afterResponse",r),e=r.response}const i=await this.handleResponse(e,s);t.me&&this.dispatchEvent(t.me,"fetch:afterRequest",{result:i});const o={status:e.status,statusText:e.statusText,headers:e.headers,data:i,url:e.url,duration:Date.now()-r};return Object.assign(t,{it:i}),o}catch(e){if(t.me&&this.dispatchEvent(t.me,"fetch:error",{reason:e instanceof Error?e.message:e+"",error:e}),e instanceof Error&&"AbortError"===e.name)throw Error("Fetch aborted for "+n);throw Error(`Fetch failed for ${n}: ${e instanceof Error?e.message:e+""}`)}finally{l&&clearTimeout(l),t.me&&a&&t.me.removeEventListener("fetch:abort",a)}}async parseURL(e,t,r){const n=await t.evaluate(e,r);if("string"!=typeof n||!n)throw Error("fetch: URL must be a non-empty string");return n}parseResponseType(e){if(!e)return"text";if(("identifier"===e.type||"expression"===e.type)&&e.name){const t=e.name.toLowerCase();if(["text","json","html","response","blob","arraybuffer"].includes(t))return"arraybuffer"===t?"arrayBuffer":t;throw Error(`fetch: invalid response type "${t}"`)}return"text"}async parseRequestOptions(e,t,r){if(!e)return{};const n=await t.evaluate(e,r);if("object"!=typeof n||null===n)throw Error('fetch: "with" options must be an object');const s={};return"method"in n&&(s.method=(n.method+"").toUpperCase()),"headers"in n&&(s.headers=this.parseHeaders(n.headers)),"body"in n&&(s.body=this.parseBody(n.body)),"credentials"in n&&(s.credentials=n.credentials),"mode"in n&&(s.mode=n.mode),"cache"in n&&(s.cache=n.cache),s}parseHeaders(e){if(e instanceof Headers)return e;const t=new Headers;if("object"==typeof e&&null!==e)for(const[r,n]of Object.entries(e))t.set(r,n+"");return t}parseBody(e){return null==e?null:e instanceof FormData||e instanceof Blob||e instanceof ArrayBuffer||e instanceof URLSearchParams||"string"==typeof e?e:"object"==typeof e?JSON.stringify(e):e+""}async handleResponse(e,t){switch(t){case"response":return e;case"json":return e.json();case"html":return this.parseHTML(await e.text());case"blob":return e.blob();case"arrayBuffer":return e.arrayBuffer();default:return e.text()}}parseHTML(e){const t=(new DOMParser).parseFromString(e,"text/html"),r=document.createDocumentFragment();return Array.from(t.body.childNodes).forEach(e=>r.appendChild(e.cloneNode(!0))),1===r.childNodes.length&&Vn(r.firstChild)?r.firstChild:r}dispatchEvent(e,t,r){e.dispatchEvent(new CustomEvent(t,{detail:r,bubbles:!0,cancelable:!0}))}},wn(t,"FetchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;bn(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),En(t,n)})(),t})()),_s=Dn((()=>{let e,t,r=[Mn({description:"Navigation functionality including URL navigation, element scrolling, and browser history",syntax:["go back","go to url <url> [in new window]","go to [position] [of] <element>"],examples:["go back",'go to url "https://example.com"',"go to top of #header"],sideEffects:["navigation","scrolling"]}),jn({name:"go",category:"navigation"})],n=[];return t=class{async parseInput(e,t,r){return e.args&&0!==e.args.length?{args:await Promise.all(e.args.map(e=>t.evaluate(e,r)))}:{args:[]}}async execute(e,t){const{args:r}=e;if(0===r.length)throw Error("Go command requires arguments");return"string"==typeof r[0]&&"back"===r[0].toLowerCase()?(await this.goBack(),{result:"back",type:"back"}):this.isUrlNavigation(r)?{result:await this.navigateToUrl(r,t),type:"url"}:{result:await this.scrollToElement(r,t),type:"scroll"}}isUrlNavigation(e){return-1!==e.findIndex(e=>"url"===e)}async goBack(){if("undefined"==typeof window||!window.history)throw Error("Browser history API not available");window.history.back()}async navigateToUrl(e,t){const r=e.findIndex(e=>"url"===e),n=e[r+1];if(!n)throw Error('URL is required after "url" keyword');const s="string"==typeof n?n:n+"",i=e.includes("new")&&e.includes("window");if(!this.isValidUrl(s))throw Error(`Invalid URL: "${s}"`);if(i){if("undefined"!=typeof window&&window.open){const e=window.open(s,"_blank");e?.focus&&e.focus()}}else s.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=s):"undefined"!=typeof window&&(window.location.assign?.(s)??(window.location.href=s));return s}isValidUrl(e){try{return e.startsWith("/")||e.startsWith("#")||new URL(e),!0}catch{return!1}}async scrollToElement(e,t){const r=this.parseScrollPosition(e),n=this.parseScrollTarget(e),s=this.parseScrollOffset(e),i=!e.includes("instantly"),o=this.resolveScrollTarget(n,t);if(!o)throw Error("Target element not found: "+n);if("undefined"!=typeof window){const e=i?"smooth":"instant",t=this.mapVerticalPosition(r.vertical),n=this.mapHorizontalPosition(r.horizontal);if(0!==s){o.scrollIntoView?.({behavior:e,block:t,inline:n});const{x:i,y:a}=this.calculateScrollPosition(o,r,s);window.scrollTo?.({left:i,top:a,behavior:e})}else o.scrollIntoView?.({behavior:e,block:t,inline:n})}return o}mapVerticalPosition(e){return{top:"start",middle:"center",bottom:"end",nearest:"nearest"}[e]||"start"}mapHorizontalPosition(e){return{left:"start",center:"center",right:"end",nearest:"nearest"}[e]||"nearest"}parseScrollPosition(e){const t={vertical:"top",horizontal:"nearest"},r=["top","middle","bottom"],n=["left","center","right"];let s=!1,i=!1;for(const o of e)"string"==typeof o&&(r.includes(o)?(t.vertical=o,s=!0):n.includes(o)&&(t.horizontal=o,i=!0));return i&&!s&&(t.vertical="nearest"),t}parseScrollTarget(e){const t=e.findIndex(e=>"of"===e);if(-1!==t&&e.length>t+1){let r=e[t+1];return"the"===r&&e.length>t+2&&(r=e[t+2]),r}for(const t of e)if("object"==typeof t&&t&&t.nodeType)return t;const r=["top","middle","bottom","left","center","right","of","the","to","smoothly","instantly"];for(const t of e)if("string"==typeof t&&!r.includes(t)&&(t.startsWith("#")||t.startsWith(".")||t.includes("[")||/^[a-zA-Z][a-zA-Z0-9-]*$/.test(t)))return t;return"body"}parseScrollOffset(e){for(let t=0;e.length>t;t++){const r=e[t];if("string"==typeof r){const e=r.match(/^([+-]?\d+)(px)?$/);if(e)return parseInt(e[1],10)}if(("+"===r||"-"===r)&&e.length>t+1){const n=e[t+1],s="number"==typeof n?n:parseInt((n+"").replace("px",""),10);if(!isNaN(s))return"-"===r?-s:s}}return 0}resolveScrollTarget(e,t){if("object"==typeof e&&e&&e.nodeType)return e;const r="string"==typeof e?e:e+"";if("body"===r&&"undefined"!=typeof document)return document.body;if("html"===r&&"undefined"!=typeof document)return document.documentElement;if("me"===r&&Vn(t.me))return t.me;if("it"===r&&Vn(t.it))return t.it;if("you"===r&&Vn(t.you))return t.you;const n=As(r,t);if(Vn(n))return n;if("undefined"!=typeof document)try{const e=document.querySelector(r);if(e)return e}catch{try{const e=document.getElementsByTagName(r);if(e.length>0)return e[0]}catch{}}return null}calculateScrollPosition(e,t,r){if("undefined"==typeof window||!e.getBoundingClientRect)return{x:0,y:0};const n=e.getBoundingClientRect(),s=window.pageXOffset||document.documentElement?.scrollLeft||0,i=window.pageYOffset||document.documentElement?.scrollTop||0,o=window.innerWidth||800,a=window.innerHeight||600;let c=s,l=i;switch(t.horizontal){case"left":c=n.left+s;break;case"center":c=n.left+s+n.width/2-o/2;break;case"right":c=n.right+s-o}switch(t.vertical){case"top":l=n.top+i+r;break;case"middle":l=n.top+i+n.height/2-a/2+r;break;case"bottom":l=n.bottom+i-a+r}return{x:Math.max(0,c),y:Math.max(0,l)}}},wn(t,"GoCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;bn(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),En(t,n)})(),t})()),Fs=Dn((()=>{let e,t,r=[Mn({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"]}),jn({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&&Array.isArray(e.values)}},wn(t,"LogCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;bn(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),En(t,n)})(),t})()),Us=function(e,t){const r=new dn(t.expressionEvaluator);for(const t of e)r.register(t);return new vn({registry:r,expressionEvaluator:t.expressionEvaluator,enableAsyncCommands:t.enableAsyncCommands??!0,commandTimeout:t.commandTimeout??1e4,enableErrorReporting:t.enableErrorReporting??!0,enableResultPattern:t.enableResultPattern??!0})}([Xn(),es(),ys(),bs(),ws(),xs(),Ts(),Ns(),Ls(),Rs(),Ms(),js(),Bs(),Ps(),_s(),Fs()],{expressionEvaluator:new class extends Mt{constructor(e){super();for(const t of e)this.registerCategory(t)}}([ir,Br,ln,Zr,rn])}),qs={parse:e=>mt(e),execute:async(e,t)=>{const r=function(e){if(!e)return xt();if(e.locals instanceof Map&&e.globals instanceof Map&&e.flags)return e;const t=xt(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=mt(e);if(!n.success||!n.node)throw Error(n.error?.message||"Parse failed");return await Us.execute(n.node,r)}},Hs=function(e){return new gn(e)}(qs),Ws={runtime:qs,parse:e=>qs.parse(e),execute:async(e,t)=>qs.execute(e,t),createContext:xt,attributeProcessor:Hs,version:"1.1.0-standard-v2-tree-shakeable",commands:["add","remove","toggle","show","hide","put","make","set","increment","decrement","send","trigger","wait","fetch","go","log"],eval:async(e,t)=>qs.execute(e,t),init:()=>{Hs.init()}};return"undefined"!=typeof window&&(window.hyperfixi=Ws,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{Hs.init()}):Hs.init()),Ws}();
|
|
2
|
+
//# sourceMappingURL=lokascript-browser-standard.js.map
|