@hyperfixi/core 2.6.0 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/api/hyperscript-api.d.ts +6 -0
  2. package/dist/ast-utils/index.js +8 -8
  3. package/dist/ast-utils/index.mjs +8 -8
  4. package/dist/bundle-generator/index.js +12 -4
  5. package/dist/bundle-generator/index.mjs +12 -4
  6. package/dist/chunks/{bridge-fFLEvCQs.js → bridge-lZbOVRDD.js} +2 -2
  7. package/dist/chunks/browser-modular-DegkWQ8d.js +2 -0
  8. package/dist/chunks/{index-BRgVy8nY.js → index-i_j9Z-1e.js} +2 -2
  9. package/dist/commands/data/set.d.ts +1 -0
  10. package/dist/commands/index.js +156 -47
  11. package/dist/commands/index.mjs +156 -47
  12. package/dist/core/context.d.ts +4 -0
  13. package/dist/dom/attribute-processor.d.ts +1 -0
  14. package/dist/hyperfixi-browser-classic-i18n.js +1 -1
  15. package/dist/hyperfixi-browser-minimal.js +1 -1
  16. package/dist/hyperfixi-browser-standard.js +1 -1
  17. package/dist/hyperfixi-browser.js +1 -1
  18. package/dist/hyperfixi-classic-i18n.js +1 -1
  19. package/dist/hyperfixi-hx-v4.js +1 -1
  20. package/dist/hyperfixi-hx.js +1 -1
  21. package/dist/hyperfixi-hybrid-complete.js +1 -1
  22. package/dist/hyperfixi-hybrid-hx.js +1 -1
  23. package/dist/hyperfixi-lite-plus.js +1 -1
  24. package/dist/hyperfixi-lite.js +1 -1
  25. package/dist/hyperfixi-minimal.js +1 -1
  26. package/dist/hyperfixi-multilingual.js +1 -1
  27. package/dist/hyperfixi-standard.js +1 -1
  28. package/dist/hyperfixi.js +1 -1
  29. package/dist/hyperfixi.mjs +1 -1
  30. package/dist/index.d.ts +1 -1
  31. package/dist/index.js +694 -459
  32. package/dist/index.min.js +1 -1
  33. package/dist/index.mjs +691 -460
  34. package/dist/lokascript-browser-classic-i18n.js +1 -1
  35. package/dist/lokascript-browser-minimal.js +1 -1
  36. package/dist/lokascript-browser-standard.js +1 -1
  37. package/dist/lokascript-browser.js +1 -1
  38. package/dist/lokascript-hybrid-complete.js +1 -1
  39. package/dist/lokascript-hybrid-hx.js +1 -1
  40. package/dist/lokascript-lite-plus.js +1 -1
  41. package/dist/lokascript-lite.js +1 -1
  42. package/dist/lokascript-multilingual.js +1 -1
  43. package/dist/parser/full-parser.js +70 -35
  44. package/dist/parser/full-parser.mjs +70 -35
  45. package/dist/parser/parser-types.d.ts +1 -1
  46. package/dist/parser/parser.d.ts +2 -0
  47. package/dist/parser/regex-parser.js +23 -14
  48. package/dist/parser/regex-parser.mjs +23 -14
  49. package/dist/registry/index.js +178 -45
  50. package/dist/registry/index.mjs +178 -45
  51. package/dist/types/core-context.d.ts +1 -0
  52. package/package.json +6 -6
  53. package/dist/chunks/browser-modular-BK3IOo93.js +0 -2
  54. package/dist/compatibility/browser-bundle.d.ts +0 -164
@@ -1,2 +1,2 @@
1
- var hyperfixi=function(){"use strict";const e="then",t="else",n="end",r="and",s="for",i="while",o="until",a="forever",c="times",l="index",u="in",f="to",h="from",d="with",p="of",m="on",y="event",g="behavior",v="global",b="the",w="start",E=new Set(["add","append","async","beep","blur","break","breakpoint","call","clear","close","continue","copy","decrement","default","empty","exit","fetch","focus","for","get","go","halt","hide","open","if","increment","install","js","log","make","measure","morph","pick","process","push","put","remove","render","repeat","replace","reset","return","scroll","select","send","set","settle","show","start","swap","take","tell","throw","toggle","transition","trigger","unless","wait"]),x=new Set(["put","trigger","send","remove","take","toggle","set","show","hide","add","halt","measure","js","tell","pick","start","swap","morph","push","replace","process"]),k=(new Set(["if","unless","repeat","wait","for","while"]),"at start of"),S="at end of",A=["into","before","after","at",k,S,"at the start of","at the end of"],N=new Set(["if","else","unless","for","while","until","end","and","or","not","in","to","from","into","with","without","as","matches","contains","then","on","when","every","init","def","behavior","the","of","first","last"]),T=e=>E.has(e.toLowerCase()),C=e=>x.has(e.toLowerCase()),O=e=>N.has(e.toLowerCase()),R=e=>$.has(e.toLowerCase()),$=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"]),L=new Set(["me","it","you","result","my","its","your"]),j=new Set(["and","or","not","no"]),I=new Set(["==","!=","===","!==","<",">","<=",">=","is","is not","am","is a","is an","is not a","is not an","precedes","does not precede","follows","does not follow","contains","starts with","ends with","does not start with","does not end with","has","have","does not contain","include","includes","does not include","match","matches","exists","does not exist","is empty","is not empty","is in","is not in","is between","is not between","equals","in","is equal to","is really equal to","is not equal to","is not really equal to","is greater than","is less than","is greater than or equal to","is less than or equal to","really equals","am in","am not in","am between","am not between","is really","is not really","is equal","is not equal","contain","do not contain","does not contains","do not match","does not match","ignoring case","sorted by","mapped to","split by","joined by"]),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","toggle"]),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 P;!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"}(P||(P={}));const F=new Set(["+","-","*","/","mod"]),B=new Set(["ms","s","seconds","minutes","hours","days"]);function q(e,t=1){const n=e.position+t;return e.input.length>n?e.input[n]:""}function V(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 _(e){const t=e.input,n=t.length;for(;n>e.position;){const n=t[e.position];if(" "!==n&&"\t"!==n&&"\r"!==n&&"\n"!==n)break;V(e)}}function H(e,t,n,r,s){const i=r??e.position-n.length,o=e.position;let a=e.column-n.length;if(void 0!==r){a=1;let t=-1;for(let n=0;r>n;n++)"\n"!==e.input[n]&&"\r"!==e.input[n]||(t=n);a=r-t}const c={kind:t,value:n,start:i,end:o,line:U(e,i),column:a};e.tokens.push(c)}function U(e,t){let n=1;for(let r=0;t>r&&e.input.length>r;r++){const t=e.input[r];"\n"===t?n++:"\r"===t&&(n++,e.input.length>r+1&&"\n"===e.input[r+1]&&r++)}return n}function z(e){const t=e.position;let n="";for(V(e),V(e);e.input.length>e.position&&"\n"!==e.input[e.position];)n+=V(e);H(e,P.COMMENT,"--"+n,t)}function W(e){const t=e.position,n=V(e);let r=n;for(;e.input.length>e.position;){const t=V(e);if(r+=t,t===n)break;"\\"===t&&e.input.length>e.position&&(r+=V(e))}H(e,P.STRING,r,t)}function J(e){const t=e.position;V(e);let n="";for(;e.input.length>e.position;){const t=e.input[e.position];if("`"===t){V(e);break}if("\\"===t){if(V(e),e.input.length>e.position){const t=V(e);switch(t){case"n":n+="\n";break;case"t":n+="\t";break;case"r":n+="\r";break;case"\\":n+="\\";break;case"`":n+="`";break;default:n+=t}}}else n+=V(e)}if(e.position>=e.input.length&&!e.input.endsWith("`"))throw Error(`Unterminated template literal at line ${e.line}, column ${e.column-n.length}`);H(e,P.TEMPLATE,n,t)}function Z(e){const t=e.position;let n=V(e);if(e.input.length>e.position&&"{"===e.input[e.position]){for(n+=V(e);e.input.length>e.position;){const t=e.input[e.position];if(n+=V(e),"}"===t)break}H(e,P.SELECTOR,n,t)}else{for(;e.input.length>e.position;){const t=e.input[e.position];if("\\"===t)V(e),e.input.length>e.position&&(n+=V(e));else{if(!ne(t)&&"-"!==t&&"_"!==t&&":"!==t)break;n+=V(e)}}H(e,P.SELECTOR,n,t)}}function K(e){const t=e.position;if(re(e))return void function(e,t){const n=e.input;let r="",s=0,i="";for(;n.length>e.position;){const t=n[e.position];if(i)r+=V(e),t===i&&(i="");else if('"'!==t&&"'"!==t){if("<"===t){if("/"===n[e.position+1]){for(;n.length>e.position&&">"!==n[e.position];)r+=V(e);if(n.length>e.position&&(r+=V(e)),s--,0>=s)break;continue}let t=!1,i="";for(;n.length>e.position;){const s=n[e.position];if(i)r+=V(e),s===i&&(i="");else if('"'!==s&&"'"!==s){if(">"===s){t="/"===n[e.position-1],r+=V(e);break}r+=V(e)}else i=s,r+=V(e)}if(t||s++,0>=s)break;continue}r+=V(e)}else i=t,r+=V(e)}H(e,P.SELECTOR,r,t)}(e,t);let n="";for(n+=V(e);e.input.length-1>e.position;){const t=e.input[e.position],r=e.input[e.position+1];if(n+=V(e),"/"===t&&">"===r){n+=V(e);break}}H(e,P.SELECTOR,n,t)}function G(e){const t=e.position;let n=V(e);for(;e.input.length>e.position;){const t=e.input[e.position];if(!ne(t)&&"_"!==t&&"-"!==t)break;n+=V(e)}H(e,P.SYMBOL,n,t)}function X(e){const t=e.position;let n="";const r=e.input[e.position];if(("'"===r||"'"===r)&&"s"===q(e,1))return n="'s",V(e),V(e),void H(e,P.OPERATOR,n,t);const s=e.input.substring(e.position,e.position+2),i=e.input.substring(e.position,e.position+3);["===","!=="].includes(i)?(n=i,V(e),V(e),V(e)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(s)?(n=s,V(e),V(e)):n=V(e),H(e,P.OPERATOR,n,t)}function Y(e){const t=e.position,n=e.input,r=n.length;let s="";for(;r>e.position;){const t=n[e.position];if("0">t||t>"9")break;s+=V(e)}if(r>e.position&&"."===n[e.position]&&(e.position+1>=r||"."!==n[e.position+1]))for(s+=V(e);r>e.position;){const t=n[e.position];if("0">t||t>"9")break;s+=V(e)}if(r>e.position){const t=n[e.position];if("e"===t||"E"===t){const t=r>e.position+1?n[e.position+1]:"",i=r>e.position+2?n[e.position+2]:"";if(t>="0"&&"9">=t||!("+"!==t&&"-"!==t||"0">i||i>"9"))for(s+=V(e),"+"!==n[e.position]&&"-"!==n[e.position]||(s+=V(e));r>e.position;){const t=n[e.position];if("0">t||t>"9")break;s+=V(e)}}}const i=e.position;let o="";for(;r>e.position;){const t=n[e.position];if(("a">t||t>"z")&&("A">t||t>"Z"))break;o+=V(e)}B.has(o)?H(e,P.TIME,s+o,t):(e.position=i,H(e,P.NUMBER,s,t))}function Q(e){const t=e.position,n=e.input,r=n.length;let s="";for(;r>e.position;){const t=n[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;s+=V(e)}const i=function(e,t,n){const r=t.toLowerCase(),s=e.position;if("'s"===t||"'s"===t)return!1;const i=e.tokens[e.tokens.length-1];if(i&&(i.kind===P.IDENTIFIER||i.kind===P.SELECTOR)){const t=e.input.length>e.position?e.input[e.position]:"";if("'"===t||"'"===t)return!1}_(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+=V(e)}if(o){const t=o.toLowerCase(),s=`${r} ${t}`,i=function(e,t,n,r){const s=t.toLowerCase(),i=n.toLowerCase();if("at"===s){const t=e.position;if("the"===i){_(e);let n="";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;n+=V(e)}const s=n.toLowerCase();if("start"===s||"end"===s){_(e);let t="";for(;e.input.length>e.position;){const n=e.input[e.position];if(("a">n||n>"z")&&("A">n||n>"Z")&&("0">n||n>"9")&&"_"!==n&&"-"!==n)break;t+=V(e)}if("of"===t.toLowerCase())return H(e,P.IDENTIFIER,`at the ${s} of`,r),!0}return e.position=t,!1}if("start"===i||"end"===i){_(e);let n="";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;n+=V(e)}return"of"===n.toLowerCase()?(H(e,P.IDENTIFIER,`at ${i} of`,r),!0):(e.position=t,!1)}}return!1}(e,r,t,n);if(i)return!0;const a=function(e,t,n){const r=e.position;let s=`${t} ${n}`,i=e.position;const o=[t,n];for(;8>o.length&&(_(e),e.input.length>e.position);){let t="";for(;e.input.length>e.position;){const n=e.input[e.position];if(("a">n||n>"z")&&("A">n||n>"Z"))break;t+=V(e)}if(!t)break;o.push(t.toLowerCase());const n=o.join(" ");I.has(n)&&(s=n,i=e.position)}return I.has(s)&&s!==`${t} ${n}`?(e.position=i,s):(e.position=r,null)}(e,r,t);if(a)return H(e,P.OPERATOR,a,n),!0;if(I.has(s))return H(e,P.OPERATOR,s,n),!0}return I.has(r)?(e.position=s,H(e,P.OPERATOR,t,n),!0):(e.position=s,!1)}(e,s,t);if(i)return;const o=function(e){const t=e.toLowerCase();return"include"===t||"includes"===t||j.has(t)||F.has(e)||F.has(t)||I.has(t)?P.OPERATOR:P.IDENTIFIER}(s);H(e,o,s,t)}function ee(e){const t=e.position,n=e.input,r=n.length;V(e);let s="$";for(;r>e.position;){const t=n[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t)break;s+=V(e)}H(e,P.IDENTIFIER,s,t)}function te(e){return/[a-zA-Z]/.test(e)}function ne(e){return/[a-zA-Z0-9]/.test(e)}function re(e){const t=e.input,n=t[e.position+1];if(!n||!/[a-zA-Z]/.test(n))return!1;let r=e.position+1,s="";for(;t.length>r&&/[a-zA-Z0-9-]/.test(t[r]);)s+=t[r],r++;return s.length>0&&-1!==t.indexOf("</"+s+">",r)}function se(e){if(re(e))return!0;let t=e.position+1,n=!1;for(;e.input.length>t;){const r=e.input[t];if("/"===r&&e.input.length>t+1&&">"===e.input[t+1])return n;if(ne(r)||"."===r||"#"===r||"["===r||"]"===r||":"===r||"-"===r||"_"===r||" "===r||"="===r||'"'===r||"'"===r||"("===r||")"===r||"*"===r||"^"===r||"$"===r||"~"===r||"|"===r||">"===r||"+"===r||","===r||"{"===r||"}"===r)n=!0,t++;else{if(" "!==r&&"\t"!==r)return!1;t++}if(t-e.position>50)return!1}return!1}function ie(e){return"+-*/^%=!<>&|(){}[],.;:?''~$".includes(e)}const oe=function(){if("undefined"!=typeof localStorage)try{const e=localStorage,t=e.getItem("hyperfixi:debug")||e.getItem("lokascript:debug");if("*"===t||"true"===t)return!0}catch{}return!("undefined"==typeof window||!window.__HYPERFIXI_DEBUG__)||"undefined"!=typeof process&&"true"===process.env?.HYPERFIXI_DEBUG}(),ae=oe,ce=oe,le=oe,ue=oe,fe=(...e)=>{ae&&console.log("🔧",...e)},he=(...e)=>{ce&&console.log("🎯",...e)},de=(...e)=>{le&&console.log("📝",...e)},pe=(...e)=>{ue&&console.log("🚀",...e)};let me=!1,ye=null;if("undefined"!=typeof window&&"undefined"!=typeof URLSearchParams)try{"semantic"===new URLSearchParams(window.location.search).get("debug")&&(me=!0,ye=window,console.log("%c[HyperFixi] Semantic debug auto-enabled via URL param","color: #667eea; font-weight: bold"))}catch{}let ge={totalParses:0,semanticSuccesses:0,semanticFallbacks:0,traditionalParses:0,averageConfidence:0,confidenceHistory:[]};class ve{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(ve.SKIP_SEMANTIC_COMMANDS.has(t))return!0;const n=e.toLowerCase();return!!/\bjs\b/.test(n)||!!/\btell\b/.test(n)||!!/\*[a-zA-Z]/.test(e)}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 r=this.analyzer.analyze(e,this.language),s=performance.now()-t;this.debugEnabled&&console.log("[SemanticIntegration] Analysis result:",{input:e,language:this.language,confidence:r.confidence,command:r.command?.name,threshold:this.confidenceThreshold});const i=r.confidence>=this.confidenceThreshold&&!!r.command,o=!i&&r.confidence>0;if(me){const t={};if(r.command?.roles)for(const[e,n]of r.command.roles)t[e]=n.value;const a={input:e.substring(0,100),language:this.language,confidence:r.confidence,threshold:this.confidenceThreshold,semanticSuccess:i,fallbackTriggered:o,command:r.command?.name,roles:Object.keys(t).length>0?t:void 0,errors:r.errors,timestamp:Date.now(),duration:s};!function(e){if(!me)return;const t=e.semanticSuccess?"semantic":e.fallbackTriggered?"fallback":"traditional",n=Math.round(100*e.confidence),r=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: ${n}% (threshold: ${r}%)`),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(),ye){const t=new CustomEvent("lokascript:semantic:parse",{detail:e,bubbles:!0});ye.dispatchEvent(t)}}(a),n=a,ge.totalParses++,n.semanticSuccess?ge.semanticSuccesses++:n.fallbackTriggered?ge.semanticFallbacks++:ge.traditionalParses++,ge.confidenceHistory.push(n.confidence),ge.confidenceHistory.length>100&&ge.confidenceHistory.shift(),ge.averageConfidence=ge.confidenceHistory.reduce((e,t)=>e+t,0)/ge.confidenceHistory.length}return i?{success:!0,node:this.buildCommandNode(r),confidence:r.confidence,tokensConsumed:r.tokensConsumed}:{success:!1,confidence:r.confidence,tokensConsumed:r.tokensConsumed,errors:r.errors}}catch(e){return{success:!1,confidence:0,errors:[e instanceof Error?e.message:e+""]}}var n}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 n=[],r={};for(const[e,s]of t.roles){const i=this.semanticValueToExpression(s);switch(e){case"patient":case"event":n.push(i);break;case"destination":"put"===t.name?r.into=i:"add"===t.name||"append"===t.name||"prepend"===t.name?r.to=i:r.on=i;break;case"source":"fetch"===t.name?n.push(i):r.from=i;break;case"quantity":r.by=i;break;case"duration":r.over=i;break;case"responseType":r.as=i;break;case"method":r.method=i;break;case"style":r.with=i;break;case"condition":r.when=i;break;default:r[e]=i}}return{type:"command",name:t.name,args:n,modifiers:Object.keys(r).length>0?r:void 0,isBlocking:!1,start:0,end:0,line:1,column:0}}buildRepeatCommandNode(e){const t=[],n={},r=e.roles.get("loopType");r&&t.push({type:"identifier",name:r.value+"",start:0,end:0,line:1,column:0});const s=e.roles.get("patient");"for"==(r?r.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&&(n.condition=this.semanticValueToExpression(c)),{type:"command",name:"repeat",args:t,modifiers:Object.keys(n).length>0?n:void 0,isBlocking:!1,start:0,end:0,line:1,column:0}}buildSetCommandNode(e){const t=[],n=e.roles.get("destination");if(n)if("property-path"===n.type){const e=n;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(n));t.push({type:"identifier",name:"to",start:0,end:0,line:1,column:0});const r=e.roles.get("patient");return r&&t.push(this.semanticValueToExpression(r)),{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=[],n=e.roles.get("condition");return n&&t.push(this.semanticValueToExpression(n)),{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 n=()=>{for(;e.length>t&&/\s/.test(e[t]);)t++},r=()=>{n();const r=t;for(;e.length>t&&/[a-zA-Z0-9_$]/.test(e[t]);)t++;return e.slice(r,t)},s=()=>{const r=[];if(t++,n(),")"!==e[t])for(r.push(i()),n();","===e[t];)t++,n(),r.push(i()),n();return")"===e[t]&&t++,r},i=()=>{n();const i=r();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;){n();const i=e[t];if("."===i){t++;const e=r();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}}ve.SKIP_SEMANTIC_COMMANDS=new Set(["swap","morph","js","tell"]);const be=new Set(["then","end","to","into","on","with","from","in","by","for","while","until","unless","else","catch","finally"]),we=new Set([")","]","}",","]);function Ee(e,t){return{infix:{bp:[e,e+1],handler:t??((t,n,r)=>{const s=r.parseExpr(e+1);return{type:"binaryExpression",operator:n.value,left:t,right:s,start:t.start,end:s.end??n.end,line:t.line??n.line,column:t.column??n.column}})}}}function xe(e,t){return{infix:{bp:[e+1,e],handler:(t,n,r)=>{const s=r.parseExpr(e);return{type:"binaryExpression",operator:n.value,left:t,right:s,start:t.start,end:s.end??n.end,line:t.line??n.line,column:t.column??n.column}}}}}function ke(e,t){return{prefix:{bp:e,handler:t??((t,n)=>{const r=n.parseExpr(e);return{type:"unaryExpression",operator:t.value,operand:r,argument:r,prefix:!0,start:t.start,end:r.end??t.end,line:t.line,column:t.column}})}}}function Se(e){return(t,n,r)=>{const s=r.advance();if(!s||!s.value)throw Error(`Type check requires a type name after 'is ${e?"not ":""}a/an', got: <end>`);let i=!0;const o=r.peek();return o&&"!"===o.value&&(r.advance(),i=!1),{type:"typeCheckExpression",value:t,typeName:s.value,nullOk:i,negated:e,start:t.start,end:s.end}}}const Ae=function(...e){const t=new Map;for(const n of e)for(const[e,r]of n){const n=t.get(e);t.set(e,n?{prefix:r.prefix??n.prefix,infix:r.infix??n.infix}:{...r})}return t}(new Map([["or",Ee(10)],["||",Ee(10)],["and",Ee(20)],["&&",Ee(20)],["==",Ee(30)],["!=",Ee(30)],["<",Ee(30)],[">",Ee(30)],["<=",Ee(30)],[">=",Ee(30)],["is",Ee(30)],["matches",Ee(30)],["contains",Ee(30)],["starts with",Ee(30)],["ends with",Ee(30)],["does not start with",Ee(30)],["does not end with",Ee(30)],["is between",Ee(30,(e,t,n)=>{const r=n.parseExpr(31),s=n.peek();if(!s||"and"!==s.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(s?.value??"<end>"));n.advance();const i=n.parseExpr(31);return{type:"betweenExpression",value:e,min:r,max:i,negated:!1,start:e.start,end:i.end}})],["is not between",Ee(30,(e,t,n)=>{const r=n.parseExpr(31),s=n.peek();if(!s||"and"!==s.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(s?.value??"<end>"));n.advance();const i=n.parseExpr(31);return{type:"betweenExpression",value:e,min:r,max:i,negated:!0,start:e.start,end:i.end}})],["am between",Ee(30,(e,t,n)=>{const r=n.parseExpr(31),s=n.peek();if(!s||"and"!==s.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(s?.value??"<end>"));n.advance();const i=n.parseExpr(31);return{type:"betweenExpression",value:e,min:r,max:i,negated:!1,start:e.start,end:i.end}})],["am not between",Ee(30,(e,t,n)=>{const r=n.parseExpr(31),s=n.peek();if(!s||"and"!==s.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(s?.value??"<end>"));n.advance();const i=n.parseExpr(31);return{type:"betweenExpression",value:e,min:r,max:i,negated:!0,start:e.start,end:i.end}})],["ignoring case",{infix:{bp:[25,26],handler:(e,t,n)=>(e.ignoringCase=!0,e)}}],["where",Ee(28,(e,t,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"where",collection:e,right:r,start:e.start,end:r.end}})],["sorted by",Ee(28,(e,t,n)=>{const r=n.parseExpr(29);let s="asc";const i=n.peek();if(i&&"string"==typeof i.value){const e=i.value.toLowerCase();"asc"===e||"ascending"===e?(n.advance(),s="asc"):"desc"!==e&&"descending"!==e||(n.advance(),s="desc")}return{type:"collectionExpression",operator:"sorted by",collection:e,right:r,order:s,start:e.start,end:r.end}})],["mapped to",Ee(28,(e,t,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"mapped to",collection:e,right:r,start:e.start,end:r.end}})],["split by",Ee(28,(e,t,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"split by",collection:e,right:r,start:e.start,end:r.end}})],["joined by",Ee(28,(e,t,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"joined by",collection:e,right:r,start:e.start,end:r.end}})],["+",{...Ee(40),...ke(80)}],["-",{...Ee(40),...ke(80)}],["*",Ee(50)],["/",Ee(50)],["%",Ee(50)],["mod",Ee(50)],["^",xe(60)],["**",xe(60)],["as",Ee(70,(e,t,n)=>{const r=()=>{const e=n.peek();!e||"a"!==e.value&&"an"!==e.value||n.advance();const t=n.parseExpr(71),r=n.peek();if(r&&":"===r.value&&t&&"identifier"===t.type){n.advance();const e=n.advance();e&&void 0!==e.value&&(t.name=`${t.name}:${e.value}`,t.end=e.end)}return t};let s=r(),i={type:"asExpression",expression:e,targetType:s,start:e.start,end:s.end??t.end,line:e.line??t.line,column:e.column??t.column};for(;n.peek()&&"|"===n.peek().value;){n.advance();const e=r();i={type:"asExpression",expression:i,targetType:e,start:i.start,end:e.end??i.end,line:i.line,column:i.column}}return i})],["not",ke(80)],["!",ke(80)],["no",ke(27)]]),new Map([["===",Ee(30)],["!==",Ee(30)],["is not",Ee(30)],["am",Ee(30)],["is in",Ee(30)],["is not in",Ee(30)],["precedes",Ee(30)],["does not precede",Ee(30)],["follows",Ee(30)],["does not follow",Ee(30)],["is a",Ee(30,Se(!1))],["is an",Ee(30,Se(!1))],["is not a",Ee(30,Se(!0))],["is not an",Ee(30,Se(!0))],["has",Ee(30)],["have",Ee(30)],["match",Ee(30)],["include",Ee(30)],["includes",Ee(30)],["equals",Ee(30)],["does not contain",Ee(30)],["does not include",Ee(30)],["am in",Ee(30)],["am not in",Ee(30)],["is really",Ee(30)],["is not really",Ee(30)],["is equal",Ee(30)],["is not equal",Ee(30)],["contain",Ee(30)],["do not contain",Ee(30)],["does not contains",Ee(30)],["do not match",Ee(30)],["does not match",Ee(30)],["is equal to",Ee(30)],["is not equal to",Ee(30)],["is really equal to",Ee(30)],["is not really equal to",Ee(30)],["really equals",Ee(30)],["is greater than",Ee(30)],["is less than",Ee(30)],["is greater than or equal to",Ee(30)],["is less than or equal to",Ee(30)],["in",Ee(30)],["of",xe(30)],["really",Ee(30)],["exists",{prefix:{bp:80,handler:(e,t)=>({type:"unaryExpression",operator:e.value,operand:t.parseExpr(80),start:e.start})},infix:{bp:[30,31],handler:(e,t)=>({type:"unaryExpression",operator:t.value,operand:e,prefix:!1,start:e.start})}}],["does not exist",{infix:{bp:[30,31],handler:(e,t)=>({type:"unaryExpression",operator:t.value,operand:e,prefix:!1,start:e.start})}}],["is empty",{infix:{bp:[30,31],handler:(e,t)=>({type:"unaryExpression",operator:t.value,operand:e,prefix:!1,start:e.start})}}],["is not empty",{infix:{bp:[30,31],handler:(e,t)=>({type:"unaryExpression",operator:t.value,operand:e,prefix:!1,start:e.start})}}],["some",ke(80)]]),new Map([["=",xe(5)]])),Ne=new Map,Te=new Map,Ce=new Map,Oe=new Set,Re=new Set,$e=new Set,Le=new Set;function je(e){return Ne.get(e.toLowerCase())}function Ie(e){return Ce.get(e)}function Me(e,t){if(0!==Re.size)for(const n of Re)try{n(e,t)}catch(e){void 0!==console&&console.error("[hyperfixi] globalReadHook threw:",e)}}function De(e,t,n){if(0!==$e.size)for(const r of $e)try{r(e,t,n)}catch(e){void 0!==console&&console.error("[hyperfixi] localWriteHook threw:",e)}}function Pe(e,t){if(0!==Le.size)for(const n of Le)try{n(e,t)}catch(e){void 0!==console&&console.error("[hyperfixi] localReadHook threw:",e)}}function Fe(e,t,n){if(e.globals.set(t,n),0!==Oe.size)for(const r of Oe)try{r(t,n,e)}catch(e){void 0!==console&&console.error("[hyperfixi] globalWriteHook threw:",e)}}function Be(e){return e.kind===P.IDENTIFIER&&E.has(e.value.toLowerCase())}function qe(e){return e.kind===P.IDENTIFIER&&D.has(e.value.toLowerCase())}function Ve(e){return e.kind===P.IDENTIFIER&&M.has(e.value.toLowerCase())}function _e(e){return e.kind===P.IDENTIFIER&&L.has(e.value.toLowerCase())}function He(e){return I.has(e.value.toLowerCase())}function Ue(e){return e.kind===P.IDENTIFIER}function ze(e){return e.kind===P.SELECTOR}function We(e){return e.kind===P.SELECTOR&&!e.value.startsWith("<")}function Je(e){return e.kind===P.STRING||e.kind===P.NUMBER||e.kind===P.TEMPLATE}function Ze(e){return e.kind===P.IDENTIFIER}function Ke(e){return e.kind===P.TIME}function Ge(e){return e.kind===P.SYMBOL}function Xe(e){return e.kind===P.COMMENT}function Ye(e){if(e.kind!==P.IDENTIFIER)return!1;const t=e.value.toLowerCase();return!(E.has(t)||D.has(t)||M.has(t)||L.has(t))}function Qe(e){return e.kind===P.STRING}function et(e){return e.kind===P.NUMBER}function tt(e){if(e.kind===P.IDENTIFIER){const t=e.value;return"true"===t||"false"===t||"null"===t||"undefined"===t}return!1}function nt(e){return e.kind===P.TEMPLATE}function rt(e){return e.kind===P.SELECTOR&&e.value.startsWith("<")}function st(e){return e.kind===P.SELECTOR&&e.value.startsWith("#")}function it(e){return e.kind===P.SELECTOR&&e.value.startsWith(".")}function ot(e){return e.kind===P.SELECTOR&&!e.value.startsWith("#")&&!e.value.startsWith(".")}function at(e){if(e.kind!==P.OPERATOR)return!1;const t=e.value.toLowerCase();return!j.has(t)&&!I.has(t)}function ct(e){const t=e.value.toLowerCase();return"then"===t||"and"===t||"else"===t||"end"===t||"on"===t}function lt(e,t,n){return{type:"literal",value:e,raw:t,start:n.start,end:n.end,line:n.line,column:n.column}}function ut(e,t){return{type:"identifier",name:e,start:t.start,end:t.end,line:t.line,column:t.column}}function ft(e,t,n,r){return{type:"binaryExpression",operator:e,left:t,right:n,start:r.start,end:r.end,line:r.line,column:r.column}}function ht(e,t){return{type:"block",commands:e,start:t.start,end:t.end,line:t.line,column:t.column}}function dt(e,t){return{type:"string",value:e,start:t.start,end:t.end,line:t.line,column:t.column}}function pt(e,t){return{type:"objectLiteral",properties:e,start:t.start,end:t.end,line:t.line,column:t.column}}function mt(e,t){return{type:"arrayLiteral",elements:e,start:t.start,end:t.end,line:t.line,column:t.column}}function yt(e,t,n){return{type:"propertyOfExpression",property:e,target:t,start:n.start,end:n.end,line:n.line,column:n.column}}function gt(e,t,n){return{type:"command",name:"__ERROR__",args:[],diagnostics:[{message:t,severity:"error",code:"parse-error",line:e.line,column:e.column,...n&&{source:n}}],start:e.start,end:e.end,line:e.line,column:e.column}}const vt=[{command:"append",keywords:["to"],syntax:"append <value> [to <target>]"},{command:"make",keywords:["a","an","from","called"],syntax:"make (a|an) <type> [from <args>] [called <name>]"},{command:"send",keywords:["to"],syntax:"send <event> to <target>"},{command:"throw",keywords:[],syntax:"throw <error>"}];function bt(e,t){return!!e&&t.some(t=>e.value===t||e.value.toLowerCase()===t)}const wt=[e,r,t,n];function Et(e,t=[]){if(e.isAtEnd())return!0;for(const t of wt)if(e.check(t))return!0;for(const n of t)if(e.check(n))return!0;return!!e.checkIsCommand()}function xt(e,t=[]){if(!Et(e,t))return e.parseExpression()}function kt(e,t,n){return!!e.check(t)&&(e.advance(),n.push(e.createIdentifier(t)),!0)}function St(e,t,n){for(const r of t)if(e.check(r))return e.advance(),n.push(e.createIdentifier(r)),r;return null}function At(e,t){return!!e.check(t)&&(e.advance(),!0)}function Nt(e){const t=e.savePosition();let n;if(e.checkIdentifierLike()){const r=e.peek().value;e.advance(),e.check(":")?(e.advance(),n=r):e.restorePosition(t)}const r=e.parseExpression();return void 0!==n?{name:n,value:r}:{value:r}}class Tt{constructor(e){this.args=[],this.isBlocking=!1,this.name=e}static from(e){const t=new Tt(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 Tt(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 Tt(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}withName(e){return this.name=e,this}withOriginalCommand(e){return this.originalCmd=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),this.originalCmd&&(e.originalCommand=this.originalCmd),e}clone(){const e=new Tt(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.originalCmd=this.originalCmd,e.startPos=this.startPos?{...this.startPos}:void 0,e.endPos=this.endPos?{...this.endPos}:void 0,e}}function Ct(e,t){const n=[];let r="";const s=e.peek().start||0,i=e.peek().line||1,o=e.peek().column||1;if(e.checkIdentifierLike()){for(r=e.advance().value;e.check(":")&&!e.isAtEnd();)e.advance(),r+=":",e.checkIdentifierLike()&&(r+=e.advance().value);if(e.check("(")){e.advance();const t=[];for(;!e.isAtEnd()&&!e.check(")");){const{name:n,value:r}=Nt(e);if(t.push(void 0!==n?{type:"objectLiteral",properties:[{key:{type:"identifier",name:n},value:r}],start:r.start,end:r.end,line:r.line,column:r.column}:r),e.check(","))e.advance();else if(!e.check(")"))break}e.check(")")&&e.advance(),n.push({type:"functionCall",name:r,args:t,start:s,end:e.getPosition().end,line:i,column:o})}else n.push({type:"string",value:r,start:s,end:e.getPosition().end,line:i,column:o})}const a=[...n];for(;!Et(e);){if(e.check("on")||e.check("to")){const t=e.advance().value;a.push(e.createIdentifier(t));continue}a.push(e.parsePrimary())}return Tt.fromIdentifier(t).withArgs(...a).endingAt(e.getPosition()).build()}function Ot(e,t){const n=[];if(e.check(b)){const t=e.advance();if(n.push({type:"identifier",name:b,start:t.start,end:t.end,line:t.line,column:t.column}),e.check(y)){const t=e.advance();n.push({type:"identifier",name:y,start:t.start,end:t.end,line:t.line,column:t.column})}}return Tt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}function Rt(r,s){const i=[];let o=!1;const a=r.savePosition();for(let t=0;500>t&&!r.isAtEnd();t++){const t=r.peek();if(t.value===e){o=!0;break}if(t.value===n||t.value===g||"def"===t.value||t.value===m)break;r.advance()}r.restorePosition(a);let c=!1;if(!o){const e=r.savePosition(),i=s.line,o=100;for(;!r.isAtEnd()&&o>r.current-e;){const e=r.peek(),s=e.value?.toLowerCase();if(s===g||"def"===s||s===m)break;if(s===t||s===n){e.line===i&&(c=!0);break}if((r.checkIsCommand()||r.isCommand(s))&&void 0!==e.line&&e.line!==i){c=!0;break}r.advance()}r.restorePosition(e)}const l=o||c;let u;if(l)u=r.parseExpression();else{const t=[],n=20;let i=0;for(;!r.isAtEnd()&&!r.checkIsCommand()&&!r.isCommand(r.peek().value)&&!r.check(e)&&n>i;){const e=r.savePosition();t.push(r.parseLogicalAnd()),r.savePosition()===e&&r.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&&r.advance();const e=[];for(;!r.isAtEnd()&&!r.check(t)&&!r.check(n)&&(r.checkIsCommand()||r.isCommand(r.peek().value));){r.advance();const t=r.parseCommand();t&&e.push(t)}if(0===e.length&&r.isAtEnd())throw Error("Expected command after 'then' in if statement - incomplete conditional");i.push(ht(e,{start:s.start,end:r.getPosition().end,line:s.line,column:s.column}));let a=!1;if(r.check(t))if(r.advance(),r.check("if")){const e=r.peek();r.advance();const t=Rt(r,e);i.push(ht([t],{start:e.start,end:r.getPosition().end,line:e.line,column:e.column})),a=!0}else{const e=[];for(;!r.isAtEnd()&&!r.check(n)&&(r.checkIsCommand()||r.isCommand(r.peek().value));){r.advance();const t=r.parseCommand();t&&e.push(t)}i.push(ht(e,{start:s.start,end:r.getPosition().end,line:s.line,column:s.column}))}a||r.consume(n,"Expected 'end' after if block")}else{if(!r.checkIsCommand()&&!r.isCommand(r.peek().value))throw Error("Expected command after if condition in single-line form");{r.advance();const e=r.parseCommand();i.push(ht([e],{start:s.start,end:r.getPosition().end,line:s.line,column:s.column}))}}return Tt.from(s).withArgs(...i).endingAt(r.getPosition()).build()}function $t(e,t){const n=[],r={};if(e.checkAnySelector()||e.checkContextVar()||e.match("<")){const t=e.parsePrimary();if(n.push(t),e.match("*")){if(e.checkIdentifierLike()){const t=e.advance();n.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();n.push(t)}}else if(e.checkIdentifierLike()){const t=e.parsePrimary();n.push(t)}if(e.match("and")&&e.match("set")&&e.checkIdentifierLike()){const t=e.advance();r.set={type:"identifier",name:t.value,start:t.start,end:t.end,line:t.line,column:t.column}}const s=Tt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition());return Object.keys(r).length>0&&s.withModifiers(r),s.build()}function Lt(e,t){const n=[],r=xt(e,[h]);r&&n.push(r),kt(e,h,n);const s=xt(e);return s&&n.push(s),Tt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}function jt(e,t){const n=[];if(e.check("between")){e.advance(),n.push(e.createIdentifier("between"));const i=xt(e,[r]);if(i&&"binaryExpression"===i.type&&"and"===i.operator)i.left&&n.push(i.left),n.push(e.createIdentifier("and")),i.right&&n.push(i.right);else{i&&n.push(i),kt(e,r,n);const t=xt(e,[h,m,s]);t&&n.push(t)}if(St(e,[h,m],n)){const t=xt(e);t&&n.push(t)}return Tt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}const i=xt(e,[h,m]);if(i&&n.push(i),St(e,[h,m],n)){const t=xt(e);t&&n.push(t)}return e.check("modal")&&(e.advance(),n.push({type:"literal",value:"modal",raw:"modal"})),Tt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}function It(e,t){const r=e.parseExpression();if(!r)return e.addError("Put command requires content expression"),null;const s=e.peek();if(!s||!A.includes(s.value))return e.addError(`Expected operation keyword (${A.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=S:"at"===i&&(e.check(w)||e.check(b)?(At(e,b),e.check(w)&&(e.advance(),e.check(p)&&(e.advance(),i=k))):e.check(n)&&(e.advance(),e.check(p)&&(e.advance(),i=S)));const a=e.parseExpression();return a?Tt.fromIdentifier(t).withArgs(r,e.createIdentifier(i),a).endingAt(e.getPosition()).build():(e.addError("Put command requires target expression after operation keyword"),null)}const Mt=["innerhtml","outerhtml","into","over","delete","morph","morphouter"];function Dt(s,i){const o=s.savePosition();let a=null,c=[];try{a=function(e){if(!e.check(":"))return null;if(e.advance(),e.check(":")){e.advance();const t=e.advance();return{type:"identifier",name:t.value,scope:"global",start:t.start-2,end:t.end}}const t=e.advance();return{type:"identifier",name:t.value,scope:"local",start:t.start-1,end:t.end}}(s)??function(e){if(!e.check(v)&&!e.check("local"))return null;const t=e.advance(),n=e.advance();return{type:"identifier",name:n.value,scope:t.value,start:t.start,end:n.end}}(s)??function(e){if(!e.check(b))return null;const t=e.savePosition();e.advance();const n=e.parseExpression();if(!n)return e.restorePosition(t),null;if("binaryExpression"===n.type&&n.operator===p){const e=n.left,t=n.right;return yt(e,t,{start:e.start??0,end:t.end??0,line:e.line??1,column:e.column??1})}return e.check(f)?n:(e.restorePosition(t),null)}(s),a||(a=s.parseExpression())}catch{s.restorePosition(o),a=null}if(!a){const i=function(s){if(s.match(":")){const e=s.advance();return{expression:{type:"identifier",name:e.value,scope:"local",start:e.start,end:e.end},tokens:[]}}const i=[];for(;!(s.isAtEnd()||s.check(f)||s.check(e)||s.check(r)||s.check(t)||s.check(n));)i.push(s.parsePrimary());if(0===i.length)return{expression:null,tokens:[]};if(i.length>=4){const e=(e,t)=>e[t];if(e(i[0],"value")===b&&e(i[2],"value")===p){const t=i[1],n=i[3];return{expression:yt(ut(e(t,"value")||e(t,"name")||"",{start:t.start??0,end:t.end??0,line:t.line??1,column:t.column??1}),{type:"idSelector"===n.type?"idSelector":"cssSelector",value:e(n,"value")||e(n,"name")||"",start:n.start??0,end:n.end??0,line:n.line,column:n.column},{start:i[0].start??0,end:n.end??0,line:i[0].line??1,column:i[0].column??1}),tokens:[]}}}return 1===i.length?{expression:i[0],tokens:[]}:{expression:null,tokens:i}}(s);a=i.expression,c=i.tokens}if(!s.check(f)){const e=s.isAtEnd()?"end of input":s.peek().value;throw Error("Expected 'to' in set command, found: "+e)}s.advance();const l=s.parseExpression()??s.parsePrimary(),u=[];return a?u.push(a):c.length>0&&u.push(...c),u.push(s.createIdentifier(f)),l&&u.push(l),Tt.fromIdentifier(i).withArgs(...u).endingAt(s.getPosition()).build()}function Pt(e,t){const n=[];for(;!Et(e,["catch","finally"])&&(e.checkIdentifierLike()||e.checkSelector()||e.checkLiteral()||e.checkTimeExpression()||e.match("<"));)n.push(e.parsePrimary());return Tt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}function Ft(e){if(e.isAtEnd())return!0;const t=e.peek().value;return["as","with","{","then","end","else","otherwise",")"].includes(t)||Et(e)}function Bt(e){if(e.check("{"))return!1;if(!e.checkIdentifierLike())return!1;const t=e.peekAt(1);return null!==t&&":"===t.value}function qt(e){const t=[],n=e.getPosition();do{if(!e.checkIdentifierLike())break;const n=e.advance(),r={type:"identifier",name:n.value,start:n.start,end:n.end,line:n.line,column:n.column};e.consume(":","Expected ':' after property name in fetch named arguments");const s=e.parsePrimary();s&&t.push({key:r,value:s})}while(e.match(",")&&!e.isAtEnd());const r=e.getPosition();return{type:"objectLiteral",properties:t,start:n.start,end:r.end,line:n.line,column:n.column}}const Vt=new Set(["em","ex","cap","ch","ic","rem","lh","rlh","vw","vh","vi","vb","vmin","vmax","cm","mm","Q","pc","pt","px"]);class _t{constructor(e,t,n){this.current=0,this.errors=[],this.warnings=[],this.prattCache=new Map,this.tokens=e,this.keywordResolver=t?.keywords,this.registryIntegration=t?.registryIntegration,t?.semanticAnalyzer&&t?.language&&(this.semanticAdapter=new ve({analyzer:t.semanticAnalyzer,language:t.language,confidenceThreshold:t.semanticConfidenceThreshold??.5})),this.originalInput=n||e.map(e=>e.value).join(" ")}resolveKeyword(e){return this.keywordResolver?this.keywordResolver.resolve(e)??e:e}addWarning(e){this.warnings.push(e)}parse(){this.prattCache.clear();const e=this.parseInternal();return this.errors.length>0&&(e.errors=[...this.errors]),e}parseInternal(){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}}const e=this.peek(),t=e&&je(e.value)?e.value:null;if(this.check("init")||this.check("on")||this.check("def")||this.checkComment()||null!==t){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")){const t=this.peek(),n=t?je(t.value):void 0;if(n){const t=this.advance(),r=n(this.getContext(),t);r&&e.push(r);continue}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")){de("✅ PARSER: Found event handlers after command sequence, parsing as program");const t=[e];de(`✅ PARSER: Starting with ${t.length} statement(s) from command sequence`);let n=0;for(;!this.isAtEnd()&&this.check("on");){de(`✅ PARSER: Parsing event handler #${n+1}, current token: ${this.peek().value}`),this.advance();const e=this.parseEventHandler();if(de("✅ PARSER: parseEventHandler returned:",e?`type=${e.type}, event=${e.event}`:"null"),e&&(t.push(e),n++,de(`✅ PARSER: Added event handler, now have ${t.length} statements total`)),de(`✅ 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 de("⚠️ 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};de("✅ PARSER: No more event handlers, at end of input");break}}return de(`✅ 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 n=this.parseExpression();if(this.error)return{success:!1,node:n||this.createErrorNode(),tokens:this.tokens,error:this.error};if(!this.isAtEnd()){const e=this.peek();return n&&["number","string","identifier"].includes(e.kind)?this.addError(`Unexpected token: ${e.value} (missing operator between values? expected one of +, -, *, /, etc.)`):this.addError("Unexpected token: "+e.value),{success:!1,node:n||this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}return{success:!0,node:n,tokens:this.tokens,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.parseExpressionPratt(0)}parseExpressionPratt(e){const t=`${this.current}:${e}`,n=this.prattCache.get(t);if(n)return this.current=n.endPos,n.node;if(this.isAtEnd())return this.addError("Unexpected end of expression"),this.createErrorNode();const r=this.peek(),s=_t.PRATT_TABLE.get(r.value);let i;if(s?.prefix){const e=this.advance();if(this.isAtEnd())return this.addError(`Expected expression after '${e.value}' operator`),this.createErrorNode();i=s.prefix.handler(e,this.makePrattContext())}else i=this.parseCall();for(;!this.isAtEnd();){const t=this.peek();if(60>=e){const e=this.tryParseStringPostfix(i,t);if(e){i=e;continue}}const n=_t.PRATT_TABLE.get(t.value);if(!n?.infix){if(be.has(t.value)||we.has(t.value))break;break}const[r]=n.infix.bp;if(e>r)break;if("="===t.value&&this.tokens.length>this.current+1&&">"===this.tokens[this.current+1].value){if(this.advance(),this.advance(),this.addError('Arrow functions (=>) are not supported in hyperscript. Use "js ... end" blocks for JavaScript callbacks.'),!this.isAtEnd())try{this.parseExpressionPratt(0)}catch(e){de("arrow body discarded after error:",e instanceof Error?e.message:e+"")}return this.createErrorNode()}if("+"===t.value||"-"===t.value){const e=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(e&&("+"===e.value||"-"===e.value))return this.addError(`Invalid operator combination: ${t.value}${e.value}`),i}if("*"===t.value||"/"===t.value||"%"===t.value){const e=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(e&&("*"===e.value||"/"===e.value||"%"===e.value||"+"===e.value||"-"===e.value))return this.addError("*"===t.value&&"*"===e.value?"Unexpected token: "+e.value:`Invalid operator combination: ${t.value}${e.value}`),i}const s=this.advance();if(this.isAtEnd()&&!_t.POSTFIX_UNARY_OPERATORS.has(s.value))return this.addError(`Expected expression after '${s.value}' operator`),i;i=n.infix.handler(i,s,this.makePrattContext())}return this.prattCache.set(t,{node:i,endPos:this.current}),i}tryParseStringPostfix(e,t){const n=t.value;let r=null;if(Vt.has(n)?r=n:"%"===n&&(this.canStartOperand(this.tokens.length>this.current+1?this.tokens[this.current+1]:null)||(r="%")),null==r)return null;const s=this.advance();return{type:"stringPostfix",expression:e,unit:r,start:e.start,end:s.end,line:e.line,column:e.column}}canStartOperand(e){if(!e)return!1;const t=e.value;return!be.has(t)&&!we.has(t)&&("number"===e.kind||"string"===e.kind||"identifier"===e.kind||"symbol"===e.kind||["(","[","{","-","+","!","#",".","<","$","@"].includes(t))}makePrattContext(){const e=this;return{peek:()=>e.tokens.length>e.current?e.tokens[e.current]:void 0,advance:()=>{const t=e.tokens[e.current];return e.current++,t},parseExpr:t=>e.parseExpressionPratt(t),isStopToken:()=>{const t=e.tokens[e.current];return!t||be.has(t.value)||we.has(t.value)},atEnd:()=>e.current>=e.tokens.length}}parseLogicalAnd(){return this.parseExpressionPratt(11)}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()||this.checkNumber()||this.checkIdentifier()||this.checkContextVar()||this.check("("))){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=[],n=this.resolveKeyword(e.name.toLowerCase());if(this.isCompoundCommand(n))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 C(e)}parseCompoundCommand(s){return function(s,i){switch(i.name.toLowerCase()){case"put":return It(s,i);case"trigger":case"send":return Ct(s,i);case"remove":return Lt(s,i);case"toggle":return jt(s,i);case"set":return Dt(s,i);case"halt":return Ot(s,i);case"measure":return $t(s,i);case"js":return function(e,t){const r=[];if(e.match("(")){for(;!e.check(")")&&!e.isAtEnd();)e.checkIdentifierLike()&&r.push(e.advance().value),e.match(",");e.consume(")","Expected ) after js parameters")}const s=e.peek().start,i=function(e,t){const n=e.getInputSlice(t);if(!n)return t;let r=0;for(;n.length>r;){const e=n[r];if("'"!==e&&"’"!==e&&"‘"!==e)if('"'!==e)if("`"!==e)if("/"===e&&n.length>r+1&&"/"===n[r+1])for(r+=2;n.length>r&&"\n"!==n[r];)r++;else if("/"===e&&n.length>r+1&&"*"===n[r+1]){for(r+=2;n.length>r&&("*"!==n[r]||r+1>=n.length||"/"!==n[r+1]);)r++;r+=2}else{if(!("e"!==e&&"E"!==e||r+3>n.length||"end"!==n.slice(r,r+3).toLowerCase()||0!==r&&/[a-zA-Z0-9_]/.test(n[r-1])||n.length>r+3&&/[a-zA-Z0-9_]/.test(n[r+3])))return t+r;r++}else{for(r++;n.length>r&&"`"!==n[r];)"\\"===n[r]&&r++,r++;r++}else{for(r++;n.length>r&&'"'!==n[r];)"\\"===n[r]&&r++,r++;r++}else{for(r++;n.length>r&&n[r]!==e;)"\\"===n[r]&&r++,r++;r++}}return t+n.length}(e,s);for(;!e.isAtEnd()&&!e.check(n)&&e.peek().start<i;)e.advance();e.consume(n,"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:r.map(e=>({type:"literal",value:e,start:t.start,end:t.end})),start:t.start,end:e.getPosition().end};return Tt.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(r))continue;if(s.check(e)||s.check(t)||s.check(n))break;if(s.checkIsCommand())continue;break}break}if(0===a.length)throw Error("tell command requires at least one command after the target");return Tt.fromIdentifier(i).withArgs(o,...a).endingAt(s.getPosition()).build()}(s,i);case"pick":return function(e,t){const n=Tt.fromIdentifier(t);At(e,b);const r=e.peek().value,s=e=>({type:"literal",value:e,start:t.start,end:t.end}),i=()=>{if(!e.match("of","from"))throw Error("pick: expected 'of' or 'from' before source expression");return e.parseExpression()};if("first"===r){e.advance();const t=e.parsePrimary(),r=i();return n.withArgs(r).withModifier("variant",s("first")).withModifier("count",t).endingAt(e.getPosition()).build()}if("last"===r){e.advance();const t=e.parsePrimary(),r=i();return n.withArgs(r).withModifier("variant",s("last")).withModifier("count",t).endingAt(e.getPosition()).build()}if("random"===r){let t;e.advance(),e.check("of")||e.check("from")||(t=e.parsePrimary());const r=i(),o=n.withArgs(r).withModifier("variant",s("random"));return t&&o.withModifier("count",t),o.endingAt(e.getPosition()).build()}if("item"===r||"items"===r||"character"===r||"characters"===r){let t,r;e.advance(),e.match("at","from"),t=e.match("start")?s("start"):e.parsePrimary();let o=!1;(e.match("to")||e.match(".."))&&(e.match("end")?o=!0:r=e.parsePrimary());let a="default";e.match("inclusive")?a="inclusive":e.match("exclusive")&&(a="exclusive");const c=i(),l=n.withArgs(c).withModifier("variant",s("range")).withModifier("rangeStart",t).withModifier("rangeMode",s(a));return o?l.withModifier("rangeEnd",s("end")):r&&l.withModifier("rangeEnd",r),l.endingAt(e.getPosition()).build()}if("match"===r||"matches"===r){e.advance(),e.match("of");const t=e.parsePrimary();let o;e.matchOperator("|")&&(o=e.advance().value);const a=i(),c=n.withArgs(a).withModifier("variant",s("match"===r?"match":"matches")).withModifier("regex",t);return o&&c.withModifier("flags",s(o)),c.endingAt(e.getPosition()).build()}return Pt(e,t)}(s,i);case"start":return function(e,t){if(!e.match("view"))throw Error("start: expected 'view transition' (only `start view transition ... end` is supported)");if(!e.match("transition"))throw Error("start view: expected 'transition'");const n={};if(e.match("using")){const t=e.parsePrimary();n.transitionName=t}const r=e.parseCommandListUntilEnd();return Tt.fromIdentifier(t).withArgs(...r).withModifiers(n).endingAt(e.getPosition()).build()}(s,i);case"swap":case"morph":return function(e,t){const n=[];let r=null;if(!e.isAtEnd()){const t=e.peek();if(t&&t.value){const s=t.value.toLowerCase();Mt.includes(s)&&(r=s,e.advance(),n.push(e.createIdentifier(r)))}}if("delete"===r){const r=e.parseExpression();return r&&n.push(r),Tt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}!e.isAtEnd()&&e.check(p)&&(e.advance(),n.push(e.createIdentifier("of")));const s=e.parseExpression();if(s&&n.push(s),!e.isAtEnd()&&e.check(d)){e.advance(),n.push(e.createIdentifier("with"));const t=e.parseExpression();t&&n.push(t)}return Tt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}(s,i);default:return Pt(s,i)}}(this.getContext(),s)}parsePutCommand(e){return It(this.getContext(),e)}parseSetCommand(e){return Dt(this.getContext(),e)}parseHaltCommand(e){return Ot(this.getContext(),e)}parseMeasureCommand(e){return $t(this.getContext(),e)}parseTriggerCommand(e){return Ct(this.getContext(),e)}parseCommandListUntilTerminator(e){const t=[],n=()=>this.check("end")||e.some(e=>this.check(e));for(de("🔄 parseCommandListUntilTerminator: Starting (extraStops:",e.join(","),")");!this.isAtEnd()&&!n();){de("📍 Loop iteration, current token:",this.peek().value,"kind:",this.peek().kind);let e=!1;const r=this.checkIsCommand(),s=!r&&this.checkIdentifier()&&this.isCommand(this.peek().value);if(r||s){de(r?"✅ Found COMMAND token:":"✅ Found IDENTIFIER that is a command:",this.peek().value),this.advance();const n=this.error;try{const r=this.parseCommand();this.error&&this.error!==n&&(de("⚠️ parseCommandListUntilTerminator: Command parsing added error, restoring. Error was:",this.error.message),this.error=n),r&&(de("✅ Parsed command:",r.name),t.push(r),e=!0)}catch(e){de("⚠️ parseCommandListUntilTerminator: Command parsing threw, restoring:",e instanceof Error?e.message:e+""),this.error=n}}else this.checkIdentifier()&&de("❌ IDENTIFIER is not a command:",this.peek().value);if(!e){de("❌ No command parsed, breaking. Current token:",this.peek().value);break}for(de("📍 After parsing command, current token:",this.peek().value);!(this.isAtEnd()||n()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(","));)de("⚠️ Skipping unexpected token:",this.peek().value),this.advance();if(this.match("then","and",","))de("✅ Found separator, continuing");else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){de("📍 No separator and no command, breaking. Current token:",this.peek().value);break}de("✅ Next token is a command, continuing without separator")}}let r="end";for(const t of e)if(this.check(t)){r=t;break}return this.check("end")||e.some(e=>this.check(e))||(r=""),de("✅ parseCommandListUntilTerminator: parsed",t.length,"commands (terminator:",r,")"),{commands:t,terminator:r}}parseCommandListUntilEnd(){const{commands:e}=this.parseCommandListUntilTerminator([]);if(de('🔍 After loop, checking for "end". Current token:',this.peek().value),!this.check("end"))throw de('❌ ERROR: Expected "end" but got:',this.peek().value,"at position:",this.peek().start),Error('Expected "end" to close repeat block');return de('✅ Found "end", consuming it'),this.advance(),e}parseCommandListUntilEndOrElse(){const{commands:e,terminator:t}=this.parseCommandListUntilTerminator(["else"]),n="else"===t;if(!n){if(!this.check("end"))throw Error('Expected "end" to close repeat block');this.advance()}return{commands:e,hasElse:n}}parseRepeatBody(){const{commands:e,terminator:t}=this.parseCommandListUntilTerminator(["else","until","while"]);if("end"===t)this.advance();else if(""===t)throw Error('Expected "end", "else", "until", or "while" to close repeat block');return{commands:e,terminator:t}}parseRepeatCommand(e){return function(e,t){const n=[];let r="forever",f=null,p=null,m=null,g=null,v=null,w=null;if(e.check(s)){e.advance(),r=s;const t=e.peek();Ue(t)&&(v=t.value,e.advance()),e.check(u)&&(e.advance(),g=e.parseExpression())}else if(e.check(u))e.advance(),r=s,v="it",g=e.parseExpression();else if(e.check(i))e.advance(),r=i,m=e.parseExpression();else if(e.check(o))if(e.advance(),r=o,e.check(y)){e.advance(),r="until-event";const t=e.peek();if(de("📍 Parsing event name, current token:",{value:t.value,kind:t.kind}),!Ue(t)&&!Ve(t))throw Error('Expected event name after "event"');if(f=t.value,e.advance(),de("✅ Got event name:",f,"Next token:",e.peek().value),de('🔍 Checking for "from", current token:',e.peek().value),e.check(h)){de('✅ Found "from", advancing...'),e.advance(),de('📍 After consuming "from", current token:',e.peek().value),At(e,b)&&de('✅ Found "the", advancing...');const t=e.peek();de("🔍 Before parsePrimary for event target:",{value:t.value,kind:t.kind,position:t.start}),p=e.parsePrimary(),de("✅ After parsePrimary, eventTarget:",p)}else de('❌ No "from" found, skipping target parsing')}else m=e.parseExpression();else e.check(a)?(e.advance(),r=a):(w=e.parseExpression(),e.check(c)&&(e.advance(),r=c));let E,x=null;if(e.check(d)){const t=e.peekAt(1);t&&t.value.toLowerCase()===l&&(e.advance(),e.advance(),x=l)}else if(e.check(l)){e.advance();const t=e.peek();Ue(t)?(x=t.value,e.advance()):x=l}let k=null,S=!1;if(r===a){const t=e.parseRepeatBody();if(E=t.commands,"else"===t.terminator)e.advance(),k=e.parseCommandListUntilEnd();else if("until"===t.terminator||"while"===t.terminator){if(S=!0,r=t.terminator,e.advance(),m=e.parseExpression(),!e.check("end"))throw Error('Expected "end" to close repeat block');e.advance()}}else{const t=e.parseCommandListUntilEndOrElse();E=t.commands,t.hasElse&&(e.advance(),k=e.parseCommandListUntilEnd())}n.push({type:"identifier",name:r,start:t.start,end:t.end,line:t.line,column:t.column});const A={start:t.start,end:t.end,line:t.line,column:t.column};v&&n.push(dt(v,A)),g&&n.push(g),m&&n.push(m),w&&n.push(w),f&&n.push(dt(f,A)),p&&n.push(p),x&&n.push(dt(x,A)),n.push(ht(E,{...A,end:A.end||0})),null!==k&&n.push(ht(k,{...A,end:A.end||0}));const N=Tt.from(t).withArgs(...n);return S&&N.withModifier("bottomTested",{type:"literal",value:!0,...A}),N.endingAt(e.getPosition()).build()}(this.getContext(),e)}parseForCommand(e){return function(e,t){const n=[];let r=null,s=null;e.check("each")&&e.advance();const i=e.peek();if(!Ue(i))throw Error('Expected variable name after "for"');if(r=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.peekAt(1);t&&t.value.toLowerCase()===l&&(e.advance(),e.advance(),o=l)}else if(e.check(l)){e.advance();const t=e.peek();Ue(t)?(o=t.value,e.advance()):o=l}const a=e.parseCommandListUntilEnd();n.push({type:"identifier",name:"for",start:t.start,end:t.end,line:t.line,column:t.column});const c={start:t.start,end:t.end,line:t.line,column:t.column};return n.push(dt(r,c)),n.push(s),o&&n.push(dt(o,c)),n.push(ht(a,{...c,end:c.end||0})),Tt.from({...t,value:"repeat"}).withArgs(...n).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseWaitCommand(e){return function(e,t){const n=[];if(e.checkTimeExpression()||e.checkLiteral()||e.checkContextVar()||e.check("(")||e.checkIdentifierLike()&&!e.check("for")&&!Et(e)){const r=e.parseExpression();return n.push(r),Tt.from(t).withArgs(...n).blocking().endingAt(e.getPosition()).build()}if(e.check("for")){e.advance();const r=[];do{const t=e.peek();if(!Ue(t))throw Error('Expected event name after "for"');const n=t.value;e.advance();const s=[];if(e.check("(")){for(e.advance();!e.isAtEnd()&&!e.check(")");){const t=e.peek();if(!Ue(t))break;s.push(t.value),e.advance(),e.check(",")&&e.advance()}if(!e.check(")"))throw Error('Expected ")" after event parameters');e.advance()}if(r.push({name:n,params:s}),!e.check("or"))break;e.advance()}while(!e.isAtEnd());let s=null;e.check(h)&&(e.advance(),At(e,b),s=e.parsePrimary());const i={start:t.start,end:e.getPosition().end,line:t.line,column:t.column};n.push(mt(r.map(e=>pt([{key:ut("name",i),value:lt(e.name,`"${e.name}"`,i)},{key:ut("args",i),value:mt(e.params.map(e=>lt(e,`"${e}"`,i)),i)}],i)),i)),s&&n.push(s)}return Tt.from(t).withArgs(...n).blocking().endingAt(e.getPosition()).build()}(this.getContext(),e)}parseInstallCommand(e){return function(e,t){const n=[];if(!e.checkIdentifierLike())throw Error('Expected behavior name after "install"');const r=e.advance().value,s=e.previous();if(n.push(ut(r,{start:s.start,end:s.end,line:s.line,column:s.column})),e.check("(")){e.advance();const r=[];for(;!e.isAtEnd()&&!e.check(")");)if(r.push(Nt(e)),e.check(","))e.advance();else if(!e.check(")"))break;if(!e.check(")"))throw Error('Expected ")" after behavior parameters');if(e.advance(),r.length>0){const s={start:t.start,end:e.getPosition().end,line:t.line,column:t.column};n.push(pt(r.map(e=>({key:e.name?ut(e.name,s):lt("_positional","_positional",s),value:e.value})),s))}}return Tt.from(t).withArgs(...n).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseTransitionCommand(e){return function(e,t){const n=[],r={};let s=null;const i=e.peek();if(Ue(i)||"*"===i.value){let t="";e.check("*")&&(t="*",e.advance());const n=function(e){if(!e.checkIdentifierLike())return"";let t=e.advance().value;for(;e.check("-")&&!e.isAtEnd();)t+="-",e.advance(),e.checkIdentifierLike()&&(t+=e.advance().value);return t}(e);n&&(t+=n,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(n.push(s),!e.check(f))throw Error('Expected "to" keyword after property in transition command');e.advance();const o=e.parsePrimary();if(r.to=o,e.check("over")){e.advance();const t=e.parsePrimary();r.over=t}if(e.check(d)){e.advance();const t=e.parsePrimary();r.with=t}return Tt.from(t).withArgs(...n).withModifiers(r).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseAddCommand(e){return function(e,t){const n=[];if(e.match("{"))n.push(e.parseCSSObjectLiteral());else{const t=xt(e,[f]);t&&n.push(t)}if(e.check(f)){e.advance();const t=xt(e);t&&n.push(t)}return Tt.from(t).withArgs(...n).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseIfCommand(e){return Rt(this.getContext(),e)}parseRemoveCommand(e){return Lt(this.getContext(),e)}parseToggleCommand(e){return jt(this.getContext(),e)}parseRegularCommand(e){return Pt(this.getContext(),e)}parseCall(){let e=this.parsePrimary();for(;;)if(this.match("("))e=this.finishCall(e);else if(this.match(".")){const t=this.consumeIdentifierLike("Expected property name after '.' - malformed member access");e=this.createMemberExpression(e,this.createIdentifier(t.value),!1)}else if(this.match("?.")){const t=this.consumeIdentifierLike("Expected property name after '?.' - malformed optional access"),n=this.createMemberExpression(e,this.createIdentifier(t.value),!1);n.optional=!0,e=n}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):Ge(this.peek())&&this.peek().value.startsWith("@")?t=this.advance().value:this.check("[")&&this.tokens[this.current+1]?.value?.startsWith("@")?(this.advance(),t=this.advance().value,this.consume("]","Expected ']' after attribute reference")):t=this.consumeIdentifierLike("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()&&Ue(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),n=this.processEscapeSequences(t);return this.createLiteral(n,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,t=e.slice(1,-2).trim(),n=this.createSelector(t);return n.fromQuery=!0,n.raw=e,n}if(this.matchSelector())return this.createSelector(this.previous().value);if(this.match("<"))return this.parseHyperscriptSelector();if(this.match("(")){if(this.isAtEnd())return this.addError("Expected expression inside parentheses"),this.createErrorNode();const 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(Ye)||this.matchPredicate(qe)||this.matchPredicate(_e)||this.matchPredicate(Be)||this.matchPredicate(Ve))){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,n=this.createSelector("."+t);return this.createCallExpression(this.createIdentifier(e.value),[n])}this.current=t}if(this.check("#")){const t=this.current;if(this.advance(),this.checkIdentifier()){const t=this.advance().value,n=this.createSelector("#"+t);return this.createCallExpression(this.createIdentifier(e.value),[n])}this.current=t}return this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||this.check("end")?this.createIdentifier(e.value):this.parseNavigationFunction(e.value)}const t=this.check(".")||this.check("?.");return"my"!==e.value||t?"its"!==e.value||t?"your"!==e.value||t?"the"===e.value?this.parseTheXofY():"values"===e.value&&this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:"values"},target:this.parsePrimary(),line:e.line,column:e.column}):this.createIdentifier(e.value):this.parseContextPropertyAccess("you"):this.parseContextPropertyAccess("it"):this.parseContextPropertyAccess("me")}if(this.match("$"))return this.parseDollarExpression();if("\\"===this.peek().value)return this.parseBlockLiteral();if(Ge(this.peek())&&this.peek().value.startsWith("@")){const e=this.advance();return{type:"attributeAccess",attributeName:e.value.substring(1),start:e.start,end:e.end,line:e.line,column:e.column}}const t=this.peek();return this.addError(`Unexpected token: ${t.value} at line ${t.line}, column ${t.column}`),this.advance(),this.createErrorNode()}parseBlockLiteral(){const e=this.peek().start;this.advance();const t=[];for(;!(this.isAtEnd()||this.check("-")&&">"===this.tokens[this.current+1]?.value);){if(!this.checkIdentifier()){this.addError("Unexpected token in block literal parameters: "+this.peek().value);break}t.push(this.advance().value),this.match(",")}return this.check("-")&&">"===this.tokens[this.current+1]?.value?(this.advance(),this.advance(),{type:"blockLiteral",parameters:t,body:this.parseExpression(),start:e,end:this.previous().end,line:this.previous().line,column:this.previous().column}):(this.addError("Expected '->' in block literal"),this.createErrorNode())}parseDollarExpression(){if(this.checkNumber()){const 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().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.check("["))this.advance(),t=this.parseExpression(),this.consume("]","Expected ']' after computed property name in object literal");else if(this.matchString()){const e=this.previous().value,n=e.slice(1,-1);t=this.createLiteral(n,e)}else{if(!this.check("-")&&!this.checkPredicate(Ye))return this.addError("Expected property name in object literal"),this.createErrorNode();{let e="",n=!1;for(;this.check("-");)this.advance(),e+="-",n=!0;for(this.checkPredicate(Ye)&&(e+=this.advance().value);this.check("-");)this.advance(),e+="-",n=!0,this.checkPredicate(Ye)&&(e+=this.advance().value);if(""===e||"-"===e)return this.addError("Expected property name in object literal"),this.createErrorNode();t=n?this.createLiteral(e,e):this.createIdentifier(e)}}this.consume(":","Expected ':' after property name in object literal");const n=this.parseExpression();if(e.push({key:t,value:n}),!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 n;if(this.matchPredicate(Ye))n=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);n=this.createLiteral(t,e)}}if(!this.consume(":","Expected ':' after CSS property name"))return this.createErrorNode();const r=[];let s=!1,i=0,o=-1,a=-1;for(;!this.isAtEnd()&&(0!==i||!this.check(";")&&!this.check("}"));){const e=this.advance();r.push(e.value),0>o&&"number"==typeof e.start&&(o=e.start),"number"==typeof e.end&&(a=e.end),"$"===e.value&&this.check("{")&&(s=!0),"{"===e.value&&i++,"}"===e.value&&i--}const c=this.originalInput&&o>=0&&a>o?this.originalInput.slice(o,a):r.join(""),l=s?{type:"templateLiteral",value:c,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}:this.createLiteral(c,c);if(t.push({key:n,value:l}),this.check(";")&&this.advance(),this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after CSS object literal properties"),{type:"objectLiteral",properties: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(),n=t.value;if(!this.check("("))return this.addError('Expected "(" after constructor name'),this.createErrorNode();this.advance();const r=[];if(!this.check(")"))do{r.push(this.parseExpression())}while(this.match(","));return this.consume(")","Expected ')' after constructor arguments"),{type:"callExpression",callee:{type:"identifier",name:n,start:t.start,end:t.end,line:t.line,column:t.column},arguments:r,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 n=[];if(this.check("(")){if(this.advance(),!this.check(")"))for(this.checkIdentifier()&&n.push(this.advance().value);this.check(",");)this.advance(),this.checkIdentifier()&&n.push(this.advance().value);this.consume(")","Expected ')' after parameter list")}const r=this.parseCommandBlock(["end","catch","finally"]);let s,i,o;return this.check("catch")&&(this.advance(),this.checkIdentifier()&&(s=this.advance().value),i=this.parseCommandBlock(["end","finally"])),this.check("finally")&&(this.advance(),o=this.parseCommandBlock(["end"])),this.consume("end","Expected 'end' after function definition"),{type:"def",name:t,params:n,body:r,...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.checkIsCommand()||this.checkIdentifierLike()?this.advance():this.consumeEvent(e);let n=t.value;return this.check(":")&&(this.advance(),n=`${n}:${this.advance().value}`),n}callExprToCommandNode(e,t){return{type:"command",name:e.callee.name,args:e.arguments,isBlocking:!1,...void 0!==t.start&&{start:t.start},...void 0!==t.end&&{end:t.end},...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}}}createPseudoCommandNode(e,t,n,r,s){return{type:"command",name:"pseudo-command",args:[{type:"objectLiteral",properties:[{key:{type:"identifier",name:"methodName"},value:{type:"literal",value:e,raw:`"${e}"`}},{key:{type:"identifier",name:"methodArgs"},value:{type:"literal",value:t.arguments,raw:JSON.stringify(t.arguments)}},...n?[{key:{type:"identifier",name:"preposition"},value:{type:"literal",value:n,raw:`"${n}"`}}]:[],{key:{type:"identifier",name:"targetExpression"},value:r}]}],isBlocking:!1,...void 0!==s.start&&{start:s.start},...void 0!==s.end&&{end:s.end},...void 0!==s.line&&{line:s.line},...void 0!==s.column&&{column:s.column}}}tryParsePseudoCommand(e,t){const n=e.callee.name,r=this.peek();if(!(_t.PSEUDO_COMMAND_PREPOSITIONS.includes(r.value.toLowerCase())||Ye(r)&&!this.isCommand(r.value)||_e(r)))return{node:this.callExprToCommandNode(e,t),isPseudo:!1,targetFailed:!1};let s,i;this.isCommand(n)&&this.addWarning({type:"command-shadow",message:`Method '${n}' shadows hyperscript command`,suggestions:[`Rename method to avoid confusion (e.g., '${n}Fn', 'my${n.charAt(0).toUpperCase()+n.slice(1)}')`,`Use 'call' command instead: call ${n}(...)`,"This works but may cause ambiguity"],severity:"warning",code:"PSEUDO_CMD_SHADOW",...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}}),_t.PSEUDO_COMMAND_PREPOSITIONS.includes(this.peek().value.toLowerCase())&&(s=this.advance().value.toLowerCase());try{i=this.parseExpression()}catch{return{node:this.callExprToCommandNode(e,t),isPseudo:!1,targetFailed:!0}}return{node:this.createPseudoCommandNode(n,e,s,i,t),isPseudo:!0,targetFailed:!1}}parseCommandWithErrorRecovery(){this.advance();const e=this.error;try{const t=this.parseCommand();return this.error&&this.error!==e&&(de("⚠️ Command parsing added error, restoring error state. Error was:",this.error.message),this.error=e),t}catch(t){return de("⚠️ Command parsing threw exception, restoring error state:",t instanceof Error?t.message:t+""),this.error=e,null}}parseEventHandler(){de("🔧 parseEventHandler: ENTRY - parsing event handler");const e=[];let t=!1;if(this.check("first")&&!this.checkIsCommand()&&this.tokens.length>this.current+1){const e=this.tokens[this.current+1],n=e?.value?.toLowerCase();n&&"of"!==n&&"in"!==n&&"from"!==n&&(this.advance(),t=!0,de("🔧 parseEventHandler: Parsed 'first' as .once alias"))}const n=this.parseEventNameWithNamespace("Expected event name after 'on'");for(e.push(n),de("🔧 parseEventHandler: Parsed first event name: "+n);this.check("or");){this.advance(),de("🔧 parseEventHandler: Found 'or', parsing additional event name");const t=this.parseEventNameWithNamespace("Expected event name after 'or'");e.push(t),de("🔧 parseEventHandler: Parsed additional event name: "+t)}let r;if(de("🔧 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,de(`🔧 parseEventHandler: Detected custom event source '${r}' for event '${t}'`)}}const s=[];if(this.match("(")){if(!this.check(")"))do{const e=this.advance();s.push(e.value)}while(this.match(","));this.consume(")","Expected ')' after event parameters"),de("🔧 parseEventHandler: Parsed event parameters: "+s.join(", "))}const i={};for(;this.check(".");){this.advance();const e=this.advance().value.toLowerCase();if("once"===e)i.once=!0,de("🔧 parseEventHandler: Parsed modifier '.once'");else if("prevent"===e)i.prevent=!0,de("🔧 parseEventHandler: Parsed modifier '.prevent'");else if("stop"===e)i.stop=!0,de("🔧 parseEventHandler: Parsed modifier '.stop'");else if("debounce"===e||"throttle"===e){if(!this.check("("))throw Error(`Expected '(' after '.${e}'`);{this.advance();const t=this.advance(),n=parseInt(t.value,10);if(isNaN(n))throw Error(`Expected number for ${e} delay, got: ${t.value}`);"debounce"===e?(i.debounce=n,de(`🔧 parseEventHandler: Parsed modifier '.debounce(${n})'`)):(i.throttle=n,de(`🔧 parseEventHandler: Parsed modifier '.throttle(${n})'`)),this.consume(")",`Expected ')' after ${e} delay`)}}else de(`🔧 parseEventHandler: Warning - unknown modifier '.${e}'`)}if(this.check("debounced")||this.check("throttled")){const e=this.advance().value.toLowerCase(),t="debounced"===e?"debounce":"throttle";if(this.match("at"))if(this.checkTimeExpression()){const n=this.advance(),r=(o=n.value).endsWith("ms")?parseInt(o,10):o.endsWith("seconds")||o.endsWith("s")?1e3*parseFloat(o):o.endsWith("minutes")?6e4*parseFloat(o):o.endsWith("hours")?36e5*parseFloat(o):o.endsWith("days")?864e5*parseFloat(o):parseInt(o,10);i[t]=r,de(`🔧 parseEventHandler: Parsed '${e} at ${n.value}' (${r}ms)`)}else if(this.matchNumber()){const n=parseInt(this.previous().value,10);i[t]=n,de(`🔧 parseEventHandler: Parsed '${e} at ${n}'`)}else this.addError(`Expected time expression after '${e} at', got: ${this.peek().value}`);else this.addError(`Expected 'at' after '${e}'`)}var o;let a,c,l,u;if(t&&(i.once=!0),Object.keys(i).length>0&&de("🔧 parseEventHandler: Parsed modifiers:",i),this.match("[")&&(a=this.parseExpression(),this.consume("]","Expected ']' after event condition")),this.match("from")){const e=this.advance();c=e.value,de(`🔧 parseEventHandler: Parsed 'from' target: ${c} (kind: ${e.kind})`)}if(this.match("of")){const e=this.advance();l=e.value.startsWith("@")?e.value.substring(1):e.value,de("🔧 parseEventHandler: Parsed attribute name: "+l)}this.match("in")&&(de("🔧 parseEventHandler: Found 'in' keyword, parsing watch target"),u=this.parseExpression(),de("🔧 parseEventHandler: Parsed watch target expression"));const f=[];for(de(`✅ parseEventHandler: About to parse commands, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd: ${this.isAtEnd()}`);!this.isAtEnd();){if(de(`✅ parseEventHandler: Loop iteration, current token: ${this.peek().value}, kind: ${this.peek().kind}`),this.check("on")){de("✅ parseEventHandler: Stopping command parsing, found next event handler 'on'");break}if(this.checkComment())de("✅ parseEventHandler: Skipping comment token: "+this.peek().value),this.advance();else{if(this.check("end")){de("✅ 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 n=this.parseCommand();f.push(n);continue}if(e&&"callExpression"===e.type){const t=this.tryParsePseudoCommand(e,e);if(f.push(t.node),t.isPseudo||t.targetFailed)continue}}else{const e=this.parseCommandWithErrorRecovery();e&&(f.push(e),de("✅ parseEventHandler: Parsed command, next token: "+(this.isAtEnd()?"END":this.peek().value)))}}else{if(!this.checkIdentifier())break;{const e=this.peek();if(this.isCommand(e.value)){const e=this.parseCommandWithErrorRecovery();e&&f.push(e)}else{let e;const t=this.error;try{e=this.parseExpression()}catch(e){de("⚠️ Expression parsing error, restoring error state:",e instanceof Error?e.message:e+""),this.error=t;break}if(e&&"callExpression"===e.type){const t=this.tryParsePseudoCommand(e,e);if(f.push(t.node),t.targetFailed)continue}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 n={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}};f.push(n)}}}}}}for(;!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(",")||this.check("on"));)this.advance();if(!this.match("then","and",",")&&!this.checkIsCommand()&&!this.isCommand(this.peek().value))break}}const h=this.getPosition(),d={type:"eventHandler",event:1===e.length?e[0]:e.join("|"),events:e,commands:f,...s.length>0&&{args:s},...a&&{condition:a},...c&&{target:c},...l&&{attributeName:l},...u&&{watchTarget:u},...r&&{customEventSource:r},...Object.keys(i).length>0&&{modifiers:i},start:h.start,end:h.end,line:h.line,column:h.column};return de(`🔧 parseEventHandler: Created node with events: ${e.join(", ")}, attributeName: ${l||"none"}, watchTarget: ${u?"yes":"none"}`),d}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 n=[];if(this.match("(")){if(!this.check(")"))do{const e=this.consumeIdentifierLike("Expected parameter name");n.push(e.value)}while(this.match(","));this.consume(")","Expected ')' after behavior parameters")}const r=new Set(n),s=[];let i;for(;!this.isAtEnd()&&!this.check("end");)if(this.match("on")){const e=this.getPosition(),t=this.parseEventNameWithNamespace("Expected event name after 'on'"),n=[];if(this.check("(")){for(this.advance();!this.isAtEnd()&&!this.check(")");){const e=this.peek();Ye(e)?(n.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(),n=r.has(t.value);this.checkIsCommand()&&!n||(e.push(t.value),i=t.value,this.advance())}}const o={type:"eventHandler",event:t,commands:this.parseCommandListUntilEnd(),...void 0!==i&&{target:i},...n.length>0&&{args:n},start:e.start,end:this.getPosition().end,line:e.line,column:e.column};s.push(o)}else{if(!this.match("init")){this.addError("Unexpected token in behavior body: "+this.peek().value);break}i={type:"initBlock",commands:this.parseCommandBlock(["end"]),start: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:n,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,n=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")||(de("⚠️ parseCommandSequence: Command parsing added non-critical error, restoring error state. Error was:",this.error.message),this.error=t)),e.push(n);!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("on"));)de("⚠️ parseCommandSequence: Skipping unexpected token:",this.peek().value),this.advance();if(this.check("on")){de('✅ parseCommandSequence: Found "on" token, stopping command sequence to allow event handler parsing');break}if(this.match("then"))continue;if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value))continue;break}{const t=this.peek(),n=this.getPosition(),r="Expected command, got: "+t.value;this.addError(r);const s=gt(n,r,t.value);if(e.push(s),this.synchronizeToCommandBoundary(),this.isAtEnd())break;if(this.match("then"))continue;if(this.check("end")||this.check("on"))break;if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value))continue;break}}return 1===e.length?e[0]:function(e){return{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}}(e)}getMultiWordPattern(e){return function(e){return vt.find(t=>t.command===e.toLowerCase())||null}(e)}isTokenKeyword(e,t){return bt(e,t)}parseMultiWordCommand(e,t){return function(e,t,n){const r=e.getMultiWordPattern(n);if(!r)return null;const s=[],i={};for(;!Et(e,["catch","finally",...r.keywords])&&!bt(e.peek(),r.keywords);){const t=e.parsePrimary();if(!t)break;if(s.push(t),!e.match(",")&&bt(e.peek(),r.keywords))break}for(;!e.isAtEnd()&&bt(e.peek(),r.keywords);){const t=e.advance().value,n=e.parseExpression();if(n&&(i[t]=n),!bt(e.peek(),r.keywords))break}const o=Tt.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?(de(`[Semantic] Successfully parsed with confidence ${t.confidence}:`,t.node.name),t.node):(de(`[Semantic] Low confidence (${t.confidence}), falling back to traditional parser`),null)}catch(e){return de("[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(),n=t.value.toLowerCase();if(e.includes(n))break;if(Be(t))break;this.advance()}}parseCommand(){const e=this.parseCommandCore();if(e&&"command"===e.type&&!e.body&&(this.check("when")||this.check("where"))){const t=this.peek().value.toLowerCase();this.advance();const n=this.parseExpression();n&&(e.modifiers={...e.modifiers??{},[t]:n})}return e}parseCommandCore(){const e=this.previous();let t=e.value;if(this.semanticAdapter&&!["install","wait","repeat","for","set","put","increment","decrement","add","append","toggle","if","unless","make","measure","trigger","halt","remove","exit","return","closest","js","tell"].includes(t.toLowerCase())){const e=this.getRemainingInput(),t=this.trySemanticParse(e);if(t)return this.skipToCommandBoundary(),t}if("beep"===t&&this.check("!")&&(this.advance(),t="beep!"),"fetch"===t)return function(e,t){const n={};let r=null;if(!e.isAtEnd()&&e.check("/")&&(r=function(e){const t=e.savePosition();let n="";for(;!e.isAtEnd()&&!Ft(e);)n+=e.advance().value;return n&&"/"!==n?{type:"literal",value:n,raw:n,start:t,end:e.savePosition()}:(e.restorePosition(t),null)}(e)),r||(r=e.parsePrimary()),!r)return e.addError("fetch requires a URL"),Tt.from(t).endingAt(e.getPosition()).build();!e.isAtEnd()&&e.check("{")&&(n.with=e.parsePrimary());for(let t=0;3>t&&!e.isAtEnd();t++)if(!e.check("as")||n.as){if(!e.check("with")||n.with){if(e.check("do")&&!n.doNotThrow){const t=e.peekAt(1),r=e.peekAt(2);if("not"===t?.value&&"throw"===r?.value){const t=e.advance();e.advance();const r=e.advance();n.doNotThrow={type:"literal",value:!0,start:t.start,end:r.end,line:t.line,column:t.column};continue}}break}e.advance(),n.with=Bt(e)?qt(e):e.parsePrimary()}else e.advance(),e.isAtEnd()||At(e,"a")||At(e,"an"),n.as=e.parsePrimary();const s=Tt.from(t).withArgs(r).endingAt(e.getPosition());return Object.keys(n).length>0&&s.withModifiers(n),s.build()}(this.getContext(),e);const n=this.parseMultiWordCommand(e,t);if(n)return n;const r=t.toLowerCase();if("repeat"===r)return this.parseRepeatCommand(e);if("for"===r)return this.parseForCommand(e);if("if"===r||"unless"===r)return this.parseIfCommand(e);if("wait"===r)return this.parseWaitCommand(e);if("install"===r)return this.parseInstallCommand(e);if("transition"===r)return this.parseTransitionCommand(e);if("add"===r)return this.parseAddCommand(e);if(this.isCompoundCommand(r))return this.parseCompoundCommand({type:"identifier",name:r,start:e.start||0,end:e.end||0,line:e.line,column:e.column})||function(e,t){return{type:"command",name:e,args:[],partial:!0,start:t.start,end:t.end,line:t.line,column:t.column}}(r,this.getPosition());const s=[];if(("increment"===t||"decrement"===t)&&!this.isAtEnd())return function(e,t){const n=t.value,r="increment"===n?"+":"-";let s=!1;e.check(v)&&(s=!0,e.advance());const i=e.parseExpression();if(!i)throw Error("Expected variable or expression after "+n);let o;if(e.check("by")){e.advance();const t=e.parseExpression();if(!t)throw Error(`Expected amount after 'by' in ${n} command`);o=t}else o=lt(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=ft(r,i,o,c),u=[a,ut(f,c),l];return Tt.from(t).withName("set").withArgs(...u).withOriginalCommand(n).endingAt({end:e.previous().end}).build()}(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 n=s[s.length-1];if(!n||"identifier"!==n.type&&"keyword"!==n.type||!t.includes(n.name??n.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 n;this.match("else")&&(n=this.parseConditionalBranch());const r=this.getPosition();return{type:"conditionalExpression",test:e,consequent:t,alternate:n,start:r.start,end:r.end,line:r.line,column:r.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())}const n=this.createCallExpression(this.createIdentifier(e),t);if("next"===e||"previous"===e){const e=this.parseRelativePositionalModifiers();e&&(n.relativePositional=e)}return n}parseRelativePositionalModifiers(){if(!(this.check("from")||this.check("within")||this.check("in")||this.check("with")))return null;let e,t,n,r=!1,s=!1;return this.match("from")&&(e=this.parseRelativePositionalOperand()),this.match("in")?(r=!0,n=this.parseRelativePositionalOperand()):this.match("within")&&(t=this.parseRelativePositionalOperand()),this.match("with")&&(this.match("wrapping"),s=!0),{from:e,within:t,inElt:n,inSearch:r,wrapping:s}}parseRelativePositionalOperand(){return this.match("the"),this.parsePrimary()}parseTheXofY(){if(!this.checkIdentifier())return this.createIdentifier("the");const e=this.peek(),t=e.value;return["first","last","next","previous","random","closest"].includes(t)?(this.advance(),this.parseNavigationFunction(t)):(this.advance(),this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:t},target:this.parseCall(),line:e.line,column:e.column}):this.createIdentifier(t))}parseContextPropertyAccess(e){if(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 n="*"+t;return this.createMemberExpression(this.createIdentifier(e),this.createIdentifier(n),!1)}{if(this.check("[")&&this.tokens[this.current+1]?.value?.startsWith("@")){this.advance();const t=this.advance();return this.consume("]","Expected ']' after attribute reference"),this.createMemberExpression(this.createIdentifier(e),{type:"attributeAccess",attributeName:t.value.substring(1),start:t.start,end:t.end,line:t.line,column:t.column},!0)}if(Ge(this.peek())&&this.peek().value.startsWith("@")){const t=this.advance();return this.createMemberExpression(this.createIdentifier(e),this.createIdentifier(t.value),!1)}const t=this.consumeIdentifierLike(`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;R(t)&&de(`💡 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 lt(e,t,this.getPosition())}createIdentifier(e){return ut(e,this.getPosition())}createBinaryExpression(e,t,n){return ft(e,t,n,this.getPosition())}createUnaryExpression(e,t,n){return function(e,t,n,r){return{type:"unaryExpression",operator:e,argument:t,prefix:n,start:r.start,end:r.end,line:r.line,column:r.column}}(e,t,n,this.getPosition())}createCallExpression(e,t){return function(e,t,n){return{type:"callExpression",callee:e,arguments:t,start:n.start,end:n.end,line:n.line,column:n.column}}(e,t,this.getPosition())}createMemberExpression(e,t,n){return function(e,t,n,r){return{type:"memberExpression",object:e,property:t,computed:n,start:r.start,end:r.end,line:r.line,column:r.column}}(e,t,n,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,n){return{type:"possessiveExpression",object:e,property:t,start:n.start,end:n.end,line:n.line,column:n.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(de(`✅ createProgramNode: Called with ${e.length} statements`),0===e.length)return de("✅ createProgramNode: Returning error node (0 statements)"),{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===e.length)return de(`✅ 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 de(`✅ 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!(!at(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(We)}matchSelector(){return this.matchPredicate(We)}checkAnySelector(){return this.checkPredicate(ze)}checkLiteral(){return this.checkPredicate(Je)}checkIdentifierLike(){return this.checkPredicate(Ue)}checkIsCommand(){return this.checkPredicate(Be)}checkCommandTerminator(){return this.checkPredicate(ct)}checkReference(){return this.checkPredicate(Ze)}checkTimeExpression(){return this.checkPredicate(Ke)}checkEvent(){return this.checkPredicate(Ve)}checkContextVar(){return this.checkPredicate(_e)}checkComment(){return this.checkPredicate(Xe)}checkIdentifier(){return this.checkPredicate(Ye)}checkKeyword(){return this.checkPredicate(qe)}checkString(){return this.checkPredicate(Qe)}matchString(){return this.matchPredicate(Qe)}checkNumber(){return this.checkPredicate(et)}matchNumber(){return this.matchPredicate(et)}checkBoolean(){return this.checkPredicate(tt)}matchBoolean(){return this.matchPredicate(tt)}checkTemplateLiteral(){return this.checkPredicate(nt)}matchTemplateLiteral(){return this.matchPredicate(nt)}checkQueryReference(){return this.checkPredicate(rt)}matchQueryReference(){return this.matchPredicate(rt)}checkIdSelector(){return this.checkPredicate(st)}checkClassSelector(){return this.checkPredicate(it)}checkCssSelector(){return this.checkPredicate(ot)}checkBasicOperator(){return this.checkPredicate(at)}matchBasicOperator(){return this.matchPredicate(at)}matchTimeExpression(){return this.matchPredicate(Ke)}matchIdentifierLike(){return this.matchPredicate(Ue)}matchComparisonOperator(){return this.matchPredicate(He)}consumePredicate(e,t){return this.checkPredicate(e)?this.advance():(this.addError(t),this.peek())}consumeIdentifier(e){return this.consumePredicate(Ye,e)}consumeIdentifierLike(e){return this.consumePredicate(Ue,e)}consumeEvent(e){return this.consumePredicate(Ve,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 n=t.start||0,r=t.line||1,s=t.column||1;if(e.includes("property name after '.'")){const e=this.current>0?this.previous():t;n=e.end||e.start||0,r=e.line||1,s=e.column||1}if(e.includes("parenthes")){const e=this.current>0?this.previous():t;n=e.end||e.start||0,r=e.line||1,s=e.column||1,0===n&&this.current>0&&(n=this.current)}if(e.includes("Expected expression after")){const e=this.current>0?this.previous():t;n=e.start||0,r=e.line||1,s=e.column||1,0===n&&(n=Math.max(1,this.current-1))}if(e.includes("Missing operand")){let e=t;for(let t=this.current-1;t>=0;t--){const n=this.tokens[t];if(n&&("+"===n.value||"-"===n.value)){e=n;break}}n=e.start||0,r=e.line||1,s=e.column||1}this.error={message:e,line:Math.max(1,r),column:Math.max(1,s),position:Math.max(0,n)},this.errors.push(this.error)}synchronizeToCommandBoundary(){for(;!this.isAtEnd();){const e=this.peek();if("then"===e.value||"end"===e.value||"on"===e.value)return;if(this.checkIsCommand()||this.isCommand(e.value)&&!this.isKeyword(e.value))return;de("⚠️ synchronize: Skipping token:",e.value),this.advance()}}parseAttributeOrArrayLiteral(){const e=this.previous().start,t=this.previous().line,n=this.previous().column;if(!this.isAtEnd()&&this.peek().value.startsWith("@")){const r=[];for(;!this.check("]")&&!this.isAtEnd();){const e=this.advance();r.push(e.value)}this.consume("]","Expected ']' after attribute literal");const s=r.join("");if(!s.includes("="))return{type:"attributeAccess",attributeName:s.replace(/^@/,""),start:e,end:this.previous().end,line:t,column:n};const i="["+s+"]";return{type:"literal",value:i,raw:i,start:e,end:this.previous().end,line:t,column:n}}const r=new Set(["=","~=","|=","^=","$=","*="]),s=this.tokens[this.current],i=this.tokens[this.current+1];if("identifier"===s?.kind&&("]"===i?.value||i&&r.has(i.value)&&"string"===this.tokens[this.current+2]?.kind)){let e="["+this.advance().value;if(this.check("]"))this.advance(),e+="]";else{const t=this.advance().value,n=this.advance().value;e+=t+'"'+(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?n.slice(1,-1):n)+'"',this.consume("]","Expected ']' after attribute selector"),e+="]"}return this.createSelector(e)}const o=[];if(!this.check("]"))do{if(this.check("]"))break;o.push(this.parseExpression())}while(this.match(","));return this.consume("]","Expected ']' after array elements"),{type:"arrayLiteral",elements:o,start:e,end:this.previous().end,line:t,column:n}}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),parseExpression:this.parseExpression.bind(this),parsePrimary:this.parsePrimary.bind(this),parseLogicalAnd:this.parseLogicalAnd.bind(this),parseCSSObjectLiteral:this.parseCSSObjectLiteral.bind(this),parseCommand:this.parseCommand.bind(this),parseCommandSequence:this.parseCommandSequence.bind(this),parseCommandListUntilEnd:this.parseCommandListUntilEnd.bind(this),parseCommandListUntilEndOrElse:this.parseCommandListUntilEndOrElse.bind(this),parseRepeatBody:this.parseRepeatBody.bind(this),getPosition:this.getPosition.bind(this),addError:this.addError.bind(this),addWarning:this.addWarning.bind(this),isCommand:this.isCommand.bind(this),isCompoundCommand:this.isCompoundCommand.bind(this),isKeyword:this.isKeyword.bind(this),getMultiWordPattern:this.getMultiWordPattern.bind(this),resolveKeyword:this.resolveKeyword.bind(this),savePosition:()=>e.current,restorePosition:t=>{e.current=t},peekAt:t=>{const n=e.current+t;return n>=0&&e.tokens.length>n?e.tokens[n]:null},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 Ht(e,t){const n=function(e){const t={input:"",position:0,line:1,column:1,tokens:[]};t.input=e;const n=e.length;for(;n>t.position&&(_(t),n>t.position);){const n=e[t.position];if("-"!==n||"-"!==q(t,1))if('"'!==n){if("'"===n||"'"===n){const e=q(t,1),n=t.tokens[t.tokens.length-1];if("s"!==e||!n||n.kind!==P.IDENTIFIER&&n.kind!==P.SELECTOR&&"]"!==n.value&&")"!==n.value&&"}"!==n.value)W(t);else{const e=t.position;V(t),V(t),H(t,P.OPERATOR,"'s",e)}continue}if("`"!==n)if("<"!==n)if("#"!==n){if("."===n){if("."===q(t,1)){const e=t.position;V(t),V(t),H(t,P.OPERATOR,"..",e);continue}const e=t.tokens[t.tokens.length-1],n=new Set(["from","to","into","on","in","at","between","first","last","next","previous","closest","random","of","some","no"]),r=e&&e.kind===P.IDENTIFIER&&E.has(e.value.toLowerCase()),s=e&&e.kind===P.IDENTIFIER&&n.has(e.value.toLowerCase());if((!e||e.kind===P.OPERATOR&&")"!==e.value&&"]"!==e.value||r||s||"("===e.value||"["===e.value||"{"===e.value||","===e.value||";"===e.value)&&(!e||e.end!==t.position)&&(te(q(t))||"{"===q(t)||"-"===q(t))){Z(t);continue}}if("@"!==n)if("{"!==n)if("}"!==n){if("["===n){const e=t.tokens[t.tokens.length-1],n=e&&e.kind===P.IDENTIFIER&&M.has(e.value)&&t.tokens.length>=2&&"on"===t.tokens[t.tokens.length-2]?.value;(!e||e.kind!==P.IDENTIFIER&&")"!==e.value&&"]"!==e.value||n)&&n?(H(t,P.SYMBOL,"["),V(t)):(H(t,P.OPERATOR,"["),V(t));continue}if("]"!==n){if("$"===n){const e=q(t,1);if(e>="a"&&"z">=e||e>="A"&&"Z">=e||"_"===e){ee(t);continue}}ie(n)?X(t):"0">n||n>"9"?("a">n||n>"z")&&("A">n||n>"Z")&&"_"!==n?(H(t,P.UNKNOWN,n),V(t)):Q(t):Y(t)}else H(t,P.OPERATOR,"]"),V(t)}else H(t,P.OPERATOR,"}"),V(t);else H(t,P.OPERATOR,"{"),V(t);else G(t)}else Z(t);else se(t)?K(t):X(t);else J(t)}else W(t);else z(t)}return t.tokens}(e);return new _t(n,t,e).parse()}_t.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty","ignoring case"]),_t.PRATT_TABLE=Ae,_t.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];class Ut{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 n of this.afterExecuteHooks)await n(e,t)}async runOnError(e,t){let n=t;for(const t of this.onErrorHooks){const r=await t(e,n);r instanceof Error&&(n=r)}return n}shouldIntercept(e,t){for(const n of this.interceptCommandHooks)if(n(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 zt(e){return e instanceof Error&&("isHalt"in e||"isExit"in e||"isBreak"in e||"isContinue"in e||"isReturn"in e)?e:null}function Wt(e){return{ok:!0,value:e}}function Jt(e){return{ok:!1,error:e}}function Zt(e){return!0===e.ok}const Kt=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,n]of this.types)if(n.isType(e))return t;return"Unknown"}getHyperScriptType(e){const t=this.inferType(e),n=this.types.get(t);return n?.hyperscriptType??"unknown"}coerce(e,t,n){const r=this.types.get(t);if(!r){if(this.config.strictMode)throw Error("Unknown target type: "+t);return null}if(r.isType(e))return e;if(this.config.cacheCoercions){const n=`${this.inferType(e)}:${t}:${JSON.stringify(e)}`;if(this.coercionCache.has(n))return this.coercionCache.get(n)}const s=this.inferType(e),i=r.coerceFrom?.[s];if(i){const r=i(e,n);if(this.config.cacheCoercions&&null!==r){const n=`${s}:${t}:${JSON.stringify(e)}`;this.coercionCache.set(n,r)}return r}return r.defaultValue}canCoerce(e,t){const n=this.types.get(t);if(!n)return!1;if(n.isType(e))return!0;const r=this.inferType(e);return void 0!==n.coerceFrom?.[r]}getCoercionInfo(e,t){const n=this.types.get(t);return n&&(e===t||n.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 n=e;if(n.startsWith("#")||n.startsWith(".")||n.match(/^[\w-]+$/))try{return document.querySelector(n)}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,n)=>{t[n+""]=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 Gt(e){const t=Kt.get("String");return t?t.isType(e):"string"==typeof e}function Xt(e){const t=Kt.get("Number");return t?t.isType(e):"number"==typeof e}function Yt(e){const t=Kt.get("Boolean");return t?t.isType(e):"boolean"==typeof e}function Qt(e){const t=Kt.get("Object");return t?t.isType(e):"object"==typeof e&&null!==e}function en(e){const t=Kt.get("Function");return t?t.isType(e):"function"==typeof e}function tn(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"style"in e}function nn(e){return e instanceof Element}function rn(e){return e instanceof HTMLElement}const sn=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function on(e,t){return sn.has(t.toLowerCase())?e.hasAttribute(t):e.getAttribute(t)}const an={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=>function(e){if(null===e||"object"!=typeof e||!("tagName"in e))return!1;const t=e.tagName;return"INPUT"===t||"SELECT"===t||"TEXTAREA"===t}(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=>"disabled"in 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,tabindex:e=>tn(e)?e.tabIndex:void 0,hidden:e=>tn(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,next:e=>e.nextElementSibling,previous:e=>e.previousElementSibling,values:e=>function(e){if(e instanceof HTMLFormElement)return new FormData(e);const t=new FormData;return e.querySelectorAll("input, select, textarea").forEach(e=>{const n=e.getAttribute("name");n&&"value"in e&&t.append(n,e.value)}),t}(e)};function cn(e,t){if(t.startsWith("*"))return function(e,t){if(!rn(e))return;if(t.startsWith("computed-"))return getComputedStyle(e).getPropertyValue(t.slice(9))||"";const n=t.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());return e.style[n]}(e,t.slice(1));if(t.startsWith("computed-")){const n=t.slice(9);return rn(e)?getComputedStyle(e).getPropertyValue(n):void 0}if(t.startsWith("@"))return on(e,t.slice(1));const n=an[t.toLowerCase()];if(n)return n(e);if(function(e,t){return e.hasAttribute(t)}(e,t))return on(e,t);const r=e[t];return en(r)?r.bind(e):r}const ln={1:"one",2:"two",3:"three",4:"four",5:"five"};function un(e,t,n,r){if(e.length!==t){return`${n} requires exactly ${s=t,ln[s]??s+""} argument${1===t?"":"s"}${r?` (${r})`:""}`}var s;return null}function fn(e,t,n,r){return"string"!=typeof e[t]?`${n} ${r||"argument "+(t+1)} must be a string`:null}function hn(e,t,n){return un(e,1,t,n)??fn(e,0,t,n)}function dn(e,t){return un(e,2,t,"left, right")}function pn(){return null}function mn(e,t,n,r){return e.length>t?`${n} expression takes at most ${1===t?"one":t+""} argument${1===t?"":"s"}${r?` (${r})`:""}`:null}function yn(e,t,n,r,s){return t>e.length||e.length>n?`${r} requires ${t}-${n} arguments${s?` (${s})`:""}`:null}function gn(e,t,n,r=[]){return{type:e,message:t,suggestions:r,...n&&{path:n}}}const vn="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 bn;function wn(){return bn({validate:e=>({success:!0,data:e})})}function En(e,t){if(vn)return wn();const n=bn({validate:n=>{if("object"!=typeof n||null===n||Array.isArray(n))return{success:!1,error:gn("type-mismatch","Expected object, received "+typeof n)};const r=n,s={};if(t?.strict){const t=Object.keys(e),n=Object.keys(r).filter(e=>!t.includes(e));if(n.length>0)return{success:!1,error:gn("runtime-error","Unexpected properties: "+n.join(", "))}}for(const[t,n]of Object.entries(e)){const e=r[t];if(!(t in r)&&!n.t)return{success:!1,error:gn("missing-argument",`Required field "${t}" is missing`,t)};const i=n.validate(e);if(!i.success)return{success:!1,error:gn("validation-error",i.error.message||`Field "${t}" validation failed`,i.error.path?`${t}.${i.error.path}`:t)};void 0!==i.data&&(s[t]=i.data)}return{success:!0,data:s}}});return n.strict=()=>En(e,{strict:!0}),n}bn=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 bn(t)}),e.min||(e.min=function(e){const t=this.validate.bind(this),n={...this,validate:n=>{const r=t(n);return r.success&&"string"==typeof r.data&&e>r.data.length?{success:!1,error:gn("runtime-error",`String must be at least ${e} characters long`)}:r}};return bn(n)}),e.max||(e.max=function(e){const t=this.validate.bind(this),n={...this,validate:n=>{const r=t(n);return r.success&&"string"==typeof r.data&&r.data.length>e?{success:!1,error:gn("runtime-error",`String must be at most ${e} characters long`)}:r}};return bn(n)}),e.default||(e.default=function(e){const t=this.validate.bind(this),n={...this,i:e,o:!0,validate:n=>void 0===n?{success:!0,data:e}:t(n)};return bn(n)}),e.rest||(e.rest=function(e){return this}),e.refine||(e.refine=function(e,t){const n=this.validate.bind(this),r={...this,validate:r=>{const s=n(r);return s.success?e(s.data)?s:{success:!1,error:gn("runtime-error",t||"Refinement validation failed")}:s}};return bn(r)}),new Proxy(e,{get:(e,t,n)=>t in e||"string"!=typeof t||t.startsWith("_")||"constructor"===t||"validate"===t||"then"===t?Reflect.get(e,t,n):function(...e){return n}})};const xn=e=>function(e={}){return vn?wn():bn({validate:t=>e.optional&&null==t?{success:!0,data:void 0}:"string"!=typeof t?{success:!1,error:gn("type-mismatch","Expected string, received "+typeof t)}:void 0!==e.minLength&&e.minLength>t.length?{success:!1,error:gn("runtime-error",`String must be at least ${e.minLength} characters long`)}:void 0!==e.maxLength&&t.length>e.maxLength?{success:!1,error:gn("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:gn("runtime-error",`Expected "${e.pattern.source.slice(1,-1)}", received "${t}"`)}:{success:!1,error:gn("missing-argument","String does not match required pattern")}:{success:!0,data:t},...e.description&&{description:e.description}})}(e||{}),kn=e=>function(e={}){return vn?wn():bn({validate:t=>{const n=Number(t);return isNaN(n)?{success:!1,error:gn("type-mismatch","Expected number, received "+typeof t)}:void 0!==e.min&&e.min>n?{success:!1,error:gn("runtime-error","Number must be at least "+e.min)}:void 0!==e.max&&n>e.max?{success:!1,error:gn("runtime-error","Number must be at most "+e.max)}:{success:!0,data:n}}})}(e||{}),Sn=()=>vn?wn():bn({validate:e=>"boolean"!=typeof e?{success:!1,error:gn("type-mismatch","Expected boolean, received "+typeof e)}:{success:!0,data:e}}),An=e=>En(e),Nn=e=>function(e){return vn?wn():bn({validate:t=>{if(!Array.isArray(t))return{success:!1,error:gn("type-mismatch","Expected array, received "+typeof t)};if(t.length!==e.length)return{success:!1,error:gn("runtime-error",`Expected tuple of length ${e.length}, received length ${t.length}`)};const n=[];for(let r=0;e.length>r;r++){const s=e[r].validate(t[r]);if(!s.success)return{success:!1,error:gn("runtime-error",s.error.message,s.error.path?`${r}.${s.error.path}`:""+r)};n.push(s.data)}return{success:!0,data:n}}})}(e),Tn=()=>wn(),Cn=()=>wn(),On=()=>function(e,t="Custom validation failed"){return vn?wn():bn({validate:n=>e(n)?{success:!0,data:n}:{success:!1,error:gn("runtime-error",t)}})}(e=>void 0===e,"Expected undefined");class Rn{trackPerformance(e,t,n,r){e.evaluationHistory&&e.evaluationHistory.push({expressionName:this.name,category:this.category,input:t,output:n.success?n.value:n.error,timestamp:r,duration:Date.now()-r,success:n.success})}trackSimple(e,t,n,r=(n?"success":"error")){e.evaluationHistory&&e.evaluationHistory.push({expressionName:this.name,category:this.category,input:"operation",output:r,timestamp:t,duration:Date.now()-t,success:n})}toBoolean(e){return!(!1===e||0===e||0n===e||""===e||null==e||Xt(e)&&isNaN(e))}success(e,t){return{success:!0,value:e,type:t}}failure(e,t,n,r,s=[]){return{success:!1,error:{name:e,type:t,message:n,code:r,suggestions:s}}}validationSuccess(){return{isValid:!0,errors:[],suggestions:[]}}validationFailure(e,t,n=[]){return{isValid:!1,errors:[{type:e,message:t,suggestions:n}],suggestions:n}}isElement(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"tagName"in e&&"string"==typeof e.tagName}inferType(e){return null===e?"null":void 0===e?"undefined":this.isElement(e)?"element":Array.isArray(e)?"array":Qt(e)?"object":typeof e}inferEvaluationType(e){return void 0===e?"Undefined":null===e?"Null":Gt(e)?"String":Xt(e)?"Number":Yt(e)?"Boolean":Array.isArray(e)?"Array":this.isElement(e)?"Element":"Object"}normalizeCollection(e){return Array.isArray(e)?e:e instanceof NodeList?Array.from(e):Gt(e)?e.split(""):null==e?[]:Qt(e)&&Symbol.iterator in e?Array.from(e):[]}toNumber(e){if(Xt(e)&&Number.isFinite(e))return e;if(Gt(e)){const t=Number(e);return Number.isFinite(t)?t:null}return Yt(e)?e?1:0:null}}function $n(e,t,n,r,s="runtime-error"){return{success:!1,error:{name:e+"ConversionError",type:s,message:n,code:t,suggestions:r}}}function Ln(e,t){return{success:!0,value:e,type:t}}function jn(e,t){return`${e}: ${t instanceof Error?t.message:t+""}`}const In={Array:(e,t)=>{try{return Array.isArray(e)?Ln(e,"array"):e instanceof NodeList?Ln(Array.from(e),"array"):Ln(null==e?[]:[e],"array")}catch(e){return $n("Array","ARRAY_CONVERSION_FAILED",jn("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?Ln("","string"):Gt(e)?Ln(e,"string"):Qt(e)?Ln(JSON.stringify(e),"string"):Ln(e+"","string")}catch(e){return $n("String","STRING_CONVERSION_FAILED",jn("Failed to convert value to String",e),["Check if object has circular references","Ensure value is serializable"])}},Boolean:(e,t)=>{try{if(Yt(e))return Ln(e,"boolean");if(null==e)return Ln(!1,"boolean");if(Gt(e)){const t=e.toLowerCase().trim();return Ln("false"!==t&&"0"!==t&&""!==t,"boolean")}return Xt(e)?Ln(0!==e&&!isNaN(e),"boolean"):Ln(!!e,"boolean")}catch(e){return $n("Boolean","BOOLEAN_CONVERSION_FAILED",jn("Failed to convert value to Boolean",e),["Use explicit true/false values","Check for unexpected data types"])}},Number:(e,t)=>{try{if(Xt(e))return Ln(e,"number");if(null==e)return Ln(0,"number");const t=Number(e);return isNaN(t)?$n("Number","INVALID_NUMBER",`Cannot convert "${e}" to a valid number`,["Check if value contains non-numeric characters","Use a valid numeric format"],"invalid-argument"):Ln(t,"number")}catch(e){return $n("Number","NUMBER_CONVERSION_FAILED",jn("Failed to convert value to Number",e),["Ensure value is convertible to number","Check for special characters"])}},Int:(e,t)=>{const n=In.Number(e,t);return n.success?Ln(Math.trunc(n.value),"number"):n},Float:(e,t)=>{const n=In.Number(e,t);return n.success?Ln(parseFloat(""+n.value),"number"):n},Date:(e,t)=>{try{if(e instanceof Date)return Ln(e,"object");if(null==e)return Ln(new Date(""),"object");if(Gt(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,n,r]=e.split("-").map(Number);return Ln(new Date(t,n-1,r),"object")}const t=new Date(e);return isNaN(t.getTime())?$n("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"):Ln(t,"object")}catch(e){return $n("Date","DATE_CONVERSION_FAILED",jn("Failed to convert value to Date",e),["Check date format","Ensure value is a valid date string or timestamp"])}},JSON:(e,t)=>{if(!Gt(e))return Ln(e,"object");try{return Ln(JSON.parse(e),"object")}catch(e){return $n("JSON","JSON_PARSE_FAILED",jn("Failed to parse value as JSON",e),["Check JSON syntax and escaping","Use `as JSONString` to stringify a value instead"],"syntax-error")}},JSONString:(e,t)=>{try{return Ln(JSON.stringify(e),"string")}catch(e){return $n("JSONString","JSON_STRINGIFY_FAILED",jn("Failed to stringify value as JSON",e),["Check for circular references","Ensure all properties are serializable","Remove functions and undefined values"])}},Object:(e,t)=>{try{if(Qt(e))return Ln(e,"object");if(Gt(e))try{return Ln(JSON.parse(e),"object")}catch(e){return $n("Object","JSON_PARSE_FAILED",jn("Cannot parse JSON string",e),["Check JSON syntax","Ensure proper escaping of quotes","Validate JSON format"],"syntax-error")}return Ln({},"object")}catch(e){return $n("Object","OBJECT_CONVERSION_FAILED",jn("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 Ln(Bn(e),"object");if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),n={};return t.forEach(e=>{const t=e;if(t.name){const e=qn(t);void 0!==e&&(n[t.name]=e)}}),Ln(n,"object")}return Ln({},"object")}catch(e){return $n("FormValues","FORM_VALUES_EXTRACTION_FAILED",jn("Failed to extract form values",e),["Ensure element is a form or contains form inputs","Check form structure","Verify input names are set"])}},FormEncoded:(e,t)=>{try{let n=e;if(e instanceof HTMLElement){const r=In.Values(e,t);if(!r.success)return r;n=r.value}if(!Qt(n))return Ln("","string");const r=new URLSearchParams;for(const[e,t]of Object.entries(n))if(null!=t)if(Array.isArray(t))for(const n of t)r.append(e,n+"");else r.append(e,t+"");return Ln(""+r,"string")}catch(e){return $n("FormEncoded","FORM_ENCODE_FAILED",jn("Failed to URL-encode values",e),["Ensure input is a form element or plain object of scalar/array values"])}},Set:(e,t)=>{try{return Ln(new Set(e),"object")}catch(e){return $n("Set","SET_CONVERSION_FAILED",jn("Failed to convert to Set",e),["Ensure the value is iterable"])}},Map:(e,t)=>{try{return Ln(new Map(Object.entries(e??{})),"object")}catch(e){return $n("Map","MAP_CONVERSION_FAILED",jn("Failed to convert to Map",e),["Ensure the value is a plain object"])}},Keys:(e,t)=>e instanceof Map?Ln(Array.from(e.keys()),"array"):Ln(Object.keys(e??{}),"array"),Entries:(e,t)=>e instanceof Map?Ln(Array.from(e.entries()),"array"):Ln(Object.entries(e??{}),"array"),Reversed:(e,t)=>{try{return Ln(Array.from(e).reverse(),"array")}catch(e){return $n("Reversed","REVERSED_CONVERSION_FAILED",jn("Failed to reverse value",e),["Ensure the value is array-like"])}},Unique:(e,t)=>{try{return Ln([...new Set(e)],"array")}catch(e){return $n("Unique","UNIQUE_CONVERSION_FAILED",jn("Failed to dedupe value",e),["Ensure the value is iterable"])}},Flat:(e,t)=>{try{return Ln(Array.from(e).flat(),"array")}catch(e){return $n("Flat","FLAT_CONVERSION_FAILED",jn("Failed to flatten value",e),["Ensure the value is array-like"])}}},Mn=An({value:Cn(),type:xn().min(1)}),Dn=An({value:Cn(),type:xn().min(1)});new class extends Rn{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=Mn,this.metadata={category:"Conversion",complexity:"medium",sideEffects:[],dependencies:[],returnTypes:["Any"],examples:[{input:'"123" as Int',description:"Convert string to integer",expectedOutput:123},{input:"form as Values",description:"Extract form values as object",expectedOutput:{name:"John",age:"25"}},{input:"[1,2,3] as JSONString",description:"Convert array to JSON string (upstream 0.9.90: use JSONString, not JSON)",expectedOutput:"[1,2,3]"},{input:"'{\"a\":1}' as JSON",description:"Parse a JSON string (upstream 0.9.90: as JSON now parses)",expectedOutput:{a:1}},{input:'"2023-12-25" as Date',description:"Parse date string",expectedOutput:new Date(2023,11,25)}],relatedExpressions:["is","Object","Array"],performance:{averageTime:1,complexity:"O(n)"}},this.documentation={summary:'Converts values between different types using the "as" keyword with comprehensive type safety',parameters:[{name:"value",type:"object",description:"The value to convert",optional:!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 JSONString into storage",explanation:"Convert array to JSON string for storage (upstream 0.9.90: use `as JSONString`)",output:'"[1,2,3]"'},{title:"Date parsing with validation",code:"put my.dateInput as Date into event.detail.date",explanation:"Parse date input with automatic validation",output:"Date object or validation error"},{title:"Boolean conversion with smart parsing",code:'if "false" as Boolean then hide else show',explanation:"Parse string boolean values correctly",output:"false (not true like naive conversion)"}],seeAlso:["is","Values","JSON","Array","Object"],tags:["conversion","types","validation","forms","json","parsing"]}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:{name:"AsExpressionValidationError",type:"validation-error",message:r.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:r.suggestions}};const{value:s,type:i}=t;if(i.startsWith("Fixed")){const r=i.match(/^Fixed:(\d+)$/),o=r?parseInt(r[1],10):0,a=In.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,n),c}let o=In[i];if(o){const r=o(s,e);return this.trackPerformance(e,t,r,n),r}const a={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON",jsonstring:"JSONString",formencoded:"FormEncoded"}[i.toLowerCase()];if(a&&(o=In[a],o)){const r=o(s,e);return this.trackPerformance(e,t,r,n),r}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,n),c}catch(r){const s={success:!1,error:{name:"AsExpressionError",type:"runtime-error",message:"Conversion failed: "+(r instanceof Error?r.message:r+""),code:"CONVERSION_FAILED",suggestions:["Check value and type compatibility","Ensure value is convertible to target type"]}};return this.trackPerformance(e,t,s,n),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 Rn{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=Dn,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 n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:{name:"IsExpressionValidationError",type:"validation-error",message:r.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:r.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=Gt(s);break;case"number":a=Xt(s)&&!isNaN(s);break;case"boolean":a=Yt(s);break;case"object":a=Qt(s);break;case"array":a=Array.isArray(s);break;case"function":a=en(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||Qt(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,n),c}catch(r){const s=this.failure("IsExpressionError","type-mismatch","Type check failed: "+(r instanceof Error?r.message:r+""),"TYPE_CHECK_FAILED",["Check type name spelling","Ensure value is accessible"]);return this.trackPerformance(e,t,s,n),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 Pn={conversions:{dynamicResolvers:[]}},Fn={Array:e=>Array.isArray(e)?e:e instanceof NodeList?Array.from(e):null==e?[]:[e],String:e=>null==e?"":Gt(e)?e:Qt(e)?JSON.stringify(e):e+"",Boolean:e=>{if(Yt(e))return e;if(null==e)return!1;if(Gt(e)){const t=e.toLowerCase().trim();return"false"!==t&&"0"!==t&&""!==t}return Xt(e)?0!==e&&!isNaN(e):!!e},Number:e=>{if(Xt(e))return e;if(null==e)return 0;const t=Number(e);return isNaN(t)?0:t},Math:e=>{if(Xt(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(!Xt(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=Fn.Number(e);return Math.trunc(t)},Float:e=>{const t=Fn.Number(e);return parseFloat(""+t)},Date:e=>{if(e instanceof Date)return e;if(null==e)return new Date(NaN);if(Gt(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,n,r]=e.split("-").map(Number);return new Date(t,n-1,r)}return new Date(e)},JSON:e=>{if(!Gt(e))return e;try{return JSON.parse(e)}catch{return e}},JSONString:e=>{try{return JSON.stringify(e)}catch{return"{}"}},Object:e=>{if(Qt(e))return e;if(Gt(e))try{return JSON.parse(e)}catch(e){return{}}return{}},Fragment:e=>{const t=document.createDocumentFragment(),n=Array.isArray(e)||e instanceof NodeList?Array.from(e):[e];for(const e of n)if(e instanceof Node)t.append(e);else{const n=document.createElement("template");n.innerHTML=null==e?"":e+"",t.append(n.content)}return t},HTML:e=>Gt(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:Fn.String(e)).join(""):e instanceof Element?e.outerHTML:Fn.String(e),Values:(e,t)=>{if(e instanceof HTMLFormElement)return Bn(e);if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),n={};return t.forEach(e=>{e.name&&(n[e.name]=qn(e))}),n}return{}},FormEncoded:(e,t)=>{const n=e instanceof HTMLElement?Fn.Values(e,t):e;if(!Qt(n))return"";const r=new URLSearchParams;for(const[e,t]of Object.entries(n))if(null!=t)if(Array.isArray(t))for(const n of t)r.append(e,n+"");else r.append(e,t+"");return""+r},Set:e=>new Set(e),Map:e=>new Map(Object.entries(e??{})),Keys:e=>e instanceof Map?Array.from(e.keys()):Object.keys(e??{}),Entries:e=>e instanceof Map?Array.from(e.entries()):Object.entries(e??{}),Reversed:e=>Array.from(e).reverse(),Unique:e=>[...new Set(e)],Flat:e=>Array.from(e).flat(),"Values:Form":(e,t)=>{const n=Fn.Values(e,t);return Fn.FormEncoded(n,t)},"Values:JSON":(e,t)=>{const n=Fn.Values(e,t);return JSON.stringify(n)}};function Bn(e){const t={};return e.querySelectorAll("input, select, textarea").forEach(e=>{const n=e;if(n.name){const e=qn(n);void 0!==e&&(void 0!==t[n.name]?(Array.isArray(t[n.name])||(t[n.name]=[t[n.name]]),t[n.name].push(e)):t[n.name]=e)}}),t}function qn(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 Vn={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON",jsonstring:"JSONString",formencoded:"FormEncoded"};function _n(e,t,n){if("string"!=typeof t)throw Error("Conversion type must be a string");if(t.startsWith("Fixed")){const{precision:n}=function(e){const t=e.match(/^Fixed(?::(\d+))?$/);return t?{precision:t[1]?parseInt(t[1],10):0}:{}}(t);return Fn.Number(e).toFixed(n??0)}if(null==e)return e;let r=Fn[t];if(r)return r(e,n);const s=Vn[t.toLowerCase()];if(s&&(r=Fn[s],r))return r(e,n);const i=Pn.conversions[t];if("function"==typeof i)return i(e,n);for(const n of Pn.conversions.dynamicResolvers){const r=n(t,e);if(void 0!==r)return r}return console.warn("Unknown conversion type: "+t),e}const Hn={as:{name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(e,...t){const[n,r]=t;return _n(n,r,e)},validate:e=>un(e,2,"as","value, type")??fn(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[n,r]=t;if(!Gt(r))throw Error("Type check requires a string type");switch(r.toLowerCase()){case"null":return null===n;case"undefined":return void 0===n;case"string":return Gt(n);case"number":return Xt(n)&&!isNaN(n);case"boolean":return Yt(n);case"object":return Qt(n);case"array":return Array.isArray(n);case"function":return en(n);case"date":return n instanceof Date;case"element":return n instanceof Element;case"node":return n instanceof Node;case"nodelist":return n instanceof NodeList;case"empty":return null==n||""===n||Array.isArray(n)&&0===n.length||Qt(n)&&0===Object.keys(n).length;default:return n?.constructor?.name?.toLowerCase()===r.toLowerCase()}},validate:e=>un(e,2,"is","value, type")??fn(e,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(e,t)=>t,validate:e=>un(e,1,"async","expression")}},Un=new Set(["__proto__","constructor","prototype"]);function zn(e,t){if(e instanceof Element)return cn(e,t);if(Qt(e)){if(Un.has(t))return;return e[t]}return e[t]}function Wn(e){let t;if(Array.isArray(e))t=e;else{if(!("undefined"!=typeof NodeList&&e instanceof NodeList||"undefined"!=typeof HTMLCollection&&e instanceof HTMLCollection))return!1;t=Array.from(e)}return 0!==t.length&&t.every(e=>e instanceof Element||null!=e&&"object"==typeof e&&e.constructor!==Object&&!Array.isArray(e))}const Jn={possessive:{name:"possessive",category:"Reference",evaluatesTo:"Any",operators:["'s","s"],async evaluate(e,...t){const[n,r]=t;if(null!=n){if("string"!=typeof r)throw Error("Property name must be a string");return Wn(n)&&!(r in n)?Array.from(n,e=>zn(e,r)):zn(n,r)}},validate:e=>un(e,2,"possessive","element, property")??fn(e,1,"possessive","property name")},my:{name:"my",category:"Reference",evaluatesTo:"Any",operators:["my"],async evaluate(e,...t){const[n]=t;if(e.me){if("string"!=typeof n)throw Error("Property name must be a string");if(e.me instanceof Element)return cn(e.me,n);if(Qt(e.me)){if(Un.has(n))return;return e.me[n]}return e.me[n]}},validate:e=>hn(e,"my","property")},its:{name:"its",category:"Reference",evaluatesTo:"Any",operators:["its"],async evaluate(e,...t){const[n]=t;if(null==e.it)return;if("string"!=typeof n)throw Error("Property name must be a string");const r=e.it;if(r instanceof Element)return cn(r,n);if(Qt(r)){if(Un.has(n))return;return r[n]}return r[n]},validate:e=>hn(e,"its","property")},your:{name:"your",category:"Reference",evaluatesTo:"Any",operators:["your"],async evaluate(e,...t){const[n]=t;if(e.you){if("string"!=typeof n)throw Error("Property name must be a string");if(e.you instanceof Element)return cn(e.you,n);if(Qt(e.you)){if(Un.has(n))return;return e.you[n]}return e.you[n]}},validate:e=>hn(e,"your","property")},of:{name:"of",category:"Reference",evaluatesTo:"Any",operators:["of"],async evaluate(e,...t){const[n,r]=t;if(null!=r){if("string"!=typeof n)throw Error("Property name must be a string");if(r instanceof Element)return cn(r,n);if(Qt(r)){if(Un.has(n))return;return r[n]}return r[n]}},validate:e=>un(e,2,"of","property, object")??fn(e,0,"of","property name")},attribute:{name:"attribute",category:"Reference",evaluatesTo:"String",operators:["@"],async evaluate(e,...t){const[n,r]=t;if("string"!=typeof n)throw Error("Attribute name must be a string");const s=r||e.me;return s&&s instanceof Element?s.getAttribute(n):null},validate:e=>yn(e,1,2,"attribute","attributeName, optional element")??fn(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[n,r,s]=t;if("string"!=typeof n)throw Error("Attribute name must be a string");if("string"!=typeof r)throw Error("Expected value must be a string");const i=s||e.me;return!!(i&&i instanceof Element)&&i.getAttribute(n)===r},validate:e=>yn(e,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??fn(e,0,"attributeWithValue","attribute name")??fn(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[n]=t;if("string"!=typeof n)throw Error("Class name must be a string");const r=n.startsWith(".")?n.slice(1):n,s=document.getElementsByClassName(r);return Array.from(s)},validate:e=>hn(e,"classReference","className")},idReference:{name:"idReference",category:"Reference",evaluatesTo:"Element",operators:["#"],async evaluate(e,...t){const[n]=t;if("string"!=typeof n)throw Error("ID value must be a string");const r=n.startsWith("#")?n.slice(1):n;return document.getElementById(r)},validate:e=>hn(e,"idReference","idValue")}};function Zn(e){return Array.isArray(e)?e:null==e?[]:"string"==typeof e?[e]:e instanceof NodeList||e instanceof HTMLCollection||"number"==typeof e.length?Array.from(e):[e]}function Kn(e,t){const n=e.registry?.get(t);if(!n)throw Error(`Expression '${t}' not in ExecutionContext.registry. The bundle's ExpressionRegistry must include this expression's category. Use createExpressionRegistry() with the relevant category objects (referencesExpressions, logicalExpressions, conversionExpressions, positionalExpressions, propertiesExpressions, specialExpressions, mathematicalExpressions).`);return n}function Gn(e){if(e&&"object"==typeof e&&"success"in e){if(e.success)return"value"in e?e.value:void 0;const t=e.errors||[];throw Error(t.length>0?t[0].message:"Expression evaluation failed")}return e}async function Xn(e,t){if(!e)throw Error("Cannot evaluate null or undefined AST node");if("literal"===e.type)return e.value;if("identifier"===e.type)return sr(e,t);const n=e;switch(e.type){case"literal":return function(e){return e.value}(n);case"identifier":return sr(n,t);case"binaryExpression":return async function(e,t){const n=e.operator,r=e.right,s=e.left;if("="===n){const n=await Xn(e.right,t);if("identifier"===s?.type&&"string"==typeof s.name){const e=s.name;return e.startsWith("$")?Fe(t,e.slice(1),n):"global"===s.scope?Fe(t,e,n):(t.locals||(t.locals=new Map),t.locals.set(e,n)),n}throw Error(`Assignment target must be a variable identifier (got '${s?.type??"undefined"}')`)}if("has"===n||"have"===n){const n=await Xn(e.left,t);return!!(n instanceof Element&&"selector"===r.type&&"string"==typeof r.value&&r.value.startsWith("."))&&n.classList.contains(r.value.slice(1))}if("in"===n||"is in"===n){const n="callExpression"===s?.type&&"identifier"===s.callee?.type?s.callee.name:null;if(("first"===n||"last"===n)&&Array.isArray(s.arguments)){const r=s.arguments[0];if("selector"===r?.type&&"string"==typeof r.value){const s=await Xn(e.right,t);if(s&&"function"==typeof s.querySelectorAll){const e=Array.from(s.querySelectorAll(r.value));return 0===e.length?null:"first"===n?e[0]:e[e.length-1]}}}if("selector"===s?.type&&s.fromQuery&&"string"==typeof s.value){const n=await Xn(e.right,t),r=n&&"function"==typeof n.querySelectorAll?n:null;if(r)return Array.from(r.querySelectorAll(s.value))}}if("of"===n&&"selector"===s?.type&&"string"==typeof s.value&&/^\*[a-zA-Z][\w-]*$/.test(s.value)){const n=await Xn(e.right,t);return Kn(t,"styleRef").evaluate(t,s.value.slice(1),n)}if("of"===n){const n=ir(e.left);if(n){const r=await Xn(e.right,t);let s=r;for(const e of n){if(null==s)return;s=nn(s)?cn(s,e):s[e]}return"function"==typeof s?s.bind(r):s}}const i=await Xn(e.left,t);if("and"===n){if(!i)return i;const n=await Xn(e.right,t);return Kn(t,"and").evaluate(t,i,n)}if("or"===n){if(i)return i;const n=await Xn(e.right,t);return Kn(t,"or").evaluate(t,i,n)}const o=await Xn(e.right,t),a=e=>"string"==typeof e?e.toLowerCase():e,c=e.ignoringCase?a(i):i,l=e.ignoringCase?a(o):o;switch(n){case"+":return"string"==typeof i||"string"==typeof o?(i??"")+""+(o??""):Array.isArray(i)?Array.isArray(o)?[...i,...o]:[...i,o]:Gn(await Kn(t,"addition").evaluate(t,{left:i,right:o}));case"-":return Gn(await Kn(t,"subtraction").evaluate(t,{left:i,right:o}));case"*":return Gn(await Kn(t,"multiplication").evaluate(t,{left:i,right:o}));case"/":return Gn(await Kn(t,"division").evaluate(t,{left:i,right:o}));case"%":case"mod":return Gn(await Kn(t,"modulo").evaluate(t,{left:i,right:o}));case"^":case"**":return Gn(await Kn(t,"power").evaluate(t,{left:i,right:o}));case">":case"is greater than":return Kn(t,"greaterThan").evaluate(t,i,o);case"<":case"is less than":return Kn(t,"lessThan").evaluate(t,i,o);case">=":case"is greater than or equal to":return Kn(t,"greaterThanOrEqual").evaluate(t,i,o);case"<=":case"is less than or equal to":return Kn(t,"lessThanOrEqual").evaluate(t,i,o);case"==":return Kn(t,"equals").evaluate(t,c,l);case"is":case"am":case"equals":case"is equal":case"is equal to":{const n=cr(e,i,o);return void 0!==n?n:Kn(t,"equals").evaluate(t,c,l)}case"!=":return Kn(t,"notEquals").evaluate(t,c,l);case"is not":case"is not equal":case"is not equal to":{const n=cr(e,i,o);return void 0!==n?!n:Kn(t,"notEquals").evaluate(t,c,l)}case"===":case"really equals":case"is really":case"is really equal to":return Kn(t,"strictEquals").evaluate(t,c,l);case"!==":case"is not really":case"is not really equal to":return Kn(t,"strictNotEquals").evaluate(t,c,l);case"as":return Kn(t,"as").evaluate(t,i,ur(o));case"contains":case"contain":case"includes":case"include":return Kn(t,"contains").evaluate(t,c,l);case"does not contain":case"do not contain":case"does not contains":case"does not include":return Kn(t,"doesNotContain").evaluate(t,c,l);case"starts with":return Kn(t,"startsWith").evaluate(t,c,l);case"ends with":return Kn(t,"endsWith").evaluate(t,c,l);case"does not start with":return!await Kn(t,"startsWith").evaluate(t,c,l);case"does not end with":return!await Kn(t,"endsWith").evaluate(t,c,l);case"match":case"matches":return Kn(t,"matches").evaluate(t,c,ar(e.right,l));case"does not match":case"do not match":return!await Kn(t,"matches").evaluate(t,c,ar(e.right,l));case"in":case"is in":case"am in":return or(i,o);case"is not in":case"am not in":return!or(i,o);case"of":return o&&"object"==typeof o?o[i]:void 0;case"precedes":return lr(i,o,Node.DOCUMENT_POSITION_FOLLOWING);case"does not precede":return!lr(i,o,Node.DOCUMENT_POSITION_FOLLOWING);case"follows":return lr(i,o,Node.DOCUMENT_POSITION_PRECEDING);case"does not follow":return!lr(i,o,Node.DOCUMENT_POSITION_PRECEDING);default:throw Error("Unknown binary operator: "+n)}}(n,t);case"asExpression":return async function(e,t){const n=await Xn(e.expression,t),r=ur(e.targetType);return Kn(t,"as").evaluate(t,n,r)}(n,t);case"betweenExpression":return async function(e,t){const n=await Xn(e.value,t),r=await Xn(e.min,t),s=await Xn(e.max,t),i=e=>"string"==typeof e?e.toLowerCase():e,[o,a,c]=e.ignoringCase?[i(n),i(r),i(s)]:[n,r,s],l=await Kn(t,"between").evaluate(t,o,a,c);return e.negated?!l:l}(n,t);case"typeCheckExpression":return async function(e,t){const n=function(e,t,n){if(null==e&&n)return!0;if(Object.prototype.toString.call(e).slice(8,-1)===t)return!0;const r=globalThis[t];return"function"==typeof r&&e instanceof r}(await Xn(e.value,t),e.typeName+"",!1!==e.nullOk);return e.negated?!n:n}(n,t);case"collectionExpression":return async function(e,t){const n=await Xn(e.collection,t);if(null==n)return n;const r=async(e,n)=>Xn(e,{...t,it:n});switch(e.operator){case"where":return async function(e,t,n){const r=Zn(e),s=[];for(const e of r)await n(t,e)&&s.push(e);return s}(n,e.right,r);case"sorted by":return async function(e,t,n,r){const s=[...Zn(e)],i=await Promise.all(s.map(e=>r(t,e))),o=s.map((e,t)=>t);o.sort((e,t)=>{const n=i[e],r=i[t];return n===r?0:null==n?1:null==r||r>n?-1:1});const a=o.map(e=>s[e]);return"desc"===n?a.reverse():a}(n,e.right,e.order??"asc",r);case"mapped to":return async function(e,t,n){const r=Zn(e);return Promise.all(r.map(e=>n(t,e)))}(n,e.right,r);case"split by":return i=await Xn(e.right,t),null==(s=n)?[]:(s+"").split(null==i?"":i+"");case"joined by":return function(e,t){const n=null==t?"":t+"";return Zn(e).map(e=>null==e?"":e+"").join(n)}(n,await Xn(e.right,t));default:throw Error("Unknown collection operator: "+e.operator)}var s,i}(n,t);case"unaryExpression":return async function(e,t){const n=e.operand??e.argument;if(!n)throw Error(`Unary expression has no operand (operator: ${e.operator})`);const r=await Xn(n,t);switch(e.operator){case"not":case"!":return Kn(t,"not").evaluate(t,r);case"no":return Kn(t,"no").evaluate(t,r);case"-":return-r;case"+":return+r;case"exists":case"some":return Kn(t,"exists").evaluate(t,r);case"does not exist":return Kn(t,"doesNotExist").evaluate(t,r);case"is empty":return Kn(t,"isEmpty").evaluate(t,r);case"is not empty":return Kn(t,"isNotEmpty").evaluate(t,r);default:throw Error("Unknown unary operator: "+e.operator)}}(n,t);case"memberExpression":return async function(e,t){const n=await Xn(e.object,t);if(e.computed){const r=await Xn(e.property,t);return Array.isArray(n)&&"number"==typeof r&&0>r?n[n.length+r]:n?.[r]}return pr(n,e.property.name,t)}(n,t);case"propertyAccess":return async function(e,t){let n=await Xn(e.object,t);for(const r of(e.property+"").split(".")){if(null==n)return;n=await pr(n,r,t)}return n}(n,t);case"callExpression":return async function(e,t){const n=await Xn(e.callee,t);if(e.isConstructor&&"function"==typeof n)return new n(...await Promise.all(e.arguments.map(e=>Xn(e,t))));if("identifier"===e.callee.type){const r=e.callee.name,s=await async function(e,t,n){return mr.has(t)?Promise.all(e.map(e=>"identifier"===e.type&&e.name?e.name:"selector"===e.type&&e.value?e.value:Xn(e,n))):Promise.all(e.map(e=>Xn(e,n)))}(e.arguments,r,t);switch(r){case"closest":return Kn(t,"closest").evaluate(t,...s);case"previous":case"next":{const n=e.relativePositional;if(n){const e=n.from?yr(await Xn(n.from,t)):t.me,i=n.within?yr(await Xn(n.within,t)):void 0,o=n.inElt?await Xn(n.inElt,t):void 0;return Kn(t,r).evaluate(t,s[0],e,{within:i,inElt:o,inSearch:n.inSearch,wrapping:n.wrapping})}return Kn(t,r).evaluate(t,...s)}case"first":return Kn(t,"first").evaluate(t,...s);case"last":return Kn(t,"last").evaluate(t,...s);default:if("function"==typeof n)return n(...s);throw Error("Cannot call non-function: "+r)}}if("function"==typeof n){const r=await Promise.all(e.arguments.map(e=>Xn(e,t)));if("memberExpression"===e.callee.type&&e.callee.object){const s=await Xn(e.callee.object,t);return n.apply(s,r)}return n(...r)}throw Error("Cannot call non-function")}(n,t);case"selector":return async function(e,t){let n=e.value;if("string"==typeof n&&!e.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(n))return Kn(t,"styleRef").evaluate(t,n.slice(1));if("string"==typeof n&&e.fromQuery&&/\$[^=]/.test(n)){const{selector:r,elements:s}=await async function(e,t){const n=Er(e),r=await Promise.all(n.filter(e=>"expr"in e).map(e=>tr(e.expr,t)));return xr(n,r)}(n,t),i=br(e,r);s.forEach((e,t)=>e.setAttribute("data-hs-query-id",t+""));try{return await Kn(t,"elementWithSelector").evaluate(t,i)}finally{s.forEach(e=>e.removeAttribute("data-hs-query-id"))}}"string"==typeof n&&!e.fromQuery&&n.includes("{")&&(n=await function(e,t){return dr(e,/\{([^}]*)\}/g,async(e,n)=>(await tr(n.trim(),t)??"")+"")}(n,t));const r="string"==typeof n?br(e,n):n,s=await Kn(t,"elementWithSelector").evaluate(t,r);return!e.fromQuery&&"string"==typeof n&&n.startsWith("#")&&Array.isArray(s)?s[0]??null:s}(n,t);case"contextReference":return async function(e,t){switch(e.contextType){case"me":case"you":case"it":return Kn(t,e.contextType).evaluate(t);case"my":case"myself":case"I":return Kn(t,"me").evaluate(t);case"your":case"yourself":return Kn(t,"you").evaluate(t);case"its":return Kn(t,"it").evaluate(t);case"event":return t.event;case"target":return t.target??t.event?.target??Kn(t,"me").evaluate(t);case"body":return"undefined"!=typeof document?document.body:void 0;case"document":return Kn(t,"document").evaluate(t);case"window":return Kn(t,"window").evaluate(t);default:return}}(n,t);case"possessiveExpression":return async function(e,t){const n=await Xn(e.object,t),r=e.property.name;return Kn(t,"possessive").evaluate(t,n,r)}(n,t);case"eventHandler":return async function(e,t){return{event:e.event,selector:e.selector,commands:e.commands,handler:async n=>{const r={...t,event:n,target:n.target,currentTarget:n.currentTarget};for(const t of e.commands)await Xn(t,r)}}}(n,t);case"conditionalExpression":return async function(e,t){return await Xn(e.test,t)?Xn(e.consequent,t):e.alternate?Xn(e.alternate,t):void 0}(n,t);case"string":return n.value;case"arrayLiteral":return async function(e,t){const n=[];for(const r of e.elements)n.push(await Xn(r,t));return n}(n,t);case"objectLiteral":return async function(e,t){const n={};for(const r of e.properties){const e=r.key;let s;s="identifier"===e.type?e.name:"literal"===e.type&&"string"===e.valueType?e.value:await Xn(e,t)+"",n[s]=await Xn(r.value,t)}return n}(n,t);case"attributeAccess":return async function(e,t){const n=e.attributeName;return t.me&&t.me instanceof Element?t.me.getAttribute(n):"@"+n}(n,t);case"propertyOfExpression":return async function(e,t){const n=e.property;if("identifier"!==n?.type)throw Error('Property name must be an identifier in "the X of Y" pattern');const r=n.name,s=await Xn(e.target,t);if(null==s)throw Error(`Cannot access property "${r}" of ${s}`);return Kn(t,"possessive").evaluate(t,s,r)}(n,t);case"templateLiteral":return async function(e,t){let n=e.value;return n=await dr(n,/\$([a-zA-Z_$][a-zA-Z0-9_.$]*|\d+)/g,async(e,n)=>{try{if(/^\d+$/.test(n))return n;if(n.includes(".")){const e=n.split(".");let r=hr(e[0],t);for(let t=1;e.length>t&&null!=r;t++)r=r[e[t]];return(r??"")+""}return(hr(n,t)??"")+""}catch{return""}}),n=await dr(n,/\$(?:\{([^}]+)\}|\(([^)]+)\))/g,async(e,n,r)=>{const s=n||r;try{return await tr(s,t)+""}catch{return"undefined"}}),n}(n,t);case"stringPostfix":return async function(e,t){return`${await Xn(e.expression,t)}${e.unit}`}(n,t);case"blockLiteral":return fr(n,t);default:{const n=Te.get(e.type);if(n)return n(e,t);throw Error("Unknown AST node type: "+e.type)}}}class Yn extends Error{constructor(e){super(`Expression node "${e}" is not synchronously evaluable`),this.name="NotSyncEvaluable"}}function Qn(e,t){const n=e;switch(n?.type){case"literal":case"string":return n.value;case"selector":return function(e,t){const n=e.value;if("string"!=typeof n)throw new Yn("selector");if(!e.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(n))throw new Yn("selector");if(e.fromQuery&&/\$[^=]/.test(n)){const{selector:r,elements:s}=function(e,t){const n=Er(e),r=n.filter(e=>"expr"in e).map(e=>er(e.expr,t));return xr(n,r)}(n,t),i=br(e,r),o=t?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!o)throw new Yn("selector");s.forEach((e,t)=>e.setAttribute("data-hs-query-id",t+""));try{return Array.from(o.querySelectorAll(i))}finally{s.forEach(e=>e.removeAttribute("data-hs-query-id"))}}const r=!e.fromQuery&&n.includes("{")?function(e,t){return e.replace(/\{([^}]*)\}/g,(e,n)=>(er(n.trim(),t)??"")+"")}(n,t):n,s=br(e,r),i=t?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!i)throw new Yn("selector");const o=Array.from(i.querySelectorAll(s));return!e.fromQuery&&r.startsWith("#")?o[0]??null:o}(n,t);case"identifier":return function(e,t){return"me"===e||"my"===e||"I"===e?t.me:"you"===e||"your"===e||"yourself"===e?t.you:"it"===e||"its"===e?t.it??t.result:"window"===e?"undefined"!=typeof window?window:globalThis:"document"===e?"undefined"!=typeof document?document:void 0:t.locals?.has(e)?t.locals.get(e):t.globals?.has(e)?t.globals.get(e):e.startsWith("$")&&t.globals?.has(e.slice(1))?t.globals.get(e.slice(1)):void 0!==t[e]?t[e]:"undefined"!=typeof globalThis&&e in globalThis?globalThis[e]:void 0}(n.name,t);case"contextReference":return function(e,t){switch(e){case"me":return t.me;case"you":return t.you;case"it":return t.it??t.result;case"event":return t.event;case"target":return t.target??t.event?.target??t.me;default:throw new Yn("contextReference")}}(n.contextType,t);case"arrayLiteral":return n.elements.map(e=>Qn(e,t));case"objectLiteral":return function(e,t){const n={};for(const r of e.properties){const e=r.key;let s;s="identifier"===e.type?e.name:"literal"===e.type&&"string"===e.valueType?e.value:Qn(e,t)+"",n[s]=Qn(r.value,t)}return n}(n,t);case"asExpression":return _n(Qn(n.expression,t),ur(n.targetType),t);case"stringPostfix":return`${Qn(n.expression,t)}${n.unit}`;case"blockLiteral":return fr(n,t);case"memberExpression":{const e=Qn(n.object,t);if(null==e)return;if(e instanceof Element||Array.isArray(e)||"undefined"!=typeof Node&&e instanceof Node)throw new Yn("memberExpression");const r=e[n.computed?Qn(n.property,t)+"":n.property?.name];return"function"==typeof r?r.bind(e):r}default:throw new Yn(n?.type??"unknown")}}function er(e,t){const n=Ht(e);if(!n.success||!n.node){const e=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(e?.message??"unknown error"))}return Qn(n.node,t)}async function tr(e,t){const n=Ht(e);if(!n.success||!n.node){const e=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(e?.message??"unknown error"))}const r=t.registry?t:{...t,registry:await rr()};return Xn(n.node,r)}let nr=null;async function rr(){if(!nr){const e=await Promise.resolve().then(function(){return ra});nr=e.createFullExpressionRegistry()}return nr}async function sr(e,t){const n=e.name;return"me"===n||"my"===n||"I"===n?Kn(t,"me").evaluate(t):"you"===n||"your"===n||"yourself"===n?Kn(t,"you").evaluate(t):"it"===n||"its"===n?Kn(t,"it").evaluate(t):"window"===n?Kn(t,"window").evaluate(t):"document"===n?Kn(t,"document").evaluate(t):"global"===e.scope&&t.globals?.has(n)?(Me(n,t),t.globals.get(n)):t.locals&&t.locals.has(n)?(Pe(n,t),t.locals.get(n)):t.globals&&t.globals.has(n)?(n.startsWith("$")&&Me(n.slice(1),t),t.globals.get(n)):n.startsWith("$")&&t.globals&&t.globals.has(n.slice(1))?(Me(n.slice(1),t),t.globals.get(n.slice(1))):void 0!==t[n]?t[n]:"undefined"!=typeof globalThis&&n in globalThis?globalThis[n]:void 0}function ir(e){const t=e;if(!t)return null;if("identifier"===t.type&&"string"==typeof t.name)return[t.name];if("memberExpression"===t.type&&!t.computed){const e=ir(t.object);if(!e)return null;const n=t.property,r="identifier"===n?.type&&"string"==typeof n.name?n.name:"string"==typeof n?.value?n.value:null;return null==r?null:[...e,r]}return null}function or(e,t){return Array.isArray(t)?t.includes(e):"string"==typeof t?t.includes(e+""):e instanceof Node&&t instanceof Node?e===t||t.contains(e):null!=t&&"object"==typeof t&&e in t}function ar(e,t){return e&&"selector"===e.type&&"string"==typeof e.value?e.value:t}function cr(e,t,n){if(void 0!==n)return;const r=e.right;if(!r||"identifier"!==r.type||"string"!=typeof r.name)return;if(null==t||"object"!=typeof t)return;const s=t[r.name];return"boolean"==typeof s?!0===s:void 0}function lr(e,t,n){return e instanceof Node&&t instanceof Node&&0!==(e.compareDocumentPosition(t)&n)}function ur(e){if("string"==typeof e)return e;if(e&&"object"==typeof e){if("string"==typeof e.name)return e.name;if("string"==typeof e.value)return e.value}return e+""}function fr(e,t){const n=e.parameters??[];return(...r)=>{const s=new Map(t.locals??new Map);n.forEach((e,t)=>s.set(e,r[t]));const i={...t,locals:s};try{return Qn(e.body,i)}catch(t){if(t instanceof Yn)return Xn(e.body,i);throw t}}}function hr(e,t){return t.locals?.has(e)?(Pe(e,t),t.locals.get(e)):"me"===e&&t.me?t.me:"you"===e&&t.you?t.you:"it"===e&&t.it?t.it:"result"===e&&t.result?t.result:"undefined"!=typeof window&&"window"===e?window:t.globals?.has(e)?t.globals.get(e):void 0}async function dr(e,t,n){const r=[];let s;for(;null!==(s=t.exec(e));)r.push({index:s.index,length:s[0].length,replacement:await n(s[0],...s.slice(1))});let i=e;for(let e=r.length-1;e>=0;e--){const{index:t,length:n,replacement:s}=r[e];i=i.substring(0,t)+s+i.substring(t+n)}return i}function pr(e,t,n){if("string"==typeof t&&t.startsWith("@")){const n=t.substring(1);return e&&"function"==typeof e.getAttribute?e.getAttribute(n):void 0}return e instanceof Element&&"string"==typeof t?cn(e,t):Wn(e)&&!(t in e)?Kn(n,"possessive").evaluate(n,e,t):e?.[t]}const mr=new Set(["closest","previous","next"]);function yr(e){return e instanceof Element?e:Array.isArray(e)&&e[0]instanceof Element?e[0]:void 0}const gr=RegExp("(\\.[a-zA-Z0-9_-]+):(?!(hover|active|focus|visited|link|focus-within|focus-visible|first-child|last-child|only-child|nth-child|nth-last-child|nth-of-type|nth-last-of-type|first-of-type|last-of-type|only-of-type|empty|root|target|lang|dir|not|has|is|where|matches|before|after|first-letter|first-line|selection|placeholder|marker|backdrop|enabled|disabled|checked|indeterminate|required|optional|valid|invalid|in-range|out-of-range|read-only|read-write|default|defined|fullscreen|modal|picture-in-picture|autofill)(?![a-zA-Z0-9_-]))","g"),vr=/[:&()[\]/]/g;function br(e,t){return e.fromQuery||!t.startsWith(".")||t.includes("{")?function(e){return e.replace(gr,"$1\\:")}(t):function(e){return e[0]+e.slice(1).replace(vr,"\\$&")}(t)}const wr=/\$\{([^}]+)\}|\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g;function Er(e){const t=[];let n,r=0;for(wr.lastIndex=0;null!==(n=wr.exec(e));)n.index>r&&t.push({lit:e.slice(r,n.index)}),t.push({expr:n[1]??n[2]}),r=n.index+n[0].length;return e.length>r&&t.push({lit:e.slice(r)}),t}function xr(e,t){let n="";const r=[];let s=0;for(const i of e){if("lit"in i){n+=i.lit;continue}const e=t[s++];nn(e)?(n+=`[data-hs-query-id='${r.length}']`,r.push(e)):n+=(e??"")+""}return{selector:n,elements:r}}class kr{constructor(e){this.elementCleanups=new WeakMap,this.elementCount=0,this.typeCounts={listener:0,observer:0,interval:0,timeout:0,custom:0},this.globalCleanups=[],this.debugMode=e?.debug??!1}registerListener(e,t,n,r,s){this.addCleanup(e,{type:"listener",target:t,eventName:n,cleanup:()=>{t.removeEventListener(n,r,s),this.debugMode&&pe(`CleanupRegistry: Removed listener '${n}'`)},description:n+" listener"})}registerObserver(e,t){this.addCleanup(e,{type:"observer",cleanup:()=>{t.disconnect(),this.debugMode&&pe("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(e,t){this.addCleanup(e,{type:"interval",cleanup:()=>{clearInterval(t),this.debugMode&&pe("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(e,t){this.addCleanup(e,{type:"timeout",cleanup:()=>{clearTimeout(t),this.debugMode&&pe("CleanupRegistry: Cleared timeout")},description:"Timeout"})}registerCustom(e,t,n){this.addCleanup(e,{type:"custom",cleanup:t,description:n||"Custom cleanup"})}registerGlobal(e,t="custom",n){this.globalCleanups.push({type:t,cleanup:e,description:n||"Global cleanup"}),this.debugMode&&pe("CleanupRegistry: Registered global cleanup: "+(n||t))}addCleanup(e,t){const n=this.elementCleanups.get(e);n?n.push(t):(this.elementCleanups.set(e,[t]),this.elementCount++),this.typeCounts[t.type]++,this.debugMode&&pe(`CleanupRegistry: Registered ${t.type} for element`,e)}cleanupElement(e){const t=this.elementCleanups.get(e);if(!t||0===t.length)return 0;let n=0;for(const e of t){try{e.cleanup(),n++}catch(e){this.debugMode&&pe("CleanupRegistry: Error during cleanup:",e)}this.typeCounts[e.type]--}return this.elementCleanups.delete(e),this.elementCount--,this.debugMode&&pe(`CleanupRegistry: Cleaned up ${n} resources for element`),n}cleanupElementTree(e){let t=this.cleanupElement(e);const n=e.querySelectorAll("*");for(const e of n)t+=this.cleanupElement(e);return t}cleanupGlobal(){let e=0;for(const t of this.globalCleanups)try{t.cleanup(),e++}catch(e){this.debugMode&&pe("CleanupRegistry: Error during global cleanup:",e)}return this.globalCleanups=[],this.debugMode&&pe(`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,n=0,r=0,s=0;for(const i of this.globalCleanups)switch(i.type){case"listener":e++;break;case"observer":t++;break;case"interval":n++;break;case"timeout":r++;break;case"custom":s++}return{elementsTracked:this.elementCount,listeners:this.typeCounts.listener+e,observers:this.typeCounts.observer+t,intervals:this.typeCounts.interval+n,timeouts:this.typeCounts.timeout+r,custom:this.typeCounts.custom+s,global:this.globalCleanups.length}}setDebugMode(e){this.debugMode=e}}const Sr=new Map;function Ar(e,t){return{me:e??null,it:null,you:null,result:null,locals:new Map,globals:t||Sr,flags:{halted:!1,breaking:!1,continuing:!1,returning:!1,async:!1}}}class Nr{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(e,t){const n=e.toLowerCase();this.sources.has(n)&&pe("[EventSourceRegistry] Overwriting existing event source: "+e),this.sources.set(n,t)}unregister(e){const t=e.toLowerCase(),n=this.sources.get(t);if(n){for(const[e,n]of this.subscriptions.entries())n.source===t&&(n.unsubscribe(),this.subscriptions.delete(e));return n.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,n){const r=this.get(e);if(!r)return void pe("[EventSourceRegistry] Unknown event source: "+e);r.initialize?.();const s=r.subscribe(t,n);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,n]of this.sources.entries())if(n.supports?.(e)??n.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 Tr{constructor(){this.providers=new Map,this.globalProviders=new Map}register(e,t,n){const r=e.toLowerCase();this.providers.set(r,"function"==typeof t?{name:r,provide:t,cache:n?.cache??!0,description:n?.description,dependencies:n?.dependencies}:t)}registerGlobal(e,t,n){const r=e.toLowerCase();this.globalProviders.set(r,"function"==typeof t?{name:r,provide:t,cache:n?.cache??!0,description:n?.description,dependencies:n?.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,n){const r=this.get(e);if(!r)return;const s="__provider_"+r.name;if(r.cache&&n?.has(s))return n.get(s);if(r.dependencies)for(const e of r.dependencies)await this.resolve(e,t,n);const i=await r.provide(t);return r.cache&&n&&n.set(s,i),i}resolveSync(e,t,n){const r=this.get(e);if(!r)return;const s="__provider_"+r.name;if(r.cache&&n?.has(s))return n.get(s);const i=r.provide(t);if(i instanceof Promise)throw Error(`Context provider '${e}' is async. Use resolve() instead of resolveSync().`);return r.cache&&n&&n.set(s,i),i}enhance(e){const t=this,n=new Map;return new Proxy(e,{get(e,r,s){if("string"==typeof r&&t.get(r))try{return t.resolveSync(r,e,n)}catch{return t.resolve(r,e,n)}return Reflect.get(e,r,s)},has:(e,n)=>!("string"!=typeof n||!t.has(n))||Reflect.has(e,n)})}async resolveAll(e){const t=new Map,n={},r=[...this.globalProviders.entries(),...this.providers.entries()];for(const[s,i]of r)try{n[s]=await this.resolve(s,e,t)}catch(e){pe(`[ContextProviderRegistry] Failed to resolve '${s}':`,e),n[s]=void 0}return n}getProviderNames(){return[...new Set([...this.globalProviders.keys(),...this.providers.keys()])]}clear(){this.providers.clear(),this.globalProviders.clear()}}const Cr={evaluate:(e,t)=>Xn(e,t)};class Or{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||{},...void 0!==e.registry&&{registry:e.registry},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 Rr{constructor(e,t,n){this.impl=e,this.hookRegistry=n??null}setHookRegistry(e){this.hookRegistry=e}createHookContext(e,t,n={}){return{commandName:this.name,element:e.me instanceof Element?e.me:null,args:t,modifiers:n,event:e.event??void 0,executionContext:e}}get name(){const e=this.impl.name;if(e)return e;const t=this.impl.metadata?.name;return"string"==typeof t?t:""}get metadata(){const e=this.impl.metadata?.syntax;return{description:this.impl.metadata?.description||"",examples:this.impl.metadata?.examples||[],syntax:Array.isArray(e)?e.join(" | "):e||""}}async execute(e,...t){const n=t[0],r=this.createHookContext(e,t,n&&"object"==typeof n&&"modifiers"in n&&n.modifiers||{});try{if(fe(`CommandAdapterV2: Executing '${this.name}' with args:`,t),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(r),this.hookRegistry?.shouldIntercept(this.name,r))return void fe(`CommandAdapterV2: '${this.name}' intercepted by hook`);const s=Or.toTyped(e);let i,o;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(fe(`CommandAdapterV2: '${this.name}' has parseInput(), calling it`),n&&"object"==typeof n&&("args"in n||"modifiers"in n)){const t=n.modifiers,r=t?.when||t?.where;if(r&&!await Xn(r,e))return void fe(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);i=await this.impl.parseInput({args:n.args||[],modifiers:t||{},commandName:n.commandName},Cr,e)}else i=t;else fe(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),i=t;if(fe("CommandAdapterV2: Calling execute with parsed input:",i),2===this.impl.execute.length)o=await this.impl.execute(i,s);else{const e=Array.isArray(i)?i:[i];o=await this.impl.execute(s,...e)}return fe("CommandAdapterV2: Command result:",o),Object.assign(e,Or.fromTyped(s,e)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(r,o),o}catch(e){if(Dr(e)||fe(`CommandAdapterV2: Error executing '${this.name}':`,e),this.hookRegistry&&e instanceof Error)throw await this.hookRegistry.runOnError(r,e);throw e}}validate(e){return this.impl.validate?this.impl.validate(e):{isValid:!0,errors:[],suggestions:[]}}}class $r{constructor(e,t){this.adapters=new Map,this.implementations=new Map,this.hookRegistry=t}setHookRegistry(e){this.hookRegistry=e;for(const t of this.adapters.values())t.setHookRegistry(e);pe(`CommandRegistryV2: Hook registry set and propagated to ${this.adapters.size} adapters`)}getHookRegistry(){return this.hookRegistry}register(e){const t=e.name||e.metadata?.name;if(!t||"string"!=typeof t)throw Error("Cannot register command: no name found. Provide a 'name' property or 'metadata.name' on the implementation.");const n=t.toLowerCase();pe(`CommandRegistryV2: Registering command '${n}'`),this.implementations.set(n,e);const r=new Rr(e,void 0,this.hookRegistry);this.adapters.set(n,r),E.add(n);const s=e.metadata?.aliases;if(s&&Array.isArray(s))for(const t of s){const n=t.toLowerCase();this.implementations.set(n,e),this.adapters.set(n,r),E.add(n)}}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 n=this.getAdapter(e);return n?n.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 Lr=null;function jr(){return Lr||(Lr=function(e){const t=e?.commands??new $r,n=e?.eventSources??new Nr,r=e?.context??new Tr,s=new Set,i={commands:t,eventSources:n,context:r,use(e){if(s.has(e.name))pe(`[LokaScriptRegistry] Plugin '${e.name}' is already installed`);else{if(e.commands)for(const n of e.commands)t.register(n);if(e.eventSources)for(const t of e.eventSources)n.register(t.name,t);if(e.contextProviders)for(const{name:t,provide:n,options:s}of e.contextProviders)r.register(t,n,s);e.setup?.(i),s.add(e.name)}},reset(){s.clear()}};return i}()),Lr}class Ir{constructor(e={}){this.contextCache=new WeakMap;const t=jr();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,pe(`[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),pe(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),t}catch(t){return pe("[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 pe(`[RegistryIntegration] Found event source for '${e}'`),t;const n=this.eventSourceRegistry.findSourceForEvent(e);if(n){const t=this.eventSourceRegistry.get(n);return pe(`[RegistryIntegration] Found event source '${n}' supporting '${e}'`),t}}hasEventSource(e){return void 0!==this.getEventSource(e)}subscribeToEventSource(e,t,n){if(!this.options.enableEventSources)throw Error("Event sources are disabled in this runtime");const r=this.eventSourceRegistry.subscribe(e,t,n);if(!r)throw Error(`Failed to subscribe to event source '${e}'`);return pe(`[RegistryIntegration] Subscribed to '${e}' event '${t.event}' (id: ${r.id})`),r}getEventSourceNames(){return this.eventSourceRegistry.getSourceNames()}getContextProviderNames(){return this.contextRegistry.getProviderNames()}destroy(){this.eventSourceRegistry.destroy(),this.contextCache=new WeakMap,pe("[RegistryIntegration] Destroyed")}}function Mr(e){const t=Error(e.type.toUpperCase()+"_EXECUTION");return t["is"+e.type.charAt(0).toUpperCase()+e.type.slice(1)]=!0,"returnValue"in e&&(t.returnValue=e.returnValue),t}function Dr(e){return e instanceof Error&&(null!==zt(e)||"HALT_EXECUTION"===e.message||"EXIT_COMMAND"===e.message||"EXIT_EXECUTION"===e.message)}function Pr(e){if(void 0===e)return;let t=e;if(t&&"object"==typeof t){const e=t;if("result"in e&&"wasAsync"in e)t=e.result;else if("result"in e&&"executed"in e){if(t=e.result,e.preserveArrayResult)return void 0!==t?t:void 0}else if("lastResult"in e&&"type"in e)t=e.lastResult;else if("conditionResult"in e&&"executedBranch"in e){if(void 0===e.result)return;t=e.result}else"value"in e&&1===Object.keys(e).length||"value"in e&&"target"in e&&"targetType"in e?t=e.value:"data"in e&&"status"in e&&"headers"in e&&(t=e.data)}return Array.isArray(t)&&t.length>0&&(t=t[0]),t}function Fr(e){return null!==e&&"object"==typeof e&&"command"in e&&"selector"in e}const Br=new WeakMap;class qr{constructor(e){this.autoCleanupObserver=null,this.registryIntegration=null,this.runtimeWarnings=[],this.options={commandTimeout:1e4,enableErrorReporting:!0,enableResultPattern:!0,enableAutoCleanup:!0,...e},this.registry=e.registry,this.expressionRegistry=e.expressionRegistry,this.behaviorRegistry=new Map,this.globalVariables=Sr,this.hookRegistry=new Ut,e.hooks&&this.hookRegistry.register("default",e.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new kr,this.options.enableAutoCleanup&&this.setupAutoCleanup(),!1!==e.registryIntegration&&(this.registryIntegration=new Ir("object"==typeof e.registryIntegration?e.registryIntegration:{}),pe("RuntimeBase: Registry integration enabled")),this.behaviorAPI={has:e=>this.behaviorRegistry.has(e),get:e=>this.behaviorRegistry.get(e),set:(e,t)=>this.behaviorRegistry.set(e,t),resolve:null,install:async(e,t,n)=>await this.installBehaviorOnElement(e,t,n)}}setupAutoCleanup(){"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.autoCleanupObserver=new MutationObserver(e=>{const t=[];for(const n of e)for(const e of n.removedNodes)e instanceof Element&&t.push(e);t.length>0&&queueMicrotask(()=>{for(const e of t)if(!e.isConnected){const t=this.cleanupRegistry.cleanupElementTree(e);t>0&&pe(`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)}trackListener(e,t,n,r,s){this.cleanupRegistry.registerListener(e,t,n,r,s)}cleanupTree(e){return this.cleanupRegistry.cleanupElementTree(e)}getCleanupStats(){return this.cleanupRegistry.getStats()}getCleanupRegistry(){return this.cleanupRegistry}logError(...e){this.options.enableErrorReporting&&console.error(...e)}logWarn(...e){this.options.enableErrorReporting&&console.warn(...e)}destroy(){this.autoCleanupObserver&&(this.autoCleanupObserver.disconnect(),this.autoCleanupObserver=null),this.cleanupRegistry.cleanupAll(),this.hookRegistry.clear(),this.behaviorRegistry.clear(),pe("RuntimeBase: Destroyed")}hasErrorDiagnostics(e){const t=e.diagnostics;return!!t?.some(e=>"error"===e.severity)}getWarnings(){return this.runtimeWarnings}async execute(e,t){pe(`RUNTIME BASE: execute() called with node type: '${e.type}'`),t.registry||(t.registry=this.expressionRegistry),t.locals.has("_behaviors")||t.locals.set("_behaviors",this.behaviorAPI),t.locals.has("_runtimeExecute")||t.locals.set("_runtimeExecute",(e,n)=>this.execute(e,n||t));try{if(this.hasErrorDiagnostics(e)){const t=e.diagnostics?.[0];return pe("⚠️ RUNTIME: Skipping error node: "+(t?.message||"unknown error")),void this.runtimeWarnings.push(t?.message||"Skipped error node")}switch(e.type){case"command":if(this.options.enableResultPattern){const n=await this.processCommandWithResult(e,t);if(!Zt(n)){if("return"===n.error.type){const e=n.error.returnValue;return void 0!==e&&Object.assign(t,{it:e,result:e}),e}throw Mr(n.error)}return n.value}try{return await this.processCommand(e,t)}catch(e){const n=zt(e);if(n?.isReturn){const e=n.returnValue;return void 0!==e&&Object.assign(t,{it:e,result:e}),e}throw e}case"eventHandler":return await this.executeEventHandler(e,t);case"event":{const n={type:"eventHandler",event:e.event,events:[e.event],commands:e.body||[],target:e.filter,modifiers:e.modifiers||{}};return await this.executeEventHandler(n,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 n=e,r=await this.executeCommandSequenceWithResult(n.commands||[],t);if(!Zt(r))throw Mr(r.error);return r.value}return await this.executeCommandSequence(e,t);case"objectLiteral":return await this.executeObjectLiteral(e,t);default:if(this.options.enableResultPattern){const n=await this.evaluateExpressionWithResult(e,t);if(!Zt(n))throw Mr(n.error);return n.value}return await this.evaluateExpression(e,t)}}catch(e){throw e}}async processCommand(e,t){const{name:n,args:r,modifiers:s}=e,i=n.toLowerCase();if(fe(`RUNTIME BASE: Processing command '${i}'`),this.registry.has(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:r||[],modifiers:s||{},commandName:i,runtime:this})}catch(e){throw Dr(e)||this.logError(`Error executing command '${i}':`,e),e}}const o=`Unknown command: ${n}. Ensure it is registered in the Runtime options.`;throw this.logWarn(o),Error(o)}toSignal(e){const t=zt(e);if(t){if(t.isHalt||"HALT_EXECUTION"===t.message)return{type:"halt"};if(t.isExit||"EXIT_COMMAND"===t.message)return{type:"exit",returnValue:t.returnValue};if(t.isBreak)return{type:"break"};if(t.isContinue)return{type:"continue"};if(t.isReturn)return{type:"return",returnValue:t.returnValue}}if(e instanceof Error){if("HALT_EXECUTION"===e.message)return{type:"halt"};if("EXIT_COMMAND"===e.message)return{type:"exit"}}return null}async processCommandWithResult(e,t){const{name:n,args:r,modifiers:s}=e,i=n.toLowerCase();if(fe(`RUNTIME BASE (Result): Processing command '${i}'`),!this.registry.has(i)){const e=`Unknown command: ${n}. Ensure it is registered in the Runtime options.`;throw this.logWarn(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 Wt(await o.execute(t,{args:r||[],modifiers:s||{},commandName:i,runtime:this}))}catch(e){const t=this.toSignal(e);if(t)return Jt(t);throw this.logError(`Error executing command '${i}':`,e),e}}async executeCommandSequenceWithResult(e,t){let n;for(const r of e){if(this.hasErrorDiagnostics(r)){const e=r.diagnostics?.[0];pe("⚠️ RUNTIME: Skipping error node: "+(e?.message||"unknown error")),this.runtimeWarnings.push(e?.message||"Skipped error node");continue}if("command"===r.type){const e=await this.processCommandWithResult(r,t);if(!Zt(e)){const n=e.error;switch(n.type){case"halt":case"exit":case"break":case"continue":return e;case"return":return void 0!==n.returnValue&&Object.assign(t,{it:n.returnValue,result:n.returnValue}),Wt(n.returnValue)}}n=e.value}else{const e=await this.evaluateExpressionWithResult(r,t);if(!Zt(e))return e;n=e.value}}return Wt(n)}async evaluateExpression(e,t){const n=t.registry?t:{...t,registry:this.expressionRegistry},r=await Xn(e,n);return Fr(r)?await this.executeCommandFromPattern(r.command,r.selector,t):r}async evaluateExpressionWithResult(e,t){const n=t.registry?t:{...t,registry:this.expressionRegistry},r=await async function(e,t){try{return Wt(await Xn(e,t))}catch(e){if(e instanceof Error){const t=e;if(t.isHalt||"HALT_EXECUTION"===t.message)return Jt({type:"halt"});if(t.isExit||"EXIT_COMMAND"===t.message)return Jt({type:"exit",returnValue:t.returnValue});if(t.isBreak)return Jt({type:"break"});if(t.isContinue)return Jt({type:"continue"});if(t.isReturn)return Jt({type:"return",returnValue:t.returnValue})}throw e}}(e,n);if(!Zt(r))return r;const s=r.value;if(Fr(s)){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:s.command,args:[{type:"literal",value:s.selector}]},t);try{return Wt(await this.executeCommandFromPattern(s.command,s.selector,t))}catch(e){const t=this.toSignal(e);if(t)return Jt(t);throw e}}return Wt(s)}async executeCommandFromPattern(e,t,n){return this.processCommand({type:"command",name:e,args:[{type:"literal",value:t}]},n)}async executeProgram(e,t){if(!e.statements||!Array.isArray(e.statements))return;let n;const r=[],s=[],i=[];for(const t of e.statements)"eventHandler"===t.type?r.push(t):"initBlock"===t.type?s.push(t):i.push(t);for(const e of r)try{await this.execute(e,t)}catch(e){if(Dr(e)&&(e.isHalt||e.isExit))break;throw e}for(const e of s)try{n=await this.execute(e,t)}catch(e){if(Dr(e)&&(e.isHalt||e.isExit))break;throw e}for(const e of i)try{n=await this.execute(e,t)}catch(e){if(Dr(e)&&(e.isHalt||e.isExit))break;throw e}return n}async executeBlock(e,t){if(e.commands&&Array.isArray(e.commands))for(const n of e.commands)try{await this.execute(n,t)}catch(e){if(Dr(e)&&e.isHalt)break;throw e}}async executeCommandSequence(e,t){if(!e.commands||!Array.isArray(e.commands))return;let n;for(const r of e.commands)try{n=await this.execute(r,t)}catch(e){if(Dr(e)){if(e.isHalt||e.isExit)break;if(e.isReturn){if(void 0!==e.returnValue)return Object.assign(t,{it:e.returnValue,result:e.returnValue}),e.returnValue;break}if(e.isBreak)throw e}throw e}return n}async executeObjectLiteral(e,t){const n={};if(!e.properties)return n;for(const r of e.properties){let e;e="identifier"===r.key.type?r.key.name:"literal"===r.key.type?r.key.value+"":await this.execute(r.key,t)+"";const s=await this.execute(r.value,t);n[e]=s}return n}enhanceContext(e){return this.registryIntegration?this.registryIntegration.enhanceContext(e):e}async executeBehaviorDefinition(e,t){const{name:n,parameters:r=[],eventHandlers:s=[],initBlock:i}=e,o=e.imperativeInstaller;"function"==typeof o?(this.behaviorRegistry.set(n,{name:n,parameters:r,type:"imperative",install:o}),pe(`RUNTIME BASE: Registered imperative behavior '${n}'`)):(this.behaviorRegistry.set(n,{name:n,parameters:r,eventHandlers:s,initBlock:i}),pe(`RUNTIME BASE: Registered behavior '${n}'`))}async installBehaviorOnElement(e,t,n){pe("BEHAVIOR: installBehaviorOnElement called: "+e);let r=this.behaviorRegistry.get(e);if(!r&&(this.behaviorAPI.resolve&&this.behaviorAPI.resolve(e)&&(r=this.behaviorRegistry.get(e)),!r))throw Error(`Behavior "${e}" not found`);if("imperative"===r.type)return void("function"==typeof r.install&&(pe(`BEHAVIOR: Installing imperative behavior '${e}'`),r.install(t,n),pe(`BEHAVIOR: Finished installing imperative behavior '${e}'`)));pe("BEHAVIOR: Found behavior, eventHandlers count: "+(r.eventHandlers?.length||0));const s={me:t,you:null,it:null,result:null,locals:new Map,globals:this.globalVariables,registry:this.expressionRegistry,halted:!1,returned:!1,broke:!1,continued:!1,async:!1},i=this.enhanceContext(s);if(r.parameters)for(const e of r.parameters)i.locals.set(e,e in n?n[e]:void 0);for(const[e,t]of Object.entries(n))r.parameters?.includes(e)||i.locals.set(e,t);if(r.initBlock){pe("BEHAVIOR: Running init block for "+e);const t=this.options.commandTimeout??1e4;try{await Promise.race([this.execute(r.initBlock,i),new Promise((n,r)=>setTimeout(()=>r(Error(`Behavior "${e}" init block timed out after ${t}ms`)),t))]),pe("BEHAVIOR: Init block completed for "+e)}catch(t){if(pe(`BEHAVIOR: Init block error for ${e}:`,t),!(t instanceof Error&&Dr(t)))throw t}}if(pe(`BEHAVIOR: About to attach ${r.eventHandlers?.length||0} handlers for ${e}`),r.eventHandlers){const t=this.options.commandTimeout??1e4;for(const n of r.eventHandlers)await Promise.race([this.executeEventHandler(n,i),new Promise((n,r)=>setTimeout(()=>r(Error(`Behavior "${e}" handler attachment timed out after ${t}ms`)),t))])}pe("BEHAVIOR: Finished installing "+e)}async executeEventHandler(e,t){const{event:n,events:r,commands:s,target:i,args:o,selector:a,attributeName:c,watchTarget:l,modifiers:u}=e,f=r&&r.length>0?r:[n];pe(`BEHAVIOR: executeEventHandler: event='${n}', target='${i}'`);let h=[],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)h=t.me?[t.me]:[];else if("string"==typeof i&&t.locals.has(i)){const e=t.locals.get(i);pe(`BEHAVIOR: Target resolution: found local '${i}', isElement: ${this.isElement(e)}`),this.isElement(e)?h=[e]:Array.isArray(e)?h=e.filter(e=>this.isElement(e)):"string"==typeof e&&(h=this.queryElements(e,t))}else pe(`BEHAVIOR: Target resolution: querying for '${i}'`),h=this.queryElements(i,t)}else h=t.me?[t.me]:[];if(0===h.length&&!d)return void pe(`BEHAVIOR: executeEventHandler - No targets found for event '${n}', returning early`);if("mutation"===n&&c)return void this.setupMutationObserver(h,c,s,t);if("change"===n&&l)return void this.setupChangeObserver(l,s,t);const p=e.customEventSource;if(p&&this.registryIntegration){pe(`BEHAVIOR: executeEventHandler - Using custom event source '${p}' for event '${n}'`);const e=async e=>{const r=new Map(t.locals),i={...t,locals:r,it:e,event:e},o=this.enhanceContext(i);pe(`CUSTOM EVENT: Executing commands for event '${n}'`);try{await this.execute({type:"program",commands:s},o)}catch(e){this.logError(`[HyperFixi] Error executing commands for custom event '${n}':`,e)}};try{const r=this.registryIntegration.subscribeToEventSource(p,{event:n,handler:e,target:i,selector:a},t);pe(`BEHAVIOR: Subscribed to custom event source '${p}' (id: ${r.id})`),this.cleanupRegistry.registerGlobal(()=>r.unsubscribe(),"listener",`Custom event source '${p}' subscription ${r.id}`)}catch(e){this.logError(`[HyperFixi] Failed to subscribe to custom event source '${p}':`,e)}return}const m=qr.createEventHandler(this,s,t,a,o);let y,g=null;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 n;y=r=>{n&&clearTimeout(n),n=setTimeout(()=>e(r),t)},g=()=>{n&&(clearTimeout(n),n=void 0)}}else if(u.throttle){const t=u.throttle;let n=0;y=r=>{const s=Date.now();t>s-n||(n=s,e(r))}}else y=e}else y=m;const v=u?.once?{once:!0}:void 0;if(d){for(const e of f)d.addEventListener(e,y,v),h.length>0?this.cleanupRegistry.registerListener(h[0],d,e,y):this.cleanupRegistry.registerGlobal(()=>d.removeEventListener(e,y),"listener",`Global ${e} listener`);g&&(h.length>0?this.cleanupRegistry.registerCustom(h[0],g,"debounce-timeout"):this.cleanupRegistry.registerGlobal(g,"timeout","debounce-timeout"))}else for(const e of h){for(const t of f){if("resize"===t&&"undefined"!=typeof ResizeObserver){const t=new ResizeObserver(e=>{for(const n of e){const e=new CustomEvent("resize",{detail:n,bubbles:!1,cancelable:!1});if(e.synthetic=!0,y(e),v?.once){t.disconnect();break}}});t.observe(e),this.cleanupRegistry.registerCustom(e,()=>t.disconnect(),"resize-observer");continue}e.addEventListener(t,y,v),this.cleanupRegistry.registerListener(e,e,t,y)}g&&this.cleanupRegistry.registerCustom(e,g,"debounce-timeout")}}static createEventHandler(e,t,n,r,s){return async i=>{const o=Br.get(i)??0;if(o>=100)return;if(Br.set(i,o+1),r&&i.target instanceof Element)try{if(!i.target.matches(r)&&!i.target.closest(r))return}catch{pe(`Event delegation: invalid CSS selector '${r}', skipping filter`)}const a=new Map(n.locals),c={...n,locals:a,it:i,event:i};a.has("target")||c.locals.set("target",i.target);const l=e.enhanceContext(c);if(s&&s.length>0){const e=i,t=e.detail;for(const n of s)l.locals.set(n,e[n]??t?.[n]??null)}for(const n of t)try{const t=Pr(await e.execute(n,l));void 0!==t&&Object.assign(l,{it:t,result:t})}catch(t){if(Dr(t)){if(t.isHalt||t.isExit)break;if(t.isReturn){void 0!==t.returnValue&&Object.assign(l,{it:t.returnValue,result:t.returnValue});break}}throw e.logError("COMMAND FAILED:",t),t}}}setupMutationObserver(e,t,n,r){pe(`RUNTIME BASE: Setting up MutationObserver for attribute '${t}' on ${e.length} elements`);for(const s of e){const e=new MutationObserver(async e=>{for(const i of e)if("attributes"===i.type&&i.attributeName===t){he(`MUTATION DETECTED: attribute '${t}' changed on`,s);const e={...r,me:s,it:i,locals:new Map(r.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 n)try{await this.execute(e,c)}catch(e){if(Dr(e)){if(e.isHalt||e.isExit||e.isReturn)break}else this.logError("Error executing mutation handler command:",e)}}});e.observe(s,{attributes:!0,attributeOldValue:!0,attributeFilter:[t]}),this.cleanupRegistry.registerObserver(s,e),pe("RUNTIME BASE: MutationObserver attached to",s,`for attribute '${t}'`)}}async setupChangeObserver(e,t,n){pe("RUNTIME BASE: Setting up MutationObserver for content changes on watch target");const r=await this.execute(e,n);let s=[];this.isElement(r)?s=[r]:Array.isArray(r)&&(s=r.filter(e=>this.isElement(e))),pe(`RUNTIME BASE: Watching ${s.length} target elements for content changes`);for(const e of s){const r=new MutationObserver(async r=>{for(const s of r)if("childList"===s.type||"characterData"===s.type){he("CONTENT CHANGE DETECTED on",e,"mutation type:",s.type);const r={...n,me:n.me,it:s,locals:new Map(n.locals)};r.locals.set("target",e);const i=s.oldValue,o=e.textContent;null!==i&&r.locals.set("oldValue",i),r.locals.set("newValue",o);const a=this.enhanceContext(r);for(const e of t)try{await this.execute(e,a)}catch(e){if(Dr(e)){if(e.isHalt||e.isExit||e.isReturn)break}else this.logError("Error executing change handler command:",e)}}});r.observe(e,{childList:!0,characterData:!0,subtree:!0,characterDataOldValue:!0}),this.cleanupRegistry.registerObserver(e,r),pe("RUNTIME BASE: MutationObserver attached to",e,"for content changes")}}queryElements(e,t){const n=t.me,r=(n instanceof Element?n.ownerDocument:null)??("undefined"!=typeof document?document:null);if(!r)return[];let s=e;s.startsWith("<")&&s.endsWith("/>")&&(s=s.slice(1,-2).trim());try{return Array.from(r.querySelectorAll(s))}catch{return pe(`queryElements: invalid CSS selector '${s}'`),[]}}isElement(e){return"undefined"!=typeof HTMLElement&&e instanceof HTMLElement||!(!e||"object"!=typeof e)&&(!!e.style&&!!e.classList)}}function Vr(...e){const t=new Map;for(const n of e)for(const[e,r]of Object.entries(n))t.set(e,r);return t}const _r=An({selector:xn().min(1),single:Sn().optional().default(!1)});function Hr(e,t){if(t.startsWith("computed-")){const n=t.substring(9);return getComputedStyle(e).getPropertyValue(n)||""}const n=t.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());return e.style[n]}new class extends Rn{constructor(){super(...arguments),this.name="me",this.category="Reference",this.syntax="me",this.description="References the current element in the execution context",this.inputSchema=On(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=e.me,s=this.isElement(r)?r:null,i=this.success(s,"element");return this.trackPerformance(e,t,i,n),i}catch(r){const s=this.failure("MeExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "me"',"ME_EVALUATION_FAILED",["Ensure element context is properly set",'Check if "me" is available in current scope']);return this.trackPerformance(e,t,s,n),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 Rn{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=On(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=e.you,s=this.isElement(r)?r:null,i=this.success(s,"element");return this.trackPerformance(e,t,i,n),i}catch(r){const s=this.failure("YouExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "you"',"YOU_EVALUATION_FAILED",["Ensure target element is available in context",'Check if "you" is set by event or command']);return this.trackPerformance(e,t,s,n),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 Rn{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=On(),this.outputType="Any",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=e.it,s={success:!0,value:r,type:this.inferType(r)};return this.trackPerformance(e,t,s,n),s}catch(r){const s=this.failure("ItExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "it"',"IT_EVALUATION_FAILED",['Ensure "it" is set by previous operation',"Check if context variable is available"]);return this.trackPerformance(e,t,s,n),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 Rn{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=_r,this.outputType="ElementList",this.metadata={category:"Reference",complexity:"medium"}}async evaluate(e,t){const n=Date.now();try{if(!this.isValidCSSSelector(t.selector)){const r=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,r,n),r}let r;if(t.single)r=document.querySelector(t.selector);else{const e=Array.from(document.querySelectorAll(t.selector));r=e.length>0?e:null}const s={success:!0,value:r,type:Array.isArray(r)?"element-list":"element"};return this.trackPerformance(e,t,s,n),s}catch(r){const s=this.failure("CSSSelectorError","runtime-error",r instanceof Error?r.message:"CSS selector evaluation failed","CSS_SELECTOR_EVALUATION_FAILED",["Check if selector is valid CSS","Ensure DOM is ready when query executes","Verify elements exist in document"]);return this.trackPerformance(e,t,s,n),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:n}=t.data;return this.isValidCSSSelector(n)?this.validationSuccess():this.validationFailure("syntax-error",`Invalid CSS selector syntax: "${n}"`,["Use .class for class selectors","Use #id for ID selectors","Use tag for element selectors","Use [attr] for attribute selectors"])}catch(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 Ur={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me??null,validate:pn},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.you??null,validate:pn},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:pn},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:pn},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.result,validate:pn},querySelector:{name:"querySelector",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){const[n]=t;if("string"!=typeof n)throw Error("querySelector requires a string selector");return document.querySelector(n)},validate:e=>hn(e,"querySelector","selector")},querySelectorAll:{name:"querySelectorAll",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const n=t[0];if("string"!=typeof n)throw Error("querySelectorAll requires a string selector");const r=document.querySelectorAll(n);return Array.from(r)},validate:e=>hn(e,"querySelectorAll","selector")},getElementById:{name:"getElementById",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){const n=t[0];if("string"!=typeof n)throw Error("getElementById requires a string ID");return document.getElementById(n)},validate:e=>hn(e,"getElementById","ID")},getElementsByClassName:{name:"getElementsByClassName",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const n=t[0];if("string"!=typeof n)throw Error("getElementsByClassName requires a string class name");const r=document.getElementsByClassName(n);return Array.from(r)},validate:e=>hn(e,"getElementsByClassName","className")},closest:{name:"closest",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){let n=t[0];if(n&&"object"==typeof n&&"type"in n){const e=n;"identifier"===e.type&&e.name?n=e.name:"literal"===e.type&&"string"==typeof e.value&&(n=e.value)}if("string"!=typeof n)throw Error("closest requires a string selector");return e.me?e.me.closest(n):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:pn},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async e=>window,validate:pn},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async e=>document,validate:pn},elementWithSelector:{name:"elementWithSelector",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const n=t[0];if("string"!=typeof n)throw Error("Selector must be a string");const r=e?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!r)throw Error("DOM not available - cannot resolve element selector");const s=r.querySelectorAll(n);return Array.from(s)},validate:e=>hn(e,"elementWithSelector","selector")},styleRef:{name:"styleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const n=t[0],r=t[1];if("string"!=typeof n)throw Error("StyleRef requires a string property name");const s=r||e.me;if(s&&s instanceof HTMLElement)return Hr(s,n)},validate:e=>yn(e,1,2,"styleRef","property, optional element")??fn(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 n=t[0],r=t[1];if("string"!=typeof n||"string"!=typeof r)throw Error("Possessive styleRef requires possessor and property strings");let s=null;if("my"===n&&e.me?s=e.me instanceof HTMLElement?e.me:null:"its"===n&&e.it&&(s=e.it instanceof HTMLElement?e.it:null),s)return Hr(s,r)},validate:e=>un(e,2,"possessiveStyleRef","possessor, property")??fn(e,0,"possessiveStyleRef","possessor")??fn(e,1,"possessiveStyleRef","property")},ofStyleRef:{name:"ofStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const n=t[0],r=t[1];if("string"!=typeof n||"string"!=typeof r)throw Error("Of styleRef requires property and reference strings");let s=null;if("me"===r&&e.me?s=e.me instanceof HTMLElement?e.me:null:"it"===r&&e.it&&(s=e.it instanceof HTMLElement?e.it:null),s)return Hr(s,n)},validate:e=>un(e,2,"ofStyleRef","property, reference")??fn(e,0,"ofStyleRef","property")??fn(e,1,"ofStyleRef","reference")}};class zr{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(this.ttl>=Date.now()-t.timestamp)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(),this.cache.set(e,{result:t,timestamp:Date.now(),accessCount:1}),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[n,r]of this.accessOrder)t>r&&(t=r,e=n);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,n)=>e+(t-n.timestamp),0)/e.length:0,totalAccesses:e.reduce((e,t)=>e+t.accessCount,0)}}}const Wr=new class{constructor(){this.domQueryCache=new zr(200,3e3),this.exprResultCache=new zr(500,2e3),this.cssMatchCache=new zr(100,5e3),this.formValueCache=new zr(50,1e3),this.hits=0,this.misses=0}querySelector(e){const t="querySelector:"+e,n=this.domQueryCache.get(t);if(void 0!==n)return this.hits++,n;this.misses++;const r=document.querySelector(e);return this.domQueryCache.set(t,r),r}querySelectorAll(e){const t="querySelectorAll:"+e,n=this.domQueryCache.get(t);if(void 0!==n)return this.hits++,n;this.misses++;const r=Array.from(document.querySelectorAll(e));return this.domQueryCache.set(t,r),r}getElementById(e){const t="getElementById:"+e,n=this.domQueryCache.get(t);if(void 0!==n)return this.hits++,n;this.misses++;const r=document.getElementById(e);return this.domQueryCache.set(t,r),r}getElementsByClassName(e){const t="getElementsByClassName:"+e,n=this.domQueryCache.get(t);if(void 0!==n)return this.hits++,n;this.misses++;const r=Array.from(document.getElementsByClassName(e));return this.domQueryCache.set(t,r),r}matches(e,t){const n=`matches:${this.getElementCacheKey(e)}:${t}`,r=this.cssMatchCache.get(n);if(void 0!==r)return this.hits++,r;this.misses++;const s=e.matches(t);return this.cssMatchCache.set(n,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),n=this.formValueCache.get("formValue:"+t);if(void 0!==n)return this.hits++,n;this.misses++}setFormValue(e,t){const n=this.getElementCacheKey(e);this.formValueCache.set("formValue:"+n,t)}invalidateElementCache(e){const t=this.getElementCacheKey(e);for(const e of[this.domQueryCache,this.cssMatchCache,this.formValueCache])for(const n of Array.from(e.cache.keys()))"string"==typeof n&&n.includes(t)&&e.delete(n)}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("."),n=this.getElementPosition(e);return`${e.tagName.toLowerCase()}${t?"."+t:""}@${n}`}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(([n,r])=>{e-r.timestamp>t.ttl&&t.delete(n)})})}};"undefined"!=typeof window&&setInterval(()=>{Wr.cleanup()},1e4);const Jr=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 n=performance.now()-t;return this.startTimes.delete(e),n}return 0}recordTokenization(e){this.metrics.tokenizationTime+=e}recordEvaluation(e){this.metrics.evaluationTime+=e}updateCacheMetrics(){const e=Wr.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 Zr(){Wr.cleanup(),Jr.getMetrics().memoryUsage>52428800&&Jr.reset()}let Kr=null;function Gr(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 n=e.trim();if(""===n)return 0;const r=parseFloat(n);if(isNaN(r))throw Error(`${t} cannot be converted to number: "${e}"`);return r}if("boolean"==typeof e)return e?1:0;if(null==e)return 0;if("object"==typeof e&&null!==e){if(Array.isArray(e)&&1===e.length){const n=e[0];if(Array.isArray(n))throw Error(t+" is a nested array, cannot convert to number");return Gr(n,t)}if("string"==typeof e.textContent||"value"in e){const t=e.value??e.textContent;if(null!=t){const e=(t+"").trim();if(""===e)return 0;const n=parseFloat(e);if(!isNaN(n))return n}}const n=e.valueOf();if("number"==typeof n&&Number.isFinite(n))return n}throw Error(`${t} cannot be converted to number: ${typeof e}`)}function Xr(e){if("number"==typeof e)return Number.isFinite(e)?e:null;if("string"==typeof e){const t=e.trim();if(""===t)return 0;const n=parseFloat(t);return isNaN(n)?null:n}return"boolean"==typeof e?e?1:0:null==e?0:null}function Yr(e,t){if(!Number.isFinite(e)){if(Number.isNaN(e))throw Error(t+" resulted in non-finite value: NaN");throw Error(`${t} resulted in non-finite value: ${e>0?"Infinity":"-Infinity"}`)}return e}function Qr(e){try{return Gr(e,"_"),!0}catch{return!1}}function es(e,t,n){if("==="===n)return e===t;if("!=="===n)return e!==t;if(null==e||null==t)return function(e,t,n){if(null==e&&null==t)switch(n){case"==":case">=":case"<=":return!0;default:return!1}switch(n){case"==":case">":case"<":case">=":case"<=":default:return!1;case"!=":return!0}}(e,t,n);const[r,s]=function(e,t){if("number"==typeof e&&"number"==typeof t)return[e,t];if("string"==typeof e&&"string"==typeof t){const n=parseFloat(e),r=parseFloat(t);return isNaN(n)||isNaN(r)?[e,t]:[n,r]}const n=Xr(e),r=Xr(t);return null!==n&&null!==r?[n,r]:[e+"",t+""]}(e,t);switch(n){case">":return r>s;case"<":return s>r;case">=":return r>=s;case"<=":return s>=r;case"==":return ts(e,t);case"!=":return!ts(e,t);default:return!1}}function ts(e,t){if(e===t)return!0;if(typeof e==typeof t)return("string"==typeof e||"number"==typeof e)&&e===t;if("number"==typeof e&&"string"==typeof t){const n=parseFloat(t);return!isNaN(n)&&e===n}if("string"==typeof e&&"number"==typeof t){const n=parseFloat(e);return!isNaN(n)&&n===t}return"boolean"==typeof e?ts(e?1:0,t):"boolean"==typeof t?ts(e,t?1:0):e+""==t+""}function ns(e,t=[]){return{isValid:!1,errors:e,suggestions:t}}function rs(e,t,n=[],r="error"){return{type:e,message:t,suggestions:n,severity:r}}function ss(e,t,n,r,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:n,output:r,timestamp:s,duration:Date.now()-s,success:i,...void 0!==o&&{error:o}}),r}"undefined"!=typeof window&&function(e=3e4){Kr&&clearInterval(Kr),Kr=setInterval(Zr,e)}();const is=An({left:Tn().describe("Left operand value"),right:Tn().describe("Right operand value")}).strict(),os=An({operand:Tn().describe("Operand value to negate")}).strict();function as(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType}new class extends Rn{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=is,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const s=this.toBoolean(t.left);if(!s)return this.trackSimple(e,n,!0,"boolean"),this.success(!1,"boolean");const i=this.toBoolean(t.right),o=s&&i;return this.trackSimple(e,n,!0,"boolean"),this.success(o,"boolean")}catch(t){return this.trackSimple(e,n,!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 Rn{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=is,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const s=this.toBoolean(t.left);if(s)return this.trackSimple(e,n,!0,"boolean"),this.success(!0,"boolean");const i=this.toBoolean(t.right),o=s||i;return this.trackSimple(e,n,!0,"boolean"),this.success(o,"boolean")}catch(t){return this.trackSimple(e,n,!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 Rn{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=os,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const s=!this.toBoolean(t.operand);return this.trackSimple(e,n,!0,"boolean"),this.success(s,"boolean")}catch(t){return this.trackSimple(e,n,!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 cs=Nn([Tn(),Tn()]),ls=Nn([Tn(),xn()]),us={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(e,t,n){const r=Date.now();try{return ss(this,e,[t,n],t==n,r)}catch(s){throw ss(this,e,[t,n],!1,r,!1,s instanceof Error?s:Error(s+"")),s}},validate:e=>dn(e,"equals"),inputSchema:cs,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"]}},fs={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],async evaluate(e,t,n){const r=e.evaluationHistory,s=t===n;return r&&ss(this,e,[t,n],s,r?Date.now():0),s},validate:e=>dn(e,"strictEquals")},hs={name:"notEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=","is not","does not equal"],async evaluate(e,t,n){const r=e.evaluationHistory,s=t!=n;return r&&ss(this,e,[t,n],s,r?Date.now():0),s},validate:e=>dn(e,"notEquals")},ds={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],async evaluate(e,t,n){const r=e.evaluationHistory,s=t!==n;return r&&ss(this,e,[t,n],s,r?Date.now():0),s},validate:e=>dn(e,"strictNotEquals")},ps={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0,i=es(t,n,"<");return r&&ss(this,e,[t,n],i,s),i},validate:e=>dn(e,"lessThan")},ms={name:"lessThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<=","is less than or equal to"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0,i=es(t,n,"<=");return r&&ss(this,e,[t,n],i,s),i},validate:e=>dn(e,"lessThanOrEqual")},ys={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0,i=es(t,n,">");return r&&ss(this,e,[t,n],i,s),i},validate:e=>dn(e,"greaterThan")},gs={name:"greaterThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">=","is greater than or equal to"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0,i=es(t,n,">=");return r&&ss(this,e,[t,n],i,s),i},validate:e=>dn(e,"greaterThanOrEqual")},vs={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(e,t,n){const r=Date.now();try{return ss(this,e,[t,n],t&&n,r)}catch(s){throw ss(this,e,[t,n],!1,r,!1,s instanceof Error?s:Error(s+"")),s}},validate:e=>dn(e,"and"),inputSchema:cs,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"]}},bs={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],async evaluate(e,t,n){const r=e.evaluationHistory,s=t||n;return r&&ss(this,e,[t,n],s,r?Date.now():0),s},validate:e=>dn(e,"or")},ws={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],async evaluate(e,t){const n=e.evaluationHistory,r=!t;return n&&ss(this,e,[t],r,n?Date.now():0),r},validate:e=>un(e,1,"not","operand")},Es={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0;let s;return s=null==t||(Gt(t)||Array.isArray(t)||t instanceof NodeList?0===t.length:!(t instanceof Node||t instanceof Element||!Qt(t)||0!==Object.keys(t).length)),n&&ss(this,e,[t],s,r),s},validate:e=>un(e,1,"isEmpty","value")},xs={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0;let s;return s=null==t||!1===t||(Array.isArray(t)||t instanceof NodeList?0===t.length:(Gt(t),!1)),n&&ss(this,e,[t],s,r),s},validate:e=>un(e,1,"no","value")},ks={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0,s=!await Es.evaluate(e,t);return n&&ss(this,e,[t],s,r),s},validate:e=>un(e,1,"isNotEmpty","value")},Ss={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0,s=As(t);return n&&ss(this,e,[t],s,r),s},validate:e=>un(e,1,"exists","value")};function As(e){return null!=e&&(Array.isArray(e)?e.length>0:!("undefined"!=typeof NodeList&&e instanceof NodeList)||e.length>0)}const Ns={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0,s=!As(t);return n&&ss(this,e,[t],s,r),s},validate:e=>un(e,1,"doesNotExist","value")},Ts={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0;let i;if(t&&n){if(as(t)&&as(n))return i=t.contains(n),r&&ss(this,e,[t,n],i,s),i;if(Gt(t)&&t.match(/^[.#][\w-]+$/)){const o=document.querySelector(t);if(o&&as(n))return i=o.contains(n),r&&ss(this,e,[t,n],i,s),i;if(o&&Gt(n)&&n.match(/^[.#][\w-]+$/)){const a=document.querySelector(n);return i=!!a&&o.contains(a),r&&ss(this,e,[t,n],i,s),i}}if(Gt(n)&&n.match(/^[.#][\w-]+$/)&&as(t)){const o=document.querySelector(n);return i=!!o&&t.contains(o),r&&ss(this,e,[t,n],i,s),i}}if(Gt(t)&&Gt(n))i=t.includes(n);else if(Array.isArray(t)||"undefined"!=typeof NodeList&&t instanceof NodeList){const e=Array.from(t);i=e.includes(n)||n instanceof Node&&e.some(e=>e instanceof Node&&e.contains(n))}else i=!(!Qt(t)||!Gt(n))&&n in t;return r&&ss(this,e,[t,n],i,s),i},validate:e=>un(e,2,"contains","container, value")},Cs={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0,i=!await Ts.evaluate(e,t,n);return r&&ss(this,e,[t,n],i,s),i},validate:e=>un(e,2,"doesNotContain","container, value")},Os={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0,i=null!=t&&null!=n&&(t+"").startsWith(n+"");return r&&ss(this,e,[t,n],i,s),i},validate:e=>un(e,2,"startsWith","str, prefix")},Rs={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0,i=null!=t&&null!=n&&(t+"").endsWith(n+"");return r&&ss(this,e,[t,n],i,s),i},validate:e=>un(e,2,"endsWith","str, suffix")},$s={name:"between",category:"Logical",evaluatesTo:"Boolean",operators:["is between","between"],async evaluate(e,t,n,r){const s=e.evaluationHistory;let i=n,o=r;if(null!=i&&null!=o&&i>o){const e=i;i=o,o=e}const a=null!=i&&null!=o&&t>=i&&o>=t;return s&&ss(this,e,[t,n,r],a,s?Date.now():0),a},validate:e=>un(e,3,"between","value, min, max")},Ls={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(e,t,n){const r=Date.now();try{let s;if(t instanceof Element&&Gt(n)){const e=n;if(e.startsWith(".")||e.startsWith("#")||e.startsWith(":")||e.startsWith("[")||/^[a-zA-Z][\w-]*$/.test(e))try{s=function(e,t){return Wr.matches(e,t)}(t,e)}catch(e){s=!1}else s=!1}else if(Gt(t)&&Gt(n)){const e=t,r=n;try{s=(r.startsWith("/")&&r.endsWith("/")?RegExp(r.slice(1,-1)):RegExp(r)).test(e)}catch(t){s=e.includes(r)}}else s=!1;return ss(this,e,[t,n],s,r)}catch(s){throw ss(this,e,[t,n],!1,r,!1,s instanceof Error?s:Error(s+"")),s}},validate:e=>un(e,2,"matches","element, selector"),inputSchema:ls,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"]}},js={name:"has",category:"Logical",evaluatesTo:"Boolean",operators:["has","have"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0;let i=!1;if(t instanceof Element&&Gt(n)){const e=n;e.startsWith(".")?i=t.classList.contains(e.slice(1)):e.startsWith("[")&&e.endsWith("]")&&(i=t.hasAttribute(e.slice(1,-1)))}return r&&ss(this,e,[t,n],i,s),i},validate:e=>un(e,2,"has","element, selector")},Is={name:"doesNotHave",category:"Logical",evaluatesTo:"Boolean",operators:["does not have"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0,i=!await js.evaluate(e,t,n);return r&&ss(this,e,[t,n],i,s),i},validate:e=>un(e,2,"doesNotHave","element, selector")},Ms={equals:us,strictEquals:fs,notEquals:hs,strictNotEquals:ds,lessThan:ps,lessThanOrEqual:ms,greaterThan:ys,greaterThanOrEqual:gs,and:vs,or:bs,not:ws,no:xs,isEmpty:Es,isNotEmpty:ks,exists:Ss,doesNotExist:Ns,contains:Ts,doesNotContain:Cs,startsWith:Os,endsWith:Rs,between:$s,matches:Ls,has:js,doesNotHave:Is},Ds=An({value:xn().describe("String literal value")}).strict(),Ps=An({value:kn().describe("Number literal value")}).strict(),Fs=An({value:Sn().describe("Boolean literal value")}).strict(),Bs=An({left:Tn().describe("Left operand"),right:Tn().describe("Right operand")}).strict();const qs={stringLiteral:new class extends Rn{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=Ds,this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid){const t=this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions);return this.trackSimple(e,n,!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,n,!0,s),i}catch(t){return this.trackSimple(e,n,!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 n=e.replace(/\$\{([^}]+)\}/g,(e,n)=>{try{const e=this.resolveExpression(n.trim(),t);return void 0!==e?e+"":""}catch(e){return""}});return n=n.replace(/\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g,(e,n)=>{try{const e=this.resolveVariable(n,t);return void 0!==e?e+"":""}catch(e){return""}}),n}resolveExpression(e,t){if(e.includes(".")){const n=e.split(".");let r=this.resolveVariable(n[0],t);for(let e=1;n.length>e&&null!=r;e++)r=r[n[e]];return r}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)?(Pe(e,t),t.locals.get(e)):t.globals?.has(e)?t.globals.get(e):void 0}},numberLiteral:new class extends Rn{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=Ps,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);return r.isValid?Number.isFinite(t.value)?(this.trackSimple(e,n,!0,t.value),this.success(t.value,"number")):(this.trackSimple(e,n,!1),this.failure("NumberValidationError","invalid-argument","Number literal must be finite","NUMBER_NOT_FINITE")):(this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(t){return this.trackSimple(e,n,!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?Number.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 Rn{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=Fs,this.outputType="Boolean",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);return r.isValid?(this.trackSimple(e,n,!0,t.value),this.success(t.value,"boolean")):(this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(t){return this.trackSimple(e,n,!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 Rn{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=Bs,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions);const s=Gr(t.left,"left operand")+Gr(t.right,"right operand");return this.trackSimple(e,n,!0,s),this.success(s,"number")}catch(t){return this.trackSimple(e,n,!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 Rn{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=Bs,this.outputType="String",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors[0]?.message||"Invalid input","STRING_CONCATENATION_VALIDATION_FAILED",r.suggestions);const s=this.convertToString(t.left)+this.convertToString(t.right);return this.trackSimple(e,n,!0,s),this.success(s,"string")}catch(t){return this.trackSimple(e,n,!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=Bs.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(Gt(e))return e;if(Xt(e))return""+e;if(Yt(e))return""+e;if(e instanceof Date)return""+e;try{return e+""}catch{return"[object Object]"}}},multiplication:new class extends Rn{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=Bs,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions);const s=Gr(t.left,"left operand")*Gr(t.right,"right operand");return this.trackSimple(e,n,!0,s),this.success(s,"number")}catch(t){return this.trackSimple(e,n,!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"])}}}},Vs={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"},_s=An({collection:Tn().describe("Collection to operate on (array, NodeList, or string)")}).strict(),Hs=An({collection:Tn().describe("Collection to access"),index:kn().describe("Index position to access")}).strict(),Us=An({collection:Tn().describe("Collection to select random item from")}).strict();new class extends Rn{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=_s,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const s=this.normalizeCollection(t.collection),i=s.length>0?s[0]:void 0,o={success:!0,value:i,type:Vs[this.inferEvaluationType(i)]};return this.trackPerformance(e,t,o,n),o}catch(r){const s=this.failure("FirstExpressionError","runtime-error","First operation failed: "+(r instanceof Error?r.message:r+""),"FIRST_OPERATION_FAILED");return this.trackPerformance(e,t,s,n),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"])}}},new class extends Rn{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=_s,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const s=this.normalizeCollection(t.collection),i=s.length>0?s[s.length-1]:void 0,o={success:!0,value:i,type:Vs[this.inferEvaluationType(i)]};return this.trackPerformance(e,t,o,n),o}catch(r){const s=this.failure("LastExpressionError","runtime-error","Last operation failed: "+(r instanceof Error?r.message:r+""),"LAST_OPERATION_FAILED");return this.trackPerformance(e,t,s,n),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"])}}},new class extends Rn{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=Hs,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.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:Vs[this.inferEvaluationType(o)]};return this.trackPerformance(e,t,a,n),a}catch(r){const s=this.failure("AtExpressionError","runtime-error","At operation failed: "+(r instanceof Error?r.message:r+""),"AT_OPERATION_FAILED");return this.trackPerformance(e,t,s,n),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}},new class extends Rn{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=Us,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const s=this.normalizeCollection(t.collection);if(0===s.length){const r={success:!0,value:void 0,type:"undefined"};return this.trackPerformance(e,t,r,n),r}const i=s[this.getSecureRandomIndex(s.length)],o={success:!0,value:i,type:Vs[this.inferEvaluationType(i)]};return this.trackPerformance(e,t,o,n),o}catch(r){const s=this.failure("RandomExpressionError","runtime-error","Random operation failed: "+(r instanceof Error?r.message:r+""),"RANDOM_OPERATION_FAILED");return this.trackPerformance(e,t,s,n),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)}};const zs={name:"first",category:"Reference",evaluatesTo:"Any",operators:["first"],async evaluate(e,t){const n=void 0!==t?t:e.it;return null==n?null:Array.isArray(n)||n instanceof NodeList||n instanceof HTMLCollection?n.length>0?n[0]:null:n instanceof Element?n.children.length>0?n.children[0]:null:Gt(n)?n.length>0?n[0]:null:Qt(n)&&"length"in n&&Xt(n.length)&&n.length>0?n[0]:null},validate:e=>mn(e,1,"first","collection")},Ws={name:"last",category:"Reference",evaluatesTo:"Any",operators:["last"],async evaluate(e,t){const n=void 0!==t?t:e.it;if(null==n)return null;if(Array.isArray(n))return n.length>0?n[n.length-1]:null;if(n instanceof NodeList||n instanceof HTMLCollection)return n.length>0?n[n.length-1]:null;if(n instanceof Element){const e=n.children;return e.length>0?e[e.length-1]:null}return Gt(n)?n.length>0?n[n.length-1]:null:Qt(n)&&"length"in n&&Xt(n.length)&&n.length>0?n[n.length-1]:null},validate:e=>mn(e,1,"last","collection")},Js={name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(e,...t){const[n,r]=t;if(!Xt(n))throw Error("Index must be a number");const s=n,i=void 0!==r?r: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(Gt(i)){const e=0>s?i.length+s:s;return e>=0&&i.length>e?i[e]:null}if(Qt(i)&&"length"in i&&Xt(i.length)){const e=0>s?i.length+s:s;return e>=0&&i.length>e?i[e]:null}return null},validate:e=>yn(e,1,2,"at","index, optional collection")??function(e){return"number"!=typeof e[0]?"at index must be a number":null}(e)};function Zs(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;const e=n.querySelector(t);if(e)return e;n=n.nextElementSibling}const r=e.parentElement;return r&&r!==document.documentElement?Zs(r,t):null}function Ks(e,t){let n=e.previousElementSibling;for(;n;){const e=Array.from(n.querySelectorAll(t)).reverse();if(e.length>0)return e[0];if(n.matches(t))return n;n=n.previousElementSibling}const r=e.parentElement;return r&&r!==document.documentElement?Ks(r,t):null}function Gs(e,t,n,r){if(n.inSearch){if(null==n.inElt)return;return function(e,t,n,r){const s=Array.from(t??[]),i=[];for(const t of s)(t.matches&&t.matches(n)||t===e)&&i.push(t);for(let t=0;i.length-1>t;t++)if(i[t]===e)return i[t+1];if(r){const e=i[0];if(e&&e.matches&&e.matches(n))return e}}(e,r?Array.from(n.inElt):Array.from(n.inElt).reverse(),t,!!n.wrapping)}const s=n.within??("undefined"!=typeof document?document.body:null);if(s)return r?function(e,t,n,r){const s=t.querySelectorAll(n);for(let t=0;s.length>t;t++){const n=s[t];if(2===n.compareDocumentPosition(e))return n}return r?s[0]:void 0}(e,s,t,!!n.wrapping):function(e,t,n,r){const s=t.querySelectorAll(n);for(let t=s.length-1;t>=0;t--){const n=s[t];if(4===n.compareDocumentPosition(e))return n}return r?s[s.length-1]:void 0}(e,s,t,!!n.wrapping)}function Xs(e){let t=0,n=e;for(;n&&n.parentElement;)t+=Array.from(n.parentElement.children).indexOf(n),n=n.parentElement,t+=1e3;return t}const Ys={first:zs,last:Ws,at:Js,next:{name:"next",category:"Reference",evaluatesTo:"Element",operators:["next"],async evaluate(e,...t){const[n,r,s]=t,i=r||e.me;return i&&i instanceof Element?n?s?Gs(i,n,s,!0):Zs(i,n):i.nextElementSibling:null},validate:e=>mn(e,3,"next","optional selector, optional fromElement, optional modifiers")||(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[n,r,s]=t,i=r||e.me;return i&&i instanceof Element?n?s?Gs(i,n,s,!1):Ks(i,n):i.previousElementSibling:null},validate:e=>mn(e,3,"previous","optional selector, optional fromElement, optional modifiers")||(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[n,r,s]=t,i=s||e.me;if(!(i&&i instanceof Element))return null;const o=i.closest(r);return o?function(e,t,n){const r=Array.from(n.querySelectorAll(t)),s=Xs(e);for(const e of r)if(Xs(e)>s)return e;return null}(i,n,o):null},validate:e=>yn(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[n,r,s]=t,i=s||e.me;if(!(i&&i instanceof Element))return null;const o=i.closest(r);return o?function(e,t,n){const r=Array.from(n.querySelectorAll(t)),s=Xs(e);for(let e=r.length-1;e>=0;e--){const t=r[e];if(s>Xs(t))return t}return null}(i,n,o):null},validate:e=>yn(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")}};function Qs(){return Vr(Ur,Ms,qs,Hn,Ys)}class ei{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 n=Ar(e);this.runtime.execute(t,n).catch(n=>{console.error('[HyperFixi] Error executing _="" attribute:',n),console.error("Element:",e),console.error("Code:",t)})}}function ti(e,t,n,r,s,i){function o(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var a,c=r.kind,l="getter"===c?"get":"setter"===c?"set":"value",u=!t&&e?r.static?e:e.prototype:null,f=t||(u?Object.getOwnPropertyDescriptor(u,r.name):{}),h=!1,d=n.length-1;d>=0;d--){var p={};for(var m in r)p[m]="access"===m?{}:r[m];for(var m in r.access)p.access[m]=r.access[m];p.addInitializer=function(e){if(h)throw new TypeError("Cannot add initializers after decoration has completed");i.push(o(e||null))};var y=(0,n[d])("accessor"===c?{get:f.get,set:f.set}:f[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))&&(f.get=a),(a=o(y.set))&&(f.set=a),(a=o(y.init))&&s.unshift(a)}else(a=o(y))&&("field"===c?s.unshift(a):f[l]=a)}u&&Object.defineProperty(u,r.name,f),h=!0}function ni(e,t,n){for(var r=arguments.length>2,s=0;t.length>s;s++)n=r?t[s].call(e,n):t[s].call(e);return r?n:void 0}function ri(e,t,n){return"symbol"==typeof t&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:n?"".concat(n," ",t):t})}function si(e){const t=e.trim();return!(!t.startsWith("[@")||!t.endsWith("]"))||!!t.startsWith("@")}function ii(e){const t=e.trim();if(t.startsWith("[@")&&t.endsWith("]")){const e=t.slice(2,-1),n=e.indexOf("=");if(-1===n)return{name:e.trim()};const r=e.slice(0,n).trim();let s=e.slice(n+1).trim();return(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),{name:r,value:s}}if(t.startsWith("@"))return{name:t.substring(1).trim()};throw Error("Invalid attribute syntax: "+e)}function oi(e,t){for(const n of e)t(n);return e}function ai(e,t,n){for(const r of e)for(const e of t)n(r,e);return e}function ci(e,t,n){const r=e.hasAttribute(t);void 0!==n?r&&e.getAttribute(t)===n?e.removeAttribute(t):e.setAttribute(t,n):r?e.removeAttribute(t):e.setAttribute(t,"")}function li(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&&fi(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&&fi(e));const t=(e+"").trim(),n=t.startsWith(".")?t.substring(1):t;return n.length>0&&fi(n)?[n]:[]}function ui(e){const t=e.trim();return/^\{[^}]+\}$/.test(t)}function fi(e){if(!e||0===e.trim().length)return!1;const t=e.trim();return!!ui(t)||/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(t)}function hi(e,t){return e.map(e=>{if(ui(e)){const n=function(e){const t=e.trim(),n=t.match(/^\{(.+)\}$/);return n?n[1].trim():t}(e),r=t.locals.get(n)??t.globals.get(n);return null!=r?r+"":(fe(`Dynamic class variable '${n}' not found in context`),"")}return e}).filter(e=>e.length>0)}"function"==typeof SuppressedError&&SuppressedError;const di=Symbol("command:name"),pi=Symbol("command:category"),mi=Symbol("command:metadata");function yi(e){return function(t,n){const r=t;r[di]=e.name,r[pi]=e.category,Object.defineProperty(t.prototype,"name",{value:e.name,writable:!1,enumerable:!0})}}function gi(e){return function(t,n){const r=t,s=r[pi];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",compatibility:e.compatibility};r[mi]=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 vi(e){return()=>new e}function bi(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"tagName"in e&&"string"==typeof e.tagName&&"classList"in e}function wi(e){return null!==e&&"object"==typeof e&&"length"in e&&"number"==typeof e.length&&(Symbol.iterator in e||"function"==typeof e.item)}function Ei(e,t){return t}function xi(e,t,n){if(bi(e))return e;if(!e){const e=t.me;if(!e)throw Error(Ei(0,"No target element — provide explicit target or ensure context.me is set"));return Si(e)}if("string"==typeof e){const n=e.trim();if("me"===n){if(!t.me)throw Error(Ei(0,'Context reference "me" is not available'));return Si(t.me)}if("it"===n){if(!bi(t.it))throw Error(Ei(0,'Context reference "it" is not an HTMLElement'));return t.it}if("you"===n){if(!t.you)throw Error(Ei(0,'Context reference "you" is not available'));return Si(t.you)}const r=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!r)throw Error(Ei(0,"DOM not available — cannot resolve element selector"));const s=r.querySelector(n);if(!s)throw Error(Ei(0,"Element not found with selector: "+n));if(!bi(s))throw Error(Ei(0,"Element found but is not an HTMLElement: "+n));return s}throw Error(Ei(0,"Invalid target type: "+typeof e))}function ki(e,t){if(Array.isArray(e))return e.filter(bi);if(wi(e))return Array.from(e).filter(bi);if(bi(e))return[e];if(!e){const e=t.me;return e&&bi(e)?[e]:[]}if("string"==typeof e){const n=e.trim();if("me"===n)return t.me&&bi(t.me)?[t.me]:[];if("it"===n)return bi(t.it)?[t.it]:[];if("you"===n)return t.you&&bi(t.you)?[t.you]:[];const r=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(r){let e=n;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const t=r.querySelectorAll(e);return Array.from(t).filter(bi)}}return[]}function Si(e){if(bi(e))return e;throw Error("Value is not an HTMLElement")}function Ai(e,t,n){switch(e.toLowerCase()){case"my":case"me":if(!t.me)throw Error(Ei(0,'No "me" element in context'));if(!bi(t.me))throw Error(Ei(0,"context.me is not an HTMLElement"));return t.me;case"its":case"it":if(!t.it)throw Error(Ei(0,'No "it" value in context'));if(!bi(t.it))throw Error(Ei(0,"context.it is not an HTMLElement"));return t.it;case"your":case"you":if(!t.you)throw Error(Ei(0,'No "you" element in context'));if(!bi(t.you))throw Error(Ei(0,"context.you is not an HTMLElement"));return t.you;default:throw Error(Ei(0,"Unknown possessive: "+e))}}const Ni=["on","from","to","in","with","at"];async function Ti(e,t,n,r,s={},i){let o=e;if(s.filterPrepositions&&e&&(o=e.filter(e=>{const t=e;return"identifier"!==t?.type||"string"!=typeof t.name||!Ni.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(!n.me)throw Error(r+" command: no target specified and context.me is null");if(!bi(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}const a=[];for(const e of o){const s=await t.evaluate(e,n);if(""!==s&&("string"!=typeof s||""!==s.trim()))if(bi(s))a.push(s);else if(wi(s)){const e=Array.from(s).filter(bi);a.push(...e)}else if(Array.isArray(s)){const e=s.filter(bi);a.push(...e)}else{if("string"!=typeof s){if(null==s)continue;throw Error(`Invalid ${r} 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=n.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!t)throw Error("DOM not available - cannot resolve element selector");const r=t.querySelectorAll(e),i=Array.from(r).filter(bi);a.push(...i)}catch(e){throw Error(`Invalid CSS selector: "${s}" - ${e instanceof Error?e.message:e+""}`)}}}if(0===a.length){if(!n.me)throw Error(r+" command: no target specified and context.me is null");if(!bi(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}return a}function Ci(e){return"string"==typeof e&&e.trim().startsWith("*")}function Oi(e){const t=function(e){const t=e.trim();if(!t.startsWith("*"))return null;const n=t.substring(1).trim();return n?{property:n}:null}(e);if(!t)return null;const n=t.property.toLowerCase();return["display","visibility","opacity"].includes(n)?n:null}function Ri(e,t,n){e.style.setProperty(t,n)}const $i=["dialog","details","summary","select"];function Li(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 ji(e,t,n){return function(e){if(!e||"object"!=typeof e)return!1;const t=e.type;if("selector"!==t&&"cssSelector"!==t&&"classSelector"!==t)return!1;const n=Li(e);return"string"==typeof n&&n.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 n=Li(e);return"string"==typeof n&&n.startsWith("*")}(e)?{value:Li(e),extractedFromNode:!0}:function(e){if(!e||"object"!=typeof e)return!1;if("attributeAccess"===e.type)return!0;if("selector"===e.type||"cssSelector"===e.type){const t=Li(e);return"string"==typeof t&&t.startsWith("@")}return!1}(e)?{value:(r=e,"attributeAccess"===r.type?"@"+r.attributeName:Li(r)),extractedFromNode:!0}:{value:await t.evaluate(e,n),extractedFromNode:!1};var r}class Ii{async resolveTargets(e,t,n,r){return Ti(e,t,n,this.mode,{filterPrepositions:!0,fallbackModifierKey:this.preposition},r)}async evaluateFirst(e,t,n){return ji(e,t,n)}parseClassNames(e){return li(e)}isAttribute(e){return si(e.trim())}isCSSProperty(e){return Ci(e.trim())}validateTargets(e){return Array.isArray(e)&&function(e){return Array.isArray(e)&&e.length>0&&e.every(e=>bi(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 Mi=(()=>{let e,t,n=[gi({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"]}),yi({name:"add",category:"dom"})],r=[],s=Ii;return t=class extends s{constructor(){super(...arguments),this.mode="add",this.preposition="to"}async parseInput(e,t,n){if(!e.args||0===e.args.length)throw Error("add command requires an argument");const{value:r}=await this.evaluateFirst(e.args[0],t,n);if("object"==typeof r&&null!==r&&!Array.isArray(r))return{type:"styles",styles:r,targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)};if("string"==typeof r){const s=r.trim();if(this.isAttribute(s)){const{name:r,value:i}=function(e){const t=ii(e);return{name:t.name,value:t.value??""}}(s);return{type:"attribute",name:r,value:i,targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)}}if(this.isCSSProperty(s)){const r=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],n);return{type:"styles",styles:{[r]:i+""},targets:await this.resolveTargets(e.args.slice(2),t,n,e.modifiers)}}}const s=this.parseClassNames(r);if(0===s.length)throw Error("add command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)}}async execute(e,t){switch(e.type){case"classes":{const n=hi(e.classes,t);n.length>0&&ai(e.targets,n,(e,t)=>{e.classList.contains(t)||e.classList.add(t)});break}case"attribute":n=e.name,r=e.value,oi(e.targets,e=>{e.setAttribute(n,r)});break;case"styles":!function(e,t){ai(e,Object.entries(t),(e,[t,n])=>{e.style.setProperty(t,n)})}(e.targets,e.styles)}var n,r}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 n=t.styles;if(0===Object.keys(n).length)return!1;if(!Object.values(n).every(e=>"string"==typeof e))return!1}return!0}},ri(t,"AddCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;ti(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),ni(t,r)})(),t})();const Di=vi(Mi);function Pi(e){return!!e.parentNode&&(e.remove(),!0)}let Fi=(()=>{let e,t,n=[gi({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"]}),yi({name:"remove",category:"dom"})],r=[],s=Ii;return t=class extends s{constructor(){super(...arguments),this.mode="remove",this.preposition="from"}async parseInput(e,t,n){if(!e.args||0===e.args.length)throw Error("remove command requires an argument");const{value:r}=await this.evaluateFirst(e.args[0],t,n);if(bi(r))return{type:"element",targets:[r]};if(Array.isArray(r)&&r.length>0&&bi(r[0]))return{type:"element",targets:r.filter(e=>bi(e))};if("string"==typeof r){const s=r.trim();if(this.isAttribute(s))return{type:"attribute",name:ii(s).name,targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)};if(this.isCSSProperty(s))return{type:"styles",properties:[s.substring(1).trim()],targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)}}const s=this.parseClassNames(r);if(0===s.length)throw Error("remove command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)}}execute(e,t){switch(e.type){case"classes":{const n=hi(e.classes,t);n.length>0&&ai(e.targets,n,(e,t)=>{e.classList.remove(t)});break}case"attribute":n=e.name,oi(e.targets,e=>{e.removeAttribute(n)});break;case"styles":!function(e,t){ai(e,t,(e,t)=>{e.style.removeProperty(t)})}(e.targets,e.properties);break;case"element":for(const t of e.targets)Pi(t)}var n}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}},ri(t,"RemoveCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;ti(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),ni(t,r)})(),t})();const Bi=vi(Fi);function qi(e){const t=e.trim().match(/^(\d+(?:\.\d+)?)\s*(s|ms|sec|seconds?|milliseconds?)?$/i);if(!t)return null;const n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();return"ms"===r||"millisecond"===r||"milliseconds"===r?{number:n,milliseconds:Math.floor(n)}:"s"===r||"sec"===r||"second"===r||"seconds"===r?{number:n,milliseconds:Math.floor(1e3*n)}:null}function Vi(e){if("number"==typeof e){if(0>e)throw Error("Duration must be >= 0");return Math.floor(e)}if("string"==typeof e){const t=qi(e);if(!t)throw Error(`Invalid duration format: "${e}"`);return t.milliseconds}throw Error("Invalid duration type: "+typeof e)}function _i(e){return 0===e.length?[]:"SUMMARY"===e[0].tagName?e.map(e=>e.closest("details")).filter(e=>null!==e):e}function Hi(e){return"DIALOG"===e.tagName}function Ui(e){return"DETAILS"===e.tagName}function zi(e,t,n){return()=>{"class"===t?e.classList.toggle(n):"attribute"===t&&ci(e,n)}}function Wi(e,t,n,r){const s=zi(e,t,n),i=setTimeout(s,r);return()=>{clearTimeout(i)}}function Ji(e,t,n,r){const s=zi(e,t,n),i=()=>{s(),e.removeEventListener(r,i)};return e.addEventListener(r,i,{once:!0}),()=>{e.removeEventListener(r,i)}}function Zi(e,t,n){if(t.startsWith("@")){const r=t.substring(1);return void(!1===n?e.removeAttribute(r):e.setAttribute(r,!0===n?"":n+""))}const r=n+"";switch(t){case"textContent":return void(e.textContent=r);case"innerHTML":return void(e.innerHTML=r);case"innerText":return void(e.innerText=r);case"id":return void(e.id=r);case"className":return void(e.className=r);case"value":return void("value"in e&&(e.value=r));case"checked":return void("checked"in e&&(e.checked=!!n))}if(t.includes(".")){const r=t.split(".");let s=e;for(let e=0;r.length-1>e;e++)if(s=s[r[e]],null==s)return;return void(s[r[r.length-1]]=n)}if(t.includes("-")||t in e.style)e.style.setProperty(t,r);else try{e[t]=n}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 Ki=/^the\s+(.+?)\s+of\s+(.+)$/i,Gi=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 Xi(e){return"string"==typeof e&&Ki.test(e)}function Yi(e,t){const n=e.match(Ki);if(!n)return null;try{return{element:xi(n[2].trim(),t),property:n[1].trim()}}catch{return null}}async function Qi(e,t,n){if(function(e){return!(!e||"object"!=typeof e)&&"propertyOfExpression"===e.type&&"object"==typeof e.property&&null!==e.property}(e))return async function(e,t,n){const r=e.property?.name;if(!r)return null;let s=await t.evaluate(e.target,n);return Array.isArray(s)&&(s=s[0]),bi(s)?{element:s,property:r}:null}(e,t,n);if(function(e){return!(!e||"object"!=typeof e)&&"propertyAccess"===e.type&&("string"==typeof e.property||"object"==typeof e.property&&null!==e.property&&"string"==typeof e.property.name)}(e))return async function(e,t,n){const r="string"==typeof e.property?e.property:e.property?.name;if(!r)return null;let s=await t.evaluate(e.object,n);return Array.isArray(s)&&(s=s[0]),bi(s)?{element:s,property:r}:null}(e,t,n);const r=e;if("possessiveExpression"===r?.type||"memberExpression"===r?.type){const e=r.object,s=r.property;let i=await t.evaluate(e,n);if(Array.isArray(i)&&(i=i[0]),!bi(i))return null;const o=s?.name||s?.value;return o?{element:i,property:o}:null}return null}function eo(e,t){const{element:n,property:r}=e;r.startsWith("*")?Ri(n,r.substring(1),t+""):Zi(n,r,t)}async function to(e,t,n){let r,s;if(e?.for){const s=await t.evaluate(e.for,n);r="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 n=qi(e);return n?n.milliseconds:t}return t}(s):void 0}if(e?.until){const r=await t.evaluate(e.until,n);"string"==typeof r&&(s=r)}return{duration:r,untilEvent:s}}function no(e,t){const n=t?.name,r=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 $i.includes(t)}(t)}(t);if(bi(e)||Array.isArray(e)&&e.every(e=>bi(e)))return{type:"element",expression:""};if(r&&n)return{type:"element",expression:n};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 $i.some(e=>t.includes(e))}(t)?{type:"element",expression:t}:{type:"class",expression:t}}return{type:"class",expression:""}}const ro=vi((()=>{let e,t,n=[gi({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"]}),yi({name:"toggle",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("toggle command requires an argument");let r=!1;if(function(e){if(!e||"asExpression"!==e.type)return!1;const t=e.targetType,n="string"==typeof t?t:t?.name;return"string"==typeof n&&"modal"===n.toLowerCase()}(e.args[0])){r=!0;const t=e.args[0].expression;e={...e,args:[t,...e.args.slice(1)]}}const s=e.args[0],i=s?.name;if("between"===i&&e.args.length>=4){const{duration:r,untilEvent:s}=await to(e.modifiers,t,n),i=async e=>{const r=e;return"selector"===r?.type?r.value:t.evaluate(e,n)},o=await i(e.args[1]),a=await i(e.args[3]),c=[];for(let t=4;e.args.length>t;t++){const n=e.args[t]?.name;"on"!==n&&"from"!==n&&c.push(e.args[t])}const l={filterPrepositions:!0,fallbackModifierKey:"on"},u=await Ti(c,t,n,"toggle",l,e.modifiers);return{type:"classes-between",classA:(o+"").replace(/^\./,""),classB:(a+"").replace(/^\./,""),targets:u,duration:r,untilEvent:s}}const o=await Qi(s,t,n);if(o)return{type:"property",target:o};if("selector"===s.type&&"string"==typeof s.value&&s.value.startsWith("*")){let r=s.value,i=1;if("*"===r&&e.args.length>1&&"identifier"===e.args[1].type&&(r="*"+e.args[1].name,i=2),"*"===r&&e.modifiers?.on){const s=e.modifiers.on?.name;if(s&&["display","visibility","opacity"].includes(s)){r="*"+s;const{duration:i,untilEvent:o}=await to(e.modifiers,t,n),a=Oi(r);if(a){const e=n.me;return{type:"css-property",property:a,targets:e?[e]:[],duration:i,untilEvent:o}}}}const o=Oi(r);if(o){const{duration:r,untilEvent:s}=await to(e.modifiers,t,n),a={filterPrepositions:!0,fallbackModifierKey:"on"};return{type:"css-property",property:o,targets:await Ti(e.args.slice(i),t,n,"toggle",a,e.modifiers),duration:r,untilEvent:s}}}const{duration:a,untilEvent:c}=await to(e.modifiers,t,n),{value:l}=await ji(s,t,n);if(Xi(l)){const e=Yi(l,n);if(e)return{type:"property",target:e}}const{type:u,expression:f}=no(l,s),h={filterPrepositions:!0,fallbackModifierKey:"on"};switch(u){case"attribute":{const{name:r,value:s}=ii(f);return{type:"attribute",name:r,value:s,targets:await Ti(e.args.slice(1),t,n,"toggle",h,e.modifiers),duration:a,untilEvent:c}}case"css-property":{const r=Oi(f);if(!r)throw Error("Invalid CSS property: "+f);return{type:"css-property",property:r,targets:await Ti(e.args.slice(1),t,n,"toggle",h,e.modifiers)}}case"element":{let i;if(bi(l))i=[l];else if(Array.isArray(l)&&l.every(e=>bi(e)))i=l;else if(f){const e=document.querySelectorAll(f);i=Array.from(e).filter(e=>bi(e))}else i=await Ti([s],t,n,"toggle",h,e.modifiers);const o=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}}(i);if("dialog"===o){const s=r?"modal":await async function(e,t,n,r){if(t?.as){const e=await n.evaluate(t.as,r);if("string"==typeof e&&"modal"===e.toLowerCase())return"modal"}if(e.length>=2){const t=await n.evaluate(e[1],r);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 n.evaluate(e[2],r);if("string"==typeof t&&"modal"===t.toLowerCase())return"modal"}}}return"non-modal"}(e.args,e.modifiers,t,n);return{type:"dialog",mode:s,targets:i}}return"details"===o?{type:"details",targets:_i(i)}:"select"===o?{type:"select",targets:i}:{type:"classes",classes:li(f),targets:i,duration:a,untilEvent:c}}default:{const r=li(f||l);if(!r.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:r,targets:await Ti(e.args.slice(1),t,n,"toggle",h,e.modifiers),duration:a,untilEvent:c}}}}async execute(e,t){switch(e.type){case"classes":{const n=hi(e.classes,t);if(0===n.length)return[...e.targets];if(ai(e.targets,n,(e,t)=>{e.classList.toggle(t)}),(e.duration||e.untilEvent)&&n.length)for(const t of e.targets)e.duration&&Wi(t,"class",n[0],e.duration),e.untilEvent&&Ji(t,"class",n[0],e.untilEvent);return[...e.targets]}case"attribute":if(n=e.name,r=e.value,oi(e.targets,e=>{ci(e,n,r)}),e.duration||e.untilEvent)for(const t of e.targets)e.duration&&Wi(t,"attribute",e.name,e.duration),e.untilEvent&&Ji(t,"attribute",e.name,e.untilEvent);return[...e.targets];case"css-property":return oi(e.targets,t=>function(e,t){const n=window.getComputedStyle(e);switch(t){case"display":"none"===n.display?(e.style.display=e.dataset.previousDisplay||"block",delete e.dataset.previousDisplay):(e.dataset.previousDisplay=n.display,e.style.display="none");break;case"visibility":e.style.visibility="hidden"===n.visibility?"visible":"hidden";break;case"opacity":e.style.opacity=0===parseFloat(n.opacity)?"1":"0"}}(t,e.property));case"property":return function(e){const t=function(e){const{element:t,property:n}=e;return n.startsWith("*")?function(e,t){return window.getComputedStyle(e).getPropertyValue(t)}(t,n.substring(1)):cn(t,n)}(e),n=e.property,r=n.startsWith("@")?n.substring(1):n;if("boolean"==typeof t||Gi.has(r)||Gi.has(r.toLowerCase())){const n=!t;return eo(e,n),n}if("number"==typeof t){const n=0===t?1:0;return eo(e,n),n}if("string"==typeof t){const r="__ht_"+n,s=e.element[r];return""===t&&void 0!==s?(eo(e,s),s):(e.element[r]=t,eo(e,""),"")}eo(e,!t)}(e.target),[e.target.element];case"dialog":return oi(e.targets,t=>{return r=e.mode,void((n=t).open?n.close():"modal"===r?n.showModal():n.show());var n,r});case"details":return oi(e.targets,e=>{var t;(t=e).open=!t.open});case"select":return oi(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 n=t.classList.contains(e.classA),r=t.classList.contains(e.classB);n?(t.classList.remove(e.classA),t.classList.add(e.classB)):r?(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&&Wi(t,"class",e.classA,e.duration),e.untilEvent&&Ji(t,"class",e.classA,e.untilEvent);return[...e.targets]}var n,r}},ri(t,"ToggleCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),ni(t,r)})(),t})());class so{async parseInput(e,t,n){const{targets:r}=await async function(e,t,n,r){return{targets:await Ti(e.args,t,n,r)}}(e,t,n,this.mode);return{targets:r,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=>bi(e))||"show"!==t.mode&&"hide"!==t.mode||"show"===t.mode&&"string"!=typeof t.defaultDisplay)}showElement(e,t="block"){const n=e.dataset.originalDisplay;void 0!==n?(e.style.display=n||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 io=(()=>{let e,t,n=[gi({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"]}),yi({name:"show",category:"dom"})],r=[],s=so;return t=class extends s{constructor(){super(...arguments),this.mode="show"}async execute(e,t){const n=e.defaultDisplay||"block";for(const t of e.targets)this.showElement(t,n)}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&!!t.targets.every(e=>bi(e))&&"string"==typeof t.defaultDisplay}},ri(t,"ShowCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;ti(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),ni(t,r)})(),t})();const oo=vi(io);let ao=(()=>{let e,t,n=[gi({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"]}),yi({name:"hide",category:"dom"})],r=[],s=so;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=>bi(e))}},ri(t,"HideCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;ti(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),ni(t,r)})(),t})();const co=vi(ao);const lo=vi((()=>{let e,t,n=[gi({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"]}),yi({name:"put",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("put requires arguments");const r=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 n=e.args[t],a=r(n),c="literal"===a?n.value:n.name;if(("literal"===a||"identifier"===a)&&s.includes(c)){i=t,o=c;break}}let a=null,c=null;if(-1===i){const t=s.find(t=>e.modifiers[t]);if(t)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,n),u=this.mapPosition(o);let f,h,d=null;if(c){const e=r(c),s=await Qi(c,t,n);if(s)return{value:l,targets:[s.element],position:"replace",memberPath:s.property};if("memberExpression"===e){const e=c.object,r=c.property;if("selector"===e?.type)d=e.value;else if("identifier"===e?.type){const s=e.name;if("my"===s||"me"===s||"I"===s){if(n.me&&r?.name)return{value:l,targets:[n.me],position:"replace",memberPath:r.name}}else if("its"===s||"it"===s){const e=await t.evaluate(c,n);"string"==typeof e&&(d=e)}else d=s}if(d&&r?.name)f=r.name;else if(!d&&!f){const e=await t.evaluate(c,n);"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&&Xi(e)){const t=Yi(e,n);if(t)return{value:l,targets:[t.element],position:"replace",memberPath:t.property}}"string"==typeof e&&this.looksLikeCss(e)?d=e:h=e+""}else if("identifier"===e){const e=c.name;if(this.looksLikeCss(e))d=e;else{const r=await t.evaluate(c,n),s=this.resolveEvaluatedAsElements(r);if(s)return{value:l,targets:s,position:u,memberPath:f};h=e}}else{const e=await t.evaluate(c,n),r=this.resolveEvaluatedAsElements(e);if(r)return{value:l,targets:r,position:u,memberPath:f};"string"==typeof e&&(this.looksLikeCss(e)?d=e:h=e)}}return h?{value:l,targets:[],position:u,memberPath:f,variableName:h}:{value:l,targets:await this.resolveTargets(d,n),position:u,memberPath:f}}async execute(e,t){const{value:n,targets:r,position:s,memberPath:i,variableName:o}=e;if(o)return t.locals&&t.locals.set(o,n),t[o]=n,void Object.assign(t,{it:n});if(i)for(const e of r)this.setProperty(e,i,n);else for(const e of r){const t=this.parseValue(n);this.insertContent(e,t,s)}return r}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||!bi(t.me))throw Error("put: no target and context.me is null");return[t.me]}const n=Array.from(document.querySelectorAll(e)).filter(e=>bi(e));if(!n.length)throw Error(`No elements: "${e}"`);return n}parseValue(e){return bi(e)?e:null==e?"":e+""}insertContent(e,t,n){if("replace"!==n)if(bi(t)){const r=t;switch(n){case"beforebegin":e.parentElement?.insertBefore(r,e);break;case"afterbegin":e.insertBefore(r,e.firstChild);break;case"beforeend":e.appendChild(r);break;case"afterend":e.parentElement?.insertBefore(r,e.nextSibling)}}else t.includes("<")&&t.includes(">")?e.insertAdjacentHTML(n,t):e.insertAdjacentText(n,t);else bi(t)?(e.innerHTML="",e.appendChild(t)):t.includes("<")&&t.includes(">")?e.innerHTML=t:e.textContent=t}resolveEvaluatedAsElements(e){if(bi(e))return[e];if(Array.isArray(e)){const t=e.filter(bi);return t.length>0?t:null}if("undefined"!=typeof NodeList&&e instanceof NodeList){const t=Array.from(e).filter(bi);return t.length>0?t:null}return null}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,n){const r=t.split(".");let s=e;for(let e=0;r.length-1>e;e++){if(!s[r[e]])throw Error(`Property path "${t}" does not exist`);s=s[r[e]]}s[r[r.length-1]]=n}},ri(t,"PutCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),ni(t,r)})(),t})());function uo(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 fo(e,t,n){return"global"===n&&t.globals&&t.globals.has(e)?t.globals.get(e):"global"!==n&&t.locals&&t.locals.has(e)?(Pe(e,t),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"===n&&t.locals&&t.locals.has(e)?(Pe(e,t),t.locals.get(e)):"undefined"!=typeof window&&e in window?window[e]:"undefined"!=typeof globalThis&&e in globalThis?globalThis[e]:void 0}function ho(e,t,n,r){if("global"===r)return Fe(n,e,t),void("undefined"!=typeof window&&(window[e]=t));if(e.startsWith("$"))Fe(n,e.slice(1),t);else{if(n.locals&&n.locals.has(e))return n.locals.set(e,t),void De(e,t,n);if(n.globals&&n.globals.has(e))return Fe(n,e,t),void("undefined"!=typeof window&&e in window&&(window[e]=t));if(n.variables&&n.variables.has(e))n.variables.set(e,t);else{if("undefined"!=typeof window&&e in window)return window[e]=t,void Fe(n,e,t);n.locals.set(e,t),De(e,t,n)}}}function po(e,t){return"me"===e?t.me:"it"===e?t.it:"you"===e?t.you:fo(e,t)}const mo={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function yo(e){return e.replace(/[&<>"']/g,e=>mo[e])}let go=(()=>{let e,t,n=[gi({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"]}),yi({name:"make",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){const r=e.modifiers.an??e.modifiers.a??e.args[0];if(!r)throw Error("Make command requires class name or DOM element expression");const s=r.raw;let i="string"==typeof s&&s.startsWith("<")?s:await t.evaluate(r,n);if(null==i)throw Error("Make command requires class name or DOM element expression");"string"==typeof i&&i.startsWith("<")&&(i=await async function(e,t){if(!e.includes("{"))return e;const n=/\{([^{}]+)\}/g,r=[];let s;for(;null!==(s=n.exec(e));){let e=s[0];try{const n=await tr(s[1].trim(),t);null!=n&&(e=yo(n+""))}catch{}r.push({index:s.index,length:s[0].length,text:e})}let i=e;for(let e=r.length-1;e>=0;e--){const{index:t,length:n,text:s}=r[e];i=i.slice(0,t)+s+i.slice(t+n)}return i}(i,n));const o=void 0!==e.modifiers.an?"an":"a",a=await async function(e,t,n){if(!e)return[];if("arrayLiteral"===e.type&&Array.isArray(e.args)){const r=[];for(const s of e.args)r.push(await t.evaluate(s,n));return r}const r=await t.evaluate(e,n);return Array.isArray(r)?r:[r]}(e.modifiers.from,t,n),c=await async function(e,t,n){if(!e)return;if(("symbol"===e.type||"identifier"===e.type)&&"string"==typeof e.name)return e.name;const r=await t.evaluate(e,n);return"string"==typeof r?r:void 0}(e.modifiers.called,t,n);return{article:o,expression:i,constructorArgs:a,variableName:c}}async execute(e,t){const{expression:n,constructorArgs:r=[],variableName:s}=e,i="string"==typeof n&&n.startsWith("<"),o=i&&n.endsWith("/>")?function(e){const t=e.slice(1,-2);let n="div",r=t;const s=t.match(/^([a-zA-Z][a-zA-Z0-9]*)/);s&&(n=s[1],r=t.slice(s[0].length));const i=document.createElement(n),o=r.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}(n):i&&/<\/[a-zA-Z]/.test(n)?function(e){const t=document.createElement("template");t.innerHTML=e.trim();const n=t.content.firstElementChild;if(n&&bi(n))return n;const r=document.createElement("div");r.innerHTML=e.trim();const s=r.firstElementChild;return s&&bi(s)?s:r}(n):function(e,t,n){if(bi(e))return e;const r=e+"";let s;if("undefined"!=typeof window&&(s=window[r]),s||"undefined"==typeof global||(s=global[r]),!s&&n.variables?.has(r)&&(s=n.variables.get(r)),!s||"function"!=typeof s)throw Error(`Constructor '${r}' not found or is not a function`);return 0===t.length?new s:new s(...t)}(n,r,t);return Object.assign(t,{it:o}),s&&ho(s,o,t),o}},ri(t,"MakeCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),ni(t,r)})(),t})();const vo=vi(go),bo=vi((()=>{let e,t,n=[gi({description:"Remove all children from an element (sets innerHTML to empty)",syntax:["empty","empty <target>","empty the <target>"],examples:["empty me","empty #list","empty .results"],sideEffects:["dom-mutation"]}),yi({name:"empty",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){return{targets:await Ti(e.args,t,n,"empty",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)t.innerHTML=""}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>bi(e))}},ri(t,"EmptyCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),ni(t,r)})(),t})());function wo(e){return e.hasAttribute("popover")}const Eo=vi((()=>{let e,t,n=[gi({description:"Open a dialog, details element, or popover",syntax:["open [<target>]","open <dialog> as modal","open <dialog> as non-modal"],examples:["open","open #myDialog","open #details","open #popup as non-modal"],sideEffects:["dom-mutation"]}),yi({name:"open",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){const r=(e.args??[]).filter(e=>{const t=e;if("identifier"!==t?.type)return!0;const n=t.name?.toLowerCase();return"as"!==n&&"modal"!==n&&"non-modal"!==n&&"nonmodal"!==n}),s=_i(await Ti(r,t,n,"open",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)),i=await async function(e,t,n,r){if(t?.as){const e=await n.evaluate(t.as,r);if("string"==typeof e){const t=e.toLowerCase().trim();if("non-modal"===t||"nonmodal"===t)return"non-modal";if("modal"===t)return"modal"}}for(let t=0;e.length-1>t;t++){const s=e[t];if("identifier"===s?.type&&"as"===s.name?.toLowerCase()){const s=await n.evaluate(e[t+1],r);if("string"==typeof s){const e=s.toLowerCase().trim();if("non-modal"===e||"nonmodal"===e)return"non-modal";if("modal"===e)return"modal"}}}return"modal"}(e.args??[],e.modifiers??{},t,n);return{targets:s,dialogMode:i}}async execute(e,t){for(const t of e.targets)if(Hi(t))t.open||("modal"===e.dialogMode?t.showModal():t.show());else if(Ui(t))t.open=!0;else if(wo(t)){const e=t;if("function"==typeof e.showPopover)try{e.showPopover()}catch{}}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(!Array.isArray(t.targets)||!t.targets.every(e=>bi(e))||"modal"!==t.dialogMode&&"non-modal"!==t.dialogMode)}},ri(t,"OpenCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),ni(t,r)})(),t})());function xo(e){return e.hasAttribute("popover")}const ko=vi((()=>{let e,t,n=[gi({description:"Close a dialog, details element, or popover",syntax:["close","close <target>"],examples:["close","close #myDialog","close #details","close #popup"],sideEffects:["dom-mutation"]}),yi({name:"close",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){return{targets:_i(await Ti(e.args,t,n,"close",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers))}}async execute(e,t){for(const t of e.targets)if(Hi(t))t.open&&t.close();else if(Ui(t))t.open=!1;else if(xo(t)){const e=t;if("function"==typeof e.hidePopover)try{e.hidePopover()}catch{}}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>bi(e))}},ri(t,"CloseCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),ni(t,r)})(),t})());function So(e){const t=e.tagName;return"INPUT"===t||"TEXTAREA"===t}const Ao=vi((()=>{let e,t,n=[gi({description:"Select the contents of a text field, or select the contents of a DOM element",syntax:["select","select <target>"],examples:["select #search","select <textarea/>","select me"],sideEffects:["focus","dom-mutation"]}),yi({name:"select",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){return{targets:await Ti(e.args,t,n,"select",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){if(0!==e.targets.length)for(const t of e.targets){if(So(t)){t.select();continue}const e=t.ownerDocument??("undefined"!=typeof document?document:null),n=e?.defaultView;if(!e||!n)continue;const r=n.getSelection?.();if(r)try{const n=e.createRange();n.selectNodeContents(t),r.removeAllRanges(),r.addRange(n)}catch{}}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>bi(e))}},ri(t,"SelectCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),ni(t,r)})(),t})());function No(e){return"FORM"===e.tagName}const To=vi((()=>{let e,t,n=[gi({description:"Reset a <form> element to its default values (HTMLFormElement.reset())",syntax:["reset","reset <target>"],examples:["reset","reset #myForm","reset <form/>"],sideEffects:["dom-mutation"]}),yi({name:"reset",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){return{targets:await Ti(e.args,t,n,"reset",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)No(t)&&t.reset()}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>bi(e))}},ri(t,"ResetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),ni(t,r)})(),t})()),Co=vi((()=>{let e,t,n=[gi({description:"Focus an element (calls HTMLElement.focus())",syntax:["focus","focus <target>","focus on <target>"],examples:["focus","focus #search","focus on <input/>"],sideEffects:["focus"]}),yi({name:"focus",category:"execution"})],r=[];return t=class{async parseInput(e,t,n){return{targets:await Ti(e.args,t,n,"focus",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)t.focus()}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>bi(e))}},ri(t,"FocusCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),ni(t,r)})(),t})()),Oo=vi((()=>{let e,t,n=[gi({description:"Remove focus from an element (calls HTMLElement.blur())",syntax:["blur","blur <target>","blur on <target>"],examples:["blur","blur #search","blur on <input/>"],sideEffects:["focus"]}),yi({name:"blur",category:"execution"})],r=[];return t=class{async parseInput(e,t,n){return{targets:await Ti(e.args,t,n,"blur",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)t.blur()}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>bi(e))}},ri(t,"BlurCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),ni(t,r)})(),t})()),Ro=vi((()=>{let e,t,n=[gi({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"]}),yi({name:"set",category:"data"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("set command requires a target");const r=e.args[0],s=r?.name||r?.value,i=r?.type;if(i){const s=Ie(i);if(s)return{type:"node-write",node:r,value:await this.extractValue(e,t,n),writer:s}}const o=await this.resolveAttributeWriteTarget(r,e,t,n);if(o){const r=await this.extractValue(e,t,n);return{type:"attribute",elements:o.elements,name:o.name,value:r}}const a=await Qi(r,t,n);if(a){const r=await this.extractValue(e,t,n);if(a.property.startsWith("*")){const e=a.property.substring(1);return{type:"style",element:a.element,property:e,value:r+""}}return{type:"property",element:a.element,property:a.property,value:r}}if("memberExpression"===r?.type||"propertyAccess"===r?.type){const s=await this.tryParseMemberExpression(r,e,t,n);if(s)return s}let c;if(c="identifier"!==r?.type&&"variable"!==r?.type||"string"!=typeof s?await t.evaluate(r,n):s,function(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;if(bi(e)||e instanceof Node)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}(c))return{type:"object-literal",properties:c,targets:await this.resolveTargets(e.modifiers.on,t,n)};if(Xi(c)){const r=Yi(c,n);if(r){const s=await this.extractValue(e,t,n);return{type:"property",element:r.element,property:r.property,value:s}}return this.parseTheXofY(c,e,t,n)}if("string"==typeof c&&Ci(c)){const r=c.substring(1).trim(),s=await this.extractValue(e,t,n);return{type:"style",element:await this.resolveElement(e.modifiers.on,t,n),property:r,value:s+""}}if("string"==typeof c&&si(c)){const r=c.substring(1).trim(),s=await this.extractValue(e,t,n);return{type:"attribute",elements:await this.resolveTargets(e.modifiers.on,t,n),name:r,value:s}}if("string"==typeof c){const r=c.match(/^(my|me|its?|your?)\s+(.+)$/i);if(r){const s=Ai(r[1],n),i=await this.extractValue(e,t,n);return{type:"property",element:s,property:r[2],value:i}}}if(bi(c))return{type:"property",element:c,property:"textContent",value:await this.extractValue(e,t,n)};if(Array.isArray(c)&&c.length>0&&bi(c[0])){const r=await this.extractValue(e,t,n);return{type:"property",element:c[0],property:"textContent",value:r}}if("string"!=typeof c)throw Error("set command target must be a string or object literal"+("memberExpression"===r?.type||"propertyAccess"===r?.type?` (a property chain evaluated to ${null===c?"null":typeof c} — check that all intermediate objects exist)`:""));return{type:"variable",name:c,value:await this.extractValue(e,t,n)}}async execute(e,t){switch(e.type){case"variable":return ho(e.name,e.value,t),"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":for(const t of e.elements)t.setAttribute(e.name,e.value+"");return Object.assign(t,{it:e.value}),{target:"@"+e.name,value:e.value,targetType:"attribute"};case"property":return Zi(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"style":return Ri(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[n,r]of Object.entries(e.properties))Zi(t,n,r);return Object.assign(t,{it:e.properties}),{target:e.targets[0]||"unknown",value:e.properties,targetType:"property"};case"member-assignment":return e.container[e.property]=e.value,Object.assign(t,{it:e.value}),{target:e.property,value:e.value,targetType:"property"};case"node-write":return await e.writer(e.node,e.value,t),Object.assign(t,{it:e.value}),{target:e.node.name??"",value:e.value,targetType:"variable"};default:throw Error("Unknown input type: "+e.type)}}async resolveAttributeWriteTarget(e,t,n,r){const s=e;if("attributeAccess"===s?.type)return{elements:await this.resolveTargets(t.modifiers.on,n,r),name:s.attributeName};if("binaryExpression"===s?.type&&"of"===s.operator&&"attributeAccess"===s.left?.type){const e=await this.evaluateToElement(s.right,n,r);if(e)return{elements:[e],name:s.left.attributeName}}if("memberExpression"===s?.type&&"attributeAccess"===s.property?.type){const e=await this.evaluateToElement(s.object,n,r);if(e)return{elements:[e],name:s.property.attributeName}}return null}async evaluateToElement(e,t,n){const r=await t.evaluate(e,n),s=Array.isArray(r)?r[0]:r;return bi(s)?s:null}async tryParseMemberExpression(e,t,n,r){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=Ai(e,r),o=await this.extractValue(t,n,r);return{type:"property",element:s,property:i.name,value:o}}}const o=e.object,a=e.computed;if(o){const s=o;let c;if("memberExpression"===s.type&&!s.computed&&"style"===s.property?.name&&s.object){const e=await n.evaluate(s.object,r);c=(e&&"object"==typeof e&&"style"in e?e.style:void 0)??await n.evaluate(o,r)}else c=await n.evaluate(o,r);if(null!=c&&"object"==typeof c){const s=a?await n.evaluate(e.property,r)+"":i?.name||"";if(s)return{type:"member-assignment",container:c,property:s,value:await this.extractValue(t,n,r)}}}return null}async extractValue(e,t,n){if(e.modifiers.to)return t.evaluate(e.modifiers.to,n);const r=e.args.findIndex(e=>"identifier"===e.type&&"to"===e.name);if(r>=0&&e.args.length>r+1)return t.evaluate(e.args[r+1],n);if(e.args.length>=2)return t.evaluate(e.args[1],n);throw Error('set command requires a value (use "to" keyword)')}async resolveElement(e,t,n){return xi(e?await t.evaluate(e,n):void 0,n)}async resolveTargets(e,t,n){return ki(e?await t.evaluate(e,n):void 0,n)}async parseTheXofY(e,t,n,r){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=xi(o,r),c=await this.extractValue(t,n,r);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&&Array.isArray(t.elements)&&t.elements.every(bi)&&"value"in t;case"property":return"string"==typeof t.property&&bi(t.element)&&"value"in t;case"style":return"string"==typeof t.property&&""!==t.property&&bi(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}}},ri(t,"SetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),ni(t,r)})(),t})());function $o(e){return e&&"object"==typeof e&&e.type||"unknown"}let Lo=(()=>{let e,t,n=[gi({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"]}),yi({name:"increment",category:"data"})],r=[];return t=class{async parseInput(e,t,n){const r="decrement"===e.commandName?.toLowerCase()?"decrement":"increment",s=await async function(e,t,n,r){if(!e.args||0===e.args.length)throw Error(r+" command requires a target");const s=e.args[0];let i,o,a;const c=$o(s);if("identifier"===c)i=s.name,s.scope&&(o=s.scope);else if("literal"===c)i=s.value;else{const e=Ie(c);if(e){const r=await t.evaluate(s,n),o="number"==typeof r?r:null==r?0:Number(r)||0;i=o,a={node:s,writer:e,currentValue:o}}else{const e=await t.evaluate(s,n);i=Array.isArray(e)&&e.length>0?e[0]:e}}let l=1,u=o;for(let r=1;e.args.length>r;r++){const s=e.args[r];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,n);"number"==typeof e&&(l=e)}}const f=e.modifiers?.by;if(f){const e=f.value;if("literal"===$o(f)&&"number"==typeof e)l=e;else if("literal"!==$o(f)){const e=await t.evaluate(f,n);"number"==typeof e&&(l=e)}}return{target:i,amount:l,...u&&{scope:u},...a&&{customWrite:a}}}(e,t,n,r);return{...s,operation:r}}async execute(e,t){const{target:n,property:r,scope:s,amount:i=1,operation:o="increment",customWrite:a}=e;if(a){const e=isFinite(i)?i:1,n="increment"===o?a.currentValue+e:a.currentValue-e;return await a.writer(a.node,n,t),Object.assign(t,{it:n}),n}const c=function(e,t,n,r){if("number"==typeof e)return e;if(bi(e)){const n=e;return t?t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)?uo(n.getAttribute(t)):uo(n[t]):uo(n.value||n.textContent)}return"string"==typeof e?"global"===n?uo(fo(e,r,"global")):e.includes(".")?function(e,t){const n=e.split("."),r=n[1],s=po(n[0],t);return s?uo(s[r]):0}(e,r):uo("me"===e&&r.me?r.me.value||0:"it"===e?r.it||0:"you"===e&&r.you?r.you.value||0:fo(e,r)):uo(e)}(n,r,s,t);let l;if(isNaN(c))l=NaN;else{const e=isFinite(i)?i:1;l="increment"===o?c+e:c-e}return function(e,t,n,r,s){if(bi(e)){const n=e;return void(t?t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)?n.setAttribute(t,r+""):n[t]=r:"value"in n&&void 0!==n.value?n.value=r+"":n.textContent=r+"")}if("string"==typeof e){if("global"===n)return void ho(e,r,s,"global");if(e.includes("."))return void function(e,t,n){const r=e.split("."),s=r[1],i=po(r[0],n);i&&(i[s]=t)}(e,r,s);if("me"===e&&s.me)return void(s.me.value=r);if("it"===e)return void Object.assign(s,{it:r});if("you"===e&&s.you)return void(s.you.value=r);ho(e,r,s)}}(n,r,s,l,t),Object.assign(t,{it:l}),l}},ri(t,"NumericModifyCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),ni(t,r)})(),t})();const jo=vi(Lo),Io=vi(Lo);function Mo(e){const t=e.tagName;return"INPUT"===t||"TEXTAREA"===t||"SELECT"===t}const Do=vi((()=>{let e,t,n=[gi({description:"Reset a variable to null or clear the value of a form field (<input>, <textarea>, <select>)",syntax:["clear <var>","clear :var","clear <target>"],examples:["clear :count","clear myVar","clear #search","clear <textarea/>"],sideEffects:["state-mutation","dom-mutation"]}),yi({name:"clear",category:"data"})],r=[];return t=class{async parseInput(e,t,n){const r=e.args?.[0],s=r?.type,i=r?.name;if(r&&("variable"===s||"identifier"===s&&"string"==typeof i))try{const e=await t.evaluate(r,n);if(!bi(e)&&!Array.isArray(e))return{type:"variable",name:i}}catch{return{type:"variable",name:i}}return{type:"form-fields",targets:await Ti(e.args,t,n,"clear",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){if("variable"===e.type)return t.locals.set(e.name,null),void Object.assign(t,{it:null});for(const t of e.targets)Mo(t)&&("SELECT"===t.tagName?t.selectedIndex=-1:t.value="")}validate(e){if("object"!=typeof e||null===e)return!1;if("variable"===e.type)return"string"==typeof e.name;if("form-fields"===e.type){const t=e.targets;return Array.isArray(t)&&t.every(e=>bi(e))}return!1}},ri(t,"ClearCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),ni(t,r)})(),t})());function Po(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 Fo=(()=>{let e,t,n=[gi({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"]}),yi({name:"trigger",category:"event"})],r=[];return t=class{async parseInput(e,t,n){const r="send"===e.commandName?.toLowerCase()?"send":"trigger",s=r;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)||"callExpression"===i(o)){a=o.name||o.callee?.name;const e=o.args||o.arguments;e?.length&&(c=await this.parseEventDetail(e,t,n))}else if("identifier"===i(o)||"keyword"===i(o))a=o.name;else{const e=await t.evaluate(o,n);a="string"==typeof e?e:e+""}const u=e.modifiers?.on||e.modifiers?.to;if(u)l=await this.resolveTargets([u],t,n,s);else{const r=e.args.findIndex((e,t)=>{if(0===t)return!1;const n=e.name||e.value;return"on"===n||"to"===n});if(-1!==r&&e.args.length-1>r){const i=e.args.slice(r+1),o=i.findIndex(e=>"with"===(e.name||e.value)),a=-1===o?i:i.slice(0,o);l=await this.resolveTargets(a,t,n,s)}else{if(!n.me)throw Error(s+": no target specified and context.me is null");l=[n.me]}}return{eventName:a,detail:c,targets:l,options:await this.parseEventOptions(e.args,t,n),mode:r}}async execute(e,t){const n=function(e,t,n={}){return new CustomEvent(e,{detail:void 0!==t?t:{},bubbles:void 0===n.bubbles||n.bubbles,cancelable:void 0===n.cancelable||n.cancelable,composed:void 0!==n.composed&&n.composed})}(e.eventName,e.detail,e.options);for(const t of e.targets)t.dispatchEvent(n);t.it=n}async resolveTargets(e,t,n,r){const s=[];for(const r of e){const e=await t.evaluate(r,n);if("window"!==e&&e!==window)if("document"!==e&&e!==document)if("me"===e&&n.me)s.push(n.me);else if("you"===e&&n.you)s.push(n.you);else if("it"===e&&n.it)s.push(n.it);else if(bi(e))s.push(e);else if(e instanceof NodeList)s.push(...Array.from(e).filter(bi));else if(Array.isArray(e))s.push(...e.filter(bi));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(bi));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(r+": no valid targets");return s}async parseEventDetail(e,t,n){if(!e?.length)return;if(1===e.length){const r=e[0];if("objectLiteral"!==r?.type)return await t.evaluate(r,n)}const r={};for(const s of e){const e=await t.evaluate(s,n);if("object"!=typeof e||null===e||Array.isArray(e)){if("string"==typeof e&&e.includes(":")){const[t,n]=e.split(":",2);r[t.trim()]=Po(n.trim())}}else Object.assign(r,e)}return Object.keys(r).length?r:void 0}async parseEventOptions(e,t,n){const r={bubbles:!0,cancelable:!0,composed:!1},s=e.findIndex(e=>"with"===(e.name||e.value));if(-1===s)return r;for(const i of e.slice(s+1)){const e=await t.evaluate(i,n);if("string"==typeof e){const t=e.toLowerCase();"bubbles"===t?r.bubbles=!0:"nobubbles"===t?r.bubbles=!1:"cancelable"===t?r.cancelable=!0:"nocancelable"===t?r.cancelable=!1:"composed"===t&&(r.composed=!0)}}return r}},ri(t,"EventDispatchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),ni(t,r)})(),t})();const Bo=vi(Fo),qo=vi(Fo);function Vo(e,t,n,r){return e?new Promise(n=>{const s=()=>{i({event:null,timedOut:!1,cancelled:!0})},i=function(n,i){let a=!1;return n=>{a||(a=!0,e.removeEventListener(t,o),r&&r.removeEventListener("abort",s),i(n))}}(0,n),o=e=>{i({event:e,timedOut:!1,cancelled:!1})};r?.aborted?n({event:null,timedOut:!1,cancelled:!0}):(e.addEventListener(t,o),r&&r.addEventListener("abort",s))}):Promise.reject(Error("waitForEvent: no target provided"))}function _o(e){return new Promise(t=>setTimeout(t,e))}const Ho=vi((()=>{let e,t,n=[gi({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"]}),yi({name:"wait",category:"async"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("wait command requires an argument");if(e.modifiers.or)return this.parseRaceCondition(e,t,n);if(e.modifiers.for)return this.parseEventWait(e.modifiers.for,e.modifiers.from,t,n);const r=e.args[0];return"arrayLiteral"===r.type&&r.elements?this.parseEventArrayWait(r.elements,e.args[1],t,n):this.parseTimeWait(e.args[0],t,n)}async execute(e,t){const n=Date.now();if("time"===e.type)return await _o(e.milliseconds),{type:"time",result:e.milliseconds,duration:Date.now()-n};if("event"===e.type){const r=e.target??t.me??document,s=(await Vo(r,e.eventName)).event;if(Object.assign(t,{it:s}),e.destructure)for(const n of e.destructure)n in s&&t.locals.set(n,s[n]);return{type:"event",result:s,duration:Date.now()-n}}const{result:r,winningCondition:s}=await this.executeRace(e.conditions,t);if(Object.assign(t,{it:r}),r instanceof Event&&"event"===s?.type&&s.destructure)for(const e of s.destructure)e in r&&t.locals.set(e,r[e]);return{type:r instanceof Event?"event":"time",result:r,duration:Date.now()-n}}async parseTimeWait(e,t,n){return{type:"time",milliseconds:Vi(await t.evaluate(e,n))}}async parseEventWait(e,t,n,r){const s=await n.evaluate(e,r);if("string"!=typeof s)throw Error("wait for: event name must be a string");const i=s.match(/^(\w+)\(([^)]+)\)$/),o=i?i[1]:s,a=i?i[2].split(",").map(e=>e.trim()):void 0;let c;if(t){const e=await n.evaluate(t,r);if(!e||"object"!=typeof e||!("addEventListener"in e))throw Error("wait for from: target must be an EventTarget");c=e}else c=r.me??void 0;return{type:"event",eventName:o,target:c,destructure:a}}async parseEventArrayWait(e,t,n,r){const s=[];for(const t of e){const e=t;if("objectLiteral"===e.type&&e.properties){let t="",n=[];for(const r of e.properties){const e=r.key?.name||r.key?.value;"name"===e&&r.value?t=r.value.value||"":"args"===e&&r.value?.elements&&(n=r.value.elements.map(e=>e.value||e.name||""))}t&&s.push({name:t,params:n})}}let i;if(t){const e=await n.evaluate(t,r);e&&"object"==typeof e&&"addEventListener"in e&&(i=e)}return i||(i=r.me??void 0),1===s.length?{type:"event",eventName:s[0].name,target:i,destructure:s[0].params.length>0?s[0].params:void 0}:{type:"race",conditions:s.map(e=>({type:"event",eventName:e.name,target:i,destructure:e.params.length>0?e.params:void 0}))}}async parseRaceCondition(e,t,n){const r=[];e.modifiers.for?r.push(await this.parseEventWait(e.modifiers.for,e.modifiers.from,t,n)):e.args[0]&&r.push(await this.parseTimeWait(e.args[0],t,n));const s=await t.evaluate(e.modifiers.or,n),i=Array.isArray(s)?s:[s];for(const e of i)try{r.push({type:"time",milliseconds:Vi(e)})}catch{if("string"==typeof e){const t=e.match(/^(\w+)\(([^)]+)\)$/);r.push(t?{type:"event",eventName:t[1],target:n.me??void 0,destructure:t[2].split(",").map(e=>e.trim())}:{type:"event",eventName:e,target:n.me??void 0})}}if(2>r.length)throw Error("wait: race requires at least 2 conditions");return{type:"race",conditions:r}}async executeRace(e,t){const n=new AbortController,r=n.signal,s=e.map(e=>"time"===e.type?_o(e.milliseconds).then(()=>({result:e.milliseconds,winningCondition:e})):Vo(e.target??t.me??document,e.eventName,0,r).then(t=>({result:t.event,winningCondition:e})));try{return await Promise.race(s)}finally{n.abort()}}},ri(t,"WaitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),ni(t,r)})(),t})()),Uo=new Map;let zo=[/^4\d{2}$/,/^5\d{2}$/],Wo=(()=>{let e,t,n=[gi({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"]}),yi({name:"fetch",category:"async"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("fetch requires a URL");const r=await this.parseURL(e.args[0],t,n),s=this.parseResponseType(e.modifiers.as);return{url:r,responseType:s,options:await this.parseRequestOptions(e.modifiers.with,t,n),throwOnError:!e.modifiers.doNotThrow&&"response"!==s}}async execute(e,t){const n=Date.now(),{url:r,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},l=Uo.get(s);if(l?.accept){const e=new Headers(c.headers);e.has("Accept")||e.set("Accept",l.accept),c.headers=e}if(t.me){const e={...c,sender:t.me,headers:c.headers||{}};this.dispatchEvent(t.me,"fetch:beforeRequest",e),c.headers=e.headers}let u;i.timeout&&(u=setTimeout(()=>o.abort(),i.timeout));try{let i=await fetch(r,c);if(t.me){const e={response:i};this.dispatchEvent(t.me,"fetch:afterResponse",e),i=e.response}if(e.throwOnError&&function(e){const t=e+"";return zo.some(e=>e.test(t))}(i.status)){const e=Error(`Fetch failed for ${r}: HTTP ${i.status} ${i.statusText}`.trim());throw e.response=i,e.isFetchStatusError=!0,e}const o=await this.handleResponse(i,s,t);t.me&&this.dispatchEvent(t.me,"fetch:afterRequest",{result:o});const a={status:i.status,statusText:i.statusText,headers:i.headers,data:o,url:i.url,duration:Date.now()-n};return Object.assign(t,{it:o}),a}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 "+r);if(e instanceof Error&&!0===e.isFetchStatusError)throw e;throw Error(`Fetch failed for ${r}: ${e instanceof Error?e.message:e+""}`)}finally{u&&clearTimeout(u),t.me&&a&&t.me.removeEventListener("fetch:abort",a)}}async parseURL(e,t,n){const r=await t.evaluate(e,n);if("string"!=typeof r||!r)throw Error("fetch: URL must be a non-empty string");return r}parseResponseType(e){if(!e)return"text";if(("identifier"===e.type||"expression"===e.type)&&e.name){const t=e.name.toLowerCase();if("object"===t)return"json";if(["text","json","html","response","blob","arraybuffer"].includes(t))return"arraybuffer"===t?"arrayBuffer":t;if(Uo.has(t))return t;throw Error(`fetch: invalid response type "${t}"`)}return"text"}async parseRequestOptions(e,t,n){if(!e)return{};const r=await t.evaluate(e,n);if("object"!=typeof r||null===r)throw Error('fetch: "with" options must be an object');const s={};return"method"in r&&(s.method=(r.method+"").toUpperCase()),"headers"in r&&(s.headers=this.parseHeaders(r.headers)),"body"in r&&(s.body=this.parseBody(r.body)),"credentials"in r&&(s.credentials=r.credentials),"mode"in r&&(s.mode=r.mode),"cache"in r&&(s.cache=r.cache),s}parseHeaders(e){if(e instanceof Headers)return e;const t=new Headers;if("object"==typeof e&&null!==e)for(const[n,r]of Object.entries(e))t.set(n,r+"");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,n){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();case"text":return e.text();default:{const r=Uo.get(t);return r?r.handler(e,n):e.text()}}}parseHTML(e){const t=(new DOMParser).parseFromString(e,"text/html"),n=document.createDocumentFragment();return Array.from(t.body.childNodes).forEach(e=>n.appendChild(e.cloneNode(!0))),1===n.childNodes.length&&bi(n.firstChild)?n.firstChild:n}dispatchEvent(e,t,n){e.dispatchEvent(new CustomEvent(t,{detail:n,bubbles:!0,cancelable:!0}))}},ri(t,"FetchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),ni(t,r)})(),t})();const Jo=vi(Wo),Zo=vi((()=>{let e,t,n=[gi({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"]}),yi({name:"go",category:"navigation"})],r=[];return t=class{async parseInput(e,t,n){return e.args&&0!==e.args.length?{args:await Promise.all(e.args.map(e=>t.evaluate(e,n)))}:{args:[]}}async execute(e,t){const{args:n}=e;if(0===n.length)throw Error("Go command requires arguments");if("string"==typeof n[0]&&"back"===n[0].toLowerCase())return await this.goBack(),{result:"back",type:"back"};if(this.isUrlNavigation(n))return{result:await this.navigateToUrl(n,t),type:"url"};const r=this.findBareUrl(n);return null!==r?{result:await this.navigateToBareUrl(r,n),type:"url"}:{result:await this.scrollToElement(n,t),type:"scroll"}}isUrlNavigation(e){return-1!==e.findIndex(e=>"url"===e)}isBareUrl(e){return!!e.startsWith("/")||/^[a-z][a-z0-9+.-]*:/i.test(e)}findBareUrl(e){for(const t of e)if("to"!==t&&"the"!==t)return"string"==typeof t&&this.isBareUrl(t)?t:null;return null}async navigateToBareUrl(e,t){if(t.includes("new")&&t.includes("window")){if("undefined"!=typeof window&&window.open){const t=window.open(e,"_blank");t?.focus&&t.focus()}}else e.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=e):"undefined"!=typeof window&&(window.location.assign?.(e)??(window.location.href=e));return e}async goBack(){if("undefined"==typeof window||!window.history)throw Error("Browser history API not available");window.history.back()}async navigateToUrl(e,t){const n=e.findIndex(e=>"url"===e),r=e[n+1];if(!r)throw Error('URL is required after "url" keyword');const s="string"==typeof r?r:r+"",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 n=this.parseScrollPosition(e),r=this.parseScrollTarget(e),s=this.parseScrollOffset(e),i=!e.includes("instantly"),o=this.resolveScrollTarget(r,t);if(!o)throw Error("Target element not found: "+r);if("undefined"!=typeof window){const e=i?"smooth":"instant",t=this.mapVerticalPosition(n.vertical),r=this.mapHorizontalPosition(n.horizontal);if(0!==s){o.scrollIntoView?.({behavior:e,block:t,inline:r});const{x:i,y:a}=this.calculateScrollPosition(o,n,s);window.scrollTo?.({left:i,top:a,behavior:e})}else o.scrollIntoView?.({behavior:e,block:t,inline:r})}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"},n=["top","middle","bottom"],r=["left","center","right"];let s=!1,i=!1;for(const o of e)"string"==typeof o&&(n.includes(o)?(t.vertical=o,s=!0):r.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 n=e[t+1];return"the"===n&&e.length>t+2&&(n=e[t+2]),n}for(const t of e)if("object"==typeof t&&t&&t.nodeType)return t;const n=["top","middle","bottom","left","center","right","of","the","to","smoothly","instantly"];for(const t of e)if("string"==typeof t&&!n.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 n=e[t];if("string"==typeof n){const e=n.match(/^([+-]?\d+)(px)?$/);if(e)return parseInt(e[1],10)}if(("+"===n||"-"===n)&&e.length>t+1){const r=e[t+1],s="number"==typeof r?r:parseInt((r+"").replace("px",""),10);if(!isNaN(s))return"-"===n?-s:s}}return 0}resolveScrollTarget(e,t){if("object"==typeof e&&e&&e.nodeType)return e;const n="string"==typeof e?e:e+"";if("body"===n&&"undefined"!=typeof document)return document.body;if("html"===n&&"undefined"!=typeof document)return document.documentElement;if("me"===n&&bi(t.me))return t.me;if("it"===n&&bi(t.it))return t.it;if("you"===n&&bi(t.you))return t.you;const r=fo(n,t);if(bi(r))return r;if("undefined"!=typeof document)try{const e=document.querySelector(n);if(e)return e}catch{try{const e=document.getElementsByTagName(n);if(e.length>0)return e[0]}catch{}}return null}calculateScrollPosition(e,t,n){if("undefined"==typeof window||!e.getBoundingClientRect)return{x:0,y:0};const r=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=r.left+s;break;case"center":c=r.left+s+r.width/2-o/2;break;case"right":c=r.right+s-o}switch(t.vertical){case"top":l=r.top+i+n;break;case"middle":l=r.top+i+r.height/2-a/2+n;break;case"bottom":l=r.bottom+i-a+n}return{x:Math.max(0,c),y:Math.max(0,l)}}},ri(t,"GoCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),ni(t,r)})(),t})()),Ko=vi((()=>{let e,t,n=[gi({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"]}),yi({name:"log",category:"utility"})],r=[];return t=class{async parseInput(e,t,n){return e.args&&0!==e.args.length?{values:await Promise.all(e.args.map(e=>t.evaluate(e,n)))}:{values:[]}}async execute(e,t){const n="undefined"!=typeof window?window.console:console;0===e.values.length?n.log():n.log(...e.values)}validate(e){return"object"==typeof e&&null!==e&&Array.isArray(e.values)}},ri(t,"LogCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),ni(t,r)})(),t})()),Go=vi((()=>{let e,t,n=[gi({description:"Drop into the debugger (emits a debugger; statement)",syntax:["breakpoint"],examples:["breakpoint","on click breakpoint"],sideEffects:["debugging"]}),yi({name:"breakpoint",category:"utility"})],r=[];return t=class{async parseInput(e,t,n){return{}}async execute(e,t){}validate(e){return"object"==typeof e&&null!==e}},ri(t,"BreakpointCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ti(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),ni(t,r)})(),t})()),Xo=function(e,t){const n=new $r(null);for(const t of e)n.register(t);return new qr({registry:n,expressionRegistry:t.expressionRegistry,enableAsyncCommands:t.enableAsyncCommands??!0,commandTimeout:t.commandTimeout??1e4,enableErrorReporting:t.enableErrorReporting??!0,enableResultPattern:t.enableResultPattern??!0})}([Di(),Bi(),ro(),oo(),co(),lo(),vo(),bo(),Eo(),ko(),Ao(),To(),Co(),Oo(),Ro(),jo(),Io(),Do(),qo(),Bo(),Ho(),Jo(),Zo(),Ko(),Go()],{expressionRegistry:Qs()}),Yo={parse:e=>Ht(e),execute:async(e,t)=>{const n=function(e){if(!e)return Ar();if(e.locals instanceof Map&&e.globals instanceof Map&&e.flags)return e;const t=Ar(e.me instanceof Element?e.me:null);return void 0!==e.it&&(t.it=e.it),void 0!==e.you&&(t.you=e.you),void 0!==e.result&&(t.result=e.result),void 0!==e.event&&Object.assign(t,{event:e.event}),t}(t),r=Ht(e);if(!r.success||!r.node)throw Error(r.error?.message||"Parse failed");return await Xo.execute(r.node,n)}},Qo=function(e){return new ei(e)}(Yo),ea={runtime:Yo,parse:e=>Yo.parse(e),execute:async(e,t)=>Yo.execute(e,t),createContext:Ar,attributeProcessor:Qo,version:"1.1.0-standard-v2-tree-shakeable",commands:["add","remove","toggle","show","hide","put","make","empty","open","close","select","reset","focus","blur","set","increment","decrement","clear","send","trigger","wait","fetch","go","log","breakpoint"],eval:async(e,t)=>Yo.execute(e,t),init:()=>{Qo.init()}};"undefined"!=typeof window&&(window.hyperfixi=ea,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{Qo.init()}):Qo.init());class ta{constructor(){this.name="addition",this.category="Special",this.syntax="left + right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=Gr(e,"left operand");return{success:!0,value:Yr(r+Gr(n,"right operand"),"addition"),type:"number"}}catch(e){return{success:!1,errors:[rs("runtime-error","Addition failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){const t=function(e){if(null==e)return ns([rs("missing-argument","Input is null or undefined")],["Provide an object with left and right operands"]);if("object"!=typeof e)return ns([rs("type-mismatch","Expected object, got "+typeof e)],["Provide an object with left and right operands"]);const t=e;if(!("left"in t)||!("right"in t)){const e=[];return"left"in t||e.push("left"),"right"in t||e.push("right"),ns([rs("missing-argument",`Missing ${e.join(" and ")} operand${e.length>1?"s":""}`)],["Provide { left: value, right: value }"])}return{isValid:!0,errors:[],suggestions:[]}}(e);if(!t.isValid)return t;const{left:n,right:r}=e;return Qr(n)?Qr(r)?{isValid:!0,errors:[],suggestions:[]}:{isValid:!1,errors:[rs("type-mismatch","Right operand cannot be converted to number: "+r)],suggestions:["Provide a numeric value for right operand"]}:{isValid:!1,errors:[rs("type-mismatch","Left operand cannot be converted to number: "+n)],suggestions:["Provide a numeric value for left operand"]}}}const na={addition:new ta,subtraction:new class{constructor(){this.name="subtraction",this.category="Special",this.syntax="left - right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=Gr(e,"left operand");return{success:!0,value:Yr(r-Gr(n,"right operand"),"subtraction"),type:"number"}}catch(e){return{success:!1,errors:[rs("runtime-error","Subtraction failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new ta).validate(e)}},multiplication:new class{constructor(){this.name="multiplication",this.category="Special",this.syntax="left * right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=Gr(e,"left operand");return{success:!0,value:Yr(r*Gr(n,"right operand"),"multiplication"),type:"number"}}catch(e){return{success:!1,errors:[rs("runtime-error","Multiplication failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new ta).validate(e)}},division:new class{constructor(){this.name="division",this.category="Special",this.syntax="left / right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=function(e,t,n=!0){if(0===t){if(n)return 0===e?NaN:e>0?1/0:-1/0;throw Error("Division by zero")}return e/t}(Gr(e,"left operand"),Gr(n,"right operand"),!0);return{success:!0,value:r,type:"number"}}catch(e){return{success:!1,errors:[rs("runtime-error","Division failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new ta).validate(e)}},modulo:new class{constructor(){this.name="modulo",this.category="Special",this.syntax="left mod right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=function(e,t){if(0===t)throw Error("Modulo by zero");return e%t}(Gr(e,"left operand"),Gr(n,"right operand"));return{success:!0,value:r,type:"number"}}catch(e){return{success:!1,errors:[rs("runtime-error","Modulo failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric and divisor is not zero"]}}}validate(e){return(new ta).validate(e)}},power:new class{constructor(){this.name="power",this.category="Special",this.syntax="left ** right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=Gr(e,"left operand"),s=Gr(n,"right operand");return{success:!0,value:Yr(Math.pow(r,s),"power"),type:"number"}}catch(e){return{success:!1,errors:[rs("runtime-error","Power failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new ta).validate(e)}}};var ra=Object.freeze({__proto__:null,conversion:Hn,conversionExpressions:Hn,createCommonRegistry:Qs,createCoreRegistry:function(){return Vr(Ur,Ms,qs)},createExpressionRegistry:Vr,createFullExpressionRegistry:function(){return Vr(Ur,Ms,Hn,Ys,Jn,qs,na)},createFullRegistry:function(){return Vr(Ur,Ms,qs,Hn,Ys,Jn)},logical:Ms,logicalExpressions:Ms,positional:Ys,positionalExpressions:Ys,properties:Jn,propertiesExpressions:Jn,references:Ur,referencesExpressions:Ur,special:qs,specialExpressions:qs});return ea}();
1
+ var hyperfixi=function(){"use strict";const e="then",t="else",n="end",r="and",s="for",i="while",o="until",a="forever",c="times",l="index",u="in",f="to",h="from",d="with",p="of",m="on",y="event",g="behavior",v="global",b="the",w="start",E=new Set(["add","append","async","beep","blur","break","breakpoint","call","clear","close","continue","copy","decrement","default","empty","exit","fetch","focus","for","get","go","halt","hide","open","if","increment","install","js","log","make","measure","morph","pick","process","push","put","remove","render","repeat","replace","reset","return","scroll","select","send","set","settle","show","start","swap","take","tell","throw","toggle","transition","trigger","unless","wait"]),x=new Set(["put","trigger","send","remove","take","toggle","set","show","hide","add","halt","measure","js","tell","pick","start","swap","morph","push","replace","process"]),k=(new Set(["if","unless","repeat","wait","for","while"]),"at start of"),S="at end of",A=["into","before","after","at",k,S,"at the start of","at the end of"],N=new Set(["if","else","unless","for","while","until","end","and","or","not","in","to","from","into","with","without","as","matches","contains","then","on","when","every","init","def","behavior","the","of","first","last"]),T=e=>E.has(e.toLowerCase()),C=e=>x.has(e.toLowerCase()),O=e=>N.has(e.toLowerCase()),R=e=>$.has(e.toLowerCase()),$=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"]),L=new Set(["me","it","you","result","my","its","your"]),j=new Set(["and","or","not","no"]),I=new Set(["==","!=","===","!==","<",">","<=",">=","is","is not","am","is a","is an","is not a","is not an","precedes","does not precede","follows","does not follow","contains","starts with","ends with","does not start with","does not end with","has","have","does not contain","include","includes","does not include","match","matches","exists","does not exist","is empty","is not empty","is in","is not in","is between","is not between","equals","in","is equal to","is really equal to","is not equal to","is not really equal to","is greater than","is less than","is greater than or equal to","is less than or equal to","really equals","am in","am not in","am between","am not between","is really","is not really","is equal","is not equal","contain","do not contain","does not contains","do not match","does not match","ignoring case","sorted by","mapped to","split by","joined by"]),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","toggle"]),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 P;!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"}(P||(P={}));const F=new Set(["+","-","*","/","mod"]),B=new Set(["ms","s","seconds","minutes","hours","days"]);function q(e,t=1){const n=e.position+t;return e.input.length>n?e.input[n]:""}function V(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 _(e){const t=e.input,n=t.length;for(;n>e.position;){const n=t[e.position];if(" "!==n&&"\t"!==n&&"\r"!==n&&"\n"!==n)break;V(e)}}function H(e,t,n,r,s){const i=r??e.position-n.length,o=e.position;let a=e.column-n.length;if(void 0!==r){a=1;let t=-1;for(let n=0;r>n;n++)"\n"!==e.input[n]&&"\r"!==e.input[n]||(t=n);a=r-t}const c={kind:t,value:n,start:i,end:o,line:U(e,i),column:a};e.tokens.push(c)}function U(e,t){let n=1;for(let r=0;t>r&&e.input.length>r;r++){const t=e.input[r];"\n"===t?n++:"\r"===t&&(n++,e.input.length>r+1&&"\n"===e.input[r+1]&&r++)}return n}function z(e){const t=e.position;let n="";for(V(e),V(e);e.input.length>e.position&&"\n"!==e.input[e.position];)n+=V(e);H(e,P.COMMENT,"--"+n,t)}function W(e){const t=e.position,n=V(e);let r=n;for(;e.input.length>e.position;){const t=V(e);if(r+=t,t===n)break;"\\"===t&&e.input.length>e.position&&(r+=V(e))}H(e,P.STRING,r,t)}function J(e){const t=e.position;V(e);let n="";for(;e.input.length>e.position;){const t=e.input[e.position];if("`"===t){V(e);break}if("\\"===t){if(V(e),e.input.length>e.position){const t=V(e);switch(t){case"n":n+="\n";break;case"t":n+="\t";break;case"r":n+="\r";break;case"\\":n+="\\";break;case"`":n+="`";break;default:n+=t}}}else n+=V(e)}if(e.position>=e.input.length&&!e.input.endsWith("`"))throw Error(`Unterminated template literal at line ${e.line}, column ${e.column-n.length}`);H(e,P.TEMPLATE,n,t)}function Z(e){const t=e.position;let n=V(e);if(e.input.length>e.position&&"{"===e.input[e.position]){for(n+=V(e);e.input.length>e.position;){const t=e.input[e.position];if(n+=V(e),"}"===t)break}H(e,P.SELECTOR,n,t)}else{for(;e.input.length>e.position;){const t=e.input[e.position];if("\\"===t)V(e),e.input.length>e.position&&(n+=V(e));else{if(!ne(t)&&"-"!==t&&"_"!==t&&":"!==t)break;n+=V(e)}}H(e,P.SELECTOR,n,t)}}function K(e){const t=e.position;if(re(e))return void function(e,t){const n=e.input;let r="",s=0,i="";for(;n.length>e.position;){const t=n[e.position];if(i)r+=V(e),t===i&&(i="");else if('"'!==t&&"'"!==t){if("<"===t){if("/"===n[e.position+1]){for(;n.length>e.position&&">"!==n[e.position];)r+=V(e);if(n.length>e.position&&(r+=V(e)),s--,0>=s)break;continue}let t=!1,i="";for(;n.length>e.position;){const s=n[e.position];if(i)r+=V(e),s===i&&(i="");else if('"'!==s&&"'"!==s){if(">"===s){t="/"===n[e.position-1],r+=V(e);break}r+=V(e)}else i=s,r+=V(e)}if(t||s++,0>=s)break;continue}r+=V(e)}else i=t,r+=V(e)}H(e,P.SELECTOR,r,t)}(e,t);let n="";for(n+=V(e);e.input.length-1>e.position;){const t=e.input[e.position],r=e.input[e.position+1];if(n+=V(e),"/"===t&&">"===r){n+=V(e);break}}H(e,P.SELECTOR,n,t)}function G(e){const t=e.position;let n=V(e);for(;e.input.length>e.position;){const t=e.input[e.position];if(!ne(t)&&"_"!==t&&"-"!==t)break;n+=V(e)}H(e,P.SYMBOL,n,t)}function X(e){const t=e.position;let n="";const r=e.input[e.position];if(("'"===r||"'"===r)&&"s"===q(e,1))return n="'s",V(e),V(e),void H(e,P.OPERATOR,n,t);const s=e.input.substring(e.position,e.position+2),i=e.input.substring(e.position,e.position+3);["===","!=="].includes(i)?(n=i,V(e),V(e),V(e)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(s)?(n=s,V(e),V(e)):n=V(e),H(e,P.OPERATOR,n,t)}function Y(e){const t=e.position,n=e.input,r=n.length;let s="";for(;r>e.position;){const t=n[e.position];if("0">t||t>"9")break;s+=V(e)}if(r>e.position&&"."===n[e.position]&&(e.position+1>=r||"."!==n[e.position+1]))for(s+=V(e);r>e.position;){const t=n[e.position];if("0">t||t>"9")break;s+=V(e)}if(r>e.position){const t=n[e.position];if("e"===t||"E"===t){const t=r>e.position+1?n[e.position+1]:"",i=r>e.position+2?n[e.position+2]:"";if(t>="0"&&"9">=t||!("+"!==t&&"-"!==t||"0">i||i>"9"))for(s+=V(e),"+"!==n[e.position]&&"-"!==n[e.position]||(s+=V(e));r>e.position;){const t=n[e.position];if("0">t||t>"9")break;s+=V(e)}}}const i=e.position;let o="";for(;r>e.position;){const t=n[e.position];if(("a">t||t>"z")&&("A">t||t>"Z"))break;o+=V(e)}B.has(o)?H(e,P.TIME,s+o,t):(e.position=i,H(e,P.NUMBER,s,t))}function Q(e){const t=e.position,n=e.input,r=n.length;let s="";for(;r>e.position;){const t=n[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;s+=V(e)}const i=function(e,t,n){const r=t.toLowerCase(),s=e.position;if("'s"===t||"'s"===t)return!1;const i=e.tokens[e.tokens.length-1];if(i&&(i.kind===P.IDENTIFIER||i.kind===P.SELECTOR)){const t=e.input.length>e.position?e.input[e.position]:"";if("'"===t||"'"===t)return!1}_(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+=V(e)}if(o){const t=o.toLowerCase(),s=`${r} ${t}`,i=function(e,t,n,r){const s=t.toLowerCase(),i=n.toLowerCase();if("at"===s){const t=e.position;if("the"===i){_(e);let n="";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;n+=V(e)}const s=n.toLowerCase();if("start"===s||"end"===s){_(e);let t="";for(;e.input.length>e.position;){const n=e.input[e.position];if(("a">n||n>"z")&&("A">n||n>"Z")&&("0">n||n>"9")&&"_"!==n&&"-"!==n)break;t+=V(e)}if("of"===t.toLowerCase())return H(e,P.IDENTIFIER,`at the ${s} of`,r),!0}return e.position=t,!1}if("start"===i||"end"===i){_(e);let n="";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;n+=V(e)}return"of"===n.toLowerCase()?(H(e,P.IDENTIFIER,`at ${i} of`,r),!0):(e.position=t,!1)}}return!1}(e,r,t,n);if(i)return!0;const a=function(e,t,n){const r=e.position;let s=`${t} ${n}`,i=e.position;const o=[t,n];for(;8>o.length&&(_(e),e.input.length>e.position);){let t="";for(;e.input.length>e.position;){const n=e.input[e.position];if(("a">n||n>"z")&&("A">n||n>"Z"))break;t+=V(e)}if(!t)break;o.push(t.toLowerCase());const n=o.join(" ");I.has(n)&&(s=n,i=e.position)}return I.has(s)&&s!==`${t} ${n}`?(e.position=i,s):(e.position=r,null)}(e,r,t);if(a)return H(e,P.OPERATOR,a,n),!0;if(I.has(s))return H(e,P.OPERATOR,s,n),!0}return I.has(r)?(e.position=s,H(e,P.OPERATOR,t,n),!0):(e.position=s,!1)}(e,s,t);if(i)return;const o=function(e){const t=e.toLowerCase();return"include"===t||"includes"===t||j.has(t)||F.has(e)||F.has(t)||I.has(t)?P.OPERATOR:P.IDENTIFIER}(s);H(e,o,s,t)}function ee(e){const t=e.position,n=e.input,r=n.length;V(e);let s="$";for(;r>e.position;){const t=n[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t)break;s+=V(e)}H(e,P.IDENTIFIER,s,t)}function te(e){return/[a-zA-Z]/.test(e)}function ne(e){return/[a-zA-Z0-9]/.test(e)}function re(e){const t=e.input,n=t[e.position+1];if(!n||!/[a-zA-Z]/.test(n))return!1;let r=e.position+1,s="";for(;t.length>r&&/[a-zA-Z0-9-]/.test(t[r]);)s+=t[r],r++;return s.length>0&&-1!==t.indexOf("</"+s+">",r)}function se(e){if(re(e))return!0;let t=e.position+1,n=!1;for(;e.input.length>t;){const r=e.input[t];if("/"===r&&e.input.length>t+1&&">"===e.input[t+1])return n;if(ne(r)||"."===r||"#"===r||"["===r||"]"===r||":"===r||"-"===r||"_"===r||" "===r||"="===r||'"'===r||"'"===r||"("===r||")"===r||"*"===r||"^"===r||"$"===r||"~"===r||"|"===r||">"===r||"+"===r||","===r||"{"===r||"}"===r)n=!0,t++;else{if(" "!==r&&"\t"!==r)return!1;t++}if(t-e.position>50)return!1}return!1}function ie(e){return"+-*/^%=!<>&|(){}[],.;:?''~$".includes(e)}const oe=function(){if("undefined"!=typeof localStorage)try{const e=localStorage,t=e.getItem("hyperfixi:debug")||e.getItem("lokascript:debug");if("*"===t||"true"===t)return!0}catch{}return!("undefined"==typeof window||!window.__HYPERFIXI_DEBUG__)||"undefined"!=typeof process&&"true"===process.env?.HYPERFIXI_DEBUG}(),ae=oe,ce=oe,le=oe,ue=oe,fe=(...e)=>{ae&&console.log("🔧",...e)},he=(...e)=>{ce&&console.log("🎯",...e)},de=(...e)=>{le&&console.log("📝",...e)},pe=(...e)=>{ue&&console.log("🚀",...e)};let me=!1,ye=null;if("undefined"!=typeof window&&"undefined"!=typeof URLSearchParams)try{"semantic"===new URLSearchParams(window.location.search).get("debug")&&(me=!0,ye=window,console.log("%c[HyperFixi] Semantic debug auto-enabled via URL param","color: #667eea; font-weight: bold"))}catch{}let ge={totalParses:0,semanticSuccesses:0,semanticFallbacks:0,traditionalParses:0,averageConfidence:0,confidenceHistory:[]};class ve{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(ve.SKIP_SEMANTIC_COMMANDS.has(t))return!0;const n=e.toLowerCase();return!!/\bjs\b/.test(n)||!!/\btell\b/.test(n)||!!/\*[a-zA-Z]/.test(e)}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 r=this.analyzer.analyze(e,this.language),s=performance.now()-t;this.debugEnabled&&console.log("[SemanticIntegration] Analysis result:",{input:e,language:this.language,confidence:r.confidence,command:r.command?.name,threshold:this.confidenceThreshold});const i=r.confidence>=this.confidenceThreshold&&!!r.command,o=!i&&r.confidence>0;if(me){const t={};if(r.command?.roles)for(const[e,n]of r.command.roles)t[e]=n.value;const a={input:e.substring(0,100),language:this.language,confidence:r.confidence,threshold:this.confidenceThreshold,semanticSuccess:i,fallbackTriggered:o,command:r.command?.name,roles:Object.keys(t).length>0?t:void 0,errors:r.errors,timestamp:Date.now(),duration:s};!function(e){if(!me)return;const t=e.semanticSuccess?"semantic":e.fallbackTriggered?"fallback":"traditional",n=Math.round(100*e.confidence),r=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: ${n}% (threshold: ${r}%)`),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(),ye){const t=new CustomEvent("lokascript:semantic:parse",{detail:e,bubbles:!0});ye.dispatchEvent(t)}}(a),n=a,ge.totalParses++,n.semanticSuccess?ge.semanticSuccesses++:n.fallbackTriggered?ge.semanticFallbacks++:ge.traditionalParses++,ge.confidenceHistory.push(n.confidence),ge.confidenceHistory.length>100&&ge.confidenceHistory.shift(),ge.averageConfidence=ge.confidenceHistory.reduce((e,t)=>e+t,0)/ge.confidenceHistory.length}return i?{success:!0,node:this.buildCommandNode(r),confidence:r.confidence,tokensConsumed:r.tokensConsumed}:{success:!1,confidence:r.confidence,tokensConsumed:r.tokensConsumed,errors:r.errors}}catch(e){return{success:!1,confidence:0,errors:[e instanceof Error?e.message:e+""]}}var n}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 n=[],r={};for(const[e,s]of t.roles){const i=this.semanticValueToExpression(s);switch(e){case"patient":case"event":n.push(i);break;case"destination":"put"===t.name?r.into=i:"add"===t.name||"append"===t.name||"prepend"===t.name?r.to=i:r.on=i;break;case"source":"fetch"===t.name?n.push(i):r.from=i;break;case"quantity":r.by=i;break;case"duration":r.over=i;break;case"responseType":r.as=i;break;case"method":r.method=i;break;case"style":r.with=i;break;case"condition":r.when=i;break;default:r[e]=i}}return{type:"command",name:t.name,args:n,modifiers:Object.keys(r).length>0?r:void 0,isBlocking:!1,start:0,end:0,line:1,column:0}}buildRepeatCommandNode(e){const t=[],n={},r=e.roles.get("loopType");r&&t.push({type:"identifier",name:r.value+"",start:0,end:0,line:1,column:0});const s=e.roles.get("patient");"for"==(r?r.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&&(n.condition=this.semanticValueToExpression(c)),{type:"command",name:"repeat",args:t,modifiers:Object.keys(n).length>0?n:void 0,isBlocking:!1,start:0,end:0,line:1,column:0}}buildSetCommandNode(e){const t=[],n=e.roles.get("destination");if(n)if("property-path"===n.type){const e=n;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(n));t.push({type:"identifier",name:"to",start:0,end:0,line:1,column:0});const r=e.roles.get("patient");return r&&t.push(this.semanticValueToExpression(r)),{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=[],n=e.roles.get("condition");return n&&t.push(this.semanticValueToExpression(n)),{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 n=()=>{for(;e.length>t&&/\s/.test(e[t]);)t++},r=()=>{n();const r=t;for(;e.length>t&&/[a-zA-Z0-9_$]/.test(e[t]);)t++;return e.slice(r,t)},s=()=>{const r=[];if(t++,n(),")"!==e[t])for(r.push(i()),n();","===e[t];)t++,n(),r.push(i()),n();return")"===e[t]&&t++,r},i=()=>{n();const i=r();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;){n();const i=e[t];if("."===i){t++;const e=r();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}}ve.SKIP_SEMANTIC_COMMANDS=new Set(["swap","morph","js","tell"]);const be=new Set(["then","end","to","into","on","with","from","in","by","for","while","until","unless","else","catch","finally"]),we=new Set([")","]","}",","]);function Ee(e,t){return{infix:{bp:[e,e+1],handler:t??((t,n,r)=>{const s=r.parseExpr(e+1);return{type:"binaryExpression",operator:n.value,left:t,right:s,start:t.start,end:s.end??n.end,line:t.line??n.line,column:t.column??n.column}})}}}function xe(e,t){return{infix:{bp:[e+1,e],handler:(t,n,r)=>{const s=r.parseExpr(e);return{type:"binaryExpression",operator:n.value,left:t,right:s,start:t.start,end:s.end??n.end,line:t.line??n.line,column:t.column??n.column}}}}}function ke(e,t){return{prefix:{bp:e,handler:t??((t,n)=>{const r=n.parseExpr(e);return{type:"unaryExpression",operator:t.value,operand:r,argument:r,prefix:!0,start:t.start,end:r.end??t.end,line:t.line,column:t.column}})}}}function Se(e){return(t,n,r)=>{const s=r.advance();if(!s||!s.value)throw Error(`Type check requires a type name after 'is ${e?"not ":""}a/an', got: <end>`);let i=!0;const o=r.peek();return o&&"!"===o.value&&(r.advance(),i=!1),{type:"typeCheckExpression",value:t,typeName:s.value,nullOk:i,negated:e,start:t.start,end:s.end}}}const Ae=function(...e){const t=new Map;for(const n of e)for(const[e,r]of n){const n=t.get(e);t.set(e,n?{prefix:r.prefix??n.prefix,infix:r.infix??n.infix}:{...r})}return t}(new Map([["or",Ee(10)],["||",Ee(10)],["and",Ee(20)],["&&",Ee(20)],["==",Ee(30)],["!=",Ee(30)],["<",Ee(30)],[">",Ee(30)],["<=",Ee(30)],[">=",Ee(30)],["is",Ee(30)],["matches",Ee(30)],["contains",Ee(30)],["starts with",Ee(30)],["ends with",Ee(30)],["does not start with",Ee(30)],["does not end with",Ee(30)],["is between",Ee(30,(e,t,n)=>{const r=n.parseExpr(31),s=n.peek();if(!s||"and"!==s.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(s?.value??"<end>"));n.advance();const i=n.parseExpr(31);return{type:"betweenExpression",value:e,min:r,max:i,negated:!1,start:e.start,end:i.end}})],["is not between",Ee(30,(e,t,n)=>{const r=n.parseExpr(31),s=n.peek();if(!s||"and"!==s.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(s?.value??"<end>"));n.advance();const i=n.parseExpr(31);return{type:"betweenExpression",value:e,min:r,max:i,negated:!0,start:e.start,end:i.end}})],["am between",Ee(30,(e,t,n)=>{const r=n.parseExpr(31),s=n.peek();if(!s||"and"!==s.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(s?.value??"<end>"));n.advance();const i=n.parseExpr(31);return{type:"betweenExpression",value:e,min:r,max:i,negated:!1,start:e.start,end:i.end}})],["am not between",Ee(30,(e,t,n)=>{const r=n.parseExpr(31),s=n.peek();if(!s||"and"!==s.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(s?.value??"<end>"));n.advance();const i=n.parseExpr(31);return{type:"betweenExpression",value:e,min:r,max:i,negated:!0,start:e.start,end:i.end}})],["ignoring case",{infix:{bp:[25,26],handler:(e,t,n)=>(e.ignoringCase=!0,e)}}],["where",Ee(28,(e,t,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"where",collection:e,right:r,start:e.start,end:r.end}})],["sorted by",Ee(28,(e,t,n)=>{const r=n.parseExpr(29);let s="asc";const i=n.peek();if(i&&"string"==typeof i.value){const e=i.value.toLowerCase();"asc"===e||"ascending"===e?(n.advance(),s="asc"):"desc"!==e&&"descending"!==e||(n.advance(),s="desc")}return{type:"collectionExpression",operator:"sorted by",collection:e,right:r,order:s,start:e.start,end:r.end}})],["mapped to",Ee(28,(e,t,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"mapped to",collection:e,right:r,start:e.start,end:r.end}})],["split by",Ee(28,(e,t,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"split by",collection:e,right:r,start:e.start,end:r.end}})],["joined by",Ee(28,(e,t,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"joined by",collection:e,right:r,start:e.start,end:r.end}})],["+",{...Ee(40),...ke(80)}],["-",{...Ee(40),...ke(80)}],["*",Ee(50)],["/",Ee(50)],["%",Ee(50)],["mod",Ee(50)],["^",xe(60)],["**",xe(60)],["as",Ee(70,(e,t,n)=>{const r=()=>{const e=n.peek();!e||"a"!==e.value&&"an"!==e.value||n.advance();const t=n.parseExpr(71),r=n.peek();if(r&&":"===r.value&&t&&"identifier"===t.type){n.advance();const e=n.advance();e&&void 0!==e.value&&(t.name=`${t.name}:${e.value}`,t.end=e.end)}return t};let s=r(),i={type:"asExpression",expression:e,targetType:s,start:e.start,end:s.end??t.end,line:e.line??t.line,column:e.column??t.column};for(;n.peek()&&"|"===n.peek().value;){n.advance();const e=r();i={type:"asExpression",expression:i,targetType:e,start:i.start,end:e.end??i.end,line:i.line,column:i.column}}return i})],["not",ke(80)],["!",ke(80)],["no",ke(27)]]),new Map([["===",Ee(30)],["!==",Ee(30)],["is not",Ee(30)],["am",Ee(30)],["is in",Ee(30)],["is not in",Ee(30)],["precedes",Ee(30)],["does not precede",Ee(30)],["follows",Ee(30)],["does not follow",Ee(30)],["is a",Ee(30,Se(!1))],["is an",Ee(30,Se(!1))],["is not a",Ee(30,Se(!0))],["is not an",Ee(30,Se(!0))],["has",Ee(30)],["have",Ee(30)],["match",Ee(30)],["include",Ee(30)],["includes",Ee(30)],["equals",Ee(30)],["does not contain",Ee(30)],["does not include",Ee(30)],["am in",Ee(30)],["am not in",Ee(30)],["is really",Ee(30)],["is not really",Ee(30)],["is equal",Ee(30)],["is not equal",Ee(30)],["contain",Ee(30)],["do not contain",Ee(30)],["does not contains",Ee(30)],["do not match",Ee(30)],["does not match",Ee(30)],["is equal to",Ee(30)],["is not equal to",Ee(30)],["is really equal to",Ee(30)],["is not really equal to",Ee(30)],["really equals",Ee(30)],["is greater than",Ee(30)],["is less than",Ee(30)],["is greater than or equal to",Ee(30)],["is less than or equal to",Ee(30)],["in",Ee(30)],["of",xe(30)],["really",Ee(30)],["exists",{prefix:{bp:80,handler:(e,t)=>({type:"unaryExpression",operator:e.value,operand:t.parseExpr(80),start:e.start})},infix:{bp:[30,31],handler:(e,t)=>({type:"unaryExpression",operator:t.value,operand:e,prefix:!1,start:e.start})}}],["does not exist",{infix:{bp:[30,31],handler:(e,t)=>({type:"unaryExpression",operator:t.value,operand:e,prefix:!1,start:e.start})}}],["is empty",{infix:{bp:[30,31],handler:(e,t)=>({type:"unaryExpression",operator:t.value,operand:e,prefix:!1,start:e.start})}}],["is not empty",{infix:{bp:[30,31],handler:(e,t)=>({type:"unaryExpression",operator:t.value,operand:e,prefix:!1,start:e.start})}}],["some",ke(80)]]),new Map([["=",xe(5)]])),Ne=new Map,Te=new Map,Ce=new Map,Oe=new Set,Re=new Set,$e=new Set,Le=new Set;function je(e){return Ne.get(e.toLowerCase())}function Ie(e){return Ce.get(e)}function Me(e,t){if(0!==Re.size)for(const n of Re)try{n(e,t)}catch(e){void 0!==console&&console.error("[hyperfixi] globalReadHook threw:",e)}}function De(e,t,n){if(0!==$e.size)for(const r of $e)try{r(e,t,n)}catch(e){void 0!==console&&console.error("[hyperfixi] localWriteHook threw:",e)}}function Pe(e,t){if(0!==Le.size)for(const n of Le)try{n(e,t)}catch(e){void 0!==console&&console.error("[hyperfixi] localReadHook threw:",e)}}function Fe(e,t,n){if(e.globals.set(t,n),0!==Oe.size)for(const r of Oe)try{r(t,n,e)}catch(e){void 0!==console&&console.error("[hyperfixi] globalWriteHook threw:",e)}}function Be(e){return e.kind===P.IDENTIFIER&&E.has(e.value.toLowerCase())}function qe(e){return e.kind===P.IDENTIFIER&&D.has(e.value.toLowerCase())}function Ve(e){return e.kind===P.IDENTIFIER&&M.has(e.value.toLowerCase())}function _e(e){return e.kind===P.IDENTIFIER&&L.has(e.value.toLowerCase())}function He(e){return I.has(e.value.toLowerCase())}function Ue(e){return e.kind===P.IDENTIFIER}function ze(e){return e.kind===P.SELECTOR}function We(e){return e.kind===P.SELECTOR&&!e.value.startsWith("<")}function Je(e){return e.kind===P.STRING||e.kind===P.NUMBER||e.kind===P.TEMPLATE}function Ze(e){return e.kind===P.IDENTIFIER}function Ke(e){return e.kind===P.TIME}function Ge(e){return e.kind===P.SYMBOL}function Xe(e){return e.kind===P.COMMENT}function Ye(e){if(e.kind!==P.IDENTIFIER)return!1;const t=e.value.toLowerCase();return!(E.has(t)||D.has(t)||M.has(t)||L.has(t))}function Qe(e){return e.kind===P.STRING}function et(e){return e.kind===P.NUMBER}function tt(e){if(e.kind===P.IDENTIFIER){const t=e.value;return"true"===t||"false"===t||"null"===t||"undefined"===t}return!1}function nt(e){return e.kind===P.TEMPLATE}function rt(e){return e.kind===P.SELECTOR&&e.value.startsWith("<")}function st(e){return e.kind===P.SELECTOR&&e.value.startsWith("#")}function it(e){return e.kind===P.SELECTOR&&e.value.startsWith(".")}function ot(e){return e.kind===P.SELECTOR&&!e.value.startsWith("#")&&!e.value.startsWith(".")}function at(e){if(e.kind!==P.OPERATOR)return!1;const t=e.value.toLowerCase();return!j.has(t)&&!I.has(t)}function ct(e){const t=e.value.toLowerCase();return"then"===t||"and"===t||"else"===t||"end"===t||"on"===t}function lt(e,t,n){return{type:"literal",value:e,raw:t,start:n.start,end:n.end,line:n.line,column:n.column}}function ut(e,t){return{type:"identifier",name:e,start:t.start,end:t.end,line:t.line,column:t.column}}function ft(e,t,n,r){return{type:"binaryExpression",operator:e,left:t,right:n,start:r.start,end:r.end,line:r.line,column:r.column}}function ht(e,t){return{type:"block",commands:e,start:t.start,end:t.end,line:t.line,column:t.column}}function dt(e,t){return{type:"string",value:e,start:t.start,end:t.end,line:t.line,column:t.column}}function pt(e,t){return{type:"objectLiteral",properties:e,start:t.start,end:t.end,line:t.line,column:t.column}}function mt(e,t){return{type:"arrayLiteral",elements:e,start:t.start,end:t.end,line:t.line,column:t.column}}function yt(e,t,n){return{type:"propertyOfExpression",property:e,target:t,start:n.start,end:n.end,line:n.line,column:n.column}}function gt(e,t,n){return{type:"command",name:"__ERROR__",args:[],diagnostics:[{message:t,severity:"error",code:"parse-error",line:e.line,column:e.column,...n&&{source:n}}],start:e.start,end:e.end,line:e.line,column:e.column}}const vt=[{command:"append",keywords:["to"],syntax:"append <value> [to <target>]"},{command:"make",keywords:["a","an","from","called"],syntax:"make (a|an) <type> [from <args>] [called <name>]"},{command:"send",keywords:["to"],syntax:"send <event> to <target>"},{command:"throw",keywords:[],syntax:"throw <error>"}];function bt(e,t){return!!e&&t.some(t=>e.value===t||e.value.toLowerCase()===t)}const wt=[e,r,t,n];function Et(e,t=[]){if(e.isAtEnd())return!0;for(const t of wt)if(e.check(t))return!0;for(const n of t)if(e.check(n))return!0;return!!e.checkIsCommand()}function xt(e,t=[]){if(!Et(e,t))return e.parseExpression()}function kt(e,t,n){return!!e.check(t)&&(e.advance(),n.push(e.createIdentifier(t)),!0)}function St(e,t,n){for(const r of t)if(e.check(r))return e.advance(),n.push(e.createIdentifier(r)),r;return null}function At(e,t){return!!e.check(t)&&(e.advance(),!0)}function Nt(e){const t=e.savePosition();let n;if(e.checkIdentifierLike()){const r=e.peek().value;e.advance(),e.check(":")?(e.advance(),n=r):e.restorePosition(t)}const r=e.parseExpression();return void 0!==n?{name:n,value:r}:{value:r}}class Tt{constructor(e){this.args=[],this.isBlocking=!1,this.name=e}static from(e){const t=new Tt(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 Tt(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 Tt(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}withName(e){return this.name=e,this}withOriginalCommand(e){return this.originalCmd=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),this.originalCmd&&(e.originalCommand=this.originalCmd),e}clone(){const e=new Tt(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.originalCmd=this.originalCmd,e.startPos=this.startPos?{...this.startPos}:void 0,e.endPos=this.endPos?{...this.endPos}:void 0,e}}function Ct(e,t){const n=[];let r="";const s=e.peek().start||0,i=e.peek().line||1,o=e.peek().column||1;if(e.checkIdentifierLike()){for(r=e.advance().value;e.check(":")&&!e.isAtEnd();)e.advance(),r+=":",e.checkIdentifierLike()&&(r+=e.advance().value);if(e.check("(")){e.advance();const t=[];for(;!e.isAtEnd()&&!e.check(")");){const{name:n,value:r}=Nt(e);if(t.push(void 0!==n?{type:"objectLiteral",properties:[{key:{type:"identifier",name:n},value:r}],start:r.start,end:r.end,line:r.line,column:r.column}:r),e.check(","))e.advance();else if(!e.check(")"))break}e.check(")")&&e.advance(),n.push({type:"functionCall",name:r,args:t,start:s,end:e.getPosition().end,line:i,column:o})}else n.push({type:"string",value:r,start:s,end:e.getPosition().end,line:i,column:o})}const a=[...n];for(;!Et(e);){if(e.check("on")||e.check("to")){const t=e.advance().value;a.push(e.createIdentifier(t));continue}a.push(e.parsePrimary())}return Tt.fromIdentifier(t).withArgs(...a).endingAt(e.getPosition()).build()}function Ot(e,t){const n=[];if(e.check(b)){const t=e.advance();if(n.push({type:"identifier",name:b,start:t.start,end:t.end,line:t.line,column:t.column}),e.check(y)){const t=e.advance();n.push({type:"identifier",name:y,start:t.start,end:t.end,line:t.line,column:t.column})}}return Tt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}function Rt(r,s){const i=[];let o=!1;const a=r.savePosition();for(let t=0;500>t&&!r.isAtEnd();t++){const t=r.peek();if(t.value===e){o=!0;break}if(t.value===n||t.value===g||"def"===t.value||t.value===m)break;r.advance()}r.restorePosition(a);let c=!1;if(!o){const e=r.savePosition(),i=s.line,o=100;for(;!r.isAtEnd()&&o>r.current-e;){const e=r.peek(),s=e.value?.toLowerCase();if(s===g||"def"===s||s===m)break;if(s===t||s===n){e.line===i&&(c=!0);break}if((r.checkIsCommand()||r.isCommand(s))&&void 0!==e.line&&e.line!==i){c=!0;break}r.advance()}r.restorePosition(e)}const l=o||c;let u;if(l)u=r.parseExpression();else{const t=[],n=20;let i=0;for(;!r.isAtEnd()&&!r.checkIsCommand()&&!r.isCommand(r.peek().value)&&!r.check(e)&&n>i;){const e=r.savePosition();t.push(r.parseLogicalAnd()),r.savePosition()===e&&r.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&&r.advance();const e=[];for(;!r.isAtEnd()&&!r.check(t)&&!r.check(n)&&(r.checkIsCommand()||r.isCommand(r.peek().value));){r.advance();const t=r.parseCommand();t&&e.push(t)}if(0===e.length&&r.isAtEnd())throw Error("Expected command after 'then' in if statement - incomplete conditional");i.push(ht(e,{start:s.start,end:r.getPosition().end,line:s.line,column:s.column}));let a=!1;if(r.check(t))if(r.advance(),r.check("if")){const e=r.peek();r.advance();const t=Rt(r,e);i.push(ht([t],{start:e.start,end:r.getPosition().end,line:e.line,column:e.column})),a=!0}else{const e=[];for(;!r.isAtEnd()&&!r.check(n)&&(r.checkIsCommand()||r.isCommand(r.peek().value));){r.advance();const t=r.parseCommand();t&&e.push(t)}i.push(ht(e,{start:s.start,end:r.getPosition().end,line:s.line,column:s.column}))}a||r.consume(n,"Expected 'end' after if block")}else{if(!r.checkIsCommand()&&!r.isCommand(r.peek().value))throw Error("Expected command after if condition in single-line form");{r.advance();const e=r.parseCommand();i.push(ht([e],{start:s.start,end:r.getPosition().end,line:s.line,column:s.column}))}}return Tt.from(s).withArgs(...i).endingAt(r.getPosition()).build()}function $t(e,t){const n=[],r={};if(e.checkAnySelector()||e.checkContextVar()||e.match("<")){const t=e.parsePrimary();if(n.push(t),e.match("*")){if(e.checkIdentifierLike()){const t=e.advance();n.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();n.push(t)}}else if(e.checkIdentifierLike()){const t=e.parsePrimary();n.push(t)}if(e.match("and")&&e.match("set")&&e.checkIdentifierLike()){const t=e.advance();r.set={type:"identifier",name:t.value,start:t.start,end:t.end,line:t.line,column:t.column}}const s=Tt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition());return Object.keys(r).length>0&&s.withModifiers(r),s.build()}function Lt(e,t){const n=[],r=xt(e,[h]);r&&n.push(r),kt(e,h,n);const s=xt(e);return s&&n.push(s),Tt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}function jt(e,t){const n=[];if(e.check("between")){e.advance(),n.push(e.createIdentifier("between"));const i=xt(e,[r]);if(i&&"binaryExpression"===i.type&&"and"===i.operator)i.left&&n.push(i.left),n.push(e.createIdentifier("and")),i.right&&n.push(i.right);else{i&&n.push(i),kt(e,r,n);const t=xt(e,[h,m,s]);t&&n.push(t)}if(St(e,[h,m],n)){const t=xt(e);t&&n.push(t)}return Tt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}const i=xt(e,[h,m]);if(i&&n.push(i),St(e,[h,m],n)){const t=xt(e);t&&n.push(t)}return e.check("modal")&&(e.advance(),n.push({type:"literal",value:"modal",raw:"modal"})),Tt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}function It(e,t){const r=e.parseExpression();if(!r)return e.addError("Put command requires content expression"),null;const s=e.peek();if(!s||!A.includes(s.value))return e.addError(`Expected operation keyword (${A.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=S:"at"===i&&(e.check(w)||e.check(b)?(At(e,b),e.check(w)&&(e.advance(),e.check(p)&&(e.advance(),i=k))):e.check(n)&&(e.advance(),e.check(p)&&(e.advance(),i=S)));const a=e.parseExpression();return a?Tt.fromIdentifier(t).withArgs(r,e.createIdentifier(i),a).endingAt(e.getPosition()).build():(e.addError("Put command requires target expression after operation keyword"),null)}const Mt=["innerhtml","outerhtml","into","over","delete","morph","morphouter"];function Dt(s,i){const o=s.savePosition();let a=null,c=[];try{a=function(e){if(!e.check(":"))return null;if(e.advance(),e.check(":")){e.advance();const t=e.advance();return{type:"identifier",name:t.value,scope:"global",start:t.start-2,end:t.end}}const t=e.advance();return{type:"identifier",name:t.value,scope:"element",start:t.start-1,end:t.end}}(s)??function(e){if(!e.check(v)&&!e.check("local"))return null;const t=e.advance(),n=e.advance();return{type:"identifier",name:n.value,scope:t.value,start:t.start,end:n.end}}(s)??function(e){if(!e.check(b))return null;const t=e.savePosition();e.advance();const n=e.parseExpression();if(!n)return e.restorePosition(t),null;if("binaryExpression"===n.type&&n.operator===p){const e=n.left,t=n.right;return yt(e,t,{start:e.start??0,end:t.end??0,line:e.line??1,column:e.column??1})}return e.check(f)?n:(e.restorePosition(t),null)}(s),a||(a=s.parseExpression())}catch{s.restorePosition(o),a=null}if(!a){const i=function(s){if(s.match(":")){const e=s.advance();return{expression:{type:"identifier",name:e.value,scope:"element",start:e.start,end:e.end},tokens:[]}}const i=[];for(;!(s.isAtEnd()||s.check(f)||s.check(e)||s.check(r)||s.check(t)||s.check(n));)i.push(s.parsePrimary());if(0===i.length)return{expression:null,tokens:[]};if(i.length>=4){const e=(e,t)=>e[t];if(e(i[0],"value")===b&&e(i[2],"value")===p){const t=i[1],n=i[3];return{expression:yt(ut(e(t,"value")||e(t,"name")||"",{start:t.start??0,end:t.end??0,line:t.line??1,column:t.column??1}),{type:"idSelector"===n.type?"idSelector":"cssSelector",value:e(n,"value")||e(n,"name")||"",start:n.start??0,end:n.end??0,line:n.line,column:n.column},{start:i[0].start??0,end:n.end??0,line:i[0].line??1,column:i[0].column??1}),tokens:[]}}}return 1===i.length?{expression:i[0],tokens:[]}:{expression:null,tokens:i}}(s);a=i.expression,c=i.tokens}if(!s.check(f)){const e=s.isAtEnd()?"end of input":s.peek().value;throw Error("Expected 'to' in set command, found: "+e)}s.advance();const l=s.parseExpression()??s.parsePrimary();let u;var h;s.check(m)&&(h=s.peekAt(1))&&("selector"===h.kind||h.value.startsWith("<")||Pt.has(h.value))&&(s.advance(),u=xt(s));const d=[];a?d.push(a):c.length>0&&d.push(...c),d.push(s.createIdentifier(f)),l&&d.push(l);const y=Tt.fromIdentifier(i).withArgs(...d);return u&&y.withModifier("on",u),y.endingAt(s.getPosition()).build()}const Pt=new Set(["me","my","it","its","you","your","yourself"]);function Ft(e,t){const n=[];for(;!Et(e,["catch","finally"])&&(e.checkIdentifierLike()||e.checkSelector()||e.checkLiteral()||e.checkTimeExpression()||e.match("<"));)n.push(e.parsePrimary());return Tt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}function Bt(e){if(e.isAtEnd())return!0;const t=e.peek().value;return["as","with","{","then","end","else","otherwise",")"].includes(t)||Et(e)}function qt(e){if(e.check("{"))return!1;if(!e.checkIdentifierLike())return!1;const t=e.peekAt(1);return null!==t&&":"===t.value}function Vt(e){const t=[],n=e.getPosition();do{if(!e.checkIdentifierLike())break;const n=e.advance(),r={type:"identifier",name:n.value,start:n.start,end:n.end,line:n.line,column:n.column};e.consume(":","Expected ':' after property name in fetch named arguments");const s=e.parsePrimary();s&&t.push({key:r,value:s})}while(e.match(",")&&!e.isAtEnd());const r=e.getPosition();return{type:"objectLiteral",properties:t,start:n.start,end:r.end,line:n.line,column:n.column}}const _t=new Set(["em","ex","cap","ch","ic","rem","lh","rlh","vw","vh","vi","vb","vmin","vmax","cm","mm","Q","pc","pt","px"]);class Ht{constructor(e,t,n){this.current=0,this.errors=[],this.warnings=[],this.prattCache=new Map,this.tokens=e,this.keywordResolver=t?.keywords,this.registryIntegration=t?.registryIntegration,t?.semanticAnalyzer&&t?.language&&(this.semanticAdapter=new ve({analyzer:t.semanticAnalyzer,language:t.language,confidenceThreshold:t.semanticConfidenceThreshold??.5})),this.originalInput=n||e.map(e=>e.value).join(" ")}resolveKeyword(e){return this.keywordResolver?this.keywordResolver.resolve(e)??e:e}addWarning(e){this.warnings.push(e)}parse(){this.prattCache.clear();const e=this.parseInternal();return this.errors.length>0&&(e.errors=[...this.errors]),e}parseInternal(){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}}const e=this.peek(),t=e&&je(e.value)?e.value:null;if(this.check("init")||this.check("on")||this.check("def")||this.checkComment()||null!==t){const e=[];for(;!this.isAtEnd();)if(this.checkComment())this.advance();else{if(this.check("then")){const e=this.peekAt(1);if(null!==e&&("init"===e.value||"on"===e.value||"def"===e.value||void 0!==je(e.value))){this.advance();continue}}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")){const t=this.peek(),n=t?je(t.value):void 0;if(n){const t=this.advance(),r=n(this.getContext(),t);r&&e.push(r);continue}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")){de("✅ PARSER: Found event handlers after command sequence, parsing as program");const t=[e];de(`✅ PARSER: Starting with ${t.length} statement(s) from command sequence`);let n=0;for(;!this.isAtEnd()&&this.check("on");){de(`✅ PARSER: Parsing event handler #${n+1}, current token: ${this.peek().value}`),this.advance();const e=this.parseEventHandler();if(de("✅ PARSER: parseEventHandler returned:",e?`type=${e.type}, event=${e.event}`:"null"),e&&(t.push(e),n++,de(`✅ PARSER: Added event handler, now have ${t.length} statements total`)),de(`✅ 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 de("⚠️ 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};de("✅ PARSER: No more event handlers, at end of input");break}}return de(`✅ 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 n=this.parseExpression();if(this.error)return{success:!1,node:n||this.createErrorNode(),tokens:this.tokens,error:this.error};if(!this.isAtEnd()){const e=this.peek();return n&&["number","string","identifier"].includes(e.kind)?this.addError(`Unexpected token: ${e.value} (missing operator between values? expected one of +, -, *, /, etc.)`):this.addError("Unexpected token: "+e.value),{success:!1,node:n||this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}return{success:!0,node:n,tokens:this.tokens,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.parseExpressionPratt(0)}parseExpressionPratt(e){const t=`${this.current}:${e}`,n=this.prattCache.get(t);if(n)return this.current=n.endPos,n.node;if(this.isAtEnd())return this.addError("Unexpected end of expression"),this.createErrorNode();const r=this.peek(),s=Ht.PRATT_TABLE.get(r.value);let i;if(s?.prefix){const e=this.advance();if(this.isAtEnd())return this.addError(`Expected expression after '${e.value}' operator`),this.createErrorNode();i=s.prefix.handler(e,this.makePrattContext())}else i=this.parseCall();for(;!this.isAtEnd();){const t=this.peek();if(60>=e){const e=this.tryParseStringPostfix(i,t);if(e){i=e;continue}}const n=Ht.PRATT_TABLE.get(t.value);if(!n?.infix){if(be.has(t.value)||we.has(t.value))break;break}const[r]=n.infix.bp;if(e>r)break;if("="===t.value&&this.tokens.length>this.current+1&&">"===this.tokens[this.current+1].value){if(this.advance(),this.advance(),this.addError('Arrow functions (=>) are not supported in hyperscript. Use "js ... end" blocks for JavaScript callbacks.'),!this.isAtEnd())try{this.parseExpressionPratt(0)}catch(e){de("arrow body discarded after error:",e instanceof Error?e.message:e+"")}return this.createErrorNode()}if("+"===t.value||"-"===t.value){const e=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(e&&("+"===e.value||"-"===e.value))return this.addError(`Invalid operator combination: ${t.value}${e.value}`),i}if("*"===t.value||"/"===t.value||"%"===t.value){const e=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(e&&("*"===e.value||"/"===e.value||"%"===e.value||"+"===e.value||"-"===e.value))return this.addError("*"===t.value&&"*"===e.value?"Unexpected token: "+e.value:`Invalid operator combination: ${t.value}${e.value}`),i}const s=this.advance();if(this.isAtEnd()&&!Ht.POSTFIX_UNARY_OPERATORS.has(s.value))return this.addError(`Expected expression after '${s.value}' operator`),i;i=n.infix.handler(i,s,this.makePrattContext())}return this.prattCache.set(t,{node:i,endPos:this.current}),i}tryParseStringPostfix(e,t){const n=t.value;let r=null;if(_t.has(n)?r=n:"%"===n&&(this.canStartOperand(this.tokens.length>this.current+1?this.tokens[this.current+1]:null)||(r="%")),null==r)return null;const s=this.advance();return{type:"stringPostfix",expression:e,unit:r,start:e.start,end:s.end,line:e.line,column:e.column}}canStartOperand(e){if(!e)return!1;const t=e.value;return!be.has(t)&&!we.has(t)&&("number"===e.kind||"string"===e.kind||"identifier"===e.kind||"symbol"===e.kind||["(","[","{","-","+","!","#",".","<","$","@"].includes(t))}makePrattContext(){const e=this;return{peek:()=>e.tokens.length>e.current?e.tokens[e.current]:void 0,advance:()=>{const t=e.tokens[e.current];return e.current++,t},parseExpr:t=>e.parseExpressionPratt(t),isStopToken:()=>{const t=e.tokens[e.current];return!t||be.has(t.value)||we.has(t.value)},atEnd:()=>e.current>=e.tokens.length}}parseLogicalAnd(){return this.parseExpressionPratt(11)}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()||this.checkNumber()||this.checkIdentifier()||this.checkContextVar()||this.check("("))){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=[],n=this.resolveKeyword(e.name.toLowerCase());if(this.isCompoundCommand(n))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 C(e)}parseCompoundCommand(s){return function(s,i){switch(i.name.toLowerCase()){case"put":return It(s,i);case"trigger":case"send":return Ct(s,i);case"remove":return Lt(s,i);case"toggle":return jt(s,i);case"set":return Dt(s,i);case"halt":return Ot(s,i);case"measure":return $t(s,i);case"js":return function(e,t){const r=[];if(e.match("(")){for(;!e.check(")")&&!e.isAtEnd();)e.checkIdentifierLike()&&r.push(e.advance().value),e.match(",");e.consume(")","Expected ) after js parameters")}const s=e.peek().start,i=function(e,t){const n=e.getInputSlice(t);if(!n)return t;let r=0;for(;n.length>r;){const e=n[r];if("'"!==e&&"’"!==e&&"‘"!==e)if('"'!==e)if("`"!==e)if("/"===e&&n.length>r+1&&"/"===n[r+1])for(r+=2;n.length>r&&"\n"!==n[r];)r++;else if("/"===e&&n.length>r+1&&"*"===n[r+1]){for(r+=2;n.length>r&&("*"!==n[r]||r+1>=n.length||"/"!==n[r+1]);)r++;r+=2}else{if(!("e"!==e&&"E"!==e||r+3>n.length||"end"!==n.slice(r,r+3).toLowerCase()||0!==r&&/[a-zA-Z0-9_]/.test(n[r-1])||n.length>r+3&&/[a-zA-Z0-9_]/.test(n[r+3])))return t+r;r++}else{for(r++;n.length>r&&"`"!==n[r];)"\\"===n[r]&&r++,r++;r++}else{for(r++;n.length>r&&'"'!==n[r];)"\\"===n[r]&&r++,r++;r++}else{for(r++;n.length>r&&n[r]!==e;)"\\"===n[r]&&r++,r++;r++}}return t+n.length}(e,s);for(;!e.isAtEnd()&&!e.check(n)&&e.peek().start<i;)e.advance();e.consume(n,"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:r.map(e=>({type:"literal",value:e,start:t.start,end:t.end})),start:t.start,end:e.getPosition().end};return Tt.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(r))continue;if(s.check(e)||s.check(t)||s.check(n))break;if(s.checkIsCommand())continue;break}break}if(0===a.length)throw Error("tell command requires at least one command after the target");return Tt.fromIdentifier(i).withArgs(o,...a).endingAt(s.getPosition()).build()}(s,i);case"pick":return function(e,t){const n=Tt.fromIdentifier(t);At(e,b);const r=e.peek().value,s=e=>({type:"literal",value:e,start:t.start,end:t.end}),i=()=>{if(!e.match("of","from"))throw Error("pick: expected 'of' or 'from' before source expression");return e.parseExpression()};if("first"===r){e.advance();const t=e.parsePrimary(),r=i();return n.withArgs(r).withModifier("variant",s("first")).withModifier("count",t).endingAt(e.getPosition()).build()}if("last"===r){e.advance();const t=e.parsePrimary(),r=i();return n.withArgs(r).withModifier("variant",s("last")).withModifier("count",t).endingAt(e.getPosition()).build()}if("random"===r){let t;e.advance(),e.check("of")||e.check("from")||(t=e.parsePrimary());const r=i(),o=n.withArgs(r).withModifier("variant",s("random"));return t&&o.withModifier("count",t),o.endingAt(e.getPosition()).build()}if("item"===r||"items"===r||"character"===r||"characters"===r){let t,r;e.advance(),e.match("at","from"),t=e.match("start")?s("start"):e.parsePrimary();let o=!1;(e.match("to")||e.match(".."))&&(e.match("end")?o=!0:r=e.parsePrimary());let a="default";e.match("inclusive")?a="inclusive":e.match("exclusive")&&(a="exclusive");const c=i(),l=n.withArgs(c).withModifier("variant",s("range")).withModifier("rangeStart",t).withModifier("rangeMode",s(a));return o?l.withModifier("rangeEnd",s("end")):r&&l.withModifier("rangeEnd",r),l.endingAt(e.getPosition()).build()}if("match"===r||"matches"===r){e.advance(),e.match("of");const t=e.parsePrimary();let o;e.matchOperator("|")&&(o=e.advance().value);const a=i(),c=n.withArgs(a).withModifier("variant",s("match"===r?"match":"matches")).withModifier("regex",t);return o&&c.withModifier("flags",s(o)),c.endingAt(e.getPosition()).build()}return Ft(e,t)}(s,i);case"start":return function(e,t){if(!e.match("view"))throw Error("start: expected 'view transition' (only `start view transition ... end` is supported)");if(!e.match("transition"))throw Error("start view: expected 'transition'");const n={};if(e.match("using")){const t=e.parsePrimary();n.transitionName=t}const r=e.parseCommandListUntilEnd();return Tt.fromIdentifier(t).withArgs(...r).withModifiers(n).endingAt(e.getPosition()).build()}(s,i);case"swap":case"morph":return function(e,t){const n=[];let r=null;if(!e.isAtEnd()){const t=e.peek();if(t&&t.value){const s=t.value.toLowerCase();Mt.includes(s)&&(r=s,e.advance(),n.push(e.createIdentifier(r)))}}if("delete"===r){const r=e.parseExpression();return r&&n.push(r),Tt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}!e.isAtEnd()&&e.check(p)&&(e.advance(),n.push(e.createIdentifier("of")));const s=e.parseExpression();if(s&&n.push(s),!e.isAtEnd()&&e.check(d)){e.advance(),n.push(e.createIdentifier("with"));const t=e.parseExpression();t&&n.push(t)}return Tt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}(s,i);default:return Ft(s,i)}}(this.getContext(),s)}parsePutCommand(e){return It(this.getContext(),e)}parseSetCommand(e){return Dt(this.getContext(),e)}parseHaltCommand(e){return Ot(this.getContext(),e)}parseMeasureCommand(e){return $t(this.getContext(),e)}parseTriggerCommand(e){return Ct(this.getContext(),e)}parseCommandListUntilTerminator(e){const t=[],n=()=>this.check("end")||e.some(e=>this.check(e));for(de("🔄 parseCommandListUntilTerminator: Starting (extraStops:",e.join(","),")");!this.isAtEnd()&&!n();){de("📍 Loop iteration, current token:",this.peek().value,"kind:",this.peek().kind);let e=!1;const r=this.checkIsCommand(),s=!r&&this.checkIdentifier()&&this.isCommand(this.peek().value);if(r||s){de(r?"✅ Found COMMAND token:":"✅ Found IDENTIFIER that is a command:",this.peek().value),this.advance();const n=this.error;try{const r=this.parseCommand();this.error&&this.error!==n&&(de("⚠️ parseCommandListUntilTerminator: Command parsing added error, restoring. Error was:",this.error.message),this.error=n),r&&(de("✅ Parsed command:",r.name),t.push(r),e=!0)}catch(e){de("⚠️ parseCommandListUntilTerminator: Command parsing threw, restoring:",e instanceof Error?e.message:e+""),this.error=n}}else this.checkIdentifier()&&de("❌ IDENTIFIER is not a command:",this.peek().value);if(!e){de("❌ No command parsed, breaking. Current token:",this.peek().value);break}for(de("📍 After parsing command, current token:",this.peek().value);!(this.isAtEnd()||n()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(","));)de("⚠️ Skipping unexpected token:",this.peek().value),this.advance();if(this.match("then","and",","))de("✅ Found separator, continuing");else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){de("📍 No separator and no command, breaking. Current token:",this.peek().value);break}de("✅ Next token is a command, continuing without separator")}}let r="end";for(const t of e)if(this.check(t)){r=t;break}return this.check("end")||e.some(e=>this.check(e))||(r=""),de("✅ parseCommandListUntilTerminator: parsed",t.length,"commands (terminator:",r,")"),{commands:t,terminator:r}}parseCommandListUntilEnd(){const{commands:e}=this.parseCommandListUntilTerminator([]);if(de('🔍 After loop, checking for "end". Current token:',this.peek().value),!this.check("end"))throw de('❌ ERROR: Expected "end" but got:',this.peek().value,"at position:",this.peek().start),Error('Expected "end" to close repeat block');return de('✅ Found "end", consuming it'),this.advance(),e}parseCommandListUntilEndOrElse(){const{commands:e,terminator:t}=this.parseCommandListUntilTerminator(["else"]),n="else"===t;if(!n){if(!this.check("end"))throw Error('Expected "end" to close repeat block');this.advance()}return{commands:e,hasElse:n}}parseRepeatBody(){const{commands:e,terminator:t}=this.parseCommandListUntilTerminator(["else","until","while"]);if("end"===t)this.advance();else if(""===t)throw Error('Expected "end", "else", "until", or "while" to close repeat block');return{commands:e,terminator:t}}parseRepeatCommand(e){return function(e,t){const n=[];let r="forever",f=null,p=null,m=null,g=null,v=null,w=null;if(e.check(s)){e.advance(),r=s;const t=e.peek();Ue(t)&&(v=t.value,e.advance()),e.check(u)&&(e.advance(),g=e.parseExpression())}else if(e.check(u))e.advance(),r=s,v="it",g=e.parseExpression();else if(e.check(i))e.advance(),r=i,m=e.parseExpression();else if(e.check(o))if(e.advance(),r=o,e.check(y)){e.advance(),r="until-event";const t=e.peek();if(de("📍 Parsing event name, current token:",{value:t.value,kind:t.kind}),!Ue(t)&&!Ve(t))throw Error('Expected event name after "event"');if(f=t.value,e.advance(),de("✅ Got event name:",f,"Next token:",e.peek().value),de('🔍 Checking for "from", current token:',e.peek().value),e.check(h)){de('✅ Found "from", advancing...'),e.advance(),de('📍 After consuming "from", current token:',e.peek().value),At(e,b)&&de('✅ Found "the", advancing...');const t=e.peek();de("🔍 Before parsePrimary for event target:",{value:t.value,kind:t.kind,position:t.start}),p=e.parsePrimary(),de("✅ After parsePrimary, eventTarget:",p)}else de('❌ No "from" found, skipping target parsing')}else m=e.parseExpression();else e.check(a)?(e.advance(),r=a):(w=e.parseExpression(),e.check(c)&&(e.advance(),r=c));let E,x=null;if(e.check(d)){const t=e.peekAt(1);t&&t.value.toLowerCase()===l&&(e.advance(),e.advance(),x=l)}else if(e.check(l)){e.advance();const t=e.peek();Ue(t)?(x=t.value,e.advance()):x=l}let k=null,S=!1;if(r===a){const t=e.parseRepeatBody();if(E=t.commands,"else"===t.terminator)e.advance(),k=e.parseCommandListUntilEnd();else if("until"===t.terminator||"while"===t.terminator){if(S=!0,r=t.terminator,e.advance(),m=e.parseExpression(),!e.check("end"))throw Error('Expected "end" to close repeat block');e.advance()}}else{const t=e.parseCommandListUntilEndOrElse();E=t.commands,t.hasElse&&(e.advance(),k=e.parseCommandListUntilEnd())}n.push({type:"identifier",name:r,start:t.start,end:t.end,line:t.line,column:t.column});const A={start:t.start,end:t.end,line:t.line,column:t.column};v&&n.push(dt(v,A)),g&&n.push(g),m&&n.push(m),w&&n.push(w),f&&n.push(dt(f,A)),p&&n.push(p),x&&n.push(dt(x,A)),n.push(ht(E,{...A,end:A.end||0})),null!==k&&n.push(ht(k,{...A,end:A.end||0}));const N=Tt.from(t).withArgs(...n);return S&&N.withModifier("bottomTested",{type:"literal",value:!0,...A}),N.endingAt(e.getPosition()).build()}(this.getContext(),e)}parseForCommand(e){return function(e,t){const n=[];let r=null,s=null;e.check("each")&&e.advance();const i=e.peek();if(!Ue(i))throw Error('Expected variable name after "for"');if(r=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.peekAt(1);t&&t.value.toLowerCase()===l&&(e.advance(),e.advance(),o=l)}else if(e.check(l)){e.advance();const t=e.peek();Ue(t)?(o=t.value,e.advance()):o=l}const a=e.parseCommandListUntilEnd();n.push({type:"identifier",name:"for",start:t.start,end:t.end,line:t.line,column:t.column});const c={start:t.start,end:t.end,line:t.line,column:t.column};return n.push(dt(r,c)),n.push(s),o&&n.push(dt(o,c)),n.push(ht(a,{...c,end:c.end||0})),Tt.from({...t,value:"repeat"}).withArgs(...n).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseWaitCommand(e){return function(e,t){const n=[];if(e.checkTimeExpression()||e.checkLiteral()||e.checkContextVar()||e.check("(")||e.checkIdentifierLike()&&!e.check("for")&&!Et(e)){const r=e.parseExpression();return n.push(r),Tt.from(t).withArgs(...n).blocking().endingAt(e.getPosition()).build()}if(e.check("for")){e.advance();const r=[];do{const t=e.peek();if(!Ue(t))throw Error('Expected event name after "for"');const n=t.value;e.advance();const s=[];if(e.check("(")){for(e.advance();!e.isAtEnd()&&!e.check(")");){const t=e.peek();if(!Ue(t))break;s.push(t.value),e.advance(),e.check(",")&&e.advance()}if(!e.check(")"))throw Error('Expected ")" after event parameters');e.advance()}if(r.push({name:n,params:s}),!e.check("or"))break;e.advance()}while(!e.isAtEnd());let s=null;e.check(h)&&(e.advance(),At(e,b),s=e.parsePrimary());const i={start:t.start,end:e.getPosition().end,line:t.line,column:t.column};n.push(mt(r.map(e=>pt([{key:ut("name",i),value:lt(e.name,`"${e.name}"`,i)},{key:ut("args",i),value:mt(e.params.map(e=>lt(e,`"${e}"`,i)),i)}],i)),i)),s&&n.push(s)}return Tt.from(t).withArgs(...n).blocking().endingAt(e.getPosition()).build()}(this.getContext(),e)}parseInstallCommand(e){return function(e,t){const n=[];if(!e.checkIdentifierLike())throw Error('Expected behavior name after "install"');const r=e.advance().value,s=e.previous();if(n.push(ut(r,{start:s.start,end:s.end,line:s.line,column:s.column})),e.check("(")){e.advance();const r=[];for(;!e.isAtEnd()&&!e.check(")");)if(r.push(Nt(e)),e.check(","))e.advance();else if(!e.check(")"))break;if(!e.check(")"))throw Error('Expected ")" after behavior parameters');if(e.advance(),r.length>0){const s={start:t.start,end:e.getPosition().end,line:t.line,column:t.column};n.push(pt(r.map(e=>({key:e.name?ut(e.name,s):lt("_positional","_positional",s),value:e.value})),s))}}return Tt.from(t).withArgs(...n).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseTransitionCommand(e){return function(e,t){const n=[],r={};let s=null;const i=e.peek();if(Ue(i)||"*"===i.value){let t="";e.check("*")&&(t="*",e.advance());const n=function(e){if(!e.checkIdentifierLike())return"";let t=e.advance().value;for(;e.check("-")&&!e.isAtEnd();)t+="-",e.advance(),e.checkIdentifierLike()&&(t+=e.advance().value);return t}(e);n&&(t+=n,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(n.push(s),!e.check(f))throw Error('Expected "to" keyword after property in transition command');e.advance();const o=e.parsePrimary();if(r.to=o,e.check("over")){e.advance();const t=e.parsePrimary();r.over=t}if(e.check(d)){e.advance();const t=e.parsePrimary();r.with=t}return Tt.from(t).withArgs(...n).withModifiers(r).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseAddCommand(e){return function(e,t){const n=[];if(e.match("{"))n.push(e.parseCSSObjectLiteral());else{const t=xt(e,[f]);t&&n.push(t)}if(e.check(f)){e.advance();const t=xt(e);t&&n.push(t)}return Tt.from(t).withArgs(...n).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseIfCommand(e){return Rt(this.getContext(),e)}parseRemoveCommand(e){return Lt(this.getContext(),e)}parseToggleCommand(e){return jt(this.getContext(),e)}parseRegularCommand(e){return Ft(this.getContext(),e)}parseCall(){let e=this.parsePrimary();for(;;)if(this.match("("))e=this.finishCall(e);else if(this.match(".")){const t=this.consumeIdentifierLike("Expected property name after '.' - malformed member access");e=this.createMemberExpression(e,this.createIdentifier(t.value),!1)}else if(this.match("?.")){const t=this.consumeIdentifierLike("Expected property name after '?.' - malformed optional access"),n=this.createMemberExpression(e,this.createIdentifier(t.value),!1);n.optional=!0,e=n}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):Ge(this.peek())&&this.peek().value.startsWith("@")?t=this.advance().value:this.check("[")&&this.tokens[this.current+1]?.value?.startsWith("@")?(this.advance(),t=this.advance().value,this.consume("]","Expected ']' after attribute reference")):t=this.consumeIdentifierLike("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()&&Ue(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),n=this.processEscapeSequences(t);return this.createLiteral(n,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,t=e.slice(1,-2).trim(),n=this.createSelector(t);return n.fromQuery=!0,n.raw=e,n}if(this.matchSelector())return this.createSelector(this.previous().value);if(this.match("<"))return this.parseHyperscriptSelector();if(this.match("(")){if(this.isAtEnd())return this.addError("Expected expression inside parentheses"),this.createErrorNode();const 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:"element",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(Ye)||this.matchPredicate(qe)||this.matchPredicate(_e)||this.matchPredicate(Be)||this.matchPredicate(Ve))){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,n=this.createSelector("."+t);return this.createCallExpression(this.createIdentifier(e.value),[n])}this.current=t}if(this.check("#")){const t=this.current;if(this.advance(),this.checkIdentifier()){const t=this.advance().value,n=this.createSelector("#"+t);return this.createCallExpression(this.createIdentifier(e.value),[n])}this.current=t}return this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||this.check("end")?this.createIdentifier(e.value):this.parseNavigationFunction(e.value)}const t=this.check(".")||this.check("?.");return"my"!==e.value||t?"its"!==e.value||t?"your"!==e.value||t?"the"===e.value?this.parseTheXofY():"values"===e.value&&this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:"values"},target:this.parsePrimary(),line:e.line,column:e.column}):this.createIdentifier(e.value):this.parseContextPropertyAccess("you"):this.parseContextPropertyAccess("it"):this.parseContextPropertyAccess("me")}if(this.match("$"))return this.parseDollarExpression();if("\\"===this.peek().value)return this.parseBlockLiteral();if(Ge(this.peek())&&this.peek().value.startsWith("@")){const e=this.advance();return{type:"attributeAccess",attributeName:e.value.substring(1),start:e.start,end:e.end,line:e.line,column:e.column}}const t=this.peek();return this.addError(`Unexpected token: ${t.value} at line ${t.line}, column ${t.column}`),this.advance(),this.createErrorNode()}parseBlockLiteral(){const e=this.peek().start;this.advance();const t=[];for(;!(this.isAtEnd()||this.check("-")&&">"===this.tokens[this.current+1]?.value);){if(!this.checkIdentifier()){this.addError("Unexpected token in block literal parameters: "+this.peek().value);break}t.push(this.advance().value),this.match(",")}return this.check("-")&&">"===this.tokens[this.current+1]?.value?(this.advance(),this.advance(),{type:"blockLiteral",parameters:t,body:this.parseExpression(),start:e,end:this.previous().end,line:this.previous().line,column:this.previous().column}):(this.addError("Expected '->' in block literal"),this.createErrorNode())}parseDollarExpression(){if(this.checkNumber()){const 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().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.check("["))this.advance(),t=this.parseExpression(),this.consume("]","Expected ']' after computed property name in object literal");else if(this.matchString()){const e=this.previous().value,n=e.slice(1,-1);t=this.createLiteral(n,e)}else{if(!this.check("-")&&!this.checkPredicate(Ye))return this.addError("Expected property name in object literal"),this.createErrorNode();{let e="",n=!1;for(;this.check("-");)this.advance(),e+="-",n=!0;for(this.checkPredicate(Ye)&&(e+=this.advance().value);this.check("-");)this.advance(),e+="-",n=!0,this.checkPredicate(Ye)&&(e+=this.advance().value);if(""===e||"-"===e)return this.addError("Expected property name in object literal"),this.createErrorNode();t=n?this.createLiteral(e,e):this.createIdentifier(e)}}this.consume(":","Expected ':' after property name in object literal");const n=this.parseExpression();if(e.push({key:t,value:n}),!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 n;if(this.matchPredicate(Ye))n=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);n=this.createLiteral(t,e)}}if(!this.consume(":","Expected ':' after CSS property name"))return this.createErrorNode();const r=[];let s=!1,i=0,o=-1,a=-1;for(;!this.isAtEnd()&&(0!==i||!this.check(";")&&!this.check("}"));){const e=this.advance();r.push(e.value),0>o&&"number"==typeof e.start&&(o=e.start),"number"==typeof e.end&&(a=e.end),"$"===e.value&&this.check("{")&&(s=!0),"{"===e.value&&i++,"}"===e.value&&i--}const c=this.originalInput&&o>=0&&a>o?this.originalInput.slice(o,a):r.join(""),l=s?{type:"templateLiteral",value:c,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}:this.createLiteral(c,c);if(t.push({key:n,value:l}),this.check(";")&&this.advance(),this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after CSS object literal properties"),{type:"objectLiteral",properties: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(),n=t.value;if(!this.check("("))return this.addError('Expected "(" after constructor name'),this.createErrorNode();this.advance();const r=[];if(!this.check(")"))do{r.push(this.parseExpression())}while(this.match(","));return this.consume(")","Expected ')' after constructor arguments"),{type:"callExpression",callee:{type:"identifier",name:n,start:t.start,end:t.end,line:t.line,column:t.column},arguments:r,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 n=[];if(this.check("(")){if(this.advance(),!this.check(")"))for(this.checkIdentifier()&&n.push(this.advance().value);this.check(",");)this.advance(),this.checkIdentifier()&&n.push(this.advance().value);this.consume(")","Expected ')' after parameter list")}const r=this.parseCommandBlock(["end","catch","finally"]);let s,i,o;return this.check("catch")&&(this.advance(),this.checkIdentifier()&&(s=this.advance().value),i=this.parseCommandBlock(["end","finally"])),this.check("finally")&&(this.advance(),o=this.parseCommandBlock(["end"])),this.consume("end","Expected 'end' after function definition"),{type:"def",name:t,params:n,body:r,...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.checkIsCommand()||this.checkIdentifierLike()?this.advance():this.consumeEvent(e);let n=t.value;return this.check(":")&&(this.advance(),n=`${n}:${this.advance().value}`),n}callExprToCommandNode(e,t){return{type:"command",name:e.callee.name,args:e.arguments,isBlocking:!1,...void 0!==t.start&&{start:t.start},...void 0!==t.end&&{end:t.end},...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}}}createPseudoCommandNode(e,t,n,r,s){return{type:"command",name:"pseudo-command",args:[{type:"objectLiteral",properties:[{key:{type:"identifier",name:"methodName"},value:{type:"literal",value:e,raw:`"${e}"`}},{key:{type:"identifier",name:"methodArgs"},value:{type:"literal",value:t.arguments,raw:JSON.stringify(t.arguments)}},...n?[{key:{type:"identifier",name:"preposition"},value:{type:"literal",value:n,raw:`"${n}"`}}]:[],{key:{type:"identifier",name:"targetExpression"},value:r}]}],isBlocking:!1,...void 0!==s.start&&{start:s.start},...void 0!==s.end&&{end:s.end},...void 0!==s.line&&{line:s.line},...void 0!==s.column&&{column:s.column}}}tryParsePseudoCommand(e,t){const n=e.callee.name,r=this.peek();if(!(Ht.PSEUDO_COMMAND_PREPOSITIONS.includes(r.value.toLowerCase())||Ye(r)&&!this.isCommand(r.value)||_e(r)))return{node:this.callExprToCommandNode(e,t),isPseudo:!1,targetFailed:!1};let s,i;this.isCommand(n)&&this.addWarning({type:"command-shadow",message:`Method '${n}' shadows hyperscript command`,suggestions:[`Rename method to avoid confusion (e.g., '${n}Fn', 'my${n.charAt(0).toUpperCase()+n.slice(1)}')`,`Use 'call' command instead: call ${n}(...)`,"This works but may cause ambiguity"],severity:"warning",code:"PSEUDO_CMD_SHADOW",...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}}),Ht.PSEUDO_COMMAND_PREPOSITIONS.includes(this.peek().value.toLowerCase())&&(s=this.advance().value.toLowerCase());try{i=this.parseExpression()}catch{return{node:this.callExprToCommandNode(e,t),isPseudo:!1,targetFailed:!0}}return{node:this.createPseudoCommandNode(n,e,s,i,t),isPseudo:!0,targetFailed:!1}}parseCommandWithErrorRecovery(){this.advance();const e=this.error;try{const t=this.parseCommand();return this.error&&this.error!==e&&(de("⚠️ Command parsing added error, restoring error state. Error was:",this.error.message),this.error=e),t}catch(t){return de("⚠️ Command parsing threw exception, restoring error state:",t instanceof Error?t.message:t+""),this.error=e,null}}parseTemporalKeywordModifiers(e){if(!this.check("debounced")&&!this.check("throttled"))return;const t=this.advance().value.toLowerCase(),n="debounced"===t?"debounce":"throttle";if(this.match("at"))if(this.checkTimeExpression()){const s=this.advance(),i=(r=s.value).endsWith("ms")?parseInt(r,10):r.endsWith("seconds")||r.endsWith("s")?1e3*parseFloat(r):r.endsWith("minutes")?6e4*parseFloat(r):r.endsWith("hours")?36e5*parseFloat(r):r.endsWith("days")?864e5*parseFloat(r):parseInt(r,10);e[n]=i,de(`🔧 parseEventHandler: Parsed '${t} at ${s.value}' (${i}ms)`)}else if(this.matchNumber()){const r=parseInt(this.previous().value,10);e[n]=r,de(`🔧 parseEventHandler: Parsed '${t} at ${r}'`)}else this.addError(`Expected time expression after '${t} at', got: ${this.peek().value}`);else this.addError(`Expected 'at' after '${t}'`);var r}parseEventHandler(){de("🔧 parseEventHandler: ENTRY - parsing event handler");const e=[];let t=!1;if(this.check("first")&&!this.checkIsCommand()&&this.tokens.length>this.current+1){const e=this.tokens[this.current+1],n=e?.value?.toLowerCase();n&&"of"!==n&&"in"!==n&&"from"!==n&&(this.advance(),t=!0,de("🔧 parseEventHandler: Parsed 'first' as .once alias"))}const n=this.parseEventNameWithNamespace("Expected event name after 'on'");for(e.push(n),de("🔧 parseEventHandler: Parsed first event name: "+n);this.check("or");){this.advance(),de("🔧 parseEventHandler: Found 'or', parsing additional event name");const t=this.parseEventNameWithNamespace("Expected event name after 'or'");e.push(t),de("🔧 parseEventHandler: Parsed additional event name: "+t)}let r;if(de("🔧 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,de(`🔧 parseEventHandler: Detected custom event source '${r}' for event '${t}'`)}}const s=[];if(this.match("(")){if(!this.check(")"))do{const e=this.advance();s.push(e.value)}while(this.match(","));this.consume(")","Expected ')' after event parameters"),de("🔧 parseEventHandler: Parsed event parameters: "+s.join(", "))}const i={};for(;this.check(".");){this.advance();const e=this.advance().value.toLowerCase();if("once"===e)i.once=!0,de("🔧 parseEventHandler: Parsed modifier '.once'");else if("prevent"===e)i.prevent=!0,de("🔧 parseEventHandler: Parsed modifier '.prevent'");else if("stop"===e)i.stop=!0,de("🔧 parseEventHandler: Parsed modifier '.stop'");else if("debounce"===e||"throttle"===e){if(!this.check("("))throw Error(`Expected '(' after '.${e}'`);{this.advance();const t=this.advance(),n=parseInt(t.value,10);if(isNaN(n))throw Error(`Expected number for ${e} delay, got: ${t.value}`);"debounce"===e?(i.debounce=n,de(`🔧 parseEventHandler: Parsed modifier '.debounce(${n})'`)):(i.throttle=n,de(`🔧 parseEventHandler: Parsed modifier '.throttle(${n})'`)),this.consume(")",`Expected ')' after ${e} delay`)}}else de(`🔧 parseEventHandler: Warning - unknown modifier '.${e}'`)}let o,a,c,l;if(this.parseTemporalKeywordModifiers(i),t&&(i.once=!0),Object.keys(i).length>0&&de("🔧 parseEventHandler: Parsed modifiers:",i),this.match("[")&&(o=this.parseExpression(),this.consume("]","Expected ']' after event condition")),this.match("from")){const e=this.advance();a=e.value,de(`🔧 parseEventHandler: Parsed 'from' target: ${a} (kind: ${e.kind})`),this.parseTemporalKeywordModifiers(i)}if(this.match("of")){const e=this.advance();c=e.value.startsWith("@")?e.value.substring(1):e.value,de("🔧 parseEventHandler: Parsed attribute name: "+c)}this.match("in")&&(de("🔧 parseEventHandler: Found 'in' keyword, parsing watch target"),l=this.parseExpression(),de("🔧 parseEventHandler: Parsed watch target expression"));const u=[];for(de(`✅ parseEventHandler: About to parse commands, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd: ${this.isAtEnd()}`);!this.isAtEnd();){if(de(`✅ parseEventHandler: Loop iteration, current token: ${this.peek().value}, kind: ${this.peek().kind}`),this.check("on")){de("✅ parseEventHandler: Stopping command parsing, found next event handler 'on'");break}if(this.checkComment())de("✅ parseEventHandler: Skipping comment token: "+this.peek().value),this.advance();else{if(this.check("end")){de("✅ 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 n=this.parseCommand();u.push(n);continue}if(e&&"callExpression"===e.type){const t=this.tryParsePseudoCommand(e,e);if(u.push(t.node),t.isPseudo||t.targetFailed)continue}}else{const e=this.parseCommandWithErrorRecovery();e&&(u.push(e),de("✅ parseEventHandler: Parsed command, next token: "+(this.isAtEnd()?"END":this.peek().value)))}}else{if(!this.checkIdentifier())break;{const e=this.peek();if(this.isCommand(e.value)){const e=this.parseCommandWithErrorRecovery();e&&u.push(e)}else{let e;const t=this.error;try{e=this.parseExpression()}catch(e){de("⚠️ Expression parsing error, restoring error state:",e instanceof Error?e.message:e+""),this.error=t;break}if(e&&"callExpression"===e.type){const t=this.tryParsePseudoCommand(e,e);if(u.push(t.node),t.targetFailed)continue}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 n={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}};u.push(n)}}}}}}for(;!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(",")||this.check("on"));)this.advance();if(!this.match("then","and",",")&&!this.checkIsCommand()&&!this.isCommand(this.peek().value))break}}const f=this.getPosition(),h={type:"eventHandler",event:1===e.length?e[0]:e.join("|"),events:e,commands:u,...s.length>0&&{args:s},...o&&{condition:o},...a&&{target:a},...c&&{attributeName:c},...l&&{watchTarget:l},...r&&{customEventSource:r},...Object.keys(i).length>0&&{modifiers:i},start:f.start,end:f.end,line:f.line,column:f.column};return de(`🔧 parseEventHandler: Created node with events: ${e.join(", ")}, attributeName: ${c||"none"}, watchTarget: ${l?"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 n=[];if(this.match("(")){if(!this.check(")"))do{const e=this.consumeIdentifierLike("Expected parameter name");n.push(e.value)}while(this.match(","));this.consume(")","Expected ')' after behavior parameters")}const r=new Set(n),s=[];let i;for(;!this.isAtEnd()&&!this.check("end");)if(this.match("on")){const e=this.getPosition(),t=this.parseEventNameWithNamespace("Expected event name after 'on'"),n=[];if(this.check("(")){for(this.advance();!this.isAtEnd()&&!this.check(")");){const e=this.peek();Ye(e)?(n.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(),n=r.has(t.value);this.checkIsCommand()&&!n||(e.push(t.value),i=t.value,this.advance())}}const o={type:"eventHandler",event:t,commands:this.parseCommandListUntilEnd(),...void 0!==i&&{target:i},...n.length>0&&{args:n},start:e.start,end:this.getPosition().end,line:e.line,column:e.column};s.push(o)}else{if(!this.match("init")){this.addError("Unexpected token in behavior body: "+this.peek().value);break}i={type:"initBlock",commands:this.parseCommandBlock(["end"]),start: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:n,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,n=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")||(de("⚠️ parseCommandSequence: Command parsing added non-critical error, restoring error state. Error was:",this.error.message),this.error=t)),e.push(n);!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("on"));)de("⚠️ parseCommandSequence: Skipping unexpected token:",this.peek().value),this.advance();if(this.check("on")){de('✅ parseCommandSequence: Found "on" token, stopping command sequence to allow event handler parsing');break}if(this.match("then"))continue;if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value))continue;break}{const t=this.peek(),n=this.getPosition(),r="Expected command, got: "+t.value;this.addError(r);const s=gt(n,r,t.value);if(e.push(s),this.synchronizeToCommandBoundary(),this.isAtEnd())break;if(this.match("then"))continue;if(this.check("end")||this.check("on"))break;if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value))continue;break}}return 1===e.length?e[0]:function(e){return{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}}(e)}getMultiWordPattern(e){return function(e){return vt.find(t=>t.command===e.toLowerCase())||null}(e)}isTokenKeyword(e,t){return bt(e,t)}parseMultiWordCommand(e,t){return function(e,t,n){const r=e.getMultiWordPattern(n);if(!r)return null;const s=[],i={};for(;!Et(e,["catch","finally",...r.keywords])&&!bt(e.peek(),r.keywords);){const t=e.parsePrimary();if(!t)break;if(s.push(t),!e.match(",")&&bt(e.peek(),r.keywords))break}for(;!e.isAtEnd()&&bt(e.peek(),r.keywords);){const t=e.advance().value,n=e.parseExpression();if(n&&(i[t]=n),!bt(e.peek(),r.keywords))break}const o=Tt.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?(de(`[Semantic] Successfully parsed with confidence ${t.confidence}:`,t.node.name),t.node):(de(`[Semantic] Low confidence (${t.confidence}), falling back to traditional parser`),null)}catch(e){return de("[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(),n=t.value.toLowerCase();if(e.includes(n))break;if(Be(t))break;this.advance()}}parseCommand(){const e=this.parseCommandCore();if(e&&"command"===e.type&&!e.body&&(this.check("when")||this.check("where"))){const t=this.peek().value.toLowerCase();this.advance();const n=this.parseExpression();n&&(e.modifiers={...e.modifiers??{},[t]:n})}return e}parseCommandCore(){const e=this.previous();let t=e.value;if(this.semanticAdapter&&!["install","wait","repeat","for","set","put","increment","decrement","add","append","toggle","if","unless","make","measure","trigger","halt","remove","exit","return","closest","js","tell"].includes(t.toLowerCase())){const e=this.getRemainingInput(),t=this.trySemanticParse(e);if(t)return this.skipToCommandBoundary(),t}if("beep"===t&&this.check("!")&&(this.advance(),t="beep!"),"fetch"===t)return function(e,t){const n={};let r=null;if(!e.isAtEnd()&&e.check("/")&&(r=function(e){const t=e.savePosition();let n="";for(;!e.isAtEnd()&&!Bt(e);)n+=e.advance().value;return n&&"/"!==n?{type:"literal",value:n,raw:n,start:t,end:e.savePosition()}:(e.restorePosition(t),null)}(e)),r||(r=e.parsePrimary()),!r)return e.addError("fetch requires a URL"),Tt.from(t).endingAt(e.getPosition()).build();!e.isAtEnd()&&e.check("{")&&(n.with=e.parsePrimary());for(let t=0;3>t&&!e.isAtEnd();t++)if(!e.check("as")||n.as){if(!e.check("with")||n.with){if(e.check("do")&&!n.doNotThrow){const t=e.peekAt(1),r=e.peekAt(2);if("not"===t?.value&&"throw"===r?.value){const t=e.advance();e.advance();const r=e.advance();n.doNotThrow={type:"literal",value:!0,start:t.start,end:r.end,line:t.line,column:t.column};continue}}break}e.advance(),n.with=qt(e)?Vt(e):e.parsePrimary()}else e.advance(),e.isAtEnd()||At(e,"a")||At(e,"an"),n.as=e.parsePrimary();const s=Tt.from(t).withArgs(r).endingAt(e.getPosition());return Object.keys(n).length>0&&s.withModifiers(n),s.build()}(this.getContext(),e);const n=this.parseMultiWordCommand(e,t);if(n)return n;const r=t.toLowerCase();if("repeat"===r)return this.parseRepeatCommand(e);if("for"===r)return this.parseForCommand(e);if("if"===r||"unless"===r)return this.parseIfCommand(e);if("wait"===r)return this.parseWaitCommand(e);if("install"===r)return this.parseInstallCommand(e);if("transition"===r)return this.parseTransitionCommand(e);if("add"===r)return this.parseAddCommand(e);if(this.isCompoundCommand(r))return this.parseCompoundCommand({type:"identifier",name:r,start:e.start||0,end:e.end||0,line:e.line,column:e.column})||function(e,t){return{type:"command",name:e,args:[],partial:!0,start:t.start,end:t.end,line:t.line,column:t.column}}(r,this.getPosition());const s=[];if(("increment"===t||"decrement"===t)&&!this.isAtEnd())return function(e,t){const n=t.value,r="increment"===n?"+":"-";let s=!1;e.check(v)&&(s=!0,e.advance());const i=e.parseExpression();if(!i)throw Error("Expected variable or expression after "+n);let o;if(e.check("by")){e.advance();const t=e.parseExpression();if(!t)throw Error(`Expected amount after 'by' in ${n} command`);o=t}else o=lt(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=ft(r,i,o,c);l.coerceNumeric=!0;const u=[a,ut(f,c),l];return Tt.from(t).withName("set").withArgs(...u).withOriginalCommand(n).endingAt({end:e.previous().end}).build()}(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 n=s[s.length-1];if(!n||"identifier"!==n.type&&"keyword"!==n.type||!t.includes(n.name??n.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 n;this.match("else")&&(n=this.parseConditionalBranch());const r=this.getPosition();return{type:"conditionalExpression",test:e,consequent:t,alternate:n,start:r.start,end:r.end,line:r.line,column:r.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())}const n=this.createCallExpression(this.createIdentifier(e),t);if("next"===e||"previous"===e){const e=this.parseRelativePositionalModifiers();e&&(n.relativePositional=e)}return n}parseRelativePositionalModifiers(){if(!(this.check("from")||this.check("within")||this.check("in")||this.check("with")))return null;let e,t,n,r=!1,s=!1;return this.match("from")&&(e=this.parseRelativePositionalOperand()),this.match("in")?(r=!0,n=this.parseRelativePositionalOperand()):this.match("within")&&(t=this.parseRelativePositionalOperand()),this.match("with")&&(this.match("wrapping"),s=!0),{from:e,within:t,inElt:n,inSearch:r,wrapping:s}}parseRelativePositionalOperand(){return this.match("the"),this.parsePrimary()}parseTheXofY(){if(!this.checkIdentifier())return this.createIdentifier("the");const e=this.peek(),t=e.value;return["first","last","next","previous","random","closest"].includes(t)?(this.advance(),this.parseNavigationFunction(t)):(this.advance(),this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:t},target:this.parseCall(),line:e.line,column:e.column}):this.createIdentifier(t))}parseContextPropertyAccess(e){if(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 n="*"+t;return this.createMemberExpression(this.createIdentifier(e),this.createIdentifier(n),!1)}{if(this.check("[")&&this.tokens[this.current+1]?.value?.startsWith("@")){this.advance();const t=this.advance();return this.consume("]","Expected ']' after attribute reference"),this.createMemberExpression(this.createIdentifier(e),{type:"attributeAccess",attributeName:t.value.substring(1),start:t.start,end:t.end,line:t.line,column:t.column},!0)}if(Ge(this.peek())&&this.peek().value.startsWith("@")){const t=this.advance();return this.createMemberExpression(this.createIdentifier(e),this.createIdentifier(t.value),!1)}const t=this.consumeIdentifierLike(`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;R(t)&&de(`💡 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 lt(e,t,this.getPosition())}createIdentifier(e){return ut(e,this.getPosition())}createBinaryExpression(e,t,n){return ft(e,t,n,this.getPosition())}createUnaryExpression(e,t,n){return function(e,t,n,r){return{type:"unaryExpression",operator:e,argument:t,prefix:n,start:r.start,end:r.end,line:r.line,column:r.column}}(e,t,n,this.getPosition())}createCallExpression(e,t){return function(e,t,n){return{type:"callExpression",callee:e,arguments:t,start:n.start,end:n.end,line:n.line,column:n.column}}(e,t,this.getPosition())}createMemberExpression(e,t,n){return function(e,t,n,r){return{type:"memberExpression",object:e,property:t,computed:n,start:r.start,end:r.end,line:r.line,column:r.column}}(e,t,n,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,n){return{type:"possessiveExpression",object:e,property:t,start:n.start,end:n.end,line:n.line,column:n.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(de(`✅ createProgramNode: Called with ${e.length} statements`),0===e.length)return de("✅ createProgramNode: Returning error node (0 statements)"),{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===e.length)return de(`✅ 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 de(`✅ 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!(!at(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(We)}matchSelector(){return this.matchPredicate(We)}checkAnySelector(){return this.checkPredicate(ze)}checkLiteral(){return this.checkPredicate(Je)}checkIdentifierLike(){return this.checkPredicate(Ue)}checkIsCommand(){return this.checkPredicate(Be)}checkCommandTerminator(){return this.checkPredicate(ct)}checkReference(){return this.checkPredicate(Ze)}checkTimeExpression(){return this.checkPredicate(Ke)}checkEvent(){return this.checkPredicate(Ve)}checkContextVar(){return this.checkPredicate(_e)}checkComment(){return this.checkPredicate(Xe)}checkIdentifier(){return this.checkPredicate(Ye)}checkKeyword(){return this.checkPredicate(qe)}checkString(){return this.checkPredicate(Qe)}matchString(){return this.matchPredicate(Qe)}checkNumber(){return this.checkPredicate(et)}matchNumber(){return this.matchPredicate(et)}checkBoolean(){return this.checkPredicate(tt)}matchBoolean(){return this.matchPredicate(tt)}checkTemplateLiteral(){return this.checkPredicate(nt)}matchTemplateLiteral(){return this.matchPredicate(nt)}checkQueryReference(){return this.checkPredicate(rt)}matchQueryReference(){return this.matchPredicate(rt)}checkIdSelector(){return this.checkPredicate(st)}checkClassSelector(){return this.checkPredicate(it)}checkCssSelector(){return this.checkPredicate(ot)}checkBasicOperator(){return this.checkPredicate(at)}matchBasicOperator(){return this.matchPredicate(at)}matchTimeExpression(){return this.matchPredicate(Ke)}matchIdentifierLike(){return this.matchPredicate(Ue)}matchComparisonOperator(){return this.matchPredicate(He)}consumePredicate(e,t){return this.checkPredicate(e)?this.advance():(this.addError(t),this.peek())}consumeIdentifier(e){return this.consumePredicate(Ye,e)}consumeIdentifierLike(e){return this.consumePredicate(Ue,e)}consumeEvent(e){return this.consumePredicate(Ve,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]}peekAt(e){const t=this.current+e;return t>=0&&this.tokens.length>t?this.tokens[t]:null}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 n=t.start||0,r=t.line||1,s=t.column||1;if(e.includes("property name after '.'")){const e=this.current>0?this.previous():t;n=e.end||e.start||0,r=e.line||1,s=e.column||1}if(e.includes("parenthes")){const e=this.current>0?this.previous():t;n=e.end||e.start||0,r=e.line||1,s=e.column||1,0===n&&this.current>0&&(n=this.current)}if(e.includes("Expected expression after")){const e=this.current>0?this.previous():t;n=e.start||0,r=e.line||1,s=e.column||1,0===n&&(n=Math.max(1,this.current-1))}if(e.includes("Missing operand")){let e=t;for(let t=this.current-1;t>=0;t--){const n=this.tokens[t];if(n&&("+"===n.value||"-"===n.value)){e=n;break}}n=e.start||0,r=e.line||1,s=e.column||1}this.error={message:e,line:Math.max(1,r),column:Math.max(1,s),position:Math.max(0,n)},this.errors.push(this.error)}synchronizeToCommandBoundary(){for(;!this.isAtEnd();){const e=this.peek();if("then"===e.value||"end"===e.value||"on"===e.value)return;if(this.checkIsCommand()||this.isCommand(e.value)&&!this.isKeyword(e.value))return;de("⚠️ synchronize: Skipping token:",e.value),this.advance()}}parseAttributeOrArrayLiteral(){const e=this.previous().start,t=this.previous().line,n=this.previous().column;if(!this.isAtEnd()&&this.peek().value.startsWith("@")){const r=[];for(;!this.check("]")&&!this.isAtEnd();){const e=this.advance();r.push(e.value)}this.consume("]","Expected ']' after attribute literal");const s=r.join("");if(!s.includes("="))return{type:"attributeAccess",attributeName:s.replace(/^@/,""),start:e,end:this.previous().end,line:t,column:n};const i="["+s+"]";return{type:"literal",value:i,raw:i,start:e,end:this.previous().end,line:t,column:n}}const r=new Set(["=","~=","|=","^=","$=","*="]),s=this.tokens[this.current],i=this.tokens[this.current+1];if("identifier"===s?.kind&&("]"===i?.value||i&&r.has(i.value)&&"string"===this.tokens[this.current+2]?.kind)){let e="["+this.advance().value;if(this.check("]"))this.advance(),e+="]";else{const t=this.advance().value,n=this.advance().value;e+=t+'"'+(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?n.slice(1,-1):n)+'"',this.consume("]","Expected ']' after attribute selector"),e+="]"}return this.createSelector(e)}const o=[];if(!this.check("]"))do{if(this.check("]"))break;o.push(this.parseExpression())}while(this.match(","));return this.consume("]","Expected ']' after array elements"),{type:"arrayLiteral",elements:o,start:e,end:this.previous().end,line:t,column:n}}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),parseExpression:this.parseExpression.bind(this),parsePrimary:this.parsePrimary.bind(this),parseLogicalAnd:this.parseLogicalAnd.bind(this),parseCSSObjectLiteral:this.parseCSSObjectLiteral.bind(this),parseCommand:this.parseCommand.bind(this),parseCommandSequence:this.parseCommandSequence.bind(this),parseCommandListUntilEnd:this.parseCommandListUntilEnd.bind(this),parseCommandListUntilEndOrElse:this.parseCommandListUntilEndOrElse.bind(this),parseRepeatBody:this.parseRepeatBody.bind(this),getPosition:this.getPosition.bind(this),addError:this.addError.bind(this),addWarning:this.addWarning.bind(this),isCommand:this.isCommand.bind(this),isCompoundCommand:this.isCompoundCommand.bind(this),isKeyword:this.isKeyword.bind(this),getMultiWordPattern:this.getMultiWordPattern.bind(this),resolveKeyword:this.resolveKeyword.bind(this),savePosition:()=>e.current,restorePosition:t=>{e.current=t},peekAt:t=>e.peekAt(t),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 Ut(e,t){const n=function(e){const t={input:"",position:0,line:1,column:1,tokens:[]};t.input=e;const n=e.length;for(;n>t.position&&(_(t),n>t.position);){const n=e[t.position];if("-"!==n||"-"!==q(t,1))if('"'!==n){if("'"===n||"'"===n){const e=q(t,1),n=t.tokens[t.tokens.length-1];if("s"!==e||!n||n.kind!==P.IDENTIFIER&&n.kind!==P.SELECTOR&&"]"!==n.value&&")"!==n.value&&"}"!==n.value)W(t);else{const e=t.position;V(t),V(t),H(t,P.OPERATOR,"'s",e)}continue}if("`"!==n)if("<"!==n)if("#"!==n){if("."===n){if("."===q(t,1)){const e=t.position;V(t),V(t),H(t,P.OPERATOR,"..",e);continue}const e=t.tokens[t.tokens.length-1],n=new Set(["from","to","into","on","in","at","between","first","last","next","previous","closest","random","of","some","no"]),r=e&&e.kind===P.IDENTIFIER&&E.has(e.value.toLowerCase()),s=e&&e.kind===P.IDENTIFIER&&n.has(e.value.toLowerCase());if((!e||e.kind===P.OPERATOR&&")"!==e.value&&"]"!==e.value||r||s||"("===e.value||"["===e.value||"{"===e.value||","===e.value||";"===e.value)&&(!e||e.end!==t.position)&&(te(q(t))||"{"===q(t)||"-"===q(t))){Z(t);continue}}if("@"!==n)if("{"!==n)if("}"!==n){if("["===n){const e=t.tokens[t.tokens.length-1],n=e&&e.kind===P.IDENTIFIER&&M.has(e.value)&&t.tokens.length>=2&&"on"===t.tokens[t.tokens.length-2]?.value;(!e||e.kind!==P.IDENTIFIER&&")"!==e.value&&"]"!==e.value||n)&&n?(H(t,P.SYMBOL,"["),V(t)):(H(t,P.OPERATOR,"["),V(t));continue}if("]"!==n){if("$"===n){const e=q(t,1);if(e>="a"&&"z">=e||e>="A"&&"Z">=e||"_"===e){ee(t);continue}}ie(n)?X(t):"0">n||n>"9"?("a">n||n>"z")&&("A">n||n>"Z")&&"_"!==n?(H(t,P.UNKNOWN,n),V(t)):Q(t):Y(t)}else H(t,P.OPERATOR,"]"),V(t)}else H(t,P.OPERATOR,"}"),V(t);else H(t,P.OPERATOR,"{"),V(t);else G(t)}else Z(t);else se(t)?K(t):X(t);else J(t)}else W(t);else z(t)}return t.tokens}(e);return new Ht(n,t,e).parse()}Ht.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty","ignoring case"]),Ht.PRATT_TABLE=Ae,Ht.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];class zt{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 n of this.afterExecuteHooks)await n(e,t)}async runOnError(e,t){let n=t;for(const t of this.onErrorHooks){const r=await t(e,n);r instanceof Error&&(n=r)}return n}shouldIntercept(e,t){for(const n of this.interceptCommandHooks)if(n(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 Wt(e){return e instanceof Error&&("isHalt"in e||"isExit"in e||"isBreak"in e||"isContinue"in e||"isReturn"in e)?e:null}function Jt(e){return{ok:!0,value:e}}function Zt(e){return{ok:!1,error:e}}function Kt(e){return!0===e.ok}const Gt=new Map,Xt=new WeakMap;function Yt(e){let t=Xt.get(e);return t||(t=new Map,Xt.set(e,t)),t}function Qt(e){return e.owner||(e.me instanceof Element?e.me:null)}function en(e,t){const n=Qt(e);if(n)return Pe(t,e),Yt(n).get(t)}function tn(e,t,n){const r=Qt(e);r&&(Yt(r).set(t,n),De(t,n,e))}function nn(e,t){return{me:e??null,owner:e??null,it:null,you:null,result:null,locals:new Map,globals:t||Gt,flags:{halted:!1,breaking:!1,continuing:!1,returning:!1,async:!1}}}function rn(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"tagName"in e&&"string"==typeof e.tagName&&"classList"in e}function sn(e){return null!==e&&"object"==typeof e&&"length"in e&&"number"==typeof e.length&&(Symbol.iterator in e||"function"==typeof e.item)}function on(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 an(e,t,n){return"element"===n?en(t,e):"global"===n&&t.globals&&t.globals.has(e)?t.globals.get(e):"global"!==n&&t.locals&&t.locals.has(e)?(Pe(e,t),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"===n&&t.locals&&t.locals.has(e)?(Pe(e,t),t.locals.get(e)):"undefined"!=typeof window&&e in window?window[e]:"undefined"!=typeof globalThis&&e in globalThis?globalThis[e]:void 0}function cn(e,t,n,r){if("element"!==r){if("global"===r)return Fe(n,e,t),void("undefined"!=typeof window&&(window[e]=t));if(e.startsWith("$"))return void Fe(n,e.slice(1),t);if(n.locals&&n.locals.has(e))return n.locals.set(e,t),void De(e,t,n);if(n.globals&&n.globals.has(e))return Fe(n,e,t),void("undefined"!=typeof window&&e in window&&(window[e]=t));if(n.variables&&n.variables.has(e))n.variables.set(e,t);else{if("undefined"!=typeof window&&e in window)return window[e]=t,void Fe(n,e,t);n.locals.set(e,t),De(e,t,n)}}else tn(n,e,t)}function ln(e,t){return"me"===e?t.me:"it"===e?t.it:"you"===e?t.you:an(e,t)}const un=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,n]of this.types)if(n.isType(e))return t;return"Unknown"}getHyperScriptType(e){const t=this.inferType(e),n=this.types.get(t);return n?.hyperscriptType??"unknown"}coerce(e,t,n){const r=this.types.get(t);if(!r){if(this.config.strictMode)throw Error("Unknown target type: "+t);return null}if(r.isType(e))return e;if(this.config.cacheCoercions){const n=`${this.inferType(e)}:${t}:${JSON.stringify(e)}`;if(this.coercionCache.has(n))return this.coercionCache.get(n)}const s=this.inferType(e),i=r.coerceFrom?.[s];if(i){const r=i(e,n);if(this.config.cacheCoercions&&null!==r){const n=`${s}:${t}:${JSON.stringify(e)}`;this.coercionCache.set(n,r)}return r}return r.defaultValue}canCoerce(e,t){const n=this.types.get(t);if(!n)return!1;if(n.isType(e))return!0;const r=this.inferType(e);return void 0!==n.coerceFrom?.[r]}getCoercionInfo(e,t){const n=this.types.get(t);return n&&(e===t||n.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 n=e;if(n.startsWith("#")||n.startsWith(".")||n.match(/^[\w-]+$/))try{return document.querySelector(n)}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,n)=>{t[n+""]=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 fn(e){const t=un.get("String");return t?t.isType(e):"string"==typeof e}function hn(e){const t=un.get("Number");return t?t.isType(e):"number"==typeof e}function dn(e){const t=un.get("Boolean");return t?t.isType(e):"boolean"==typeof e}function pn(e){const t=un.get("Object");return t?t.isType(e):"object"==typeof e&&null!==e}function mn(e){const t=un.get("Function");return t?t.isType(e):"function"==typeof e}function yn(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"style"in e}function gn(e){return e instanceof Element}function vn(e){return e instanceof HTMLElement}const bn=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function wn(e,t){return bn.has(t.toLowerCase())?e.hasAttribute(t):e.getAttribute(t)}const En={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=>function(e){if(null===e||"object"!=typeof e||!("tagName"in e))return!1;const t=e.tagName;return"INPUT"===t||"SELECT"===t||"TEXTAREA"===t}(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=>"disabled"in 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,tabindex:e=>yn(e)?e.tabIndex:void 0,hidden:e=>yn(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,next:e=>e.nextElementSibling,previous:e=>e.previousElementSibling,values:e=>function(e){if(e instanceof HTMLFormElement)return new FormData(e);const t=new FormData;return e.querySelectorAll("input, select, textarea").forEach(e=>{const n=e.getAttribute("name");n&&"value"in e&&t.append(n,e.value)}),t}(e)};function xn(e,t){if(t.startsWith("*"))return function(e,t){if(!vn(e))return;if(t.startsWith("computed-"))return getComputedStyle(e).getPropertyValue(t.slice(9))||"";const n=t.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());return e.style[n]}(e,t.slice(1));if(t.startsWith("computed-")){const n=t.slice(9);return vn(e)?getComputedStyle(e).getPropertyValue(n):void 0}if(t.startsWith("@"))return wn(e,t.slice(1));const n=En[t.toLowerCase()];if(n)return n(e);if(function(e,t){return e.hasAttribute(t)}(e,t))return wn(e,t);const r=e[t];return mn(r)?r.bind(e):r}const kn={1:"one",2:"two",3:"three",4:"four",5:"five"};function Sn(e,t,n,r){if(e.length!==t){return`${n} requires exactly ${s=t,kn[s]??s+""} argument${1===t?"":"s"}${r?` (${r})`:""}`}var s;return null}function An(e,t,n,r){return"string"!=typeof e[t]?`${n} ${r||"argument "+(t+1)} must be a string`:null}function Nn(e,t,n){return Sn(e,1,t,n)??An(e,0,t,n)}function Tn(e,t){return Sn(e,2,t,"left, right")}function Cn(){return null}function On(e,t,n,r){return e.length>t?`${n} expression takes at most ${1===t?"one":t+""} argument${1===t?"":"s"}${r?` (${r})`:""}`:null}function Rn(e,t,n,r,s){return t>e.length||e.length>n?`${r} requires ${t}-${n} arguments${s?` (${s})`:""}`:null}function $n(e,t,n,r=[]){return{type:e,message:t,suggestions:r,...n&&{path:n}}}const Ln="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 jn;function In(){return jn({validate:e=>({success:!0,data:e})})}function Mn(e,t){if(Ln)return In();const n=jn({validate:n=>{if("object"!=typeof n||null===n||Array.isArray(n))return{success:!1,error:$n("type-mismatch","Expected object, received "+typeof n)};const r=n,s={};if(t?.strict){const t=Object.keys(e),n=Object.keys(r).filter(e=>!t.includes(e));if(n.length>0)return{success:!1,error:$n("runtime-error","Unexpected properties: "+n.join(", "))}}for(const[t,n]of Object.entries(e)){const e=r[t];if(!(t in r)&&!n.t)return{success:!1,error:$n("missing-argument",`Required field "${t}" is missing`,t)};const i=n.validate(e);if(!i.success)return{success:!1,error:$n("validation-error",i.error.message||`Field "${t}" validation failed`,i.error.path?`${t}.${i.error.path}`:t)};void 0!==i.data&&(s[t]=i.data)}return{success:!0,data:s}}});return n.strict=()=>Mn(e,{strict:!0}),n}jn=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 jn(t)}),e.min||(e.min=function(e){const t=this.validate.bind(this),n={...this,validate:n=>{const r=t(n);return r.success&&"string"==typeof r.data&&e>r.data.length?{success:!1,error:$n("runtime-error",`String must be at least ${e} characters long`)}:r}};return jn(n)}),e.max||(e.max=function(e){const t=this.validate.bind(this),n={...this,validate:n=>{const r=t(n);return r.success&&"string"==typeof r.data&&r.data.length>e?{success:!1,error:$n("runtime-error",`String must be at most ${e} characters long`)}:r}};return jn(n)}),e.default||(e.default=function(e){const t=this.validate.bind(this),n={...this,i:e,o:!0,validate:n=>void 0===n?{success:!0,data:e}:t(n)};return jn(n)}),e.rest||(e.rest=function(e){return this}),e.refine||(e.refine=function(e,t){const n=this.validate.bind(this),r={...this,validate:r=>{const s=n(r);return s.success?e(s.data)?s:{success:!1,error:$n("runtime-error",t||"Refinement validation failed")}:s}};return jn(r)}),new Proxy(e,{get:(e,t,n)=>t in e||"string"!=typeof t||t.startsWith("_")||"constructor"===t||"validate"===t||"then"===t?Reflect.get(e,t,n):function(...e){return n}})};const Dn=e=>function(e={}){return Ln?In():jn({validate:t=>e.optional&&null==t?{success:!0,data:void 0}:"string"!=typeof t?{success:!1,error:$n("type-mismatch","Expected string, received "+typeof t)}:void 0!==e.minLength&&e.minLength>t.length?{success:!1,error:$n("runtime-error",`String must be at least ${e.minLength} characters long`)}:void 0!==e.maxLength&&t.length>e.maxLength?{success:!1,error:$n("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:$n("runtime-error",`Expected "${e.pattern.source.slice(1,-1)}", received "${t}"`)}:{success:!1,error:$n("missing-argument","String does not match required pattern")}:{success:!0,data:t},...e.description&&{description:e.description}})}(e||{}),Pn=e=>function(e={}){return Ln?In():jn({validate:t=>{const n=Number(t);return isNaN(n)?{success:!1,error:$n("type-mismatch","Expected number, received "+typeof t)}:void 0!==e.min&&e.min>n?{success:!1,error:$n("runtime-error","Number must be at least "+e.min)}:void 0!==e.max&&n>e.max?{success:!1,error:$n("runtime-error","Number must be at most "+e.max)}:{success:!0,data:n}}})}(e||{}),Fn=()=>Ln?In():jn({validate:e=>"boolean"!=typeof e?{success:!1,error:$n("type-mismatch","Expected boolean, received "+typeof e)}:{success:!0,data:e}}),Bn=e=>Mn(e),qn=e=>function(e){return Ln?In():jn({validate:t=>{if(!Array.isArray(t))return{success:!1,error:$n("type-mismatch","Expected array, received "+typeof t)};if(t.length!==e.length)return{success:!1,error:$n("runtime-error",`Expected tuple of length ${e.length}, received length ${t.length}`)};const n=[];for(let r=0;e.length>r;r++){const s=e[r].validate(t[r]);if(!s.success)return{success:!1,error:$n("runtime-error",s.error.message,s.error.path?`${r}.${s.error.path}`:""+r)};n.push(s.data)}return{success:!0,data:n}}})}(e),Vn=()=>In(),_n=()=>In(),Hn=()=>function(e,t="Custom validation failed"){return Ln?In():jn({validate:n=>e(n)?{success:!0,data:n}:{success:!1,error:$n("runtime-error",t)}})}(e=>void 0===e,"Expected undefined");class Un{trackPerformance(e,t,n,r){e.evaluationHistory&&e.evaluationHistory.push({expressionName:this.name,category:this.category,input:t,output:n.success?n.value:n.error,timestamp:r,duration:Date.now()-r,success:n.success})}trackSimple(e,t,n,r=(n?"success":"error")){e.evaluationHistory&&e.evaluationHistory.push({expressionName:this.name,category:this.category,input:"operation",output:r,timestamp:t,duration:Date.now()-t,success:n})}toBoolean(e){return!(!1===e||0===e||0n===e||""===e||null==e||hn(e)&&isNaN(e))}success(e,t){return{success:!0,value:e,type:t}}failure(e,t,n,r,s=[]){return{success:!1,error:{name:e,type:t,message:n,code:r,suggestions:s}}}validationSuccess(){return{isValid:!0,errors:[],suggestions:[]}}validationFailure(e,t,n=[]){return{isValid:!1,errors:[{type:e,message:t,suggestions:n}],suggestions:n}}isElement(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"tagName"in e&&"string"==typeof e.tagName}inferType(e){return null===e?"null":void 0===e?"undefined":this.isElement(e)?"element":Array.isArray(e)?"array":pn(e)?"object":typeof e}inferEvaluationType(e){return void 0===e?"Undefined":null===e?"Null":fn(e)?"String":hn(e)?"Number":dn(e)?"Boolean":Array.isArray(e)?"Array":this.isElement(e)?"Element":"Object"}normalizeCollection(e){return Array.isArray(e)?e:e instanceof NodeList?Array.from(e):fn(e)?e.split(""):null==e?[]:pn(e)&&Symbol.iterator in e?Array.from(e):[]}toNumber(e){if(hn(e)&&Number.isFinite(e))return e;if(fn(e)){const t=Number(e);return Number.isFinite(t)?t:null}return dn(e)?e?1:0:null}}function zn(e,t,n,r,s="runtime-error"){return{success:!1,error:{name:e+"ConversionError",type:s,message:n,code:t,suggestions:r}}}function Wn(e,t){return{success:!0,value:e,type:t}}function Jn(e,t){return`${e}: ${t instanceof Error?t.message:t+""}`}const Zn={Array:(e,t)=>{try{return Array.isArray(e)?Wn(e,"array"):e instanceof NodeList?Wn(Array.from(e),"array"):Wn(null==e?[]:[e],"array")}catch(e){return zn("Array","ARRAY_CONVERSION_FAILED",Jn("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?Wn("","string"):fn(e)?Wn(e,"string"):pn(e)?Wn(JSON.stringify(e),"string"):Wn(e+"","string")}catch(e){return zn("String","STRING_CONVERSION_FAILED",Jn("Failed to convert value to String",e),["Check if object has circular references","Ensure value is serializable"])}},Boolean:(e,t)=>{try{if(dn(e))return Wn(e,"boolean");if(null==e)return Wn(!1,"boolean");if(fn(e)){const t=e.toLowerCase().trim();return Wn("false"!==t&&"0"!==t&&""!==t,"boolean")}return hn(e)?Wn(0!==e&&!isNaN(e),"boolean"):Wn(!!e,"boolean")}catch(e){return zn("Boolean","BOOLEAN_CONVERSION_FAILED",Jn("Failed to convert value to Boolean",e),["Use explicit true/false values","Check for unexpected data types"])}},Number:(e,t)=>{try{if(hn(e))return Wn(e,"number");if(null==e)return Wn(0,"number");const t=Number(e);return isNaN(t)?zn("Number","INVALID_NUMBER",`Cannot convert "${e}" to a valid number`,["Check if value contains non-numeric characters","Use a valid numeric format"],"invalid-argument"):Wn(t,"number")}catch(e){return zn("Number","NUMBER_CONVERSION_FAILED",Jn("Failed to convert value to Number",e),["Ensure value is convertible to number","Check for special characters"])}},Int:(e,t)=>{const n=Zn.Number(e,t);return n.success?Wn(Math.trunc(n.value),"number"):n},Float:(e,t)=>{const n=Zn.Number(e,t);return n.success?Wn(parseFloat(""+n.value),"number"):n},Date:(e,t)=>{try{if(e instanceof Date)return Wn(e,"object");if(null==e)return Wn(new Date(""),"object");if(fn(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,n,r]=e.split("-").map(Number);return Wn(new Date(t,n-1,r),"object")}const t=new Date(e);return isNaN(t.getTime())?zn("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"):Wn(t,"object")}catch(e){return zn("Date","DATE_CONVERSION_FAILED",Jn("Failed to convert value to Date",e),["Check date format","Ensure value is a valid date string or timestamp"])}},JSON:(e,t)=>{if(!fn(e))return Wn(e,"object");try{return Wn(JSON.parse(e),"object")}catch(e){return zn("JSON","JSON_PARSE_FAILED",Jn("Failed to parse value as JSON",e),["Check JSON syntax and escaping","Use `as JSONString` to stringify a value instead"],"syntax-error")}},JSONString:(e,t)=>{try{return Wn(JSON.stringify(e),"string")}catch(e){return zn("JSONString","JSON_STRINGIFY_FAILED",Jn("Failed to stringify value as JSON",e),["Check for circular references","Ensure all properties are serializable","Remove functions and undefined values"])}},Object:(e,t)=>{try{if(pn(e))return Wn(e,"object");if(fn(e))try{return Wn(JSON.parse(e),"object")}catch(e){return zn("Object","JSON_PARSE_FAILED",Jn("Cannot parse JSON string",e),["Check JSON syntax","Ensure proper escaping of quotes","Validate JSON format"],"syntax-error")}return Wn({},"object")}catch(e){return zn("Object","OBJECT_CONVERSION_FAILED",Jn("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 Wn(Qn(e),"object");if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),n={};return t.forEach(e=>{const t=e;if(t.name){const e=er(t);void 0!==e&&(n[t.name]=e)}}),Wn(n,"object")}return Wn({},"object")}catch(e){return zn("FormValues","FORM_VALUES_EXTRACTION_FAILED",Jn("Failed to extract form values",e),["Ensure element is a form or contains form inputs","Check form structure","Verify input names are set"])}},FormEncoded:(e,t)=>{try{let n=e;if(e instanceof HTMLElement){const r=Zn.Values(e,t);if(!r.success)return r;n=r.value}if(!pn(n))return Wn("","string");const r=new URLSearchParams;for(const[e,t]of Object.entries(n))if(null!=t)if(Array.isArray(t))for(const n of t)r.append(e,n+"");else r.append(e,t+"");return Wn(""+r,"string")}catch(e){return zn("FormEncoded","FORM_ENCODE_FAILED",Jn("Failed to URL-encode values",e),["Ensure input is a form element or plain object of scalar/array values"])}},Set:(e,t)=>{try{return Wn(new Set(e),"object")}catch(e){return zn("Set","SET_CONVERSION_FAILED",Jn("Failed to convert to Set",e),["Ensure the value is iterable"])}},Map:(e,t)=>{try{return Wn(new Map(Object.entries(e??{})),"object")}catch(e){return zn("Map","MAP_CONVERSION_FAILED",Jn("Failed to convert to Map",e),["Ensure the value is a plain object"])}},Keys:(e,t)=>e instanceof Map?Wn(Array.from(e.keys()),"array"):Wn(Object.keys(e??{}),"array"),Entries:(e,t)=>e instanceof Map?Wn(Array.from(e.entries()),"array"):Wn(Object.entries(e??{}),"array"),Reversed:(e,t)=>{try{return Wn(Array.from(e).reverse(),"array")}catch(e){return zn("Reversed","REVERSED_CONVERSION_FAILED",Jn("Failed to reverse value",e),["Ensure the value is array-like"])}},Unique:(e,t)=>{try{return Wn([...new Set(e)],"array")}catch(e){return zn("Unique","UNIQUE_CONVERSION_FAILED",Jn("Failed to dedupe value",e),["Ensure the value is iterable"])}},Flat:(e,t)=>{try{return Wn(Array.from(e).flat(),"array")}catch(e){return zn("Flat","FLAT_CONVERSION_FAILED",Jn("Failed to flatten value",e),["Ensure the value is array-like"])}}},Kn=Bn({value:_n(),type:Dn().min(1)}),Gn=Bn({value:_n(),type:Dn().min(1)});new class extends Un{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=Kn,this.metadata={category:"Conversion",complexity:"medium",sideEffects:[],dependencies:[],returnTypes:["Any"],examples:[{input:'"123" as Int',description:"Convert string to integer",expectedOutput:123},{input:"form as Values",description:"Extract form values as object",expectedOutput:{name:"John",age:"25"}},{input:"[1,2,3] as JSONString",description:"Convert array to JSON string (upstream 0.9.90: use JSONString, not JSON)",expectedOutput:"[1,2,3]"},{input:"'{\"a\":1}' as JSON",description:"Parse a JSON string (upstream 0.9.90: as JSON now parses)",expectedOutput:{a:1}},{input:'"2023-12-25" as Date',description:"Parse date string",expectedOutput:new Date(2023,11,25)}],relatedExpressions:["is","Object","Array"],performance:{averageTime:1,complexity:"O(n)"}},this.documentation={summary:'Converts values between different types using the "as" keyword with comprehensive type safety',parameters:[{name:"value",type:"object",description:"The value to convert",optional:!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 JSONString into storage",explanation:"Convert array to JSON string for storage (upstream 0.9.90: use `as JSONString`)",output:'"[1,2,3]"'},{title:"Date parsing with validation",code:"put my.dateInput as Date into event.detail.date",explanation:"Parse date input with automatic validation",output:"Date object or validation error"},{title:"Boolean conversion with smart parsing",code:'if "false" as Boolean then hide else show',explanation:"Parse string boolean values correctly",output:"false (not true like naive conversion)"}],seeAlso:["is","Values","JSON","Array","Object"],tags:["conversion","types","validation","forms","json","parsing"]}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:{name:"AsExpressionValidationError",type:"validation-error",message:r.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:r.suggestions}};const{value:s,type:i}=t;if(i.startsWith("Fixed")){const r=i.match(/^Fixed:(\d+)$/),o=r?parseInt(r[1],10):0,a=Zn.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,n),c}let o=Zn[i];if(o){const r=o(s,e);return this.trackPerformance(e,t,r,n),r}const a={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON",jsonstring:"JSONString",formencoded:"FormEncoded"}[i.toLowerCase()];if(a&&(o=Zn[a],o)){const r=o(s,e);return this.trackPerformance(e,t,r,n),r}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,n),c}catch(r){const s={success:!1,error:{name:"AsExpressionError",type:"runtime-error",message:"Conversion failed: "+(r instanceof Error?r.message:r+""),code:"CONVERSION_FAILED",suggestions:["Check value and type compatibility","Ensure value is convertible to target type"]}};return this.trackPerformance(e,t,s,n),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 Un{constructor(){super(...arguments),this.name="is",this.category="Conversion",this.syntax="value is Type",this.description="Checks if a value is of a specific type",this.outputType="Boolean",this.inputSchema=Gn,this.metadata={category:"Conversion",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"42 is number",description:"Check if value is a number",expectedOutput:!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 n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:{name:"IsExpressionValidationError",type:"validation-error",message:r.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:r.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=fn(s);break;case"number":a=hn(s)&&!isNaN(s);break;case"boolean":a=dn(s);break;case"object":a=pn(s);break;case"array":a=Array.isArray(s);break;case"function":a=mn(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||pn(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,n),c}catch(r){const s=this.failure("IsExpressionError","type-mismatch","Type check failed: "+(r instanceof Error?r.message:r+""),"TYPE_CHECK_FAILED",["Check type name spelling","Ensure value is accessible"]);return this.trackPerformance(e,t,s,n),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 Xn={conversions:{dynamicResolvers:[]}},Yn={Array:e=>Array.isArray(e)?e:e instanceof NodeList?Array.from(e):null==e?[]:[e],String:e=>null==e?"":fn(e)?e:pn(e)?JSON.stringify(e):e+"",Boolean:e=>{if(dn(e))return e;if(null==e)return!1;if(fn(e)){const t=e.toLowerCase().trim();return"false"!==t&&"0"!==t&&""!==t}return hn(e)?0!==e&&!isNaN(e):!!e},Number:e=>{if(hn(e))return e;if(null==e)return 0;const t=Number(e);return isNaN(t)?0:t},Math:e=>{if(hn(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(!hn(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=Yn.Number(e);return Math.trunc(t)},Float:e=>{const t=Yn.Number(e);return parseFloat(""+t)},Date:e=>{if(e instanceof Date)return e;if(null==e)return new Date(NaN);if(fn(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,n,r]=e.split("-").map(Number);return new Date(t,n-1,r)}return new Date(e)},JSON:e=>{if(!fn(e))return e;try{return JSON.parse(e)}catch{return e}},JSONString:e=>{try{return JSON.stringify(e)}catch{return"{}"}},Object:e=>{if(pn(e))return e;if(fn(e))try{return JSON.parse(e)}catch(e){return{}}return{}},Fragment:e=>{const t=document.createDocumentFragment(),n=Array.isArray(e)||e instanceof NodeList?Array.from(e):[e];for(const e of n)if(e instanceof Node)t.append(e);else{const n=document.createElement("template");n.innerHTML=null==e?"":e+"",t.append(n.content)}return t},HTML:e=>fn(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:Yn.String(e)).join(""):e instanceof Element?e.outerHTML:Yn.String(e),Values:(e,t)=>{if(e instanceof HTMLFormElement)return Qn(e);if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),n={};return t.forEach(e=>{e.name&&(n[e.name]=er(e))}),n}return{}},FormEncoded:(e,t)=>{const n=e instanceof HTMLElement?Yn.Values(e,t):e;if(!pn(n))return"";const r=new URLSearchParams;for(const[e,t]of Object.entries(n))if(null!=t)if(Array.isArray(t))for(const n of t)r.append(e,n+"");else r.append(e,t+"");return""+r},Set:e=>new Set(e),Map:e=>new Map(Object.entries(e??{})),Keys:e=>e instanceof Map?Array.from(e.keys()):Object.keys(e??{}),Entries:e=>e instanceof Map?Array.from(e.entries()):Object.entries(e??{}),Reversed:e=>Array.from(e).reverse(),Unique:e=>[...new Set(e)],Flat:e=>Array.from(e).flat(),"Values:Form":(e,t)=>{const n=Yn.Values(e,t);return Yn.FormEncoded(n,t)},"Values:JSON":(e,t)=>{const n=Yn.Values(e,t);return JSON.stringify(n)}};function Qn(e){const t={};return e.querySelectorAll("input, select, textarea").forEach(e=>{const n=e;if(n.name){const e=er(n);void 0!==e&&(void 0!==t[n.name]?(Array.isArray(t[n.name])||(t[n.name]=[t[n.name]]),t[n.name].push(e)):t[n.name]=e)}}),t}function er(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 tr={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON",jsonstring:"JSONString",formencoded:"FormEncoded"};function nr(e,t,n){if("string"!=typeof t)throw Error("Conversion type must be a string");if(t.startsWith("Fixed")){const{precision:n}=function(e){const t=e.match(/^Fixed(?::(\d+))?$/);return t?{precision:t[1]?parseInt(t[1],10):0}:{}}(t);return Yn.Number(e).toFixed(n??0)}if(null==e)return e;let r=Yn[t];if(r)return r(e,n);const s=tr[t.toLowerCase()];if(s&&(r=Yn[s],r))return r(e,n);const i=Xn.conversions[t];if("function"==typeof i)return i(e,n);for(const n of Xn.conversions.dynamicResolvers){const r=n(t,e);if(void 0!==r)return r}return console.warn("Unknown conversion type: "+t),e}const rr={as:{name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(e,...t){const[n,r]=t;return nr(n,r,e)},validate:e=>Sn(e,2,"as","value, type")??An(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[n,r]=t;if(!fn(r))throw Error("Type check requires a string type");switch(r.toLowerCase()){case"null":return null===n;case"undefined":return void 0===n;case"string":return fn(n);case"number":return hn(n)&&!isNaN(n);case"boolean":return dn(n);case"object":return pn(n);case"array":return Array.isArray(n);case"function":return mn(n);case"date":return n instanceof Date;case"element":return n instanceof Element;case"node":return n instanceof Node;case"nodelist":return n instanceof NodeList;case"empty":return null==n||""===n||Array.isArray(n)&&0===n.length||pn(n)&&0===Object.keys(n).length;default:return n?.constructor?.name?.toLowerCase()===r.toLowerCase()}},validate:e=>Sn(e,2,"is","value, type")??An(e,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(e,t)=>t,validate:e=>Sn(e,1,"async","expression")}},sr=new Set(["__proto__","constructor","prototype"]);function ir(e,t){if(e instanceof Element)return xn(e,t);if(pn(e)){if(sr.has(t))return;return e[t]}return e[t]}function or(e){let t;if(Array.isArray(e))t=e;else{if(!("undefined"!=typeof NodeList&&e instanceof NodeList||"undefined"!=typeof HTMLCollection&&e instanceof HTMLCollection))return!1;t=Array.from(e)}return 0!==t.length&&t.every(e=>e instanceof Element||null!=e&&"object"==typeof e&&e.constructor!==Object&&!Array.isArray(e))}const ar={possessive:{name:"possessive",category:"Reference",evaluatesTo:"Any",operators:["'s","s"],async evaluate(e,...t){const[n,r]=t;if(null!=n){if("string"!=typeof r)throw Error("Property name must be a string");return or(n)&&!(r in n)?Array.from(n,e=>ir(e,r)):ir(n,r)}},validate:e=>Sn(e,2,"possessive","element, property")??An(e,1,"possessive","property name")},my:{name:"my",category:"Reference",evaluatesTo:"Any",operators:["my"],async evaluate(e,...t){const[n]=t;if(e.me){if("string"!=typeof n)throw Error("Property name must be a string");if(e.me instanceof Element)return xn(e.me,n);if(pn(e.me)){if(sr.has(n))return;return e.me[n]}return e.me[n]}},validate:e=>Nn(e,"my","property")},its:{name:"its",category:"Reference",evaluatesTo:"Any",operators:["its"],async evaluate(e,...t){const[n]=t;if(null==e.it)return;if("string"!=typeof n)throw Error("Property name must be a string");const r=e.it;if(r instanceof Element)return xn(r,n);if(pn(r)){if(sr.has(n))return;return r[n]}return r[n]},validate:e=>Nn(e,"its","property")},your:{name:"your",category:"Reference",evaluatesTo:"Any",operators:["your"],async evaluate(e,...t){const[n]=t;if(e.you){if("string"!=typeof n)throw Error("Property name must be a string");if(e.you instanceof Element)return xn(e.you,n);if(pn(e.you)){if(sr.has(n))return;return e.you[n]}return e.you[n]}},validate:e=>Nn(e,"your","property")},of:{name:"of",category:"Reference",evaluatesTo:"Any",operators:["of"],async evaluate(e,...t){const[n,r]=t;if(null!=r){if("string"!=typeof n)throw Error("Property name must be a string");if(r instanceof Element)return xn(r,n);if(pn(r)){if(sr.has(n))return;return r[n]}return r[n]}},validate:e=>Sn(e,2,"of","property, object")??An(e,0,"of","property name")},attribute:{name:"attribute",category:"Reference",evaluatesTo:"String",operators:["@"],async evaluate(e,...t){const[n,r]=t;if("string"!=typeof n)throw Error("Attribute name must be a string");const s=r||e.me;return s&&s instanceof Element?s.getAttribute(n):null},validate:e=>Rn(e,1,2,"attribute","attributeName, optional element")??An(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[n,r,s]=t;if("string"!=typeof n)throw Error("Attribute name must be a string");if("string"!=typeof r)throw Error("Expected value must be a string");const i=s||e.me;return!!(i&&i instanceof Element)&&i.getAttribute(n)===r},validate:e=>Rn(e,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??An(e,0,"attributeWithValue","attribute name")??An(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[n]=t;if("string"!=typeof n)throw Error("Class name must be a string");const r=n.startsWith(".")?n.slice(1):n,s=document.getElementsByClassName(r);return Array.from(s)},validate:e=>Nn(e,"classReference","className")},idReference:{name:"idReference",category:"Reference",evaluatesTo:"Element",operators:["#"],async evaluate(e,...t){const[n]=t;if("string"!=typeof n)throw Error("ID value must be a string");const r=n.startsWith("#")?n.slice(1):n;return document.getElementById(r)},validate:e=>Nn(e,"idReference","idValue")}};function cr(e){return Array.isArray(e)?e:null==e?[]:"string"==typeof e?[e]:e instanceof NodeList||e instanceof HTMLCollection||"number"==typeof e.length?Array.from(e):[e]}function lr(e,t){const n=e.registry?.get(t);if(!n)throw Error(`Expression '${t}' not in ExecutionContext.registry. The bundle's ExpressionRegistry must include this expression's category. Use createExpressionRegistry() with the relevant category objects (referencesExpressions, logicalExpressions, conversionExpressions, positionalExpressions, propertiesExpressions, specialExpressions, mathematicalExpressions).`);return n}function ur(e){if(e&&"object"==typeof e&&"success"in e){if(e.success)return"value"in e?e.value:void 0;const t=e.errors||[];throw Error(t.length>0?t[0].message:"Expression evaluation failed")}return e}async function fr(e,t){if(!e)throw Error("Cannot evaluate null or undefined AST node");if("literal"===e.type)return e.value;if("identifier"===e.type)return vr(e,t);const n=e;switch(e.type){case"literal":return function(e){return e.value}(n);case"identifier":return vr(n,t);case"binaryExpression":return async function(e,t){const n=e.operator,r=e.right,s=e.left;if("="===n){const n=await fr(e.right,t);if("identifier"===s?.type&&"string"==typeof s.name){const e=s.name;return e.startsWith("$")?Fe(t,e.slice(1),n):"global"===s.scope?Fe(t,e,n):"element"===s.scope?tn(t,e,n):(t.locals||(t.locals=new Map),t.locals.set(e,n)),n}throw Error(`Assignment target must be a variable identifier (got '${s?.type??"undefined"}')`)}if("has"===n||"have"===n){const n=await fr(e.left,t);return!!(n instanceof Element&&"selector"===r.type&&"string"==typeof r.value&&r.value.startsWith("."))&&n.classList.contains(r.value.slice(1))}if("in"===n||"is in"===n){const n="callExpression"===s?.type&&"identifier"===s.callee?.type?s.callee.name:null;if(("first"===n||"last"===n)&&Array.isArray(s.arguments)){const r=s.arguments[0];if("selector"===r?.type&&"string"==typeof r.value){const s=await fr(e.right,t);if(s&&"function"==typeof s.querySelectorAll){const e=Array.from(s.querySelectorAll(r.value));return 0===e.length?null:"first"===n?e[0]:e[e.length-1]}}}if("selector"===s?.type&&s.fromQuery&&"string"==typeof s.value){const n=await fr(e.right,t),r=n&&"function"==typeof n.querySelectorAll?n:null;if(r)return Array.from(r.querySelectorAll(s.value))}}if("of"===n&&"selector"===s?.type&&"string"==typeof s.value&&/^\*[a-zA-Z][\w-]*$/.test(s.value)){const n=await fr(e.right,t);return lr(t,"styleRef").evaluate(t,s.value.slice(1),n)}if("of"===n){const n=br(e.left);if(n){const r=await fr(e.right,t);let s=r;for(const e of n){if(null==s)return;s=gn(s)?xn(s,e):s[e]}return"function"==typeof s?s.bind(r):s}}const i=await fr(e.left,t);if("and"===n){if(!i)return i;const n=await fr(e.right,t);return lr(t,"and").evaluate(t,i,n)}if("or"===n){if(i)return i;const n=await fr(e.right,t);return lr(t,"or").evaluate(t,i,n)}const o=await fr(e.right,t),a=e=>"string"==typeof e?e.toLowerCase():e,c=e.ignoringCase?a(i):i,l=e.ignoringCase?a(o):o;switch(n){case"+":{let n=i,r=o;return e.coerceNumeric&&("string"==typeof n&&(n=on(n)),"string"==typeof r&&(r=on(r))),"string"==typeof n||"string"==typeof r?(n??"")+""+(r??""):Array.isArray(n)?Array.isArray(r)?[...n,...r]:[...n,r]:ur(await lr(t,"addition").evaluate(t,{left:n,right:r}))}case"-":return ur(await lr(t,"subtraction").evaluate(t,{left:i,right:o}));case"*":return ur(await lr(t,"multiplication").evaluate(t,{left:i,right:o}));case"/":return ur(await lr(t,"division").evaluate(t,{left:i,right:o}));case"%":case"mod":return ur(await lr(t,"modulo").evaluate(t,{left:i,right:o}));case"^":case"**":return ur(await lr(t,"power").evaluate(t,{left:i,right:o}));case">":case"is greater than":return lr(t,"greaterThan").evaluate(t,i,o);case"<":case"is less than":return lr(t,"lessThan").evaluate(t,i,o);case">=":case"is greater than or equal to":return lr(t,"greaterThanOrEqual").evaluate(t,i,o);case"<=":case"is less than or equal to":return lr(t,"lessThanOrEqual").evaluate(t,i,o);case"==":return lr(t,"equals").evaluate(t,c,l);case"is":case"am":case"equals":case"is equal":case"is equal to":{const n=xr(e,i,o);return void 0!==n?n:lr(t,"equals").evaluate(t,c,l)}case"!=":return lr(t,"notEquals").evaluate(t,c,l);case"is not":case"is not equal":case"is not equal to":{const n=xr(e,i,o);return void 0!==n?!n:lr(t,"notEquals").evaluate(t,c,l)}case"===":case"really equals":case"is really":case"is really equal to":return lr(t,"strictEquals").evaluate(t,c,l);case"!==":case"is not really":case"is not really equal to":return lr(t,"strictNotEquals").evaluate(t,c,l);case"as":return lr(t,"as").evaluate(t,i,Sr(o));case"contains":case"contain":case"includes":case"include":return lr(t,"contains").evaluate(t,c,l);case"does not contain":case"do not contain":case"does not contains":case"does not include":return lr(t,"doesNotContain").evaluate(t,c,l);case"starts with":return lr(t,"startsWith").evaluate(t,c,l);case"ends with":return lr(t,"endsWith").evaluate(t,c,l);case"does not start with":return!await lr(t,"startsWith").evaluate(t,c,l);case"does not end with":return!await lr(t,"endsWith").evaluate(t,c,l);case"match":case"matches":return lr(t,"matches").evaluate(t,c,Er(e.right,l));case"does not match":case"do not match":return!await lr(t,"matches").evaluate(t,c,Er(e.right,l));case"in":case"is in":case"am in":return wr(i,o);case"is not in":case"am not in":return!wr(i,o);case"of":return o&&"object"==typeof o?o[i]:void 0;case"precedes":return kr(i,o,Node.DOCUMENT_POSITION_FOLLOWING);case"does not precede":return!kr(i,o,Node.DOCUMENT_POSITION_FOLLOWING);case"follows":return kr(i,o,Node.DOCUMENT_POSITION_PRECEDING);case"does not follow":return!kr(i,o,Node.DOCUMENT_POSITION_PRECEDING);default:throw Error("Unknown binary operator: "+n)}}(n,t);case"asExpression":return async function(e,t){const n=await fr(e.expression,t),r=Sr(e.targetType);return lr(t,"as").evaluate(t,n,r)}(n,t);case"betweenExpression":return async function(e,t){const n=await fr(e.value,t),r=await fr(e.min,t),s=await fr(e.max,t),i=e=>"string"==typeof e?e.toLowerCase():e,[o,a,c]=e.ignoringCase?[i(n),i(r),i(s)]:[n,r,s],l=await lr(t,"between").evaluate(t,o,a,c);return e.negated?!l:l}(n,t);case"typeCheckExpression":return async function(e,t){const n=function(e,t,n){if(null==e&&n)return!0;if(Object.prototype.toString.call(e).slice(8,-1)===t)return!0;const r=globalThis[t];return"function"==typeof r&&e instanceof r}(await fr(e.value,t),e.typeName+"",!1!==e.nullOk);return e.negated?!n:n}(n,t);case"collectionExpression":return async function(e,t){const n=await fr(e.collection,t);if(null==n)return n;const r=async(e,n)=>fr(e,{...t,it:n});switch(e.operator){case"where":return async function(e,t,n){const r=cr(e),s=[];for(const e of r)await n(t,e)&&s.push(e);return s}(n,e.right,r);case"sorted by":return async function(e,t,n,r){const s=[...cr(e)],i=await Promise.all(s.map(e=>r(t,e))),o=s.map((e,t)=>t);o.sort((e,t)=>{const n=i[e],r=i[t];return n===r?0:null==n?1:null==r||r>n?-1:1});const a=o.map(e=>s[e]);return"desc"===n?a.reverse():a}(n,e.right,e.order??"asc",r);case"mapped to":return async function(e,t,n){const r=cr(e);return Promise.all(r.map(e=>n(t,e)))}(n,e.right,r);case"split by":return i=await fr(e.right,t),null==(s=n)?[]:(s+"").split(null==i?"":i+"");case"joined by":return function(e,t){const n=null==t?"":t+"";return cr(e).map(e=>null==e?"":e+"").join(n)}(n,await fr(e.right,t));default:throw Error("Unknown collection operator: "+e.operator)}var s,i}(n,t);case"unaryExpression":return async function(e,t){const n=e.operand??e.argument;if(!n)throw Error(`Unary expression has no operand (operator: ${e.operator})`);const r=await fr(n,t);switch(e.operator){case"not":case"!":return lr(t,"not").evaluate(t,r);case"no":return lr(t,"no").evaluate(t,r);case"-":return-r;case"+":return+r;case"exists":case"some":return lr(t,"exists").evaluate(t,r);case"does not exist":return lr(t,"doesNotExist").evaluate(t,r);case"is empty":return lr(t,"isEmpty").evaluate(t,r);case"is not empty":return lr(t,"isNotEmpty").evaluate(t,r);default:throw Error("Unknown unary operator: "+e.operator)}}(n,t);case"memberExpression":return async function(e,t){const n=await fr(e.object,t);if(e.computed){const r=await fr(e.property,t);return Array.isArray(n)&&"number"==typeof r&&0>r?n[n.length+r]:n?.[r]}return Cr(n,e.property.name,t)}(n,t);case"propertyAccess":return async function(e,t){let n=await fr(e.object,t);for(const r of(e.property+"").split(".")){if(null==n)return;n=await Cr(n,r,t)}return n}(n,t);case"callExpression":return async function(e,t){const n=await fr(e.callee,t);if(e.isConstructor&&"function"==typeof n)return new n(...await Promise.all(e.arguments.map(e=>fr(e,t))));if("identifier"===e.callee.type){const r=e.callee.name,s=await async function(e,t,n){return Or.has(t)?Promise.all(e.map(e=>"identifier"===e.type&&e.name?e.name:"selector"===e.type&&e.value?e.value:fr(e,n))):Promise.all(e.map(e=>fr(e,n)))}(e.arguments,r,t);switch(r){case"closest":return lr(t,"closest").evaluate(t,...s);case"previous":case"next":{const n=e.relativePositional;if(n){const e=n.from?Rr(await fr(n.from,t)):t.me,i=n.within?Rr(await fr(n.within,t)):void 0,o=n.inElt?await fr(n.inElt,t):void 0;return lr(t,r).evaluate(t,s[0],e,{within:i,inElt:o,inSearch:n.inSearch,wrapping:n.wrapping})}return lr(t,r).evaluate(t,...s)}case"first":return lr(t,"first").evaluate(t,...s);case"last":return lr(t,"last").evaluate(t,...s);default:if("function"==typeof n)return n(...s);throw Error("Cannot call non-function: "+r)}}if("function"==typeof n){const r=await Promise.all(e.arguments.map(e=>fr(e,t)));if("memberExpression"===e.callee.type&&e.callee.object){const s=await fr(e.callee.object,t);return n.apply(s,r)}return n(...r)}throw Error("Cannot call non-function")}(n,t);case"selector":return async function(e,t){let n=e.value;if("string"==typeof n&&!e.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(n))return lr(t,"styleRef").evaluate(t,n.slice(1));if("string"==typeof n&&e.fromQuery&&/\$[^=]/.test(n)){const{selector:r,elements:s}=await async function(e,t){const n=Mr(e),r=await Promise.all(n.filter(e=>"expr"in e).map(e=>mr(e.expr,t)));return Dr(n,r)}(n,t),i=jr(e,r);s.forEach((e,t)=>e.setAttribute("data-hs-query-id",t+""));try{return await lr(t,"elementWithSelector").evaluate(t,i)}finally{s.forEach(e=>e.removeAttribute("data-hs-query-id"))}}"string"==typeof n&&!e.fromQuery&&n.includes("{")&&(n=await function(e,t){return Tr(e,/\{([^}]*)\}/g,async(e,n)=>(await mr(n.trim(),t)??"")+"")}(n,t));const r="string"==typeof n?jr(e,n):n,s=await lr(t,"elementWithSelector").evaluate(t,r);return!e.fromQuery&&"string"==typeof n&&n.startsWith("#")&&Array.isArray(s)?s[0]??null:s}(n,t);case"contextReference":return async function(e,t){switch(e.contextType){case"me":case"you":case"it":return lr(t,e.contextType).evaluate(t);case"my":case"myself":case"I":return lr(t,"me").evaluate(t);case"your":case"yourself":return lr(t,"you").evaluate(t);case"its":return lr(t,"it").evaluate(t);case"event":return t.event;case"target":return t.target??t.event?.target??lr(t,"me").evaluate(t);case"body":return"undefined"!=typeof document?document.body:void 0;case"document":return lr(t,"document").evaluate(t);case"window":return lr(t,"window").evaluate(t);default:return}}(n,t);case"possessiveExpression":return async function(e,t){const n=await fr(e.object,t),r=e.property.name;return lr(t,"possessive").evaluate(t,n,r)}(n,t);case"eventHandler":return async function(e,t){return{event:e.event,selector:e.selector,commands:e.commands,handler:async n=>{const r={...t,event:n,target:n.target,currentTarget:n.currentTarget};for(const t of e.commands)await fr(t,r)}}}(n,t);case"conditionalExpression":return async function(e,t){return await fr(e.test,t)?fr(e.consequent,t):e.alternate?fr(e.alternate,t):void 0}(n,t);case"string":return n.value;case"arrayLiteral":return async function(e,t){const n=[];for(const r of e.elements)n.push(await fr(r,t));return n}(n,t);case"objectLiteral":return async function(e,t){const n={};for(const r of e.properties){const e=r.key;let s;s="identifier"===e.type?e.name:"literal"===e.type&&"string"===e.valueType?e.value:await fr(e,t)+"",n[s]=await fr(r.value,t)}return n}(n,t);case"attributeAccess":return async function(e,t){const n=e.attributeName;return t.me&&t.me instanceof Element?t.me.getAttribute(n):"@"+n}(n,t);case"propertyOfExpression":return async function(e,t){const n=e.property;if("identifier"!==n?.type)throw Error('Property name must be an identifier in "the X of Y" pattern');const r=n.name,s=await fr(e.target,t);if(null==s)throw Error(`Cannot access property "${r}" of ${s}`);return lr(t,"possessive").evaluate(t,s,r)}(n,t);case"templateLiteral":return async function(e,t){let n=e.value;return n=await Tr(n,/\$([a-zA-Z_$][a-zA-Z0-9_.$]*|\d+)/g,async(e,n)=>{try{if(/^\d+$/.test(n))return n;if(n.includes(".")){const e=n.split(".");let r=Nr(e[0],t);for(let t=1;e.length>t&&null!=r;t++)r=r[e[t]];return(r??"")+""}return(Nr(n,t)??"")+""}catch{return""}}),n=await Tr(n,/\$(?:\{([^}]+)\}|\(([^)]+)\))/g,async(e,n,r)=>{const s=n||r;try{return await mr(s,t)+""}catch{return"undefined"}}),n}(n,t);case"stringPostfix":return async function(e,t){return`${await fr(e.expression,t)}${e.unit}`}(n,t);case"blockLiteral":return Ar(n,t);default:{const n=Te.get(e.type);if(n)return n(e,t);throw Error("Unknown AST node type: "+e.type)}}}class hr extends Error{constructor(e){super(`Expression node "${e}" is not synchronously evaluable`),this.name="NotSyncEvaluable"}}function dr(e,t){const n=e;switch(n?.type){case"literal":case"string":return n.value;case"selector":return function(e,t){const n=e.value;if("string"!=typeof n)throw new hr("selector");if(!e.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(n))throw new hr("selector");if(e.fromQuery&&/\$[^=]/.test(n)){const{selector:r,elements:s}=function(e,t){const n=Mr(e),r=n.filter(e=>"expr"in e).map(e=>pr(e.expr,t));return Dr(n,r)}(n,t),i=jr(e,r),o=t?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!o)throw new hr("selector");s.forEach((e,t)=>e.setAttribute("data-hs-query-id",t+""));try{return Array.from(o.querySelectorAll(i))}finally{s.forEach(e=>e.removeAttribute("data-hs-query-id"))}}const r=!e.fromQuery&&n.includes("{")?function(e,t){return e.replace(/\{([^}]*)\}/g,(e,n)=>(pr(n.trim(),t)??"")+"")}(n,t):n,s=jr(e,r),i=t?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!i)throw new hr("selector");const o=Array.from(i.querySelectorAll(s));return!e.fromQuery&&r.startsWith("#")?o[0]??null:o}(n,t);case"identifier":return function(e,t,n){return"me"===e||"my"===e||"I"===e?t.me:"you"===e||"your"===e||"yourself"===e?t.you:"it"===e||"its"===e?t.it??t.result:"window"===e?"undefined"!=typeof window?window:globalThis:"document"===e?"undefined"!=typeof document?document:void 0:"element"===n?en(t,e):t.locals?.has(e)?t.locals.get(e):t.globals?.has(e)?t.globals.get(e):e.startsWith("$")&&t.globals?.has(e.slice(1))?t.globals.get(e.slice(1)):void 0!==t[e]?t[e]:"undefined"!=typeof globalThis&&e in globalThis?globalThis[e]:void 0}(n.name,t,n.scope);case"contextReference":return function(e,t){switch(e){case"me":return t.me;case"you":return t.you;case"it":return t.it??t.result;case"event":return t.event;case"target":return t.target??t.event?.target??t.me;default:throw new hr("contextReference")}}(n.contextType,t);case"arrayLiteral":return n.elements.map(e=>dr(e,t));case"objectLiteral":return function(e,t){const n={};for(const r of e.properties){const e=r.key;let s;s="identifier"===e.type?e.name:"literal"===e.type&&"string"===e.valueType?e.value:dr(e,t)+"",n[s]=dr(r.value,t)}return n}(n,t);case"asExpression":return nr(dr(n.expression,t),Sr(n.targetType),t);case"stringPostfix":return`${dr(n.expression,t)}${n.unit}`;case"blockLiteral":return Ar(n,t);case"memberExpression":{const e=dr(n.object,t);if(null==e)return;if(e instanceof Element||Array.isArray(e)||"undefined"!=typeof Node&&e instanceof Node)throw new hr("memberExpression");const r=e[n.computed?dr(n.property,t)+"":n.property?.name];return"function"==typeof r?r.bind(e):r}default:throw new hr(n?.type??"unknown")}}function pr(e,t){const n=Ut(e);if(!n.success||!n.node){const e=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(e?.message??"unknown error"))}return dr(n.node,t)}async function mr(e,t){const n=Ut(e);if(!n.success||!n.node){const e=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(e?.message??"unknown error"))}const r=t.registry?t:{...t,registry:await gr()};return fr(n.node,r)}let yr=null;async function gr(){if(!yr){const e=await Promise.resolve().then(function(){return la});yr=e.createFullExpressionRegistry()}return yr}async function vr(e,t){const n=e.name;return"me"===n||"my"===n||"I"===n?lr(t,"me").evaluate(t):"you"===n||"your"===n||"yourself"===n?lr(t,"you").evaluate(t):"it"===n||"its"===n?lr(t,"it").evaluate(t):"window"===n?lr(t,"window").evaluate(t):"document"===n?lr(t,"document").evaluate(t):"global"===e.scope&&t.globals?.has(n)?(Me(n,t),t.globals.get(n)):"element"===e.scope?en(t,n):t.locals&&t.locals.has(n)?(Pe(n,t),t.locals.get(n)):t.globals&&t.globals.has(n)?(n.startsWith("$")&&Me(n.slice(1),t),t.globals.get(n)):n.startsWith("$")&&t.globals&&t.globals.has(n.slice(1))?(Me(n.slice(1),t),t.globals.get(n.slice(1))):void 0!==t[n]?t[n]:"undefined"!=typeof globalThis&&n in globalThis?globalThis[n]:void 0}function br(e){const t=e;if(!t)return null;if("identifier"===t.type&&"string"==typeof t.name)return[t.name];if("memberExpression"===t.type&&!t.computed){const e=br(t.object);if(!e)return null;const n=t.property,r="identifier"===n?.type&&"string"==typeof n.name?n.name:"string"==typeof n?.value?n.value:null;return null==r?null:[...e,r]}return null}function wr(e,t){return Array.isArray(t)?t.includes(e):"string"==typeof t?t.includes(e+""):e instanceof Node&&t instanceof Node?e===t||t.contains(e):null!=t&&"object"==typeof t&&e in t}function Er(e,t){return e&&"selector"===e.type&&"string"==typeof e.value?e.value:t}function xr(e,t,n){if(void 0!==n)return;const r=e.right;if(!r||"identifier"!==r.type||"string"!=typeof r.name)return;if(null==t||"object"!=typeof t)return;const s=t[r.name];return"boolean"==typeof s?!0===s:void 0}function kr(e,t,n){return e instanceof Node&&t instanceof Node&&0!==(e.compareDocumentPosition(t)&n)}function Sr(e){if("string"==typeof e)return e;if(e&&"object"==typeof e){if("string"==typeof e.name)return e.name;if("string"==typeof e.value)return e.value}return e+""}function Ar(e,t){const n=e.parameters??[];return(...r)=>{const s=new Map(t.locals??new Map);n.forEach((e,t)=>s.set(e,r[t]));const i={...t,locals:s};try{return dr(e.body,i)}catch(t){if(t instanceof hr)return fr(e.body,i);throw t}}}function Nr(e,t){return t.locals?.has(e)?(Pe(e,t),t.locals.get(e)):"me"===e&&t.me?t.me:"you"===e&&t.you?t.you:"it"===e&&t.it?t.it:"result"===e&&t.result?t.result:"undefined"!=typeof window&&"window"===e?window:t.globals?.has(e)?t.globals.get(e):void 0}async function Tr(e,t,n){const r=[];let s;for(;null!==(s=t.exec(e));)r.push({index:s.index,length:s[0].length,replacement:await n(s[0],...s.slice(1))});let i=e;for(let e=r.length-1;e>=0;e--){const{index:t,length:n,replacement:s}=r[e];i=i.substring(0,t)+s+i.substring(t+n)}return i}function Cr(e,t,n){if("string"==typeof t&&t.startsWith("@")){const n=t.substring(1);return e&&"function"==typeof e.getAttribute?e.getAttribute(n):void 0}return e instanceof Element&&"string"==typeof t?xn(e,t):or(e)&&!(t in e)?lr(n,"possessive").evaluate(n,e,t):e?.[t]}const Or=new Set(["closest","previous","next"]);function Rr(e){return e instanceof Element?e:Array.isArray(e)&&e[0]instanceof Element?e[0]:void 0}const $r=RegExp("(\\.[a-zA-Z0-9_-]+):(?!(hover|active|focus|visited|link|focus-within|focus-visible|first-child|last-child|only-child|nth-child|nth-last-child|nth-of-type|nth-last-of-type|first-of-type|last-of-type|only-of-type|empty|root|target|lang|dir|not|has|is|where|matches|before|after|first-letter|first-line|selection|placeholder|marker|backdrop|enabled|disabled|checked|indeterminate|required|optional|valid|invalid|in-range|out-of-range|read-only|read-write|default|defined|fullscreen|modal|picture-in-picture|autofill)(?![a-zA-Z0-9_-]))","g"),Lr=/[:&()[\]/]/g;function jr(e,t){return e.fromQuery||!t.startsWith(".")||t.includes("{")?function(e){return e.replace($r,"$1\\:")}(t):function(e){return e[0]+e.slice(1).replace(Lr,"\\$&")}(t)}const Ir=/\$\{([^}]+)\}|\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g;function Mr(e){const t=[];let n,r=0;for(Ir.lastIndex=0;null!==(n=Ir.exec(e));)n.index>r&&t.push({lit:e.slice(r,n.index)}),t.push({expr:n[1]??n[2]}),r=n.index+n[0].length;return e.length>r&&t.push({lit:e.slice(r)}),t}function Dr(e,t){let n="";const r=[];let s=0;for(const i of e){if("lit"in i){n+=i.lit;continue}const e=t[s++];gn(e)?(n+=`[data-hs-query-id='${r.length}']`,r.push(e)):n+=(e??"")+""}return{selector:n,elements:r}}class Pr{constructor(e){this.elementCleanups=new WeakMap,this.elementCount=0,this.typeCounts={listener:0,observer:0,interval:0,timeout:0,custom:0},this.globalCleanups=[],this.debugMode=e?.debug??!1}registerListener(e,t,n,r,s){this.addCleanup(e,{type:"listener",target:t,eventName:n,cleanup:()=>{t.removeEventListener(n,r,s),this.debugMode&&pe(`CleanupRegistry: Removed listener '${n}'`)},description:n+" listener"})}registerObserver(e,t){this.addCleanup(e,{type:"observer",cleanup:()=>{t.disconnect(),this.debugMode&&pe("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(e,t){this.addCleanup(e,{type:"interval",cleanup:()=>{clearInterval(t),this.debugMode&&pe("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(e,t){this.addCleanup(e,{type:"timeout",cleanup:()=>{clearTimeout(t),this.debugMode&&pe("CleanupRegistry: Cleared timeout")},description:"Timeout"})}registerCustom(e,t,n){this.addCleanup(e,{type:"custom",cleanup:t,description:n||"Custom cleanup"})}registerGlobal(e,t="custom",n){this.globalCleanups.push({type:t,cleanup:e,description:n||"Global cleanup"}),this.debugMode&&pe("CleanupRegistry: Registered global cleanup: "+(n||t))}addCleanup(e,t){const n=this.elementCleanups.get(e);n?n.push(t):(this.elementCleanups.set(e,[t]),this.elementCount++),this.typeCounts[t.type]++,this.debugMode&&pe(`CleanupRegistry: Registered ${t.type} for element`,e)}cleanupElement(e){const t=this.elementCleanups.get(e);if(!t||0===t.length)return 0;let n=0;for(const e of t){try{e.cleanup(),n++}catch(e){this.debugMode&&pe("CleanupRegistry: Error during cleanup:",e)}this.typeCounts[e.type]--}return this.elementCleanups.delete(e),this.elementCount--,this.debugMode&&pe(`CleanupRegistry: Cleaned up ${n} resources for element`),n}cleanupElementTree(e){let t=this.cleanupElement(e);const n=e.querySelectorAll("*");for(const e of n)t+=this.cleanupElement(e);return t}cleanupGlobal(){let e=0;for(const t of this.globalCleanups)try{t.cleanup(),e++}catch(e){this.debugMode&&pe("CleanupRegistry: Error during global cleanup:",e)}return this.globalCleanups=[],this.debugMode&&pe(`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,n=0,r=0,s=0;for(const i of this.globalCleanups)switch(i.type){case"listener":e++;break;case"observer":t++;break;case"interval":n++;break;case"timeout":r++;break;case"custom":s++}return{elementsTracked:this.elementCount,listeners:this.typeCounts.listener+e,observers:this.typeCounts.observer+t,intervals:this.typeCounts.interval+n,timeouts:this.typeCounts.timeout+r,custom:this.typeCounts.custom+s,global:this.globalCleanups.length}}setDebugMode(e){this.debugMode=e}}class Fr{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(e,t){const n=e.toLowerCase();this.sources.has(n)&&pe("[EventSourceRegistry] Overwriting existing event source: "+e),this.sources.set(n,t)}unregister(e){const t=e.toLowerCase(),n=this.sources.get(t);if(n){for(const[e,n]of this.subscriptions.entries())n.source===t&&(n.unsubscribe(),this.subscriptions.delete(e));return n.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,n){const r=this.get(e);if(!r)return void pe("[EventSourceRegistry] Unknown event source: "+e);r.initialize?.();const s=r.subscribe(t,n);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,n]of this.sources.entries())if(n.supports?.(e)??n.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 Br{constructor(){this.providers=new Map,this.globalProviders=new Map}register(e,t,n){const r=e.toLowerCase();this.providers.set(r,"function"==typeof t?{name:r,provide:t,cache:n?.cache??!0,description:n?.description,dependencies:n?.dependencies}:t)}registerGlobal(e,t,n){const r=e.toLowerCase();this.globalProviders.set(r,"function"==typeof t?{name:r,provide:t,cache:n?.cache??!0,description:n?.description,dependencies:n?.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,n){const r=this.get(e);if(!r)return;const s="__provider_"+r.name;if(r.cache&&n?.has(s))return n.get(s);if(r.dependencies)for(const e of r.dependencies)await this.resolve(e,t,n);const i=await r.provide(t);return r.cache&&n&&n.set(s,i),i}resolveSync(e,t,n){const r=this.get(e);if(!r)return;const s="__provider_"+r.name;if(r.cache&&n?.has(s))return n.get(s);const i=r.provide(t);if(i instanceof Promise)throw Error(`Context provider '${e}' is async. Use resolve() instead of resolveSync().`);return r.cache&&n&&n.set(s,i),i}enhance(e){const t=this,n=new Map;return new Proxy(e,{get(e,r,s){if("string"==typeof r&&t.get(r))try{return t.resolveSync(r,e,n)}catch{return t.resolve(r,e,n)}return Reflect.get(e,r,s)},has:(e,n)=>!("string"!=typeof n||!t.has(n))||Reflect.has(e,n)})}async resolveAll(e){const t=new Map,n={},r=[...this.globalProviders.entries(),...this.providers.entries()];for(const[s,i]of r)try{n[s]=await this.resolve(s,e,t)}catch(e){pe(`[ContextProviderRegistry] Failed to resolve '${s}':`,e),n[s]=void 0}return n}getProviderNames(){return[...new Set([...this.globalProviders.keys(),...this.providers.keys()])]}clear(){this.providers.clear(),this.globalProviders.clear()}}const qr={evaluate:(e,t)=>fr(e,t)};class Vr{static toTyped(e){return{me:e.me,...void 0!==e.owner&&{owner:e.owner},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||{},...void 0!==e.registry&&{registry:e.registry},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 _r{constructor(e,t,n){this.impl=e,this.hookRegistry=n??null}setHookRegistry(e){this.hookRegistry=e}createHookContext(e,t,n={}){return{commandName:this.name,element:e.me instanceof Element?e.me:null,args:t,modifiers:n,event:e.event??void 0,executionContext:e}}get name(){const e=this.impl.name;if(e)return e;const t=this.impl.metadata?.name;return"string"==typeof t?t:""}get metadata(){const e=this.impl.metadata?.syntax;return{description:this.impl.metadata?.description||"",examples:this.impl.metadata?.examples||[],syntax:Array.isArray(e)?e.join(" | "):e||""}}async execute(e,...t){const n=t[0],r=this.createHookContext(e,t,n&&"object"==typeof n&&"modifiers"in n&&n.modifiers||{});try{if(fe(`CommandAdapterV2: Executing '${this.name}' with args:`,t),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(r),this.hookRegistry?.shouldIntercept(this.name,r))return void fe(`CommandAdapterV2: '${this.name}' intercepted by hook`);const s=Vr.toTyped(e);let i,o;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(fe(`CommandAdapterV2: '${this.name}' has parseInput(), calling it`),n&&"object"==typeof n&&("args"in n||"modifiers"in n)){const t=n.modifiers,r=t?.when||t?.where;if(r&&!await fr(r,e))return void fe(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);i=await this.impl.parseInput({args:n.args||[],modifiers:t||{},commandName:n.commandName},qr,e)}else i=t;else fe(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),i=t;if(fe("CommandAdapterV2: Calling execute with parsed input:",i),2===this.impl.execute.length)o=await this.impl.execute(i,s);else{const e=Array.isArray(i)?i:[i];o=await this.impl.execute(s,...e)}return fe("CommandAdapterV2: Command result:",o),Object.assign(e,Vr.fromTyped(s,e)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(r,o),o}catch(e){if(Zr(e)||fe(`CommandAdapterV2: Error executing '${this.name}':`,e),this.hookRegistry&&e instanceof Error)throw await this.hookRegistry.runOnError(r,e);throw e}}validate(e){return this.impl.validate?this.impl.validate(e):{isValid:!0,errors:[],suggestions:[]}}}class Hr{constructor(e,t){this.adapters=new Map,this.implementations=new Map,this.hookRegistry=t}setHookRegistry(e){this.hookRegistry=e;for(const t of this.adapters.values())t.setHookRegistry(e);pe(`CommandRegistryV2: Hook registry set and propagated to ${this.adapters.size} adapters`)}getHookRegistry(){return this.hookRegistry}register(e){const t=e.name||e.metadata?.name;if(!t||"string"!=typeof t)throw Error("Cannot register command: no name found. Provide a 'name' property or 'metadata.name' on the implementation.");const n=t.toLowerCase();pe(`CommandRegistryV2: Registering command '${n}'`),this.implementations.set(n,e);const r=new _r(e,void 0,this.hookRegistry);this.adapters.set(n,r),E.add(n);const s=e.metadata?.aliases;if(s&&Array.isArray(s))for(const t of s){const n=t.toLowerCase();this.implementations.set(n,e),this.adapters.set(n,r),E.add(n)}}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 n=this.getAdapter(e);return n?n.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 Ur=null;function zr(){return Ur||(Ur=function(e){const t=e?.commands??new Hr,n=e?.eventSources??new Fr,r=e?.context??new Br,s=new Set,i={commands:t,eventSources:n,context:r,use(e){if(s.has(e.name))pe(`[LokaScriptRegistry] Plugin '${e.name}' is already installed`);else{if(e.commands)for(const n of e.commands)t.register(n);if(e.eventSources)for(const t of e.eventSources)n.register(t.name,t);if(e.contextProviders)for(const{name:t,provide:n,options:s}of e.contextProviders)r.register(t,n,s);e.setup?.(i),s.add(e.name)}},reset(){s.clear()}};return i}()),Ur}class Wr{constructor(e={}){this.contextCache=new WeakMap;const t=zr();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,pe(`[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),pe(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),t}catch(t){return pe("[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 pe(`[RegistryIntegration] Found event source for '${e}'`),t;const n=this.eventSourceRegistry.findSourceForEvent(e);if(n){const t=this.eventSourceRegistry.get(n);return pe(`[RegistryIntegration] Found event source '${n}' supporting '${e}'`),t}}hasEventSource(e){return void 0!==this.getEventSource(e)}subscribeToEventSource(e,t,n){if(!this.options.enableEventSources)throw Error("Event sources are disabled in this runtime");const r=this.eventSourceRegistry.subscribe(e,t,n);if(!r)throw Error(`Failed to subscribe to event source '${e}'`);return pe(`[RegistryIntegration] Subscribed to '${e}' event '${t.event}' (id: ${r.id})`),r}getEventSourceNames(){return this.eventSourceRegistry.getSourceNames()}getContextProviderNames(){return this.contextRegistry.getProviderNames()}destroy(){this.eventSourceRegistry.destroy(),this.contextCache=new WeakMap,pe("[RegistryIntegration] Destroyed")}}function Jr(e){const t=Error(e.type.toUpperCase()+"_EXECUTION");return t["is"+e.type.charAt(0).toUpperCase()+e.type.slice(1)]=!0,"returnValue"in e&&(t.returnValue=e.returnValue),t}function Zr(e){return e instanceof Error&&(null!==Wt(e)||"HALT_EXECUTION"===e.message||"EXIT_COMMAND"===e.message||"EXIT_EXECUTION"===e.message)}function Kr(e){if(void 0===e)return;let t=e;if(t&&"object"==typeof t){const e=t;if("result"in e&&"wasAsync"in e)t=e.result;else if("result"in e&&"executed"in e){if(t=e.result,e.preserveArrayResult)return void 0!==t?t:void 0}else if("lastResult"in e&&"type"in e)t=e.lastResult;else if("conditionResult"in e&&"executedBranch"in e){if(void 0===e.result)return;t=e.result}else"value"in e&&1===Object.keys(e).length||"value"in e&&"target"in e&&"targetType"in e?t=e.value:"data"in e&&"status"in e&&"headers"in e&&(t=e.data)}return Array.isArray(t)&&t.length>0&&(t=t[0]),t}function Gr(e){return null!==e&&"object"==typeof e&&"command"in e&&"selector"in e}const Xr=new WeakMap;class Yr{constructor(e){this.autoCleanupObserver=null,this.registryIntegration=null,this.runtimeWarnings=[],this.options={commandTimeout:1e4,enableErrorReporting:!0,enableResultPattern:!0,enableAutoCleanup:!0,...e},this.registry=e.registry,this.expressionRegistry=e.expressionRegistry,this.behaviorRegistry=new Map,this.globalVariables=Gt,this.hookRegistry=new zt,e.hooks&&this.hookRegistry.register("default",e.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new Pr,this.options.enableAutoCleanup&&this.setupAutoCleanup(),!1!==e.registryIntegration&&(this.registryIntegration=new Wr("object"==typeof e.registryIntegration?e.registryIntegration:{}),pe("RuntimeBase: Registry integration enabled")),this.behaviorAPI={has:e=>this.behaviorRegistry.has(e),get:e=>this.behaviorRegistry.get(e),set:(e,t)=>this.behaviorRegistry.set(e,t),resolve:null,install:async(e,t,n)=>await this.installBehaviorOnElement(e,t,n)}}setupAutoCleanup(){"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.autoCleanupObserver=new MutationObserver(e=>{const t=[];for(const n of e)for(const e of n.removedNodes)e instanceof Element&&t.push(e);t.length>0&&queueMicrotask(()=>{for(const e of t)if(!e.isConnected){const t=this.cleanupRegistry.cleanupElementTree(e);t>0&&pe(`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)}trackListener(e,t,n,r,s){this.cleanupRegistry.registerListener(e,t,n,r,s)}cleanupTree(e){return this.cleanupRegistry.cleanupElementTree(e)}getCleanupStats(){return this.cleanupRegistry.getStats()}getCleanupRegistry(){return this.cleanupRegistry}logError(...e){this.options.enableErrorReporting&&console.error(...e)}logWarn(...e){this.options.enableErrorReporting&&console.warn(...e)}destroy(){this.autoCleanupObserver&&(this.autoCleanupObserver.disconnect(),this.autoCleanupObserver=null),this.cleanupRegistry.cleanupAll(),this.hookRegistry.clear(),this.behaviorRegistry.clear(),pe("RuntimeBase: Destroyed")}hasErrorDiagnostics(e){const t=e.diagnostics;return!!t?.some(e=>"error"===e.severity)}getWarnings(){return this.runtimeWarnings}async execute(e,t){pe(`RUNTIME BASE: execute() called with node type: '${e.type}'`),t.registry||(t.registry=this.expressionRegistry),t.locals.has("_behaviors")||t.locals.set("_behaviors",this.behaviorAPI),t.locals.has("_runtimeExecute")||t.locals.set("_runtimeExecute",(e,n)=>this.execute(e,n||t));try{if(this.hasErrorDiagnostics(e)){const t=e.diagnostics?.[0];return pe("⚠️ RUNTIME: Skipping error node: "+(t?.message||"unknown error")),void this.runtimeWarnings.push(t?.message||"Skipped error node")}switch(e.type){case"command":if(this.options.enableResultPattern){const n=await this.processCommandWithResult(e,t);if(!Kt(n)){if("return"===n.error.type){const e=n.error.returnValue;return void 0!==e&&Object.assign(t,{it:e,result:e}),e}throw Jr(n.error)}return n.value}try{return await this.processCommand(e,t)}catch(e){const n=Wt(e);if(n?.isReturn){const e=n.returnValue;return void 0!==e&&Object.assign(t,{it:e,result:e}),e}throw e}case"eventHandler":return await this.executeEventHandler(e,t);case"event":{const n={type:"eventHandler",event:e.event,events:[e.event],commands:e.body||[],target:e.filter,modifiers:e.modifiers||{}};return await this.executeEventHandler(n,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 n=e,r=await this.executeCommandSequenceWithResult(n.commands||[],t);if(!Kt(r))throw Jr(r.error);return r.value}return await this.executeCommandSequence(e,t);case"objectLiteral":return await this.executeObjectLiteral(e,t);default:if(this.options.enableResultPattern){const n=await this.evaluateExpressionWithResult(e,t);if(!Kt(n))throw Jr(n.error);return n.value}return await this.evaluateExpression(e,t)}}catch(e){throw e}}async processCommand(e,t){const{name:n,args:r,modifiers:s}=e,i=n.toLowerCase();if(fe(`RUNTIME BASE: Processing command '${i}'`),this.registry.has(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:r||[],modifiers:s||{},commandName:i,runtime:this})}catch(e){throw Zr(e)||this.logError(`Error executing command '${i}':`,e),e}}const o=`Unknown command: ${n}. Ensure it is registered in the Runtime options.`;throw this.logWarn(o),Error(o)}toSignal(e){const t=Wt(e);if(t){if(t.isHalt||"HALT_EXECUTION"===t.message)return{type:"halt"};if(t.isExit||"EXIT_COMMAND"===t.message)return{type:"exit",returnValue:t.returnValue};if(t.isBreak)return{type:"break"};if(t.isContinue)return{type:"continue"};if(t.isReturn)return{type:"return",returnValue:t.returnValue}}if(e instanceof Error){if("HALT_EXECUTION"===e.message)return{type:"halt"};if("EXIT_COMMAND"===e.message)return{type:"exit"}}return null}async processCommandWithResult(e,t){const{name:n,args:r,modifiers:s}=e,i=n.toLowerCase();if(fe(`RUNTIME BASE (Result): Processing command '${i}'`),!this.registry.has(i)){const e=`Unknown command: ${n}. Ensure it is registered in the Runtime options.`;throw this.logWarn(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 Jt(await o.execute(t,{args:r||[],modifiers:s||{},commandName:i,runtime:this}))}catch(e){const t=this.toSignal(e);if(t)return Zt(t);throw this.logError(`Error executing command '${i}':`,e),e}}async executeCommandSequenceWithResult(e,t){let n;for(const r of e){if(this.hasErrorDiagnostics(r)){const e=r.diagnostics?.[0];pe("⚠️ RUNTIME: Skipping error node: "+(e?.message||"unknown error")),this.runtimeWarnings.push(e?.message||"Skipped error node");continue}if("command"===r.type){const e=await this.processCommandWithResult(r,t);if(!Kt(e)){const n=e.error;switch(n.type){case"halt":case"exit":case"break":case"continue":return e;case"return":return void 0!==n.returnValue&&Object.assign(t,{it:n.returnValue,result:n.returnValue}),Jt(n.returnValue)}}n=e.value}else{const e=await this.evaluateExpressionWithResult(r,t);if(!Kt(e))return e;n=e.value}}return Jt(n)}async evaluateExpression(e,t){const n=t.registry?t:{...t,registry:this.expressionRegistry},r=await fr(e,n);return Gr(r)?await this.executeCommandFromPattern(r.command,r.selector,t):r}async evaluateExpressionWithResult(e,t){const n=t.registry?t:{...t,registry:this.expressionRegistry},r=await async function(e,t){try{return Jt(await fr(e,t))}catch(e){if(e instanceof Error){const t=e;if(t.isHalt||"HALT_EXECUTION"===t.message)return Zt({type:"halt"});if(t.isExit||"EXIT_COMMAND"===t.message)return Zt({type:"exit",returnValue:t.returnValue});if(t.isBreak)return Zt({type:"break"});if(t.isContinue)return Zt({type:"continue"});if(t.isReturn)return Zt({type:"return",returnValue:t.returnValue})}throw e}}(e,n);if(!Kt(r))return r;const s=r.value;if(Gr(s)){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:s.command,args:[{type:"literal",value:s.selector}]},t);try{return Jt(await this.executeCommandFromPattern(s.command,s.selector,t))}catch(e){const t=this.toSignal(e);if(t)return Zt(t);throw e}}return Jt(s)}async executeCommandFromPattern(e,t,n){return this.processCommand({type:"command",name:e,args:[{type:"literal",value:t}]},n)}async executeProgram(e,t){if(!e.statements||!Array.isArray(e.statements))return;let n;const r=[],s=[],i=[];for(const t of e.statements)"eventHandler"===t.type?r.push(t):"initBlock"===t.type?s.push(t):i.push(t);for(const e of r)try{await this.execute(e,t)}catch(e){if(Zr(e)&&(e.isHalt||e.isExit))break;throw e}for(const e of s)try{n=await this.execute(e,t)}catch(e){if(Zr(e)&&(e.isHalt||e.isExit))break;throw e}for(const e of i)try{n=await this.execute(e,t)}catch(e){if(Zr(e)&&(e.isHalt||e.isExit))break;throw e}return n}async executeBlock(e,t){if(e.commands&&Array.isArray(e.commands))for(const n of e.commands)try{await this.execute(n,t)}catch(e){if(Zr(e)&&e.isHalt)break;throw e}}async executeCommandSequence(e,t){if(!e.commands||!Array.isArray(e.commands))return;let n;for(const r of e.commands)try{n=await this.execute(r,t)}catch(e){if(Zr(e)){if(e.isHalt||e.isExit)break;if(e.isReturn){if(void 0!==e.returnValue)return Object.assign(t,{it:e.returnValue,result:e.returnValue}),e.returnValue;break}if(e.isBreak)throw e}throw e}return n}async executeObjectLiteral(e,t){const n={};if(!e.properties)return n;for(const r of e.properties){let e;e="identifier"===r.key.type?r.key.name:"literal"===r.key.type?r.key.value+"":await this.execute(r.key,t)+"";const s=await this.execute(r.value,t);n[e]=s}return n}enhanceContext(e){return this.registryIntegration?this.registryIntegration.enhanceContext(e):e}async executeBehaviorDefinition(e,t){const{name:n,parameters:r=[],eventHandlers:s=[],initBlock:i}=e,o=e.imperativeInstaller;"function"==typeof o?(this.behaviorRegistry.set(n,{name:n,parameters:r,type:"imperative",install:o}),pe(`RUNTIME BASE: Registered imperative behavior '${n}'`)):(this.behaviorRegistry.set(n,{name:n,parameters:r,eventHandlers:s,initBlock:i}),pe(`RUNTIME BASE: Registered behavior '${n}'`))}async installBehaviorOnElement(e,t,n){pe("BEHAVIOR: installBehaviorOnElement called: "+e);let r=this.behaviorRegistry.get(e);if(!r&&(this.behaviorAPI.resolve&&this.behaviorAPI.resolve(e)&&(r=this.behaviorRegistry.get(e)),!r))throw Error(`Behavior "${e}" not found`);if("imperative"===r.type)return void("function"==typeof r.install&&(pe(`BEHAVIOR: Installing imperative behavior '${e}'`),r.install(t,n),pe(`BEHAVIOR: Finished installing imperative behavior '${e}'`)));pe("BEHAVIOR: Found behavior, eventHandlers count: "+(r.eventHandlers?.length||0));const s={me:t,owner:t,you:null,it:null,result:null,locals:new Map,globals:this.globalVariables,registry:this.expressionRegistry,halted:!1,returned:!1,broke:!1,continued:!1,async:!1},i=this.enhanceContext(s);if(r.parameters)for(const e of r.parameters)i.locals.set(e,e in n?n[e]:void 0);for(const[e,t]of Object.entries(n))r.parameters?.includes(e)||i.locals.set(e,t);if(r.initBlock){pe("BEHAVIOR: Running init block for "+e);const t=this.options.commandTimeout??1e4;try{await Promise.race([this.execute(r.initBlock,i),new Promise((n,r)=>setTimeout(()=>r(Error(`Behavior "${e}" init block timed out after ${t}ms`)),t))]),pe("BEHAVIOR: Init block completed for "+e)}catch(t){if(pe(`BEHAVIOR: Init block error for ${e}:`,t),!(t instanceof Error&&Zr(t)))throw t}}if(pe(`BEHAVIOR: About to attach ${r.eventHandlers?.length||0} handlers for ${e}`),r.eventHandlers){const t=this.options.commandTimeout??1e4;for(const n of r.eventHandlers)await Promise.race([this.executeEventHandler(n,i),new Promise((n,r)=>setTimeout(()=>r(Error(`Behavior "${e}" handler attachment timed out after ${t}ms`)),t))])}pe("BEHAVIOR: Finished installing "+e)}async executeEventHandler(e,t){const{event:n,events:r,commands:s,target:i,args:o,selector:a,attributeName:c,watchTarget:l,modifiers:u}=e,f=r&&r.length>0?r:[n];pe(`BEHAVIOR: executeEventHandler: event='${n}', target='${i}'`);let h=[],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)h=t.me?[t.me]:[];else if("string"==typeof i&&t.locals.has(i)){const e=t.locals.get(i);pe(`BEHAVIOR: Target resolution: found local '${i}', isElement: ${this.isElement(e)}`),this.isElement(e)?h=[e]:Array.isArray(e)?h=e.filter(e=>this.isElement(e)):"string"==typeof e&&(h=this.queryElements(e,t))}else pe(`BEHAVIOR: Target resolution: querying for '${i}'`),h=this.queryElements(i,t)}else h=t.me?[t.me]:[];if(0===h.length&&!d)return void pe(`BEHAVIOR: executeEventHandler - No targets found for event '${n}', returning early`);if("mutation"===n&&c)return void this.setupMutationObserver(h,c,s,t);if("change"===n&&l)return void this.setupChangeObserver(l,s,t);const p=e.customEventSource;if(p&&this.registryIntegration){pe(`BEHAVIOR: executeEventHandler - Using custom event source '${p}' for event '${n}'`);const e=async e=>{const r=new Map(t.locals),i={...t,locals:r,it:e,event:e},o=this.enhanceContext(i);pe(`CUSTOM EVENT: Executing commands for event '${n}'`);try{await this.execute({type:"program",commands:s},o)}catch(e){this.logError(`[HyperFixi] Error executing commands for custom event '${n}':`,e)}};try{const r=this.registryIntegration.subscribeToEventSource(p,{event:n,handler:e,target:i,selector:a},t);pe(`BEHAVIOR: Subscribed to custom event source '${p}' (id: ${r.id})`),this.cleanupRegistry.registerGlobal(()=>r.unsubscribe(),"listener",`Custom event source '${p}' subscription ${r.id}`)}catch(e){this.logError(`[HyperFixi] Failed to subscribe to custom event source '${p}':`,e)}return}const m=Yr.createEventHandler(this,s,t,a,o);let y,g=null;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 n;y=r=>{n&&clearTimeout(n),n=setTimeout(()=>e(r),t)},g=()=>{n&&(clearTimeout(n),n=void 0)}}else if(u.throttle){const t=u.throttle;let n=0;y=r=>{const s=Date.now();t>s-n||(n=s,e(r))}}else y=e}else y=m;const v=u?.once?{once:!0}:void 0;if(d){for(const e of f)d.addEventListener(e,y,v),h.length>0?this.cleanupRegistry.registerListener(h[0],d,e,y):this.cleanupRegistry.registerGlobal(()=>d.removeEventListener(e,y),"listener",`Global ${e} listener`);g&&(h.length>0?this.cleanupRegistry.registerCustom(h[0],g,"debounce-timeout"):this.cleanupRegistry.registerGlobal(g,"timeout","debounce-timeout"))}else for(const e of h){for(const t of f){if("resize"===t&&"undefined"!=typeof ResizeObserver){const t=new ResizeObserver(e=>{for(const n of e){const e=new CustomEvent("resize",{detail:n,bubbles:!1,cancelable:!1});if(e.synthetic=!0,y(e),v?.once){t.disconnect();break}}});t.observe(e),this.cleanupRegistry.registerCustom(e,()=>t.disconnect(),"resize-observer");continue}e.addEventListener(t,y,v),this.cleanupRegistry.registerListener(e,e,t,y)}g&&this.cleanupRegistry.registerCustom(e,g,"debounce-timeout")}}static createEventHandler(e,t,n,r,s){return async i=>{const o=Xr.get(i)??0;if(o>=100)return;if(Xr.set(i,o+1),r&&i.target instanceof Element)try{if(!i.target.matches(r)&&!i.target.closest(r))return}catch{pe(`Event delegation: invalid CSS selector '${r}', skipping filter`)}const a=new Map(n.locals),c={...n,locals:a,it:i,event:i};a.has("target")||c.locals.set("target",i.target);const l=e.enhanceContext(c);if(s&&s.length>0){const e=i,t=e.detail;for(const n of s)l.locals.set(n,e[n]??t?.[n]??null)}for(const n of t)try{const t=Kr(await e.execute(n,l));void 0!==t&&Object.assign(l,{it:t,result:t})}catch(t){if(Zr(t)){if(t.isHalt||t.isExit)break;if(t.isReturn){void 0!==t.returnValue&&Object.assign(l,{it:t.returnValue,result:t.returnValue});break}}throw e.logError("COMMAND FAILED:",t),t}}}setupMutationObserver(e,t,n,r){pe(`RUNTIME BASE: Setting up MutationObserver for attribute '${t}' on ${e.length} elements`);for(const s of e){const e=new MutationObserver(async e=>{for(const i of e)if("attributes"===i.type&&i.attributeName===t){he(`MUTATION DETECTED: attribute '${t}' changed on`,s);const e={...r,me:s,it:i,locals:new Map(r.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 n)try{await this.execute(e,c)}catch(e){if(Zr(e)){if(e.isHalt||e.isExit||e.isReturn)break}else this.logError("Error executing mutation handler command:",e)}}});e.observe(s,{attributes:!0,attributeOldValue:!0,attributeFilter:[t]}),this.cleanupRegistry.registerObserver(s,e),pe("RUNTIME BASE: MutationObserver attached to",s,`for attribute '${t}'`)}}async setupChangeObserver(e,t,n){pe("RUNTIME BASE: Setting up MutationObserver for content changes on watch target");const r=await this.execute(e,n);let s=[];this.isElement(r)?s=[r]:Array.isArray(r)&&(s=r.filter(e=>this.isElement(e))),pe(`RUNTIME BASE: Watching ${s.length} target elements for content changes`);for(const e of s){const r=new MutationObserver(async r=>{for(const s of r)if("childList"===s.type||"characterData"===s.type){he("CONTENT CHANGE DETECTED on",e,"mutation type:",s.type);const r={...n,me:n.me,it:s,locals:new Map(n.locals)};r.locals.set("target",e);const i=s.oldValue,o=e.textContent;null!==i&&r.locals.set("oldValue",i),r.locals.set("newValue",o);const a=this.enhanceContext(r);for(const e of t)try{await this.execute(e,a)}catch(e){if(Zr(e)){if(e.isHalt||e.isExit||e.isReturn)break}else this.logError("Error executing change handler command:",e)}}});r.observe(e,{childList:!0,characterData:!0,subtree:!0,characterDataOldValue:!0}),this.cleanupRegistry.registerObserver(e,r),pe("RUNTIME BASE: MutationObserver attached to",e,"for content changes")}}queryElements(e,t){const n=t.me,r=(n instanceof Element?n.ownerDocument:null)??("undefined"!=typeof document?document:null);if(!r)return[];let s=e;s.startsWith("<")&&s.endsWith("/>")&&(s=s.slice(1,-2).trim());try{return Array.from(r.querySelectorAll(s))}catch{return pe(`queryElements: invalid CSS selector '${s}'`),[]}}isElement(e){return"undefined"!=typeof HTMLElement&&e instanceof HTMLElement||!(!e||"object"!=typeof e)&&(!!e.style&&!!e.classList)}}function Qr(...e){const t=new Map;for(const n of e)for(const[e,r]of Object.entries(n))t.set(e,r);return t}const es=Bn({selector:Dn().min(1),single:Fn().optional().default(!1)});function ts(e,t){if(t.startsWith("computed-")){const n=t.substring(9);return getComputedStyle(e).getPropertyValue(n)||""}const n=t.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());return e.style[n]}new class extends Un{constructor(){super(...arguments),this.name="me",this.category="Reference",this.syntax="me",this.description="References the current element in the execution context",this.inputSchema=Hn(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=e.me,s=this.isElement(r)?r:null,i=this.success(s,"element");return this.trackPerformance(e,t,i,n),i}catch(r){const s=this.failure("MeExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "me"',"ME_EVALUATION_FAILED",["Ensure element context is properly set",'Check if "me" is available in current scope']);return this.trackPerformance(e,t,s,n),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 Un{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=Hn(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=e.you,s=this.isElement(r)?r:null,i=this.success(s,"element");return this.trackPerformance(e,t,i,n),i}catch(r){const s=this.failure("YouExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "you"',"YOU_EVALUATION_FAILED",["Ensure target element is available in context",'Check if "you" is set by event or command']);return this.trackPerformance(e,t,s,n),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 Un{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=Hn(),this.outputType="Any",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=e.it,s={success:!0,value:r,type:this.inferType(r)};return this.trackPerformance(e,t,s,n),s}catch(r){const s=this.failure("ItExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "it"',"IT_EVALUATION_FAILED",['Ensure "it" is set by previous operation',"Check if context variable is available"]);return this.trackPerformance(e,t,s,n),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 Un{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=es,this.outputType="ElementList",this.metadata={category:"Reference",complexity:"medium"}}async evaluate(e,t){const n=Date.now();try{if(!this.isValidCSSSelector(t.selector)){const r=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,r,n),r}let r;if(t.single)r=document.querySelector(t.selector);else{const e=Array.from(document.querySelectorAll(t.selector));r=e.length>0?e:null}const s={success:!0,value:r,type:Array.isArray(r)?"element-list":"element"};return this.trackPerformance(e,t,s,n),s}catch(r){const s=this.failure("CSSSelectorError","runtime-error",r instanceof Error?r.message:"CSS selector evaluation failed","CSS_SELECTOR_EVALUATION_FAILED",["Check if selector is valid CSS","Ensure DOM is ready when query executes","Verify elements exist in document"]);return this.trackPerformance(e,t,s,n),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:n}=t.data;return this.isValidCSSSelector(n)?this.validationSuccess():this.validationFailure("syntax-error",`Invalid CSS selector syntax: "${n}"`,["Use .class for class selectors","Use #id for ID selectors","Use tag for element selectors","Use [attr] for attribute selectors"])}catch(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 ns={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me??null,validate:Cn},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.you??null,validate:Cn},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:Cn},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:Cn},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.result,validate:Cn},querySelector:{name:"querySelector",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){const[n]=t;if("string"!=typeof n)throw Error("querySelector requires a string selector");return document.querySelector(n)},validate:e=>Nn(e,"querySelector","selector")},querySelectorAll:{name:"querySelectorAll",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const n=t[0];if("string"!=typeof n)throw Error("querySelectorAll requires a string selector");const r=document.querySelectorAll(n);return Array.from(r)},validate:e=>Nn(e,"querySelectorAll","selector")},getElementById:{name:"getElementById",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){const n=t[0];if("string"!=typeof n)throw Error("getElementById requires a string ID");return document.getElementById(n)},validate:e=>Nn(e,"getElementById","ID")},getElementsByClassName:{name:"getElementsByClassName",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const n=t[0];if("string"!=typeof n)throw Error("getElementsByClassName requires a string class name");const r=document.getElementsByClassName(n);return Array.from(r)},validate:e=>Nn(e,"getElementsByClassName","className")},closest:{name:"closest",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){let n=t[0];if(n&&"object"==typeof n&&"type"in n){const e=n;"identifier"===e.type&&e.name?n=e.name:"literal"===e.type&&"string"==typeof e.value&&(n=e.value)}if("string"!=typeof n)throw Error("closest requires a string selector");return e.me?e.me.closest(n):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:Cn},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async e=>window,validate:Cn},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async e=>document,validate:Cn},elementWithSelector:{name:"elementWithSelector",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const n=t[0];if("string"!=typeof n)throw Error("Selector must be a string");const r=e?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!r)throw Error("DOM not available - cannot resolve element selector");const s=r.querySelectorAll(n);return Array.from(s)},validate:e=>Nn(e,"elementWithSelector","selector")},styleRef:{name:"styleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const n=t[0],r=t[1];if("string"!=typeof n)throw Error("StyleRef requires a string property name");const s=r||e.me;if(s&&s instanceof HTMLElement)return ts(s,n)},validate:e=>Rn(e,1,2,"styleRef","property, optional element")??An(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 n=t[0],r=t[1];if("string"!=typeof n||"string"!=typeof r)throw Error("Possessive styleRef requires possessor and property strings");let s=null;if("my"===n&&e.me?s=e.me instanceof HTMLElement?e.me:null:"its"===n&&e.it&&(s=e.it instanceof HTMLElement?e.it:null),s)return ts(s,r)},validate:e=>Sn(e,2,"possessiveStyleRef","possessor, property")??An(e,0,"possessiveStyleRef","possessor")??An(e,1,"possessiveStyleRef","property")},ofStyleRef:{name:"ofStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const n=t[0],r=t[1];if("string"!=typeof n||"string"!=typeof r)throw Error("Of styleRef requires property and reference strings");let s=null;if("me"===r&&e.me?s=e.me instanceof HTMLElement?e.me:null:"it"===r&&e.it&&(s=e.it instanceof HTMLElement?e.it:null),s)return ts(s,n)},validate:e=>Sn(e,2,"ofStyleRef","property, reference")??An(e,0,"ofStyleRef","property")??An(e,1,"ofStyleRef","reference")}};class rs{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(this.ttl>=Date.now()-t.timestamp)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(),this.cache.set(e,{result:t,timestamp:Date.now(),accessCount:1}),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[n,r]of this.accessOrder)t>r&&(t=r,e=n);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,n)=>e+(t-n.timestamp),0)/e.length:0,totalAccesses:e.reduce((e,t)=>e+t.accessCount,0)}}}const ss=new class{constructor(){this.domQueryCache=new rs(200,3e3),this.exprResultCache=new rs(500,2e3),this.cssMatchCache=new rs(100,5e3),this.formValueCache=new rs(50,1e3),this.hits=0,this.misses=0}querySelector(e){const t="querySelector:"+e,n=this.domQueryCache.get(t);if(void 0!==n)return this.hits++,n;this.misses++;const r=document.querySelector(e);return this.domQueryCache.set(t,r),r}querySelectorAll(e){const t="querySelectorAll:"+e,n=this.domQueryCache.get(t);if(void 0!==n)return this.hits++,n;this.misses++;const r=Array.from(document.querySelectorAll(e));return this.domQueryCache.set(t,r),r}getElementById(e){const t="getElementById:"+e,n=this.domQueryCache.get(t);if(void 0!==n)return this.hits++,n;this.misses++;const r=document.getElementById(e);return this.domQueryCache.set(t,r),r}getElementsByClassName(e){const t="getElementsByClassName:"+e,n=this.domQueryCache.get(t);if(void 0!==n)return this.hits++,n;this.misses++;const r=Array.from(document.getElementsByClassName(e));return this.domQueryCache.set(t,r),r}matches(e,t){const n=`matches:${this.getElementCacheKey(e)}:${t}`,r=this.cssMatchCache.get(n);if(void 0!==r)return this.hits++,r;this.misses++;const s=e.matches(t);return this.cssMatchCache.set(n,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),n=this.formValueCache.get("formValue:"+t);if(void 0!==n)return this.hits++,n;this.misses++}setFormValue(e,t){const n=this.getElementCacheKey(e);this.formValueCache.set("formValue:"+n,t)}invalidateElementCache(e){const t=this.getElementCacheKey(e);for(const e of[this.domQueryCache,this.cssMatchCache,this.formValueCache])for(const n of Array.from(e.cache.keys()))"string"==typeof n&&n.includes(t)&&e.delete(n)}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("."),n=this.getElementPosition(e);return`${e.tagName.toLowerCase()}${t?"."+t:""}@${n}`}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(([n,r])=>{e-r.timestamp>t.ttl&&t.delete(n)})})}};"undefined"!=typeof window&&setInterval(()=>{ss.cleanup()},1e4);const is=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 n=performance.now()-t;return this.startTimes.delete(e),n}return 0}recordTokenization(e){this.metrics.tokenizationTime+=e}recordEvaluation(e){this.metrics.evaluationTime+=e}updateCacheMetrics(){const e=ss.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 os(){ss.cleanup(),is.getMetrics().memoryUsage>52428800&&is.reset()}let as=null;function cs(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 n=e.trim();if(""===n)return 0;const r=parseFloat(n);if(isNaN(r))throw Error(`${t} cannot be converted to number: "${e}"`);return r}if("boolean"==typeof e)return e?1:0;if(null==e)return 0;if("object"==typeof e&&null!==e){if(Array.isArray(e)&&1===e.length){const n=e[0];if(Array.isArray(n))throw Error(t+" is a nested array, cannot convert to number");return cs(n,t)}if("string"==typeof e.textContent||"value"in e){const t=e.value??e.textContent;if(null!=t){const e=(t+"").trim();if(""===e)return 0;const n=parseFloat(e);if(!isNaN(n))return n}}const n=e.valueOf();if("number"==typeof n&&Number.isFinite(n))return n}throw Error(`${t} cannot be converted to number: ${typeof e}`)}function ls(e){if("number"==typeof e)return Number.isFinite(e)?e:null;if("string"==typeof e){const t=e.trim();if(""===t)return 0;const n=parseFloat(t);return isNaN(n)?null:n}return"boolean"==typeof e?e?1:0:null==e?0:null}function us(e,t){if(!Number.isFinite(e)){if(Number.isNaN(e))throw Error(t+" resulted in non-finite value: NaN");throw Error(`${t} resulted in non-finite value: ${e>0?"Infinity":"-Infinity"}`)}return e}function fs(e){try{return cs(e,"_"),!0}catch{return!1}}function hs(e,t,n){if("==="===n)return e===t;if("!=="===n)return e!==t;if(null==e||null==t)return function(e,t,n){if(null==e&&null==t)switch(n){case"==":case">=":case"<=":return!0;default:return!1}switch(n){case"==":case">":case"<":case">=":case"<=":default:return!1;case"!=":return!0}}(e,t,n);const[r,s]=function(e,t){if("number"==typeof e&&"number"==typeof t)return[e,t];if("string"==typeof e&&"string"==typeof t){const n=parseFloat(e),r=parseFloat(t);return isNaN(n)||isNaN(r)?[e,t]:[n,r]}const n=ls(e),r=ls(t);return null!==n&&null!==r?[n,r]:[e+"",t+""]}(e,t);switch(n){case">":return r>s;case"<":return s>r;case">=":return r>=s;case"<=":return s>=r;case"==":return ds(e,t);case"!=":return!ds(e,t);default:return!1}}function ds(e,t){if(e===t)return!0;if(typeof e==typeof t)return("string"==typeof e||"number"==typeof e)&&e===t;if("number"==typeof e&&"string"==typeof t){const n=parseFloat(t);return!isNaN(n)&&e===n}if("string"==typeof e&&"number"==typeof t){const n=parseFloat(e);return!isNaN(n)&&n===t}return"boolean"==typeof e?ds(e?1:0,t):"boolean"==typeof t?ds(e,t?1:0):e+""==t+""}function ps(e,t=[]){return{isValid:!1,errors:e,suggestions:t}}function ms(e,t,n=[],r="error"){return{type:e,message:t,suggestions:n,severity:r}}function ys(e,t,n,r,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:n,output:r,timestamp:s,duration:Date.now()-s,success:i,...void 0!==o&&{error:o}}),r}"undefined"!=typeof window&&function(e=3e4){as&&clearInterval(as),as=setInterval(os,e)}();const gs=Bn({left:Vn().describe("Left operand value"),right:Vn().describe("Right operand value")}).strict(),vs=Bn({operand:Vn().describe("Operand value to negate")}).strict();function bs(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType}new class extends Un{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=gs,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const s=this.toBoolean(t.left);if(!s)return this.trackSimple(e,n,!0,"boolean"),this.success(!1,"boolean");const i=this.toBoolean(t.right),o=s&&i;return this.trackSimple(e,n,!0,"boolean"),this.success(o,"boolean")}catch(t){return this.trackSimple(e,n,!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 Un{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=gs,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const s=this.toBoolean(t.left);if(s)return this.trackSimple(e,n,!0,"boolean"),this.success(!0,"boolean");const i=this.toBoolean(t.right),o=s||i;return this.trackSimple(e,n,!0,"boolean"),this.success(o,"boolean")}catch(t){return this.trackSimple(e,n,!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 Un{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=vs,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const s=!this.toBoolean(t.operand);return this.trackSimple(e,n,!0,"boolean"),this.success(s,"boolean")}catch(t){return this.trackSimple(e,n,!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 ws=qn([Vn(),Vn()]),Es=qn([Vn(),Dn()]),xs={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(e,t,n){const r=Date.now();try{return ys(this,e,[t,n],t==n,r)}catch(s){throw ys(this,e,[t,n],!1,r,!1,s instanceof Error?s:Error(s+"")),s}},validate:e=>Tn(e,"equals"),inputSchema:ws,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"]}},ks={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],async evaluate(e,t,n){const r=e.evaluationHistory,s=t===n;return r&&ys(this,e,[t,n],s,r?Date.now():0),s},validate:e=>Tn(e,"strictEquals")},Ss={name:"notEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=","is not","does not equal"],async evaluate(e,t,n){const r=e.evaluationHistory,s=t!=n;return r&&ys(this,e,[t,n],s,r?Date.now():0),s},validate:e=>Tn(e,"notEquals")},As={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],async evaluate(e,t,n){const r=e.evaluationHistory,s=t!==n;return r&&ys(this,e,[t,n],s,r?Date.now():0),s},validate:e=>Tn(e,"strictNotEquals")},Ns={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0,i=hs(t,n,"<");return r&&ys(this,e,[t,n],i,s),i},validate:e=>Tn(e,"lessThan")},Ts={name:"lessThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<=","is less than or equal to"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0,i=hs(t,n,"<=");return r&&ys(this,e,[t,n],i,s),i},validate:e=>Tn(e,"lessThanOrEqual")},Cs={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0,i=hs(t,n,">");return r&&ys(this,e,[t,n],i,s),i},validate:e=>Tn(e,"greaterThan")},Os={name:"greaterThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">=","is greater than or equal to"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0,i=hs(t,n,">=");return r&&ys(this,e,[t,n],i,s),i},validate:e=>Tn(e,"greaterThanOrEqual")},Rs={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(e,t,n){const r=Date.now();try{return ys(this,e,[t,n],t&&n,r)}catch(s){throw ys(this,e,[t,n],!1,r,!1,s instanceof Error?s:Error(s+"")),s}},validate:e=>Tn(e,"and"),inputSchema:ws,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"]}},$s={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],async evaluate(e,t,n){const r=e.evaluationHistory,s=t||n;return r&&ys(this,e,[t,n],s,r?Date.now():0),s},validate:e=>Tn(e,"or")},Ls={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],async evaluate(e,t){const n=e.evaluationHistory,r=!t;return n&&ys(this,e,[t],r,n?Date.now():0),r},validate:e=>Sn(e,1,"not","operand")},js={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0;let s;return s=null==t||(fn(t)||Array.isArray(t)||t instanceof NodeList?0===t.length:!(t instanceof Node||t instanceof Element||!pn(t)||0!==Object.keys(t).length)),n&&ys(this,e,[t],s,r),s},validate:e=>Sn(e,1,"isEmpty","value")},Is={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0;let s;return s=null==t||!1===t||(Array.isArray(t)||t instanceof NodeList?0===t.length:(fn(t),!1)),n&&ys(this,e,[t],s,r),s},validate:e=>Sn(e,1,"no","value")},Ms={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0,s=!await js.evaluate(e,t);return n&&ys(this,e,[t],s,r),s},validate:e=>Sn(e,1,"isNotEmpty","value")},Ds={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0,s=Ps(t);return n&&ys(this,e,[t],s,r),s},validate:e=>Sn(e,1,"exists","value")};function Ps(e){return null!=e&&(Array.isArray(e)?e.length>0:!("undefined"!=typeof NodeList&&e instanceof NodeList)||e.length>0)}const Fs={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0,s=!Ps(t);return n&&ys(this,e,[t],s,r),s},validate:e=>Sn(e,1,"doesNotExist","value")},Bs={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0;let i;if(t&&n){if(bs(t)&&bs(n))return i=t.contains(n),r&&ys(this,e,[t,n],i,s),i;if(fn(t)&&t.match(/^[.#][\w-]+$/)){const o=document.querySelector(t);if(o&&bs(n))return i=o.contains(n),r&&ys(this,e,[t,n],i,s),i;if(o&&fn(n)&&n.match(/^[.#][\w-]+$/)){const a=document.querySelector(n);return i=!!a&&o.contains(a),r&&ys(this,e,[t,n],i,s),i}}if(fn(n)&&n.match(/^[.#][\w-]+$/)&&bs(t)){const o=document.querySelector(n);return i=!!o&&t.contains(o),r&&ys(this,e,[t,n],i,s),i}}if(fn(t)&&fn(n))i=t.includes(n);else if(Array.isArray(t)||"undefined"!=typeof NodeList&&t instanceof NodeList){const e=Array.from(t);i=e.includes(n)||n instanceof Node&&e.some(e=>e instanceof Node&&e.contains(n))}else i=!(!pn(t)||!fn(n))&&n in t;return r&&ys(this,e,[t,n],i,s),i},validate:e=>Sn(e,2,"contains","container, value")},qs={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0,i=!await Bs.evaluate(e,t,n);return r&&ys(this,e,[t,n],i,s),i},validate:e=>Sn(e,2,"doesNotContain","container, value")},Vs={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0,i=null!=t&&null!=n&&(t+"").startsWith(n+"");return r&&ys(this,e,[t,n],i,s),i},validate:e=>Sn(e,2,"startsWith","str, prefix")},_s={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0,i=null!=t&&null!=n&&(t+"").endsWith(n+"");return r&&ys(this,e,[t,n],i,s),i},validate:e=>Sn(e,2,"endsWith","str, suffix")},Hs={name:"between",category:"Logical",evaluatesTo:"Boolean",operators:["is between","between"],async evaluate(e,t,n,r){const s=e.evaluationHistory;let i=n,o=r;if(null!=i&&null!=o&&i>o){const e=i;i=o,o=e}const a=null!=i&&null!=o&&t>=i&&o>=t;return s&&ys(this,e,[t,n,r],a,s?Date.now():0),a},validate:e=>Sn(e,3,"between","value, min, max")},Us={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(e,t,n){const r=Date.now();try{let s;if(t instanceof Element&&fn(n)){const e=n;if(e.startsWith(".")||e.startsWith("#")||e.startsWith(":")||e.startsWith("[")||/^[a-zA-Z][\w-]*$/.test(e))try{s=function(e,t){return ss.matches(e,t)}(t,e)}catch(e){s=!1}else s=!1}else if(fn(t)&&fn(n)){const e=t,r=n;try{s=(r.startsWith("/")&&r.endsWith("/")?RegExp(r.slice(1,-1)):RegExp(r)).test(e)}catch(t){s=e.includes(r)}}else s=!1;return ys(this,e,[t,n],s,r)}catch(s){throw ys(this,e,[t,n],!1,r,!1,s instanceof Error?s:Error(s+"")),s}},validate:e=>Sn(e,2,"matches","element, selector"),inputSchema:Es,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"]}},zs={name:"has",category:"Logical",evaluatesTo:"Boolean",operators:["has","have"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0;let i=!1;if(t instanceof Element&&fn(n)){const e=n;e.startsWith(".")?i=t.classList.contains(e.slice(1)):e.startsWith("[")&&e.endsWith("]")&&(i=t.hasAttribute(e.slice(1,-1)))}return r&&ys(this,e,[t,n],i,s),i},validate:e=>Sn(e,2,"has","element, selector")},Ws={name:"doesNotHave",category:"Logical",evaluatesTo:"Boolean",operators:["does not have"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0,i=!await zs.evaluate(e,t,n);return r&&ys(this,e,[t,n],i,s),i},validate:e=>Sn(e,2,"doesNotHave","element, selector")},Js={equals:xs,strictEquals:ks,notEquals:Ss,strictNotEquals:As,lessThan:Ns,lessThanOrEqual:Ts,greaterThan:Cs,greaterThanOrEqual:Os,and:Rs,or:$s,not:Ls,no:Is,isEmpty:js,isNotEmpty:Ms,exists:Ds,doesNotExist:Fs,contains:Bs,doesNotContain:qs,startsWith:Vs,endsWith:_s,between:Hs,matches:Us,has:zs,doesNotHave:Ws},Zs=Bn({value:Dn().describe("String literal value")}).strict(),Ks=Bn({value:Pn().describe("Number literal value")}).strict(),Gs=Bn({value:Fn().describe("Boolean literal value")}).strict(),Xs=Bn({left:Vn().describe("Left operand"),right:Vn().describe("Right operand")}).strict();const Ys={stringLiteral:new class extends Un{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=Zs,this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid){const t=this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions);return this.trackSimple(e,n,!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,n,!0,s),i}catch(t){return this.trackSimple(e,n,!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 n=e.replace(/\$\{([^}]+)\}/g,(e,n)=>{try{const e=this.resolveExpression(n.trim(),t);return void 0!==e?e+"":""}catch(e){return""}});return n=n.replace(/\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g,(e,n)=>{try{const e=this.resolveVariable(n,t);return void 0!==e?e+"":""}catch(e){return""}}),n}resolveExpression(e,t){if(e.includes(".")){const n=e.split(".");let r=this.resolveVariable(n[0],t);for(let e=1;n.length>e&&null!=r;e++)r=r[n[e]];return r}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)?(Pe(e,t),t.locals.get(e)):t.globals?.has(e)?t.globals.get(e):void 0}},numberLiteral:new class extends Un{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=Ks,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);return r.isValid?Number.isFinite(t.value)?(this.trackSimple(e,n,!0,t.value),this.success(t.value,"number")):(this.trackSimple(e,n,!1),this.failure("NumberValidationError","invalid-argument","Number literal must be finite","NUMBER_NOT_FINITE")):(this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(t){return this.trackSimple(e,n,!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?Number.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 Un{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=Gs,this.outputType="Boolean",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);return r.isValid?(this.trackSimple(e,n,!0,t.value),this.success(t.value,"boolean")):(this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(t){return this.trackSimple(e,n,!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 Un{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=Xs,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions);const s=cs(t.left,"left operand")+cs(t.right,"right operand");return this.trackSimple(e,n,!0,s),this.success(s,"number")}catch(t){return this.trackSimple(e,n,!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 Un{constructor(){super(...arguments),this.name="stringConcatenation",this.category="Special",this.syntax="left + right (string concatenation)",this.description="Concatenation of two values into a string",this.inputSchema=Xs,this.outputType="String",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors[0]?.message||"Invalid input","STRING_CONCATENATION_VALIDATION_FAILED",r.suggestions);const s=this.convertToString(t.left)+this.convertToString(t.right);return this.trackSimple(e,n,!0,s),this.success(s,"string")}catch(t){return this.trackSimple(e,n,!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=Xs.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(fn(e))return e;if(hn(e))return""+e;if(dn(e))return""+e;if(e instanceof Date)return""+e;try{return e+""}catch{return"[object Object]"}}},multiplication:new class extends Un{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=Xs,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions);const s=cs(t.left,"left operand")*cs(t.right,"right operand");return this.trackSimple(e,n,!0,s),this.success(s,"number")}catch(t){return this.trackSimple(e,n,!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"])}}}},Qs={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"},ei=Bn({collection:Vn().describe("Collection to operate on (array, NodeList, or string)")}).strict(),ti=Bn({collection:Vn().describe("Collection to access"),index:Pn().describe("Index position to access")}).strict(),ni=Bn({collection:Vn().describe("Collection to select random item from")}).strict();new class extends Un{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=ei,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const s=this.normalizeCollection(t.collection),i=s.length>0?s[0]:void 0,o={success:!0,value:i,type:Qs[this.inferEvaluationType(i)]};return this.trackPerformance(e,t,o,n),o}catch(r){const s=this.failure("FirstExpressionError","runtime-error","First operation failed: "+(r instanceof Error?r.message:r+""),"FIRST_OPERATION_FAILED");return this.trackPerformance(e,t,s,n),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"])}}},new class extends Un{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=ei,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const s=this.normalizeCollection(t.collection),i=s.length>0?s[s.length-1]:void 0,o={success:!0,value:i,type:Qs[this.inferEvaluationType(i)]};return this.trackPerformance(e,t,o,n),o}catch(r){const s=this.failure("LastExpressionError","runtime-error","Last operation failed: "+(r instanceof Error?r.message:r+""),"LAST_OPERATION_FAILED");return this.trackPerformance(e,t,s,n),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"])}}},new class extends Un{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=ti,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.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:Qs[this.inferEvaluationType(o)]};return this.trackPerformance(e,t,a,n),a}catch(r){const s=this.failure("AtExpressionError","runtime-error","At operation failed: "+(r instanceof Error?r.message:r+""),"AT_OPERATION_FAILED");return this.trackPerformance(e,t,s,n),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}},new class extends Un{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=ni,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const s=this.normalizeCollection(t.collection);if(0===s.length){const r={success:!0,value:void 0,type:"undefined"};return this.trackPerformance(e,t,r,n),r}const i=s[this.getSecureRandomIndex(s.length)],o={success:!0,value:i,type:Qs[this.inferEvaluationType(i)]};return this.trackPerformance(e,t,o,n),o}catch(r){const s=this.failure("RandomExpressionError","runtime-error","Random operation failed: "+(r instanceof Error?r.message:r+""),"RANDOM_OPERATION_FAILED");return this.trackPerformance(e,t,s,n),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)}};const ri={name:"first",category:"Reference",evaluatesTo:"Any",operators:["first"],async evaluate(e,t){const n=void 0!==t?t:e.it;return null==n?null:Array.isArray(n)||n instanceof NodeList||n instanceof HTMLCollection?n.length>0?n[0]:null:n instanceof Element?n.children.length>0?n.children[0]:null:fn(n)?n.length>0?n[0]:null:pn(n)&&"length"in n&&hn(n.length)&&n.length>0?n[0]:null},validate:e=>On(e,1,"first","collection")},si={name:"last",category:"Reference",evaluatesTo:"Any",operators:["last"],async evaluate(e,t){const n=void 0!==t?t:e.it;if(null==n)return null;if(Array.isArray(n))return n.length>0?n[n.length-1]:null;if(n instanceof NodeList||n instanceof HTMLCollection)return n.length>0?n[n.length-1]:null;if(n instanceof Element){const e=n.children;return e.length>0?e[e.length-1]:null}return fn(n)?n.length>0?n[n.length-1]:null:pn(n)&&"length"in n&&hn(n.length)&&n.length>0?n[n.length-1]:null},validate:e=>On(e,1,"last","collection")},ii={name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(e,...t){const[n,r]=t;if(!hn(n))throw Error("Index must be a number");const s=n,i=void 0!==r?r: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(fn(i)){const e=0>s?i.length+s:s;return e>=0&&i.length>e?i[e]:null}if(pn(i)&&"length"in i&&hn(i.length)){const e=0>s?i.length+s:s;return e>=0&&i.length>e?i[e]:null}return null},validate:e=>Rn(e,1,2,"at","index, optional collection")??function(e){return"number"!=typeof e[0]?"at index must be a number":null}(e)};function oi(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;const e=n.querySelector(t);if(e)return e;n=n.nextElementSibling}const r=e.parentElement;return r&&r!==document.documentElement?oi(r,t):null}function ai(e,t){let n=e.previousElementSibling;for(;n;){const e=Array.from(n.querySelectorAll(t)).reverse();if(e.length>0)return e[0];if(n.matches(t))return n;n=n.previousElementSibling}const r=e.parentElement;return r&&r!==document.documentElement?ai(r,t):null}function ci(e,t,n,r){if(n.inSearch){if(null==n.inElt)return;return function(e,t,n,r){const s=Array.from(t??[]),i=[];for(const t of s)(t.matches&&t.matches(n)||t===e)&&i.push(t);for(let t=0;i.length-1>t;t++)if(i[t]===e)return i[t+1];if(r){const e=i[0];if(e&&e.matches&&e.matches(n))return e}}(e,r?Array.from(n.inElt):Array.from(n.inElt).reverse(),t,!!n.wrapping)}const s=n.within??("undefined"!=typeof document?document.body:null);if(s)return r?function(e,t,n,r){const s=t.querySelectorAll(n);for(let t=0;s.length>t;t++){const n=s[t];if(2===n.compareDocumentPosition(e))return n}return r?s[0]:void 0}(e,s,t,!!n.wrapping):function(e,t,n,r){const s=t.querySelectorAll(n);for(let t=s.length-1;t>=0;t--){const n=s[t];if(4===n.compareDocumentPosition(e))return n}return r?s[s.length-1]:void 0}(e,s,t,!!n.wrapping)}function li(e){let t=0,n=e;for(;n&&n.parentElement;)t+=Array.from(n.parentElement.children).indexOf(n),n=n.parentElement,t+=1e3;return t}const ui={first:ri,last:si,at:ii,next:{name:"next",category:"Reference",evaluatesTo:"Element",operators:["next"],async evaluate(e,...t){const[n,r,s]=t,i=r||e.me;return i&&i instanceof Element?n?s?ci(i,n,s,!0):oi(i,n):i.nextElementSibling:null},validate:e=>On(e,3,"next","optional selector, optional fromElement, optional modifiers")||(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[n,r,s]=t,i=r||e.me;return i&&i instanceof Element?n?s?ci(i,n,s,!1):ai(i,n):i.previousElementSibling:null},validate:e=>On(e,3,"previous","optional selector, optional fromElement, optional modifiers")||(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[n,r,s]=t,i=s||e.me;if(!(i&&i instanceof Element))return null;const o=i.closest(r);return o?function(e,t,n){const r=Array.from(n.querySelectorAll(t)),s=li(e);for(const e of r)if(li(e)>s)return e;return null}(i,n,o):null},validate:e=>Rn(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[n,r,s]=t,i=s||e.me;if(!(i&&i instanceof Element))return null;const o=i.closest(r);return o?function(e,t,n){const r=Array.from(n.querySelectorAll(t)),s=li(e);for(let e=r.length-1;e>=0;e--){const t=r[e];if(s>li(t))return t}return null}(i,n,o):null},validate:e=>Rn(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")}};function fi(){return Qr(ns,Js,Ys,rr,ui)}class hi{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 n=nn(e);this.runtime.execute(t,n).catch(n=>{console.error('[HyperFixi] Error executing _="" attribute:',n),console.error("Element:",e),console.error("Code:",t)})}}function di(e,t,n,r,s,i){function o(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var a,c=r.kind,l="getter"===c?"get":"setter"===c?"set":"value",u=!t&&e?r.static?e:e.prototype:null,f=t||(u?Object.getOwnPropertyDescriptor(u,r.name):{}),h=!1,d=n.length-1;d>=0;d--){var p={};for(var m in r)p[m]="access"===m?{}:r[m];for(var m in r.access)p.access[m]=r.access[m];p.addInitializer=function(e){if(h)throw new TypeError("Cannot add initializers after decoration has completed");i.push(o(e||null))};var y=(0,n[d])("accessor"===c?{get:f.get,set:f.set}:f[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))&&(f.get=a),(a=o(y.set))&&(f.set=a),(a=o(y.init))&&s.unshift(a)}else(a=o(y))&&("field"===c?s.unshift(a):f[l]=a)}u&&Object.defineProperty(u,r.name,f),h=!0}function pi(e,t,n){for(var r=arguments.length>2,s=0;t.length>s;s++)n=r?t[s].call(e,n):t[s].call(e);return r?n:void 0}function mi(e,t,n){return"symbol"==typeof t&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:n?"".concat(n," ",t):t})}function yi(e){const t=e.trim();return!(!t.startsWith("[@")||!t.endsWith("]"))||!!t.startsWith("@")}function gi(e){const t=e.trim();if(t.startsWith("[@")&&t.endsWith("]")){const e=t.slice(2,-1),n=e.indexOf("=");if(-1===n)return{name:e.trim()};const r=e.slice(0,n).trim();let s=e.slice(n+1).trim();return(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),{name:r,value:s}}if(t.startsWith("@"))return{name:t.substring(1).trim()};throw Error("Invalid attribute syntax: "+e)}function vi(e,t){for(const n of e)t(n);return e}function bi(e,t,n){for(const r of e)for(const e of t)n(r,e);return e}function wi(e,t,n){const r=e.hasAttribute(t);void 0!==n?r&&e.getAttribute(t)===n?e.removeAttribute(t):e.setAttribute(t,n):r?e.removeAttribute(t):e.setAttribute(t,"")}function Ei(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&&ki(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&&ki(e));const t=(e+"").trim(),n=t.startsWith(".")?t.substring(1):t;return n.length>0&&ki(n)?[n]:[]}function xi(e){const t=e.trim();return/^\{[^}]+\}$/.test(t)}function ki(e){if(!e||0===e.trim().length)return!1;const t=e.trim();return!!xi(t)||/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(t)}function Si(e,t){return e.map(e=>{if(xi(e)){const n=function(e){const t=e.trim(),n=t.match(/^\{(.+)\}$/);return n?n[1].trim():t}(e),r=t.locals.get(n)??t.globals.get(n);return null!=r?r+"":(fe(`Dynamic class variable '${n}' not found in context`),"")}return e}).filter(e=>e.length>0)}"function"==typeof SuppressedError&&SuppressedError;const Ai=Symbol("command:name"),Ni=Symbol("command:category"),Ti=Symbol("command:metadata");function Ci(e){return function(t,n){const r=t;r[Ai]=e.name,r[Ni]=e.category,Object.defineProperty(t.prototype,"name",{value:e.name,writable:!1,enumerable:!0})}}function Oi(e){return function(t,n){const r=t,s=r[Ni];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",compatibility:e.compatibility};r[Ti]=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 Ri(e){return()=>new e}function $i(e,t){return t}function Li(e,t,n){if(rn(e))return e;if(!e){const e=t.me;if(!e)throw Error($i(0,"No target element — provide explicit target or ensure context.me is set"));return Ii(e)}if("string"==typeof e){const n=e.trim();if("me"===n){if(!t.me)throw Error($i(0,'Context reference "me" is not available'));return Ii(t.me)}if("it"===n){if(!rn(t.it))throw Error($i(0,'Context reference "it" is not an HTMLElement'));return t.it}if("you"===n){if(!t.you)throw Error($i(0,'Context reference "you" is not available'));return Ii(t.you)}const r=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!r)throw Error($i(0,"DOM not available — cannot resolve element selector"));const s=r.querySelector(n);if(!s)throw Error($i(0,"Element not found with selector: "+n));if(!rn(s))throw Error($i(0,"Element found but is not an HTMLElement: "+n));return s}throw Error($i(0,"Invalid target type: "+typeof e))}function ji(e,t){if(Array.isArray(e))return e.filter(rn);if(sn(e))return Array.from(e).filter(rn);if(rn(e))return[e];if(!e){const e=t.me;return e&&rn(e)?[e]:[]}if("string"==typeof e){const n=e.trim();if("me"===n)return t.me&&rn(t.me)?[t.me]:[];if("it"===n)return rn(t.it)?[t.it]:[];if("you"===n)return t.you&&rn(t.you)?[t.you]:[];const r=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(r){let e=n;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const t=r.querySelectorAll(e);return Array.from(t).filter(rn)}}return[]}function Ii(e){if(rn(e))return e;throw Error("Value is not an HTMLElement")}function Mi(e,t,n){switch(e.toLowerCase()){case"my":case"me":if(!t.me)throw Error($i(0,'No "me" element in context'));if(!rn(t.me))throw Error($i(0,"context.me is not an HTMLElement"));return t.me;case"its":case"it":if(!t.it)throw Error($i(0,'No "it" value in context'));if(!rn(t.it))throw Error($i(0,"context.it is not an HTMLElement"));return t.it;case"your":case"you":if(!t.you)throw Error($i(0,'No "you" element in context'));if(!rn(t.you))throw Error($i(0,"context.you is not an HTMLElement"));return t.you;default:throw Error($i(0,"Unknown possessive: "+e))}}const Di=["on","from","to","in","with","at"];async function Pi(e,t,n,r,s={},i){let o=e;if(s.filterPrepositions&&e&&(o=e.filter(e=>{const t=e;return"identifier"!==t?.type||"string"!=typeof t.name||!Di.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(!n.me)throw Error(r+" command: no target specified and context.me is null");if(!rn(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}const a=[];for(const e of o){const s=await t.evaluate(e,n);if(""!==s&&("string"!=typeof s||""!==s.trim()))if(rn(s))a.push(s);else if(sn(s)){const e=Array.from(s).filter(rn);a.push(...e)}else if(Array.isArray(s)){const e=s.filter(rn);a.push(...e)}else{if("string"!=typeof s){if(null==s)continue;throw Error(`Invalid ${r} 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=n.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!t)throw Error("DOM not available - cannot resolve element selector");const r=t.querySelectorAll(e),i=Array.from(r).filter(rn);a.push(...i)}catch(e){throw Error(`Invalid CSS selector: "${s}" - ${e instanceof Error?e.message:e+""}`)}}}if(0===a.length){if(!n.me)throw Error(r+" command: no target specified and context.me is null");if(!rn(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}return a}function Fi(e){return"string"==typeof e&&e.trim().startsWith("*")}function Bi(e){const t=function(e){const t=e.trim();if(!t.startsWith("*"))return null;const n=t.substring(1).trim();return n?{property:n}:null}(e);if(!t)return null;const n=t.property.toLowerCase();return["display","visibility","opacity"].includes(n)?n:null}function qi(e,t,n){e.style.setProperty(t,n)}const Vi=["dialog","details","summary","select"];function _i(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 Hi(e,t,n){return function(e){if(!e||"object"!=typeof e)return!1;const t=e.type;if("selector"!==t&&"cssSelector"!==t&&"classSelector"!==t)return!1;const n=_i(e);return"string"==typeof n&&n.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 n=_i(e);return"string"==typeof n&&n.startsWith("*")}(e)?{value:_i(e),extractedFromNode:!0}:function(e){if(!e||"object"!=typeof e)return!1;if("attributeAccess"===e.type)return!0;if("selector"===e.type||"cssSelector"===e.type){const t=_i(e);return"string"==typeof t&&t.startsWith("@")}return!1}(e)?{value:(r=e,"attributeAccess"===r.type?"@"+r.attributeName:_i(r)),extractedFromNode:!0}:{value:await t.evaluate(e,n),extractedFromNode:!1};var r}class Ui{async resolveTargets(e,t,n,r){return Pi(e,t,n,this.mode,{filterPrepositions:!0,fallbackModifierKey:this.preposition},r)}async evaluateFirst(e,t,n){return Hi(e,t,n)}parseClassNames(e){return Ei(e)}isAttribute(e){return yi(e.trim())}isCSSProperty(e){return Fi(e.trim())}validateTargets(e){return Array.isArray(e)&&function(e){return Array.isArray(e)&&e.length>0&&e.every(e=>rn(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 zi=(()=>{let e,t,n=[Oi({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"]}),Ci({name:"add",category:"dom"})],r=[],s=Ui;return t=class extends s{constructor(){super(...arguments),this.mode="add",this.preposition="to"}async parseInput(e,t,n){if(!e.args||0===e.args.length)throw Error("add command requires an argument");const{value:r}=await this.evaluateFirst(e.args[0],t,n);if("object"==typeof r&&null!==r&&!Array.isArray(r))return{type:"styles",styles:r,targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)};if("string"==typeof r){const s=r.trim();if(this.isAttribute(s)){const{name:r,value:i}=function(e){const t=gi(e);return{name:t.name,value:t.value??""}}(s);return{type:"attribute",name:r,value:i,targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)}}if(this.isCSSProperty(s)){const r=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],n);return{type:"styles",styles:{[r]:i+""},targets:await this.resolveTargets(e.args.slice(2),t,n,e.modifiers)}}}const s=this.parseClassNames(r);if(0===s.length)throw Error("add command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)}}async execute(e,t){switch(e.type){case"classes":{const n=Si(e.classes,t);n.length>0&&bi(e.targets,n,(e,t)=>{e.classList.contains(t)||e.classList.add(t)});break}case"attribute":n=e.name,r=e.value,vi(e.targets,e=>{e.setAttribute(n,r)});break;case"styles":!function(e,t){bi(e,Object.entries(t),(e,[t,n])=>{e.style.setProperty(t,n)})}(e.targets,e.styles)}var n,r}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 n=t.styles;if(0===Object.keys(n).length)return!1;if(!Object.values(n).every(e=>"string"==typeof e))return!1}return!0}},mi(t,"AddCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;di(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),pi(t,r)})(),t})();const Wi=Ri(zi);function Ji(e){return!!e.parentNode&&(e.remove(),!0)}let Zi=(()=>{let e,t,n=[Oi({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"]}),Ci({name:"remove",category:"dom"})],r=[],s=Ui;return t=class extends s{constructor(){super(...arguments),this.mode="remove",this.preposition="from"}async parseInput(e,t,n){if(!e.args||0===e.args.length)throw Error("remove command requires an argument");const{value:r}=await this.evaluateFirst(e.args[0],t,n);if(rn(r))return{type:"element",targets:[r]};if(Array.isArray(r)&&r.length>0&&rn(r[0]))return{type:"element",targets:r.filter(e=>rn(e))};if("string"==typeof r){const s=r.trim();if(this.isAttribute(s))return{type:"attribute",name:gi(s).name,targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)};if(this.isCSSProperty(s))return{type:"styles",properties:[s.substring(1).trim()],targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)}}const s=this.parseClassNames(r);if(0===s.length)throw Error("remove command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)}}execute(e,t){switch(e.type){case"classes":{const n=Si(e.classes,t);n.length>0&&bi(e.targets,n,(e,t)=>{e.classList.remove(t)});break}case"attribute":n=e.name,vi(e.targets,e=>{e.removeAttribute(n)});break;case"styles":!function(e,t){bi(e,t,(e,t)=>{e.style.removeProperty(t)})}(e.targets,e.properties);break;case"element":for(const t of e.targets)Ji(t)}var n}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}},mi(t,"RemoveCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;di(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),pi(t,r)})(),t})();const Ki=Ri(Zi);function Gi(e){const t=e.trim().match(/^(\d+(?:\.\d+)?)\s*(s|ms|sec|seconds?|milliseconds?)?$/i);if(!t)return null;const n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();return"ms"===r||"millisecond"===r||"milliseconds"===r?{number:n,milliseconds:Math.floor(n)}:"s"===r||"sec"===r||"second"===r||"seconds"===r?{number:n,milliseconds:Math.floor(1e3*n)}:null}function Xi(e){if("number"==typeof e){if(0>e)throw Error("Duration must be >= 0");return Math.floor(e)}if("string"==typeof e){const t=Gi(e);if(!t)throw Error(`Invalid duration format: "${e}"`);return t.milliseconds}throw Error("Invalid duration type: "+typeof e)}function Yi(e){return 0===e.length?[]:"SUMMARY"===e[0].tagName?e.map(e=>e.closest("details")).filter(e=>null!==e):e}function Qi(e){return"DIALOG"===e.tagName}function eo(e){return"DETAILS"===e.tagName}function to(e,t,n){return()=>{"class"===t?e.classList.toggle(n):"attribute"===t&&wi(e,n)}}function no(e,t,n,r){const s=to(e,t,n),i=setTimeout(s,r);return()=>{clearTimeout(i)}}function ro(e,t,n,r){const s=to(e,t,n),i=()=>{s(),e.removeEventListener(r,i)};return e.addEventListener(r,i,{once:!0}),()=>{e.removeEventListener(r,i)}}function so(e,t,n){if(t.startsWith("@")){const r=t.substring(1);return void(!1===n?e.removeAttribute(r):e.setAttribute(r,!0===n?"":n+""))}const r=n+"";switch(t){case"textContent":return void(e.textContent=r);case"innerHTML":return void(e.innerHTML=r);case"innerText":return void(e.innerText=r);case"id":return void(e.id=r);case"className":return void(e.className=r);case"value":return void("value"in e&&(e.value=r));case"checked":return void("checked"in e&&(e.checked=!!n))}if(t.includes(".")){const r=t.split(".");let s=e;for(let e=0;r.length-1>e;e++)if(s=s[r[e]],null==s)return;return void(s[r[r.length-1]]=n)}if(t.includes("-")||t in e.style)e.style.setProperty(t,r);else try{e[t]=n}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 io=/^the\s+(.+?)\s+of\s+(.+)$/i,oo=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 ao(e){return"string"==typeof e&&io.test(e)}function co(e,t){const n=e.match(io);if(!n)return null;try{return{element:Li(n[2].trim(),t),property:n[1].trim()}}catch{return null}}async function lo(e,t,n){if(function(e){return!(!e||"object"!=typeof e)&&"propertyOfExpression"===e.type&&"object"==typeof e.property&&null!==e.property}(e))return async function(e,t,n){const r=e.property?.name;if(!r)return null;let s=await t.evaluate(e.target,n);return Array.isArray(s)&&(s=s[0]),rn(s)?{element:s,property:r}:null}(e,t,n);if(function(e){return!(!e||"object"!=typeof e)&&"propertyAccess"===e.type&&("string"==typeof e.property||"object"==typeof e.property&&null!==e.property&&"string"==typeof e.property.name)}(e))return async function(e,t,n){const r="string"==typeof e.property?e.property:e.property?.name;if(!r)return null;let s=await t.evaluate(e.object,n);return Array.isArray(s)&&(s=s[0]),rn(s)?{element:s,property:r}:null}(e,t,n);const r=e;if("possessiveExpression"===r?.type||"memberExpression"===r?.type){const e=r.object,s=r.property;let i=await t.evaluate(e,n);if(Array.isArray(i)&&(i=i[0]),!rn(i))return null;const o=s?.name||s?.value;return o?{element:i,property:o}:null}return null}function uo(e,t){const{element:n,property:r}=e;r.startsWith("*")?qi(n,r.substring(1),t+""):so(n,r,t)}async function fo(e,t,n){let r,s;if(e?.for){const s=await t.evaluate(e.for,n);r="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 n=Gi(e);return n?n.milliseconds:t}return t}(s):void 0}if(e?.until){const r=await t.evaluate(e.until,n);"string"==typeof r&&(s=r)}return{duration:r,untilEvent:s}}function ho(e,t){const n=t?.name,r=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 Vi.includes(t)}(t)}(t);if(rn(e)||Array.isArray(e)&&e.every(e=>rn(e)))return{type:"element",expression:""};if(r&&n)return{type:"element",expression:n};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 Vi.some(e=>t.includes(e))}(t)?{type:"element",expression:t}:{type:"class",expression:t}}return{type:"class",expression:""}}const po=Ri((()=>{let e,t,n=[Oi({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"]}),Ci({name:"toggle",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("toggle command requires an argument");let r=!1;if(function(e){if(!e||"asExpression"!==e.type)return!1;const t=e.targetType,n="string"==typeof t?t:t?.name;return"string"==typeof n&&"modal"===n.toLowerCase()}(e.args[0])){r=!0;const t=e.args[0].expression;e={...e,args:[t,...e.args.slice(1)]}}const s=e.args[0],i=s?.name;if("between"===i&&e.args.length>=4){const{duration:r,untilEvent:s}=await fo(e.modifiers,t,n),i=async e=>{const r=e;return"selector"===r?.type?r.value:t.evaluate(e,n)},o=await i(e.args[1]),a=await i(e.args[3]),c=[];for(let t=4;e.args.length>t;t++){const n=e.args[t]?.name;"on"!==n&&"from"!==n&&c.push(e.args[t])}const l={filterPrepositions:!0,fallbackModifierKey:"on"},u=await Pi(c,t,n,"toggle",l,e.modifiers);return{type:"classes-between",classA:(o+"").replace(/^\./,""),classB:(a+"").replace(/^\./,""),targets:u,duration:r,untilEvent:s}}const o=await lo(s,t,n);if(o)return{type:"property",target:o};if("selector"===s.type&&"string"==typeof s.value&&s.value.startsWith("*")){let r=s.value,i=1;if("*"===r&&e.args.length>1&&"identifier"===e.args[1].type&&(r="*"+e.args[1].name,i=2),"*"===r&&e.modifiers?.on){const s=e.modifiers.on?.name;if(s&&["display","visibility","opacity"].includes(s)){r="*"+s;const{duration:i,untilEvent:o}=await fo(e.modifiers,t,n),a=Bi(r);if(a){const e=n.me;return{type:"css-property",property:a,targets:e?[e]:[],duration:i,untilEvent:o}}}}const o=Bi(r);if(o){const{duration:r,untilEvent:s}=await fo(e.modifiers,t,n),a={filterPrepositions:!0,fallbackModifierKey:"on"};return{type:"css-property",property:o,targets:await Pi(e.args.slice(i),t,n,"toggle",a,e.modifiers),duration:r,untilEvent:s}}}const{duration:a,untilEvent:c}=await fo(e.modifiers,t,n),{value:l}=await Hi(s,t,n);if(ao(l)){const e=co(l,n);if(e)return{type:"property",target:e}}const{type:u,expression:f}=ho(l,s),h={filterPrepositions:!0,fallbackModifierKey:"on"};switch(u){case"attribute":{const{name:r,value:s}=gi(f);return{type:"attribute",name:r,value:s,targets:await Pi(e.args.slice(1),t,n,"toggle",h,e.modifiers),duration:a,untilEvent:c}}case"css-property":{const r=Bi(f);if(!r)throw Error("Invalid CSS property: "+f);return{type:"css-property",property:r,targets:await Pi(e.args.slice(1),t,n,"toggle",h,e.modifiers)}}case"element":{let i;if(rn(l))i=[l];else if(Array.isArray(l)&&l.every(e=>rn(e)))i=l;else if(f){const e=document.querySelectorAll(f);i=Array.from(e).filter(e=>rn(e))}else i=await Pi([s],t,n,"toggle",h,e.modifiers);const o=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}}(i);if("dialog"===o){const s=r?"modal":await async function(e,t,n,r){if(t?.as){const e=await n.evaluate(t.as,r);if("string"==typeof e&&"modal"===e.toLowerCase())return"modal"}if(e.length>=2){const t=await n.evaluate(e[1],r);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 n.evaluate(e[2],r);if("string"==typeof t&&"modal"===t.toLowerCase())return"modal"}}}return"non-modal"}(e.args,e.modifiers,t,n);return{type:"dialog",mode:s,targets:i}}return"details"===o?{type:"details",targets:Yi(i)}:"select"===o?{type:"select",targets:i}:{type:"classes",classes:Ei(f),targets:i,duration:a,untilEvent:c}}default:{const r=Ei(f||l);if(!r.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:r,targets:await Pi(e.args.slice(1),t,n,"toggle",h,e.modifiers),duration:a,untilEvent:c}}}}async execute(e,t){switch(e.type){case"classes":{const n=Si(e.classes,t);if(0===n.length)return[...e.targets];if(bi(e.targets,n,(e,t)=>{e.classList.toggle(t)}),(e.duration||e.untilEvent)&&n.length)for(const t of e.targets)e.duration&&no(t,"class",n[0],e.duration),e.untilEvent&&ro(t,"class",n[0],e.untilEvent);return[...e.targets]}case"attribute":if(n=e.name,r=e.value,vi(e.targets,e=>{wi(e,n,r)}),e.duration||e.untilEvent)for(const t of e.targets)e.duration&&no(t,"attribute",e.name,e.duration),e.untilEvent&&ro(t,"attribute",e.name,e.untilEvent);return[...e.targets];case"css-property":return vi(e.targets,t=>function(e,t){const n=window.getComputedStyle(e);switch(t){case"display":"none"===n.display?(e.style.display=e.dataset.previousDisplay||"block",delete e.dataset.previousDisplay):(e.dataset.previousDisplay=n.display,e.style.display="none");break;case"visibility":e.style.visibility="hidden"===n.visibility?"visible":"hidden";break;case"opacity":e.style.opacity=0===parseFloat(n.opacity)?"1":"0"}}(t,e.property));case"property":return function(e){const t=function(e){const{element:t,property:n}=e;return n.startsWith("*")?function(e,t){return window.getComputedStyle(e).getPropertyValue(t)}(t,n.substring(1)):xn(t,n)}(e),n=e.property,r=n.startsWith("@")?n.substring(1):n;if("boolean"==typeof t||oo.has(r)||oo.has(r.toLowerCase())){const n=!t;return uo(e,n),n}if("number"==typeof t){const n=0===t?1:0;return uo(e,n),n}if("string"==typeof t){const r="__ht_"+n,s=e.element[r];return""===t&&void 0!==s?(uo(e,s),s):(e.element[r]=t,uo(e,""),"")}uo(e,!t)}(e.target),[e.target.element];case"dialog":return vi(e.targets,t=>{return r=e.mode,void((n=t).open?n.close():"modal"===r?n.showModal():n.show());var n,r});case"details":return vi(e.targets,e=>{var t;(t=e).open=!t.open});case"select":return vi(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 n=t.classList.contains(e.classA),r=t.classList.contains(e.classB);n?(t.classList.remove(e.classA),t.classList.add(e.classB)):r?(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&&no(t,"class",e.classA,e.duration),e.untilEvent&&ro(t,"class",e.classA,e.untilEvent);return[...e.targets]}var n,r}},mi(t,"ToggleCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;di(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),pi(t,r)})(),t})());class mo{async parseInput(e,t,n){const{targets:r}=await async function(e,t,n,r){return{targets:await Pi(e.args,t,n,r)}}(e,t,n,this.mode);return{targets:r,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=>rn(e))||"show"!==t.mode&&"hide"!==t.mode||"show"===t.mode&&"string"!=typeof t.defaultDisplay)}showElement(e,t="block"){const n=e.dataset.originalDisplay;void 0!==n?(e.style.display=n||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 yo=(()=>{let e,t,n=[Oi({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"]}),Ci({name:"show",category:"dom"})],r=[],s=mo;return t=class extends s{constructor(){super(...arguments),this.mode="show"}async execute(e,t){const n=e.defaultDisplay||"block";for(const t of e.targets)this.showElement(t,n)}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&!!t.targets.every(e=>rn(e))&&"string"==typeof t.defaultDisplay}},mi(t,"ShowCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;di(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),pi(t,r)})(),t})();const go=Ri(yo);let vo=(()=>{let e,t,n=[Oi({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"]}),Ci({name:"hide",category:"dom"})],r=[],s=mo;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=>rn(e))}},mi(t,"HideCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;di(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),pi(t,r)})(),t})();const bo=Ri(vo);const wo=Ri((()=>{let e,t,n=[Oi({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"]}),Ci({name:"put",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("put requires arguments");const r=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 n=e.args[t],a=r(n),c="literal"===a?n.value:n.name;if(("literal"===a||"identifier"===a)&&s.includes(c)){i=t,o=c;break}}let a=null,c=null;if(-1===i){const t=s.find(t=>e.modifiers[t]);if(t)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,n),u=this.mapPosition(o);let f,h,d=null;if(c){const e=r(c),s=await lo(c,t,n);if(s)return{value:l,targets:[s.element],position:"replace",memberPath:s.property};if("memberExpression"===e){const e=c.object,r=c.property;if("selector"===e?.type)d=e.value;else if("identifier"===e?.type){const s=e.name;if("my"===s||"me"===s||"I"===s){if(n.me&&r?.name)return{value:l,targets:[n.me],position:"replace",memberPath:r.name}}else if("its"===s||"it"===s){const e=await t.evaluate(c,n);"string"==typeof e&&(d=e)}else d=s}if(d&&r?.name)f=r.name;else if(!d&&!f){const e=await t.evaluate(c,n);"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&&ao(e)){const t=co(e,n);if(t)return{value:l,targets:[t.element],position:"replace",memberPath:t.property}}"string"==typeof e&&this.looksLikeCss(e)?d=e:h=e+""}else if("identifier"===e){const e=c.name;if(this.looksLikeCss(e))d=e;else{const r=await t.evaluate(c,n),s=this.resolveEvaluatedAsElements(r);if(s)return{value:l,targets:s,position:u,memberPath:f};h=e}}else{const e=await t.evaluate(c,n),r=this.resolveEvaluatedAsElements(e);if(r)return{value:l,targets:r,position:u,memberPath:f};"string"==typeof e&&(this.looksLikeCss(e)?d=e:h=e)}}return h?{value:l,targets:[],position:u,memberPath:f,variableName:h}:{value:l,targets:await this.resolveTargets(d,n),position:u,memberPath:f}}async execute(e,t){const{value:n,targets:r,position:s,memberPath:i,variableName:o}=e;if(o)return t.locals&&t.locals.set(o,n),t[o]=n,void Object.assign(t,{it:n});if(i)for(const e of r)this.setProperty(e,i,n);else for(const e of r){const t=this.parseValue(n);this.insertContent(e,t,s)}return r}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||!rn(t.me))throw Error("put: no target and context.me is null");return[t.me]}const n=Array.from(document.querySelectorAll(e)).filter(e=>rn(e));if(!n.length)throw Error(`No elements: "${e}"`);return n}parseValue(e){return rn(e)?e:null==e?"":e+""}insertContent(e,t,n){if("replace"!==n)if(rn(t)){const r=t;switch(n){case"beforebegin":e.parentElement?.insertBefore(r,e);break;case"afterbegin":e.insertBefore(r,e.firstChild);break;case"beforeend":e.appendChild(r);break;case"afterend":e.parentElement?.insertBefore(r,e.nextSibling)}}else t.includes("<")&&t.includes(">")?e.insertAdjacentHTML(n,t):e.insertAdjacentText(n,t);else rn(t)?(e.innerHTML="",e.appendChild(t)):t.includes("<")&&t.includes(">")?e.innerHTML=t:e.textContent=t}resolveEvaluatedAsElements(e){if(rn(e))return[e];if(Array.isArray(e)){const t=e.filter(rn);return t.length>0?t:null}if("undefined"!=typeof NodeList&&e instanceof NodeList){const t=Array.from(e).filter(rn);return t.length>0?t:null}return null}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,n){const r=t.split(".");let s=e;for(let e=0;r.length-1>e;e++){if(!s[r[e]])throw Error(`Property path "${t}" does not exist`);s=s[r[e]]}s[r[r.length-1]]=n}},mi(t,"PutCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;di(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),pi(t,r)})(),t})()),Eo={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function xo(e){return e.replace(/[&<>"']/g,e=>Eo[e])}let ko=(()=>{let e,t,n=[Oi({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"]}),Ci({name:"make",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){const r=e.modifiers.an??e.modifiers.a??e.args[0];if(!r)throw Error("Make command requires class name or DOM element expression");const s=r.raw;let i="string"==typeof s&&s.startsWith("<")?s:await t.evaluate(r,n);if(null==i)throw Error("Make command requires class name or DOM element expression");"string"==typeof i&&i.startsWith("<")&&(i=await async function(e,t){if(!e.includes("{"))return e;const n=/\{([^{}]+)\}/g,r=[];let s;for(;null!==(s=n.exec(e));){let e=s[0];try{const n=await mr(s[1].trim(),t);null!=n&&(e=xo(n+""))}catch{}r.push({index:s.index,length:s[0].length,text:e})}let i=e;for(let e=r.length-1;e>=0;e--){const{index:t,length:n,text:s}=r[e];i=i.slice(0,t)+s+i.slice(t+n)}return i}(i,n));const o=void 0!==e.modifiers.an?"an":"a",a=await async function(e,t,n){if(!e)return[];if("arrayLiteral"===e.type&&Array.isArray(e.args)){const r=[];for(const s of e.args)r.push(await t.evaluate(s,n));return r}const r=await t.evaluate(e,n);return Array.isArray(r)?r:[r]}(e.modifiers.from,t,n),c=await async function(e,t,n){if(!e)return;if(("symbol"===e.type||"identifier"===e.type)&&"string"==typeof e.name)return e.name;const r=await t.evaluate(e,n);return"string"==typeof r?r:void 0}(e.modifiers.called,t,n);return{article:o,expression:i,constructorArgs:a,variableName:c}}async execute(e,t){const{expression:n,constructorArgs:r=[],variableName:s}=e,i="string"==typeof n&&n.startsWith("<"),o=i&&n.endsWith("/>")?function(e){const t=e.slice(1,-2);let n="div",r=t;const s=t.match(/^([a-zA-Z][a-zA-Z0-9]*)/);s&&(n=s[1],r=t.slice(s[0].length));const i=document.createElement(n),o=r.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}(n):i&&/<\/[a-zA-Z]/.test(n)?function(e){const t=document.createElement("template");t.innerHTML=e.trim();const n=t.content.firstElementChild;if(n&&rn(n))return n;const r=document.createElement("div");r.innerHTML=e.trim();const s=r.firstElementChild;return s&&rn(s)?s:r}(n):function(e,t,n){if(rn(e))return e;const r=e+"";let s;if("undefined"!=typeof window&&(s=window[r]),s||"undefined"==typeof global||(s=global[r]),!s&&n.variables?.has(r)&&(s=n.variables.get(r)),!s||"function"!=typeof s)throw Error(`Constructor '${r}' not found or is not a function`);return 0===t.length?new s:new s(...t)}(n,r,t);return Object.assign(t,{it:o}),s&&cn(s,o,t),o}},mi(t,"MakeCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;di(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),pi(t,r)})(),t})();const So=Ri(ko),Ao=Ri((()=>{let e,t,n=[Oi({description:"Remove all children from an element (sets innerHTML to empty)",syntax:["empty","empty <target>","empty the <target>"],examples:["empty me","empty #list","empty .results"],sideEffects:["dom-mutation"]}),Ci({name:"empty",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){return{targets:await Pi(e.args,t,n,"empty",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)t.innerHTML=""}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>rn(e))}},mi(t,"EmptyCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;di(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),pi(t,r)})(),t})());function No(e){return e.hasAttribute("popover")}const To=Ri((()=>{let e,t,n=[Oi({description:"Open a dialog, details element, or popover",syntax:["open [<target>]","open <dialog> as modal","open <dialog> as non-modal"],examples:["open","open #myDialog","open #details","open #popup as non-modal"],sideEffects:["dom-mutation"]}),Ci({name:"open",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){const r=(e.args??[]).filter(e=>{const t=e;if("identifier"!==t?.type)return!0;const n=t.name?.toLowerCase();return"as"!==n&&"modal"!==n&&"non-modal"!==n&&"nonmodal"!==n}),s=Yi(await Pi(r,t,n,"open",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)),i=await async function(e,t,n,r){if(t?.as){const e=await n.evaluate(t.as,r);if("string"==typeof e){const t=e.toLowerCase().trim();if("non-modal"===t||"nonmodal"===t)return"non-modal";if("modal"===t)return"modal"}}for(let t=0;e.length-1>t;t++){const s=e[t];if("identifier"===s?.type&&"as"===s.name?.toLowerCase()){const s=await n.evaluate(e[t+1],r);if("string"==typeof s){const e=s.toLowerCase().trim();if("non-modal"===e||"nonmodal"===e)return"non-modal";if("modal"===e)return"modal"}}}return"modal"}(e.args??[],e.modifiers??{},t,n);return{targets:s,dialogMode:i}}async execute(e,t){for(const t of e.targets)if(Qi(t))t.open||("modal"===e.dialogMode?t.showModal():t.show());else if(eo(t))t.open=!0;else if(No(t)){const e=t;if("function"==typeof e.showPopover)try{e.showPopover()}catch{}}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(!Array.isArray(t.targets)||!t.targets.every(e=>rn(e))||"modal"!==t.dialogMode&&"non-modal"!==t.dialogMode)}},mi(t,"OpenCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;di(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),pi(t,r)})(),t})());function Co(e){return e.hasAttribute("popover")}const Oo=Ri((()=>{let e,t,n=[Oi({description:"Close a dialog, details element, or popover",syntax:["close","close <target>"],examples:["close","close #myDialog","close #details","close #popup"],sideEffects:["dom-mutation"]}),Ci({name:"close",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){return{targets:Yi(await Pi(e.args,t,n,"close",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers))}}async execute(e,t){for(const t of e.targets)if(Qi(t))t.open&&t.close();else if(eo(t))t.open=!1;else if(Co(t)){const e=t;if("function"==typeof e.hidePopover)try{e.hidePopover()}catch{}}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>rn(e))}},mi(t,"CloseCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;di(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),pi(t,r)})(),t})());function Ro(e){const t=e.tagName;return"INPUT"===t||"TEXTAREA"===t}const $o=Ri((()=>{let e,t,n=[Oi({description:"Select the contents of a text field, or select the contents of a DOM element",syntax:["select","select <target>"],examples:["select #search","select <textarea/>","select me"],sideEffects:["focus","dom-mutation"]}),Ci({name:"select",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){return{targets:await Pi(e.args,t,n,"select",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){if(0!==e.targets.length)for(const t of e.targets){if(Ro(t)){t.select();continue}const e=t.ownerDocument??("undefined"!=typeof document?document:null),n=e?.defaultView;if(!e||!n)continue;const r=n.getSelection?.();if(r)try{const n=e.createRange();n.selectNodeContents(t),r.removeAllRanges(),r.addRange(n)}catch{}}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>rn(e))}},mi(t,"SelectCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;di(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),pi(t,r)})(),t})());function Lo(e){return"FORM"===e.tagName}const jo=Ri((()=>{let e,t,n=[Oi({description:"Reset a <form> element to its default values (HTMLFormElement.reset())",syntax:["reset","reset <target>"],examples:["reset","reset #myForm","reset <form/>"],sideEffects:["dom-mutation"]}),Ci({name:"reset",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){return{targets:await Pi(e.args,t,n,"reset",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)Lo(t)&&t.reset()}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>rn(e))}},mi(t,"ResetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;di(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),pi(t,r)})(),t})()),Io=Ri((()=>{let e,t,n=[Oi({description:"Focus an element (calls HTMLElement.focus())",syntax:["focus","focus <target>","focus on <target>"],examples:["focus","focus #search","focus on <input/>"],sideEffects:["focus"]}),Ci({name:"focus",category:"execution"})],r=[];return t=class{async parseInput(e,t,n){return{targets:await Pi(e.args,t,n,"focus",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)t.focus()}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>rn(e))}},mi(t,"FocusCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;di(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),pi(t,r)})(),t})()),Mo=Ri((()=>{let e,t,n=[Oi({description:"Remove focus from an element (calls HTMLElement.blur())",syntax:["blur","blur <target>","blur on <target>"],examples:["blur","blur #search","blur on <input/>"],sideEffects:["focus"]}),Ci({name:"blur",category:"execution"})],r=[];return t=class{async parseInput(e,t,n){return{targets:await Pi(e.args,t,n,"blur",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)t.blur()}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>rn(e))}},mi(t,"BlurCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;di(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),pi(t,r)})(),t})()),Do=Ri((()=>{let e,t,n=[Oi({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"]}),Ci({name:"set",category:"data"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("set command requires a target");const r=e.args[0],s=r?.name||r?.value,i=r?.scope,o=r?.type;if(o){const s=Ie(o);if(s)return{type:"node-write",node:r,value:await this.extractValue(e,t,n),writer:s}}const a=await this.resolveAttributeWriteTarget(r,e,t,n);if(a){const r=await this.extractValue(e,t,n);return{type:"attribute",elements:a.elements,name:a.name,value:r}}const c=await lo(r,t,n);if(c){const r=await this.extractValue(e,t,n);if(c.property.startsWith("*")){const e=c.property.substring(1);return{type:"style",element:c.element,property:e,value:r+""}}return{type:"property",element:c.element,property:c.property,value:r}}if("memberExpression"===r?.type||"propertyAccess"===r?.type){const s=await this.tryParseMemberExpression(r,e,t,n);if(s)return s}let l;if(l="identifier"!==r?.type&&"variable"!==r?.type||"string"!=typeof s?await t.evaluate(r,n):s,function(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;if(rn(e)||e instanceof Node)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}(l))return{type:"object-literal",properties:l,targets:await this.resolveTargets(e.modifiers.on,t,n)};if(ao(l)){const r=co(l,n);if(r){const s=await this.extractValue(e,t,n);return{type:"property",element:r.element,property:r.property,value:s}}return this.parseTheXofY(l,e,t,n)}if("string"==typeof l&&Fi(l)){const r=l.substring(1).trim(),s=await this.extractValue(e,t,n);return{type:"style",element:await this.resolveElement(e.modifiers.on,t,n),property:r,value:s+""}}if("string"==typeof l&&yi(l)){const r=l.substring(1).trim(),s=await this.extractValue(e,t,n);return{type:"attribute",elements:await this.resolveTargets(e.modifiers.on,t,n),name:r,value:s}}if("string"==typeof l){const r=l.match(/^(my|me|its?|your?)\s+(.+)$/i);if(r){const s=Mi(r[1],n),i=await this.extractValue(e,t,n);return{type:"property",element:s,property:r[2],value:i}}}if(rn(l))return{type:"property",element:l,property:"textContent",value:await this.extractValue(e,t,n)};if(Array.isArray(l)&&l.length>0&&rn(l[0])){const r=await this.extractValue(e,t,n);return{type:"property",element:l[0],property:"textContent",value:r}}if("string"!=typeof l)throw Error("set command target must be a string or object literal"+("memberExpression"===r?.type||"propertyAccess"===r?.type?` (a property chain evaluated to ${null===l?"null":typeof l} — check that all intermediate objects exist)`:""));return{type:"variable",name:l,value:await this.extractValue(e,t,n),scope:"element"===i||"global"===i?i:void 0}}async execute(e,t){switch(e.type){case"variable":return"element"===e.scope?tn(t,e.name,e.value):"global"===e.scope?cn(e.name,e.value,t,"global"):cn(e.name,e.value,t),"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":for(const t of e.elements)t.setAttribute(e.name,e.value+"");return Object.assign(t,{it:e.value}),{target:"@"+e.name,value:e.value,targetType:"attribute"};case"property":return so(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"style":return qi(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[n,r]of Object.entries(e.properties))so(t,n,r);return Object.assign(t,{it:e.properties}),{target:e.targets[0]||"unknown",value:e.properties,targetType:"property"};case"member-assignment":return e.container[e.property]=e.value,Object.assign(t,{it:e.value}),{target:e.property,value:e.value,targetType:"property"};case"node-write":return await e.writer(e.node,e.value,t),Object.assign(t,{it:e.value}),{target:e.node.name??"",value:e.value,targetType:"variable"};default:throw Error("Unknown input type: "+e.type)}}async resolveAttributeWriteTarget(e,t,n,r){const s=e;if("attributeAccess"===s?.type)return{elements:await this.resolveTargets(t.modifiers.on,n,r),name:s.attributeName};if("binaryExpression"===s?.type&&"of"===s.operator&&"attributeAccess"===s.left?.type){const e=await this.evaluateToElement(s.right,n,r);if(e)return{elements:[e],name:s.left.attributeName}}if("memberExpression"===s?.type&&"attributeAccess"===s.property?.type){const e=await this.evaluateToElement(s.object,n,r);if(e)return{elements:[e],name:s.property.attributeName}}return null}async evaluateToElement(e,t,n){const r=await t.evaluate(e,n),s=Array.isArray(r)?r[0]:r;return rn(s)?s:null}async tryParseMemberExpression(e,t,n,r){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=Mi(e,r),o=await this.extractValue(t,n,r);return{type:"property",element:s,property:i.name,value:o}}}const o=e.object,a=e.computed;if(o){const s=o;let c;if("memberExpression"===s.type&&!s.computed&&"style"===s.property?.name&&s.object){const e=await n.evaluate(s.object,r);c=(e&&"object"==typeof e&&"style"in e?e.style:void 0)??await n.evaluate(o,r)}else c=await n.evaluate(o,r);if(null!=c&&"object"==typeof c){const s=a?await n.evaluate(e.property,r)+"":i?.name||"";if(s)return{type:"member-assignment",container:c,property:s,value:await this.extractValue(t,n,r)}}}return null}async extractValue(e,t,n){if(e.modifiers.to)return t.evaluate(e.modifiers.to,n);const r=e.args.findIndex(e=>"identifier"===e.type&&"to"===e.name);if(r>=0&&e.args.length>r+1)return t.evaluate(e.args[r+1],n);if(e.args.length>=2)return t.evaluate(e.args[1],n);throw Error('set command requires a value (use "to" keyword)')}async resolveElement(e,t,n){return Li(e?await t.evaluate(e,n):void 0,n)}async resolveTargets(e,t,n){return ji(e?await t.evaluate(e,n):void 0,n)}async parseTheXofY(e,t,n,r){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=Li(o,r),c=await this.extractValue(t,n,r);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&&Array.isArray(t.elements)&&t.elements.every(rn)&&"value"in t;case"property":return"string"==typeof t.property&&rn(t.element)&&"value"in t;case"style":return"string"==typeof t.property&&""!==t.property&&rn(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}}},mi(t,"SetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;di(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),pi(t,r)})(),t})());function Po(e){return e&&"object"==typeof e&&e.type||"unknown"}let Fo=(()=>{let e,t,n=[Oi({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"]}),Ci({name:"increment",category:"data"})],r=[];return t=class{async parseInput(e,t,n){const r="decrement"===e.commandName?.toLowerCase()?"decrement":"increment",s=await async function(e,t,n,r){if(!e.args||0===e.args.length)throw Error(r+" command requires a target");const s=e.args[0];let i,o,a;const c=Po(s);if("identifier"===c)i=s.name,s.scope&&(o=s.scope);else if("literal"===c)i=s.value;else{const e=Ie(c);if(e){const r=await t.evaluate(s,n),o="number"==typeof r?r:null==r?0:Number(r)||0;i=o,a={node:s,writer:e,currentValue:o}}else{const e=await t.evaluate(s,n);i=Array.isArray(e)&&e.length>0?e[0]:e}}let l=1,u=o;for(let r=1;e.args.length>r;r++){const s=e.args[r];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,n);"number"==typeof e&&(l=e)}}const f=e.modifiers?.by;if(f){const e=f.value;if("literal"===Po(f)&&"number"==typeof e)l=e;else if("literal"!==Po(f)){const e=await t.evaluate(f,n);"number"==typeof e&&(l=e)}}return{target:i,amount:l,...u&&{scope:u},...a&&{customWrite:a}}}(e,t,n,r);return{...s,operation:r}}async execute(e,t){const{target:n,property:r,scope:s,amount:i=1,operation:o="increment",customWrite:a}=e;if(a){const e=isFinite(i)?i:1,n="increment"===o?a.currentValue+e:a.currentValue-e;return await a.writer(a.node,n,t),Object.assign(t,{it:n}),n}const c=function(e,t,n,r){if("number"==typeof e)return e;if(rn(e)){const n=e;return t?t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)?on(n.getAttribute(t)):on(n[t]):on(n.value||n.textContent)}return"string"==typeof e?"element"===n?on(an(e,r,"element")):"global"===n?on(an(e,r,"global")):e.includes(".")?function(e,t){const n=e.split("."),r=n[1],s=ln(n[0],t);return s?on(s[r]):0}(e,r):on("me"===e&&r.me?r.me.value||0:"it"===e?r.it||0:"you"===e&&r.you?r.you.value||0:an(e,r)):on(e)}(n,r,s,t);let l;if(isNaN(c))l=NaN;else{const e=isFinite(i)?i:1;l="increment"===o?c+e:c-e}return function(e,t,n,r,s){if(rn(e)){const n=e;return void(t?t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)?n.setAttribute(t,r+""):n[t]=r:"value"in n&&void 0!==n.value?n.value=r+"":n.textContent=r+"")}if("string"==typeof e){if("element"===n)return void cn(e,r,s,"element");if("global"===n)return void cn(e,r,s,"global");if(e.includes("."))return void function(e,t,n){const r=e.split("."),s=r[1],i=ln(r[0],n);i&&(i[s]=t)}(e,r,s);if("me"===e&&s.me)return void(s.me.value=r);if("it"===e)return void Object.assign(s,{it:r});if("you"===e&&s.you)return void(s.you.value=r);cn(e,r,s)}}(n,r,s,l,t),Object.assign(t,{it:l}),l}},mi(t,"NumericModifyCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;di(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),pi(t,r)})(),t})();const Bo=Ri(Fo),qo=Ri(Fo);function Vo(e){const t=e.tagName;return"INPUT"===t||"TEXTAREA"===t||"SELECT"===t}const _o=Ri((()=>{let e,t,n=[Oi({description:"Reset a variable to null or clear the value of a form field (<input>, <textarea>, <select>)",syntax:["clear <var>","clear :var","clear <target>"],examples:["clear :count","clear myVar","clear #search","clear <textarea/>"],sideEffects:["state-mutation","dom-mutation"]}),Ci({name:"clear",category:"data"})],r=[];return t=class{async parseInput(e,t,n){const r=e.args?.[0],s=r?.type,i=r?.name;if(r&&("variable"===s||"identifier"===s&&"string"==typeof i))try{const e=await t.evaluate(r,n);if(!rn(e)&&!Array.isArray(e))return{type:"variable",name:i}}catch{return{type:"variable",name:i}}return{type:"form-fields",targets:await Pi(e.args,t,n,"clear",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){if("variable"===e.type)return t.locals.set(e.name,null),void Object.assign(t,{it:null});for(const t of e.targets)Vo(t)&&("SELECT"===t.tagName?t.selectedIndex=-1:t.value="")}validate(e){if("object"!=typeof e||null===e)return!1;if("variable"===e.type)return"string"==typeof e.name;if("form-fields"===e.type){const t=e.targets;return Array.isArray(t)&&t.every(e=>rn(e))}return!1}},mi(t,"ClearCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;di(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),pi(t,r)})(),t})());function Ho(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 Uo=(()=>{let e,t,n=[Oi({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"]}),Ci({name:"trigger",category:"event"})],r=[];return t=class{async parseInput(e,t,n){const r="send"===e.commandName?.toLowerCase()?"send":"trigger",s=r;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)||"callExpression"===i(o)){a=o.name||o.callee?.name;const e=o.args||o.arguments;e?.length&&(c=await this.parseEventDetail(e,t,n))}else if("identifier"===i(o)||"keyword"===i(o))a=o.name;else{const e=await t.evaluate(o,n);a="string"==typeof e?e:e+""}const u=e.modifiers?.on||e.modifiers?.to;if(u)l=await this.resolveTargets([u],t,n,s);else{const r=e.args.findIndex((e,t)=>{if(0===t)return!1;const n=e.name||e.value;return"on"===n||"to"===n});if(-1!==r&&e.args.length-1>r){const i=e.args.slice(r+1),o=i.findIndex(e=>"with"===(e.name||e.value)),a=-1===o?i:i.slice(0,o);l=await this.resolveTargets(a,t,n,s)}else{if(!n.me)throw Error(s+": no target specified and context.me is null");l=[n.me]}}return{eventName:a,detail:c,targets:l,options:await this.parseEventOptions(e.args,t,n),mode:r}}async execute(e,t){const n=function(e,t,n={}){return new CustomEvent(e,{detail:void 0!==t?t:{},bubbles:void 0===n.bubbles||n.bubbles,cancelable:void 0===n.cancelable||n.cancelable,composed:void 0!==n.composed&&n.composed})}(e.eventName,e.detail,e.options);for(const t of e.targets)t.dispatchEvent(n);t.it=n}async resolveTargets(e,t,n,r){const s=[];for(const r of e){const e=await t.evaluate(r,n);if("window"!==e&&e!==window)if("document"!==e&&e!==document)if("me"===e&&n.me)s.push(n.me);else if("you"===e&&n.you)s.push(n.you);else if("it"===e&&n.it)s.push(n.it);else if(rn(e))s.push(e);else if(e instanceof NodeList)s.push(...Array.from(e).filter(rn));else if(Array.isArray(e))s.push(...e.filter(rn));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(rn));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(r+": no valid targets");return s}async parseEventDetail(e,t,n){if(!e?.length)return;if(1===e.length){const r=e[0];if("objectLiteral"!==r?.type)return await t.evaluate(r,n)}const r={};for(const s of e){const e=await t.evaluate(s,n);if("object"!=typeof e||null===e||Array.isArray(e)){if("string"==typeof e&&e.includes(":")){const[t,n]=e.split(":",2);r[t.trim()]=Ho(n.trim())}}else Object.assign(r,e)}return Object.keys(r).length?r:void 0}async parseEventOptions(e,t,n){const r={bubbles:!0,cancelable:!0,composed:!1},s=e.findIndex(e=>"with"===(e.name||e.value));if(-1===s)return r;for(const i of e.slice(s+1)){const e=await t.evaluate(i,n);if("string"==typeof e){const t=e.toLowerCase();"bubbles"===t?r.bubbles=!0:"nobubbles"===t?r.bubbles=!1:"cancelable"===t?r.cancelable=!0:"nocancelable"===t?r.cancelable=!1:"composed"===t&&(r.composed=!0)}}return r}},mi(t,"EventDispatchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;di(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),pi(t,r)})(),t})();const zo=Ri(Uo),Wo=Ri(Uo);function Jo(e,t,n,r){return e?new Promise(n=>{const s=()=>{i({event:null,timedOut:!1,cancelled:!0})},i=function(n,i){let a=!1;return n=>{a||(a=!0,e.removeEventListener(t,o),r&&r.removeEventListener("abort",s),i(n))}}(0,n),o=e=>{i({event:e,timedOut:!1,cancelled:!1})};r?.aborted?n({event:null,timedOut:!1,cancelled:!0}):(e.addEventListener(t,o),r&&r.addEventListener("abort",s))}):Promise.reject(Error("waitForEvent: no target provided"))}function Zo(e){return new Promise(t=>setTimeout(t,e))}const Ko=Ri((()=>{let e,t,n=[Oi({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"]}),Ci({name:"wait",category:"async"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("wait command requires an argument");if(e.modifiers.or)return this.parseRaceCondition(e,t,n);if(e.modifiers.for)return this.parseEventWait(e.modifiers.for,e.modifiers.from,t,n);const r=e.args[0];return"arrayLiteral"===r.type&&r.elements?this.parseEventArrayWait(r.elements,e.args[1],t,n):this.parseTimeWait(e.args[0],t,n)}async execute(e,t){const n=Date.now();if("time"===e.type)return await Zo(e.milliseconds),{type:"time",result:e.milliseconds,duration:Date.now()-n};if("event"===e.type){const r=e.target??t.me??document,s=(await Jo(r,e.eventName)).event;if(Object.assign(t,{it:s}),e.destructure)for(const n of e.destructure)n in s&&t.locals.set(n,s[n]);return{type:"event",result:s,duration:Date.now()-n}}const{result:r,winningCondition:s}=await this.executeRace(e.conditions,t);if(Object.assign(t,{it:r}),r instanceof Event&&"event"===s?.type&&s.destructure)for(const e of s.destructure)e in r&&t.locals.set(e,r[e]);return{type:r instanceof Event?"event":"time",result:r,duration:Date.now()-n}}async parseTimeWait(e,t,n){return{type:"time",milliseconds:Xi(await t.evaluate(e,n))}}async parseEventWait(e,t,n,r){const s=await n.evaluate(e,r);if("string"!=typeof s)throw Error("wait for: event name must be a string");const i=s.match(/^(\w+)\(([^)]+)\)$/),o=i?i[1]:s,a=i?i[2].split(",").map(e=>e.trim()):void 0;let c;if(t){const e=await n.evaluate(t,r);if(!e||"object"!=typeof e||!("addEventListener"in e))throw Error("wait for from: target must be an EventTarget");c=e}else c=r.me??void 0;return{type:"event",eventName:o,target:c,destructure:a}}async parseEventArrayWait(e,t,n,r){const s=[];for(const t of e){const e=t;if("objectLiteral"===e.type&&e.properties){let t="",n=[];for(const r of e.properties){const e=r.key?.name||r.key?.value;"name"===e&&r.value?t=r.value.value||"":"args"===e&&r.value?.elements&&(n=r.value.elements.map(e=>e.value||e.name||""))}t&&s.push({name:t,params:n})}}let i;if(t){const e=await n.evaluate(t,r);e&&"object"==typeof e&&"addEventListener"in e&&(i=e)}return i||(i=r.me??void 0),1===s.length?{type:"event",eventName:s[0].name,target:i,destructure:s[0].params.length>0?s[0].params:void 0}:{type:"race",conditions:s.map(e=>({type:"event",eventName:e.name,target:i,destructure:e.params.length>0?e.params:void 0}))}}async parseRaceCondition(e,t,n){const r=[];e.modifiers.for?r.push(await this.parseEventWait(e.modifiers.for,e.modifiers.from,t,n)):e.args[0]&&r.push(await this.parseTimeWait(e.args[0],t,n));const s=await t.evaluate(e.modifiers.or,n),i=Array.isArray(s)?s:[s];for(const e of i)try{r.push({type:"time",milliseconds:Xi(e)})}catch{if("string"==typeof e){const t=e.match(/^(\w+)\(([^)]+)\)$/);r.push(t?{type:"event",eventName:t[1],target:n.me??void 0,destructure:t[2].split(",").map(e=>e.trim())}:{type:"event",eventName:e,target:n.me??void 0})}}if(2>r.length)throw Error("wait: race requires at least 2 conditions");return{type:"race",conditions:r}}async executeRace(e,t){const n=new AbortController,r=n.signal,s=e.map(e=>"time"===e.type?Zo(e.milliseconds).then(()=>({result:e.milliseconds,winningCondition:e})):Jo(e.target??t.me??document,e.eventName,0,r).then(t=>({result:t.event,winningCondition:e})));try{return await Promise.race(s)}finally{n.abort()}}},mi(t,"WaitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;di(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),pi(t,r)})(),t})()),Go=new Map;let Xo=[/^4\d{2}$/,/^5\d{2}$/],Yo=(()=>{let e,t,n=[Oi({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"]}),Ci({name:"fetch",category:"async"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("fetch requires a URL");const r=await this.parseURL(e.args[0],t,n),s=this.parseResponseType(e.modifiers.as);return{url:r,responseType:s,options:await this.parseRequestOptions(e.modifiers.with,t,n),throwOnError:!e.modifiers.doNotThrow&&"response"!==s}}async execute(e,t){const n=Date.now(),{url:r,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},l=Go.get(s);if(l?.accept){const e=new Headers(c.headers);e.has("Accept")||e.set("Accept",l.accept),c.headers=e}if(t.me){const e={...c,sender:t.me,headers:c.headers||{}};this.dispatchEvent(t.me,"fetch:beforeRequest",e),c.headers=e.headers}let u;i.timeout&&(u=setTimeout(()=>o.abort(),i.timeout));try{let i=await fetch(r,c);if(t.me){const e={response:i};this.dispatchEvent(t.me,"fetch:afterResponse",e),i=e.response}if(e.throwOnError&&function(e){const t=e+"";return Xo.some(e=>e.test(t))}(i.status)){const e=Error(`Fetch failed for ${r}: HTTP ${i.status} ${i.statusText}`.trim());throw e.response=i,e.isFetchStatusError=!0,e}const o=await this.handleResponse(i,s,t);t.me&&this.dispatchEvent(t.me,"fetch:afterRequest",{result:o});const a={status:i.status,statusText:i.statusText,headers:i.headers,data:o,url:i.url,duration:Date.now()-n};return Object.assign(t,{it:o}),a}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 "+r);if(e instanceof Error&&!0===e.isFetchStatusError)throw e;throw Error(`Fetch failed for ${r}: ${e instanceof Error?e.message:e+""}`)}finally{u&&clearTimeout(u),t.me&&a&&t.me.removeEventListener("fetch:abort",a)}}async parseURL(e,t,n){const r=await t.evaluate(e,n);if("string"!=typeof r||!r)throw Error("fetch: URL must be a non-empty string");return r}parseResponseType(e){if(!e)return"text";if(("identifier"===e.type||"expression"===e.type)&&e.name){const t=e.name.toLowerCase();if("object"===t)return"json";if(["text","json","html","response","blob","arraybuffer"].includes(t))return"arraybuffer"===t?"arrayBuffer":t;if(Go.has(t))return t;throw Error(`fetch: invalid response type "${t}"`)}return"text"}async parseRequestOptions(e,t,n){if(!e)return{};const r=await t.evaluate(e,n);if("object"!=typeof r||null===r)throw Error('fetch: "with" options must be an object');const s={};return"method"in r&&(s.method=(r.method+"").toUpperCase()),"headers"in r&&(s.headers=this.parseHeaders(r.headers)),"body"in r&&(s.body=this.parseBody(r.body)),"credentials"in r&&(s.credentials=r.credentials),"mode"in r&&(s.mode=r.mode),"cache"in r&&(s.cache=r.cache),s}parseHeaders(e){if(e instanceof Headers)return e;const t=new Headers;if("object"==typeof e&&null!==e)for(const[n,r]of Object.entries(e))t.set(n,r+"");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,n){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();case"text":return e.text();default:{const r=Go.get(t);return r?r.handler(e,n):e.text()}}}parseHTML(e){const t=(new DOMParser).parseFromString(e,"text/html"),n=document.createDocumentFragment();return Array.from(t.body.childNodes).forEach(e=>n.appendChild(e.cloneNode(!0))),1===n.childNodes.length&&rn(n.firstChild)?n.firstChild:n}dispatchEvent(e,t,n){e.dispatchEvent(new CustomEvent(t,{detail:n,bubbles:!0,cancelable:!0}))}},mi(t,"FetchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;di(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),pi(t,r)})(),t})();const Qo=Ri(Yo),ea=Ri((()=>{let e,t,n=[Oi({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"]}),Ci({name:"go",category:"navigation"})],r=[];return t=class{async parseInput(e,t,n){return e.args&&0!==e.args.length?{args:await Promise.all(e.args.map(e=>t.evaluate(e,n)))}:{args:[]}}async execute(e,t){const{args:n}=e;if(0===n.length)throw Error("Go command requires arguments");if("string"==typeof n[0]&&"back"===n[0].toLowerCase())return await this.goBack(),{result:"back",type:"back"};if(this.isUrlNavigation(n))return{result:await this.navigateToUrl(n,t),type:"url"};const r=this.findBareUrl(n);return null!==r?{result:await this.navigateToBareUrl(r,n),type:"url"}:{result:await this.scrollToElement(n,t),type:"scroll"}}isUrlNavigation(e){return-1!==e.findIndex(e=>"url"===e)}isBareUrl(e){return!!e.startsWith("/")||/^[a-z][a-z0-9+.-]*:/i.test(e)}findBareUrl(e){for(const t of e)if("to"!==t&&"the"!==t)return"string"==typeof t&&this.isBareUrl(t)?t:null;return null}async navigateToBareUrl(e,t){if(t.includes("new")&&t.includes("window")){if("undefined"!=typeof window&&window.open){const t=window.open(e,"_blank");t?.focus&&t.focus()}}else e.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=e):"undefined"!=typeof window&&(window.location.assign?.(e)??(window.location.href=e));return e}async goBack(){if("undefined"==typeof window||!window.history)throw Error("Browser history API not available");window.history.back()}async navigateToUrl(e,t){const n=e.findIndex(e=>"url"===e),r=e[n+1];if(!r)throw Error('URL is required after "url" keyword');const s="string"==typeof r?r:r+"",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 n=this.parseScrollPosition(e),r=this.parseScrollTarget(e),s=this.parseScrollOffset(e),i=!e.includes("instantly"),o=this.resolveScrollTarget(r,t);if(!o)throw Error("Target element not found: "+r);if("undefined"!=typeof window){const e=i?"smooth":"instant",t=this.mapVerticalPosition(n.vertical),r=this.mapHorizontalPosition(n.horizontal);if(0!==s){o.scrollIntoView?.({behavior:e,block:t,inline:r});const{x:i,y:a}=this.calculateScrollPosition(o,n,s);window.scrollTo?.({left:i,top:a,behavior:e})}else o.scrollIntoView?.({behavior:e,block:t,inline:r})}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"},n=["top","middle","bottom"],r=["left","center","right"];let s=!1,i=!1;for(const o of e)"string"==typeof o&&(n.includes(o)?(t.vertical=o,s=!0):r.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 n=e[t+1];return"the"===n&&e.length>t+2&&(n=e[t+2]),n}for(const t of e)if("object"==typeof t&&t&&t.nodeType)return t;const n=["top","middle","bottom","left","center","right","of","the","to","smoothly","instantly"];for(const t of e)if("string"==typeof t&&!n.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 n=e[t];if("string"==typeof n){const e=n.match(/^([+-]?\d+)(px)?$/);if(e)return parseInt(e[1],10)}if(("+"===n||"-"===n)&&e.length>t+1){const r=e[t+1],s="number"==typeof r?r:parseInt((r+"").replace("px",""),10);if(!isNaN(s))return"-"===n?-s:s}}return 0}resolveScrollTarget(e,t){if("object"==typeof e&&e&&e.nodeType)return e;const n="string"==typeof e?e:e+"";if("body"===n&&"undefined"!=typeof document)return document.body;if("html"===n&&"undefined"!=typeof document)return document.documentElement;if("me"===n&&rn(t.me))return t.me;if("it"===n&&rn(t.it))return t.it;if("you"===n&&rn(t.you))return t.you;const r=an(n,t);if(rn(r))return r;if("undefined"!=typeof document)try{const e=document.querySelector(n);if(e)return e}catch{try{const e=document.getElementsByTagName(n);if(e.length>0)return e[0]}catch{}}return null}calculateScrollPosition(e,t,n){if("undefined"==typeof window||!e.getBoundingClientRect)return{x:0,y:0};const r=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=r.left+s;break;case"center":c=r.left+s+r.width/2-o/2;break;case"right":c=r.right+s-o}switch(t.vertical){case"top":l=r.top+i+n;break;case"middle":l=r.top+i+r.height/2-a/2+n;break;case"bottom":l=r.bottom+i-a+n}return{x:Math.max(0,c),y:Math.max(0,l)}}},mi(t,"GoCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;di(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),pi(t,r)})(),t})()),ta=Ri((()=>{let e,t,n=[Oi({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"]}),Ci({name:"log",category:"utility"})],r=[];return t=class{async parseInput(e,t,n){return e.args&&0!==e.args.length?{values:await Promise.all(e.args.map(e=>t.evaluate(e,n)))}:{values:[]}}async execute(e,t){const n="undefined"!=typeof window?window.console:console;0===e.values.length?n.log():n.log(...e.values)}validate(e){return"object"==typeof e&&null!==e&&Array.isArray(e.values)}},mi(t,"LogCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;di(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),pi(t,r)})(),t})()),na=Ri((()=>{let e,t,n=[Oi({description:"Drop into the debugger (emits a debugger; statement)",syntax:["breakpoint"],examples:["breakpoint","on click breakpoint"],sideEffects:["debugging"]}),Ci({name:"breakpoint",category:"utility"})],r=[];return t=class{async parseInput(e,t,n){return{}}async execute(e,t){}validate(e){return"object"==typeof e&&null!==e}},mi(t,"BreakpointCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;di(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),pi(t,r)})(),t})()),ra=function(e,t){const n=new Hr(null);for(const t of e)n.register(t);return new Yr({registry:n,expressionRegistry:t.expressionRegistry,enableAsyncCommands:t.enableAsyncCommands??!0,commandTimeout:t.commandTimeout??1e4,enableErrorReporting:t.enableErrorReporting??!0,enableResultPattern:t.enableResultPattern??!0})}([Wi(),Ki(),po(),go(),bo(),wo(),So(),Ao(),To(),Oo(),$o(),jo(),Io(),Mo(),Do(),Bo(),qo(),_o(),Wo(),zo(),Ko(),Qo(),ea(),ta(),na()],{expressionRegistry:fi()}),sa={parse:e=>Ut(e),execute:async(e,t)=>{const n=function(e){if(!e)return nn();if(e.locals instanceof Map&&e.globals instanceof Map&&e.flags)return e;const t=nn(e.me instanceof Element?e.me:null);return void 0!==e.it&&(t.it=e.it),void 0!==e.you&&(t.you=e.you),void 0!==e.result&&(t.result=e.result),void 0!==e.event&&Object.assign(t,{event:e.event}),t}(t),r=Ut(e);if(!r.success||!r.node)throw Error(r.error?.message||"Parse failed");return await ra.execute(r.node,n)}},ia=function(e){return new hi(e)}(sa),oa={runtime:sa,parse:e=>sa.parse(e),execute:async(e,t)=>sa.execute(e,t),createContext:nn,attributeProcessor:ia,version:"1.1.0-standard-v2-tree-shakeable",commands:["add","remove","toggle","show","hide","put","make","empty","open","close","select","reset","focus","blur","set","increment","decrement","clear","send","trigger","wait","fetch","go","log","breakpoint"],eval:async(e,t)=>sa.execute(e,t),init:()=>{ia.init()}};"undefined"!=typeof window&&(window.hyperfixi=oa,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{ia.init()}):ia.init());class aa{constructor(){this.name="addition",this.category="Special",this.syntax="left + right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=cs(e,"left operand");return{success:!0,value:us(r+cs(n,"right operand"),"addition"),type:"number"}}catch(e){return{success:!1,errors:[ms("runtime-error","Addition failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){const t=function(e){if(null==e)return ps([ms("missing-argument","Input is null or undefined")],["Provide an object with left and right operands"]);if("object"!=typeof e)return ps([ms("type-mismatch","Expected object, got "+typeof e)],["Provide an object with left and right operands"]);const t=e;if(!("left"in t)||!("right"in t)){const e=[];return"left"in t||e.push("left"),"right"in t||e.push("right"),ps([ms("missing-argument",`Missing ${e.join(" and ")} operand${e.length>1?"s":""}`)],["Provide { left: value, right: value }"])}return{isValid:!0,errors:[],suggestions:[]}}(e);if(!t.isValid)return t;const{left:n,right:r}=e;return fs(n)?fs(r)?{isValid:!0,errors:[],suggestions:[]}:{isValid:!1,errors:[ms("type-mismatch","Right operand cannot be converted to number: "+r)],suggestions:["Provide a numeric value for right operand"]}:{isValid:!1,errors:[ms("type-mismatch","Left operand cannot be converted to number: "+n)],suggestions:["Provide a numeric value for left operand"]}}}const ca={addition:new aa,subtraction:new class{constructor(){this.name="subtraction",this.category="Special",this.syntax="left - right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=cs(e,"left operand");return{success:!0,value:us(r-cs(n,"right operand"),"subtraction"),type:"number"}}catch(e){return{success:!1,errors:[ms("runtime-error","Subtraction failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new aa).validate(e)}},multiplication:new class{constructor(){this.name="multiplication",this.category="Special",this.syntax="left * right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=cs(e,"left operand");return{success:!0,value:us(r*cs(n,"right operand"),"multiplication"),type:"number"}}catch(e){return{success:!1,errors:[ms("runtime-error","Multiplication failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new aa).validate(e)}},division:new class{constructor(){this.name="division",this.category="Special",this.syntax="left / right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=function(e,t,n=!0){if(0===t){if(n)return 0===e?NaN:e>0?1/0:-1/0;throw Error("Division by zero")}return e/t}(cs(e,"left operand"),cs(n,"right operand"),!0);return{success:!0,value:r,type:"number"}}catch(e){return{success:!1,errors:[ms("runtime-error","Division failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new aa).validate(e)}},modulo:new class{constructor(){this.name="modulo",this.category="Special",this.syntax="left mod right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=function(e,t){if(0===t)throw Error("Modulo by zero");return e%t}(cs(e,"left operand"),cs(n,"right operand"));return{success:!0,value:r,type:"number"}}catch(e){return{success:!1,errors:[ms("runtime-error","Modulo failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric and divisor is not zero"]}}}validate(e){return(new aa).validate(e)}},power:new class{constructor(){this.name="power",this.category="Special",this.syntax="left ** right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=cs(e,"left operand"),s=cs(n,"right operand");return{success:!0,value:us(Math.pow(r,s),"power"),type:"number"}}catch(e){return{success:!1,errors:[ms("runtime-error","Power failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new aa).validate(e)}}};var la=Object.freeze({__proto__:null,conversion:rr,conversionExpressions:rr,createCommonRegistry:fi,createCoreRegistry:function(){return Qr(ns,Js,Ys)},createExpressionRegistry:Qr,createFullExpressionRegistry:function(){return Qr(ns,Js,rr,ui,ar,Ys,ca)},createFullRegistry:function(){return Qr(ns,Js,Ys,rr,ui,ar)},logical:Js,logicalExpressions:Js,positional:ui,positionalExpressions:ui,properties:ar,propertiesExpressions:ar,references:ns,referencesExpressions:ns,special:Ys,specialExpressions:Ys});return oa}();
2
2
  //# sourceMappingURL=hyperfixi-standard.js.map