@hyperfixi/core 2.0.0 → 2.2.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 (76) hide show
  1. package/dist/api/hyperscript-api.d.ts +8 -1
  2. package/dist/ast-utils/index.d.ts +1 -1
  3. package/dist/ast-utils/index.js +11 -1
  4. package/dist/ast-utils/index.mjs +11 -1
  5. package/dist/ast-utils/interchange/index.d.ts +1 -1
  6. package/dist/ast-utils/interchange/lsp.d.ts +4 -1
  7. package/dist/behaviors/index.js +13 -5
  8. package/dist/behaviors/index.mjs +13 -5
  9. package/dist/bundle-generator/index.js +9 -0
  10. package/dist/bundle-generator/index.mjs +9 -0
  11. package/dist/chunks/{bridge-I6ceoWxV.js → bridge-D2DBo02Z.js} +2 -2
  12. package/dist/chunks/browser-modular-BA3JFmkq.js +2 -0
  13. package/dist/chunks/feature-eventsource-B5F2-H1r.js +2 -0
  14. package/dist/chunks/feature-sockets-ClOH7vk7.js +2 -0
  15. package/dist/chunks/feature-webworker-3bAp0ac9.js +2 -0
  16. package/dist/chunks/index-C6Fn0jGB.js +2 -0
  17. package/dist/commands/dom/toggle.d.ts +2 -0
  18. package/dist/commands/index.js +62 -6
  19. package/dist/commands/index.mjs +62 -6
  20. package/dist/debug/debug-controller.d.ts +62 -0
  21. package/dist/debug/index.d.ts +5 -0
  22. package/dist/expressions/index.js +16 -79
  23. package/dist/expressions/index.mjs +16 -79
  24. package/dist/hyperfixi-classic-i18n.js +1 -1
  25. package/dist/hyperfixi-hx.js +1 -1
  26. package/dist/hyperfixi-hybrid-complete.js +1 -1
  27. package/dist/hyperfixi-minimal.js +1 -1
  28. package/dist/hyperfixi-multilingual.js +1 -1
  29. package/dist/hyperfixi-standard.js +1 -1
  30. package/dist/hyperfixi.js +1 -1
  31. package/dist/hyperfixi.mjs +1 -1
  32. package/dist/i18n/error-catalog.d.ts +12 -0
  33. package/dist/index.d.ts +2 -0
  34. package/dist/index.js +35334 -24306
  35. package/dist/index.min.js +1 -1
  36. package/dist/index.mjs +35333 -24307
  37. package/dist/lokascript-browser-classic-i18n.js +1 -1
  38. package/dist/lokascript-browser-minimal.js +1 -1
  39. package/dist/lokascript-browser-standard.js +1 -1
  40. package/dist/lokascript-browser.js +1 -1
  41. package/dist/lokascript-hybrid-complete.js +1 -1
  42. package/dist/lokascript-hybrid-hx.js +1 -1
  43. package/dist/lokascript-multilingual.js +1 -1
  44. package/dist/lse/index.d.ts +15 -0
  45. package/dist/lse/index.js +84 -0
  46. package/dist/lse/index.mjs +71 -0
  47. package/dist/metadata.d.ts +4 -4
  48. package/dist/metadata.js +4 -4
  49. package/dist/metadata.mjs +4 -4
  50. package/dist/parser/full-parser.js +608 -271
  51. package/dist/parser/full-parser.mjs +608 -271
  52. package/dist/parser/helpers/ast-helpers.d.ts +1 -0
  53. package/dist/parser/hybrid/index.js +35 -2
  54. package/dist/parser/hybrid/index.mjs +35 -2
  55. package/dist/parser/hybrid/parser-core.d.ts +1 -0
  56. package/dist/parser/hybrid/parser-core.js +35 -2
  57. package/dist/parser/hybrid/parser-core.mjs +35 -2
  58. package/dist/parser/hybrid/tokenizer.js +5 -0
  59. package/dist/parser/hybrid/tokenizer.mjs +5 -0
  60. package/dist/parser/hybrid-parser.js +35 -2
  61. package/dist/parser/hybrid-parser.mjs +35 -2
  62. package/dist/parser/parser-types.d.ts +22 -7
  63. package/dist/parser/parser.d.ts +7 -0
  64. package/dist/parser/pratt-parser.d.ts +42 -0
  65. package/dist/parser/token-consumer.d.ts +1 -2
  66. package/dist/parser/tokenizer.d.ts +0 -33
  67. package/dist/registry/index.js +16 -79
  68. package/dist/registry/index.mjs +16 -79
  69. package/dist/runtime/runtime-base.d.ts +4 -0
  70. package/dist/types/base-types.d.ts +11 -0
  71. package/dist/types/core.d.ts +1 -0
  72. package/package.json +15 -6
  73. package/dist/chunks/browser-modular-Dv6PAV3c.js +0 -2
  74. package/dist/chunks/feature-eventsource-DWb514fy.js +0 -2
  75. package/dist/chunks/feature-sockets-3PFuvCVY.js +0 -2
  76. package/dist/chunks/feature-webworker-DTm_eh-E.js +0 -2
@@ -1 +1 @@
1
- var hyperfixi=function(){"use strict";const t="then",e="else",r="end",n="and",s="for",i="while",o="until",a="forever",c="times",l="index",u="in",h="to",f="from",d="with",p="of",m="on",y="event",v="behavior",g="global",b="the",E="start",w=new Set(["add","append","async","beep","break","call","continue","copy","decrement","default","exit","fetch","for","get","go","halt","hide","if","increment","install","js","log","make","measure","morph","pick","process","push","put","remove","render","repeat","replace","return","send","set","settle","show","swap","take","tell","throw","toggle","transition","trigger","unless","wait"]),x=new Set(["put","trigger","send","remove","take","toggle","set","show","hide","add","halt","measure","js","tell","swap","morph","push","replace","process"]),k=(new Set(["if","unless","repeat","wait","for","while"]),"at start of"),A="at end of",S=["into","before","after","at",k,A,"at the start of","at the end of"],C=new Set(["if","else","unless","for","while","until","end","and","or","not","in","to","from","into","with","without","as","matches","contains","then","on","when","every","init","def","behavior","the","of","first","last"]),N=new Set(["hsl","hsla","rgb","rgba","hwb","lab","lch","oklch","oklab","color","color-mix","calc","min","max","clamp","var","url","linear-gradient","radial-gradient","conic-gradient","repeating-linear-gradient","repeating-radial-gradient","repeating-conic-gradient"]),T=new Set(["me","it","you","result","my","its","your"]),O=new Set(["and","or","not","no"]),L=new Set(["==","!=","===","!==","<",">","<=",">=","is","is not","is a","is an","is not a","is not an","contains","has","have","does not contain","include","includes","does not include","match","matches","exists","does not exist","is empty","is not empty","is in","is not in","equals","in","is equal to","is really equal to","is not equal to","is not really equal to","is greater than","is less than","is greater than or equal to","is less than or equal to","really equals"]),$=new Set(["click","dblclick","mousedown","mouseup","mouseover","mouseout","mousemove","mouseenter","mouseleave","focus","blur","change","input","submit","reset","select","load","unload","resize","scroll","keydown","keyup","keypress","touchstart","touchend","touchmove","touchcancel","drag","drop","dragover","dragenter","dragleave","cut","copy","paste","toggle"]),R=new Set(["on","init","behavior","def","if","else","unless","for","while","until","end","and","or","not","in","to","from","into","with","as","then","when","where","after","before","by","at","between","async","no","start","of","the","new","global","local","equal","equals","greater","less","than","really","catch","finally","throw","return"]);var I,j;function D(t){switch(t){case j.KEYWORD:case j.COMMAND:case j.EXPRESSION:case j.CONTEXT_VAR:case j.GLOBAL_VAR:case j.EVENT:case j.IDENTIFIER:return I.IDENTIFIER;case j.STRING:return I.STRING;case j.NUMBER:return I.NUMBER;case j.BOOLEAN:return I.IDENTIFIER;case j.TEMPLATE_LITERAL:return I.TEMPLATE;case j.CSS_SELECTOR:case j.ID_SELECTOR:case j.CLASS_SELECTOR:case j.QUERY_REFERENCE:return I.SELECTOR;case j.OPERATOR:case j.LOGICAL_OPERATOR:case j.COMPARISON_OPERATOR:return I.OPERATOR;case j.TIME_EXPRESSION:return I.TIME;case j.COMMENT:return I.COMMENT;case j.SYMBOL:return I.SYMBOL;default:return I.UNKNOWN}}!function(t){t.IDENTIFIER="identifier",t.STRING="string",t.NUMBER="number",t.SELECTOR="selector",t.OPERATOR="operator",t.TIME="time",t.TEMPLATE="template",t.COMMENT="comment",t.SYMBOL="symbol",t.UNKNOWN="unknown"}(I||(I={})),function(t){t.KEYWORD="keyword",t.COMMAND="command",t.EXPRESSION="expression",t.STRING="string",t.NUMBER="number",t.BOOLEAN="boolean",t.TEMPLATE_LITERAL="template_literal",t.CSS_SELECTOR="css_selector",t.ID_SELECTOR="id_selector",t.CLASS_SELECTOR="class_selector",t.QUERY_REFERENCE="query_reference",t.CONTEXT_VAR="context_var",t.GLOBAL_VAR="global_var",t.EVENT="event",t.OPERATOR="operator",t.LOGICAL_OPERATOR="logical_operator",t.COMPARISON_OPERATOR="comparison_operator",t.TIME_EXPRESSION="time_expression",t.OBJECT_LITERAL="object_literal",t.ARRAY_LITERAL="array_literal",t.SYMBOL="symbol",t.COMMENT="comment",t.IDENTIFIER="identifier",t.UNKNOWN="unknown"}(j||(j={}));const M=R,P=new Set(["+","-","*","/","mod"]),V=new Set(["ms","s","seconds","minutes","hours","days"]);function B(t,e=1){const r=t.position+e;return t.input.length>r?t.input[r]:""}function _(t){const e=t.input[t.position];return t.position++,"\n"===e?(t.line++,t.column=1):"\r"===e?("\n"===(t.input.length>t.position?t.input[t.position]:"")&&t.position++,t.line++,t.column=1):t.column++,e}function F(t){const e=t.input,r=e.length;for(;r>t.position;){const r=e[t.position];if(" "!==r&&"\t"!==r&&"\r"!==r&&"\n"!==r)break;_(t)}}function q(t,e,r,n,s){const i=n??t.position-r.length,o=t.position;let a=t.column-r.length;if(void 0!==n){a=1;let e=-1;for(let r=0;n>r;r++)"\n"!==t.input[r]&&"\r"!==t.input[r]||(e=r);a=n-e}const c={kind:D(e),value:r,start:i,end:o,line:H(t,i),column:a};t.tokens.push(c)}function H(t,e){let r=1;for(let n=0;e>n&&t.input.length>n;n++){const e=t.input[n];"\n"===e?r++:"\r"===e&&(r++,t.input.length>n+1&&"\n"===t.input[n+1]&&n++)}return r}function U(t){const e=t.position;let r="";for(_(t),_(t);t.input.length>t.position&&"\n"!==t.input[t.position];)r+=_(t);q(t,j.COMMENT,"--"+r,e)}function W(t){const e=t.position,r=_(t);let n=r;for(;t.input.length>t.position;){const e=_(t);if(n+=e,e===r)break;"\\"===e&&t.input.length>t.position&&(n+=_(t))}q(t,j.STRING,n,e)}function z(t){const e=t.position;_(t);let r="";for(;t.input.length>t.position;){const e=t.input[t.position];if("`"===e){_(t);break}if("\\"===e){if(_(t),t.input.length>t.position){const e=_(t);switch(e){case"n":r+="\n";break;case"t":r+="\t";break;case"r":r+="\r";break;case"\\":r+="\\";break;case"`":r+="`";break;default:r+=e}}}else r+=_(t)}if(t.position>=t.input.length&&!t.input.endsWith("`"))throw Error(`Unterminated template literal at line ${t.line}, column ${t.column-r.length}`);q(t,j.TEMPLATE_LITERAL,r,e)}function J(t){const e=t.position,r=_(t);let n=r;for(;t.input.length>t.position;){const e=t.input[t.position];if(!et(e)&&"-"!==e&&"_"!==e&&":"!==e)break;n+=_(t)}q(t,"#"===r?j.ID_SELECTOR:j.CLASS_SELECTOR,n,e)}function Z(t){const e=t.position;let r="";for(r+=_(t);t.input.length-1>t.position;){const e=t.input[t.position],n=t.input[t.position+1];if(r+=_(t),"/"===e&&">"===n){r+=_(t);break}}q(t,j.QUERY_REFERENCE,r,e)}function G(t){const e=t.position;let r=_(t);for(;t.input.length>t.position;){const e=t.input[t.position];if(!et(e)&&"_"!==e&&"-"!==e)break;r+=_(t)}q(t,j.SYMBOL,r,e)}function X(t){const e=t.position;let r="";const n=t.input[t.position];if(("'"===n||"'"===n)&&"s"===B(t,1))return r="'s",_(t),_(t),void q(t,j.OPERATOR,r,e);const s=t.input.substring(t.position,t.position+2),i=t.input.substring(t.position,t.position+3);["===","!=="].includes(i)?(r=i,_(t),_(t),_(t)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(s)?(r=s,_(t),_(t)):r=_(t);let o=j.OPERATOR;L.has(r)?o=j.COMPARISON_OPERATOR:["&&","||"].includes(r)?o=j.LOGICAL_OPERATOR:P.has(r)&&(o=j.OPERATOR),q(t,o,r,e)}function Y(t){const e=t.position,r=t.input,n=r.length;let s="";for(;n>t.position;){const e=r[t.position];if("0">e||e>"9")break;s+=_(t)}if(n>t.position&&"."===r[t.position]&&(t.position+1>=n||"."!==r[t.position+1]))for(s+=_(t);n>t.position;){const e=r[t.position];if("0">e||e>"9")break;s+=_(t)}if(n>t.position){const e=r[t.position];if("e"===e||"E"===e){const e=n>t.position+1?r[t.position+1]:"",i=n>t.position+2?r[t.position+2]:"";if(e>="0"&&"9">=e||!("+"!==e&&"-"!==e||"0">i||i>"9"))for(s+=_(t),"+"!==r[t.position]&&"-"!==r[t.position]||(s+=_(t));n>t.position;){const e=r[t.position];if("0">e||e>"9")break;s+=_(t)}}}const i=t.position;let o="";for(;n>t.position;){const e=r[t.position];if(("a">e||e>"z")&&("A">e||e>"Z"))break;o+=_(t)}V.has(o)?q(t,j.TIME_EXPRESSION,s+o,e):(t.position=i,q(t,j.NUMBER,s,e))}function K(t){const e=t.position,r=t.input,n=r.length;let s="";for(;n>t.position;){const e=r[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;s+=_(t)}const i=function(t,e,r){const n=e.toLowerCase(),s=t.position;if("'s"===e||"'s"===e)return 0;const i=t.tokens[t.tokens.length-1];if(i&&("identifier"===i.kind||"id_selector"===i.kind||"class_selector"===i.kind||"context_var"===i.kind)){const e=t.input.length>t.position?t.input[t.position]:"";if("'"===e||"'"===e)return 0}F(t);let o="";for(;t.input.length>t.position;){const e=t.input[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;o+=_(t)}if(o){const e=o.toLowerCase(),s=`${n} ${e}`,i=function(t,e,r,n){const s=e.toLowerCase(),i=r.toLowerCase();if("at"===s){const e=t.position;if("the"===i){F(t);let r="";for(;t.input.length>t.position;){const e=t.input[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;r+=_(t)}const s=r.toLowerCase();if("start"===s||"end"===s){F(t);let e="";for(;t.input.length>t.position;){const r=t.input[t.position];if(("a">r||r>"z")&&("A">r||r>"Z")&&("0">r||r>"9")&&"_"!==r&&"-"!==r)break;e+=_(t)}if("of"===e.toLowerCase())return q(t,j.KEYWORD,`at the ${s} of`,n),1}return t.position=e,0}if("start"===i||"end"===i){F(t);let r="";for(;t.input.length>t.position;){const e=t.input[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;r+=_(t)}return"of"===r.toLowerCase()?(q(t,j.KEYWORD,`at ${i} of`,n),1):(t.position=e,0)}}return 0}(t,n,e,r);if(i)return 1;const a=function(t,e,r){const n=t.position;let s=`${e} ${r}`,i=t.position;const o=[e,r];for(;8>o.length&&(F(t),t.input.length>t.position);){let e="";for(;t.input.length>t.position;){const r=t.input[t.position];if(("a">r||r>"z")&&("A">r||r>"Z"))break;e+=_(t)}if(!e)break;o.push(e.toLowerCase());const r=o.join(" ");L.has(r)&&(s=r,i=t.position)}return L.has(s)&&s!==`${e} ${r}`?(t.position=i,s):(t.position=n,null)}(t,n,e);if(a)return q(t,j.COMPARISON_OPERATOR,a,r),1;if(L.has(s))return q(t,j.COMPARISON_OPERATOR,s,r),1}return L.has(n)?(t.position=s,q(t,j.COMPARISON_OPERATOR,e,r),1):(t.position=s,0)}(t,s,e);if(i)return;const o=function(t){const e=t.toLowerCase();return"include"===e||"includes"===e?j.COMPARISON_OPERATOR:O.has(e)?j.LOGICAL_OPERATOR:P.has(t)||P.has(e)?j.OPERATOR:L.has(e)?j.COMPARISON_OPERATOR:"I"===t||T.has(e)?j.CONTEXT_VAR:w.has(e)?j.COMMAND:$.has(e)?j.EVENT:["true","false","null","undefined"].includes(e)?j.BOOLEAN:M.has(e)?j.KEYWORD:j.IDENTIFIER}(s);q(t,o,s,e)}function Q(t){const e=t.position,r=t.input,n=r.length;_(t);let s="$";for(;n>t.position;){const e=r[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e)break;s+=_(t)}q(t,j.GLOBAL_VAR,s,e)}function tt(t){return/[a-zA-Z]/.test(t)}function et(t){return/[a-zA-Z0-9]/.test(t)}function rt(t){let e=t.position+1,r=0;for(;t.input.length>e;){const n=t.input[e];if("/"===n&&t.input.length>e+1&&">"===t.input[e+1])return r;if(et(n)||"."===n||"#"===n||"["===n||"]"===n||":"===n||"-"===n||"_"===n||" "===n||"="===n||'"'===n||"'"===n||"("===n||")"===n||"*"===n||"^"===n||"$"===n||"~"===n||"|"===n||">"===n||"+"===n||","===n)r=1,e++;else{if(" "!==n&&"\t"!==n)return 0;e++}if(e-t.position>50)return 0}return 0}function nt(t){return"+-*/^%=!<>&|(){}[],.;:?''~$".includes(t)}const st=function(){if("undefined"!=typeof localStorage)try{const t=localStorage,e=t.getItem("hyperfixi:debug")||t.getItem("lokascript:debug");if("*"===e||"true"===e)return 1}catch{}return"undefined"!=typeof process&&"true"===process.env?.HYPERFIXI_DEBUG?1:0}(),it=st,ot=st,at=st,ct=st,lt=st,ut=(...t)=>{it&&console.log("🔧",...t)},ht=(...t)=>{ot&&console.log("🎯",...t)},ft=(...t)=>{at&&console.log("📝",...t)},dt=(...t)=>{ct&&console.log("🔍",...t)},pt=(...t)=>{lt&&console.log("🚀",...t)};let mt=0,yt=null;if("undefined"!=typeof window&&"undefined"!=typeof URLSearchParams)try{"semantic"===new URLSearchParams(window.location.search).get("debug")&&(mt=1,yt=window,console.log("%c[HyperFixi] Semantic debug auto-enabled via URL param","color: #667eea; font-weight: bold"))}catch{}let vt={totalParses:0,semanticSuccesses:0,semanticFallbacks:0,traditionalParses:0,averageConfidence:0,confidenceHistory:[]};class gt{constructor(t){this.analyzer=t.analyzer,this.language=t.language,this.confidenceThreshold=t.confidenceThreshold??.5,this.debugEnabled=t.debug??0}isAvailable(){return this.analyzer.supportsLanguage(this.language)}shouldSkipSemantic(t){const e=t.trim().split(/\s+/)[0]?.toLowerCase();if(gt.SKIP_SEMANTIC_COMMANDS.has(e))return 1;const r=t.toLowerCase();return/\bjs\b/.test(r)||/\btell\b/.test(r)?1:0}trySemanticParse(t){const e=performance.now();if(this.shouldSkipSemantic(t))return{success:0,confidence:0,errors:["Command skipped for semantic parsing - using traditional parser"]};if(!this.isAvailable())return{success:0,confidence:0,errors:[`Semantic parsing not available for language '${this.language}'`]};try{const n=this.analyzer.analyze(t,this.language),s=performance.now()-e;this.debugEnabled&&console.log("[SemanticIntegration] Analysis result:",{input:t,language:this.language,confidence:n.confidence,command:n.command?.name,threshold:this.confidenceThreshold});const i=n.confidence>=this.confidenceThreshold&&!!n.command,o=!i&&n.confidence>0;if(mt){const e={};if(n.command?.roles)for(const[t,r]of n.command.roles)e[t]=r.value;const a={input:t.substring(0,100),language:this.language,confidence:n.confidence,threshold:this.confidenceThreshold,semanticSuccess:i,fallbackTriggered:o,command:n.command?.name,roles:Object.keys(e).length>0?e:void 0,errors:n.errors,timestamp:Date.now(),duration:s};!function(t){if(!mt)return;const e=t.semanticSuccess?"semantic":t.fallbackTriggered?"fallback":"traditional",r=Math.round(100*t.confidence),n=Math.round(100*t.threshold),s=t.semanticSuccess?"color: #4caf50; font-weight: bold":t.fallbackTriggered?"color: #ff9800; font-weight: bold":"color: #9e9e9e";if(console.groupCollapsed(`%c[Semantic] ${e.toUpperCase()} %c${t.input.substring(0,50)}${t.input.length>50?"...":""}`,s,"color: #888"),console.log(`Confidence: ${r}% (threshold: ${n}%)`),t.command&&console.log("Command: "+t.command),t.roles&&Object.keys(t.roles).length>0&&console.log("Roles:",t.roles),t.duration&&console.log(`Duration: ${t.duration.toFixed(2)}ms`),t.errors?.length&&console.log("Errors:",t.errors),console.groupEnd(),yt){const e=new CustomEvent("lokascript:semantic:parse",{detail:t,bubbles:1});yt.dispatchEvent(e)}}(a),r=a,vt.totalParses++,r.semanticSuccess?vt.semanticSuccesses++:r.fallbackTriggered?vt.semanticFallbacks++:vt.traditionalParses++,vt.confidenceHistory.push(r.confidence),vt.confidenceHistory.length>100&&vt.confidenceHistory.shift(),vt.averageConfidence=vt.confidenceHistory.reduce((t,e)=>t+e,0)/vt.confidenceHistory.length}return i?{success:1,node:this.buildCommandNode(n),confidence:n.confidence,tokensConsumed:n.tokensConsumed}:{success:0,confidence:n.confidence,tokensConsumed:n.tokensConsumed,errors:n.errors}}catch(t){return{success:0,confidence:0,errors:[t instanceof Error?t.message:t+""]}}var r}buildCommandNode(t){const{command:e}=t;if(!e)throw Error("Cannot build command node without command data");if("repeat"===e.name)return this.buildRepeatCommandNode(e);if("for"===e.name)return this.buildRepeatCommandNode(e);if("set"===e.name)return this.buildSetCommandNode(e);if("if"===e.name||"unless"===e.name)return this.buildIfCommandNode(e);const r=[],n={};for(const[t,s]of e.roles){const i=this.semanticValueToExpression(s);switch(t){case"patient":case"event":r.push(i);break;case"destination":"put"===e.name?n.into=i:"add"===e.name||"append"===e.name||"prepend"===e.name?n.to=i:n.on=i;break;case"source":"fetch"===e.name?r.push(i):n.from=i;break;case"quantity":n.by=i;break;case"duration":n.over=i;break;case"responseType":n.as=i;break;case"method":n.method=i;break;case"style":n.with=i;break;case"condition":n.when=i;break;default:n[t]=i}}return{type:"command",name:e.name,args:r,modifiers:Object.keys(n).length>0?n:void 0,isBlocking:0,start:0,end:0,line:1,column:0}}buildRepeatCommandNode(t){const e=[],r={},n=t.roles.get("loopType");n&&e.push({type:"identifier",name:n.value+"",start:0,end:0,line:1,column:0});const s=t.roles.get("patient");"for"==(n?n.value+"":"")&&s&&e.push({type:"identifier",name:"expression"===s.type&&s.raw||s.value+"",start:0,end:0,line:1,column:0});const i=t.roles.get("event");i&&e.push({type:"string",value:i.value+"",start:0,end:0,line:1,column:0});const o=t.roles.get("source");o&&e.push(this.semanticValueToExpression(o));const a=t.roles.get("quantity");a&&e.push(this.semanticValueToExpression(a));const c=t.roles.get("condition");return c&&(r.condition=this.semanticValueToExpression(c)),{type:"command",name:"repeat",args:e,modifiers:Object.keys(r).length>0?r:void 0,isBlocking:0,start:0,end:0,line:1,column:0}}buildSetCommandNode(t){const e=[],r=t.roles.get("destination");if(r)if("property-path"===r.type){const t=r;e.push({type:"possessiveExpression",object:this.semanticValueToExpression(t.object),property:this.createPropertyNode(t.property),start:0,end:0,line:1,column:0})}else e.push(this.semanticValueToExpression(r));e.push({type:"identifier",name:"to",start:0,end:0,line:1,column:0});const n=t.roles.get("patient");return n&&e.push(this.semanticValueToExpression(n)),{type:"command",name:"set",args:e,isBlocking:0,start:0,end:0,line:1,column:0}}createPropertyNode(t){return t.startsWith("*")?{type:"cssProperty",name:t.substring(1),start:0,end:0,line:1,column:0}:{type:"identifier",name:t,start:0,end:0,line:1,column:0}}buildIfCommandNode(t){const e=[],r=t.roles.get("condition");return r&&e.push(this.semanticValueToExpression(r)),{type:"command",name:t.name,args:e,isBlocking:0,start:0,end:0,line:1,column:0}}semanticValueToExpression(t){switch(t.type){case"selector":return{type:"selector",value:t.value,start:0,end:0,line:1,column:0};case"reference":return{type:"identifier",name:t.value,start:0,end:0,line:1,column:0};case"literal":return"string"==typeof t.value&&t.value.includes("${")&&t.value.includes("}")?{type:"templateLiteral",value:t.value,start:0,end:0,line:1,column:0}:{type:"literal",value:t.value,raw:t.raw??t.value,start:0,end:0,line:1,column:0};case"property-path":{const e=t;return{type:"memberExpression",object:this.semanticValueToExpression(e.object),property:{type:"identifier",name:e.property,start:0,end:0,line:1,column:0},computed:0,start:0,end:0,line:1,column:0}}default:return this.parseExpressionString(t.raw||"")}}parseExpressionString(t){let e=0;const r=()=>{for(;t.length>e&&/\s/.test(t[e]);)e++},n=()=>{r();const n=e;for(;t.length>e&&/[a-zA-Z0-9_$]/.test(t[e]);)e++;return t.slice(n,e)},s=()=>{const n=[];if(e++,r(),")"!==t[e])for(n.push(i()),r();","===t[e];)e++,r(),n.push(i()),r();return")"===t[e]&&e++,n},i=()=>{r();const i=n();if(!i)return{type:"identifier",name:t.trim(),start:0,end:0,line:1,column:0};let o={type:"identifier",name:i,start:0,end:0,line:1,column:0};for(;t.length>e;){r();const i=t[e];if("."===i){e++;const t=n();t&&(o={type:"memberExpression",object:o,property:{type:"identifier",name:t,start:0,end:0,line:1,column:0},computed:0,start:0,end:0,line:1,column:0})}else{if("("!==i)break;o={type:"callExpression",callee:o,arguments:s(),start:0,end:0,line:1,column:0}}}return o};return i()}getLanguage(){return this.language}getConfidenceThreshold(){return this.confidenceThreshold}}function bt(t){return t.kind!==I.IDENTIFIER?0:w.has(t.value.toLowerCase())}function Et(t){return t.kind!==I.IDENTIFIER?0:R.has(t.value.toLowerCase())}function wt(t){return t.kind!==I.IDENTIFIER?0:$.has(t.value.toLowerCase())}function xt(t){return t.kind!==I.IDENTIFIER?0:T.has(t.value.toLowerCase())}function kt(t){return L.has(t.value.toLowerCase())}function At(t){return t.kind===I.IDENTIFIER}function St(t){return t.kind===I.SELECTOR}function Ct(t){return t.kind!==I.SELECTOR?0:!t.value.startsWith("<")}function Nt(t){return t.kind===I.STRING||t.kind===I.NUMBER||t.kind===I.TEMPLATE}function Tt(t){return t.kind===I.IDENTIFIER}function Ot(t){return t.kind===I.TIME}function Lt(t){return t.kind===I.SYMBOL}function $t(t){return t.kind===I.COMMENT}function Rt(t){if(t.kind!==I.IDENTIFIER)return 0;const e=t.value.toLowerCase();return!(w.has(e)||R.has(e)||$.has(e)||T.has(e))}function It(t){return t.kind===I.STRING}function jt(t){return t.kind===I.NUMBER}function Dt(t){if(t.kind===I.IDENTIFIER){const e=t.value;return"true"===e||"false"===e||"null"===e||"undefined"===e}return 0}function Mt(t){return t.kind===I.TEMPLATE}function Pt(t){return t.kind===I.SELECTOR&&t.value.startsWith("<")}function Vt(t){return t.kind===I.SELECTOR&&t.value.startsWith("#")}function Bt(t){return t.kind===I.SELECTOR&&t.value.startsWith(".")}function _t(t){return t.kind!==I.SELECTOR?0:!t.value.startsWith("#")&&!t.value.startsWith(".")}function Ft(t){if(t.kind!==I.OPERATOR)return 0;const e=t.value.toLowerCase();return!O.has(e)&&!L.has(e)}function qt(t){const e=t.value.toLowerCase();return"then"===e||"and"===e||"else"===e||"end"===e||"on"===e}function Ht(t,e,r){return{type:"literal",value:t,raw:e,start:r.start,end:r.end,line:r.line,column:r.column}}function Ut(t,e){return{type:"identifier",name:t,start:e.start,end:e.end,line:e.line,column:e.column}}function Wt(t,e,r,n){return{type:"binaryExpression",operator:t,left:e,right:r,start:n.start,end:n.end,line:n.line,column:n.column}}function zt(t,e){return{type:"block",commands:t,start:e.start,end:e.end,line:e.line,column:e.column}}function Jt(t,e){return{type:"string",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}function Zt(t,e){return{type:"objectLiteral",properties:t,start:e.start,end:e.end,line:e.line,column:e.column}}function Gt(t,e){return{type:"arrayLiteral",elements:t,start:e.start,end:e.end,line:e.line,column:e.column}}gt.SKIP_SEMANTIC_COMMANDS=new Set(["swap","morph","js","tell"]);const Xt=[{command:"append",keywords:["to"],syntax:"append <value> [to <target>]"},{command:"make",keywords:["a","an"],syntax:"make (a|an) <type>"},{command:"send",keywords:["to"],syntax:"send <event> to <target>"},{command:"throw",keywords:[],syntax:"throw <error>"}];function Yt(t,e){return t?e.some(e=>t.value===e||t.value.toLowerCase()===e):0}const Kt=[t,n,e,r];function Qt(t,e=[]){if(t.isAtEnd())return 1;for(const e of Kt)if(t.check(e))return 1;for(const r of e)if(t.check(r))return 1;return t.checkIsCommand()?1:0}function te(t,e=[]){if(!Qt(t,e))return t.parseExpression()}function ee(t,e,r){return t.check(e)?(t.advance(),r.push(t.createIdentifier(e)),1):0}function re(t,e,r){for(const n of e)if(t.check(n))return t.advance(),r.push(t.createIdentifier(n)),n;return null}function ne(t,e){return t.check(e)?(t.advance(),1):0}class se{constructor(t){this.args=[],this.isBlocking=0,this.name=t}static from(t){const e=new se(t.value);return e.startPos={start:t.start??0,end:t.end??0,line:t.line??1,column:t.column??1},e}static fromIdentifier(t){const e=new se(t.name);return void 0!==t.start&&(e.startPos={start:t.start,end:t.end??0,line:t.line??1,column:t.column??1}),e}static named(t){return new se(t)}withArgs(...t){return this.args.push(...t),this}withBody(t){return this.body=t,this}withImplicitTarget(t){return this.implicitTarget=t,this}withModifier(t,e){return this.modifiers||(this.modifiers={}),this.modifiers[t]=e,this}withModifiers(t){return this.modifiers={...this.modifiers,...t},this}withName(t){return this.name=t,this}withOriginalCommand(t){return this.originalCmd=t,this}blocking(t=1){return this.isBlocking=t,this}startingAt(t){return this.startPos={start:t.start??0,end:t.end??0,line:t.line??1,column:t.column??1},this}endingAt(t){return this.endPos={start:t.start??this.startPos?.start??0,end:t.end,line:t.line??this.startPos?.line??1,column:t.column??this.startPos?.column??1},this}build(){const t={type:"command",name:this.name,args:this.args,isBlocking:this.isBlocking,start:this.startPos?.start??0,end:this.endPos?.end??this.startPos?.end??0,line:this.startPos?.line??1,column:this.startPos?.column??1};return this.body&&(t.body=this.body),this.implicitTarget&&(t.implicitTarget=this.implicitTarget),this.modifiers&&(t.modifiers=this.modifiers),this.originalCmd&&(t.originalCommand=this.originalCmd),t}clone(){const t=new se(this.name);return t.args=[...this.args],t.body=this.body?[...this.body]:void 0,t.implicitTarget=this.implicitTarget,t.isBlocking=this.isBlocking,t.modifiers=this.modifiers?{...this.modifiers}:void 0,t.originalCmd=this.originalCmd,t.startPos=this.startPos?{...this.startPos}:void 0,t.endPos=this.endPos?{...this.endPos}:void 0,t}}function ie(t,e){const r=[];let n="";const s=t.peek().start||0,i=t.peek().line||1,o=t.peek().column||1;if(t.checkIdentifierLike()){for(n=t.advance().value;t.check(":")&&!t.isAtEnd();)t.advance(),n+=":",t.checkIdentifierLike()&&(n+=t.advance().value);if(t.check("(")){t.advance();const e=[];for(;!t.isAtEnd()&&!t.check(")");){const r=t.savePosition();let n;if(t.checkIdentifierLike()){const e=t.peek().value;t.advance(),t.check(":")?(t.advance(),n=e):t.restorePosition(r)}const s=t.parseExpression();if(e.push(void 0!==n?{type:"objectLiteral",properties:[{key:{type:"identifier",name:n},value:s}],start:s.start,end:s.end,line:s.line,column:s.column}:s),t.check(","))t.advance();else if(!t.check(")"))break}t.check(")")&&t.advance(),r.push({type:"functionCall",name:n,args:e,start:s,end:t.getPosition().end,line:i,column:o})}else r.push({type:"string",value:n,start:s,end:t.getPosition().end,line:i,column:o})}for(;!Qt(t);)r.push(t.parsePrimary());let a=-1,c="on";for(let t=0;r.length>t;t++){const e=r[t],n=e.name||e.value;if(!("identifier"!==e.type&&"literal"!==e.type&&"keyword"!==e.type||"on"!==n&&"to"!==n)){a=t,c=n;break}}const l=[];if(-1===a)l.push(...r);else{const e=r.slice(0,a),n=r.slice(a+1);l.push(...e),l.push(t.createIdentifier(c)),l.push(...n)}return se.fromIdentifier(e).withArgs(...l).endingAt(t.getPosition()).build()}function oe(t,e){const r=[];if(t.check(b)){const e=t.advance();if(r.push({type:"identifier",name:b,start:e.start,end:e.end,line:e.line,column:e.column}),t.check(y)){const e=t.advance();r.push({type:"identifier",name:y,start:e.start,end:e.end,line:e.line,column:e.column})}}return se.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}function ae(n,s){const i=[];let o=0;const a=n.savePosition();for(let e=0;500>e&&!n.isAtEnd();e++){const e=n.peek();if(e.value===t){o=1;break}if(e.value===r||e.value===v||"def"===e.value||e.value===m)break;n.advance()}n.restorePosition(a);let c=0;if(!o){const t=n.savePosition(),i=s.line,o=100;for(;!n.isAtEnd()&&o>n.current-t;){const t=n.peek(),s=t.value?.toLowerCase();if(s===v||"def"===s||s===m)break;if(s===e||s===r){t.line===i&&(c=1);break}if((n.checkIsCommand()||n.isCommand(s))&&void 0!==t.line&&t.line!==i){c=1;break}n.advance()}n.restorePosition(t)}const l=o||c;let u;if(l)u=n.parseExpression();else{const e=[],r=20;let i=0;for(;!n.isAtEnd()&&!n.checkIsCommand()&&!n.isCommand(n.peek().value)&&!n.check(t)&&r>i;){const t=n.savePosition();e.push(n.parseLogicalAnd()),n.savePosition()===t&&n.advance(),i++}if(0===e.length)throw Error("Expected condition after if/unless");u=1===e.length?e[0]:{type:"expression",tokens:e,start:e[0].start,end:e[e.length-1].end,line:s.line,column:s.column}}if(i.push(u),l){o&&n.advance();const t=[];for(;!n.isAtEnd()&&!n.check(e)&&!n.check(r)&&(n.checkIsCommand()||n.isCommand(n.peek().value));){n.advance();const e=n.parseCommand();e&&t.push(e)}if(0===t.length&&n.isAtEnd())throw Error("Expected command after 'then' in if statement - incomplete conditional");i.push(zt(t,{start:s.start,end:n.getPosition().end,line:s.line,column:s.column}));let a=0;if(n.check(e))if(n.advance(),n.check("if")){const t=n.peek();n.advance();const e=ae(n,t);i.push(zt([e],{start:t.start,end:n.getPosition().end,line:t.line,column:t.column})),a=1}else{const t=[];for(;!n.isAtEnd()&&!n.check(r)&&(n.checkIsCommand()||n.isCommand(n.peek().value));){n.advance();const e=n.parseCommand();e&&t.push(e)}i.push(zt(t,{start:s.start,end:n.getPosition().end,line:s.line,column:s.column}))}a||n.consume(r,"Expected 'end' after if block")}else{if(!n.checkIsCommand()&&!n.isCommand(n.peek().value))throw Error("Expected command after if condition in single-line form");{n.advance();const t=n.parseCommand();i.push(zt([t],{start:s.start,end:n.getPosition().end,line:s.line,column:s.column}))}}return se.from(s).withArgs(...i).endingAt(n.getPosition()).build()}function ce(t,e){const r=[],n={};if(t.checkAnySelector()||t.checkContextVar()||t.match("<")){const e=t.parsePrimary();if(r.push(e),t.match("*")){if(t.checkIdentifierLike()){const e=t.advance();r.push({type:"identifier",name:"*"+e.value,start:e.start-1,end:e.end,line:e.line,column:e.column})}}else if(t.checkIdentifierLike()){const e=t.parsePrimary();r.push(e)}}else if(t.checkIdentifierLike()){const e=t.parsePrimary();r.push(e)}if(t.match("and")&&t.match("set")&&t.checkIdentifierLike()){const e=t.advance();n.set={type:"identifier",name:e.value,start:e.start,end:e.end,line:e.line,column:e.column}}const s=se.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition());return Object.keys(n).length>0&&s.withModifiers(n),s.build()}function le(t,e){const r=[],n=te(t,[f]);n&&r.push(n),ee(t,f,r);const s=te(t);return s&&r.push(s),se.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}function ue(t,e){const r=[];if(t.check("between")){t.advance(),r.push(t.createIdentifier("between"));const i=te(t,[n]);i&&r.push(i),ee(t,n,r);const o=te(t,[f,m,s]);if(o&&r.push(o),re(t,[f,m],r)){const e=te(t);e&&r.push(e)}return se.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}const i=te(t,[f,m]);if(i&&r.push(i),re(t,[f,m],r)){const e=te(t);e&&r.push(e)}return se.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}function he(t,e){const n=t.parseExpression();if(!n)return t.addError("Put command requires content expression"),null;const s=t.peek();if(!s||!S.includes(s.value))return t.addError(`Expected operation keyword (${S.join(", ")}) after put expression, got: ${s?.value}`),null;let i=t.advance().value;const o=i.toLowerCase();"at start of"===o||"at the start of"===o?i=k:"at end of"===o||"at the end of"===o?i=A:"at"===i&&(t.check(E)||t.check(b)?(ne(t,b),t.check(E)&&(t.advance(),t.check(p)&&(t.advance(),i=k))):t.check(r)&&(t.advance(),t.check(p)&&(t.advance(),i=A)));const a=t.parseExpression();return a?se.fromIdentifier(e).withArgs(n,t.createIdentifier(i),a).endingAt(t.getPosition()).build():(t.addError("Put command requires target expression after operation keyword"),null)}const fe=["innerhtml","outerhtml","into","over","delete","morph","morphouter"];function de(s,i){const o=s.savePosition();let a=null,c=[];try{a=function(t){if(!t.check(":"))return null;if(t.advance(),t.check(":")){t.advance();const e=t.advance();return{type:"identifier",name:e.value,scope:"global",start:e.start-2,end:e.end}}const e=t.advance();return{type:"identifier",name:e.value,scope:"local",start:e.start-1,end:e.end}}(s)??function(t){if(!t.check(g)&&!t.check("local"))return null;const e=t.advance(),r=t.advance();return{type:"identifier",name:r.value,scope:e.value,start:e.start,end:r.end}}(s)??function(t,e){if(!t.check(b))return null;const r=t.savePosition();t.advance();const n=t.peek(),s=t.peekAt(1);if(n&&s&&s.value===p){const r=t.advance();if(t.check(p)){t.advance();const n=t.advance(),s=n.value.startsWith("#");return{type:"propertyOfExpression",property:{type:"identifier",name:r.value,start:r.start,end:r.end},target:{type:s?"idSelector":"cssSelector",value:n.value,start:n.start,end:n.end},start:e,end:t.savePosition()}}return t.restorePosition(e),null}if(n&&s&&s.value===h){const e=t.advance();return{type:"identifier",name:e.value,start:e.start,end:e.end}}return t.restorePosition(r),null}(s,o),a||(a=s.parseExpression())}catch{s.restorePosition(o),a=null}if(!a){const i=function(s){if(s.match(":")){const t=s.advance();return{expression:{type:"identifier",name:t.value,scope:"local",start:t.start,end:t.end},tokens:[]}}const i=[];for(;!(s.isAtEnd()||s.check(h)||s.check(t)||s.check(n)||s.check(e)||s.check(r));)i.push(s.parsePrimary());if(0===i.length)return{expression:null,tokens:[]};if(i.length>=4){const t=(t,e)=>t[e];if(t(i[0],"value")===b&&t(i[2],"value")===p){const e=i[1],r=i[3];return{expression:(o=Ut(t(e,"value")||t(e,"name")||"",{start:e.start??0,end:e.end??0,line:e.line??1,column:e.column??1}),a={type:"idSelector"===r.type?"idSelector":"cssSelector",value:t(r,"value")||t(r,"name")||"",start:r.start??0,end:r.end??0,line:r.line,column:r.column},c={start:i[0].start??0,end:r.end??0,line:i[0].line??1,column:i[0].column??1},{type:"propertyOfExpression",property:o,target:a,start:c.start,end:c.end,line:c.line,column:c.column}),tokens:[]}}}var o,a,c;return 1===i.length?{expression:i[0],tokens:[]}:{expression:null,tokens:i}}(s);a=i.expression,c=i.tokens}if(!s.check(h)){const t=s.isAtEnd()?"end of input":s.peek().value;throw Error("Expected 'to' in set command, found: "+t)}s.advance();const l=s.parseExpression()??s.parsePrimary(),u=[];return a?u.push(a):c.length>0&&u.push(...c),u.push(s.createIdentifier(h)),l&&u.push(l),se.fromIdentifier(i).withArgs(...u).endingAt(s.getPosition()).build()}function pe(t,e){const r=[];for(;!Qt(t,["catch","finally"])&&(t.checkIdentifierLike()||t.checkSelector()||t.checkLiteral()||t.checkTimeExpression()||t.match("<"));)r.push(t.parsePrimary());return se.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}function me(t){if(t.isAtEnd())return 1;const e=t.peek().value;return["as","with","{","then","end","else","otherwise",")"].includes(e)||Qt(t)}function ye(t){if(t.check("{"))return 0;if(!t.checkIdentifierLike())return 0;const e=t.peekAt(1);return null!==e&&":"===e.value}function ve(t){const e=[],r=t.getPosition();do{if(!t.checkIdentifierLike())break;const r=t.advance(),n={type:"identifier",name:r.value,start:r.start,end:r.end,line:r.line,column:r.column};t.consume(":","Expected ':' after property name in fetch named arguments");const s=t.parsePrimary();s&&e.push({key:n,value:s})}while(t.match(",")&&!t.isAtEnd());const n=t.getPosition();return{type:"objectLiteral",properties:e,start:r.start,end:n.end,line:r.line,column:r.column}}class ge{constructor(t,e,r){this.current=0,this.warnings=[],this.tokens=t,this.keywordResolver=e?.keywords,this.registryIntegration=e?.registryIntegration,e?.semanticAnalyzer&&e?.language&&(this.semanticAdapter=new gt({analyzer:e.semanticAnalyzer,language:e.language,confidenceThreshold:e.semanticConfidenceThreshold??.5})),this.originalInput=r||t.map(t=>t.value).join(" ")}resolveKeyword(t){return this.keywordResolver?this.keywordResolver.resolve(t)??t:t}addWarning(t){this.warnings.push(t)}parse(){try{if(0===this.tokens.length)return this.addError("Cannot parse empty input"),{success:0,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings};if(this.check("behavior")){const t=[];for(;this.check("behavior");){this.advance();const e=this.parseBehaviorDefinition();if(e&&t.push(e),this.error)break}return this.error?{success:0,node:1===t.length?t[0]:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:1,node:1===t.length?t[0]:this.createProgramNode(t),tokens:this.tokens,warnings:this.warnings}}if(this.check("init")||this.check("on")||this.check("def")||this.checkComment()){const t=[];for(;!this.isAtEnd();)if(this.checkComment())this.advance();else if(this.check("init")){this.advance();const e=this.parseTopLevelInitBlock();e&&t.push(e)}else if(this.check("on")){this.advance();const e=this.parseEventHandler();e&&t.push(e)}else{if(!this.check("def"))break;{this.advance();const e=this.parseDefFeature();e&&t.push(e)}}return this.isAtEnd()?this.error?{success:0,node:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:1,node:this.createProgramNode(t),tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:0,node:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings})}if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){const t=this.parseCommandSequence();if(t){if(!this.isAtEnd()&&this.check("on")){ft("✅ PARSER: Found event handlers after command sequence, parsing as program");const e=[t];ft(`✅ PARSER: Starting with ${e.length} statement(s) from command sequence`);let r=0;for(;!this.isAtEnd()&&this.check("on");){ft(`✅ PARSER: Parsing event handler #${r+1}, current token: ${this.peek().value}`),this.advance();const t=this.parseEventHandler();if(ft("✅ PARSER: parseEventHandler returned:",t?`type=${t.type}, event=${t.event}`:"null"),t&&(e.push(t),r++,ft(`✅ PARSER: Added event handler, now have ${e.length} statements total`)),ft(`✅ 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 ft("⚠️ PARSER: Unexpected token after event handlers: "+this.peek().value),this.addError("Unexpected token after event handlers: "+this.peek().value),{success:0,node:this.createProgramNode(e),tokens:this.tokens,error:this.error};ft("✅ PARSER: No more event handlers, at end of input");break}}return ft(`✅ PARSER: Finished parsing, creating Program node with ${e.length} statements`),this.error?{success:0,node:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:1,node:this.createProgramNode(e),tokens:this.tokens,warnings:this.warnings}}return this.isAtEnd()?this.error?{success:0,node:t,tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:1,node:t,tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:0,node:t||this.createErrorNode(),tokens:this.tokens,error:this.error})}}const t=this.parseExpression();return this.error?{success:0,node:t||this.createErrorNode(),tokens:this.tokens,error:this.error}:this.isAtEnd()?{success:1,node:t,tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:0,node:t||this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings})}catch(t){return this.addError(t instanceof Error?t.message:"Unknown parsing error"),{success:0,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}}parseExpression(){return this.parseAssignment()}parseAssignment(){let t=this.parseLogicalOr();if(this.match("=")){if(this.check(">")){if(this.advance(),this.addError('Arrow functions (=>) are not supported in hyperscript. Use "js ... end" blocks for JavaScript callbacks.'),!this.isAtEnd())try{this.parseExpression()}catch{}return this.createErrorNode()}const e=this.previous().value,r=this.parseAssignment();t=this.createBinaryExpression(e,t,r)}return t}parseLogicalOr(){let t=this.parseLogicalAnd();for(;this.match("or");){const e=this.previous().value,r=this.parseLogicalAnd();t=this.createBinaryExpression(e,t,r)}return t}parseLogicalAnd(){let t=this.parseEquality();for(;this.match("and");){const e=this.previous().value,r=this.parseEquality();t=this.createBinaryExpression(e,t,r)}return t}parseEquality(){let t=this.parseComparison();for(;this.matchComparisonOperator()||this.match("is","match","matches","contains","include","includes","in","of","as","really");){const e=this.previous().value;if(ge.POSTFIX_UNARY_OPERATORS.has(e)){t=this.createUnaryExpression(e,t,0);continue}const r=this.parseComparison();t=this.createBinaryExpression(e,t,r)}return t}parseComparison(){let t=this.parseAddition();for(;this.matchComparisonOperator();){const e=this.previous().value;if(ge.POSTFIX_UNARY_OPERATORS.has(e)){t=this.createUnaryExpression(e,t,0);continue}const r=this.parseAddition();t=this.createBinaryExpression(e,t,r)}return t}parseAddition(){let t=this.parseMultiplication();for(;this.match("+","-")||this.matchOperator("+")||this.matchOperator("-");){const e=this.previous().value;if(this.check("+")||this.check("-"))return this.addError(`Invalid operator combination: ${e}${this.peek().value}`),t;if(this.isAtEnd())return this.addError(`Expected expression after '${e}' operator`),t;const r=this.parseMultiplication();t=this.createBinaryExpression(e,t,r)}return t}parseMultiplication(){let t=this.parseUnary();for(;this.match("*","/","%","mod");){const e=this.previous().value;if(this.check("*")||this.check("/")||this.check("%")||this.check("+")||this.check("-")){const r=this.peek().value;return this.addError("*"===e&&"*"===r?"Unexpected token: "+r:`Invalid operator combination: ${e}${r}`),t}if(this.isAtEnd())return this.addError(`Expected expression after '${e}' operator`),t;const r=this.parseUnary();t=this.createBinaryExpression(e,t,r)}return t}parseUnary(){if(this.match("not","no","exists","some","-","+")){const t=this.previous().value;if(this.isAtEnd())return this.addError(`Expected expression after '${t}' operator`),this.createErrorNode();const e=this.parseUnary();return this.createUnaryExpression(t,e,1)}if(this.check("does")&&this.tokens.length>this.current+1&&"not"===this.tokens[this.current+1].value&&this.tokens.length>this.current+2&&"exist"===this.tokens[this.current+2].value){if(this.advance(),this.advance(),this.advance(),this.isAtEnd())return this.addError("Expected expression after 'does not exist' operator"),this.createErrorNode();const t=this.parseUnary();return this.createUnaryExpression("does not exist",t,1)}return this.parseImplicitBinary()}parseImplicitBinary(){let t=this.parseCall();for(;!(this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("and")||this.check("else")||this.check(")")||this.check("]")||this.check(","));){if("identifier"!==t.type){if("literal"===t.type&&(this.checkNumber()||this.checkIdentifier())){const e=this.peek();return this.addError(`Missing operator between '${t.raw||t.value}' and '${e.value}'`),t}break}if(this.isCommand(t.name))if(this.isCompoundCommand(t.name.toLowerCase())){if(!(this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkTimeExpression()||this.checkString()||this.checkNumber()||this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()))break;{const e=this.createCommandFromIdentifier(t);e&&(t=e)}}else if("wait"===t.name.toLowerCase()&&this.checkTimeExpression()){const e=this.createCommandFromIdentifier(t);e&&(t=e)}else{if(!this.checkSelector())break;{const e=this.parseCall();t=this.createBinaryExpression(" ",t,e)}}else{if(!this.checkSelector())break;{const e=this.parseCall();t=this.createBinaryExpression(" ",t,e)}}}return t}isCommand(t){return this.keywordResolver?this.keywordResolver.isCommand(t):(t=>w.has(t.toLowerCase()))(t)}isKeyword(t){return this.keywordResolver?this.keywordResolver.isKeyword(t):(t=>C.has(t.toLowerCase()))(t)}createCommandFromIdentifier(t){const e=[],r=this.resolveKeyword(t.name.toLowerCase());if(this.isCompoundCommand(r))return this.parseCompoundCommand(t);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.checkIsCommand())&&(this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()||this.checkEvent()||this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkString()||this.checkNumber()||this.checkTimeExpression()||this.match("<"));)e.push(this.parsePrimary());return{type:"command",name:t.name,args:e,isBlocking:0,...void 0!==t.start&&{start:t.start},end:this.getPosition().end,...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}}}isCompoundCommand(t){return x.has(t.toLowerCase())}parseCompoundCommand(s){return function(s,i){switch(i.name.toLowerCase()){case"put":return he(s,i);case"trigger":case"send":return ie(s,i);case"remove":return le(s,i);case"toggle":return ue(s,i);case"set":return de(s,i);case"halt":return oe(s,i);case"measure":return ce(s,i);case"js":return function(t,e){const n=[];if(t.match("(")){for(;!t.check(")")&&!t.isAtEnd();)t.checkIdentifierLike()&&n.push(t.advance().value),t.match(",");t.consume(")","Expected ) after js parameters")}const s=t.peek().start;for(;!t.check(r)&&!t.isAtEnd();)t.advance();const i=t.peek().start;t.consume(r,"Expected end after js code body");const o={type:"literal",value:t.getInputSlice(s,i).trim(),start:e.start,end:t.getPosition().end},a={type:"arrayLiteral",elements:n.map(t=>({type:"literal",value:t,start:e.start,end:e.end})),start:e.start,end:t.getPosition().end};return se.fromIdentifier(e).withArgs(o,a).endingAt(t.getPosition()).build()}(s,i);case"tell":return function(s,i){const o=s.parseExpression();if(!o)throw Error("tell command requires a target expression");const a=[];for(;!s.isAtEnd();){if(s.checkIsCommand()){try{s.advance();const t=s.parseCommand();if(!t)break;a.push(t)}catch{break}if(s.match(n))continue;if(s.check(t)||s.check(e)||s.check(r))break;if(s.checkIsCommand())continue;break}break}if(0===a.length)throw Error("tell command requires at least one command after the target");return se.fromIdentifier(i).withArgs(o,...a).endingAt(s.getPosition()).build()}(s,i);case"swap":case"morph":return function(t,e){console.log("[PARSER DEBUG] parseSwapCommand called");const r=[];let n=null;if(!t.isAtEnd()){const e=t.peek();if(e&&e.value){const s=e.value.toLowerCase();fe.includes(s)&&(n=s,t.advance(),r.push(t.createIdentifier(n)))}}if("delete"===n){const n=t.parseExpression();return n&&r.push(n),se.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}!t.isAtEnd()&&t.check(p)&&(t.advance(),r.push(t.createIdentifier("of")));const s=t.parseExpression();if(s&&r.push(s),!t.isAtEnd()&&t.check(d)){t.advance(),r.push(t.createIdentifier("with"));const e=t.parseExpression();e&&r.push(e)}return se.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}(s,i);default:return pe(s,i)}}(this.getContext(),s)}parsePutCommand(t){return he(this.getContext(),t)}parseSetCommand(t){return de(this.getContext(),t)}parseHaltCommand(t){return oe(this.getContext(),t)}parseMeasureCommand(t){return ce(this.getContext(),t)}parseTriggerCommand(t){return ie(this.getContext(),t)}parseCommandListUntilEnd(){const t=[];for(ft("🔄 parseCommandListUntilEnd: Starting to parse command list");!this.isAtEnd()&&!this.check("end");){ft("📍 Loop iteration, current token:",this.peek().value,"kind:",this.peek().kind);let e=0;const r=this.checkIsCommand(),n=!r&&this.checkIdentifier()&&this.isCommand(this.peek().value);if(r||n){ft(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&&(ft("⚠️ parseCommandListUntilEnd: Command parsing added error, restoring error state. Error was:",this.error.message),this.error=n),r&&(ft("✅ Parsed command:",r.name),t.push(r),e=1)}catch(t){ft("⚠️ parseCommandListUntilEnd: Command parsing threw exception, restoring error state:",t instanceof Error?t.message:t+""),this.error=n}}else this.checkIdentifier()&&ft("❌ IDENTIFIER is not a command:",this.peek().value);if(!e){ft("❌ No command parsed, breaking. Current token:",this.peek().value);break}for(ft("📍 After parsing command, current token:",this.peek().value);!(this.isAtEnd()||this.check("end")||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(","));)ft("⚠️ Skipping unexpected token:",this.peek().value),this.advance();if(this.match("then","and",","))ft("✅ Found separator, continuing");else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){ft("📍 No separator and no command, breaking. Current token:",this.peek().value);break}ft("✅ Next token is a command, continuing without separator")}}if(ft('🔍 After loop, checking for "end". Current token:',this.peek().value),!this.check("end"))throw ft('❌ ERROR: Expected "end" but got:',this.peek().value,"at position:",this.peek().start),Error('Expected "end" to close repeat block');return ft('✅ Found "end", consuming it'),this.advance(),ft("✅ parseCommandListUntilEnd: Successfully parsed",t.length,"commands"),t}parseRepeatCommand(t){return function(t,e){const r=[];let n="forever",h=null,p=null,m=null,v=null,g=null,E=null;if(t.check(s)){t.advance(),n=s;const e=t.peek();At(e)&&(g=e.value,t.advance()),t.check(u)&&(t.advance(),v=t.parseExpression())}else if(t.check(u))t.advance(),n=s,g="it",v=t.parseExpression();else if(t.check(i))t.advance(),n=i,m=t.parseExpression();else if(t.check(o))if(t.advance(),n=o,t.check(y)){t.advance(),n="until-event";const e=t.peek();if(ft("📍 Parsing event name, current token:",{value:e.value,kind:e.kind}),!At(e)&&!wt(e))throw Error('Expected event name after "event"');if(h=e.value,t.advance(),ft("✅ Got event name:",h,"Next token:",t.peek().value),ft('🔍 Checking for "from", current token:',t.peek().value),t.check(f)){ft('✅ Found "from", advancing...'),t.advance(),ft('📍 After consuming "from", current token:',t.peek().value),ne(t,b)&&ft('✅ Found "the", advancing...');const e=t.peek();ft("🔍 Before parsePrimary for event target:",{value:e.value,kind:e.kind,position:e.start}),p=t.parsePrimary(),ft("✅ After parsePrimary, eventTarget:",p)}else ft('❌ No "from" found, skipping target parsing')}else m=t.parseExpression();else t.check(a)?(t.advance(),n=a):(E=t.parseExpression(),t.check(c)&&(t.advance(),n=c));let w=null;if(t.check(d)){const e=t.peekAt(1);e&&e.value.toLowerCase()===l&&(t.advance(),t.advance(),w=l)}else if(t.check(l)){t.advance();const e=t.peek();At(e)?(w=e.value,t.advance()):w=l}const x=t.parseCommandListUntilEnd();r.push({type:"identifier",name:n,start:e.start,end:e.end,line:e.line,column:e.column});const k={start:e.start,end:e.end,line:e.line,column:e.column};return g&&r.push(Jt(g,k)),v&&r.push(v),m&&r.push(m),E&&r.push(E),h&&r.push(Jt(h,k)),p&&r.push(p),w&&r.push(Jt(w,k)),r.push(zt(x,{...k,end:k.end||0})),se.from(e).withArgs(...r).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseForCommand(t){return function(t,e){const r=[];let n=null,s=null;t.check("each")&&t.advance();const i=t.peek();if(!At(i))throw Error('Expected variable name after "for"');if(n=i.value,t.advance(),!t.check(u))throw Error('Expected "in" after variable name in for loop');if(t.advance(),s=t.parseExpression(),!s)throw Error('Expected collection expression after "in"');let o=null;if(t.check(d)){const e=t.peekAt(1);e&&e.value.toLowerCase()===l&&(t.advance(),t.advance(),o=l)}else if(t.check(l)){t.advance();const e=t.peek();At(e)?(o=e.value,t.advance()):o=l}const a=t.parseCommandListUntilEnd();r.push({type:"identifier",name:"for",start:e.start,end:e.end,line:e.line,column:e.column});const c={start:e.start,end:e.end,line:e.line,column:e.column};return r.push(Jt(n,c)),r.push(s),o&&r.push(Jt(o,c)),r.push(zt(a,{...c,end:c.end||0})),se.from({...e,value:"repeat"}).withArgs(...r).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseWaitCommand(t){return function(t,e){const r=[];if(t.checkTimeExpression()||t.checkLiteral()){const n=t.parsePrimary();return r.push(n),se.from(e).withArgs(...r).blocking().endingAt(t.getPosition()).build()}if(t.check("for")){t.advance();const n=[];do{const e=t.peek();if(!At(e))throw Error('Expected event name after "for"');const r=e.value;t.advance();const s=[];if(t.check("(")){for(t.advance();!t.isAtEnd()&&!t.check(")");){const e=t.peek();if(!At(e))break;s.push(e.value),t.advance(),t.check(",")&&t.advance()}if(!t.check(")"))throw Error('Expected ")" after event parameters');t.advance()}if(n.push({name:r,params:s}),!t.check("or"))break;t.advance()}while(!t.isAtEnd());let s=null;t.check(f)&&(t.advance(),ne(t,b),s=t.parsePrimary());const i={start:e.start,end:t.getPosition().end,line:e.line,column:e.column};r.push(Gt(n.map(t=>Zt([{key:Ut("name",i),value:Ht(t.name,`"${t.name}"`,i)},{key:Ut("args",i),value:Gt(t.params.map(t=>Ht(t,`"${t}"`,i)),i)}],i)),i)),s&&r.push(s)}return se.from(e).withArgs(...r).blocking().endingAt(t.getPosition()).build()}(this.getContext(),t)}parseInstallCommand(t){return function(t,e){const r=[];if(!t.checkIdentifierLike())throw Error('Expected behavior name after "install"');const n=t.advance().value,s=t.previous();if(r.push(Ut(n,{start:s.start,end:s.end,line:s.line,column:s.column})),t.check("(")){t.advance();const n=[];for(;!t.isAtEnd()&&!t.check(")");){const e=t.savePosition();let r;if(t.checkIdentifierLike()){const n=t.peek().value;t.advance(),t.check(":")?(t.advance(),r=n):t.restorePosition(e)}const s=t.parseExpression();if(n.push(void 0!==r?{name:r,value:s}:{value:s}),t.check(","))t.advance();else if(!t.check(")"))break}if(!t.check(")"))throw Error('Expected ")" after behavior parameters');if(t.advance(),n.length>0){const s={start:e.start,end:t.getPosition().end,line:e.line,column:e.column};r.push(Zt(n.map(t=>({key:t.name?Ut(t.name,s):Ht("_positional","_positional",s),value:t.value})),s))}}return se.from(e).withArgs(...r).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseTransitionCommand(t){return function(t,e){const r=[],n={};let s=null;const i=t.peek();if(At(i)||"*"===i.value){let e="";t.check("*")&&(e="*",t.advance());const r=function(t){if(!t.checkIdentifierLike())return"";let e=t.advance().value;for(;t.check("-")&&!t.isAtEnd();)e+="-",t.advance(),t.checkIdentifierLike()&&(e+=t.advance().value);return e}(t);r&&(e+=r,s={type:"string",value:e,start:i.start||0,end:t.getPosition().end,line:i.line,column:i.column})}if(!s)throw Error("Transition command requires a CSS property");if(r.push(s),!t.check(h))throw Error('Expected "to" keyword after property in transition command');t.advance();const o=t.parsePrimary();if(n.to=o,t.check("over")){t.advance();const e=t.parsePrimary();n.over=e}if(t.check(d)){t.advance();const e=t.parsePrimary();n.with=e}return se.from(e).withArgs(...r).withModifiers(n).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseAddCommand(t){return function(t,e){const r=[];if(t.match("{"))r.push(t.parseCSSObjectLiteral());else{const e=te(t,[h]);e&&r.push(e)}if(t.check(h)){t.advance();const e=te(t);e&&r.push(e)}return se.from(e).withArgs(...r).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseIfCommand(t){return ae(this.getContext(),t)}parseRemoveCommand(t){return le(this.getContext(),t)}parseToggleCommand(t){return ue(this.getContext(),t)}parseRegularCommand(t){return pe(this.getContext(),t)}parseCall(){let t=this.parsePrimary();for(;;)if(this.match("("))t=this.finishCall(t);else if(this.match(".")){const e=this.consumeIdentifier("Expected property name after '.' - malformed member access");t=this.createMemberExpression(t,this.createIdentifier(e.value),0)}else if(this.match("[")){const e=this.parseExpression();this.consume("]","Expected ']' after array index"),t=this.createMemberExpression(t,e,1)}else{if(!this.check("'s"))break;{let e;this.advance(),this.check("*")?(this.advance(),e="*"+this.consumeIdentifier("Expected property name after * in CSS property syntax").value):e=Lt(this.peek())&&this.peek().value.startsWith("@")?this.advance().value:this.consumeIdentifier("Expected property name after possessive").value,t=this.createPossessiveExpression(t,this.createIdentifier(e))}}return t}parsePrimary(){if(this.check("*")){const t=this.current;if(this.advance(),!this.isAtEnd()&&At(this.peek())){const t=this.advance().value;return this.createSelector("*"+t)}this.current=t}if(this.check("*")||this.check("/")||this.check("%")||this.check("mod")){const t=this.peek();return this.addError(`Binary operator '${t.value}' requires a left operand`),this.createErrorNode()}if(this.matchNumber()){const t=parseFloat(this.previous().value);return this.createLiteral(t,this.previous().value)}if(this.matchString()){const t=this.previous().value;if(2>t.length||t.startsWith('"')&&!t.endsWith('"')||t.startsWith("'")&&!t.endsWith("'"))return this.addError("Unclosed string literal - string not properly closed"),this.createErrorNode();const e=t.slice(1,-1),r=this.processEscapeSequences(e);return this.createLiteral(r,t)}if(this.matchTemplateLiteral()){const t=this.previous();return{type:"templateLiteral",value:t.value,start:t.start||0,end:t.end||0,line:t.line,column:t.column}}if(this.matchBoolean()){const t=this.previous().value;let e;switch(t){case"true":e=1;break;case"false":e=0;break;case"null":e=null;break;case"undefined":e=void 0;break;default:e="true"===t}return this.createLiteral(e,t)}if(this.matchTimeExpression()){const t=this.previous().value;return this.createLiteral(t,t)}if(this.matchQueryReference()){const t=this.previous().value.slice(1,-2).trim();return this.createSelector(t)}if(this.matchSelector())return this.createSelector(this.previous().value);if(this.match("<"))return this.parseHyperscriptSelector();if(this.match("(")){if(this.isAtEnd())return this.addError("Expected expression inside parentheses"),this.createErrorNode();const t=this.parseExpression();return this.consume(")","Expected closing parenthesis ')' after expression - unclosed parentheses"),t}if(this.match("{"))return this.parseObjectLiteral();if(this.match("["))return this.parseAttributeOrArrayLiteral();if(this.check(":")){if(this.advance(),this.check(":")){this.advance();const t=this.advance();return{type:"identifier",name:t.value,scope:"global",start:t.start-2,end:t.end,line:t.line,column:t.column}}{const t=this.advance();return{type:"identifier",name:t.value,scope:"local",start:t.start-1,end:t.end,line:t.line,column:t.column}}}if(this.matchBasicOperator()){const t=this.previous();return this.createIdentifier(t.value)}const t=this.peek();if((!t||"end"!==t.value&&"else"!==t.value&&"then"!==t.value)&&(this.matchPredicate(Rt)||this.matchPredicate(Et)||this.matchPredicate(xt)||this.matchPredicate(bt)||this.matchPredicate(wt))){const t=this.previous();if("new"===t.value)return this.parseConstructorCall();if("on"===t.value)return this.parseEventHandler();if("if"===t.value)return this.parseConditional();if("closest"===t.value||"first"===t.value||"last"===t.value||"previous"===t.value||"next"===t.value){if(this.check("(")||this.checkCssSelector()||this.checkClassSelector()||this.checkIdSelector()||this.check("<")||this.checkQueryReference())return this.parseNavigationFunction(t.value);if(this.check(".")){const e=this.current;if(this.advance(),this.checkIdentifier()){const e=this.advance().value,r=this.createSelector("."+e);return this.createCallExpression(this.createIdentifier(t.value),[r])}this.current=e}if(this.check("#")){const e=this.current;if(this.advance(),this.checkIdentifier()){const e=this.advance().value,r=this.createSelector("#"+e);return this.createCallExpression(this.createIdentifier(t.value),[r])}this.current=e}return this.createIdentifier(t.value)}return"my"!==t.value||this.check(".")?"its"!==t.value||this.check(".")?"your"!==t.value||this.check(".")?"the"===t.value?this.parseTheXofY():this.createIdentifier(t.value):this.parseContextPropertyAccess("you"):this.parseContextPropertyAccess("it"):this.parseContextPropertyAccess("me")}if(this.match("$"))return this.parseDollarExpression();if(Lt(this.peek())&&this.peek().value.startsWith("@")){const t=this.advance();return{type:"attributeAccess",attributeName:t.value.substring(1),start:t.start,end:t.end,line:t.line,column:t.column}}const e=this.peek();return this.addError(`Unexpected token: ${e.value} at line ${e.line}, column ${e.column}`),this.advance(),this.createErrorNode()}parseDollarExpression(){if(this.checkNumber()){const t=this.advance().value;return this.createLiteral(t,"$"+t)}if(this.checkIdentifier()){const t=this.advance();let e=this.createIdentifier(t.value);for(;this.match(".");){if(!this.checkIdentifier())return this.addError("Expected property name after '.' in dollar expression"),this.createErrorNode();{const t=this.advance();e=this.createMemberExpression(e,this.createIdentifier(t.value),0)}}return{type:"dollarExpression",expression:e,raw:`$${t.value}${this.previous().value||""}`,line:t.line,column:t.column-1}}return this.addError("Expected identifier or number after '$'"),this.createErrorNode()}parseHyperscriptSelector(){let t="";for(;!this.check("/")&&!this.isAtEnd();)t+=this.advance().value;return this.consume("/","Expected '/' in hyperscript selector"),this.consume(">","Expected '>' after '/' in hyperscript selector"),this.createSelector(t)}parseObjectLiteral(){const t=[],e=this.getPosition();if(this.check("}"))return this.advance(),{type:"objectLiteral",properties:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column};do{let e;if(this.matchPredicate(Rt))e=this.createIdentifier(this.previous().value);else{if(!this.matchString())return this.addError("Expected property name in object literal"),this.createErrorNode();{const t=this.previous().value,r=t.slice(1,-1);e=this.createLiteral(r,t)}}this.consume(":","Expected ':' after property name in object literal");const r=this.parseExpression();if(t.push({key:e,value:r}),!this.match(","))break;if(this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after object literal properties"),{type:"objectLiteral",properties:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseCSSObjectLiteral(){const t=this.getPosition(),e=[];do{if(this.check("}"))break;let r;if(this.matchPredicate(Rt))r=this.createIdentifier(this.previous().value);else{if(!this.matchString())return this.addError("Expected CSS property name"),this.createErrorNode();{const t=this.previous().value,e=t.slice(1,-1);r=this.createLiteral(e,t)}}if(!this.consume(":","Expected ':' after CSS property name"))return this.createErrorNode();const n=[];let s=0,i=0;for(;!this.isAtEnd()&&(0!==i||!this.check(";")&&!this.check("}"));){const t=this.advance();n.push(t.value),"$"===t.value&&this.check("{")&&(s=1),"{"===t.value&&i++,"}"===t.value&&i--}const o=n.join(""),a=s?{type:"templateLiteral",value:o,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}:this.createLiteral(o,o);if(e.push({key:r,value:a}),this.check(";")&&this.advance(),this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after CSS object literal properties"),{type:"objectLiteral",properties:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseConstructorCall(){const t=this.previous();if(!this.checkIdentifier())return this.addError('Expected constructor name after "new"'),this.createErrorNode();const e=this.advance(),r=e.value;if(!this.check("("))return this.addError('Expected "(" after constructor name'),this.createErrorNode();if(this.advance(),this.check(")"))this.advance();else{let t=1;for(;t>0&&!this.isAtEnd();){const e=this.advance();"("===e.value&&t++,")"===e.value&&t--}}return{type:"callExpression",callee:{type:"identifier",name:r,start:e.start,end:e.end,line:e.line,column:e.column},arguments:[],isConstructor:1,start:t.start,end:this.previous().end,line:t.line,column:t.column}}parseTopLevelInitBlock(){const t=this.getPosition(),e=this.parseCommandBlock(["end"]);return this.consume("end","Expected 'end' after init block"),{type:"initBlock",commands:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseDefFeature(){const t=this.getPosition();let e="";if(!this.checkIdentifier())return this.addError("Expected function name after 'def'"),{type:"def",name:"",params:[],body:[],start:t.start,end:this.getPosition().end,line:t.line,column:t.column};for(e=this.advance().value;this.check(".");)this.advance(),this.checkIdentifier()&&(e+="."+this.advance().value);const r=[];if(this.check("(")){if(this.advance(),!this.check(")"))for(this.checkIdentifier()&&r.push(this.advance().value);this.check(",");)this.advance(),this.checkIdentifier()&&r.push(this.advance().value);this.consume(")","Expected ')' after parameter list")}const n=this.parseCommandBlock(["end","catch","finally"]);let s,i,o;return this.check("catch")&&(this.advance(),this.checkIdentifier()&&(s=this.advance().value),i=this.parseCommandBlock(["end","finally"])),this.check("finally")&&(this.advance(),o=this.parseCommandBlock(["end"])),this.consume("end","Expected 'end' after function definition"),{type:"def",name:e,params:r,body:n,...void 0!==s&&{errorSymbol:s},...void 0!==i&&{errorHandler:i},...void 0!==o&&{finallyHandler:o},start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseEventNameWithNamespace(t){let e;e=this.checkEvent()||this.checkIdentifier()||this.checkIsCommand()||this.checkIdentifierLike()?this.advance():this.consumeEvent(t);let r=e.value;return this.check(":")&&(this.advance(),r=`${r}:${this.advance().value}`),r}callExprToCommandNode(t,e){return{type:"command",name:t.callee.name,args:t.arguments,isBlocking:0,...void 0!==e.start&&{start:e.start},...void 0!==e.end&&{end:e.end},...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}}}createPseudoCommandNode(t,e,r,n,s){return{type:"command",name:"pseudo-command",args:[{type:"objectLiteral",properties:[{key:{type:"identifier",name:"methodName"},value:{type:"literal",value:t,raw:`"${t}"`}},{key:{type:"identifier",name:"methodArgs"},value:{type:"literal",value:e.arguments,raw:JSON.stringify(e.arguments)}},...r?[{key:{type:"identifier",name:"preposition"},value:{type:"literal",value:r,raw:`"${r}"`}}]:[],{key:{type:"identifier",name:"targetExpression"},value:n}]}],isBlocking:0,...void 0!==s.start&&{start:s.start},...void 0!==s.end&&{end:s.end},...void 0!==s.line&&{line:s.line},...void 0!==s.column&&{column:s.column}}}tryParsePseudoCommand(t,e){const r=t.callee.name,n=this.peek();if(!(ge.PSEUDO_COMMAND_PREPOSITIONS.includes(n.value.toLowerCase())||Rt(n)&&!this.isCommand(n.value)||xt(n)))return{node:this.callExprToCommandNode(t,e),isPseudo:0,targetFailed:0};let s,i;this.isCommand(r)&&this.addWarning({type:"command-shadow",message:`Method '${r}' shadows hyperscript command`,suggestions:[`Rename method to avoid confusion (e.g., '${r}Fn', 'my${r.charAt(0).toUpperCase()+r.slice(1)}')`,`Use 'call' command instead: call ${r}(...)`,"This works but may cause ambiguity"],severity:"warning",code:"PSEUDO_CMD_SHADOW",...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}}),ge.PSEUDO_COMMAND_PREPOSITIONS.includes(this.peek().value.toLowerCase())&&(s=this.advance().value.toLowerCase());try{i=this.parseExpression()}catch{return{node:this.callExprToCommandNode(t,e),isPseudo:0,targetFailed:1}}return{node:this.createPseudoCommandNode(r,t,s,i,e),isPseudo:1,targetFailed:0}}parseCommandWithErrorRecovery(){this.advance();const t=this.error;try{const e=this.parseCommand();return this.error&&this.error!==t&&(ft("⚠️ Command parsing added error, restoring error state. Error was:",this.error.message),this.error=t),e}catch(e){return ft("⚠️ Command parsing threw exception, restoring error state:",e instanceof Error?e.message:e+""),this.error=t,null}}parseEventHandler(){ft("🔧 parseEventHandler: ENTRY - parsing event handler");const t=[],e=this.parseEventNameWithNamespace("Expected event name after 'on'");for(t.push(e),ft("🔧 parseEventHandler: Parsed first event name: "+e);this.check("or");){this.advance(),ft("🔧 parseEventHandler: Found 'or', parsing additional event name");const e=this.parseEventNameWithNamespace("Expected event name after 'or'");t.push(e),ft("🔧 parseEventHandler: Parsed additional event name: "+e)}let r;if(ft("🔧 parseEventHandler: Total events parsed: "+t.join(", ")),this.registryIntegration){const e=t[0];if(this.registryIntegration.hasEventSource(e)){const t=this.registryIntegration.getEventSource(e);r=t?.name,ft(`🔧 parseEventHandler: Detected custom event source '${r}' for event '${e}'`)}}const n=[];if(this.match("(")){if(!this.check(")"))do{const t=this.advance();n.push(t.value)}while(this.match(","));this.consume(")","Expected ')' after event parameters"),ft("🔧 parseEventHandler: Parsed event parameters: "+n.join(", "))}const s={};for(;this.check(".");){this.advance();const t=this.advance().value.toLowerCase();if("once"===t)s.once=1,ft("🔧 parseEventHandler: Parsed modifier '.once'");else if("prevent"===t)s.prevent=1,ft("🔧 parseEventHandler: Parsed modifier '.prevent'");else if("stop"===t)s.stop=1,ft("🔧 parseEventHandler: Parsed modifier '.stop'");else if("debounce"===t||"throttle"===t){if(!this.check("("))throw Error(`Expected '(' after '.${t}'`);{this.advance();const e=this.advance(),r=parseInt(e.value,10);if(isNaN(r))throw Error(`Expected number for ${t} delay, got: ${e.value}`);"debounce"===t?(s.debounce=r,ft(`🔧 parseEventHandler: Parsed modifier '.debounce(${r})'`)):(s.throttle=r,ft(`🔧 parseEventHandler: Parsed modifier '.throttle(${r})'`)),this.consume(")",`Expected ')' after ${t} delay`)}}else ft(`🔧 parseEventHandler: Warning - unknown modifier '.${t}'`)}if(this.check("debounced")||this.check("throttled")){const t=this.advance().value.toLowerCase(),e="debounced"===t?"debounce":"throttle";if(this.match("at"))if(this.checkTimeExpression()){const r=this.advance(),n=(i=r.value).endsWith("ms")?parseInt(i,10):i.endsWith("seconds")||i.endsWith("s")?1e3*parseFloat(i):i.endsWith("minutes")?6e4*parseFloat(i):i.endsWith("hours")?36e5*parseFloat(i):i.endsWith("days")?864e5*parseFloat(i):parseInt(i,10);s[e]=n,ft(`🔧 parseEventHandler: Parsed '${t} at ${r.value}' (${n}ms)`)}else if(this.matchNumber()){const r=parseInt(this.previous().value,10);s[e]=r,ft(`🔧 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 i;let o,a,c,l;if(Object.keys(s).length>0&&ft("🔧 parseEventHandler: Parsed modifiers:",s),this.match("[")&&(o=this.parseExpression(),this.consume("]","Expected ']' after event condition")),this.match("from")){const t=this.advance();a=t.value,ft(`🔧 parseEventHandler: Parsed 'from' target: ${a} (kind: ${t.kind})`)}if(this.match("of")){const t=this.advance();c=t.value.startsWith("@")?t.value.substring(1):t.value,ft("🔧 parseEventHandler: Parsed attribute name: "+c)}this.match("in")&&(ft("🔧 parseEventHandler: Found 'in' keyword, parsing watch target"),l=this.parseExpression(),ft("🔧 parseEventHandler: Parsed watch target expression"));const u=[];for(ft(`✅ parseEventHandler: About to parse commands, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd: ${this.isAtEnd()}`);!this.isAtEnd();){if(ft(`✅ parseEventHandler: Loop iteration, current token: ${this.peek().value}, kind: ${this.peek().kind}`),this.check("on")){ft("✅ parseEventHandler: Stopping command parsing, found next event handler 'on'");break}if(this.checkComment())ft("✅ parseEventHandler: Skipping comment token: "+this.peek().value),this.advance();else{if(this.check("end")){ft("✅ parseEventHandler: Stopping command parsing, found 'end' keyword"),this.advance();break}if(this.checkIsCommand()){const t="("===this.tokens[this.current+1]?.value,e=this.peek().value.toLowerCase();if(t&&"js"!==e&&"tell"!==e){let t;const e=this.error;try{t=this.parseExpression()}catch(t){this.error=e,this.advance();const r=this.parseCommand();u.push(r);continue}if(t&&"callExpression"===t.type){const e=this.tryParsePseudoCommand(t,t);if(u.push(e.node),e.isPseudo||e.targetFailed)continue}}else{const t=this.parseCommandWithErrorRecovery();t&&(u.push(t),ft("✅ parseEventHandler: Parsed command, next token: "+(this.isAtEnd()?"END":this.peek().value)))}}else{if(!this.checkIdentifier())break;{const t=this.peek();if(this.isCommand(t.value)){const t=this.parseCommandWithErrorRecovery();t&&u.push(t)}else{let t;const e=this.error;try{t=this.parseExpression()}catch(t){ft("⚠️ Expression parsing error, restoring error state:",t instanceof Error?t.message:t+""),this.error=e;break}if(t&&"callExpression"===t.type){const e=this.tryParsePseudoCommand(t,t);if(u.push(e.node),e.targetFailed)continue}else{if(!t||"binaryExpression"!==t.type||" "!==t.operator)break;{const e=t;if(!e.left||"identifier"!==e.left.type||!this.isCommand(e.left.name))break;{const r={type:"command",name:e.left.name,args:[e.right],isBlocking:0,...void 0!==t.start&&{start:t.start},...void 0!==t.end&&{end:t.end},...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}};u.push(r)}}}}}}for(;!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(",")||this.check("on"));)this.advance();if(!this.match("then","and",",")&&!this.checkIsCommand()&&!this.isCommand(this.peek().value))break}}const h=this.getPosition(),f={type:"eventHandler",event:1===t.length?t[0]:t.join("|"),events:t,commands:u,...n.length>0&&{params:n},...o&&{condition:o},...a&&{target:a},...c&&{attributeName:c},...l&&{watchTarget:l},...r&&{customEventSource:r},...Object.keys(s).length>0&&{modifiers:s},start:h.start,end:h.end,line:h.line,column:h.column};return ft(`🔧 parseEventHandler: Created node with events: ${t.join(", ")}, attributeName: ${c||"none"}, watchTarget: ${l?"yes":"none"}`),f}parseBehaviorDefinition(){const t=this.getPosition(),e=this.consumeIdentifier("Expected behavior name after 'behavior' keyword").value;/^[A-Z]/.test(e)||this.addError(`Behavior name must start with uppercase letter (got "${e}")`);const r=[];if(this.match("(")){if(!this.check(")"))do{const t=this.consumeIdentifierLike("Expected parameter name");r.push(t.value)}while(this.match(","));this.consume(")","Expected ')' after behavior parameters")}const n=new Set(r),s=[];let i;for(;!this.isAtEnd()&&!this.check("end");)if(this.match("on")){const t=this.getPosition(),e=this.peek().value;this.advance();const r=[];if(this.check("(")){for(this.advance();!this.isAtEnd()&&!this.check(")");){const t=this.peek();Rt(t)?(r.push(t.value),this.advance(),this.check(",")&&this.advance()):this.advance()}this.check(")")&&this.advance()}let i;if(this.check("from")){this.advance();const t=[];if(this.check("the")&&this.advance(),!this.isAtEnd()){const e=this.peek(),r=n.has(e.value);this.checkIsCommand()&&!r||(t.push(e.value),i=e.value,this.advance())}}const o=[];for(;!this.isAtEnd()&&!this.check("end");){if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){this.check("end")||this.addError("Unexpected token in event handler: "+this.peek().value);break}{this.advance();const t=this.error;try{const e=this.parseCommand();for(this.error&&this.error!==t&&(this.error=t),o.push(e);!(this.isAtEnd()||this.check("end")||this.checkIsCommand()||this.isCommand(this.peek().value));)this.advance()}catch(e){this.error=t;break}}}const a={type:"eventHandler",event:e,commands:o,...void 0!==i&&{target:i},...r.length>0&&{args:r},start:t.start,end:this.getPosition().end,line:t.line,column:t.column};s.push(a),this.consume("end","Expected 'end' after event handler body")}else{if(!this.match("init")){this.addError("Unexpected token in behavior body: "+this.peek().value);break}i={type:"initBlock",commands:this.parseCommandBlock(["end"]),start:t.start,end:this.getPosition().end,line:t.line,column:t.column},this.consume("end","Expected 'end' after init block")}return this.consume("end","Expected 'end' to close behavior definition"),{type:"behavior",name:e,parameters:r,eventHandlers:s,...void 0!==i?{initBlock:i}:{},start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseCommandSequence(){const t=[];for(;!this.isAtEnd();){if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){this.advance();const e=this.error,r=this.parseCommand();for(this.error&&this.error!==e&&(this.error.message.includes("Expected closing parenthesis")||this.error.message.includes("Expected ')'")||this.error.message.includes("unclosed parenthes")||this.error.message.includes("Unclosed parenthes")||(ft("⚠️ parseCommandSequence: Command parsing added non-critical error, restoring error state. Error was:",this.error.message),this.error=e)),t.push(r);!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("on"));)ft("⚠️ parseCommandSequence: Skipping unexpected token:",this.peek().value),this.advance();if(this.check("on")){ft('✅ parseCommandSequence: Found "on" token, stopping command sequence to allow event handler parsing');break}if(this.match("then"))continue;if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value))continue;break}this.addError("Expected command, got: "+this.peek().value);break}return 1===t.length?t[0]:function(t){return{type:"CommandSequence",commands:t,start:t[0]?.start||0,end:t[t.length-1]?.end||0,line:t[0]?.line||1,column:t[0]?.column||1}}(t)}getMultiWordPattern(t){return function(t){return Xt.find(e=>e.command===t.toLowerCase())||null}(t)}isTokenKeyword(t,e){return Yt(t,e)}parseMultiWordCommand(t,e){return function(t,e,r){const n=t.getMultiWordPattern(r);if(!n)return null;const s=[],i={};for(;!Qt(t,["catch","finally",...n.keywords])&&!Yt(t.peek(),n.keywords);){const e=t.parsePrimary();if(!e)break;if(s.push(e),!t.match(",")&&Yt(t.peek(),n.keywords))break}for(;!t.isAtEnd()&&Yt(t.peek(),n.keywords);){const e=t.advance().value,r=t.parseExpression();if(r&&(i[e]=r),!Yt(t.peek(),n.keywords))break}const o=se.from(e).withArgs(...s).endingAt(t.getPosition());return Object.keys(i).length>0&&o.withModifiers(i),o.build()}(this.getContext(),t,e)}parseCommandBlock(t){const e=[];for(;!this.isAtEnd()&&!t.some(t=>this.check(t));)if(this.checkComment())this.advance();else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value))break;{this.advance();const t=this.parseCommand();e.push(t)}}return e}trySemanticParse(t){if(!this.semanticAdapter||!this.semanticAdapter.isAvailable())return null;try{const e=this.semanticAdapter.trySemanticParse(t);return e.success&&e.node?(ft(`[Semantic] Successfully parsed with confidence ${e.confidence}:`,e.node.name),e.node):(ft(`[Semantic] Low confidence (${e.confidence}), falling back to traditional parser`),null)}catch(t){return ft("[Semantic] Error during semantic parse:",t),null}}getRemainingInput(){if(!this.originalInput)return this.tokens.slice(this.current>0?this.current-1:0).map(t=>t.value).join(" ");const t=this.current>0?this.tokens[this.current-1]:this.tokens[0];return t&&void 0!==t.start?this.originalInput.slice(t.start):this.originalInput}skipToCommandBoundary(){const t=["then","and","else","end"];for(;!this.isAtEnd();){const e=this.peek(),r=e.value.toLowerCase();if(t.includes(r))break;if(bt(e))break;this.advance()}}parseCommand(){const t=this.previous();let e=t.value;if(this.semanticAdapter&&!["install","wait","repeat","for","set","put","increment","decrement","add","if","unless","make","measure","trigger","halt","remove","exit","return","closest","js","tell"].includes(e.toLowerCase())){const t=this.getRemainingInput(),e=this.trySemanticParse(t);if(e)return this.skipToCommandBoundary(),e}if("beep"===e&&this.check("!")&&(this.advance(),e="beep!"),"fetch"===e)return function(t,e){const r={};let n=null;if(!t.isAtEnd()&&t.check("/")&&(n=function(t){const e=t.savePosition();let r="";for(;!t.isAtEnd()&&!me(t);)r+=t.advance().value;return r&&"/"!==r?{type:"literal",value:r,raw:r,start:e,end:t.savePosition()}:(t.restorePosition(e),null)}(t)),n||(n=t.parsePrimary()),!n)return t.addError("fetch requires a URL"),se.from(e).endingAt(t.getPosition()).build();!t.isAtEnd()&&t.check("{")&&(r.with=t.parsePrimary());for(let e=0;2>e&&!t.isAtEnd();e++)if(!t.check("as")||r.as){if(!t.check("with")||r.with)break;t.advance(),r.with=ye(t)?ve(t):t.parsePrimary()}else t.advance(),t.isAtEnd()||ne(t,"a")||ne(t,"an"),r.as=t.parsePrimary();const s=se.from(e).withArgs(n).endingAt(t.getPosition());return Object.keys(r).length>0&&s.withModifiers(r),s.build()}(this.getContext(),t);const r=this.parseMultiWordCommand(t,e);if(r)return r;const n=e.toLowerCase();if("repeat"===n)return this.parseRepeatCommand(t);if("for"===n)return this.parseForCommand(t);if("if"===n||"unless"===n)return this.parseIfCommand(t);if("wait"===n)return this.parseWaitCommand(t);if("install"===n)return this.parseInstallCommand(t);if("transition"===n)return this.parseTransitionCommand(t);if("add"===n)return this.parseAddCommand(t);if(this.isCompoundCommand(n))return this.parseCompoundCommand({type:"identifier",name:n,start:t.start||0,end:t.end||0,line:t.line,column:t.column})||this.createErrorNode();const s=[];if(("increment"===e||"decrement"===e)&&!this.isAtEnd())return function(t,e){const r=e.value,n="increment"===r?"+":"-";let s=0;t.check(g)&&(s=1,t.advance());const i=t.parseExpression();if(!i)throw Error("Expected variable or expression after "+r);let o;if(t.check("by")){t.advance();const e=t.parseExpression();if(!e)throw Error(`Expected amount after 'by' in ${r} command`);o=e}else o=Ht(1,"1",{start:e.start,end:t.previous().end,line:e.line,column:e.column});let a=i;s&&"identifier"===i.type&&(a={...i,scope:"global"});const c={start:e.start,end:t.previous().end,line:e.line,column:e.column},l=Wt(n,i,o,c),u=[a,Ut(h,c),l];return se.from(e).withName("set").withArgs(...u).withOriginalCommand(r).endingAt({end:t.previous().end}).build()}(this.getContext(),t);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.check("end")||this.checkIsCommand());){const t=this.parseExpression();if(s.push(t||this.parsePrimary()),this.match(","))continue;const e=["into","from","to","with","by","at","before","after","over"];if(e.some(t=>this.check(t)))continue;const r=s[s.length-1];if(!r||"identifier"!==r.type&&"keyword"!==r.type||!e.includes(r.name??r.value))break}const i=this.getPosition();return{type:"command",name:e,args:s,isBlocking:0,start:i.start,end:i.end,line:i.line,column:i.column}}parseConditional(){const t=this.parseExpression();this.consume("then","Expected 'then' after if condition");const e=this.parseConditionalBranch();let r;this.match("else")&&(r=this.parseConditionalBranch());const n=this.getPosition();return{type:"conditionalExpression",test:t,consequent:e,alternate:r,start:n.start,end:n.end,line:n.line,column:n.column}}parseConditionalBranch(){if(this.checkIsCommand()){const t=this.advance(),e=this.createIdentifier(t.value);return this.createCommandFromIdentifier(e)||e}if(this.checkIdentifier()||this.checkKeyword()){const t=this.peek();if(this.isCommand(t.value)){const t=this.advance(),e=this.createIdentifier(t.value);return this.createCommandFromIdentifier(e)||e}}return this.parseExpression()}parseNavigationFunction(t){const e=[];if(this.match("of"))e.push(this.parseExpression());else{if(this.check("("))return this.finishCall(this.createIdentifier(t));this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||e.push(this.parsePrimary())}return this.createCallExpression(this.createIdentifier(t),e)}parseTheXofY(){if(!this.checkIdentifier())return this.createIdentifier("the");const t=this.peek(),e=t.value;return["first","last","next","previous","random","closest"].includes(e)?(this.advance(),this.parseNavigationFunction(e)):(this.advance(),this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:e},target:this.parsePrimary(),line:t.line,column:t.column}):this.createIdentifier(e))}parseContextPropertyAccess(t){if("me"===t&&this.match("*")){let e="";if(!this.checkIdentifier())return this.addError("Expected property name after 'my *'"),this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(""),0);for(e=this.advance().value;this.check("-")&&!this.isAtEnd();){if(e+="-",this.advance(),!this.checkIdentifier()){this.addError("Expected identifier after hyphen in CSS property name");break}e+=this.advance().value}const r="computed-"+e;return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(r),0)}{if(Lt(this.peek())&&this.peek().value.startsWith("@")){const e=this.advance();return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(e.value),0)}const e=this.consumeIdentifier(`Expected property name after '${{me:"my",it:"its",you:"your"}[t]}'`);return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(e.value),0)}}parseMyPropertyAccess(){return this.parseContextPropertyAccess("me")}finishCall(t){const e=[];if(!this.check(")"))do{if(this.check(","))return this.addError("Unexpected token in function arguments"),this.createCallExpression(t,[this.createErrorNode()]);e.push(this.parseExpression())}while(this.match(","));if(!this.check(")")&&"identifier"===t.type){const e=t.name;N.has(e.toLowerCase())&&ft(`💡 Tip: CSS functions like ${e}() should be quoted for clean parsing. Use '${e}(...)' or \`${e}(...)\` instead.`)}return this.consume(")","Expected ')' after arguments"),this.createCallExpression(t,e)}createLiteral(t,e){return Ht(t,e,this.getPosition())}createIdentifier(t){return Ut(t,this.getPosition())}createBinaryExpression(t,e,r){return Wt(t,e,r,this.getPosition())}createUnaryExpression(t,e,r){return function(t,e,r,n){return{type:"unaryExpression",operator:t,argument:e,prefix:r,start:n.start,end:n.end,line:n.line,column:n.column}}(t,e,r,this.getPosition())}createCallExpression(t,e){return function(t,e,r){return{type:"callExpression",callee:t,arguments:e,start:r.start,end:r.end,line:r.line,column:r.column}}(t,e,this.getPosition())}createMemberExpression(t,e,r){return function(t,e,r,n){return{type:"memberExpression",object:t,property:e,computed:r,start:n.start,end:n.end,line:n.line,column:n.column}}(t,e,r,this.getPosition())}createSelector(t){return function(t,e){return{type:"selector",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}(t,this.getPosition())}createPossessiveExpression(t,e){return function(t,e,r){return{type:"possessiveExpression",object:t,property:e,start:r.start,end:r.end,line:r.line,column:r.column}}(t,e,this.getPosition())}createErrorNode(){return{type:"identifier",name:"__ERROR__",start:(t=this.getPosition()).start,end:t.end,line:t.line,column:t.column};var t}processEscapeSequences(t){return t.replace(/\\(.)/g,(t,e)=>{switch(e){case"n":return"\n";case"t":return"\t";case"r":return"\r";case"b":return"\b";case"f":return"\f";case"v":return"\v";case"0":return"\0";case"\\":return"\\";case'"':return'"';case"'":return"'";default:return e}})}createProgramNode(t){return function(t){if(ft(`✅ createProgramNode: Called with ${t.length} statements`),0===t.length)return ft("✅ createProgramNode: Returning error node (0 statements)"),{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===t.length)return ft(`✅ createProgramNode: Returning single statement (type=${t[0].type})`),t[0];const e={type:"Program",statements:t,start:t[0]?.start||0,end:t[t.length-1]?.end||0,line:t[0]?.line||1,column:t[0]?.column||1};return ft(`✅ createProgramNode: Returning Program node with ${t.length} statements, type=${e.type}`),e}(t)}match(...t){for(const e of t)if(this.check(e))return this.advance(),1;return 0}matchOperator(t){if(this.isAtEnd())return 0;const e=this.peek();return Ft(e)&&e.value===t?(this.advance(),1):0}check(t){if(this.isAtEnd())return 0;const e=this.peek().value;return this.resolveKeyword(e)===t}checkPredicate(t){return this.isAtEnd()?0:t(this.peek())}matchPredicate(t){return this.checkPredicate(t)?(this.advance(),1):0}checkSelector(){return this.checkPredicate(Ct)}matchSelector(){return this.matchPredicate(Ct)}checkAnySelector(){return this.checkPredicate(St)}checkLiteral(){return this.checkPredicate(Nt)}checkIdentifierLike(){return this.checkPredicate(At)}checkIsCommand(){return this.checkPredicate(bt)}checkCommandTerminator(){return this.checkPredicate(qt)}checkReference(){return this.checkPredicate(Tt)}checkTimeExpression(){return this.checkPredicate(Ot)}checkEvent(){return this.checkPredicate(wt)}checkContextVar(){return this.checkPredicate(xt)}checkComment(){return this.checkPredicate($t)}checkIdentifier(){return this.checkPredicate(Rt)}checkKeyword(){return this.checkPredicate(Et)}checkString(){return this.checkPredicate(It)}matchString(){return this.matchPredicate(It)}checkNumber(){return this.checkPredicate(jt)}matchNumber(){return this.matchPredicate(jt)}checkBoolean(){return this.checkPredicate(Dt)}matchBoolean(){return this.matchPredicate(Dt)}checkTemplateLiteral(){return this.checkPredicate(Mt)}matchTemplateLiteral(){return this.matchPredicate(Mt)}checkQueryReference(){return this.checkPredicate(Pt)}matchQueryReference(){return this.matchPredicate(Pt)}checkIdSelector(){return this.checkPredicate(Vt)}checkClassSelector(){return this.checkPredicate(Bt)}checkCssSelector(){return this.checkPredicate(_t)}checkBasicOperator(){return this.checkPredicate(Ft)}matchBasicOperator(){return this.matchPredicate(Ft)}matchTimeExpression(){return this.matchPredicate(Ot)}matchIdentifierLike(){return this.matchPredicate(At)}matchComparisonOperator(){return this.matchPredicate(kt)}consumePredicate(t,e){return this.checkPredicate(t)?this.advance():(this.addError(e),this.peek())}consumeIdentifier(t){return this.consumePredicate(Rt,t)}consumeIdentifierLike(t){return this.consumePredicate(At,t)}consumeEvent(t){return this.consumePredicate(wt,t)}advance(){return this.isAtEnd()||this.current++,this.previous()}isAtEnd(){return this.current>=this.tokens.length}peek(){return this.isAtEnd()?{kind:"unknown",value:"",start:0,end:0,line:1,column:1}:this.tokens[this.current]}previous(){return this.tokens[this.current-1]}consume(t,e){return this.check(t)?this.advance():(this.addError(e),this.peek())}addError(t){const e=this.peek();let r=e.start||0,n=e.line||1,s=e.column||1;if(t.includes("property name after '.'")){const t=this.current>0?this.previous():e;r=t.end||t.start||0,n=t.line||1,s=t.column||1}if(t.includes("parenthes")){const t=this.current>0?this.previous():e;r=t.end||t.start||0,n=t.line||1,s=t.column||1,0===r&&this.current>0&&(r=this.current)}if(t.includes("Expected expression after")){const t=this.current>0?this.previous():e;r=t.start||0,n=t.line||1,s=t.column||1,0===r&&(r=Math.max(1,this.current-1))}if(t.includes("Missing operand")){let t=e;for(let e=this.current-1;e>=0;e--){const r=this.tokens[e];if(r&&("+"===r.value||"-"===r.value)){t=r;break}}r=t.start||0,n=t.line||1,s=t.column||1}this.error={message:t,line:Math.max(1,n),column:Math.max(1,s),position:Math.max(0,r)}}parseAttributeOrArrayLiteral(){const t=this.previous().start,e=this.previous().line,r=this.previous().column;if(!this.isAtEnd()&&this.peek().value.startsWith("@")){const n=[];for(;!this.check("]")&&!this.isAtEnd();){const t=this.advance();n.push(t.value)}this.consume("]","Expected ']' after attribute literal");const s="["+n.join("")+"]";return{type:"literal",value:s,raw:s,start:t,end:this.previous().end,line:e,column:r}}const n=[];if(!this.check("]"))do{if(this.check("]"))break;n.push(this.parseExpression())}while(this.match(","));return this.consume("]","Expected ']' after array elements"),{type:"arrayLiteral",elements:n,start:t,end:this.previous().end,line:e,column:r}}getPosition(){const t=this.current>0?this.previous():this.peek();return{start:t.start||0,end:t.end||0,line:t.line||1,column:t.column||1}}getContext(){const t=this,e={tokens:this.tokens,advance:this.advance.bind(this),peek:this.peek.bind(this),previous:this.previous.bind(this),consume:this.consume.bind(this),check:this.check.bind(this),checkIdentifierLike:this.checkIdentifierLike.bind(this),checkSelector:this.checkSelector.bind(this),checkAnySelector:this.checkAnySelector.bind(this),checkLiteral:this.checkLiteral.bind(this),checkReference:this.checkReference.bind(this),checkTimeExpression:this.checkTimeExpression.bind(this),checkEvent:this.checkEvent.bind(this),checkIsCommand:this.checkIsCommand.bind(this),checkContextVar:this.checkContextVar.bind(this),match:this.match.bind(this),matchOperator:this.matchOperator.bind(this),isAtEnd:this.isAtEnd.bind(this),createIdentifier:this.createIdentifier.bind(this),createLiteral:this.createLiteral.bind(this),createSelector:this.createSelector.bind(this),createBinaryExpression:this.createBinaryExpression.bind(this),createUnaryExpression:this.createUnaryExpression.bind(this),createMemberExpression:this.createMemberExpression.bind(this),createPossessiveExpression:this.createPossessiveExpression.bind(this),createCallExpression:this.createCallExpression.bind(this),createErrorNode:this.createErrorNode.bind(this),createProgramNode:this.createProgramNode.bind(this),createCommandFromIdentifier:this.createCommandFromIdentifier.bind(this),parseExpression:this.parseExpression.bind(this),parsePrimary:this.parsePrimary.bind(this),parseCall:this.parseCall.bind(this),parseAssignment:this.parseAssignment.bind(this),parseLogicalOr:this.parseLogicalOr.bind(this),parseLogicalAnd:this.parseLogicalAnd.bind(this),parseEquality:this.parseEquality.bind(this),parseComparison:this.parseComparison.bind(this),parseAddition:this.parseAddition.bind(this),parseMultiplication:this.parseMultiplication.bind(this),parseImplicitBinary:this.parseImplicitBinary.bind(this),parseConditional:this.parseConditional.bind(this),parseConditionalBranch:this.parseConditionalBranch.bind(this),parseEventHandler:this.parseEventHandler.bind(this),parseBehaviorDefinition:this.parseBehaviorDefinition.bind(this),parseNavigationFunction:this.parseNavigationFunction.bind(this),parseMyPropertyAccess:this.parseMyPropertyAccess.bind(this),parseDollarExpression:this.parseDollarExpression.bind(this),parseHyperscriptSelector:this.parseHyperscriptSelector.bind(this),parseAttributeOrArrayLiteral:this.parseAttributeOrArrayLiteral.bind(this),parseObjectLiteral:this.parseObjectLiteral.bind(this),parseCSSObjectLiteral:this.parseCSSObjectLiteral.bind(this),parseCommand:this.parseCommand.bind(this),parseCommandSequence:this.parseCommandSequence.bind(this),parseCommandListUntilEnd:this.parseCommandListUntilEnd.bind(this),getPosition:this.getPosition.bind(this),addError:this.addError.bind(this),addWarning:this.addWarning.bind(this),isCommand:this.isCommand.bind(this),isCompoundCommand:this.isCompoundCommand.bind(this),isKeyword:this.isKeyword.bind(this),getMultiWordPattern:this.getMultiWordPattern.bind(this),resolveKeyword:this.resolveKeyword.bind(this),savePosition:()=>t.current,restorePosition:e=>{t.current=e},peekAt:e=>{const r=t.current+e;return r>=0&&t.tokens.length>r?t.tokens[r]:null},getInputSlice:(t,e)=>this.originalInput?0>t||t>=this.originalInput.length?"":void 0!==e?this.originalInput.slice(t,e):this.originalInput.slice(t):""};return Object.defineProperty(e,"current",{get:()=>t.current,set:e=>{t.current=e},enumerable:1,configurable:1}),e}}function be(t,e){const r=function(t){const e={input:"",position:0,line:1,column:1,tokens:[]};e.input=t;const r=t.length;for(;r>e.position&&(F(e),r>e.position);){const r=t[e.position];if("-"!==r||"-"!==B(e,1))if('"'!==r){if("'"===r||"'"===r){const t=B(e,1),r=e.tokens[e.tokens.length-1];if("s"!==t||!r||r.kind!==I.IDENTIFIER&&r.kind!==I.SELECTOR&&"]"!==r.value&&")"!==r.value&&"}"!==r.value)W(e);else{const t=e.position;_(e),_(e),q(e,j.OPERATOR,"'s",t)}continue}if("`"!==r)if("<"!==r)if("#"!==r){if("."===r){if("."===B(e,1)){const t=e.position;_(e),_(e),q(e,j.OPERATOR,"..",t);continue}const t=e.tokens[e.tokens.length-1],r=new Set(["from","to","into","on","in","at","first","last","next","previous","closest","random"]),n=t&&t.kind===I.IDENTIFIER&&w.has(t.value.toLowerCase()),s=t&&t.kind===I.IDENTIFIER&&r.has(t.value.toLowerCase());if((!t||t.kind===I.OPERATOR&&")"!==t.value&&"]"!==t.value||n||s||"("===t.value||"["===t.value||"{"===t.value||","===t.value||";"===t.value)&&tt(B(e))){J(e);continue}}if("@"!==r)if("{"!==r)if("}"!==r){if("["===r){const t=e.tokens[e.tokens.length-1],r=t&&(t.kind===j.EVENT||t.kind===j.IDENTIFIER&&$.has(t.value))&&e.tokens.length>=2&&"on"===e.tokens[e.tokens.length-2]?.value;(!t||t.kind!==j.IDENTIFIER&&t.kind!==j.CONTEXT_VAR&&")"!==t.value&&"]"!==t.value||r)&&r?(q(e,j.SYMBOL,"["),_(e)):(q(e,j.OPERATOR,"["),_(e));continue}if("]"!==r){if("$"===r){const t=B(e,1);if(t>="a"&&"z">=t||t>="A"&&"Z">=t||"_"===t){Q(e);continue}}nt(r)?X(e):"0">r||r>"9"?("a">r||r>"z")&&("A">r||r>"Z")&&"_"!==r?(q(e,j.UNKNOWN,r),_(e)):K(e):Y(e)}else q(e,j.OPERATOR,"]"),_(e)}else q(e,j.OPERATOR,"}"),_(e);else q(e,j.OPERATOR,"{"),_(e);else G(e)}else J(e);else rt(e)?Z(e):X(e);else z(e)}else W(e);else U(e)}return e.tokens}(t);return new ge(r,e,t).parse()}ge.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty"]),ge.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];class Ee{constructor(){this.hooks=new Map,this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}register(t,e){this.unregister(t),this.hooks.set(t,e),e.beforeExecute&&this.beforeExecuteHooks.push(e.beforeExecute),e.afterExecute&&this.afterExecuteHooks.push(e.afterExecute),e.onError&&this.onErrorHooks.push(e.onError),e.interceptCommand&&this.interceptCommandHooks.push(e.interceptCommand)}unregister(t){const e=this.hooks.get(t);if(!e)return 0;if(e.beforeExecute){const t=this.beforeExecuteHooks.indexOf(e.beforeExecute);t>-1&&this.beforeExecuteHooks.splice(t,1)}if(e.afterExecute){const t=this.afterExecuteHooks.indexOf(e.afterExecute);t>-1&&this.afterExecuteHooks.splice(t,1)}if(e.onError){const t=this.onErrorHooks.indexOf(e.onError);t>-1&&this.onErrorHooks.splice(t,1)}if(e.interceptCommand){const t=this.interceptCommandHooks.indexOf(e.interceptCommand);t>-1&&this.interceptCommandHooks.splice(t,1)}return this.hooks.delete(t)}has(t){return this.hooks.has(t)}async runBeforeExecute(t){for(const e of this.beforeExecuteHooks)await e(t)}async runAfterExecute(t,e){for(const r of this.afterExecuteHooks)await r(t,e)}async runOnError(t,e){let r=e;for(const e of this.onErrorHooks){const n=await e(t,r);n instanceof Error&&(r=n)}return r}shouldIntercept(t,e){for(const r of this.interceptCommandHooks)if(r(t,e))return 1;return 0}getRegisteredNames(){return Array.from(this.hooks.keys())}clear(){this.hooks.clear(),this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}}function we(t){return t instanceof Error&&("isHalt"in t||"isExit"in t||"isBreak"in t||"isContinue"in t||"isReturn"in t)?t:null}function xe(t){return{ok:1,value:t}}function ke(t){return{ok:0,error:t}}function Ae(t){return 1==t.ok}class Se{constructor(t){this.elementCleanups=new WeakMap,this.elementCount=0,this.typeCounts={listener:0,observer:0,interval:0,timeout:0,custom:0},this.globalCleanups=[],this.debugMode=t?.debug??0}registerListener(t,e,r,n,s){this.addCleanup(t,{type:"listener",target:e,eventName:r,cleanup:()=>{e.removeEventListener(r,n,s),this.debugMode&&pt(`CleanupRegistry: Removed listener '${r}'`)},description:r+" listener"})}registerObserver(t,e){this.addCleanup(t,{type:"observer",cleanup:()=>{e.disconnect(),this.debugMode&&pt("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(t,e){this.addCleanup(t,{type:"interval",cleanup:()=>{clearInterval(e),this.debugMode&&pt("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(t,e){this.addCleanup(t,{type:"timeout",cleanup:()=>{clearTimeout(e),this.debugMode&&pt("CleanupRegistry: Cleared timeout")},description:"Timeout"})}registerCustom(t,e,r){this.addCleanup(t,{type:"custom",cleanup:e,description:r||"Custom cleanup"})}registerGlobal(t,e="custom",r){this.globalCleanups.push({type:e,cleanup:t,description:r||"Global cleanup"}),this.debugMode&&pt("CleanupRegistry: Registered global cleanup: "+(r||e))}addCleanup(t,e){const r=this.elementCleanups.get(t);r?r.push(e):(this.elementCleanups.set(t,[e]),this.elementCount++),this.typeCounts[e.type]++,this.debugMode&&pt(`CleanupRegistry: Registered ${e.type} for element`,t)}cleanupElement(t){const e=this.elementCleanups.get(t);if(!e||0===e.length)return 0;let r=0;for(const t of e){try{t.cleanup(),r++}catch(t){this.debugMode&&pt("CleanupRegistry: Error during cleanup:",t)}this.typeCounts[t.type]--}return this.elementCleanups.delete(t),this.elementCount--,this.debugMode&&pt(`CleanupRegistry: Cleaned up ${r} resources for element`),r}cleanupElementTree(t){let e=this.cleanupElement(t);const r=t.querySelectorAll("*");for(const t of r)e+=this.cleanupElement(t);return e}cleanupGlobal(){let t=0;for(const e of this.globalCleanups)try{e.cleanup(),t++}catch(t){this.debugMode&&pt("CleanupRegistry: Error during global cleanup:",t)}return this.globalCleanups=[],this.debugMode&&pt(`CleanupRegistry: Cleaned up ${t} global resources`),t}cleanupAll(){return this.cleanupGlobal()}hasCleanups(t){const e=this.elementCleanups.get(t);return void 0!==e&&e.length>0}getCleanupCount(t){const e=this.elementCleanups.get(t);return e?.length??0}getStats(){let t=0,e=0,r=0,n=0,s=0;for(const i of this.globalCleanups)switch(i.type){case"listener":t++;break;case"observer":e++;break;case"interval":r++;break;case"timeout":n++;break;case"custom":s++}return{elementsTracked:this.elementCount,listeners:this.typeCounts.listener+t,observers:this.typeCounts.observer+e,intervals:this.typeCounts.interval+r,timeouts:this.typeCounts.timeout+n,custom:this.typeCounts.custom+s,global:this.globalCleanups.length}}setDebugMode(t){this.debugMode=t}}const Ce=new Map;function Ne(t,e){return{me:t??null,it:null,you:null,result:null,locals:new Map,globals:e||Ce,flags:{halted:0,breaking:0,continuing:0,returning:0,async:0}}}class Te{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(t,e){const r=t.toLowerCase();this.sources.has(r)&&console.warn("[EventSourceRegistry] Overwriting existing event source: "+t),this.sources.set(r,e)}unregister(t){const e=t.toLowerCase(),r=this.sources.get(e);if(r){for(const[t,r]of this.subscriptions.entries())r.source===e&&(r.unsubscribe(),this.subscriptions.delete(t));return r.destroy?.(),this.sources.delete(e)}return 0}get(t){return this.sources.get(t.toLowerCase())}has(t){return this.sources.has(t.toLowerCase())}subscribe(t,e,r){const n=this.get(t);if(!n)return void console.warn("[EventSourceRegistry] Unknown event source: "+t);n.initialize?.();const s=n.subscribe(e,r);return this.subscriptions.set(s.id,s),s}unsubscribe(t){const e=this.subscriptions.get(t);return e?(e.unsubscribe(),this.subscriptions.delete(t)):0}getSourceNames(){return Array.from(this.sources.keys())}getSubscriptions(){return Array.from(this.subscriptions.values())}findSourceForEvent(t){for(const[e,r]of this.sources.entries())if(r.supports?.(t)??r.supportedEvents?.includes(t))return e}generateId(){return`sub_${this.nextId++}_${Date.now().toString(36)}`}destroy(){for(const t of this.subscriptions.values())t.unsubscribe();this.subscriptions.clear();for(const t of this.sources.values())t.destroy?.();this.sources.clear()}}class Oe{constructor(){this.providers=new Map,this.globalProviders=new Map}register(t,e,r){const n=t.toLowerCase();this.providers.set(n,"function"==typeof e?{name:n,provide:e,cache:r?.cache??1,description:r?.description,dependencies:r?.dependencies}:e)}registerGlobal(t,e,r){const n=t.toLowerCase();this.globalProviders.set(n,"function"==typeof e?{name:n,provide:e,cache:r?.cache??1,description:r?.description,dependencies:r?.dependencies}:e)}unregister(t){return this.providers.delete(t.toLowerCase())}unregisterGlobal(t){return this.globalProviders.delete(t.toLowerCase())}get(t){const e=t.toLowerCase();return this.providers.get(e)??this.globalProviders.get(e)}has(t){const e=t.toLowerCase();return this.providers.has(e)||this.globalProviders.has(e)}async resolve(t,e,r){const n=this.get(t);if(!n)return;const s="__provider_"+n.name;if(n.cache&&r?.has(s))return r.get(s);if(n.dependencies)for(const t of n.dependencies)await this.resolve(t,e,r);const i=await n.provide(e);return n.cache&&r&&r.set(s,i),i}resolveSync(t,e,r){const n=this.get(t);if(!n)return;const s="__provider_"+n.name;if(n.cache&&r?.has(s))return r.get(s);const i=n.provide(e);if(i instanceof Promise)throw Error(`Context provider '${t}' is async. Use resolve() instead of resolveSync().`);return n.cache&&r&&r.set(s,i),i}enhance(t){const e=this,r=new Map;return new Proxy(t,{get(t,n,s){if("string"==typeof n&&e.get(n))try{return e.resolveSync(n,t,r)}catch{return e.resolve(n,t,r)}return Reflect.get(t,n,s)},has:(t,r)=>"string"==typeof r&&e.has(r)?1:Reflect.has(t,r)})}async resolveAll(t){const e=new Map,r={},n=[...this.globalProviders.entries(),...this.providers.entries()];for(const[s,i]of n)try{r[s]=await this.resolve(s,t,e)}catch(t){console.warn(`[ContextProviderRegistry] Failed to resolve '${s}':`,t),r[s]=void 0}return r}getProviderNames(){return[...new Set([...this.globalProviders.keys(),...this.providers.keys()])]}clear(){this.providers.clear(),this.globalProviders.clear()}}const Le=new class{constructor(t={}){this.types=new Map,this.coercionCache=new Map,this.config={strictMode:0,cacheCoercions:1,...t},this.registerBuiltinTypes()}register(t){this.types.has(t.name)&&console.warn(`ExpressionTypeRegistry: Overwriting existing type '${t.name}'`),this.types.set(t.name,t)}get(t){return this.types.get(t)}has(t){return this.types.has(t)}getTypeNames(){return Array.from(this.types.keys())}inferType(t){for(const[e,r]of this.types)if(r.isType(t))return e;return"Unknown"}getHyperScriptType(t){const e=this.inferType(t),r=this.types.get(e);return r?.hyperscriptType??"unknown"}coerce(t,e,r){const n=this.types.get(e);if(!n){if(this.config.strictMode)throw Error("Unknown target type: "+e);return null}if(n.isType(t))return t;if(this.config.cacheCoercions){const r=`${this.inferType(t)}:${e}:${JSON.stringify(t)}`;if(this.coercionCache.has(r))return this.coercionCache.get(r)}const s=this.inferType(t),i=n.coerceFrom?.[s];if(i){const n=i(t,r);if(this.config.cacheCoercions&&null!==n){const r=`${s}:${e}:${JSON.stringify(t)}`;this.coercionCache.set(r,n)}return n}return n.defaultValue}canCoerce(t,e){const r=this.types.get(e);if(!r)return 0;if(r.isType(t))return 1;const n=this.inferType(t);return void 0!==r.coerceFrom?.[n]}getCoercionInfo(t,e){const r=this.types.get(e);return r&&(t===e||r.coerceFrom?.[t])?{possible:1,direct:1}:{possible:0,direct:0}}clearCache(){this.coercionCache.clear()}getStats(){return{typeCount:this.types.size,cacheSize:this.coercionCache.size,typeNames:this.getTypeNames()}}registerBuiltinTypes(){this.register({name:"String",hyperscriptType:"string",tsType:"string",isType:t=>"string"==typeof t,defaultValue:"",description:"Text string value",examples:["hello","world",""],coerceFrom:{Number:t=>t+"",Boolean:t=>t+"",Null:()=>"",Undefined:()=>"",Array:t=>Array.isArray(t)?t.join(", "):null,Object:t=>{try{return JSON.stringify(t)}catch{return t+""}},Element:t=>t instanceof Element?t.textContent??t.outerHTML:null}}),this.register({name:"Number",hyperscriptType:"number",tsType:"number",isType:t=>"number"==typeof t&&!isNaN(t),defaultValue:0,description:"Numeric value (integer or float)",examples:[0,1,3.14,-42],coerceFrom:{String:t=>{const e=parseFloat(t);return isNaN(e)?null:e},Boolean:t=>t?1:0,Null:()=>0,Undefined:()=>null}}),this.register({name:"Boolean",hyperscriptType:"boolean",tsType:"boolean",isType:t=>"boolean"==typeof t,defaultValue:0,description:"True or false value",examples:[1,0],coerceFrom:{String:t=>{const e=t.toLowerCase().trim();return"true"===e||"yes"===e||"1"===e?1:"false"===e||"no"===e||"0"===e||""===e?0:e.length>0},Number:t=>0!==t,Null:()=>0,Undefined:()=>0,Array:t=>Array.isArray(t)?t.length>0:0,Element:t=>t instanceof Element,ElementList:t=>Array.isArray(t)&&t.length>0}}),this.register({name:"Element",hyperscriptType:"element",tsType:"Element | HTMLElement",isType:t=>t instanceof Element,defaultValue:null,description:"DOM Element",coerceFrom:{String:(t,e)=>{const r=t;if(r.startsWith("#")||r.startsWith(".")||r.match(/^[\w-]+$/))try{return document.querySelector(r)}catch{return null}return null},ElementList:t=>Array.isArray(t)&&t.length>0?t[0]:null,NodeList:t=>t.length>0?t[0]:null}}),this.register({name:"ElementList",hyperscriptType:"element-list",tsType:"Element[]",isType:t=>Array.isArray(t)&&t.length>0&&t.every(t=>t instanceof Element),defaultValue:[],description:"Array of DOM Elements",coerceFrom:{Element:t=>t instanceof Element?[t]:[],NodeList:t=>Array.from(t),String:t=>{try{return Array.from(document.querySelectorAll(t))}catch{return[]}},Array:t=>{const e=t;return e.every(t=>t instanceof Element)?e:[]}}}),this.register({name:"Array",hyperscriptType:"array",tsType:"unknown[]",isType:t=>Array.isArray(t),defaultValue:[],description:"Array of values",coerceFrom:{String:t=>{const e=t;try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map(t=>t.trim())},ElementList:t=>t,NodeList:t=>Array.from(t),Object:t=>Object.values(t)}}),this.register({name:"Object",hyperscriptType:"object",tsType:"Record<string, unknown>",isType:t=>!("object"!=typeof t||null===t||Array.isArray(t)||t instanceof Element),defaultValue:{},description:"Plain JavaScript object",coerceFrom:{String:t=>{try{const e=JSON.parse(t);if("object"==typeof e&&null!==e&&!Array.isArray(e))return e}catch{}return null},Array:t=>{const e={};return t.forEach((t,r)=>{e[r+""]=t}),e}}}),this.register({name:"Null",hyperscriptType:"null",tsType:"null",isType:t=>null===t,defaultValue:null,description:"Null value"}),this.register({name:"Undefined",hyperscriptType:"undefined",tsType:"undefined",isType:t=>void 0===t,defaultValue:void 0,description:"Undefined value"}),this.register({name:"Function",hyperscriptType:"function",tsType:"Function",isType:t=>"function"==typeof t,defaultValue:null,description:"JavaScript function"}),this.register({name:"Event",hyperscriptType:"event",tsType:"Event",isType:t=>t instanceof Event,defaultValue:null,description:"DOM Event"}),this.register({name:"NodeList",hyperscriptType:"element-list",tsType:"NodeList",isType:t=>t instanceof NodeList,defaultValue:null,description:"DOM NodeList (typically from querySelectorAll)",coerceFrom:{Array:t=>null}}),this.register({name:"Unknown",hyperscriptType:"unknown",tsType:"unknown",isType:t=>1,defaultValue:null,description:"Unknown/any value type"})}};function $e(t){const e=Le.get("String");return e?e.isType(t):"string"==typeof t}function Re(t){const e=Le.get("Number");return e?e.isType(t):"number"==typeof t}function Ie(t){const e=Le.get("Boolean");return e?e.isType(t):"boolean"==typeof t}function je(t){const e=Le.get("Object");return e?e.isType(t):"object"==typeof t&&null!==t}function De(t){const e=Le.get("Function");return e?e.isType(t):"function"==typeof t}function Me(t){if(null===t||"object"!=typeof t||!("tagName"in t))return 0;const e=t.tagName;return"INPUT"===e||"SELECT"===e||"TEXTAREA"===e}function Pe(t){return t instanceof Element}const Ve=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function Be(t,e){return Ve.has(e.toLowerCase())?t.hasAttribute(e):t.getAttribute(e)}const _e={id:t=>t.id,classname:t=>t.className,class:t=>t.className,tagname:t=>t.tagName.toLowerCase(),innertext:t=>t.textContent?.trim(),innerHTML:t=>t.innerHTML,outerhtml:t=>t.outerHTML,value:t=>Me(t)?t.value:void 0,checked:t=>function(t){return null!==t&&"object"==typeof t&&"tagName"in t&&"INPUT"===t.tagName}(t)?t.checked:void 0,disabled:t=>Me(t)?t.disabled:void 0,selected:t=>function(t){return null!=t&&"object"==typeof t&&"tagName"in t&&"OPTION"===t.tagName}(t)?t.selected:void 0,hidden:t=>function(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"style"in t}(t)?t.hidden:void 0,style:t=>getComputedStyle(t),children:t=>Array.from(t.children),parent:t=>t.parentElement,firstchild:t=>t.firstElementChild,lastchild:t=>t.lastElementChild,nextsibling:t=>t.nextElementSibling,previoussibling:t=>t.previousElementSibling};function Fe(t,e){if(e.startsWith("computed-")){const r=e.slice(9);return function(t){return t instanceof HTMLElement}(t)?getComputedStyle(t).getPropertyValue(r):void 0}if(e.startsWith("@"))return Be(t,e.slice(1));const r=_e[e.toLowerCase()];if(r)return r(t);if(function(t,e){return t.hasAttribute(e)}(t,e))return Be(t,e);const n=t[e];return De(n)?n.bind(t):n}function qe(t){if("string"==typeof t)return t;if(t&&"object"==typeof t){if("string"==typeof t.name)return t.name;if("string"==typeof t.value)return t.value}return t}function He(t){return t.me?.ownerDocument??("undefined"!=typeof document?document:null)}function Ue(t,e){return e.locals?.has(t)?e.locals.get(t):e.globals?.has(t)?e.globals.get(t):e.variables?.has(t)?e.variables.get(t):"me"===t?e.me:"it"===t?e.it:"result"===t?e.result:void 0}async function We(t,e){if(t.includes(".")){const r=t.split(".");let n=Ue(r[0],e);for(let t=1;r.length>t&&null!=n;t++)n=n[r[t]];return n}return Ue(t,e)}async function ze(t,e){if(dt(`RESOLVE: Looking for '${t}' in context`,{hasInLocals:e.locals.has(t),localsKeys:Array.from(e.locals.keys()),value:e.locals.get(t)}),e.locals.has(t)){const r=e.locals.get(t);return dt(`RESOLVE: Found '${t}' in locals:`,r),r}if(e.globals&&e.globals.has(t)){const r=e.globals.get(t);return dt(`RESOLVE: Found '${t}' in globals:`,r),r}if(e.variables&&e.variables.has(t)){const r=e.variables.get(t);return dt(`RESOLVE: Found '${t}' in variables (legacy):`,r),r}const r=Number(t);if(!isNaN(r))return r;if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t.includes(".")){const r=t.split("."),n=r[0];let s=null;if(e.locals.has(n)?s=e.locals.get(n):e.globals&&e.globals.has(n)?s=e.globals.get(n):e.variables&&e.variables.has(n)&&(s=e.variables.get(n)),null!=s){for(let t=1;r.length>t;t++){if(null==s)return void dt(`RESOLVE: Property access failed at '${r[t-1]}'`);s=s[r[t]]}return dt(`RESOLVE: Property access '${t}' =`,s),s}}return t}async function Je(t,e){dt("EVAL: Evaluating expression:",t);const r=t.match(/^(.+?)\s*\?(?![\.\[])\s*(.+?)\s*:\s*(.+)$/);if(r){const[,t,n,s]=r;dt("EVAL: Parsed ternary:",{conditionExpr:t,trueExpr:n,falseExpr:s});const i=await ze(t.trim(),e);if(dt("EVAL: Ternary condition value:",i),i){const t=await ze(n.trim(),e);return dt("EVAL: Ternary returned true branch:",t),t}{const t=await ze(s.trim(),e);return dt("EVAL: Ternary returned false branch:",t),t}}const n=t.match(/^([a-zA-Z_$][a-zA-Z0-9_$]*|\d+(?:\.\d+)?)\s*([\+\-\*\/\%])\s*([a-zA-Z_$][a-zA-Z0-9_$]*|\d+(?:\.\d+)?)$/);if(n){const[,t,r,s]=n;dt("EVAL: Parsed arithmetic:",{left:t,operator:r,right:s});const i=await ze(t.trim(),e),o=await ze(s.trim(),e);dt("EVAL: Resolved values:",{leftValue:i,rightValue:o});const a=Number(i),c=Number(o);if(!isNaN(a)&&!isNaN(c)){let t;switch(r){case"+":t=a+c;break;case"-":t=a-c;break;case"*":t=a*c;break;case"/":t=a/c;break;case"%":t=a%c;break;default:t=a}return dt("EVAL: Arithmetic result:",t),t}}const s=await ze(t.trim(),e);return dt("EVAL: Fallback result:",s),s}function Ze(t){if(Array.isArray(t)&&1===t.length&&(t=t[0]),null!==t&&"object"==typeof t&&"string"==typeof t.textContent){const e=t.value??t.textContent;if(null!=e){const t=(e+"").trim();if(""===t)return 0;const r=parseFloat(t);return isNaN(r)?t:r}return 0}return t}async function Ge(t,e,r,n,s){try{const i=s(await n(t.object,r));if(null==i)throw Error("Cannot call method on null or undefined");const o=qe(t.property);if(!o||"string"!=typeof o)throw Error("Invalid method name: "+o);const a=i[o];if("function"!=typeof a)throw Error(`Property "${o}" is not a function on ${i.constructor?.name||typeof i}`);const c=await Promise.all(e.map(t=>n(t,r)));return a.apply(i,c)}catch(t){if(t instanceof Error)throw t;throw Error("Failed to evaluate method call: "+t)}}class Xe{constructor(){this.expressionRegistry=new Map}registerCategory(t){Object.entries(t).forEach(([t,e])=>{this.expressionRegistry.set(t,e)})}unwrapSelectorResult(t){if(t instanceof NodeList&&t.length>0)return t[0];if(Array.isArray(t)&&t.length>0){const e=t[0];return"index"in t&&"input"in t?t:e instanceof Element||e instanceof Node?e:t}return t}async evaluate(t,e){if(!t)return dt("EVALUATOR: Received null/undefined node, returning null"),null;if(!t.type)throw console.error("EVALUATOR: Node missing type property:",t),Error("Node missing type property: "+JSON.stringify(t));switch(t.type){case"identifier":return this.evaluateIdentifier(t,e);case"literal":return this.evaluateLiteral(t,e);case"string":return t.value??"";case"memberExpression":return this.evaluateMemberExpression(t,e);case"binaryExpression":return this.evaluateBinaryExpression(t,e);case"unaryExpression":return this.evaluateUnaryExpression(t,e);case"callExpression":return this.evaluateCallExpression(t,e);case"selector":return this.evaluateSelector(t,e);case"dollarExpression":return this.evaluateDollarExpression(t,e);case"possessiveExpression":return this.evaluatePossessiveExpression(t,e);case"templateLiteral":return this.evaluateTemplateLiteral(t,e);case"arrayLiteral":return this.evaluateArrayLiteral(t,e);case"objectLiteral":return this.evaluateObjectLiteral(t,e);case"conditionalExpression":return this.evaluateConditionalExpression(t,e);case"cssSelector":return this.evaluateCSSSelector(t,e);case"propertyAccess":return this.evaluatePropertyAccess(t,e);case"propertyOfExpression":return this.evaluatePropertyOfExpression(t,e);case"contextReference":return this.evaluateContextReference(t,e);case"queryReference":return this.evaluateQueryReference(t,e);case"idSelector":return this.evaluateIdSelector(t,e);case"attributeAccess":return this.evaluateAttributeAccess(t,e);default:throw Error("Unsupported AST node type for evaluation: "+t.type)}}async evaluateWithResult(t,e){try{return xe(await this.evaluate(t,e))}catch(t){if(t instanceof Error){const e=t;if(e.isHalt||"HALT_EXECUTION"===e.message)return ke({type:"halt"});if(e.isExit||"EXIT_COMMAND"===e.message)return ke({type:"exit",returnValue:e.returnValue});if(e.isBreak)return ke({type:"break"});if(e.isContinue)return ke({type:"continue"});if(e.isReturn)return ke({type:"return",returnValue:e.returnValue})}throw t}}async evaluateArrayLiteral(t,e){const r=t.elements||[],n=[];for(const t of r){const r=await this.evaluate(t,e);n.push(r)}return n}async evaluateObjectLiteral(t,e){const r=t.properties||[],n={};for(const t of r){let r;r="identifier"===t.key.type?t.key.name:"literal"===t.key.type?t.key.value+"":await this.evaluate(t.key,e)+"";const s=await this.evaluate(t.value,e);n[r]=s}return n}async evaluateConditionalExpression(t,e){return await this.evaluate(t.test,e)?this.evaluate(t.consequent,e):t.alternate?this.evaluate(t.alternate,e):void 0}async evaluateTemplateLiteral(t,e){return async function(t,e){let r=t.value||"";dt("TEMPLATE LITERAL: Evaluating",{template:r,node:t});const n=/\$([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)/g,s=[];let i;for(;null!==(i=n.exec(r));)"{"!==r[i.index+1]&&s.push({match:i[0],varName:i[1],index:i.index});for(let t=s.length-1;t>=0;t--){const{match:n,varName:i,index:o}=s[t],a=await We(i,e);dt(`TEMPLATE: $${i} resolved to`,a),r=r.slice(0,o)+((a??"")+"")+r.slice(o+n.length)}let o="",a=0;for(;r.length>a;){const t=r.indexOf("${",a);if(-1===t){o+=r.slice(a);break}o+=r.slice(a,t);let n=1,s=t+2;for(;r.length>s&&n>0;)"{"===r[s]&&n++,"}"===r[s]&&n--,n>0&&s++;if(0!==n)throw Error("Unterminated template expression in: "+r);const i=r.slice(t+2,s);let c;dt("TEMPLATE: Evaluating expression:",i);const l=i.trim();e.locals.has(l)?(c=e.locals.get(l),dt(`TEMPLATE: Found in locals: ${l} =`,c)):e.globals&&e.globals.has(l)?(c=e.globals.get(l),dt(`TEMPLATE: Found in globals: ${l} =`,c)):e.variables&&e.variables.has(l)?(c=e.variables.get(l),dt(`TEMPLATE: Found in variables (legacy): ${l} =`,c)):(c=await Je(i,e),dt(`TEMPLATE: Evaluated expression "${i}" =`,c)),o+=c+"",a=s+1}return o}(t,e)}async evaluateSimpleExpression(t,e){return Je(t,e)}async resolveValue(t,e){return ze(t,e)}async evaluateIdentifier(t,e){const{name:r,scope:n}=t;if("me"===r||"my"===r||"I"===r)return e.me;if("you"===r||"your"===r)return e.you;if("it"===r||"its"===r)return e.it;if("result"===r)return e.result;if("event"===r)return e.event;const s=this.expressionRegistry.get(r);return s?s.evaluate(e):"local"===n?e.locals?.has(r)?e.locals.get(r):void 0:"global"===n?e.globals?.has(r)?e.globals.get(r):"undefined"!=typeof window&&r in window?window[r]:void 0:e.locals?.has(r)?e.locals.get(r):e.globals?.has(r)?e.globals.get(r):e.variables?.has(r)?e.variables.get(r):"undefined"!=typeof globalThis&&r in globalThis?globalThis[r]:"undefined"!=typeof window&&r in window?window[r]:void 0}async evaluateLiteral(t,e){return t.value}async evaluateContextReference(t,e){const{contextType:r}=t;switch(r){case"me":return e.me;case"it":return e.result;case"you":return e.you;case"event":return e.event;case"body":return e.meta?.ownerDocument?.body||document?.body;case"detail":return e.event?.detail;case"target":return e.you||e.event?.target;case"sender":return e.event?.target;default:return e.locals&&e.locals.has(r)?e.locals.get(r):void dt("Unknown context reference type: "+r)}}async evaluateMemberExpression(t,e){const{object:r,property:n,computed:s}=t;if("identifier"===r.type&&["add","remove"].includes(r.name)){const t=r.name,s=qe(n);if(!e.me)throw Error('Context element "me" is null');return void("add"===t?e.me.classList.add(s):"remove"===t&&e.me.classList.remove(s))}let i=await this.evaluate(r,e);if(s)return i[await this.evaluate(n,e)];{const t=qe(n);if(Array.isArray(i)&&"string"==typeof t&&("length"===t||t in Array.prototype)||(i=this.unwrapSelectorResult(i)),"string"==typeof t){if(t.startsWith("computed-")){const e=t.substring(9);return i&&"undefined"!=typeof window&&i instanceof Element?window.getComputedStyle(i).getPropertyValue(e):void 0}if(t.startsWith("@")){const e=t.substring(1);return i&&"function"==typeof i.getAttribute?Be(i,e):void 0}if(i&&i instanceof Element){if("previous"===t||"prev"===t)return i.previousElementSibling;if("next"===t)return i.nextElementSibling}}const e=i?.[t];return"function"==typeof e?e.bind(i):e}}coerceArithmeticOperand(t){return Ze(t)}async evaluateBinaryExpression(t,e){return async function(t,e,r,n,s){const{operator:i,left:o,right:a}=t;if("in"===i&&"selector"===o.type){let t=o.value;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const s=n(await r(a,e));if(!s||"function"!=typeof s.querySelector)throw Error(`'in' operator requires a DOM element as the right operand (got: ${typeof s})`);const i=s.querySelectorAll(t);return Array.from(i)}if("in"===i&&"queryReference"===o.type){let t=o.selector;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const s=n(await r(a,e));if(!s||"function"!=typeof s.querySelector)throw Error(`'in' operator requires a DOM element as the right operand (got: ${typeof s})`);const i=s.querySelectorAll(t);return Array.from(i)}if("in"===i){let t=null,s=null;if("positionalExpression"===o.type){t=o.operator;const n=o.argument;"cssSelector"===n?.type?s=n.selector:"selector"===n?.type?s=n.value:"classSelector"===n?.type?s="."+n.className:"idSelector"===n?.type?s="#"+n.id:n&&(s=await r(n,e)+"")}else if("memberExpression"!==o.type||"identifier"!==o.object?.type||"first"!==o.object.name&&"last"!==o.object.name){if("callExpression"===o.type&&"identifier"===o.callee?.type&&("first"===o.callee.name||"last"===o.callee.name)){t=o.callee.name;const n=o.arguments?.[0];"selector"===n?.type?s=n.value:"cssSelector"===n?.type?s=n.selector:"classSelector"===n?.type?s="."+n.className:"idSelector"===n?.type?s="#"+n.id:n&&(s=await r(n,e)+"")}}else t=o.object.name,"identifier"===o.property?.type&&o.property.name&&(s="."+o.property.name);if(t&&s){const i=n(await r(a,e));if(!i||"function"!=typeof i.querySelectorAll)return;const o=i.querySelectorAll(s),c=Array.from(o);return"first"===t?c.length>0?c[0]:void 0:"last"===t?c.length>0?c[c.length-1]:void 0:c}}if("matches"===i&&("selector"===a.type||"cssSelector"===a.type||"classSelector"===a.type)){const t=await r(o,e),n=a.value||a.selector;if(t&&"function"==typeof t.matches)try{return t.matches(n)}catch{return 0}return 0}const c=await r(o,e),l=await r(a,e);if("has"===i||"have"===i){if(c instanceof Element){if("cssSelector"===a.type&&"class"===a.selectorType||"selector"===a.type&&a.value?.startsWith(".")){const t=a.selector?.slice(1)||a.value?.slice(1)||"";return c.classList.contains(t)}if("attributeAccess"===a.type||"attributeRef"===a.type){const t=a.attributeName||a.name||a.value?.replace(/^@/,"")||"";return c.hasAttribute(t)}if("cssSelector"===a.type&&"attribute"===a.selectorType){const t=(a.selector||a.value||"").replace(/^@/,"");return c.hasAttribute(t)}if("cssSelector"===a.type&&"id"===a.selectorType||"idSelector"===a.type){const t=(a.selector||a.value||"").replace(/^#/,"");return null!==c.querySelector("#"+CSS.escape(t))}if("selector"===a.type||"queryReference"===a.type){let t=a.value||a.selector||"";t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());try{return null!==c.querySelector(t)}catch{return 0}}if("cssSelector"===a.type){const t=a.selector||"";try{return null!==c.querySelector(t)}catch{return 0}}}return Array.isArray(c)?c.includes(l):"string"==typeof c?c.includes(l+""):0}switch(i){case">":case"is greater than":return c>l;case"<":case"is less than":return l>c;case">=":case"is greater than or equal to":return c>=l;case"<=":case"is less than or equal to":return l>=c;case"==":case"equals":case"is equal to":return c==l;case"===":case"is really equal to":case"really equals":return c===l;case"!=":case"is not equal to":return c!=l;case"!==":case"is not really equal to":return c!==l;case"+":{const t=Ze(c),r=Ze(l);if("string"==typeof t||"string"==typeof r){const n=s.get("stringConcatenation");if(n){dt("Using string concatenation for:",{leftValue:t,rightValue:r});const s=await n.evaluate(e,{left:t,right:r});return s.success?s.value:t+r}}else{const n=s.get("addition");if(n){dt("Using numeric addition for:",{leftValue:t,rightValue:r});const s=await n.evaluate(e,{left:t,right:r});return s.success?s.value:t+r}}return t+r}case"-":return Ze(c)-Ze(l);case"*":return Ze(c)*Ze(l);case"/":return Ze(c)/Ze(l);case"%":case"mod":return Ze(c)%Ze(l);case"as":const t="string"==typeof l?l:"identifier"===a.type?a.name:"literal"===a.type?a.value:l+"",r=s.get("as");return r?r.evaluate(e,c,t):c;case"&&":case"and":return c&&l;case"||":case"or":return c||l;case"is":return c===l;case"is not":return c!==l;case"is a":case"is an":switch("identifier"===a.type?a.name.toLowerCase():(l+"").toLowerCase()){case"string":return"string"==typeof c;case"number":return"number"==typeof c;case"boolean":return"boolean"==typeof c;case"object":return"object"==typeof c&&null!==c;case"array":return Array.isArray(c);case"function":return"function"==typeof c;case"null":return null===c;case"undefined":return void 0===c;default:const t="identifier"===a.type?a.name:l+"";return null!=c&&c.constructor?.name===t}case"is not a":case"is not an":switch("identifier"===a.type?a.name.toLowerCase():(l+"").toLowerCase()){case"string":return"string"!=typeof c;case"number":return"number"!=typeof c;case"boolean":return"boolean"!=typeof c;case"object":return!("object"==typeof c&&null!==c);case"array":return!Array.isArray(c);case"function":return"function"!=typeof c;case"null":return null!==c;case"undefined":return void 0!==c;default:const t="identifier"===a.type?a.name:l+"";return!(null!=c&&c.constructor?.name===t)}case"=":if("identifier"===o.type){const t=o.name;return"result"===t?e.result=l:"it"===t?e.it=l:"you"===t?e.you=l:e.locals.set(t,l),l}throw Error("Left side of assignment must be an identifier");case"contains":case"include":case"includes":return Array.isArray(c)?c.includes(l):"string"==typeof c?c.includes(l+""):c&&"function"==typeof c.matches?c.matches(l+""):0;case"match":case"matches":if(c&&"function"==typeof c.matches){const t="string"==typeof l?l:l+"";try{return c.matches(t)}catch{return 0}}return 0;case"in":const n="string"==typeof c?c:c+"",u=l;if(!u||"function"!=typeof u.querySelector){if(Array.isArray(u))return u.includes(c);if("object"==typeof u&&null!==u)return n in u;throw Error(`'in' operator requires a DOM element, array, or object as the right operand (got: ${typeof u})`)}return u.querySelector(n);case" ":return"string"==typeof c&&"string"==typeof l?{command:c,selector:l}:"identifier"===o.type&&"selector"===a.type?{command:o.name,selector:a.value}:l;default:throw Error(`Unsupported binary operator: "${i}" (length: ${i.length})`)}}(t,e,this.evaluate.bind(this),this.unwrapSelectorResult.bind(this),this.expressionRegistry,this.evaluateSelector.bind(this))}async evaluateUnaryExpression(t,e){const{operator:r,argument:n}=t,s=await this.evaluate(n,e);switch(r){case"not":case"!":const t=this.expressionRegistry.get("not");return t?t.evaluate(e,s):!s;case"no":const n=this.expressionRegistry.get("no");return n?n.evaluate(e,s):0;case"some":return null==s?0:"string"==typeof s||Array.isArray(s)||s instanceof NodeList||s instanceof HTMLCollection?s.length>0:"object"==typeof s?Object.keys(s).length>0:1;case"exists":const i=this.expressionRegistry.get("exists");return i?i.evaluate(e,s):null!=s;case"does not exist":const o=this.expressionRegistry.get("doesNotExist");return o?o.evaluate(e,s):null==s;case"-":return-s;case"+":return+s;default:throw Error("Unsupported unary operator: "+r)}}async evaluateCallExpression(t,e){return async function(t,e,r,n,s,i){const{callee:o,arguments:a,isConstructor:c}=t;if(c){const t=o.name,n=e.globals?.get(t)||window[t];if("function"==typeof n)return new n(...await Promise.all(a.map(t=>r(t,e))));throw Error("Unknown constructor: "+t)}if("memberExpression"===o.type||"propertyAccess"===o.type)return Ge(o,a,e,r,n);const l=o.name||o,u=s.get(l);if(u){const t=["first","last","random","at"],n=["closest","previous","next"].includes(l),s=t.includes(l),o=await Promise.all(a.map(t=>n&&t&&"selector"===t.type&&"string"==typeof t.value?t.value:n&&t&&"identifier"===t.type&&"string"==typeof t.name?t.name:s&&t&&"selector"===t.type&&"string"==typeof t.value?i(t,e):r(t,e)));return u.evaluate(e,...o)}const h=e.globals?.get(l)||window[l];if("function"==typeof h)return h(...await Promise.all(a.map(t=>r(t,e))));throw Error("Unknown function: "+l)}(t,e,this.evaluate.bind(this),this.unwrapSelectorResult.bind(this),this.expressionRegistry,this.evaluateSelector.bind(this))}async evaluateMethodCall(t,e,r){return Ge(t,e,r,this.evaluate.bind(this),this.unwrapSelectorResult.bind(this))}async evaluateSelector(t,e){return function(t,e){let r=t.value;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());const n=He(e);if(!n)return[];const s=n.querySelectorAll(r);return Array.from(s).filter(t=>t&&"object"==typeof t&&1===t.nodeType&&"string"==typeof t.tagName)}(t,e)}evaluateAttributeAccess(t,e){return e.me&&"function"==typeof e.me.getAttribute?Be(e.me,t.attributeName):"@"+t.attributeName}getAvailableExpressions(){return Array.from(this.expressionRegistry.keys())}async evaluateDollarExpression(t,e){const r=await this.evaluate(t.expression,e);if("identifier"===t.expression.type){const r=t.expression.name;return/^\d+$/.test(r)?r:e.locals?.has(r)?e.locals.get(r):"me"===r&&e.me?e.me:"you"===r&&e.you?e.you:"it"===r&&e.it?e.it:"result"===r&&e.result?e.result:"undefined"!=typeof window&&"window"===r?window:e.globals?.has(r)?e.globals.get(r):void 0}return r}async evaluatePossessiveExpression(t,e){const{object:r,property:n}=t,s=this.unwrapSelectorResult(await this.evaluate(r,e));if(!s)return;const i=qe(n);return"string"==typeof i&&Pe(s)?Fe(s,i):s[i]}hasExpression(t){return this.expressionRegistry.has(t)}async evaluateCSSSelector(t,e){return function(t,e){let r=t.selector;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());const n=He(e);if(!n)return"id"===t.selectorType?null:[];if("id"===t.selectorType){const t=r.startsWith("#")?r.slice(1):r;return n.getElementById(t)}if("class"===t.selectorType){const t=r.replace(/:/g,"\\:"),e=n.querySelectorAll(t);return Array.from(e).filter(t=>t instanceof HTMLElement)}const s=n.querySelectorAll(r);return Array.from(s).filter(t=>t instanceof HTMLElement)}(t,e)}async evaluateIdSelector(t,e){return function(t,e){const r=He(e);if(!r)return null;const n=t.value.startsWith("#")?t.value.slice(1):t.value;return r.getElementById(n)}(t,e)}async evaluateQueryReference(t,e){return function(t,e){let r=t.selector;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());const n=He(e);if(!n)return[];try{return n.querySelectorAll(r)}catch{return n.createDocumentFragment().childNodes}}(t,e)}async evaluatePropertyAccess(t,e){const r=await this.evaluate(t.object,e),n=t.property;if(null==r)throw Error(`Cannot access property "${n.name||n.value}" of ${r}`);const s=n.name||n.value;if(!s)throw Error("Property name must be an identifier");try{let t;return t=Pe(r)?Fe(r,s):r[s],"function"==typeof t?t.bind(r):t}catch(t){throw Error(`Error accessing property "${s}": ${t}`)}}async evaluatePropertyOfExpression(t,e){const r=t.property,n=r.name||r.value;if(!n)throw Error('Property name must be an identifier in "the X of Y" pattern');const s=this.unwrapSelectorResult(await this.evaluate(t.target,e));if(null==s)throw Error(`Cannot access property "${n}" of ${s}`);try{let t;return t=Pe(s)?Fe(s,n):s[n],"function"==typeof t?t.bind(s):t}catch(t){throw Error(`Failed to access property "${n}" on target: ${t}`)}}}const Ye={1:"one",2:"two",3:"three",4:"four",5:"five"};function Ke(t,e,r,n){return t.length!==e?`${r} requires exactly ${s=e,Ye[s]??s+""} argument${1===e?"":"s"}${n?` (${n})`:""}`:null;var s}function Qe(t,e,r,n){return"string"!=typeof t[e]?`${r} ${n||"argument "+(e+1)} must be a string`:null}function tr(t,e,r){return Ke(t,1,e,r)??Qe(t,0,e,r)}function er(t,e){return Ke(t,2,e,"left, right")}function rr(){return null}function nr(t,e,r,n){return t.length>e?`${r} expression takes at most ${1===e?"one":e+""} argument${1===e?"":"s"}${n?` (${n})`:""}`:null}function sr(t,e,r,n,s){return e>t.length||t.length>r?`${n} requires ${e}-${r} arguments${s?` (${s})`:""}`:null}function ir(t,e,r,n=[]){return{type:t,message:e,suggestions:n,...r&&{path:r}}}const or=("undefined"!=typeof process?1:0)||"undefined"!=typeof process&&"true"===process.env.HYPERFIXI_SKIP_VALIDATION||"undefined"!=typeof globalThis&&"true"===globalThis.HYPERFIXI_SKIP_VALIDATION;let ar;function cr(){return ar({validate:t=>({success:1,data:t})})}function lr(t,e){if(or)return cr();const r=ar({validate:r=>{if("object"!=typeof r||null===r||Array.isArray(r))return{success:0,error:ir("type-mismatch","Expected object, received "+typeof r)};const n=r,s={};if(e?.strict){const e=Object.keys(t),r=Object.keys(n).filter(t=>!e.includes(t));if(r.length>0)return{success:0,error:ir("runtime-error","Unexpected properties: "+r.join(", "))}}for(const[e,r]of Object.entries(t)){const t=n[e];if(!(e in n)&&!r.t)return{success:0,error:ir("missing-argument",`Required field "${e}" is missing`,e)};const i=r.validate(t);if(!i.success)return{success:0,error:ir("validation-error",i.error.message||`Field "${e}" validation failed`,i.error.path?`${e}.${i.error.path}`:e)};void 0!==i.data&&(s[e]=i.data)}return{success:1,data:s}}});return r.strict=()=>lr(t,{strict:1}),r}ar=function(t){return t.describe||(t.describe=function(t){return this.description=t,this}),t.safeParse||(t.safeParse=function(t){const e=this.validate(t);return e.success?{success:1,data:e.data}:{success:0,error:{errors:e.error?[e.error]:[]}}}),t.parse||(t.parse=function(t){const e=this.validate(t);if(e.success&&void 0!==e.data)return e.data;throw Error(e.error?.message||"Validation failed")}),t.optional||(t.optional=function(){const t=this.validate.bind(this),e={...this,t:1,validate:e=>null==e?{success:1,data:void 0}:t(e)};return ar(e)}),t.min||(t.min=function(t){const e=this.validate.bind(this),r={...this,validate:r=>{const n=e(r);return n.success&&"string"==typeof n.data&&t>n.data.length?{success:0,error:ir("runtime-error",`String must be at least ${t} characters long`)}:n}};return ar(r)}),t.max||(t.max=function(t){const e=this.validate.bind(this),r={...this,validate:r=>{const n=e(r);return n.success&&"string"==typeof n.data&&n.data.length>t?{success:0,error:ir("runtime-error",`String must be at most ${t} characters long`)}:n}};return ar(r)}),t.default||(t.default=function(t){const e=this.validate.bind(this),r={...this,i:t,o:1,validate:r=>void 0===r?{success:1,data:t}:e(r)};return ar(r)}),t.rest||(t.rest=function(t){return this}),t.refine||(t.refine=function(t,e){const r=this.validate.bind(this),n={...this,validate:n=>{const s=r(n);return s.success?t(s.data)?s:{success:0,error:ir("runtime-error",e||"Refinement validation failed")}:s}};return ar(n)}),new Proxy(t,{get:(t,e,r)=>e in t||"string"!=typeof e||e.startsWith("_")||"constructor"===e||"validate"===e||"then"===e?Reflect.get(t,e,r):function(...t){return r}})};const ur=t=>function(t={}){return or?cr():ar({validate:e=>t.optional&&null==e?{success:1,data:void 0}:"string"!=typeof e?{success:0,error:ir("type-mismatch","Expected string, received "+typeof e)}:void 0!==t.minLength&&t.minLength>e.length?{success:0,error:ir("runtime-error",`String must be at least ${t.minLength} characters long`)}:void 0!==t.maxLength&&e.length>t.maxLength?{success:0,error:ir("runtime-error",`String must be at most ${t.maxLength} characters long`)}:t.pattern&&!t.pattern.test(e)?t.pattern.source.startsWith("^")&&t.pattern.source.endsWith("$")?{success:0,error:ir("runtime-error",`Expected "${t.pattern.source.slice(1,-1)}", received "${e}"`)}:{success:0,error:ir("missing-argument","String does not match required pattern")}:{success:1,data:e},...t.description&&{description:t.description}})}(t||{}),hr=t=>function(t={}){return or?cr():ar({validate:e=>{const r=Number(e);return isNaN(r)?{success:0,error:ir("type-mismatch","Expected number, received "+typeof e)}:void 0!==t.min&&t.min>r?{success:0,error:ir("runtime-error","Number must be at least "+t.min)}:void 0!==t.max&&r>t.max?{success:0,error:ir("runtime-error","Number must be at most "+t.max)}:{success:1,data:r}}})}(t||{}),fr=()=>or?cr():ar({validate:t=>"boolean"!=typeof t?{success:0,error:ir("type-mismatch","Expected boolean, received "+typeof t)}:{success:1,data:t}}),dr=t=>lr(t),pr=t=>function(t){return or?cr():ar({validate:e=>{if(!Array.isArray(e))return{success:0,error:ir("type-mismatch","Expected array, received "+typeof e)};if(e.length!==t.length)return{success:0,error:ir("runtime-error",`Expected tuple of length ${t.length}, received length ${e.length}`)};const r=[];for(let n=0;t.length>n;n++){const s=t[n].validate(e[n]);if(!s.success)return{success:0,error:ir("runtime-error",s.error.message,s.error.path?`${n}.${s.error.path}`:""+n)};r.push(s.data)}return{success:1,data:r}}})}(t),mr=()=>cr(),yr=()=>cr(),vr=()=>function(t,e="Custom validation failed"){return or?cr():ar({validate:r=>t(r)?{success:1,data:r}:{success:0,error:ir("runtime-error",e)}})}(t=>void 0===t,"Expected undefined");class gr{trackPerformance(t,e,r,n){t.evaluationHistory&&t.evaluationHistory.push({expressionName:this.name,category:this.category,input:e,output:r.success?r.value:r.error,timestamp:n,duration:Date.now()-n,success:r.success})}trackSimple(t,e,r,n=(r?"success":"error")){t.evaluationHistory&&t.evaluationHistory.push({expressionName:this.name,category:this.category,input:"operation",output:n,timestamp:e,duration:Date.now()-e,success:r})}toBoolean(t){return 0==t||0===t||0n===t||""===t||null==t||Re(t)&&isNaN(t)?0:1}success(t,e){return{success:1,value:t,type:e}}failure(t,e,r,n,s=[]){return{success:0,error:{name:t,type:e,message:r,code:n,suggestions:s}}}validationSuccess(){return{isValid:1,errors:[],suggestions:[]}}validationFailure(t,e,r=[]){return{isValid:0,errors:[{type:t,message:e,suggestions:r}],suggestions:r}}isElement(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"tagName"in t&&"string"==typeof t.tagName}inferType(t){return null===t?"null":void 0===t?"undefined":this.isElement(t)?"element":Array.isArray(t)?"array":je(t)?"object":typeof t}inferEvaluationType(t){return void 0===t?"Undefined":null===t?"Null":$e(t)?"String":Re(t)?"Number":Ie(t)?"Boolean":Array.isArray(t)?"Array":this.isElement(t)?"Element":"Object"}normalizeCollection(t){return Array.isArray(t)?t:t instanceof NodeList?Array.from(t):$e(t)?t.split(""):null==t?[]:je(t)&&Symbol.iterator in t?Array.from(t):[]}toNumber(t){if(Re(t)&&Number.isFinite(t))return t;if($e(t)){const e=Number(t);return Number.isFinite(e)?e:null}return Ie(t)?t?1:0:null}}const br=dr({selector:ur().min(1),single:fr().optional().default(0)});new class extends gr{constructor(){super(...arguments),this.name="me",this.category="Reference",this.syntax="me",this.description="References the current element in the execution context",this.inputSchema=vr(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=t.me,s=this.isElement(n)?n:null,i=this.success(s,"element");return this.trackPerformance(t,e,i,r),i}catch(n){const s=this.failure("MeExpressionError","runtime-error",n instanceof Error?n.message:'Failed to evaluate "me"',"ME_EVALUATION_FAILED",["Ensure element context is properly set",'Check if "me" is available in current scope']);return this.trackPerformance(t,e,s,r),s}}validate(t){return void 0!==t?this.validationFailure("type-mismatch",'"me" expression takes no arguments',['Use "me" without any parameters']):this.validationSuccess()}},new class extends gr{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=vr(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=t.you,s=this.isElement(n)?n:null,i=this.success(s,"element");return this.trackPerformance(t,e,i,r),i}catch(n){const s=this.failure("YouExpressionError","runtime-error",n instanceof Error?n.message:'Failed to evaluate "you"',"YOU_EVALUATION_FAILED",["Ensure target element is available in context",'Check if "you" is set by event or command']);return this.trackPerformance(t,e,s,r),s}}validate(t){return void 0!==t?this.validationFailure("type-mismatch",'"you" expression takes no arguments',['Use "you" without any parameters']):this.validationSuccess()}},new class extends gr{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=vr(),this.outputType="Any",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=t.it,s={success:1,value:n,type:this.inferType(n)};return this.trackPerformance(t,e,s,r),s}catch(n){const s=this.failure("ItExpressionError","runtime-error",n instanceof Error?n.message:'Failed to evaluate "it"',"IT_EVALUATION_FAILED",['Ensure "it" is set by previous operation',"Check if context variable is available"]);return this.trackPerformance(t,e,s,r),s}}validate(t){return void 0!==t?this.validationFailure("type-mismatch",'"it" expression takes no arguments',['Use "it" without any parameters']):this.validationSuccess()}},new class extends gr{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=br,this.outputType="ElementList",this.metadata={category:"Reference",complexity:"medium"}}async evaluate(t,e){const r=Date.now();try{if(!this.isValidCSSSelector(e.selector)){const n=this.failure("CSSSelectorError","invalid-argument",`Invalid CSS selector: "${e.selector}"`,"INVALID_CSS_SELECTOR",["Check selector syntax","Use valid CSS selector patterns like .class, #id, tag[attr]","Avoid special characters that need escaping"]);return this.trackPerformance(t,e,n,r),n}let n;if(e.single)n=document.querySelector(e.selector);else{const t=Array.from(document.querySelectorAll(e.selector));n=t.length>0?t:null}const s={success:1,value:n,type:Array.isArray(n)?"element-list":"element"};return this.trackPerformance(t,e,s,r),s}catch(n){const s=this.failure("CSSSelectorError","runtime-error",n instanceof Error?n.message:"CSS selector evaluation failed","CSS_SELECTOR_EVALUATION_FAILED",["Check if selector is valid CSS","Ensure DOM is ready when query executes","Verify elements exist in document"]);return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);if(!e.success)return{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid input: "+t.message,suggestions:this.getValidationSuggestion(t.code??"unknown")}))??[],suggestions:["Provide valid CSS selector string","Check selector syntax"]};const{selector:r}=e.data;return this.isValidCSSSelector(r)?this.validationSuccess():this.validationFailure("syntax-error",`Invalid CSS selector syntax: "${r}"`,["Use .class for class selectors","Use #id for ID selectors","Use tag for element selectors","Use [attr] for attribute selectors"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Ensure input matches expected format"])}}isValidCSSSelector(t){try{return document.querySelector(t),1}catch{return 0}}getValidationSuggestion(t){return[{too_small:"CSS selector cannot be empty",invalid_type:"Selector must be a string",required:"CSS selector is required"}[t]||"Check input format and types"]}};const Er={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.me instanceof HTMLElement?t.me:null,validate:rr},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.you instanceof HTMLElement?t.you:null,validate:rr},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it,validate:rr},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it,validate:rr},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.result,validate:rr},querySelector:{name:"querySelector",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){const[r]=e;if("string"!=typeof r)throw Error("querySelector requires a string selector");return document.querySelector(r)},validate:t=>tr(t,"querySelector","selector")},querySelectorAll:{name:"querySelectorAll",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const r=e[0];if("string"!=typeof r)throw Error("querySelectorAll requires a string selector");const n=document.querySelectorAll(r);return Array.from(n)},validate:t=>tr(t,"querySelectorAll","selector")},getElementById:{name:"getElementById",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){const r=e[0];if("string"!=typeof r)throw Error("getElementById requires a string ID");return document.getElementById(r)},validate:t=>tr(t,"getElementById","ID")},getElementsByClassName:{name:"getElementsByClassName",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const r=e[0];if("string"!=typeof r)throw Error("getElementsByClassName requires a string class name");const n=document.getElementsByClassName(r);return Array.from(n)},validate:t=>tr(t,"getElementsByClassName","className")},closest:{name:"closest",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){let r=e[0];if(r&&"object"==typeof r&&"type"in r){const t=r;"identifier"===t.type&&t.name?r=t.name:"literal"===t.type&&"string"==typeof t.value&&(r=t.value)}if("string"!=typeof r)throw Error("closest requires a string selector");return t.me?t.me.closest(r):null},validate(t){if(1!==t.length)return"closest requires exactly 1 argument (selector)";const e=t[0];return"string"==typeof e||e&&"object"==typeof e&&"type"in e&&("identifier"===e.type||"literal"===e.type)?null:"closest selector must be a string or identifier"}},parent:{name:"parent",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.me?t.me.parentElement:null,validate:rr},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async t=>window,validate:rr},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async t=>document,validate:rr},elementWithSelector:{name:"elementWithSelector",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const r=e[0];if("string"!=typeof r)throw Error("Selector must be a string");const n=document.querySelectorAll(r);return Array.from(n)},validate:t=>tr(t,"elementWithSelector","selector")},styleRef:{name:"styleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const r=e[0],n=e[1];if("string"!=typeof r)throw Error("StyleRef requires a string property name");const s=n||t.me;if(s&&s instanceof HTMLElement){if(r.startsWith("computed-")){const t=r.substring(9);return getComputedStyle(s).getPropertyValue(t)||""}return s.style.getPropertyValue(r)||void 0}},validate:t=>sr(t,1,2,"styleRef","property, optional element")??Qe(t,0,"styleRef","property")??(2===t.length&&t[1]&&"object"!=typeof t[1]?"styleRef element must be an HTMLElement":null)},possessiveStyleRef:{name:"possessiveStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const r=e[0],n=e[1];if("string"!=typeof r||"string"!=typeof n)throw Error("Possessive styleRef requires possessor and property strings");let s=null;if("my"===r&&t.me?s=t.me instanceof HTMLElement?t.me:null:"its"===r&&t.it&&(s=t.it instanceof HTMLElement?t.it:null),s){if(n.startsWith("computed-")){const t=n.substring(9);return getComputedStyle(s).getPropertyValue(t)||""}return s.style.getPropertyValue(n)||void 0}},validate:t=>Ke(t,2,"possessiveStyleRef","possessor, property")??Qe(t,0,"possessiveStyleRef","possessor")??Qe(t,1,"possessiveStyleRef","property")},ofStyleRef:{name:"ofStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const r=e[0],n=e[1];if("string"!=typeof r||"string"!=typeof n)throw Error("Of styleRef requires property and reference strings");let s=null;if("me"===n&&t.me?s=t.me instanceof HTMLElement?t.me:null:"it"===n&&t.it&&(s=t.it instanceof HTMLElement?t.it:null),s){if(r.startsWith("computed-")){const t=r.substring(9);return getComputedStyle(s).getPropertyValue(t)||""}return s.style.getPropertyValue(r)||void 0}},validate:t=>Ke(t,2,"ofStyleRef","property, reference")??Qe(t,0,"ofStyleRef","property")??Qe(t,1,"ofStyleRef","reference")}};class wr{constructor(t=100,e=5e3){this.maxSize=t,this.ttl=e,this.cache=new Map,this.accessOrder=new Map,this.accessCounter=0}get(t){const e=this.cache.get(t);if(e){if(Date.now()-e.timestamp<=this.ttl)return e.accessCount++,this.accessOrder.set(t,++this.accessCounter),e.result;this.delete(t)}}set(t,e){this.maxSize>this.cache.size||this.cache.has(t)||this.evictLRU();const r={result:e,timestamp:Date.now(),accessCount:1};this.cache.set(t,r),this.accessOrder.set(t,++this.accessCounter)}delete(t){return this.accessOrder.delete(t),this.cache.delete(t)}clear(){this.cache.clear(),this.accessOrder.clear(),this.accessCounter=0}size(){return this.cache.size}evictLRU(){let t,e=1/0;for(const[r,n]of this.accessOrder)e>n&&(e=n,t=r);void 0!==t&&this.delete(t)}getStats(){const t=Array.from(this.cache.values()),e=Date.now();return{size:this.cache.size,maxSize:this.maxSize,hitRate:t.length>0?t.filter(t=>t.accessCount>1).length/t.length:0,avgAge:t.length>0?t.reduce((t,r)=>t+(e-r.timestamp),0)/t.length:0,totalAccesses:t.reduce((t,e)=>t+e.accessCount,0)}}}const xr=new class{constructor(){this.domQueryCache=new wr(200,3e3),this.exprResultCache=new wr(500,2e3),this.cssMatchCache=new wr(100,5e3),this.formValueCache=new wr(50,1e3),this.hits=0,this.misses=0}querySelector(t){const e="querySelector:"+t,r=this.domQueryCache.get(e);if(void 0!==r)return this.hits++,r;this.misses++;const n=document.querySelector(t);return this.domQueryCache.set(e,n),n}querySelectorAll(t){const e="querySelectorAll:"+t,r=this.domQueryCache.get(e);if(void 0!==r)return this.hits++,r;this.misses++;const n=Array.from(document.querySelectorAll(t));return this.domQueryCache.set(e,n),n}getElementById(t){const e="getElementById:"+t,r=this.domQueryCache.get(e);if(void 0!==r)return this.hits++,r;this.misses++;const n=document.getElementById(t);return this.domQueryCache.set(e,n),n}getElementsByClassName(t){const e="getElementsByClassName:"+t,r=this.domQueryCache.get(e);if(void 0!==r)return this.hits++,r;this.misses++;const n=Array.from(document.getElementsByClassName(t));return this.domQueryCache.set(e,n),n}matches(t,e){const r=`matches:${this.getElementCacheKey(t)}:${e}`,n=this.cssMatchCache.get(r);if(void 0!==n)return this.hits++,n;this.misses++;const s=t.matches(e);return this.cssMatchCache.set(r,s),s}getExpressionResult(t){const e=this.exprResultCache.get(t);if(void 0!==e)return this.hits++,e;this.misses++}setExpressionResult(t,e){this.exprResultCache.set(t,e)}getFormValue(t){const e=this.getElementCacheKey(t),r=this.formValueCache.get("formValue:"+e);if(void 0!==r)return this.hits++,r;this.misses++}setFormValue(t,e){const r=this.getElementCacheKey(t);this.formValueCache.set("formValue:"+r,e)}invalidateElementCache(t){const e=this.getElementCacheKey(t);for(const t of[this.domQueryCache,this.cssMatchCache,this.formValueCache])for(const r of Array.from(t.cache.keys()))"string"==typeof r&&r.includes(e)&&t.delete(r)}invalidateAll(){this.domQueryCache.clear(),this.exprResultCache.clear(),this.cssMatchCache.clear(),this.formValueCache.clear(),this.hits=0,this.misses=0}getElementCacheKey(t){if(t.id)return"#"+t.id;const e=Array.from(t.classList).sort().join("."),r=this.getElementPosition(t);return`${t.tagName.toLowerCase()}${e?"."+e:""}@${r}`}getElementPosition(t){return""+Array.from(t.parentElement?.children||[]).indexOf(t)}getPerformanceStats(){const t=this.hits+this.misses;return{hits:this.hits,misses:this.misses,hitRate:Math.round(100*(t>0?this.hits/t*100:0))/100,domQueryCache:this.domQueryCache.getStats(),exprResultCache:this.exprResultCache.getStats(),cssMatchCache:this.cssMatchCache.getStats(),formValueCache:this.formValueCache.getStats()}}cleanup(){const t=Date.now();[this.domQueryCache,this.exprResultCache,this.cssMatchCache,this.formValueCache].forEach(e=>{Array.from(e.cache.entries()).forEach(([r,n])=>{t-n.timestamp>e.ttl&&e.delete(r)})})}};"undefined"!=typeof window&&setInterval(()=>{xr.cleanup()},1e4);const kr=new class{constructor(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0},this.startTimes=new Map}startTimer(t){this.startTimes.set(t,performance.now())}endTimer(t){const e=this.startTimes.get(t);if(e){const r=performance.now()-e;return this.startTimes.delete(t),r}return 0}recordTokenization(t){this.metrics.tokenizationTime+=t}recordEvaluation(t){this.metrics.evaluationTime+=t}updateCacheMetrics(){const t=xr.getPerformanceStats();this.metrics.cacheHitRate=t.hitRate}getMetrics(){return this.updateCacheMetrics(),{...this.metrics}}reset(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0}}};function Ar(){xr.cleanup(),kr.getMetrics().memoryUsage>52428800&&kr.reset()}let Sr=null;function Cr(t,e){if("number"==typeof t){if(!Number.isFinite(t))throw Error(`${e} must be a finite number, got ${t}`);return t}if("string"==typeof t){const r=t.trim();if(""===r)return 0;const n=parseFloat(r);if(isNaN(n))throw Error(`${e} cannot be converted to number: "${t}"`);return n}if("boolean"==typeof t)return t?1:0;if(null==t)return 0;if("object"==typeof t&&null!==t){if(Array.isArray(t)&&1===t.length){const r=t[0];if(Array.isArray(r))throw Error(e+" is a nested array, cannot convert to number");return Cr(r,e)}if("string"==typeof t.textContent||"value"in t){const e=t.value??t.textContent;if(null!=e){const t=(e+"").trim();if(""===t)return 0;const r=parseFloat(t);if(!isNaN(r))return r}}const r=t.valueOf();if("number"==typeof r&&Number.isFinite(r))return r}throw Error(`${e} cannot be converted to number: ${typeof t}`)}function Nr(t){if("number"==typeof t)return Number.isFinite(t)?t:null;if("string"==typeof t){const e=t.trim();if(""===e)return 0;const r=parseFloat(e);return isNaN(r)?null:r}return"boolean"==typeof t?t?1:0:null==t?0:null}function Tr(t,e,r){if("==="===r)return t===e;if("!=="===r)return t!==e;if(null==t||null==e)return function(t,e,r){if(null==t&&null==e)switch(r){case"==":case">=":case"<=":return 1;default:return 0}switch(r){case"==":case">":case"<":case">=":case"<=":default:return 0;case"!=":return 1}}(t,e,r);const[n,s]=function(t,e){if("number"==typeof t&&"number"==typeof e)return[t,e];if("string"==typeof t&&"string"==typeof e){const r=parseFloat(t),n=parseFloat(e);return isNaN(r)||isNaN(n)?[t,e]:[r,n]}const r=Nr(t),n=Nr(e);return null!==r&&null!==n?[r,n]:[t+"",e+""]}(t,e);switch(r){case">":return n>s;case"<":return s>n;case">=":return n>=s;case"<=":return s>=n;case"==":return Or(t,e);case"!=":return!Or(t,e);default:return 0}}function Or(t,e){if(t===e)return 1;if(typeof t==typeof e)return"string"==typeof t||"number"==typeof t?t===e:0;if("number"==typeof t&&"string"==typeof e){const r=parseFloat(e);return!isNaN(r)&&t===r}if("string"==typeof t&&"number"==typeof e){const r=parseFloat(t);return!isNaN(r)&&r===e}return"boolean"==typeof t?Or(t?1:0,e):"boolean"==typeof e?Or(t,e?1:0):t+""==e+""}function Lr(t,e,r,n,s,i=1,o){return e&&"object"==typeof e&&"evaluationHistory"in e&&Array.isArray(e.evaluationHistory)&&e.evaluationHistory.push({expressionName:t.name,category:t.category,input:r,output:n,timestamp:s,duration:Date.now()-s,success:i,...void 0!==o&&{error:o}}),n}"undefined"!=typeof window&&function(t=3e4){Sr&&clearInterval(Sr),Sr=setInterval(Ar,t)}();const $r=dr({left:mr().describe("Left operand value"),right:mr().describe("Right operand value")}).strict(),Rr=dr({operand:mr().describe("Operand value to negate")}).strict();function Ir(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType}new class extends gr{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=$r,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:0,error:n.errors[0]};const s=this.toBoolean(e.left);if(!s)return this.trackSimple(t,r,1,"boolean"),this.success(0,"boolean");const i=this.toBoolean(e.right),o=s&&i;return this.trackSimple(t,r,1,"boolean"),this.success(o,"boolean")}catch(e){return this.trackSimple(t,r,0),this.failure("AndExpressionError","runtime-error","Logical AND operation failed: "+(e instanceof Error?e.message:e+""),"AND_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid AND operation input: "+t.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends gr{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=$r,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:0,error:n.errors[0]};const s=this.toBoolean(e.left);if(s)return this.trackSimple(t,r,1,"boolean"),this.success(1,"boolean");const i=this.toBoolean(e.right),o=s||i;return this.trackSimple(t,r,1,"boolean"),this.success(o,"boolean")}catch(e){return this.trackSimple(t,r,0),this.failure("OrExpressionError","runtime-error","Logical OR operation failed: "+(e instanceof Error?e.message:e+""),"OR_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid OR operation input: "+t.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends gr{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=Rr,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:0,error:n.errors[0]};const s=!this.toBoolean(e.operand);return this.trackSimple(t,r,1,"boolean"),this.success(s,"boolean")}catch(e){return this.trackSimple(t,r,0),this.failure("NotExpressionError","runtime-error","Logical NOT operation failed: "+(e instanceof Error?e.message:e+""),"NOT_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid NOT operation input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a single operand","Ensure operand is a valid value"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}};const jr=pr([mr(),mr()]),Dr=pr([mr(),ur()]),Mr={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(t,e,r){const n=Date.now();try{return Lr(this,t,[e,r],e==r,n)}catch(s){throw Lr(this,t,[e,r],0,n,0,s instanceof Error?s:Error(s+"")),s}},validate:t=>er(t,"equals"),inputSchema:jr,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"value is 5",description:"Check if value equals 5 using loose equality",expectedOutput:1,context:{result:5}},{input:'"5" == 5',description:'String "5" equals number 5 with type coercion',expectedOutput:1}],relatedExpressions:["strictEquals","notEquals"],performance:{averageTime:.001,complexity:"O(1)"}},documentation:{summary:"Compares two values for loose equality, allowing type coercion",parameters:[{name:"left",type:"unknown",description:"Left operand for comparison",optional:0,examples:["5",'"hello"',"true","null"]},{name:"right",type:"unknown",description:"Right operand for comparison",optional:0,examples:["5",'"hello"',"true","null"]}],returns:{type:"Boolean",description:"True if values are loosely equal, false otherwise",examples:["true","false"]},examples:[{title:"Basic equality check",code:"if my.value is 10",explanation:"Check if element value equals 10",output:"Boolean result"},{title:"Type coercion",code:'if "5" == 5',explanation:'String "5" equals number 5 with automatic type conversion',output:"true"},{title:"Null checks",code:"if value is null",explanation:"Check if value is null or undefined",output:"Boolean result"}],seeAlso:["strictEquals","notEquals","matches"],tags:["comparison","equality","logic","type-coercion"]}},Pr={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=e===r;return n&&Lr(this,t,[e,r],i,s),i},validate:t=>er(t,"strictEquals")},Vr={name:"notEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=","is not","does not equal"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=e!=r;return n&&Lr(this,t,[e,r],i,s),i},validate:t=>er(t,"notEquals")},Br={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=e!==r;return n&&Lr(this,t,[e,r],i,s),i},validate:t=>er(t,"strictNotEquals")},_r={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=Tr(e,r,"<");return n&&Lr(this,t,[e,r],i,s),i},validate:t=>er(t,"lessThan")},Fr={name:"lessThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<=","is less than or equal to"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=Tr(e,r,"<=");return n&&Lr(this,t,[e,r],i,s),i},validate:t=>er(t,"lessThanOrEqual")},qr={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=Tr(e,r,">");return n&&Lr(this,t,[e,r],i,s),i},validate:t=>er(t,"greaterThan")},Hr={name:"greaterThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">=","is greater than or equal to"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=Tr(e,r,">=");return n&&Lr(this,t,[e,r],i,s),i},validate:t=>er(t,"greaterThanOrEqual")},Ur={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(t,e,r){const n=Date.now();try{return Lr(this,t,[e,r],e&&r,n)}catch(s){throw Lr(this,t,[e,r],0,n,0,s instanceof Error?s:Error(s+"")),s}},validate:t=>er(t,"and"),inputSchema:jr,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"true and false",description:"Logical AND of boolean values",expectedOutput:0},{input:"name and age",description:"Both name and age must be truthy",expectedOutput:1,context:{variables:new Map([["name","John"],["age",25]])}}],relatedExpressions:["or","not"],performance:{averageTime:.001,complexity:"O(1)"}},documentation:{summary:"Logical AND operation that returns true only if both operands are truthy",parameters:[{name:"left",type:"unknown",description:"Left operand (evaluated for truthiness)",optional:0,examples:["true","name","5",'"hello"']},{name:"right",type:"unknown",description:"Right operand (evaluated for truthiness)",optional:0,examples:["false","age","0",'""']}],returns:{type:"Boolean",description:"True if both operands are truthy, false otherwise",examples:["true","false"]},examples:[{title:"Form validation",code:"if name and email",explanation:"Check if both name and email have values",output:"Boolean result"},{title:"Multiple conditions",code:"if age > 18 and hasLicense",explanation:"Combine multiple conditions",output:"Boolean result"},{title:"Short-circuit evaluation",code:"if element and element.value",explanation:"Check element exists before accessing properties",output:"Boolean result"}],seeAlso:["or","not","exists"],tags:["logic","boolean","conditions","validation"]}},Wr={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=e||r;return n&&Lr(this,t,[e,r],i,s),i},validate:t=>er(t,"or")},zr={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],async evaluate(t,e){const r=t.evaluationHistory,n=r?Date.now():0,s=!e;return r&&Lr(this,t,[e],s,n),s},validate:t=>Ke(t,1,"not","operand")},Jr={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],async evaluate(t,e){const r=t.evaluationHistory,n=r?Date.now():0;let s;return s=null==e?1:$e(e)||Array.isArray(e)||e instanceof NodeList?0===e.length:e instanceof Node||e instanceof Element?0:je(e)?0===Object.keys(e).length:0,r&&Lr(this,t,[e],s,n),s},validate:t=>Ke(t,1,"isEmpty","value")},Zr={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],async evaluate(t,e){const r=t.evaluationHistory,n=r?Date.now():0;let s;return s=null==e||0==e?1:Array.isArray(e)||e instanceof NodeList?0===e.length:$e(e)||e instanceof Node||e instanceof Element?0:je(e)?0===Object.keys(e).length:0,r&&Lr(this,t,[e],s,n),s},validate:t=>Ke(t,1,"no","value")},Gr={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],async evaluate(t,e){const r=t.evaluationHistory,n=r?Date.now():0,s=!await Jr.evaluate(t,e);return r&&Lr(this,t,[e],s,n),s},validate:t=>Ke(t,1,"isNotEmpty","value")},Xr={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],async evaluate(t,e){const r=t.evaluationHistory,n=r?Date.now():0,s=null!=e;return r&&Lr(this,t,[e],s,n),s},validate:t=>Ke(t,1,"exists","value")},Yr={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],async evaluate(t,e){const r=t.evaluationHistory,n=r?Date.now():0,s=null==e;return r&&Lr(this,t,[e],s,n),s},validate:t=>Ke(t,1,"doesNotExist","value")},Kr={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0;let i;if(e&&r){if(Ir(e)&&Ir(r))return i=e.contains(r),n&&Lr(this,t,[e,r],i,s),i;if($e(e)&&e.match(/^[.#][\w-]+$/)){const o=document.querySelector(e);if(o&&Ir(r))return i=o.contains(r),n&&Lr(this,t,[e,r],i,s),i;if(o&&$e(r)&&r.match(/^[.#][\w-]+$/)){const a=document.querySelector(r);return i=a?o.contains(a):0,n&&Lr(this,t,[e,r],i,s),i}}if($e(r)&&r.match(/^[.#][\w-]+$/)&&Ir(e)){const o=document.querySelector(r);return i=o?e.contains(o):0,n&&Lr(this,t,[e,r],i,s),i}}return i=$e(e)&&$e(r)||Array.isArray(e)?e.includes(r):"undefined"!=typeof NodeList&&e instanceof NodeList?Array.from(e).includes(r):je(e)&&$e(r)?r in e:0,n&&Lr(this,t,[e,r],i,s),i},validate:t=>Ke(t,2,"contains","container, value")},Qr={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=!await Kr.evaluate(t,e,r);return n&&Lr(this,t,[e,r],i,s),i},validate:t=>Ke(t,2,"doesNotContain","container, value")},tn={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=$e(e)&&$e(r)?e.startsWith(r):0;return n&&Lr(this,t,[e,r],i,s),i},validate:t=>Ke(t,2,"startsWith","str, prefix")},en={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=$e(e)&&$e(r)?e.endsWith(r):0;return n&&Lr(this,t,[e,r],i,s),i},validate:t=>Ke(t,2,"endsWith","str, suffix")},rn={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(t,e,r){const n=Date.now();try{let s;if(e instanceof Element&&$e(r)){const t=r;if(t.startsWith(".")||t.startsWith("#")||t.startsWith(":")||t.startsWith("[")||/^[a-zA-Z][\w-]*$/.test(t))try{s=function(t,e){return xr.matches(t,e)}(e,t)}catch(t){s=0}else s=0}else if($e(e)&&$e(r)){const t=e,n=r;try{s=(n.startsWith("/")&&n.endsWith("/")?RegExp(n.slice(1,-1)):RegExp(n)).test(t)}catch(e){s=t.includes(n)}}else s=0;return Lr(this,t,[e,r],s,n)}catch(s){throw Lr(this,t,[e,r],0,n,0,s instanceof Error?s:Error(s+"")),s}},validate:t=>Ke(t,2,"matches","element, selector"),inputSchema:Dr,metadata:{category:"Logical",complexity:"medium",sideEffects:["dom-query"],dependencies:[],returnTypes:["Boolean"],examples:[{input:'element matches ".active"',description:"Check if element has active class",expectedOutput:1},{input:'text matches "/^hello/"',description:'Check if text starts with "hello" using regex',expectedOutput:1,context:{variables:new Map([["text","hello world"]])}}],relatedExpressions:["contains","startsWith","endsWith"],performance:{averageTime:.5,complexity:"O(n)"}},documentation:{summary:"Tests if element matches CSS selector or string matches regex pattern",parameters:[{name:"element",type:"Element | string",description:"DOM element or string to test",optional:0,examples:["<div>",'"hello world"',"me","target"]},{name:"selector",type:"string",description:"CSS selector or regex pattern to match against",optional:0,examples:['".active"','"#navbar"','"/^hello/"','"\\\\d+"']}],returns:{type:"Boolean",description:"True if element matches selector/pattern",examples:["true","false"]},examples:[{title:"CSS class matching",code:'if me matches ".active"',explanation:'Check if current element has "active" class',output:"Boolean result"},{title:"Attribute matching",code:'if target matches "[data-role=\\"button\\"]"',explanation:"Check if element has specific data attribute",output:"Boolean result"},{title:"Regex pattern matching",code:'if email matches "/^[^@]+@[^@]+\\\\.[^@]+$/"',explanation:"Validate email format with regex",output:"Boolean result"},{title:"Complex CSS selector",code:'if element matches ".card:hover .button"',explanation:"Match complex CSS selector with pseudo-classes",output:"Boolean result"}],seeAlso:["contains","startsWith","endsWith","querySelector"],tags:["pattern","css","regex","validation","dom"]}},nn={name:"has",category:"Logical",evaluatesTo:"Boolean",operators:["has","have"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0;let i=0;if(e instanceof Element&&$e(r)){const t=r;t.startsWith(".")?i=e.classList.contains(t.slice(1)):t.startsWith("[")&&t.endsWith("]")&&(i=e.hasAttribute(t.slice(1,-1)))}return n&&Lr(this,t,[e,r],i,s),i},validate:t=>Ke(t,2,"has","element, selector")},sn={name:"doesNotHave",category:"Logical",evaluatesTo:"Boolean",operators:["does not have"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=!await nn.evaluate(t,e,r);return n&&Lr(this,t,[e,r],i,s),i},validate:t=>Ke(t,2,"doesNotHave","element, selector")},on={equals:Mr,strictEquals:Pr,notEquals:Vr,strictNotEquals:Br,lessThan:_r,lessThanOrEqual:Fr,greaterThan:qr,greaterThanOrEqual:Hr,and:Ur,or:Wr,not:zr,no:Zr,isEmpty:Jr,isNotEmpty:Gr,exists:Xr,doesNotExist:Yr,contains:Kr,doesNotContain:Qr,startsWith:tn,endsWith:en,matches:rn,has:nn,doesNotHave:sn};function an(t,e,r,n,s="runtime-error"){return{success:0,error:{name:t+"ConversionError",type:s,message:r,code:e,suggestions:n}}}function cn(t,e){return{success:1,value:t,type:e}}function ln(t,e){return`${t}: ${e instanceof Error?e.message:e+""}`}const un={Array:(t,e)=>{try{return Array.isArray(t)?cn(t,"array"):t instanceof NodeList?cn(Array.from(t),"array"):cn(null==t?[]:[t],"array")}catch(t){return an("Array","ARRAY_CONVERSION_FAILED",ln("Failed to convert value to Array",t),["Check if value is iterable","Ensure value is not circular reference"])}},String:(t,e)=>{try{return null==t?cn("","string"):$e(t)?cn(t,"string"):je(t)?cn(JSON.stringify(t),"string"):cn(t+"","string")}catch(t){return an("String","STRING_CONVERSION_FAILED",ln("Failed to convert value to String",t),["Check if object has circular references","Ensure value is serializable"])}},Boolean:(t,e)=>{try{if(Ie(t))return cn(t,"boolean");if(null==t)return cn(0,"boolean");if($e(t)){const e=t.toLowerCase().trim();return cn("false"!==e&&"0"!==e&&""!==e,"boolean")}return Re(t)?cn(0!==t&&!isNaN(t),"boolean"):cn(!!t,"boolean")}catch(t){return an("Boolean","BOOLEAN_CONVERSION_FAILED",ln("Failed to convert value to Boolean",t),["Use explicit true/false values","Check for unexpected data types"])}},Number:(t,e)=>{try{if(Re(t))return cn(t,"number");if(null==t)return cn(0,"number");const e=Number(t);return isNaN(e)?an("Number","INVALID_NUMBER",`Cannot convert "${t}" to a valid number`,["Check if value contains non-numeric characters","Use a valid numeric format"],"invalid-argument"):cn(e,"number")}catch(t){return an("Number","NUMBER_CONVERSION_FAILED",ln("Failed to convert value to Number",t),["Ensure value is convertible to number","Check for special characters"])}},Int:(t,e)=>{const r=un.Number(t,e);return r.success?cn(Math.trunc(r.value),"number"):r},Float:(t,e)=>{const r=un.Number(t,e);return r.success?cn(parseFloat(""+r.value),"number"):r},Date:(t,e)=>{try{if(t instanceof Date)return cn(t,"object");if(null==t)return cn(new Date(""),"object");if($e(t)&&/^\d{4}-\d{2}-\d{2}$/.test(t)){const[e,r,n]=t.split("-").map(Number);return cn(new Date(e,r-1,n),"object")}const e=new Date(t);return isNaN(e.getTime())?an("Date","INVALID_DATE",`Cannot convert "${t}" to a valid date`,["Use ISO 8601 format (YYYY-MM-DD)","Check date string format","Ensure date values are valid"],"invalid-argument"):cn(e,"object")}catch(t){return an("Date","DATE_CONVERSION_FAILED",ln("Failed to convert value to Date",t),["Check date format","Ensure value is a valid date string or timestamp"])}},JSON:(t,e)=>{try{return cn(JSON.stringify(t),"string")}catch(t){return an("JSON","JSON_STRINGIFY_FAILED",ln("Failed to convert value to JSON",t),["Check for circular references","Ensure all properties are serializable","Remove functions and undefined values"])}},Object:(t,e)=>{try{if(je(t))return cn(t,"object");if($e(t))try{return cn(JSON.parse(t),"object")}catch(t){return an("Object","JSON_PARSE_FAILED",ln("Cannot parse JSON string",t),["Check JSON syntax","Ensure proper escaping of quotes","Validate JSON format"],"syntax-error")}return cn({},"object")}catch(t){return an("Object","OBJECT_CONVERSION_FAILED",ln("Failed to convert value to Object",t),["Ensure value is valid JSON string or object","Check for syntax errors"])}},Values:(t,e)=>{try{if(t instanceof HTMLFormElement)return cn(function(t){const e={};return t.querySelectorAll("input, select, textarea").forEach(t=>{const r=t;if(r.name){const t=dn(r);void 0!==t&&(void 0!==e[r.name]?(Array.isArray(e[r.name])||(e[r.name]=[e[r.name]]),e[r.name].push(t)):e[r.name]=t)}}),e}(t),"object");if(t instanceof HTMLElement){const e=t.querySelectorAll("input, select, textarea"),r={};return e.forEach(t=>{const e=t;if(e.name){const t=dn(e);void 0!==t&&(r[e.name]=t)}}),cn(r,"object")}return cn({},"object")}catch(t){return an("FormValues","FORM_VALUES_EXTRACTION_FAILED",ln("Failed to extract form values",t),["Ensure element is a form or contains form inputs","Check form structure","Verify input names are set"])}}},hn=dr({value:yr(),type:ur().min(1)}),fn=dr({value:yr(),type:ur().min(1)});function dn(t){if(t instanceof HTMLInputElement)switch(t.type){case"checkbox":return t.checked;case"radio":return t.checked?t.value:void 0;case"number":case"range":return t.valueAsNumber;case"date":case"datetime-local":return t.valueAsDate;case"file":return t.files;default:return t.value}return t instanceof HTMLSelectElement&&t.multiple?Array.from(t.selectedOptions).map(t=>t.value):t.value}new class extends gr{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=hn,this.metadata={category:"Conversion",complexity:"medium",sideEffects:[],dependencies:[],returnTypes:["Any"],examples:[{input:'"123" as Int',description:"Convert string to integer",expectedOutput:123},{input:"form as Values",description:"Extract form values as object",expectedOutput:{name:"John",age:"25"}},{input:"[1,2,3] as JSON",description:"Convert array to JSON string",expectedOutput:"[1,2,3]"},{input:'"2023-12-25" as Date',description:"Parse date string",expectedOutput:new Date(2023,11,25)}],relatedExpressions:["is","Object","Array"],performance:{averageTime:1,complexity:"O(n)"}},this.documentation={summary:'Converts values between different types using the "as" keyword with comprehensive type safety',parameters:[{name:"value",type:"object",description:"The value to convert",optional:0,examples:['"123"',"form","[1,2,3]","true","null"]},{name:"type",type:"string",description:"Target conversion type",optional:0,examples:["Int","String","Boolean","Array","JSON","Object","Date","Values","HTML","Fragment"]}],returns:{type:"object",description:"Structured result with converted value or detailed error information",examples:['{ success: true, value: 123, type: "number" }',"{ success: false, error: { ... } }"]},examples:[{title:"String to number conversion",code:"if my.value as Int > 100",explanation:"Convert form input to integer for comparison",output:"Boolean result"},{title:"Form data extraction",code:"put closest <form /> as Values into result",explanation:"Extract all form values as structured object",output:'{ name: "John", age: "25", ... }'},{title:"Array to JSON serialization",code:"put items as JSON into storage",explanation:"Convert array to JSON string for storage",output:'"[1,2,3]"'},{title:"Date parsing with validation",code:"put my.dateInput as Date into event.detail.date",explanation:"Parse date input with automatic validation",output:"Date object or validation error"},{title:"Boolean conversion with smart parsing",code:'if "false" as Boolean then hide else show',explanation:"Parse string boolean values correctly",output:"false (not true like naive conversion)"}],seeAlso:["is","Values","JSON","Array","Object"],tags:["conversion","types","validation","forms","json","parsing"]}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:0,error:{name:"AsExpressionValidationError",type:"validation-error",message:n.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:n.suggestions}};const{value:s,type:i}=e;if(i.startsWith("Fixed")){const n=i.match(/^Fixed:(\d+)$/),o=n?parseInt(n[1],10):2,a=un.Number(s,t);if(!a.success)return a;const c={success:1,value:a.value.toFixed(o),type:"string"};return this.trackPerformance(t,e,c,r),c}let o=un[i];if(o){const n=o(s,t);return this.trackPerformance(t,e,n,r),n}const a={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON"}[i.toLowerCase()];if(a&&(o=un[a],o)){const n=o(s,t);return this.trackPerformance(t,e,n,r),n}const c={success:0,error:{name:"UnknownConversionTypeError",type:"validation-error",message:"Unknown conversion type: "+i,code:"UNKNOWN_CONVERSION_TYPE",suggestions:["Use supported types: String, Number, Boolean, Array, Object, Date, JSON, Values","Check type spelling and capitalization","See documentation for complete list of conversion types"]}};return this.trackPerformance(t,e,c,r),c}catch(n){const s={success:0,error:{name:"AsExpressionError",type:"runtime-error",message:"Conversion failed: "+(n instanceof Error?n.message:n+""),code:"CONVERSION_FAILED",suggestions:["Check value and type compatibility","Ensure value is convertible to target type"]}};return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?{isValid:1,errors:[],suggestions:[]}:{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:t.message,suggestions:["Expected valid input structure, got: "+t.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(t){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}},new class extends gr{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=fn,this.metadata={category:"Conversion",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"42 is number",description:"Check if value is a number",expectedOutput:1},{input:"null is empty",description:"Check if value is empty/null",expectedOutput:1},{input:"element is Element",description:"Check if value is DOM element",expectedOutput:1,context:{element:"<div>...</div>"}}],relatedExpressions:["as","empty","exists"],performance:{averageTime:.1,complexity:"O(1)"}},this.documentation={summary:"Checks if a value is of a specific type with comprehensive type detection",parameters:[{name:"value",type:"object",description:"The value to check",optional:0,examples:["42","null","element",'"text"',"[]"]},{name:"type",type:"string",description:"Type name to check against",optional:0,examples:["number","string","boolean","array","object","element","empty","null"]}],returns:{type:"object",description:"Boolean result indicating type match",examples:['{ success: true, value: true, type: "boolean" }']},examples:[{title:"Number validation",code:"if my.age is number then proceed",explanation:"Check if form input is valid number",output:"Boolean result"},{title:"Empty check",code:"if result is empty then show message",explanation:"Check if result is null, undefined, or empty",output:"Boolean result"},{title:"Element validation",code:"if target is element then addClass",explanation:"Ensure target is valid DOM element before manipulation",output:"Boolean result"}],seeAlso:["as","empty","exists","null"],tags:["validation","types","checking","guards"]}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:0,error:{name:"IsExpressionValidationError",type:"validation-error",message:n.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:n.suggestions}};const{value:s,type:i}=e,o=i.toLowerCase();let a;switch(o){case"null":a=null===s;break;case"undefined":a=void 0===s;break;case"string":a=$e(s);break;case"number":a=Re(s)&&!isNaN(s);break;case"boolean":a=Ie(s);break;case"object":a=je(s);break;case"array":a=Array.isArray(s);break;case"function":a=De(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||je(s)&&0===Object.keys(s).length;break;default:a=s?.constructor?.name?.toLowerCase()===o}const c=this.success(a,"boolean");return this.trackPerformance(t,e,c,r),c}catch(n){const s=this.failure("IsExpressionError","type-mismatch","Type check failed: "+(n instanceof Error?n.message:n+""),"TYPE_CHECK_FAILED",["Check type name spelling","Ensure value is accessible"]);return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:t.message,suggestions:["Expected valid input structure, got: "+t.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(t){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}};const pn={Array:t=>Array.isArray(t)?t:t instanceof NodeList?Array.from(t):null==t?[]:[t],String:t=>null==t?"":$e(t)?t:je(t)?JSON.stringify(t):t+"",Boolean:t=>{if(Ie(t))return t;if(null==t)return 0;if($e(t)){const e=t.toLowerCase().trim();return"false"===e||"0"===e||""===e?0:1}return Re(t)?0!==t&&!isNaN(t):!!t},Number:t=>{if(Re(t))return t;if(null==t)return 0;const e=Number(t);return isNaN(e)?0:e},Math:t=>{if(Re(t))return t;if(null==t)return 0;const e=(t+"").trim();if(!e)return 0;try{return function(t){if(t=t.replace(/\s/g,""),!/^[0-9+\-*/().]+$/.test(t))throw Error("Invalid characters in math expression");try{const e=Function(`"use strict"; return (${t})`)();if(!Re(e)||!isFinite(e))throw Error("Expression did not evaluate to a finite number");return e}catch(t){throw Error("Math expression evaluation failed: "+(t instanceof Error?t.message:t+""))}}(e)}catch(t){return console.warn("Math conversion failed:",t),0}},Int:t=>{const e=pn.Number(t);return Math.trunc(e)},Float:t=>{const e=pn.Number(t);return parseFloat(""+e)},Date:t=>{if(t instanceof Date)return t;if(null==t)return new Date(NaN);if($e(t)&&/^\d{4}-\d{2}-\d{2}$/.test(t)){const[e,r,n]=t.split("-").map(Number);return new Date(e,r-1,n)}return new Date(t)},JSON:t=>{try{return JSON.stringify(t)}catch(t){return"{}"}},Object:t=>{if(je(t))return t;if($e(t))try{return JSON.parse(t)}catch(t){return{}}return{}},Fragment:t=>{$e(t)||(t=pn.String(t));const e=document.createElement("template");return e.innerHTML=t+"",e.content},HTML:t=>$e(t)?t:t instanceof NodeList?Array.from(t).map(t=>t instanceof Element?t.outerHTML:t.textContent||"").join(""):Array.isArray(t)?t.map(t=>t instanceof Element?t.outerHTML:pn.String(t)).join(""):t instanceof Element?t.outerHTML:pn.String(t),Values:(t,e)=>{if(t instanceof HTMLFormElement)return function(t){const e={};return t.querySelectorAll("input, select, textarea").forEach(t=>{const r=t;if(r.name){const t=mn(r);void 0!==t&&(void 0!==e[r.name]?(Array.isArray(e[r.name])||(e[r.name]=[e[r.name]]),e[r.name].push(t)):e[r.name]=t)}}),e}(t);if(t instanceof HTMLElement){const e=t.querySelectorAll("input, select, textarea"),r={};return e.forEach(t=>{t.name&&(r[t.name]=mn(t))}),r}return{}},"Values:Form":(t,e)=>{const r=pn.Values(t,e);return""+new URLSearchParams(r)},"Values:JSON":(t,e)=>{const r=pn.Values(t,e);return JSON.stringify(r)}};function mn(t){if(t instanceof HTMLInputElement)switch(t.type){case"checkbox":return t.checked;case"radio":return t.checked?t.value:void 0;case"number":case"range":return t.valueAsNumber;case"date":case"datetime-local":return t.valueAsDate;case"file":return t.files;default:return t.value}return t instanceof HTMLSelectElement&&t.multiple?Array.from(t.selectedOptions).map(t=>t.value):t.value}const yn={as:{name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(t,...e){const[r,n]=e;if("string"!=typeof n)throw Error("Conversion type must be a string");if(n.startsWith("Fixed")){const{precision:t}=function(t){const e=t.match(/^Fixed(?::(\d+))?$/);return e?{precision:e[1]?parseInt(e[1],10):2}:{}}(n);return pn.Number(r).toFixed(t||2)}let s=pn[n];if(s)return s(r,t);const i={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON"}[n.toLowerCase()];return i&&(s=pn[i],s)?s(r,t):(console.warn("Unknown conversion type: "+n),r)},validate:t=>Ke(t,2,"as","value, type")??Qe(t,1,"as","conversion type")},is:{name:"is",category:"Conversion",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is a","is an"],async evaluate(t,...e){const[r,n]=e;if(!$e(n))throw Error("Type check requires a string type");switch(n.toLowerCase()){case"null":return null===r;case"undefined":return void 0===r;case"string":return $e(r);case"number":return Re(r)&&!isNaN(r);case"boolean":return Ie(r);case"object":return je(r);case"array":return Array.isArray(r);case"function":return De(r);case"date":return r instanceof Date;case"element":return r instanceof Element;case"node":return r instanceof Node;case"nodelist":return r instanceof NodeList;case"empty":return null==r||""===r||Array.isArray(r)&&0===r.length||je(r)&&0===Object.keys(r).length;default:return r?.constructor?.name?.toLowerCase()===n.toLowerCase()}},validate:t=>Ke(t,2,"is","value, type")??Qe(t,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(t,e)=>e,validate:t=>Ke(t,1,"async","expression")}},vn={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"},gn=dr({collection:mr().describe("Collection to operate on (array, NodeList, or string)")}).strict(),bn=dr({collection:mr().describe("Collection to access"),index:hr().describe("Index position to access")}).strict(),En=dr({collection:mr().describe("Collection to select random item from")}).strict();function wn(t,e){let r=t.nextElementSibling;for(;r;){if(r.matches(e))return r;const t=r.querySelector(e);if(t)return t;r=r.nextElementSibling}const n=t.parentElement;return n&&n!==document.documentElement?wn(n,e):null}function xn(t,e){let r=t.previousElementSibling;for(;r;){const t=Array.from(r.querySelectorAll(e)).reverse();if(t.length>0)return t[0];if(r.matches(e))return r;r=r.previousElementSibling}const n=t.parentElement;return n&&n!==document.documentElement?xn(n,e):null}function kn(t){let e=0,r=t;for(;r&&r.parentElement;)e+=Array.from(r.parentElement.children).indexOf(r),r=r.parentElement,e+=1e3;return e}new class extends gr{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=gn,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:0,error:n.errors[0]};const s=this.normalizeCollection(e.collection),i=s.length>0?s[0]:void 0,o={success:1,value:i,type:vn[this.inferEvaluationType(i)]};return this.trackPerformance(t,e,o,r),o}catch(n){const s=this.failure("FirstExpressionError","runtime-error","First operation failed: "+(n instanceof Error?n.message:n+""),"FIRST_OPERATION_FAILED");return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid first input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends gr{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=gn,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:0,error:n.errors[0]};const s=this.normalizeCollection(e.collection),i=s.length>0?s[s.length-1]:void 0,o={success:1,value:i,type:vn[this.inferEvaluationType(i)]};return this.trackPerformance(t,e,o,r),o}catch(n){const s=this.failure("LastExpressionError","runtime-error","Last operation failed: "+(n instanceof Error?n.message:n+""),"LAST_OPERATION_FAILED");return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid last input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends gr{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=bn,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:0,error:n.errors[0]};const s=this.normalizeCollection(e.collection),i=this.normalizeIndex(e.index,s.length),o=i>=0&&s.length>i?s[i]:void 0,a={success:1,value:o,type:vn[this.inferEvaluationType(o)]};return this.trackPerformance(t,e,a,r),a}catch(n){const s=this.failure("AtExpressionError","runtime-error","At operation failed: "+(n instanceof Error?n.message:n+""),"AT_OPERATION_FAILED");return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid at input: "+t.message,suggestions:[]}))??[],suggestions:["Provide collection and index parameters","Ensure index is a number"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}normalizeIndex(t,e){return 0>t?e+t:t}},new class extends gr{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=En,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:0,error:n.errors[0]};const s=this.normalizeCollection(e.collection);if(0===s.length){const n={success:1,value:void 0,type:"undefined"};return this.trackPerformance(t,e,n,r),n}const i=s[this.getSecureRandomIndex(s.length)],o={success:1,value:i,type:vn[this.inferEvaluationType(i)]};return this.trackPerformance(t,e,o,r),o}catch(n){const s=this.failure("RandomExpressionError","runtime-error","Random operation failed: "+(n instanceof Error?n.message:n+""),"RANDOM_OPERATION_FAILED");return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid random input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}getSecureRandomIndex(t){if("undefined"!=typeof crypto&&crypto.getRandomValues){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]%t}return Math.floor(Math.random()*t)}};const An={first:{name:"first",category:"Reference",evaluatesTo:"Any",operators:["first"],async evaluate(t,e){const r=void 0!==e?e:t.it;return null==r?null:Array.isArray(r)||r instanceof NodeList||r instanceof HTMLCollection?r.length>0?r[0]:null:r instanceof Element?r.children.length>0?r.children[0]:null:$e(r)?r.length>0?r[0]:null:je(r)&&"length"in r&&Re(r.length)&&r.length>0?r[0]:null},validate:t=>nr(t,1,"first","collection")},last:{name:"last",category:"Reference",evaluatesTo:"Any",operators:["last"],async evaluate(t,e){const r=void 0!==e?e:t.it;if(null==r)return null;if(Array.isArray(r))return r.length>0?r[r.length-1]:null;if(r instanceof NodeList||r instanceof HTMLCollection)return r.length>0?r[r.length-1]:null;if(r instanceof Element){const t=r.children;return t.length>0?t[t.length-1]:null}return $e(r)?r.length>0?r[r.length-1]:null:je(r)&&"length"in r&&Re(r.length)&&r.length>0?r[r.length-1]:null},validate:t=>nr(t,1,"last","collection")},at:{name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(t,...e){const[r,n]=e;if(!Re(r))throw Error("Index must be a number");const s=r,i=void 0!==n?n:t.it;if(null==i)return null;if(Array.isArray(i)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}if(i instanceof NodeList||i instanceof HTMLCollection){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}if(i instanceof Element){const t=i.children,e=0>s?t.length+s:s;return e>=0&&t.length>e?t[e]:null}if($e(i)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}if(je(i)&&"length"in i&&Re(i.length)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}return null},validate:t=>sr(t,1,2,"at","index, optional collection")??function(t){return"number"!=typeof t[0]?"at index must be a number":null}(t)},next:{name:"next",category:"Reference",evaluatesTo:"Element",operators:["next"],async evaluate(t,...e){const[r,n]=e,s=n||t.me;return s&&s instanceof Element?r?wn(s,r):s.nextElementSibling:null},validate:t=>nr(t,2,"next","optional selector, optional fromElement")||(1>t.length||null==t[0]||"string"==typeof t[0]?2>t.length||null==t[1]||t[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},previous:{name:"previous",category:"Reference",evaluatesTo:"Element",operators:["previous","prev"],async evaluate(t,...e){const[r,n]=e,s=n||t.me;return s&&s instanceof Element?r?xn(s,r):s.previousElementSibling:null},validate:t=>nr(t,2,"previous","optional selector, optional fromElement")||(1>t.length||null==t[0]||"string"==typeof t[0]?2>t.length||null==t[1]||t[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},nextWithin:{name:"nextWithin",category:"Reference",evaluatesTo:"Element",operators:["next within"],async evaluate(t,...e){const[r,n,s]=e,i=s||t.me;if(!(i&&i instanceof Element))return null;const o=i.closest(n);return o?function(t,e,r){const n=Array.from(r.querySelectorAll(e)),s=kn(t);for(const t of n)if(kn(t)>s)return t;return null}(i,r,o):null},validate:t=>sr(t,2,3,"nextWithin","selector, withinSelector, optional fromElement")||("string"!=typeof t[0]?"selector must be a string":"string"!=typeof t[1]?"withinSelector must be a string":3>t.length||null==t[2]||t[2]instanceof Element?null:"fromElement must be an Element")},previousWithin:{name:"previousWithin",category:"Reference",evaluatesTo:"Element",operators:["previous within"],async evaluate(t,...e){const[r,n,s]=e,i=s||t.me;if(!(i&&i instanceof Element))return null;const o=i.closest(n);return o?function(t,e,r){const n=Array.from(r.querySelectorAll(e)),s=kn(t);for(let t=n.length-1;t>=0;t--){const e=n[t];if(s>kn(e))return e}return null}(i,r,o):null},validate:t=>sr(t,2,3,"previousWithin","selector, withinSelector, optional fromElement")||("string"!=typeof t[0]?"selector must be a string":"string"!=typeof t[1]?"withinSelector must be a string":3>t.length||null==t[2]||t[2]instanceof Element?null:"fromElement must be an Element")}},Sn=new Set(["__proto__","constructor","prototype"]),Cn={possessive:{name:"possessive",category:"Reference",evaluatesTo:"Any",operators:["'s","s"],async evaluate(t,...e){const[r,n]=e;if(null!=r){if("string"!=typeof n)throw Error("Property name must be a string");if(r instanceof Element)return Fe(r,n);if(je(r)){if(Sn.has(n))return;return r[n]}return r[n]}},validate:t=>Ke(t,2,"possessive","element, property")??Qe(t,1,"possessive","property name")},my:{name:"my",category:"Reference",evaluatesTo:"Any",operators:["my"],async evaluate(t,...e){const[r]=e;if(t.me){if("string"!=typeof r)throw Error("Property name must be a string");if(t.me instanceof Element)return Fe(t.me,r);if(je(t.me)){if(Sn.has(r))return;return t.me[r]}return t.me[r]}},validate:t=>tr(t,"my","property")},its:{name:"its",category:"Reference",evaluatesTo:"Any",operators:["its"],async evaluate(t,...e){const[r]=e;if(null==t.it)return;if("string"!=typeof r)throw Error("Property name must be a string");const n=t.it;if(n instanceof Element)return Fe(n,r);if(je(n)){if(Sn.has(r))return;return n[r]}return n[r]},validate:t=>tr(t,"its","property")},your:{name:"your",category:"Reference",evaluatesTo:"Any",operators:["your"],async evaluate(t,...e){const[r]=e;if(t.you){if("string"!=typeof r)throw Error("Property name must be a string");if(t.you instanceof Element)return Fe(t.you,r);if(je(t.you)){if(Sn.has(r))return;return t.you[r]}return t.you[r]}},validate:t=>tr(t,"your","property")},of:{name:"of",category:"Reference",evaluatesTo:"Any",operators:["of"],async evaluate(t,...e){const[r,n]=e;if(null!=n){if("string"!=typeof r)throw Error("Property name must be a string");if(n instanceof Element)return Fe(n,r);if(je(n)){if(Sn.has(r))return;return n[r]}return n[r]}},validate:t=>Ke(t,2,"of","property, object")??Qe(t,0,"of","property name")},attribute:{name:"attribute",category:"Reference",evaluatesTo:"String",operators:["@"],async evaluate(t,...e){const[r,n]=e;if("string"!=typeof r)throw Error("Attribute name must be a string");const s=n||t.me;return s&&s instanceof Element?s.getAttribute(r):null},validate:t=>sr(t,1,2,"attribute","attributeName, optional element")??Qe(t,0,"attribute","attribute name")??(2>t.length||null==t[1]||t[1]instanceof Element?null:"attribute element must be an Element")},attributeWithValue:{name:"attributeWithValue",category:"Reference",evaluatesTo:"Boolean",operators:["@="],async evaluate(t,...e){const[r,n,s]=e;if("string"!=typeof r)throw Error("Attribute name must be a string");if("string"!=typeof n)throw Error("Expected value must be a string");const i=s||t.me;return i&&i instanceof Element?i.getAttribute(r)===n:0},validate:t=>sr(t,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??Qe(t,0,"attributeWithValue","attribute name")??Qe(t,1,"attributeWithValue","expected value")??(3>t.length||null==t[2]||t[2]instanceof Element?null:"attributeWithValue element must be an Element")},classReference:{name:"classReference",category:"Reference",evaluatesTo:"Array",operators:["."],async evaluate(t,...e){const[r]=e;if("string"!=typeof r)throw Error("Class name must be a string");const n=r.startsWith(".")?r.slice(1):r,s=document.getElementsByClassName(n);return Array.from(s)},validate:t=>tr(t,"classReference","className")},idReference:{name:"idReference",category:"Reference",evaluatesTo:"Element",operators:["#"],async evaluate(t,...e){const[r]=e;if("string"!=typeof r)throw Error("ID value must be a string");const n=r.startsWith("#")?r.slice(1):r;return document.getElementById(n)},validate:t=>tr(t,"idReference","idValue")}},Nn=dr({value:ur().describe("String literal value")}).strict(),Tn=dr({value:hr().describe("Number literal value")}).strict(),On=dr({value:fr().describe("Boolean literal value")}).strict(),Ln=dr({left:mr().describe("Left operand"),right:mr().describe("Right operand")}).strict(),$n={stringLiteral:new class extends gr{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=Nn,this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid){const e=this.failure("ValidationError","validation-error",n.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",n.suggestions);return this.trackSimple(t,r,0),e}let s=e.value;(s.includes("${")||s.includes("$"))&&(s=this.interpolateString(s,t));const i=this.success(s,"string");return this.trackSimple(t,r,1,s),i}catch(e){return this.trackSimple(t,r,0),this.failure("StringEvaluationError","runtime-error","String literal evaluation failed: "+(e instanceof Error?e.message:e+""),"STRING_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid string literal input",["Provide a value parameter","Ensure value is a string"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}interpolateString(t,e){let r=t.replace(/\$\{([^}]+)\}/g,(t,r)=>{try{const t=this.resolveExpression(r.trim(),e);return void 0!==t?t+"":""}catch(t){return""}});return r=r.replace(/\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g,(t,r)=>{try{const t=this.resolveVariable(r,e);return void 0!==t?t+"":""}catch(t){return""}}),r}resolveExpression(t,e){if(t.includes(".")){const r=t.split(".");let n=this.resolveVariable(r[0],e);for(let t=1;r.length>t&&null!=n;t++)n=n[r[t]];return n}return this.resolveVariable(t,e)}resolveVariable(t,e){return"me"===t&&e.me?e.me:"you"===t&&e.you?e.you:"it"===t&&e.it?e.it:"result"===t&&e.result?e.result:e.locals?.has(t)?e.locals.get(t):e.globals?.has(t)?e.globals.get(t):void 0}},numberLiteral:new class extends gr{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=Tn,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);return n.isValid?Number.isFinite(e.value)?(this.trackSimple(t,r,1,e.value),this.success(e.value,"number")):(this.trackSimple(t,r,0),this.failure("NumberValidationError","invalid-argument","Number literal must be finite","NUMBER_NOT_FINITE")):(this.trackSimple(t,r,0),this.failure("ValidationError","validation-error",n.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",n.suggestions))}catch(e){return this.trackSimple(t,r,0),this.failure("NumberEvaluationError","runtime-error","Number literal evaluation failed: "+(e instanceof Error?e.message:e+""),"NUMBER_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?Number.isFinite(e.data.value)?this.validationSuccess():this.validationFailure("invalid-argument","Number literal value must be finite",["Use finite numbers only","Avoid Infinity and NaN values"]):this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid number literal input",["Provide a value parameter","Ensure value is a number"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},booleanLiteral:new class extends gr{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=On,this.outputType="Boolean",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);return n.isValid?(this.trackSimple(t,r,1,e.value),this.success(e.value,"boolean")):(this.trackSimple(t,r,0),this.failure("ValidationError","validation-error",n.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",n.suggestions))}catch(e){return this.trackSimple(t,r,0),this.failure("BooleanEvaluationError","runtime-error","Boolean literal evaluation failed: "+(e instanceof Error?e.message:e+""),"BOOLEAN_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid boolean literal input",["Provide a value parameter","Ensure value is a boolean"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},addition:new class extends gr{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=Ln,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return this.trackSimple(t,r,0),this.failure("ValidationError","validation-error",n.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",n.suggestions);const s=Cr(e.left,"left operand")+Cr(e.right,"right operand");return this.trackSimple(t,r,1,s),this.success(s,"number")}catch(e){return this.trackSimple(t,r,0),this.failure("AdditionError","runtime-error","Addition failed: "+(e instanceof Error?e.message:e+""),"ADDITION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid addition input",["Provide left and right operands"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},stringConcatenation:new class extends gr{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=Ln,this.outputType="String",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return this.trackSimple(t,r,0),this.failure("ValidationError","validation-error",n.errors[0]?.message||"Invalid input","STRING_CONCATENATION_VALIDATION_FAILED",n.suggestions);const s=this.convertToString(e.left)+this.convertToString(e.right);return this.trackSimple(t,r,1,s),this.success(s,"string")}catch(e){return this.trackSimple(t,r,0),this.failure("StringConcatenationError","runtime-error",e instanceof Error?e.message:"String concatenation failed","STRING_CONCATENATION_ERROR",["Check that operands can be converted to strings"])}}validate(t){const e=Ln.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid string concatenation input",["Provide left and right operands for concatenation"])}convertToString(t){if(null===t)return"null";if(void 0===t)return"undefined";if($e(t))return t;if(Re(t))return""+t;if(Ie(t))return""+t;if(t instanceof Date)return""+t;try{return t+""}catch{return"[object Object]"}}},multiplication:new class extends gr{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=Ln,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return this.trackSimple(t,r,0),this.failure("ValidationError","validation-error",n.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",n.suggestions);const s=Cr(e.left,"left operand")*Cr(e.right,"right operand");return this.trackSimple(t,r,1,s),this.success(s,"number")}catch(e){return this.trackSimple(t,r,0),this.failure("MultiplicationError","runtime-error","Multiplication failed: "+(e instanceof Error?e.message:e+""),"MULTIPLICATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid multiplication input",["Provide left and right operands"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}};class Rn extends Xe{constructor(){super(),this.registerExpressions()}registerExpressions(){this.registerCategory(Er),this.registerCategory(on),this.registerCategory(yn),this.registerCategory(An),this.registerCategory(Cn),this.registerCategory($n)}}class In{static toTyped(t){return{me:t.me,it:t.it,you:t.you,result:t.result,...void 0!==t.event&&{event:t.event},variables:t.variables||new Map,locals:t.locals||new Map,globals:t.globals||new Map,...void 0!==t.events&&{events:t.events},meta:t.meta||{},expressionStack:[],evaluationDepth:0,validationMode:"strict",evaluationHistory:[]}}static fromTyped(t,e){return{...e,me:t.me,it:t.it,you:t.you,result:t.result,...void 0!==t.event&&{event:t.event},...void 0!==t.variables&&{variables:t.variables},locals:t.locals,globals:t.globals,...void 0!==t.events&&{events:t.events},...void 0!==t.meta&&{meta:t.meta}}}}class jn{constructor(t,e,r){this.impl=t,this.expressionEvaluator=e??new Rn,this.hookRegistry=r??null}setHookRegistry(t){this.hookRegistry=t}createHookContext(t,e,r={}){return{commandName:this.name,element:t.me instanceof Element?t.me:null,args:e,modifiers:r,event:t.event??void 0,executionContext:t}}get name(){return this.impl.name||this.impl.metadata?.name}get metadata(){return{description:this.impl.metadata?.description||"",examples:this.impl.metadata?.examples||[],syntax:this.impl.metadata?.syntax||""}}async execute(t,...e){const r=e[0],n=this.createHookContext(t,e,r&&"object"==typeof r&&"modifiers"in r&&r.modifiers||{});try{if(ut(`CommandAdapterV2: Executing '${this.name}' with args:`,e),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(n),this.hookRegistry?.shouldIntercept(this.name,n))return void ut(`CommandAdapterV2: '${this.name}' intercepted by hook`);t.locals||(t.locals=new Map),t.locals.set("__evaluator",this.expressionEvaluator);const s=In.toTyped(t);let i,o;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(ut(`CommandAdapterV2: '${this.name}' has parseInput(), calling it`),r&&"object"==typeof r&&("args"in r||"modifiers"in r)){const e=r.modifiers,n=e?.when||e?.where;if(n&&!await this.expressionEvaluator.evaluate(n,t))return void ut(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);i=await this.impl.parseInput({args:r.args||[],modifiers:e||{},commandName:r.commandName},this.expressionEvaluator,t)}else i=e;else ut(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),i=e;return ut("CommandAdapterV2: Calling execute with parsed input:",i),o=2===this.impl.execute.length?await this.impl.execute(i,s):await this.impl.execute(s,...i),ut("CommandAdapterV2: Command result:",o),Object.assign(t,In.fromTyped(s,t)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(n,o),o}catch(t){if(_n(t)||ut(`CommandAdapterV2: Error executing '${this.name}':`,t),this.hookRegistry&&t instanceof Error)throw await this.hookRegistry.runOnError(n,t);throw t}}validate(t){return this.impl.validate?this.impl.validate(t):{isValid:1,errors:[],suggestions:[]}}}class Dn{constructor(t,e){this.adapters=new Map,this.implementations=new Map,this.sharedEvaluator=t,this.hookRegistry=e}setHookRegistry(t){this.hookRegistry=t;for(const e of this.adapters.values())e.setHookRegistry(t);pt(`CommandRegistryV2: Hook registry set and propagated to ${this.adapters.size} adapters`)}getHookRegistry(){return this.hookRegistry}register(t){const e=t.name||t.metadata?.name;if(!e||"string"!=typeof e)throw Error("Cannot register command: no name found. Provide a 'name' property or 'metadata.name' on the implementation.");const r=e.toLowerCase();pt(`CommandRegistryV2: Registering command '${r}'`),this.implementations.set(r,t);const n=new jn(t,this.sharedEvaluator,this.hookRegistry);this.adapters.set(r,n),w.add(r);const s=t.metadata?.aliases;if(s&&Array.isArray(s))for(const e of s){const r=e.toLowerCase();this.implementations.set(r,t),this.adapters.set(r,n),w.add(r)}}getAdapter(t){return this.adapters.get(t.toLowerCase())}has(t){return this.adapters.has(t.toLowerCase())}getCommandNames(){return Array.from(this.adapters.keys())}getImplementation(t){return this.implementations.get(t.toLowerCase())}getAdapters(){return new Map(this.adapters)}validateCommand(t,e){const r=this.getAdapter(t);return r?r.validate(e):{isValid:0,errors:[{type:"runtime-error",message:"Unknown command: "+t,suggestions:["Available commands: "+this.getCommandNames().join(", ")]}],suggestions:["Available commands: "+this.getCommandNames().join(", ")]}}}let Mn=null;function Pn(){return Mn||(Mn=function(){const t=new Dn,e=new Te,r=new Oe,n=new Set,s={commands:t,eventSources:e,context:r,use(i){if(n.has(i.name))console.warn(`[LokaScriptRegistry] Plugin '${i.name}' is already installed`);else{if(i.commands)for(const e of i.commands)t.register(e);if(i.eventSources)for(const t of i.eventSources)e.register(t.name,t);if(i.contextProviders)for(const{name:t,provide:e,options:n}of i.contextProviders)r.register(t,e,n);i.setup?.(s),n.add(i.name)}},reset(){n.clear()}};return s}()),Mn}class Vn{constructor(t={}){this.contextCache=new WeakMap;const e=Pn();this.options={enableContextProviders:t.enableContextProviders??1,enableEventSources:t.enableEventSources??1,registry:t.registry??{}},this.contextRegistry=this.options.registry.context??e.context,this.eventSourceRegistry=this.options.registry.eventSources??e.eventSources,pt(`[RegistryIntegration] Initialized (context=${this.options.enableContextProviders}, events=${this.options.enableEventSources})`)}enhanceContext(t){if(!this.options.enableContextProviders)return t;const e=this.contextCache.get(t);if(e)return e;try{const e=this.contextRegistry.enhance(t);return this.contextCache.set(t,e),pt(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),e}catch(e){return pt("[RegistryIntegration] Failed to enhance context: "+(e instanceof Error?e.message:e+"")),t}}getEventSource(t){if(!this.options.enableEventSources)return;const e=this.eventSourceRegistry.get(t);if(e)return pt(`[RegistryIntegration] Found event source for '${t}'`),e;const r=this.eventSourceRegistry.findSourceForEvent(t);if(r){const e=this.eventSourceRegistry.get(r);return pt(`[RegistryIntegration] Found event source '${r}' supporting '${t}'`),e}}hasEventSource(t){return void 0!==this.getEventSource(t)}subscribeToEventSource(t,e,r){if(!this.options.enableEventSources)throw Error("Event sources are disabled in this runtime");const n=this.eventSourceRegistry.subscribe(t,e,r);if(!n)throw Error(`Failed to subscribe to event source '${t}'`);return pt(`[RegistryIntegration] Subscribed to '${t}' event '${e.event}' (id: ${n.id})`),n}getEventSourceNames(){return this.eventSourceRegistry.getSourceNames()}getContextProviderNames(){return this.contextRegistry.getProviderNames()}destroy(){this.eventSourceRegistry.destroy(),this.contextCache=new WeakMap,pt("[RegistryIntegration] Destroyed")}}function Bn(t){const e=Error(t.type.toUpperCase()+"_EXECUTION");return e["is"+t.type.charAt(0).toUpperCase()+t.type.slice(1)]=1,"returnValue"in t&&(e.returnValue=t.returnValue),e}function _n(t){return t instanceof Error?null!==we(t)||"HALT_EXECUTION"===t.message||"EXIT_COMMAND"===t.message||"EXIT_EXECUTION"===t.message:0}function Fn(t){if(void 0===t)return;let e=t;if(e&&"object"==typeof e){const t=e;if("result"in t&&"wasAsync"in t)e=t.result;else if("result"in t&&"executed"in t){if(e=t.result,t.preserveArrayResult)return void 0!==e?e:void 0}else if("lastResult"in t&&"type"in t)e=t.lastResult;else if("conditionResult"in t&&"executedBranch"in t){if(void 0===t.result)return;e=t.result}else"value"in t&&1===Object.keys(t).length||"value"in t&&"target"in t&&"targetType"in t?e=t.value:"data"in t&&"status"in t&&"headers"in t&&(e=t.data)}return Array.isArray(e)&&e.length>0&&(e=e[0]),e}function qn(t){return null!==t&&"object"==typeof t&&"command"in t&&"selector"in t}const Hn=new WeakMap;class Un{constructor(t){this.autoCleanupObserver=null,this.registryIntegration=null,this.options={commandTimeout:1e4,enableErrorReporting:1,enableResultPattern:1,enableAutoCleanup:1,...t},this.registry=t.registry,this.expressionEvaluator=t.expressionEvaluator,this.behaviorRegistry=new Map,this.globalVariables=Ce,this.hookRegistry=new Ee,t.hooks&&this.hookRegistry.register("default",t.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new Se,this.options.enableAutoCleanup&&this.setupAutoCleanup(),0!=t.registryIntegration&&(this.registryIntegration=new Vn("object"==typeof t.registryIntegration?t.registryIntegration:{}),pt("RuntimeBase: Registry integration enabled")),this.behaviorAPI={has:t=>this.behaviorRegistry.has(t),get:t=>this.behaviorRegistry.get(t),install:async(t,e,r)=>await this.installBehaviorOnElement(t,e,r)}}setupAutoCleanup(){"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.autoCleanupObserver=new MutationObserver(t=>{const e=[];for(const r of t)for(const t of r.removedNodes)t instanceof Element&&e.push(t);e.length>0&&queueMicrotask(()=>{for(const t of e)if(!t.isConnected){const e=this.cleanupRegistry.cleanupElementTree(t);e>0&&pt(`RuntimeBase: Auto-cleaned ${e} resources for removed element`)}})}),document.body?this.autoCleanupObserver.observe(document.body,{childList:1,subtree:1}):document.addEventListener("DOMContentLoaded",()=>{this.autoCleanupObserver?.observe(document.body,{childList:1,subtree:1})},{once:1}))}registerHooks(t,e){this.hookRegistry.register(t,e)}unregisterHooks(t){return this.hookRegistry.unregister(t)}getRegisteredHooks(){return this.hookRegistry.getRegisteredNames()}cleanup(t){return this.cleanupRegistry.cleanupElement(t)}cleanupTree(t){return this.cleanupRegistry.cleanupElementTree(t)}getCleanupStats(){return this.cleanupRegistry.getStats()}destroy(){this.autoCleanupObserver&&(this.autoCleanupObserver.disconnect(),this.autoCleanupObserver=null),this.cleanupRegistry.cleanupAll(),this.hookRegistry.clear(),this.behaviorRegistry.clear(),pt("RuntimeBase: Destroyed")}async execute(t,e){pt(`RUNTIME BASE: execute() called with node type: '${t.type}'`),e.locals.has("_behaviors")||e.locals.set("_behaviors",this.behaviorAPI),e.locals.has("_runtimeExecute")||e.locals.set("_runtimeExecute",(t,r)=>this.execute(t,r||e));try{switch(t.type){case"command":if(this.options.enableResultPattern)try{const r=await this.processCommandWithResult(t,e);if(!Ae(r))throw Bn(r.error);return r.value}catch(t){throw t}return await this.processCommand(t,e);case"eventHandler":return await this.executeEventHandler(t,e);case"event":{const r={type:"eventHandler",event:t.event,events:[t.event],commands:t.body||[],target:t.filter,modifiers:t.modifiers||{}};return await this.executeEventHandler(r,e)}case"behavior":return await this.executeBehaviorDefinition(t,e);case"Program":return await this.executeProgram(t,e);case"initBlock":case"block":return await this.executeBlock(t,e);case"sequence":case"CommandSequence":if(this.options.enableResultPattern){const r=t,n=await this.executeCommandSequenceWithResult(r.commands||[],e);if(!Ae(n))throw Bn(n.error);return n.value}return await this.executeCommandSequence(t,e);case"objectLiteral":return await this.executeObjectLiteral(t,e);default:if(this.options.enableResultPattern){const r=await this.evaluateExpressionWithResult(t,e);if(!Ae(r))throw Bn(r.error);return r.value}return await this.evaluateExpression(t,e)}}catch(t){throw t}}async processCommand(t,e){const{name:r,args:n,modifiers:s}=t,i=r.toLowerCase();if(ut(`RUNTIME BASE: Processing command '${i}'`),this.registry.has(i)){const t=await this.registry.getAdapter(i);if(!t)throw Error(`Command '${i}' is registered but failed to load adapter.`);try{return await t.execute(e,{args:n||[],modifiers:s||{},commandName:i,runtime:this})}catch(t){throw _n(t)||console.error(`Error executing command '${i}':`,t),t}}const o=`Unknown command: ${r}. Ensure it is registered in the Runtime options.`;throw this.options.enableErrorReporting&&console.warn(o),Error(o)}toSignal(t){const e=we(t);if(e){if(e.isHalt||"HALT_EXECUTION"===e.message)return{type:"halt"};if(e.isExit||"EXIT_COMMAND"===e.message)return{type:"exit",returnValue:e.returnValue};if(e.isBreak)return{type:"break"};if(e.isContinue)return{type:"continue"};if(e.isReturn)return{type:"return",returnValue:e.returnValue}}if(t instanceof Error){if("HALT_EXECUTION"===t.message)return{type:"halt"};if("EXIT_COMMAND"===t.message)return{type:"exit"}}return null}async processCommandWithResult(t,e){const{name:r,args:n,modifiers:s}=t,i=r.toLowerCase();if(ut(`RUNTIME BASE (Result): Processing command '${i}'`),!this.registry.has(i)){const t=`Unknown command: ${r}. Ensure it is registered in the Runtime options.`;throw this.options.enableErrorReporting&&console.warn(t),Error(t)}const o=await this.registry.getAdapter(i);if(!o)throw Error(`Command '${i}' is registered but failed to load adapter.`);try{return xe(await o.execute(e,{args:n||[],modifiers:s||{},commandName:i,runtime:this}))}catch(t){const e=this.toSignal(t);if(e)return ke(e);throw console.error(`Error executing command '${i}':`,t),t}}async executeCommandSequenceWithResult(t,e){let r;for(const n of t)if("command"===n.type){const t=await this.processCommandWithResult(n,e);if(!Ae(t)){const r=t.error;switch(r.type){case"halt":case"exit":case"break":case"continue":return t;case"return":return void 0!==r.returnValue&&Object.assign(e,{it:r.returnValue,result:r.returnValue}),xe(r.returnValue)}}r=t.value}else{const t=await this.evaluateExpressionWithResult(n,e);if(!Ae(t))return t;r=t.value}return xe(r)}async evaluateExpression(t,e){const r=await this.expressionEvaluator.evaluate(t,e);return qn(r)?await this.executeCommandFromPattern(r.command,r.selector,e):r}async evaluateExpressionWithResult(t,e){const r=await this.expressionEvaluator.evaluateWithResult(t,e);if(!Ae(r))return r;const n=r.value;if(qn(n)){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:n.command,args:[{type:"literal",value:n.selector}]},e);try{return xe(await this.executeCommandFromPattern(n.command,n.selector,e))}catch(t){const e=this.toSignal(t);if(e)return ke(e);throw t}}return xe(n)}async executeCommandFromPattern(t,e,r){return this.processCommand({type:"command",name:t,args:[{type:"literal",value:e}]},r)}async executeProgram(t,e){if(!t.statements||!Array.isArray(t.statements))return;let r;const n=[],s=[],i=[];for(const e of t.statements)"eventHandler"===e.type?n.push(e):"initBlock"===e.type?s.push(e):i.push(e);for(const t of n)try{await this.execute(t,e)}catch(t){if(_n(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of s)try{r=await this.execute(t,e)}catch(t){if(_n(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of i)try{r=await this.execute(t,e)}catch(t){if(_n(t)&&(t.isHalt||t.isExit))break;throw t}return r}async executeBlock(t,e){if(t.commands&&Array.isArray(t.commands))for(const r of t.commands)try{await this.execute(r,e)}catch(t){if(_n(t)&&t.isHalt)break;throw t}}async executeCommandSequence(t,e){if(!t.commands||!Array.isArray(t.commands))return;let r;for(const n of t.commands)try{r=await this.execute(n,e)}catch(t){if(_n(t)){if(t.isHalt||t.isExit)break;if(t.isReturn){if(void 0!==t.returnValue)return Object.assign(e,{it:t.returnValue,result:t.returnValue}),t.returnValue;break}if(t.isBreak)throw t}throw t}return r}async executeObjectLiteral(t,e){const r={};if(!t.properties)return r;for(const n of t.properties){let t;t="identifier"===n.key.type?n.key.name:"literal"===n.key.type?n.key.value+"":await this.execute(n.key,e)+"";const s=await this.execute(n.value,e);r[t]=s}return r}enhanceContext(t){return this.registryIntegration?this.registryIntegration.enhanceContext(t):t}async executeBehaviorDefinition(t,e){const{name:r,parameters:n,eventHandlers:s,initBlock:i}=t;this.behaviorRegistry.set(r,{name:r,parameters:n,eventHandlers:s,initBlock:i}),pt(`RUNTIME BASE: Registered behavior '${r}'`)}async installBehaviorOnElement(t,e,r){pt("BEHAVIOR: installBehaviorOnElement called: "+t);const n=this.behaviorRegistry.get(t);if(!n)throw Error(`Behavior "${t}" not found`);pt("BEHAVIOR: Found behavior, eventHandlers count: "+(n.eventHandlers?.length||0));const s={me:e,you:null,it:null,result:null,locals:new Map,globals:this.globalVariables,halted:0,returned:0,broke:0,continued:0,async:0},i=this.enhanceContext(s);if(n.parameters)for(const t of n.parameters)i.locals.set(t,t in r?r[t]:void 0);for(const[t,e]of Object.entries(r))n.parameters?.includes(t)||i.locals.set(t,e);if(n.initBlock){pt("BEHAVIOR: Running init block for "+t);const e=this.options.commandTimeout??1e4;try{await Promise.race([this.execute(n.initBlock,i),new Promise((r,n)=>setTimeout(()=>n(Error(`Behavior "${t}" init block timed out after ${e}ms`)),e))]),pt("BEHAVIOR: Init block completed for "+t)}catch(e){if(pt(`BEHAVIOR: Init block error for ${t}:`,e),!(e instanceof Error&&_n(e)))throw e}}if(pt(`BEHAVIOR: About to attach ${n.eventHandlers?.length||0} handlers for ${t}`),n.eventHandlers){const e=this.options.commandTimeout??1e4;for(const r of n.eventHandlers)await Promise.race([this.executeEventHandler(r,i),new Promise((r,n)=>setTimeout(()=>n(Error(`Behavior "${t}" handler attachment timed out after ${e}ms`)),e))])}pt("BEHAVIOR: Finished installing "+t)}async executeEventHandler(t,e){const{event:r,events:n,commands:s,target:i,args:o,selector:a,attributeName:c,watchTarget:l,modifiers:u}=t,h=n&&n.length>0?n:[r];pt(`BEHAVIOR: executeEventHandler: event='${r}', target='${i}'`);let f=[],d=null;if(i){const t="string"==typeof i?i.toLowerCase():"";if("window"===t||"the window"===t)d=window;else if("document"===t||"the document"===t||"body"===t)d=document;else if("me"===t||"myself"===t)f=e.me?[e.me]:[];else if("string"==typeof i&&e.locals.has(i)){const t=e.locals.get(i);pt(`BEHAVIOR: Target resolution: found local '${i}', isElement: ${this.isElement(t)}`),this.isElement(t)?f=[t]:Array.isArray(t)?f=t.filter(t=>this.isElement(t)):"string"==typeof t&&(f=this.queryElements(t,e))}else pt(`BEHAVIOR: Target resolution: querying for '${i}'`),f=this.queryElements(i,e)}else f=e.me?[e.me]:[];if(0===f.length&&!d)return void pt(`BEHAVIOR: executeEventHandler - No targets found for event '${r}', returning early`);if("mutation"===r&&c)return void this.setupMutationObserver(f,c,s,e);if("change"===r&&l)return void this.setupChangeObserver(l,s,e);const p=t.customEventSource;if(p&&this.registryIntegration){pt(`BEHAVIOR: executeEventHandler - Using custom event source '${p}' for event '${r}'`);const t=async t=>{const n=new Map(e.locals),i={...e,locals:n,it:t,event:t},o=this.enhanceContext(i);pt(`CUSTOM EVENT: Executing commands for event '${r}'`);try{await this.execute({type:"program",commands:s},o)}catch(t){console.error(`[HyperFixi] Error executing commands for custom event '${r}':`,t)}};try{const n=this.registryIntegration.subscribeToEventSource(p,{event:r,handler:t,target:i,selector:a},e);pt(`BEHAVIOR: Subscribed to custom event source '${p}' (id: ${n.id})`),this.cleanupRegistry.registerGlobal(()=>n.unsubscribe(),"listener",`Custom event source '${p}' subscription ${n.id}`)}catch(t){console.error(`[HyperFixi] Failed to subscribe to custom event source '${p}':`,t)}return}const m=Un.createEventHandler(this,s,e,a,o);let y,v=null;if(u){let t=m;if(u.prevent){const e=t;t=async t=>(t.preventDefault(),e(t))}if(u.stop){const e=t;t=async t=>(t.stopPropagation(),e(t))}if(u.debounce){const e=u.debounce;let r;y=n=>{r&&clearTimeout(r),r=setTimeout(()=>t(n),e)},v=()=>{r&&(clearTimeout(r),r=void 0)}}else if(u.throttle){const e=u.throttle;let r=0;y=n=>{const s=Date.now();e>s-r||(r=s,t(n))}}else y=t}else y=m;const g=u?.once?{once:1}:void 0;if(d){for(const t of h)d.addEventListener(t,y,g),f.length>0?this.cleanupRegistry.registerListener(f[0],d,t,y):this.cleanupRegistry.registerGlobal(()=>d.removeEventListener(t,y),"listener",`Global ${t} listener`);v&&(f.length>0?this.cleanupRegistry.registerCustom(f[0],v,"debounce-timeout"):this.cleanupRegistry.registerGlobal(v,"timeout","debounce-timeout"))}else for(const t of f){for(const e of h)t.addEventListener(e,y,g),this.cleanupRegistry.registerListener(t,t,e,y);v&&this.cleanupRegistry.registerCustom(t,v,"debounce-timeout")}}static createEventHandler(t,e,r,n,s){return async i=>{const o=Hn.get(i)??0;if(o>=100)return;if(Hn.set(i,o+1),n&&i.target instanceof Element)try{if(!i.target.matches(n)&&!i.target.closest(n))return}catch{pt(`Event delegation: invalid CSS selector '${n}', skipping filter`)}const a=new Map(r.locals),c={...r,locals:a,it:i,event:i};a.has("target")||c.locals.set("target",i.target);const l=t.enhanceContext(c);if(s&&s.length>0){const t=i,e=t.detail;for(const r of s)l.locals.set(r,t[r]??e?.[r]??null)}for(const r of e)try{const e=Fn(await t.execute(r,l));void 0!==e&&Object.assign(l,{it:e,result:e})}catch(t){if(_n(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 console.error("COMMAND FAILED:",t),t}}}setupMutationObserver(t,e,r,n){pt(`RUNTIME BASE: Setting up MutationObserver for attribute '${e}' on ${t.length} elements`);for(const s of t){const t=new MutationObserver(async t=>{for(const i of t)if("attributes"===i.type&&i.attributeName===e){ht(`MUTATION DETECTED: attribute '${e}' changed on`,s);const t={...n,me:s,it:i,locals:new Map(n.locals)},o=i.oldValue,a=s.getAttribute(e);t.locals.set("oldValue",o),t.locals.set("newValue",a);const c=this.enhanceContext(t);for(const t of r)try{await this.execute(t,c)}catch(t){if(_n(t)){if(t.isHalt||t.isExit||t.isReturn)break}else console.error("Error executing mutation handler command:",t)}}});t.observe(s,{attributes:1,attributeOldValue:1,attributeFilter:[e]}),this.cleanupRegistry.registerObserver(s,t),pt("RUNTIME BASE: MutationObserver attached to",s,`for attribute '${e}'`)}}async setupChangeObserver(t,e,r){pt("RUNTIME BASE: Setting up MutationObserver for content changes on watch target");const n=await this.execute(t,r);let s=[];this.isElement(n)?s=[n]:Array.isArray(n)&&(s=n.filter(t=>this.isElement(t))),pt(`RUNTIME BASE: Watching ${s.length} target elements for content changes`);for(const t of s){const n=new MutationObserver(async n=>{for(const s of n)if("childList"===s.type||"characterData"===s.type){ht("CONTENT CHANGE DETECTED on",t,"mutation type:",s.type);const n={...r,me:r.me,it:s,locals:new Map(r.locals)};n.locals.set("target",t);const i=s.oldValue,o=t.textContent;null!==i&&n.locals.set("oldValue",i),n.locals.set("newValue",o);const a=this.enhanceContext(n);for(const t of e)try{await this.execute(t,a)}catch(t){if(_n(t)){if(t.isHalt||t.isExit||t.isReturn)break}else console.error("Error executing change handler command:",t)}}});n.observe(t,{childList:1,characterData:1,subtree:1,characterDataOldValue:1}),this.cleanupRegistry.registerObserver(t,n),pt("RUNTIME BASE: MutationObserver attached to",t,"for content changes")}}queryElements(t,e){const r=e.me,n=(r instanceof Element?r.ownerDocument:null)??("undefined"!=typeof document?document:null);if(!n)return[];let s=t;s.startsWith("<")&&s.endsWith("/>")&&(s=s.slice(1,-2).trim());try{return Array.from(n.querySelectorAll(s))}catch{return pt(`queryElements: invalid CSS selector '${s}'`),[]}}isElement(t){return"undefined"!=typeof HTMLElement&&t instanceof HTMLElement?1:t&&"object"==typeof t?!!t.style&&!!t.classList:0}}class Wn{constructor(t){this.observer=null,this.initialized=0,this.runtime=t}init(){"undefined"!=typeof document&&(this.initialized||(this.initialized=1,this.scanDocument(),this.observer=new MutationObserver(t=>{for(const e of t)"childList"===e.type?e.addedNodes.forEach(t=>{t.nodeType===Node.ELEMENT_NODE&&(this.processElement(t),this.scanElement(t))}):"attributes"===e.type&&"_"===e.attributeName&&this.processElement(e.target)}),this.observer.observe(document.body,{childList:1,subtree:1,attributes:1,attributeFilter:["_"]})))}destroy(){this.observer&&(this.observer.disconnect(),this.observer=null),this.initialized=0}reset(){this.destroy()}scanAndProcessAll(){this.scanDocument()}scanDocument(){document.body&&this.scanElement(document.body)}scanElement(t){t.hasAttribute("_")&&this.processElement(t),t.querySelectorAll("[_]").forEach(t=>this.processElement(t))}processElement(t){const e=t.getAttribute("_");if(!e)return;const r=Ne(t);this.runtime.execute(e,r).catch(r=>{console.error('[HyperFixi] Error executing _="" attribute:',r),console.error("Element:",t),console.error("Code:",e)})}}function zn(t,e,r,n,s,i){function o(t){if(void 0!==t&&"function"!=typeof t)throw new TypeError("Function expected");return t}for(var a,c=n.kind,l="getter"===c?"get":"setter"===c?"set":"value",u=!e&&t?n.static?t:t.prototype:null,h=e||(u?Object.getOwnPropertyDescriptor(u,n.name):{}),f=0,d=r.length-1;d>=0;d--){var p={};for(var m in n)p[m]="access"===m?{}:n[m];for(var m in n.access)p.access[m]=n.access[m];p.addInitializer=function(t){if(f)throw new TypeError("Cannot add initializers after decoration has completed");i.push(o(t||null))};var y=(0,r[d])("accessor"===c?{get:h.get,set:h.set}:h[l],p);if("accessor"===c){if(void 0===y)continue;if(null===y||"object"!=typeof y)throw new TypeError("Object expected");(a=o(y.get))&&(h.get=a),(a=o(y.set))&&(h.set=a),(a=o(y.init))&&s.unshift(a)}else(a=o(y))&&("field"===c?s.unshift(a):h[l]=a)}u&&Object.defineProperty(u,n.name,h),f=1}function Jn(t,e,r){for(var n=arguments.length>2,s=0;e.length>s;s++)r=n?e[s].call(t,r):e[s].call(t);return n?r:void 0}function Zn(t,e,r){return"symbol"==typeof e&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:1,value:r?"".concat(r," ",e):e})}function Gn(t){const e=t.trim();return e.startsWith("[@")&&e.endsWith("]")||e.startsWith("@")?1:0}function Xn(t){const e=t.trim();if(e.startsWith("[@")&&e.endsWith("]")){const t=e.slice(2,-1),r=t.indexOf("=");if(-1===r)return{name:t.trim()};const n=t.slice(0,r).trim();let s=t.slice(r+1).trim();return(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),{name:n,value:s}}if(e.startsWith("@"))return{name:e.substring(1).trim()};throw Error("Invalid attribute syntax: "+t)}function Yn(t,e){for(const r of t)e(r);return t}function Kn(t,e,r){for(const n of t)for(const t of e)r(n,t);return t}function Qn(t,e,r){const n=t.hasAttribute(e);void 0!==r?n&&t.getAttribute(e)===r?t.removeAttribute(e):t.setAttribute(e,r):n?t.removeAttribute(e):t.setAttribute(e,"")}function ts(t){if(!t)return[];if("string"==typeof t)return t.trim().split(/[\s,]+/).map(t=>{const e=t.trim();return e.startsWith(".")?e.substring(1):e}).filter(t=>t.length>0&&rs(t));if(Array.isArray(t))return t.map(t=>{const e=(t+"").trim();return e.startsWith(".")?e.substring(1):e}).filter(t=>t.length>0&&rs(t));const e=(t+"").trim(),r=e.startsWith(".")?e.substring(1):e;return r.length>0&&rs(r)?[r]:[]}function es(t){const e=t.trim();return/^\{[^}]+\}$/.test(e)}function rs(t){if(!t||0===t.trim().length)return 0;const e=t.trim();return es(e)?1:/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(e)}function ns(t,e){return t.map(t=>{if(es(t)){const r=function(t){const e=t.trim(),r=e.match(/^\{(.+)\}$/);return r?r[1].trim():e}(t),n=e.locals.get(r)??e.globals.get(r);return null!=n?n+"":(console.warn(`Dynamic class variable '${r}' not found in context`),"")}return t}).filter(t=>t.length>0)}"function"==typeof SuppressedError&&SuppressedError;const ss=Symbol("command:name"),is=Symbol("command:category"),os=Symbol("command:metadata");function as(t){return function(e,r){const n=e;n[ss]=t.name,n[is]=t.category,Object.defineProperty(e.prototype,"name",{value:t.name,writable:0,enumerable:1})}}function cs(t){return function(e,r){const n=e,s=n[is];if(!s)throw Error("@meta decorator requires @command decorator to be applied first on "+e.name);const i={description:t.description,syntax:t.syntax,examples:t.examples,category:s,sideEffects:t.sideEffects,deprecated:t.deprecated,deprecationMessage:t.deprecationMessage,aliases:t.aliases,relatedCommands:t.relatedCommands,isBlocking:t.isBlocking??0,hasBody:t.hasBody??0,version:"1.0.0",compatibility:t.compatibility};n[os]=i,Object.defineProperty(e,"metadata",{value:i,writable:0,enumerable:1,configurable:0}),Object.defineProperty(e.prototype,"metadata",{get:()=>i,enumerable:1,configurable:0})}}function ls(t){return()=>new t}function us(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"tagName"in t&&"string"==typeof t.tagName&&"classList"in t}function hs(t,e){if(us(t))return t;if(!t){const t=e.me;if(!t)throw Error("No target element - provide explicit target or ensure context.me is set");return fs(t)}if("string"==typeof t){const r=t.trim();if("me"===r){if(!e.me)throw Error('Context reference "me" is not available');return fs(e.me)}if("it"===r){if(!us(e.it))throw Error('Context reference "it" is not an HTMLElement');return e.it}if("you"===r){if(!e.you)throw Error('Context reference "you" is not available');return fs(e.you)}const n=e.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!n)throw Error("DOM not available - cannot resolve element selector");const s=n.querySelector(r);if(!s)throw Error("Element not found with selector: "+r);if(!us(s))throw Error("Element found but is not an HTMLElement: "+r);return s}throw Error("Invalid target type: "+typeof t)}function fs(t){if(us(t))return t;throw Error("Value is not an HTMLElement")}function ds(t,e){switch(t.toLowerCase()){case"my":case"me":if(!e.me)throw Error('No "me" element in context');if(!us(e.me))throw Error("context.me is not an HTMLElement");return e.me;case"its":case"it":if(!e.it)throw Error('No "it" value in context');if(!us(e.it))throw Error("context.it is not an HTMLElement");return e.it;case"your":case"you":if(!e.you)throw Error('No "you" element in context');if(!us(e.you))throw Error("context.you is not an HTMLElement");return e.you;default:throw Error("Unknown possessive: "+t)}}const ps=["on","from","to","in","with","at"];async function ms(t,e,r,n,s={},i){let o=t;if(s.filterPrepositions&&t&&(o=t.filter(t=>{const e=t;return"identifier"===e?.type&&"string"==typeof e.name?!ps.includes(e.name.toLowerCase()):1})),(!o||0===o.length)&&s.fallbackModifierKey&&i){const t=i[s.fallbackModifierKey];t&&(o=[t])}if(!o||0===o.length){if(!r.me)throw Error(n+" command: no target specified and context.me is null");if(!us(r.me))throw Error(n+" command: context.me must be an HTMLElement");return[r.me]}const a=[];for(const t of o){const s=await e.evaluate(t,r);if(""!==s&&("string"!=typeof s||""!==s.trim()))if(us(s))a.push(s);else if(s instanceof NodeList){const t=Array.from(s).filter(us);a.push(...t)}else if(Array.isArray(s)){const t=s.filter(us);a.push(...t)}else{if("string"!=typeof s)throw Error(`Invalid ${n} target: expected HTMLElement or CSS selector, got ${typeof s}`);try{let t=s;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const e=r.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!e)throw Error("DOM not available - cannot resolve element selector");const n=e.querySelectorAll(t),i=Array.from(n).filter(us);a.push(...i)}catch(t){throw Error(`Invalid CSS selector: "${s}" - ${t instanceof Error?t.message:t+""}`)}}}if(0===a.length){if(!r.me)throw Error(n+" command: no target specified and context.me is null");if(!us(r.me))throw Error(n+" command: context.me must be an HTMLElement");return[r.me]}return a}function ys(t){return"string"==typeof t&&t.trim().startsWith("*")}function vs(t,e,r){t.style.setProperty(e,r)}const gs=["dialog","details","summary","select"];function bs(t){return t&&"object"==typeof t?"string"==typeof t.selector?t.selector:"string"==typeof t.value?t.value:"string"==typeof t.name?t.name:null:null}async function Es(t,e,r){return function(t){if(!t||"object"!=typeof t)return 0;const e=t.type;if("selector"!==e&&"cssSelector"!==e&&"classSelector"!==e)return 0;const r=bs(t);return"string"==typeof r&&r.startsWith(".")}(t)||function(t){if(!t||"object"!=typeof t)return 0;const e=t.type;if("selector"!==e&&"cssSelector"!==e&&"cssProperty"!==e)return 0;const r=bs(t);return"string"==typeof r&&r.startsWith("*")}(t)?{value:bs(t),extractedFromNode:1}:function(t){if(!t||"object"!=typeof t)return 0;if("attributeAccess"===t.type)return 1;if("selector"===t.type||"cssSelector"===t.type){const e=bs(t);return"string"==typeof e&&e.startsWith("@")}return 0}(t)?{value:(n=t,"attributeAccess"===n.type?"@"+n.attributeName:bs(n)),extractedFromNode:1}:{value:await e.evaluate(t,r),extractedFromNode:0};var n}class ws{async resolveTargets(t,e,r,n){return ms(t,e,r,this.mode,{filterPrepositions:1,fallbackModifierKey:this.preposition},n)}async evaluateFirst(t,e,r){return Es(t,e,r)}parseClassNames(t){return ts(t)}isAttribute(t){return Gn(t.trim())}isCSSProperty(t){return ys(t.trim())}validateTargets(t){return Array.isArray(t)&&function(t){return Array.isArray(t)&&t.length>0&&t.every(t=>us(t))}(t)}validateType(t,e){return function(t,e){return"string"==typeof t&&e.includes(t)}(t,e)}validateStringArray(t,e=1){return Array.isArray(t)&&function(t,e=1){return Array.isArray(t)&&t.length>=e&&t.every(t=>"string"==typeof t&&t.length>0)}(t,e)}}let xs=(()=>{let t,e,r=[cs({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"]}),as({name:"add",category:"dom"})],n=[],s=ws;return e=class extends s{constructor(){super(...arguments),this.mode="add",this.preposition="to"}async parseInput(t,e,r){if(!t.args||0===t.args.length)throw Error("add command requires an argument");const{value:n}=await this.evaluateFirst(t.args[0],e,r);if("object"==typeof n&&null!==n&&!Array.isArray(n))return{type:"styles",styles:n,targets:await this.resolveTargets(t.args.slice(1),e,r,t.modifiers)};if("string"==typeof n){const s=n.trim();if(this.isAttribute(s)){const{name:n,value:i}=function(t){const e=Xn(t);return{name:e.name,value:e.value??""}}(s);return{type:"attribute",name:n,value:i,targets:await this.resolveTargets(t.args.slice(1),e,r,t.modifiers)}}if(this.isCSSProperty(s)){const n=s.substring(1).trim();if(2>t.args.length)throw Error("add *property requires a value argument");const i=await e.evaluate(t.args[1],r);return{type:"styles",styles:{[n]:i+""},targets:await this.resolveTargets(t.args.slice(2),e,r,t.modifiers)}}}const s=this.parseClassNames(n);if(0===s.length)throw Error("add command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(t.args.slice(1),e,r,t.modifiers)}}async execute(t,e){switch(t.type){case"classes":{const r=ns(t.classes,e);r.length>0&&Kn(t.targets,r,(t,e)=>{t.classList.contains(e)||t.classList.add(e)});break}case"attribute":r=t.name,n=t.value,Yn(t.targets,t=>{t.setAttribute(r,n)});break;case"styles":Kn(t.targets,Object.entries(t.styles),(t,[e,r])=>{t.style.setProperty(e,r)})}var r,n}validate(t){if("object"!=typeof t||null===t)return 0;const e=t;if(!this.validateType(e.type,["classes","attribute","styles"]))return 0;if(!this.validateTargets(e.targets))return 0;if("classes"===e.type){if(!this.validateStringArray(t.classes,1))return 0}else if("attribute"===e.type){if("string"!=typeof t.name||0===t.name.length)return 0;if("string"!=typeof t.value)return 0}else if("styles"===e.type){const e=t;if("object"!=typeof e.styles||null===e.styles)return 0;if(Array.isArray(e.styles))return 0;const r=e.styles;if(0===Object.keys(r).length)return 0;if(!Object.values(r).every(t=>"string"==typeof t))return 0}return 1}},Zn(e,"AddCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;zn(null,t={value:e},r,{kind:"class",name:e.name,metadata:i},null,n),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:i}),Jn(e,n)})(),e})();const ks=ls(xs);function As(t){return t.parentNode?(t.remove(),1):0}let Ss=(()=>{let t,e,r=[cs({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"]}),as({name:"remove",category:"dom"})],n=[],s=ws;return e=class extends s{constructor(){super(...arguments),this.mode="remove",this.preposition="from"}async parseInput(t,e,r){if(!t.args||0===t.args.length)throw Error("remove command requires an argument");const{value:n}=await this.evaluateFirst(t.args[0],e,r);if(us(n))return{type:"element",targets:[n]};if(Array.isArray(n)&&n.length>0&&us(n[0]))return{type:"element",targets:n.filter(t=>us(t))};if("string"==typeof n){const s=n.trim();if(this.isAttribute(s))return{type:"attribute",name:Xn(s).name,targets:await this.resolveTargets(t.args.slice(1),e,r,t.modifiers)};if(this.isCSSProperty(s))return{type:"styles",properties:[s.substring(1).trim()],targets:await this.resolveTargets(t.args.slice(1),e,r,t.modifiers)}}const s=this.parseClassNames(n);if(0===s.length)throw Error("remove command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(t.args.slice(1),e,r,t.modifiers)}}execute(t,e){switch(t.type){case"classes":{const r=ns(t.classes,e);r.length>0&&Kn(t.targets,r,(t,e)=>{t.classList.remove(e)});break}case"attribute":r=t.name,Yn(t.targets,t=>{t.removeAttribute(r)});break;case"styles":Kn(t.targets,t.properties,(t,e)=>{t.style.removeProperty(e)});break;case"element":for(const e of t.targets)As(e)}var r}validate(t){if("object"!=typeof t||null===t)return 0;const e=t;if(!this.validateType(e.type,["classes","attribute","styles","element"]))return 0;if(!this.validateTargets(e.targets))return 0;if("classes"===e.type){if(!this.validateStringArray(t.classes,1))return 0}else if("attribute"===e.type){if("string"!=typeof t.name||0===t.name.length)return 0}else if("styles"===e.type&&!this.validateStringArray(t.properties,1))return 0;return 1}},Zn(e,"RemoveCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;zn(null,t={value:e},r,{kind:"class",name:e.name,metadata:i},null,n),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:i}),Jn(e,n)})(),e})();const Cs=ls(Ss);function Ns(t){const e=t.trim().match(/^(\d+(?:\.\d+)?)\s*(s|ms|sec|seconds?|milliseconds?)?$/i);if(!e)return null;const r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();return"ms"===n||"millisecond"===n||"milliseconds"===n?{number:r,milliseconds:Math.floor(r)}:"s"===n||"sec"===n||"second"===n||"seconds"===n?{number:r,milliseconds:Math.floor(1e3*r)}:null}function Ts(t){if("number"==typeof t){if(0>t)throw Error("Duration must be >= 0");return Math.floor(t)}if("string"==typeof t){const e=Ns(t);if(!e)throw Error(`Invalid duration format: "${t}"`);return e.milliseconds}throw Error("Invalid duration type: "+typeof t)}function Os(t){return 0===t.length?[]:"SUMMARY"===t[0].tagName?t.map(t=>t.closest("details")).filter(t=>null!==t):t}function Ls(t,e,r){return()=>{"class"===e?t.classList.toggle(r):"attribute"===e&&Qn(t,r)}}function $s(t,e,r,n){const s=Ls(t,e,r),i=setTimeout(s,n);return()=>{clearTimeout(i)}}function Rs(t,e,r,n){const s=Ls(t,e,r),i=()=>{s(),t.removeEventListener(n,i)};return t.addEventListener(n,i,{once:1}),()=>{t.removeEventListener(n,i)}}function Is(t,e,r){if(e.startsWith("@")){const n=e.substring(1);return void(0==r?t.removeAttribute(n):t.setAttribute(n,1==r?"":r+""))}const n=r+"";switch(e){case"textContent":return void(t.textContent=n);case"innerHTML":return void(t.innerHTML=n);case"innerText":return void(t.innerText=n);case"id":return void(t.id=n);case"className":return void(t.className=n);case"value":return void("value"in t&&(t.value=n));case"checked":return void("checked"in t&&(t.checked=!!r))}if(e.includes(".")){const n=e.split(".");let s=t;for(let t=0;n.length-1>t;t++)if(s=s[n[t]],null==s)return;return void(s[n[n.length-1]]=r)}if(e.includes("-")||e in t.style)t.style.setProperty(e,n);else try{t[e]=r}catch(t){if(!(t instanceof TypeError&&(t.message.includes("only a getter")||t.message.includes("read only"))))throw Error(`Cannot set property '${e}': ${t instanceof Error?t.message:"Unknown error"}`)}}const js=/^the\s+(.+?)\s+of\s+(.+)$/i,Ds=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 Ms(t){return"string"==typeof t&&js.test(t)}function Ps(t,e){const r=t.match(js);if(!r)return null;try{return{element:hs(r[2].trim(),e),property:r[1].trim()}}catch{return null}}async function Vs(t,e,r){if(function(t){return t&&"object"==typeof t?"propertyOfExpression"===t.type&&"object"==typeof t.property&&null!==t.property:0}(t))return async function(t,e,r){const n=t.property?.name;if(!n)return null;let s=await e.evaluate(t.target,r);return Array.isArray(s)&&(s=s[0]),us(s)?{element:s,property:n}:null}(t,e,r);if(function(t){return t&&"object"==typeof t?"propertyAccess"!==t.type?0:"string"==typeof t.property||"object"==typeof t.property&&null!==t.property&&"string"==typeof t.property.name:0}(t))return async function(t,e,r){const n="string"==typeof t.property?t.property:t.property?.name;if(!n)return null;let s=await e.evaluate(t.object,r);return Array.isArray(s)&&(s=s[0]),us(s)?{element:s,property:n}:null}(t,e,r);const n=t;if("possessiveExpression"===n?.type||"memberExpression"===n?.type){const t=n.object,s=n.property;let i=await e.evaluate(t,r);if(Array.isArray(i)&&(i=i[0]),!us(i))return null;const o=s?.name||s?.value;return o&&(o.startsWith("@")||o.startsWith("*"))?{element:i,property:o}:null}return null}function Bs(t,e){const{element:r,property:n}=t;n.startsWith("*")?vs(r,n.substring(1),e+""):Is(r,n,e)}async function _s(t,e,r){let n,s;if(t?.for){const s=await e.evaluate(t.for,r);n="number"==typeof s?s:"string"==typeof s?function(t,e=300){if("number"==typeof t)return Math.max(0,Math.floor(t));if("string"==typeof t){const r=Ns(t);return r?r.milliseconds:e}return e}(s):void 0}if(t?.until){const n=await e.evaluate(t.until,r);"string"==typeof n&&(s=n)}return{duration:n,untilEvent:s}}const Fs=ls((()=>{let t,e,r=[cs({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"]}),as({name:"toggle",category:"dom"})],n=[];return e=class{async parseInput(t,e,r){if(!t.args?.length)throw Error("toggle command requires an argument");const n=t.args[0],s=n?.name;if("between"===s&&t.args.length>=4){const{duration:n,untilEvent:s}=await _s(t.modifiers,e,r),i=await e.evaluate(t.args[1],r),o=await e.evaluate(t.args[3],r),a=[];for(let e=4;t.args.length>e;e++){const r=t.args[e]?.name;"on"!==r&&"from"!==r&&a.push(t.args[e])}const c={filterPrepositions:1,fallbackModifierKey:"on"},l=await ms(a,e,r,"toggle",c,t.modifiers);return{type:"classes-between",classA:(i+"").replace(/^\./,""),classB:(o+"").replace(/^\./,""),targets:l,duration:n,untilEvent:s}}const i=await Vs(n,e,r);if(i)return{type:"property",target:i};const{duration:o,untilEvent:a}=await _s(t.modifiers,e,r),{value:c}=await Es(n,e,r);if(Ms(c)){const t=Ps(c,r);if(t)return{type:"property",target:t}}const{type:l,expression:u}=function(t,e){const r=e?.name,n=function(t){if(!t||"object"!=typeof t)return 0;if("identifier"!==t.type)return 0;const e=t.name;return"string"==typeof e&&function(t){if("string"!=typeof t)return 0;const e=t.toLowerCase();return gs.includes(e)}(e)}(e);if(us(t)||Array.isArray(t)&&t.every(t=>us(t)))return{type:"element",expression:""};if(n&&r)return{type:"element",expression:r};if("string"==typeof t){const e=t.trim();return e.startsWith("@")||e.startsWith("[@")?{type:"attribute",expression:e}:e.startsWith("*")?{type:"css-property",expression:e}:e.startsWith(".")?{type:"class",expression:e}:e.startsWith("#")||function(t){if("string"!=typeof t)return 0;const e=t.toLowerCase();return gs.some(t=>e.includes(t))}(e)?{type:"element",expression:e}:{type:"class",expression:e}}return{type:"class",expression:""}}(c,n),h={filterPrepositions:1,fallbackModifierKey:"on"};switch(l){case"attribute":{const{name:n,value:s}=Xn(u);return{type:"attribute",name:n,value:s,targets:await ms(t.args.slice(1),e,r,"toggle",h,t.modifiers),duration:o,untilEvent:a}}case"css-property":{const n=function(t){const e=function(t){const e=t.trim();if(!e.startsWith("*"))return null;const r=e.substring(1).trim();return r?{property:r}:null}(t);if(!e)return null;const r=e.property.toLowerCase();return["display","visibility","opacity"].includes(r)?r:null}(u);if(!n)throw Error("Invalid CSS property: "+u);return{type:"css-property",property:n,targets:await ms(t.args.slice(1),e,r,"toggle",h,t.modifiers)}}case"element":{let s;if(us(c))s=[c];else if(Array.isArray(c)&&c.every(t=>us(t)))s=c;else if(u){const t=document.querySelectorAll(u);s=Array.from(t).filter(t=>us(t))}else s=await ms([n],e,r,"toggle",h,t.modifiers);const i=function(t){if(0===t.length)return null;const e=t[0].tagName;if(!t.every(t=>t.tagName===e))return null;switch(e){case"DIALOG":return"dialog";case"DETAILS":return"details";case"SELECT":return"select";case"SUMMARY":return t.map(t=>t.closest("details")).filter(t=>null!==t).length>0?"details":null;default:return null}}(s);if("dialog"===i){const n=await async function(t,e,r,n){if(e?.as){const t=await r.evaluate(e.as,n);if("string"==typeof t&&"modal"===t.toLowerCase())return"modal"}if(t.length>=2){const e=await r.evaluate(t[1],n);if("string"==typeof e){const s=e.toLowerCase();if("modal"===s||"as modal"===s)return"modal";if("as"===s&&t.length>=3){const e=await r.evaluate(t[2],n);if("string"==typeof e&&"modal"===e.toLowerCase())return"modal"}}}return"non-modal"}(t.args,t.modifiers,e,r);return{type:"dialog",mode:n,targets:s}}return"details"===i?{type:"details",targets:Os(s)}:"select"===i?{type:"select",targets:s}:{type:"classes",classes:ts(u),targets:s,duration:o,untilEvent:a}}default:{const n=ts(u||c);if(!n.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:n,targets:await ms(t.args.slice(1),e,r,"toggle",h,t.modifiers),duration:o,untilEvent:a}}}}async execute(t,e){switch(t.type){case"classes":{const r=ns(t.classes,e);if(0===r.length)return[...t.targets];if(Kn(t.targets,r,(t,e)=>{t.classList.toggle(e)}),(t.duration||t.untilEvent)&&r.length)for(const e of t.targets)t.duration&&$s(e,"class",r[0],t.duration),t.untilEvent&&Rs(e,"class",r[0],t.untilEvent);return[...t.targets]}case"attribute":if(r=t.name,n=t.value,Yn(t.targets,t=>{Qn(t,r,n)}),t.duration||t.untilEvent)for(const e of t.targets)t.duration&&$s(e,"attribute",t.name,t.duration),t.untilEvent&&Rs(e,"attribute",t.name,t.untilEvent);return[...t.targets];case"css-property":return Yn(t.targets,e=>function(t,e){const r=window.getComputedStyle(t);switch(e){case"display":"none"===r.display?(t.style.display=t.dataset.previousDisplay||"block",delete t.dataset.previousDisplay):(t.dataset.previousDisplay=r.display,t.style.display="none");break;case"visibility":t.style.visibility="hidden"===r.visibility?"visible":"hidden";break;case"opacity":t.style.opacity=0===parseFloat(r.opacity)?"1":"0"}}(e,t.property));case"property":return function(t){const e=function(t){const{element:e,property:r}=t;return r.startsWith("*")?function(t,e){return window.getComputedStyle(t).getPropertyValue(e)}(e,r.substring(1)):Fe(e,r)}(t),r=t.property,n=r.startsWith("@")?r.substring(1):r;if("boolean"==typeof e||Ds.has(n)||Ds.has(n.toLowerCase())){const r=!e;return Bs(t,r),r}if("number"==typeof e){const r=0===e?1:0;return Bs(t,r),r}if("string"==typeof e){const n="__ht_"+r,s=t.element[n];return""===e&&void 0!==s?(Bs(t,s),s):(t.element[n]=e,Bs(t,""),"")}Bs(t,!e)}(t.target),[t.target.element];case"dialog":return Yn(t.targets,e=>{return n=t.mode,void((r=e).open?r.close():"modal"===n?r.showModal():r.show());var r,n});case"details":return Yn(t.targets,t=>{var e;(e=t).open=!e.open});case"select":return Yn(t.targets,t=>function(t){if(document.activeElement===t)t.blur();else{if(t.focus(),"showPicker"in t&&"function"==typeof t.showPicker)try{return void t.showPicker()}catch{}const e=new MouseEvent("click",{view:window,bubbles:1,cancelable:1});t.dispatchEvent(e)}}(t));case"classes-between":for(const e of t.targets){const r=e.classList.contains(t.classA),n=e.classList.contains(t.classB);r?(e.classList.remove(t.classA),e.classList.add(t.classB)):n?(e.classList.remove(t.classB),e.classList.add(t.classA)):e.classList.add(t.classA)}if(t.duration||t.untilEvent)for(const e of t.targets)t.duration&&$s(e,"class",t.classA,t.duration),t.untilEvent&&Rs(e,"class",t.classA,t.untilEvent);return[...t.targets]}var r,n}},Zn(e,"ToggleCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;zn(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),Jn(e,n)})(),e})());class qs{async parseInput(t,e,r){const{targets:n}=await async function(t,e,r,n){return{targets:await ms(t.args,e,r,n)}}(t,e,r,this.mode);return{targets:n,mode:this.mode,defaultDisplay:"show"===this.mode?"block":void 0}}validate(t){if("object"!=typeof t||null===t)return 0;const e=t;return Array.isArray(e.targets)&&e.targets.every(t=>us(t))?"show"!==e.mode&&"hide"!==e.mode||"show"===e.mode&&"string"!=typeof e.defaultDisplay?0:1:0}showElement(t,e="block"){const r=t.dataset.originalDisplay;void 0!==r?(t.style.display=r||e,delete t.dataset.originalDisplay):"none"===t.style.display&&(t.style.display=e),t.classList.add("show")}hideElement(t){if(!t.dataset.originalDisplay){const e=t.style.display;t.dataset.originalDisplay="none"===e?"":e}t.style.display="none",t.classList.remove("show")}}let Hs=(()=>{let t,e,r=[cs({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"]}),as({name:"show",category:"dom"})],n=[],s=qs;return e=class extends s{constructor(){super(...arguments),this.mode="show"}async execute(t,e){const r=t.defaultDisplay||"block";for(const e of t.targets)this.showElement(e,r)}validate(t){if("object"!=typeof t||null===t)return 0;const e=t;return Array.isArray(e.targets)&&e.targets.every(t=>us(t))?"string"!=typeof e.defaultDisplay?0:1:0}},Zn(e,"ShowCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;zn(null,t={value:e},r,{kind:"class",name:e.name,metadata:i},null,n),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:i}),Jn(e,n)})(),e})();const Us=ls(Hs);let Ws=(()=>{let t,e,r=[cs({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"]}),as({name:"hide",category:"dom"})],n=[],s=qs;return e=class extends s{constructor(){super(...arguments),this.mode="hide"}async execute(t,e){for(const e of t.targets)this.hideElement(e)}validate(t){if("object"!=typeof t||null===t)return 0;const e=t;return Array.isArray(e.targets)&&e.targets.every(t=>us(t))?1:0}},Zn(e,"HideCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;zn(null,t={value:e},r,{kind:"class",name:e.name,metadata:i},null,n),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:i}),Jn(e,n)})(),e})();const zs=ls(Ws),Js=ls((()=>{let t,e,r=[cs({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"]}),as({name:"put",category:"dom"})],n=[];return e=class{async parseInput(t,e,r){if(!t.args?.length)throw Error("put requires arguments");const n=t=>t?.type||"unknown",s=["into","before","after","at","at start of","at end of"];let i=-1,o=null;for(let e=0;t.args.length>e;e++){const r=t.args[e],a=n(r),c="literal"===a?r.value:r.name;if(("literal"===a||"identifier"===a)&&s.includes(c)){i=e,o=c;break}}let a=null,c=null;if(-1===i)if(t.modifiers.into||t.modifiers.before||t.modifiers.after){const e=t.modifiers.into?"into":t.modifiers.before?"before":"after";a=t.args[0],o=e,c=t.modifiers[e]}else if(3>t.args.length){if(2>t.args.length)throw Error("put requires content and position");a=t.args[0],o=t.args[1]?.value||t.args[1]?.name||"into"}else a=t.args[0],o=t.args[1]?.value||t.args[1]?.name||null,c=t.args[2];else a=t.args.slice(0,i)[0]||null,c=t.args.slice(i+1)[0]||null;if(!a)throw Error("put requires content");if(!o)throw Error("put requires position keyword");const l=await e.evaluate(a,r),u=this.mapPosition(o);let h,f,d=null;if(c){const t=n(c),s=await Vs(c,e,r);if(s)return{value:l,targets:[s.element],position:"replace",memberPath:s.property};if("memberExpression"===t){const t=c.object,n=c.property;if("selector"===t?.type?d=t.value:"identifier"===t?.type&&(d=t.name),d&&n?.name)h=n.name;else{const t=await e.evaluate(c,r);"string"==typeof t&&(d=t)}}else if("identifier"===t&&"me"===c.name)d=null;else if("selector"===t||"cssSelector"===t)d=c.value||c.selector;else if("literal"===t){const t=c.value;if("string"==typeof t&&Ms(t)){const e=Ps(t,r);if(e)return{value:l,targets:[e.element],position:"replace",memberPath:e.property}}"string"==typeof t&&this.looksLikeCss(t)?d=t:f=t+""}else if("identifier"===t){const t=c.name;if(this.looksLikeCss(t))d=t;else{const n=await e.evaluate(c,r),s=this.resolveEvaluatedAsElements(n);if(s)return{value:l,targets:s,position:u,memberPath:h};f=t}}else{const t=await e.evaluate(c,r),n=this.resolveEvaluatedAsElements(t);if(n)return{value:l,targets:n,position:u,memberPath:h};"string"==typeof t&&(this.looksLikeCss(t)?d=t:f=t)}}return f?{value:l,targets:[],position:u,memberPath:h,variableName:f}:{value:l,targets:await this.resolveTargets(d,r),position:u,memberPath:h}}async execute(t,e){const{value:r,targets:n,position:s,memberPath:i,variableName:o}=t;if(o)return e.locals&&e.locals.set(o,r),e[o]=r,void Object.assign(e,{it:r});if(i)for(const t of n)this.setProperty(t,i,r);else for(const t of n){const e=this.parseValue(r);this.insertContent(t,e,s)}return n}mapPosition(t){switch(t){case"into":return"replace";case"before":return"beforebegin";case"after":return"afterend";case"at start of":return"afterbegin";case"at end of":return"beforeend";default:throw Error("Invalid position: "+t)}}async resolveTargets(t,e){if(!t||"me"===t){if(!e.me||!us(e.me))throw Error("put: no target and context.me is null");return[e.me]}const r=Array.from(document.querySelectorAll(t)).filter(t=>us(t));if(!r.length)throw Error(`No elements: "${t}"`);return r}parseValue(t){return us(t)?t:null==t?"":t+""}insertContent(t,e,r){if("replace"!==r)if(us(e)){const n=e;switch(r){case"beforebegin":t.parentElement?.insertBefore(n,t);break;case"afterbegin":t.insertBefore(n,t.firstChild);break;case"beforeend":t.appendChild(n);break;case"afterend":t.parentElement?.insertBefore(n,t.nextSibling)}}else e.includes("<")&&e.includes(">")?t.insertAdjacentHTML(r,e):t.insertAdjacentText(r,e);else us(e)?(t.innerHTML="",t.appendChild(e)):e.includes("<")&&e.includes(">")?t.innerHTML=e:t.textContent=e}resolveEvaluatedAsElements(t){if(us(t))return[t];if(Array.isArray(t)){const e=t.filter(us);return e.length>0?e:null}if("undefined"!=typeof NodeList&&t instanceof NodeList){const e=Array.from(t).filter(us);return e.length>0?e:null}return null}looksLikeCss(t){return t?/^[#.\[]/.test(t)||/[>+~\s]/.test(t)&&t.length>1?1:["div","span","p","a","button","input","form","ul","li","ol","table","tr","td","th","img","h1","h2","h3","h4","h5","h6","section","article","header","footer","nav","main","aside","dialog","label","select","option","textarea"].includes(t.toLowerCase()):0}setProperty(t,e,r){const n=e.split(".");let s=t;for(let t=0;n.length-1>t;t++){if(!s[n[t]])throw Error(`Property path "${e}" does not exist`);s=s[n[t]]}s[n[n.length-1]]=r}},Zn(e,"PutCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;zn(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),Jn(e,n)})(),e})()),Zs=ls((()=>{let t,e,r=[cs({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"]}),as({name:"set",category:"data"})],n=[];return e=class{async parseInput(t,e,r){if(!t.args?.length)throw Error("set command requires a target");const n=t.args[0],s=n?.name||n?.value,i=await Vs(n,e,r);if(i){const n=await this.extractValue(t,e,r);if(i.property.startsWith("*")){const t=i.property.substring(1);return{type:"style",element:i.element,property:t,value:n+""}}return{type:"property",element:i.element,property:i.property,value:n}}if("memberExpression"===n?.type||"propertyAccess"===n?.type){const s=await this.tryParseMemberExpression(n,t,e,r);if(s)return s}let o;if(o="identifier"!==n?.type&&"variable"!==n?.type||"string"!=typeof s?await e.evaluate(n,r):s,function(t){if("object"!=typeof t||null===t||Array.isArray(t))return 0;if(us(t)||t instanceof Node)return 0;const e=Object.getPrototypeOf(t);return e===Object.prototype||null===e}(o))return{type:"object-literal",properties:o,targets:await this.resolveTargets(t.modifiers.on,e,r)};if(Ms(o)){const n=Ps(o,r);if(n){const s=await this.extractValue(t,e,r);return{type:"property",element:n.element,property:n.property,value:s}}return this.parseTheXofY(o,t,e,r)}if("string"==typeof o&&ys(o)){const n=o.substring(1).trim(),s=await this.extractValue(t,e,r);return{type:"style",element:await this.resolveElement(t.modifiers.on,e,r),property:n,value:s+""}}if("string"==typeof o&&Gn(o)){const n=o.substring(1).trim(),s=await this.extractValue(t,e,r);return{type:"attribute",element:await this.resolveElement(t.modifiers.on,e,r),name:n,value:s}}if("string"==typeof o){const n=o.match(/^(my|me|its?|your?)\s+(.+)$/i);if(n){const s=ds(n[1],r),i=await this.extractValue(t,e,r);return{type:"property",element:s,property:n[2],value:i}}}if(us(o))return{type:"property",element:o,property:"textContent",value:await this.extractValue(t,e,r)};if(Array.isArray(o)&&o.length>0&&us(o[0])){const n=await this.extractValue(t,e,r);return{type:"property",element:o[0],property:"textContent",value:n}}if("string"!=typeof o)throw Error("set command target must be a string or object literal");return{type:"variable",name:o,value:await this.extractValue(t,e,r)}}async execute(t,e){switch(t.type){case"variable":return e.locals.set(t.name,t.value),"result"!==t.name&&"it"!==t.name||Object.assign(e,{[t.name]:t.value}),Object.assign(e,{it:t.value}),{target:t.name,value:t.value,targetType:"variable"};case"attribute":return t.element.setAttribute(t.name,t.value+""),Object.assign(e,{it:t.value}),{target:"@"+t.name,value:t.value,targetType:"attribute"};case"property":return Is(t.element,t.property,t.value),Object.assign(e,{it:t.value}),{target:t.element,value:t.value,targetType:"property"};case"style":return vs(t.element,t.property,t.value),Object.assign(e,{it:t.value}),{target:t.element,value:t.value,targetType:"property"};case"object-literal":for(const e of t.targets)for(const[r,n]of Object.entries(t.properties))Is(e,r,n);return Object.assign(e,{it:t.properties}),{target:t.targets[0]||"unknown",value:t.properties,targetType:"property"};case"member-assignment":return t.container[t.property]=t.value,Object.assign(e,{it:t.value}),{target:t.property,value:t.value,targetType:"property"};default:throw Error("Unknown input type: "+t.type)}}async tryParseMemberExpression(t,e,r,n){const s=t.object,i=t.property;if(s?.name&&i?.name){const t=s.name.toLowerCase();if(["me","my","it","its","you","your"].includes(t)){const s=ds(t,n),o=await this.extractValue(e,r,n);return{type:"property",element:s,property:i.name,value:o}}}const o=t.object,a=t.computed;if(o){const s=await r.evaluate(o,n);if(null!=s&&"object"==typeof s){const o=a?await r.evaluate(t.property,n)+"":i?.name||"";if(o)return{type:"member-assignment",container:s,property:o,value:await this.extractValue(e,r,n)}}}return null}async extractValue(t,e,r){if(t.modifiers.to)return e.evaluate(t.modifiers.to,r);const n=t.args.findIndex(t=>"identifier"===t.type&&"to"===t.name);if(n>=0&&t.args.length>n+1)return e.evaluate(t.args[n+1],r);if(t.args.length>=2)return e.evaluate(t.args[1],r);throw Error('set command requires a value (use "to" keyword)')}async resolveElement(t,e,r){return hs(t?await e.evaluate(t,r):void 0,r)}async resolveTargets(t,e,r){return function(t,e){if(Array.isArray(t))return t.filter(us);if(t instanceof NodeList)return Array.from(t).filter(us);if(us(t))return[t];if(!t){const t=e.me;return t&&us(t)?[t]:[]}if("string"==typeof t){const r=t.trim();if("me"===r)return e.me&&us(e.me)?[e.me]:[];if("it"===r)return us(e.it)?[e.it]:[];if("you"===r)return e.you&&us(e.you)?[e.you]:[];const n=e.me?.ownerDocument??("undefined"!=typeof document?document:null);if(n){let t=r;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const e=n.querySelectorAll(t);return Array.from(e).filter(us)}}return[]}(t?await e.evaluate(t,r):void 0,r)}async parseTheXofY(t,e,r,n){const s=t.match(/^the\s+(.+?)\s+of\s+(.+)$/i);if(!s)throw Error('Invalid "the X of Y" syntax');const[,i,o]=s,a=hs(o,n),c=await this.extractValue(e,r,n);return{type:"property",element:a,property:i.trim(),value:c}}validate(t){if(!t||"object"!=typeof t)return 0;const e=t;if(!e.type||"string"!=typeof e.type)return 0;if(!["variable","attribute","property","style","object-literal"].includes(e.type))return 0;switch(e.type){case"variable":return"string"==typeof e.name&&"value"in e;case"attribute":return"string"==typeof e.name&&us(e.element)&&"value"in e;case"property":return"string"==typeof e.property&&us(e.element)&&"value"in e;case"style":return"string"==typeof e.property&&""!==e.property&&us(e.element)&&"string"==typeof e.value;case"object-literal":return null!==e.properties&&"object"==typeof e.properties&&Array.isArray(e.targets)&&e.targets.length>0;default:return 0}}},Zn(e,"SetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;zn(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),Jn(e,n)})(),e})());function Gs(t){const e=t.trim();return/^\d+$/.test(e)?parseInt(e,10):/^\d*\.\d+$/.test(e)?parseFloat(e):"true"===e?1:"false"===e?0:"null"===e?null:"undefined"!==e?e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e:void 0}const Xs=ls((()=>{let t,e,r=[cs({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"]}),as({name:"trigger",category:"event"})],n=[];return e=class{async parseInput(t,e,r){const n="send"===t.commandName?.toLowerCase()?"send":"trigger",s=n;if(!t.args?.length)throw Error(s+" command requires an event name");const i=t=>t?.type||"unknown",o=t.args[0];let a,c,l;if("functionCall"===i(o)||"callExpression"===i(o)){a=o.name||o.callee?.name;const t=o.args||o.arguments;t?.length&&(c=await this.parseEventDetail(t,e,r))}else if("identifier"===i(o)||"keyword"===i(o))a=o.name;else{const t=await e.evaluate(o,r);a="string"==typeof t?t:t+""}const u=t.modifiers?.on||t.modifiers?.to;if(u)l=await this.resolveTargets([u],e,r,s);else{const n=t.args.findIndex((t,e)=>{if(0===e)return 0;const r=t.name||t.value;return"on"===r||"to"===r});if(-1!==n&&t.args.length-1>n){const i=t.args.slice(n+1),o=i.findIndex(t=>"with"===(t.name||t.value)),a=-1===o?i:i.slice(0,o);l=await this.resolveTargets(a,e,r,s)}else{if(!r.me)throw Error(s+": no target specified and context.me is null");l=[r.me]}}return{eventName:a,detail:c,targets:l,options:await this.parseEventOptions(t.args,e,r),mode:n}}async execute(t,e){const r=function(t,e,r={}){return new CustomEvent(t,{detail:void 0!==e?e:{},bubbles:void 0!==r.bubbles?r.bubbles:1,cancelable:void 0!==r.cancelable?r.cancelable:1,composed:void 0!==r.composed?r.composed:0})}(t.eventName,t.detail,t.options);for(const e of t.targets)e.dispatchEvent(r);e.it=r}async resolveTargets(t,e,r,n){const s=[];for(const n of t){const t=await e.evaluate(n,r);if("window"!==t&&t!==window)if("document"!==t&&t!==document)if("me"===t&&r.me)s.push(r.me);else if("you"===t&&r.you)s.push(r.you);else if("it"===t&&r.it)s.push(r.it);else if(us(t))s.push(t);else if(t instanceof NodeList)s.push(...Array.from(t).filter(us));else if(Array.isArray(t))s.push(...t.filter(us));else{if("string"==typeof t){const e=document.querySelectorAll(t);if(0===e.length)throw Error(`No elements found: "${t}"`);s.push(...Array.from(e).filter(us));continue}if(!t||"object"!=typeof t||!("addEventListener"in t))throw Error("Invalid target: "+typeof t);s.push(t)}else s.push(document);else s.push(window)}if(!s.length)throw Error(n+": no valid targets");return s}async parseEventDetail(t,e,r){if(!t?.length)return;if(1===t.length){const n=t[0];if("objectLiteral"!==n?.type)return await e.evaluate(n,r)}const n={};for(const s of t){const t=await e.evaluate(s,r);if("object"!=typeof t||null===t||Array.isArray(t)){if("string"==typeof t&&t.includes(":")){const[e,r]=t.split(":",2);n[e.trim()]=Gs(r.trim())}}else Object.assign(n,t)}return Object.keys(n).length?n:void 0}async parseEventOptions(t,e,r){const n={bubbles:1,cancelable:1,composed:0},s=t.findIndex(t=>"with"===(t.name||t.value));if(-1===s)return n;for(const i of t.slice(s+1)){const t=await e.evaluate(i,r);if("string"==typeof t){const e=t.toLowerCase();"bubbles"===e?n.bubbles=1:"nobubbles"===e?n.bubbles=0:"cancelable"===e?n.cancelable=1:"nocancelable"===e?n.cancelable=0:"composed"===e&&(n.composed=1)}}return n}},Zn(e,"EventDispatchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;zn(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),Jn(e,n)})(),e})()),Ys=ls((()=>{let t,e,r=[cs({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"]}),as({name:"log",category:"utility"})],n=[];return e=class{async parseInput(t,e,r){return t.args&&0!==t.args.length?{values:await Promise.all(t.args.map(t=>e.evaluate(t,r)))}:{values:[]}}async execute(t,e){const r="undefined"!=typeof window?window.console:console;0===t.values.length?r.log():r.log(...t.values)}validate(t){return"object"!=typeof t||null===t?0:Array.isArray(t.values)}},Zn(e,"LogCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;zn(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),Jn(e,n)})(),e})());function Ks(t,e,r){return t?new Promise(r=>{const n=function(r,n){let i=0;return r=>{i||(i=1,t.removeEventListener(e,s),n(r))}}(0,r),s=t=>{n({event:t,timedOut:0,cancelled:0})};t.addEventListener(e,s)}):Promise.reject(Error("waitForEvent: no target provided"))}function Qs(t){return new Promise(e=>setTimeout(e,t))}const ti=ls((()=>{let t,e,r=[cs({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"]}),as({name:"wait",category:"async"})],n=[];return e=class{async parseInput(t,e,r){if(!t.args?.length)throw Error("wait command requires an argument");if(t.modifiers.or)return this.parseRaceCondition(t,e,r);if(t.modifiers.for)return this.parseEventWait(t.modifiers.for,t.modifiers.from,e,r);const n=t.args[0];return"arrayLiteral"===n.type&&n.elements?this.parseEventArrayWait(n.elements,t.args[1],e,r):this.parseTimeWait(t.args[0],e,r)}async execute(t,e){const r=Date.now();if("time"===t.type)return await Qs(t.milliseconds),{type:"time",result:t.milliseconds,duration:Date.now()-r};if("event"===t.type){const n=t.target??e.me??document,s=(await Ks(n,t.eventName)).event;if(Object.assign(e,{it:s}),t.destructure)for(const r of t.destructure)r in s&&e.locals.set(r,s[r]);return{type:"event",result:s,duration:Date.now()-r}}const{result:n,winningCondition:s}=await this.executeRace(t.conditions,e);if(Object.assign(e,{it:n}),n instanceof Event&&"event"===s?.type&&s.destructure)for(const t of s.destructure)t in n&&e.locals.set(t,n[t]);return{type:n instanceof Event?"event":"time",result:n,duration:Date.now()-r}}async parseTimeWait(t,e,r){return{type:"time",milliseconds:Ts(await e.evaluate(t,r))}}async parseEventWait(t,e,r,n){const s=await r.evaluate(t,n);if("string"!=typeof s)throw Error("wait for: event name must be a string");const i=s.match(/^(\w+)\(([^)]+)\)$/),o=i?i[1]:s,a=i?i[2].split(",").map(t=>t.trim()):void 0;let c;if(e){const t=await r.evaluate(e,n);if(!t||"object"!=typeof t||!("addEventListener"in t))throw Error("wait for from: target must be an EventTarget");c=t}else c=n.me??void 0;return{type:"event",eventName:o,target:c,destructure:a}}async parseEventArrayWait(t,e,r,n){const s=[];for(const e of t){const t=e;if("objectLiteral"===t.type&&t.properties){let e="",r=[];for(const n of t.properties){const t=n.key?.name||n.key?.value;"name"===t&&n.value?e=n.value.value||"":"args"===t&&n.value?.elements&&(r=n.value.elements.map(t=>t.value||t.name||""))}e&&s.push({name:e,params:r})}}let i;if(e){const t=await r.evaluate(e,n);t&&"object"==typeof t&&"addEventListener"in t&&(i=t)}return i||(i=n.me??void 0),1===s.length?{type:"event",eventName:s[0].name,target:i,destructure:s[0].params.length>0?s[0].params:void 0}:{type:"race",conditions:s.map(t=>({type:"event",eventName:t.name,target:i,destructure:t.params.length>0?t.params:void 0}))}}async parseRaceCondition(t,e,r){const n=[];t.modifiers.for?n.push(await this.parseEventWait(t.modifiers.for,t.modifiers.from,e,r)):t.args[0]&&n.push(await this.parseTimeWait(t.args[0],e,r));const s=await e.evaluate(t.modifiers.or,r),i=Array.isArray(s)?s:[s];for(const t of i)try{n.push({type:"time",milliseconds:Ts(t)})}catch{if("string"==typeof t){const e=t.match(/^(\w+)\(([^)]+)\)$/);n.push(e?{type:"event",eventName:e[1],target:r.me??void 0,destructure:e[2].split(",").map(t=>t.trim())}:{type:"event",eventName:t,target:r.me??void 0})}}if(2>n.length)throw Error("wait: race requires at least 2 conditions");return{type:"race",conditions:n}}async executeRace(t,e){const r=t.map(t=>"time"===t.type?Qs(t.milliseconds).then(()=>({result:t.milliseconds,winningCondition:t})):Ks(t.target??e.me??document,t.eventName).then(e=>({result:e.event,winningCondition:t})));return Promise.race(r)}},Zn(e,"WaitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;zn(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),Jn(e,n)})(),e})()),ei=function(t,e){const r=new Dn(e.expressionEvaluator);for(const e of t)r.register(e);return new Un({registry:r,expressionEvaluator:e.expressionEvaluator,enableAsyncCommands:e.enableAsyncCommands??1,commandTimeout:e.commandTimeout??1e4,enableErrorReporting:e.enableErrorReporting??1,enableResultPattern:e.enableResultPattern??1})}([ks(),Cs(),Fs(),Us(),zs(),Js(),Zs(),Xs(),Ys(),ti()],{expressionEvaluator:new class extends Xe{constructor(t){super();for(const e of t)this.registerCategory(e)}}([Er,on,$n])}),ri={parse:t=>be(t),execute:async(t,e)=>{const r=function(t){if(!t)return Ne();if(t.locals instanceof Map&&t.globals instanceof Map&&t.flags)return t;const e=Ne(t.me instanceof Element?t.me:null);return void 0!==t.it&&(e.it=t.it),void 0!==t.you&&(e.you=t.you),void 0!==t.result&&(e.result=t.result),void 0!==t.event&&Object.assign(e,{event:t.event}),e}(e),n=be(t);if(!n.success||!n.node)throw Error(n.error?.message||"Parse failed");return await ei.execute(n.node,r)}},ni=function(t){return new Wn(t)}(ri),si={runtime:ri,parse:t=>ri.parse(t),execute:async(t,e)=>ri.execute(t,e),createContext:Ne,attributeProcessor:ni,version:"1.1.0-minimal-v2-tree-shakeable",commands:["add","remove","toggle","show","hide","put","set","send","log","wait"],eval:async(t,e)=>ri.execute(t,e),init:()=>{ni.init()}};return"undefined"!=typeof window&&(window.hyperfixi=si,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{ni.init()}):ni.init()),si}();
1
+ var hyperfixi=function(){"use strict";const t="then",e="else",r="end",n="and",s="for",i="while",o="until",a="forever",c="times",l="index",u="in",h="to",f="from",d="with",p="of",m="on",y="event",v="behavior",g="global",b="the",E="start",w=new Set(["add","append","async","beep","break","call","continue","copy","decrement","default","exit","fetch","for","get","go","halt","hide","if","increment","install","js","log","make","measure","morph","pick","process","push","put","remove","render","repeat","replace","return","send","set","settle","show","swap","take","tell","throw","toggle","transition","trigger","unless","wait"]),x=new Set(["put","trigger","send","remove","take","toggle","set","show","hide","add","halt","measure","js","tell","swap","morph","push","replace","process"]),k=(new Set(["if","unless","repeat","wait","for","while"]),"at start of"),A="at end of",S=["into","before","after","at",k,A,"at the start of","at the end of"],C=new Set(["if","else","unless","for","while","until","end","and","or","not","in","to","from","into","with","without","as","matches","contains","then","on","when","every","init","def","behavior","the","of","first","last"]),N=new Set(["hsl","hsla","rgb","rgba","hwb","lab","lch","oklch","oklab","color","color-mix","calc","min","max","clamp","var","url","linear-gradient","radial-gradient","conic-gradient","repeating-linear-gradient","repeating-radial-gradient","repeating-conic-gradient"]),T=new Set(["me","it","you","result","my","its","your"]),O=new Set(["and","or","not","no"]),$=new Set(["==","!=","===","!==","<",">","<=",">=","is","is not","is a","is an","is not a","is not an","contains","has","have","does not contain","include","includes","does not include","match","matches","exists","does not exist","is empty","is not empty","is in","is not in","equals","in","is equal to","is really equal to","is not equal to","is not really equal to","is greater than","is less than","is greater than or equal to","is less than or equal to","really equals"]),L=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"]),R=new Set(["on","init","behavior","def","if","else","unless","for","while","until","end","and","or","not","in","to","from","into","with","as","then","when","where","after","before","by","at","between","async","no","start","of","the","new","global","local","equal","equals","greater","less","than","really","catch","finally","throw","return"]);var I;!function(t){t.IDENTIFIER="identifier",t.STRING="string",t.NUMBER="number",t.SELECTOR="selector",t.OPERATOR="operator",t.TIME="time",t.TEMPLATE="template",t.COMMENT="comment",t.SYMBOL="symbol",t.UNKNOWN="unknown"}(I||(I={}));const j=new Set(["+","-","*","/","mod"]),M=new Set(["ms","s","seconds","minutes","hours","days"]);function D(t,e=1){const r=t.position+e;return t.input.length>r?t.input[r]:""}function P(t){const e=t.input[t.position];return t.position++,"\n"===e?(t.line++,t.column=1):"\r"===e?("\n"===(t.input.length>t.position?t.input[t.position]:"")&&t.position++,t.line++,t.column=1):t.column++,e}function V(t){const e=t.input,r=e.length;for(;r>t.position;){const r=e[t.position];if(" "!==r&&"\t"!==r&&"\r"!==r&&"\n"!==r)break;P(t)}}function B(t,e,r,n,s){const i=n??t.position-r.length,o=t.position;let a=t.column-r.length;if(void 0!==n){a=1;let e=-1;for(let r=0;n>r;r++)"\n"!==t.input[r]&&"\r"!==t.input[r]||(e=r);a=n-e}const c={kind:e,value:r,start:i,end:o,line:F(t,i),column:a};t.tokens.push(c)}function F(t,e){let r=1;for(let n=0;e>n&&t.input.length>n;n++){const e=t.input[n];"\n"===e?r++:"\r"===e&&(r++,t.input.length>n+1&&"\n"===t.input[n+1]&&n++)}return r}function _(t){const e=t.position;let r="";for(P(t),P(t);t.input.length>t.position&&"\n"!==t.input[t.position];)r+=P(t);B(t,I.COMMENT,"--"+r,e)}function q(t){const e=t.position,r=P(t);let n=r;for(;t.input.length>t.position;){const e=P(t);if(n+=e,e===r)break;"\\"===e&&t.input.length>t.position&&(n+=P(t))}B(t,I.STRING,n,e)}function H(t){const e=t.position;P(t);let r="";for(;t.input.length>t.position;){const e=t.input[t.position];if("`"===e){P(t);break}if("\\"===e){if(P(t),t.input.length>t.position){const e=P(t);switch(e){case"n":r+="\n";break;case"t":r+="\t";break;case"r":r+="\r";break;case"\\":r+="\\";break;case"`":r+="`";break;default:r+=e}}}else r+=P(t)}if(t.position>=t.input.length&&!t.input.endsWith("`"))throw Error(`Unterminated template literal at line ${t.line}, column ${t.column-r.length}`);B(t,I.TEMPLATE,r,e)}function U(t){const e=t.position;let r=P(t);for(;t.input.length>t.position;){const e=t.input[t.position];if(!K(e)&&"-"!==e&&"_"!==e&&":"!==e)break;r+=P(t)}B(t,I.SELECTOR,r,e)}function W(t){const e=t.position;let r="";for(r+=P(t);t.input.length-1>t.position;){const e=t.input[t.position],n=t.input[t.position+1];if(r+=P(t),"/"===e&&">"===n){r+=P(t);break}}B(t,I.SELECTOR,r,e)}function z(t){const e=t.position;let r=P(t);for(;t.input.length>t.position;){const e=t.input[t.position];if(!K(e)&&"_"!==e&&"-"!==e)break;r+=P(t)}B(t,I.SYMBOL,r,e)}function J(t){const e=t.position;let r="";const n=t.input[t.position];if(("'"===n||"'"===n)&&"s"===D(t,1))return r="'s",P(t),P(t),void B(t,I.OPERATOR,r,e);const s=t.input.substring(t.position,t.position+2),i=t.input.substring(t.position,t.position+3);["===","!=="].includes(i)?(r=i,P(t),P(t),P(t)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(s)?(r=s,P(t),P(t)):r=P(t),B(t,I.OPERATOR,r,e)}function Z(t){const e=t.position,r=t.input,n=r.length;let s="";for(;n>t.position;){const e=r[t.position];if("0">e||e>"9")break;s+=P(t)}if(n>t.position&&"."===r[t.position]&&(t.position+1>=n||"."!==r[t.position+1]))for(s+=P(t);n>t.position;){const e=r[t.position];if("0">e||e>"9")break;s+=P(t)}if(n>t.position){const e=r[t.position];if("e"===e||"E"===e){const e=n>t.position+1?r[t.position+1]:"",i=n>t.position+2?r[t.position+2]:"";if(e>="0"&&"9">=e||!("+"!==e&&"-"!==e||"0">i||i>"9"))for(s+=P(t),"+"!==r[t.position]&&"-"!==r[t.position]||(s+=P(t));n>t.position;){const e=r[t.position];if("0">e||e>"9")break;s+=P(t)}}}const i=t.position;let o="";for(;n>t.position;){const e=r[t.position];if(("a">e||e>"z")&&("A">e||e>"Z"))break;o+=P(t)}M.has(o)?B(t,I.TIME,s+o,e):(t.position=i,B(t,I.NUMBER,s,e))}function G(t){const e=t.position,r=t.input,n=r.length;let s="";for(;n>t.position;){const e=r[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;s+=P(t)}const i=function(t,e,r){const n=e.toLowerCase(),s=t.position;if("'s"===e||"'s"===e)return 0;const i=t.tokens[t.tokens.length-1];if(i&&(i.kind===I.IDENTIFIER||i.kind===I.SELECTOR)){const e=t.input.length>t.position?t.input[t.position]:"";if("'"===e||"'"===e)return 0}V(t);let o="";for(;t.input.length>t.position;){const e=t.input[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;o+=P(t)}if(o){const e=o.toLowerCase(),s=`${n} ${e}`,i=function(t,e,r,n){const s=e.toLowerCase(),i=r.toLowerCase();if("at"===s){const e=t.position;if("the"===i){V(t);let r="";for(;t.input.length>t.position;){const e=t.input[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;r+=P(t)}const s=r.toLowerCase();if("start"===s||"end"===s){V(t);let e="";for(;t.input.length>t.position;){const r=t.input[t.position];if(("a">r||r>"z")&&("A">r||r>"Z")&&("0">r||r>"9")&&"_"!==r&&"-"!==r)break;e+=P(t)}if("of"===e.toLowerCase())return B(t,I.IDENTIFIER,`at the ${s} of`,n),1}return t.position=e,0}if("start"===i||"end"===i){V(t);let r="";for(;t.input.length>t.position;){const e=t.input[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;r+=P(t)}return"of"===r.toLowerCase()?(B(t,I.IDENTIFIER,`at ${i} of`,n),1):(t.position=e,0)}}return 0}(t,n,e,r);if(i)return 1;const a=function(t,e,r){const n=t.position;let s=`${e} ${r}`,i=t.position;const o=[e,r];for(;8>o.length&&(V(t),t.input.length>t.position);){let e="";for(;t.input.length>t.position;){const r=t.input[t.position];if(("a">r||r>"z")&&("A">r||r>"Z"))break;e+=P(t)}if(!e)break;o.push(e.toLowerCase());const r=o.join(" ");$.has(r)&&(s=r,i=t.position)}return $.has(s)&&s!==`${e} ${r}`?(t.position=i,s):(t.position=n,null)}(t,n,e);if(a)return B(t,I.OPERATOR,a,r),1;if($.has(s))return B(t,I.OPERATOR,s,r),1}return $.has(n)?(t.position=s,B(t,I.OPERATOR,e,r),1):(t.position=s,0)}(t,s,e);if(i)return;const o=function(t){const e=t.toLowerCase();return"include"===e||"includes"===e||O.has(e)||j.has(t)||j.has(e)||$.has(e)?I.OPERATOR:I.IDENTIFIER}(s);B(t,o,s,e)}function X(t){const e=t.position,r=t.input,n=r.length;P(t);let s="$";for(;n>t.position;){const e=r[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e)break;s+=P(t)}B(t,I.IDENTIFIER,s,e)}function Y(t){return/[a-zA-Z]/.test(t)}function K(t){return/[a-zA-Z0-9]/.test(t)}function Q(t){let e=t.position+1,r=0;for(;t.input.length>e;){const n=t.input[e];if("/"===n&&t.input.length>e+1&&">"===t.input[e+1])return r;if(K(n)||"."===n||"#"===n||"["===n||"]"===n||":"===n||"-"===n||"_"===n||" "===n||"="===n||'"'===n||"'"===n||"("===n||")"===n||"*"===n||"^"===n||"$"===n||"~"===n||"|"===n||">"===n||"+"===n||","===n)r=1,e++;else{if(" "!==n&&"\t"!==n)return 0;e++}if(e-t.position>50)return 0}return 0}function tt(t){return"+-*/^%=!<>&|(){}[],.;:?''~$".includes(t)}const et=function(){if("undefined"!=typeof localStorage)try{const t=localStorage,e=t.getItem("hyperfixi:debug")||t.getItem("lokascript:debug");if("*"===e||"true"===e)return 1}catch{}return"undefined"!=typeof process&&"true"===process.env?.HYPERFIXI_DEBUG?1:0}(),rt=et,nt=et,st=et,it=et,ot=et,at=(...t)=>{rt&&console.log("🔧",...t)},ct=(...t)=>{nt&&console.log("🎯",...t)},lt=(...t)=>{st&&console.log("📝",...t)},ut=(...t)=>{it&&console.log("🔍",...t)},ht=(...t)=>{ot&&console.log("🚀",...t)};let ft=0,dt=null;if("undefined"!=typeof window&&"undefined"!=typeof URLSearchParams)try{"semantic"===new URLSearchParams(window.location.search).get("debug")&&(ft=1,dt=window,console.log("%c[HyperFixi] Semantic debug auto-enabled via URL param","color: #667eea; font-weight: bold"))}catch{}let pt={totalParses:0,semanticSuccesses:0,semanticFallbacks:0,traditionalParses:0,averageConfidence:0,confidenceHistory:[]};class mt{constructor(t){this.analyzer=t.analyzer,this.language=t.language,this.confidenceThreshold=t.confidenceThreshold??.5,this.debugEnabled=t.debug??0}isAvailable(){return this.analyzer.supportsLanguage(this.language)}shouldSkipSemantic(t){const e=t.trim().split(/\s+/)[0]?.toLowerCase();if(mt.SKIP_SEMANTIC_COMMANDS.has(e))return 1;const r=t.toLowerCase();return/\bjs\b/.test(r)||/\btell\b/.test(r)||/\*[a-zA-Z]/.test(t)?1:0}trySemanticParse(t){const e=performance.now();if(this.shouldSkipSemantic(t))return{success:0,confidence:0,errors:["Command skipped for semantic parsing - using traditional parser"]};if(!this.isAvailable())return{success:0,confidence:0,errors:[`Semantic parsing not available for language '${this.language}'`]};try{const n=this.analyzer.analyze(t,this.language),s=performance.now()-e;this.debugEnabled&&console.log("[SemanticIntegration] Analysis result:",{input:t,language:this.language,confidence:n.confidence,command:n.command?.name,threshold:this.confidenceThreshold});const i=n.confidence>=this.confidenceThreshold&&!!n.command,o=!i&&n.confidence>0;if(ft){const e={};if(n.command?.roles)for(const[t,r]of n.command.roles)e[t]=r.value;const a={input:t.substring(0,100),language:this.language,confidence:n.confidence,threshold:this.confidenceThreshold,semanticSuccess:i,fallbackTriggered:o,command:n.command?.name,roles:Object.keys(e).length>0?e:void 0,errors:n.errors,timestamp:Date.now(),duration:s};!function(t){if(!ft)return;const e=t.semanticSuccess?"semantic":t.fallbackTriggered?"fallback":"traditional",r=Math.round(100*t.confidence),n=Math.round(100*t.threshold),s=t.semanticSuccess?"color: #4caf50; font-weight: bold":t.fallbackTriggered?"color: #ff9800; font-weight: bold":"color: #9e9e9e";if(console.groupCollapsed(`%c[Semantic] ${e.toUpperCase()} %c${t.input.substring(0,50)}${t.input.length>50?"...":""}`,s,"color: #888"),console.log(`Confidence: ${r}% (threshold: ${n}%)`),t.command&&console.log("Command: "+t.command),t.roles&&Object.keys(t.roles).length>0&&console.log("Roles:",t.roles),t.duration&&console.log(`Duration: ${t.duration.toFixed(2)}ms`),t.errors?.length&&console.log("Errors:",t.errors),console.groupEnd(),dt){const e=new CustomEvent("lokascript:semantic:parse",{detail:t,bubbles:1});dt.dispatchEvent(e)}}(a),r=a,pt.totalParses++,r.semanticSuccess?pt.semanticSuccesses++:r.fallbackTriggered?pt.semanticFallbacks++:pt.traditionalParses++,pt.confidenceHistory.push(r.confidence),pt.confidenceHistory.length>100&&pt.confidenceHistory.shift(),pt.averageConfidence=pt.confidenceHistory.reduce((t,e)=>t+e,0)/pt.confidenceHistory.length}return i?{success:1,node:this.buildCommandNode(n),confidence:n.confidence,tokensConsumed:n.tokensConsumed}:{success:0,confidence:n.confidence,tokensConsumed:n.tokensConsumed,errors:n.errors}}catch(t){return{success:0,confidence:0,errors:[t instanceof Error?t.message:t+""]}}var r}buildCommandNode(t){const{command:e}=t;if(!e)throw Error("Cannot build command node without command data");if("repeat"===e.name)return this.buildRepeatCommandNode(e);if("for"===e.name)return this.buildRepeatCommandNode(e);if("set"===e.name)return this.buildSetCommandNode(e);if("if"===e.name||"unless"===e.name)return this.buildIfCommandNode(e);const r=[],n={};for(const[t,s]of e.roles){const i=this.semanticValueToExpression(s);switch(t){case"patient":case"event":r.push(i);break;case"destination":"put"===e.name?n.into=i:"add"===e.name||"append"===e.name||"prepend"===e.name?n.to=i:n.on=i;break;case"source":"fetch"===e.name?r.push(i):n.from=i;break;case"quantity":n.by=i;break;case"duration":n.over=i;break;case"responseType":n.as=i;break;case"method":n.method=i;break;case"style":n.with=i;break;case"condition":n.when=i;break;default:n[t]=i}}return{type:"command",name:e.name,args:r,modifiers:Object.keys(n).length>0?n:void 0,isBlocking:0,start:0,end:0,line:1,column:0}}buildRepeatCommandNode(t){const e=[],r={},n=t.roles.get("loopType");n&&e.push({type:"identifier",name:n.value+"",start:0,end:0,line:1,column:0});const s=t.roles.get("patient");"for"==(n?n.value+"":"")&&s&&e.push({type:"identifier",name:"expression"===s.type&&s.raw||s.value+"",start:0,end:0,line:1,column:0});const i=t.roles.get("event");i&&e.push({type:"string",value:i.value+"",start:0,end:0,line:1,column:0});const o=t.roles.get("source");o&&e.push(this.semanticValueToExpression(o));const a=t.roles.get("quantity");a&&e.push(this.semanticValueToExpression(a));const c=t.roles.get("condition");return c&&(r.condition=this.semanticValueToExpression(c)),{type:"command",name:"repeat",args:e,modifiers:Object.keys(r).length>0?r:void 0,isBlocking:0,start:0,end:0,line:1,column:0}}buildSetCommandNode(t){const e=[],r=t.roles.get("destination");if(r)if("property-path"===r.type){const t=r;e.push({type:"possessiveExpression",object:this.semanticValueToExpression(t.object),property:this.createPropertyNode(t.property),start:0,end:0,line:1,column:0})}else e.push(this.semanticValueToExpression(r));e.push({type:"identifier",name:"to",start:0,end:0,line:1,column:0});const n=t.roles.get("patient");return n&&e.push(this.semanticValueToExpression(n)),{type:"command",name:"set",args:e,isBlocking:0,start:0,end:0,line:1,column:0}}createPropertyNode(t){return t.startsWith("*")?{type:"cssProperty",name:t.substring(1),start:0,end:0,line:1,column:0}:{type:"identifier",name:t,start:0,end:0,line:1,column:0}}buildIfCommandNode(t){const e=[],r=t.roles.get("condition");return r&&e.push(this.semanticValueToExpression(r)),{type:"command",name:t.name,args:e,isBlocking:0,start:0,end:0,line:1,column:0}}semanticValueToExpression(t){switch(t.type){case"selector":return{type:"selector",value:t.value,start:0,end:0,line:1,column:0};case"reference":return{type:"identifier",name:t.value,start:0,end:0,line:1,column:0};case"literal":return"string"==typeof t.value&&t.value.includes("${")&&t.value.includes("}")?{type:"templateLiteral",value:t.value,start:0,end:0,line:1,column:0}:{type:"literal",value:t.value,raw:t.raw??t.value,start:0,end:0,line:1,column:0};case"property-path":{const e=t;return{type:"memberExpression",object:this.semanticValueToExpression(e.object),property:{type:"identifier",name:e.property,start:0,end:0,line:1,column:0},computed:0,start:0,end:0,line:1,column:0}}default:return this.parseExpressionString(t.raw||"")}}parseExpressionString(t){let e=0;const r=()=>{for(;t.length>e&&/\s/.test(t[e]);)e++},n=()=>{r();const n=e;for(;t.length>e&&/[a-zA-Z0-9_$]/.test(t[e]);)e++;return t.slice(n,e)},s=()=>{const n=[];if(e++,r(),")"!==t[e])for(n.push(i()),r();","===t[e];)e++,r(),n.push(i()),r();return")"===t[e]&&e++,n},i=()=>{r();const i=n();if(!i)return{type:"identifier",name:t.trim(),start:0,end:0,line:1,column:0};let o={type:"identifier",name:i,start:0,end:0,line:1,column:0};for(;t.length>e;){r();const i=t[e];if("."===i){e++;const t=n();t&&(o={type:"memberExpression",object:o,property:{type:"identifier",name:t,start:0,end:0,line:1,column:0},computed:0,start:0,end:0,line:1,column:0})}else{if("("!==i)break;o={type:"callExpression",callee:o,arguments:s(),start:0,end:0,line:1,column:0}}}return o};return i()}getLanguage(){return this.language}getConfidenceThreshold(){return this.confidenceThreshold}}function yt(t){return t.kind!==I.IDENTIFIER?0:w.has(t.value.toLowerCase())}function vt(t){return t.kind!==I.IDENTIFIER?0:R.has(t.value.toLowerCase())}function gt(t){return t.kind!==I.IDENTIFIER?0:L.has(t.value.toLowerCase())}function bt(t){return t.kind!==I.IDENTIFIER?0:T.has(t.value.toLowerCase())}function Et(t){return $.has(t.value.toLowerCase())}function wt(t){return t.kind===I.IDENTIFIER}function xt(t){return t.kind===I.SELECTOR}function kt(t){return t.kind!==I.SELECTOR?0:!t.value.startsWith("<")}function At(t){return t.kind===I.STRING||t.kind===I.NUMBER||t.kind===I.TEMPLATE}function St(t){return t.kind===I.IDENTIFIER}function Ct(t){return t.kind===I.TIME}function Nt(t){return t.kind===I.SYMBOL}function Tt(t){return t.kind===I.COMMENT}function Ot(t){if(t.kind!==I.IDENTIFIER)return 0;const e=t.value.toLowerCase();return!(w.has(e)||R.has(e)||L.has(e)||T.has(e))}function $t(t){return t.kind===I.STRING}function Lt(t){return t.kind===I.NUMBER}function Rt(t){if(t.kind===I.IDENTIFIER){const e=t.value;return"true"===e||"false"===e||"null"===e||"undefined"===e}return 0}function It(t){return t.kind===I.TEMPLATE}function jt(t){return t.kind===I.SELECTOR&&t.value.startsWith("<")}function Mt(t){return t.kind===I.SELECTOR&&t.value.startsWith("#")}function Dt(t){return t.kind===I.SELECTOR&&t.value.startsWith(".")}function Pt(t){return t.kind!==I.SELECTOR?0:!t.value.startsWith("#")&&!t.value.startsWith(".")}function Vt(t){if(t.kind!==I.OPERATOR)return 0;const e=t.value.toLowerCase();return!O.has(e)&&!$.has(e)}function Bt(t){const e=t.value.toLowerCase();return"then"===e||"and"===e||"else"===e||"end"===e||"on"===e}function Ft(t,e,r){return{type:"literal",value:t,raw:e,start:r.start,end:r.end,line:r.line,column:r.column}}function _t(t,e){return{type:"identifier",name:t,start:e.start,end:e.end,line:e.line,column:e.column}}function qt(t,e,r,n){return{type:"binaryExpression",operator:t,left:e,right:r,start:n.start,end:n.end,line:n.line,column:n.column}}function Ht(t,e){return{type:"block",commands:t,start:e.start,end:e.end,line:e.line,column:e.column}}function Ut(t,e){return{type:"string",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}function Wt(t,e){return{type:"objectLiteral",properties:t,start:e.start,end:e.end,line:e.line,column:e.column}}function zt(t,e){return{type:"arrayLiteral",elements:t,start:e.start,end:e.end,line:e.line,column:e.column}}function Jt(t,e,r){return{type:"command",name:"__ERROR__",args:[],diagnostics:[{message:e,severity:"error",code:"parse-error",line:t.line,column:t.column,...r&&{source:r}}],start:t.start,end:t.end,line:t.line,column:t.column}}mt.SKIP_SEMANTIC_COMMANDS=new Set(["swap","morph","js","tell"]);const Zt=[{command:"append",keywords:["to"],syntax:"append <value> [to <target>]"},{command:"make",keywords:["a","an"],syntax:"make (a|an) <type>"},{command:"send",keywords:["to"],syntax:"send <event> to <target>"},{command:"throw",keywords:[],syntax:"throw <error>"}];function Gt(t,e){return t?e.some(e=>t.value===e||t.value.toLowerCase()===e):0}const Xt=[t,n,e,r];function Yt(t,e=[]){if(t.isAtEnd())return 1;for(const e of Xt)if(t.check(e))return 1;for(const r of e)if(t.check(r))return 1;return t.checkIsCommand()?1:0}function Kt(t,e=[]){if(!Yt(t,e))return t.parseExpression()}function Qt(t,e,r){return t.check(e)?(t.advance(),r.push(t.createIdentifier(e)),1):0}function te(t,e,r){for(const n of e)if(t.check(n))return t.advance(),r.push(t.createIdentifier(n)),n;return null}function ee(t,e){return t.check(e)?(t.advance(),1):0}class re{constructor(t){this.args=[],this.isBlocking=0,this.name=t}static from(t){const e=new re(t.value);return e.startPos={start:t.start??0,end:t.end??0,line:t.line??1,column:t.column??1},e}static fromIdentifier(t){const e=new re(t.name);return void 0!==t.start&&(e.startPos={start:t.start,end:t.end??0,line:t.line??1,column:t.column??1}),e}static named(t){return new re(t)}withArgs(...t){return this.args.push(...t),this}withBody(t){return this.body=t,this}withImplicitTarget(t){return this.implicitTarget=t,this}withModifier(t,e){return this.modifiers||(this.modifiers={}),this.modifiers[t]=e,this}withModifiers(t){return this.modifiers={...this.modifiers,...t},this}withName(t){return this.name=t,this}withOriginalCommand(t){return this.originalCmd=t,this}blocking(t=1){return this.isBlocking=t,this}startingAt(t){return this.startPos={start:t.start??0,end:t.end??0,line:t.line??1,column:t.column??1},this}endingAt(t){return this.endPos={start:t.start??this.startPos?.start??0,end:t.end,line:t.line??this.startPos?.line??1,column:t.column??this.startPos?.column??1},this}build(){const t={type:"command",name:this.name,args:this.args,isBlocking:this.isBlocking,start:this.startPos?.start??0,end:this.endPos?.end??this.startPos?.end??0,line:this.startPos?.line??1,column:this.startPos?.column??1};return this.body&&(t.body=this.body),this.implicitTarget&&(t.implicitTarget=this.implicitTarget),this.modifiers&&(t.modifiers=this.modifiers),this.originalCmd&&(t.originalCommand=this.originalCmd),t}clone(){const t=new re(this.name);return t.args=[...this.args],t.body=this.body?[...this.body]:void 0,t.implicitTarget=this.implicitTarget,t.isBlocking=this.isBlocking,t.modifiers=this.modifiers?{...this.modifiers}:void 0,t.originalCmd=this.originalCmd,t.startPos=this.startPos?{...this.startPos}:void 0,t.endPos=this.endPos?{...this.endPos}:void 0,t}}function ne(t,e){const r=[];let n="";const s=t.peek().start||0,i=t.peek().line||1,o=t.peek().column||1;if(t.checkIdentifierLike()){for(n=t.advance().value;t.check(":")&&!t.isAtEnd();)t.advance(),n+=":",t.checkIdentifierLike()&&(n+=t.advance().value);if(t.check("(")){t.advance();const e=[];for(;!t.isAtEnd()&&!t.check(")");){const r=t.savePosition();let n;if(t.checkIdentifierLike()){const e=t.peek().value;t.advance(),t.check(":")?(t.advance(),n=e):t.restorePosition(r)}const s=t.parseExpression();if(e.push(void 0!==n?{type:"objectLiteral",properties:[{key:{type:"identifier",name:n},value:s}],start:s.start,end:s.end,line:s.line,column:s.column}:s),t.check(","))t.advance();else if(!t.check(")"))break}t.check(")")&&t.advance(),r.push({type:"functionCall",name:n,args:e,start:s,end:t.getPosition().end,line:i,column:o})}else r.push({type:"string",value:n,start:s,end:t.getPosition().end,line:i,column:o})}for(;!Yt(t);)r.push(t.parsePrimary());let a=-1,c="on";for(let t=0;r.length>t;t++){const e=r[t],n=e.name||e.value;if(!("identifier"!==e.type&&"literal"!==e.type&&"keyword"!==e.type||"on"!==n&&"to"!==n)){a=t,c=n;break}}const l=[];if(-1===a)l.push(...r);else{const e=r.slice(0,a),n=r.slice(a+1);l.push(...e),l.push(t.createIdentifier(c)),l.push(...n)}return re.fromIdentifier(e).withArgs(...l).endingAt(t.getPosition()).build()}function se(t,e){const r=[];if(t.check(b)){const e=t.advance();if(r.push({type:"identifier",name:b,start:e.start,end:e.end,line:e.line,column:e.column}),t.check(y)){const e=t.advance();r.push({type:"identifier",name:y,start:e.start,end:e.end,line:e.line,column:e.column})}}return re.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}function ie(n,s){const i=[];let o=0;const a=n.savePosition();for(let e=0;500>e&&!n.isAtEnd();e++){const e=n.peek();if(e.value===t){o=1;break}if(e.value===r||e.value===v||"def"===e.value||e.value===m)break;n.advance()}n.restorePosition(a);let c=0;if(!o){const t=n.savePosition(),i=s.line,o=100;for(;!n.isAtEnd()&&o>n.current-t;){const t=n.peek(),s=t.value?.toLowerCase();if(s===v||"def"===s||s===m)break;if(s===e||s===r){t.line===i&&(c=1);break}if((n.checkIsCommand()||n.isCommand(s))&&void 0!==t.line&&t.line!==i){c=1;break}n.advance()}n.restorePosition(t)}const l=o||c;let u;if(l)u=n.parseExpression();else{const e=[],r=20;let i=0;for(;!n.isAtEnd()&&!n.checkIsCommand()&&!n.isCommand(n.peek().value)&&!n.check(t)&&r>i;){const t=n.savePosition();e.push(n.parseLogicalAnd()),n.savePosition()===t&&n.advance(),i++}if(0===e.length)throw Error("Expected condition after if/unless");u=1===e.length?e[0]:{type:"expression",tokens:e,start:e[0].start,end:e[e.length-1].end,line:s.line,column:s.column}}if(i.push(u),l){o&&n.advance();const t=[];for(;!n.isAtEnd()&&!n.check(e)&&!n.check(r)&&(n.checkIsCommand()||n.isCommand(n.peek().value));){n.advance();const e=n.parseCommand();e&&t.push(e)}if(0===t.length&&n.isAtEnd())throw Error("Expected command after 'then' in if statement - incomplete conditional");i.push(Ht(t,{start:s.start,end:n.getPosition().end,line:s.line,column:s.column}));let a=0;if(n.check(e))if(n.advance(),n.check("if")){const t=n.peek();n.advance();const e=ie(n,t);i.push(Ht([e],{start:t.start,end:n.getPosition().end,line:t.line,column:t.column})),a=1}else{const t=[];for(;!n.isAtEnd()&&!n.check(r)&&(n.checkIsCommand()||n.isCommand(n.peek().value));){n.advance();const e=n.parseCommand();e&&t.push(e)}i.push(Ht(t,{start:s.start,end:n.getPosition().end,line:s.line,column:s.column}))}a||n.consume(r,"Expected 'end' after if block")}else{if(!n.checkIsCommand()&&!n.isCommand(n.peek().value))throw Error("Expected command after if condition in single-line form");{n.advance();const t=n.parseCommand();i.push(Ht([t],{start:s.start,end:n.getPosition().end,line:s.line,column:s.column}))}}return re.from(s).withArgs(...i).endingAt(n.getPosition()).build()}function oe(t,e){const r=[],n={};if(t.checkAnySelector()||t.checkContextVar()||t.match("<")){const e=t.parsePrimary();if(r.push(e),t.match("*")){if(t.checkIdentifierLike()){const e=t.advance();r.push({type:"identifier",name:"*"+e.value,start:e.start-1,end:e.end,line:e.line,column:e.column})}}else if(t.checkIdentifierLike()){const e=t.parsePrimary();r.push(e)}}else if(t.checkIdentifierLike()){const e=t.parsePrimary();r.push(e)}if(t.match("and")&&t.match("set")&&t.checkIdentifierLike()){const e=t.advance();n.set={type:"identifier",name:e.value,start:e.start,end:e.end,line:e.line,column:e.column}}const s=re.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition());return Object.keys(n).length>0&&s.withModifiers(n),s.build()}function ae(t,e){const r=[],n=Kt(t,[f]);n&&r.push(n),Qt(t,f,r);const s=Kt(t);return s&&r.push(s),re.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}function ce(t,e){const r=[];if(t.check("between")){t.advance(),r.push(t.createIdentifier("between"));const i=Kt(t,[n]);i&&r.push(i),Qt(t,n,r);const o=Kt(t,[f,m,s]);if(o&&r.push(o),te(t,[f,m],r)){const e=Kt(t);e&&r.push(e)}return re.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}const i=Kt(t,[f,m]);if(i&&r.push(i),te(t,[f,m],r)){const e=Kt(t);e&&r.push(e)}return re.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}function le(t,e){const n=t.parseExpression();if(!n)return t.addError("Put command requires content expression"),null;const s=t.peek();if(!s||!S.includes(s.value))return t.addError(`Expected operation keyword (${S.join(", ")}) after put expression, got: ${s?.value}`),null;let i=t.advance().value;const o=i.toLowerCase();"at start of"===o||"at the start of"===o?i=k:"at end of"===o||"at the end of"===o?i=A:"at"===i&&(t.check(E)||t.check(b)?(ee(t,b),t.check(E)&&(t.advance(),t.check(p)&&(t.advance(),i=k))):t.check(r)&&(t.advance(),t.check(p)&&(t.advance(),i=A)));const a=t.parseExpression();return a?re.fromIdentifier(e).withArgs(n,t.createIdentifier(i),a).endingAt(t.getPosition()).build():(t.addError("Put command requires target expression after operation keyword"),null)}const ue=["innerhtml","outerhtml","into","over","delete","morph","morphouter"];function he(s,i){const o=s.savePosition();let a=null,c=[];try{a=function(t){if(!t.check(":"))return null;if(t.advance(),t.check(":")){t.advance();const e=t.advance();return{type:"identifier",name:e.value,scope:"global",start:e.start-2,end:e.end}}const e=t.advance();return{type:"identifier",name:e.value,scope:"local",start:e.start-1,end:e.end}}(s)??function(t){if(!t.check(g)&&!t.check("local"))return null;const e=t.advance(),r=t.advance();return{type:"identifier",name:r.value,scope:e.value,start:e.start,end:r.end}}(s)??function(t,e){if(!t.check(b))return null;const r=t.savePosition();t.advance();const n=t.peek(),s=t.peekAt(1);if(n&&s&&s.value===p){const r=t.advance();if(t.check(p)){t.advance();const n=t.advance(),s=n.value.startsWith("#");return{type:"propertyOfExpression",property:{type:"identifier",name:r.value,start:r.start,end:r.end},target:{type:s?"idSelector":"cssSelector",value:n.value,start:n.start,end:n.end},start:e,end:t.savePosition()}}return t.restorePosition(e),null}if(n&&s&&s.value===h){const e=t.advance();return{type:"identifier",name:e.value,start:e.start,end:e.end}}return t.restorePosition(r),null}(s,o),a||(a=s.parseExpression())}catch{s.restorePosition(o),a=null}if(!a){const i=function(s){if(s.match(":")){const t=s.advance();return{expression:{type:"identifier",name:t.value,scope:"local",start:t.start,end:t.end},tokens:[]}}const i=[];for(;!(s.isAtEnd()||s.check(h)||s.check(t)||s.check(n)||s.check(e)||s.check(r));)i.push(s.parsePrimary());if(0===i.length)return{expression:null,tokens:[]};if(i.length>=4){const t=(t,e)=>t[e];if(t(i[0],"value")===b&&t(i[2],"value")===p){const e=i[1],r=i[3];return{expression:(o=_t(t(e,"value")||t(e,"name")||"",{start:e.start??0,end:e.end??0,line:e.line??1,column:e.column??1}),a={type:"idSelector"===r.type?"idSelector":"cssSelector",value:t(r,"value")||t(r,"name")||"",start:r.start??0,end:r.end??0,line:r.line,column:r.column},c={start:i[0].start??0,end:r.end??0,line:i[0].line??1,column:i[0].column??1},{type:"propertyOfExpression",property:o,target:a,start:c.start,end:c.end,line:c.line,column:c.column}),tokens:[]}}}var o,a,c;return 1===i.length?{expression:i[0],tokens:[]}:{expression:null,tokens:i}}(s);a=i.expression,c=i.tokens}if(!s.check(h)){const t=s.isAtEnd()?"end of input":s.peek().value;throw Error("Expected 'to' in set command, found: "+t)}s.advance();const l=s.parseExpression()??s.parsePrimary(),u=[];return a?u.push(a):c.length>0&&u.push(...c),u.push(s.createIdentifier(h)),l&&u.push(l),re.fromIdentifier(i).withArgs(...u).endingAt(s.getPosition()).build()}function fe(t,e){const r=[];for(;!Yt(t,["catch","finally"])&&(t.checkIdentifierLike()||t.checkSelector()||t.checkLiteral()||t.checkTimeExpression()||t.match("<"));)r.push(t.parsePrimary());return re.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}function de(t){if(t.isAtEnd())return 1;const e=t.peek().value;return["as","with","{","then","end","else","otherwise",")"].includes(e)||Yt(t)}function pe(t){if(t.check("{"))return 0;if(!t.checkIdentifierLike())return 0;const e=t.peekAt(1);return null!==e&&":"===e.value}function me(t){const e=[],r=t.getPosition();do{if(!t.checkIdentifierLike())break;const r=t.advance(),n={type:"identifier",name:r.value,start:r.start,end:r.end,line:r.line,column:r.column};t.consume(":","Expected ':' after property name in fetch named arguments");const s=t.parsePrimary();s&&e.push({key:n,value:s})}while(t.match(",")&&!t.isAtEnd());const n=t.getPosition();return{type:"objectLiteral",properties:e,start:r.start,end:n.end,line:r.line,column:r.column}}const ye=new Set(["then","end","to","into","on","with","from","in","by","for","while","until","unless","else","catch","finally"]),ve=new Set([")","]","}",","]);function ge(...t){const e=new Map;for(const r of t)for(const[t,n]of r){const r=e.get(t);e.set(t,r?{prefix:n.prefix??r.prefix,infix:n.infix??r.infix}:{...n})}return e}function be(t,e){return{infix:{bp:[t,t+1],handler:e??((e,r,n)=>({type:"binaryExpression",operator:r.value,left:e,right:n.parseExpr(t+1),start:e.start}))}}}function Ee(t,e){return{infix:{bp:[t+1,t],handler:(e,r,n)=>({type:"binaryExpression",operator:r.value,left:e,right:n.parseExpr(t),start:e.start})}}}function we(t,e){return{prefix:{bp:t,handler:e??((e,r)=>({type:"unaryExpression",operator:e.value,operand:r.parseExpr(t),start:e.start}))}}}const xe=new Map([["or",be(10)],["||",be(10)],["and",be(20)],["&&",be(20)],["==",be(30)],["!=",be(30)],["<",be(30)],[">",be(30)],["<=",be(30)],[">=",be(30)],["is",be(30)],["matches",be(30)],["contains",be(30)],["+",{...be(40),...we(80)}],["-",{...be(40),...we(80)}],["*",be(50)],["/",be(50)],["%",be(50)],["mod",be(50)],["^",Ee(60)],["**",Ee(60)],["as",be(70,(t,e,r)=>({type:"asExpression",expression:t,targetType:r.parseExpr(71),start:t.start}))],["not",we(80)],["!",we(80)],["no",we(80)]]),ke=new Map([["first",we(85,(t,e)=>({type:"positionalExpression",position:"first",operand:e.parseExpr(85),start:t.start}))],["last",we(85,(t,e)=>({type:"positionalExpression",position:"last",operand:e.parseExpr(85),start:t.start}))]]),Ae=new Map([[".",{infix:{bp:[90,91],handler:(t,e,r)=>({type:"propertyAccess",object:t,property:r.advance().value,start:t.start})}}],["?.",{infix:{bp:[90,91],handler:(t,e,r)=>({type:"optionalChain",object:t,property:r.advance().value,start:t.start})}}],["'s",{infix:{bp:[95,96],handler:(t,e,r)=>({type:"possessiveExpression",object:t,property:r.advance().value,start:t.start})}}]]),Se=new Map([["===",be(30)],["!==",be(30)],["is not",be(30)],["is a",be(30)],["is an",be(30)],["is not a",be(30)],["is not an",be(30)],["is in",be(30)],["is not in",be(30)],["has",be(30)],["have",be(30)],["match",be(30)],["include",be(30)],["includes",be(30)],["equals",be(30)],["does not contain",be(30)],["does not include",be(30)],["in",be(30)],["of",be(30)],["really",be(30)],["exists",{prefix:{bp:80,handler:(t,e)=>({type:"unaryExpression",operator:t.value,operand:e.parseExpr(80),start:t.start})},infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:0,start:t.start})}}],["does not exist",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:0,start:t.start})}}],["is empty",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:0,start:t.start})}}],["is not empty",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:0,start:t.start})}}],["some",we(80)]]),Ce=new Map([["=",Ee(5)]]);ge(xe,ke,Ae);const Ne=ge(xe,Se,Ce);class Te{constructor(t,e,r){this.current=0,this.errors=[],this.warnings=[],this.prattCache=new Map,this.tokens=t,this.keywordResolver=e?.keywords,this.registryIntegration=e?.registryIntegration,e?.semanticAnalyzer&&e?.language&&(this.semanticAdapter=new mt({analyzer:e.semanticAnalyzer,language:e.language,confidenceThreshold:e.semanticConfidenceThreshold??.5})),this.originalInput=r||t.map(t=>t.value).join(" ")}resolveKeyword(t){return this.keywordResolver?this.keywordResolver.resolve(t)??t:t}addWarning(t){this.warnings.push(t)}parse(){this.prattCache.clear();const t=this.parseInternal();return this.errors.length>0&&(t.errors=[...this.errors]),t}parseInternal(){try{if(0===this.tokens.length)return this.addError("Cannot parse empty input"),{success:0,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings};if(this.check("behavior")){const t=[];for(;this.check("behavior");){this.advance();const e=this.parseBehaviorDefinition();if(e&&t.push(e),this.error)break}return this.error?{success:0,node:1===t.length?t[0]:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:1,node:1===t.length?t[0]:this.createProgramNode(t),tokens:this.tokens,warnings:this.warnings}}if(this.check("init")||this.check("on")||this.check("def")||this.checkComment()){const t=[];for(;!this.isAtEnd();)if(this.checkComment())this.advance();else if(this.check("init")){this.advance();const e=this.parseTopLevelInitBlock();e&&t.push(e)}else if(this.check("on")){this.advance();const e=this.parseEventHandler();e&&t.push(e)}else{if(!this.check("def"))break;{this.advance();const e=this.parseDefFeature();e&&t.push(e)}}return this.isAtEnd()?this.error?{success:0,node:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:1,node:this.createProgramNode(t),tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:0,node:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings})}if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){const t=this.parseCommandSequence();if(t){if(!this.isAtEnd()&&this.check("on")){lt("✅ PARSER: Found event handlers after command sequence, parsing as program");const e=[t];lt(`✅ PARSER: Starting with ${e.length} statement(s) from command sequence`);let r=0;for(;!this.isAtEnd()&&this.check("on");){lt(`✅ PARSER: Parsing event handler #${r+1}, current token: ${this.peek().value}`),this.advance();const t=this.parseEventHandler();if(lt("✅ PARSER: parseEventHandler returned:",t?`type=${t.type}, event=${t.event}`:"null"),t&&(e.push(t),r++,lt(`✅ PARSER: Added event handler, now have ${e.length} statements total`)),lt(`✅ PARSER: After parsing event handler, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd=${this.isAtEnd()}, check('on')=${this.check("on")}`),!this.isAtEnd()&&!this.check("on")){if(!this.isAtEnd())return lt("⚠️ PARSER: Unexpected token after event handlers: "+this.peek().value),this.addError("Unexpected token after event handlers: "+this.peek().value),{success:0,node:this.createProgramNode(e),tokens:this.tokens,error:this.error};lt("✅ PARSER: No more event handlers, at end of input");break}}return lt(`✅ PARSER: Finished parsing, creating Program node with ${e.length} statements`),this.error?{success:0,node:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:1,node:this.createProgramNode(e),tokens:this.tokens,warnings:this.warnings}}return this.isAtEnd()?this.error?{success:0,node:t,tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:1,node:t,tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:0,node:t||this.createErrorNode(),tokens:this.tokens,error:this.error})}}const t=this.parseExpression();return this.error?{success:0,node:t||this.createErrorNode(),tokens:this.tokens,error:this.error}:this.isAtEnd()?{success:1,node:t,tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:0,node:t||this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings})}catch(t){return this.addError(t instanceof Error?t.message:"Unknown parsing error"),{success:0,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}}parseExpression(){return this.parseExpressionPratt(0)}parseExpressionPratt(t){const e=`${this.current}:${t}`,r=this.prattCache.get(e);if(r)return this.current=r.endPos,r.node;if(this.isAtEnd())return this.addError("Unexpected end of expression"),this.createErrorNode();const n=this.peek(),s=Te.PRATT_TABLE.get(n.value);let i;if(s?.prefix){const t=this.advance();if(this.isAtEnd())return this.addError(`Expected expression after '${t.value}' operator`),this.createErrorNode();i=s.prefix.handler(t,this.makePrattContext())}else i=this.parseCall();for(;!this.isAtEnd();){const e=this.peek(),r=Te.PRATT_TABLE.get(e.value);if(!r?.infix){if(ye.has(e.value)||ve.has(e.value))break;break}const[n]=r.infix.bp;if(t>n)break;if("="===e.value&&this.tokens.length>this.current+1&&">"===this.tokens[this.current+1].value){if(this.advance(),this.advance(),this.addError('Arrow functions (=>) are not supported in hyperscript. Use "js ... end" blocks for JavaScript callbacks.'),!this.isAtEnd())try{this.parseExpressionPratt(0)}catch{}return this.createErrorNode()}if("+"===e.value||"-"===e.value){const t=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(t&&("+"===t.value||"-"===t.value))return this.addError(`Invalid operator combination: ${e.value}${t.value}`),i}if("*"===e.value||"/"===e.value||"%"===e.value){const t=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(t&&("*"===t.value||"/"===t.value||"%"===t.value||"+"===t.value||"-"===t.value))return this.addError("*"===e.value&&"*"===t.value?"Unexpected token: "+t.value:`Invalid operator combination: ${e.value}${t.value}`),i}const s=this.advance();if(this.isAtEnd()&&!Te.POSTFIX_UNARY_OPERATORS.has(s.value))return this.addError(`Expected expression after '${s.value}' operator`),i;i=r.infix.handler(i,s,this.makePrattContext())}return this.prattCache.set(e,{node:i,endPos:this.current}),i}makePrattContext(){const t=this;return{peek:()=>t.tokens.length>t.current?t.tokens[t.current]:void 0,advance:()=>{const e=t.tokens[t.current];return t.current++,e},parseExpr:e=>t.parseExpressionPratt(e),isStopToken:()=>{const e=t.tokens[t.current];return e?ye.has(e.value)||ve.has(e.value):1},atEnd:()=>t.current>=t.tokens.length}}parseAssignment(){let t=this.parseLogicalOr();if(this.match("=")){if(this.check(">")){if(this.advance(),this.addError('Arrow functions (=>) are not supported in hyperscript. Use "js ... end" blocks for JavaScript callbacks.'),!this.isAtEnd())try{this.parseExpression()}catch{}return this.createErrorNode()}const e=this.previous().value,r=this.parseAssignment();t=this.createBinaryExpression(e,t,r)}return t}parseLogicalOr(){let t=this.parseLogicalAnd();for(;this.match("or");){const e=this.previous().value,r=this.parseLogicalAnd();t=this.createBinaryExpression(e,t,r)}return t}parseLogicalAnd(){let t=this.parseEquality();for(;this.match("and");){const e=this.previous().value,r=this.parseEquality();t=this.createBinaryExpression(e,t,r)}return t}parseEquality(){let t=this.parseComparison();for(;this.matchComparisonOperator()||this.match("is","match","matches","contains","include","includes","in","of","as","really");){const e=this.previous().value;if(Te.POSTFIX_UNARY_OPERATORS.has(e)){t=this.createUnaryExpression(e,t,0);continue}const r=this.parseComparison();t=this.createBinaryExpression(e,t,r)}return t}parseComparison(){let t=this.parseAddition();for(;this.matchComparisonOperator();){const e=this.previous().value;if(Te.POSTFIX_UNARY_OPERATORS.has(e)){t=this.createUnaryExpression(e,t,0);continue}const r=this.parseAddition();t=this.createBinaryExpression(e,t,r)}return t}parseAddition(){let t=this.parseMultiplication();for(;this.match("+","-")||this.matchOperator("+")||this.matchOperator("-");){const e=this.previous().value;if(this.check("+")||this.check("-"))return this.addError(`Invalid operator combination: ${e}${this.peek().value}`),t;if(this.isAtEnd())return this.addError(`Expected expression after '${e}' operator`),t;const r=this.parseMultiplication();t=this.createBinaryExpression(e,t,r)}return t}parseMultiplication(){let t=this.parseUnary();for(;this.match("*","/","%","mod");){const e=this.previous().value;if(this.check("*")||this.check("/")||this.check("%")||this.check("+")||this.check("-")){const r=this.peek().value;return this.addError("*"===e&&"*"===r?"Unexpected token: "+r:`Invalid operator combination: ${e}${r}`),t}if(this.isAtEnd())return this.addError(`Expected expression after '${e}' operator`),t;const r=this.parseUnary();t=this.createBinaryExpression(e,t,r)}return t}parseUnary(){if(this.match("not","no","exists","some","-","+")){const t=this.previous().value;if(this.isAtEnd())return this.addError(`Expected expression after '${t}' operator`),this.createErrorNode();const e=this.parseUnary();return this.createUnaryExpression(t,e,1)}if(this.check("does")&&this.tokens.length>this.current+1&&"not"===this.tokens[this.current+1].value&&this.tokens.length>this.current+2&&"exist"===this.tokens[this.current+2].value){if(this.advance(),this.advance(),this.advance(),this.isAtEnd())return this.addError("Expected expression after 'does not exist' operator"),this.createErrorNode();const t=this.parseUnary();return this.createUnaryExpression("does not exist",t,1)}return this.parseImplicitBinary()}parseImplicitBinary(){let t=this.parseCall();for(;!(this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("and")||this.check("else")||this.check(")")||this.check("]")||this.check(","));){if("identifier"!==t.type){if("literal"===t.type&&(this.checkNumber()||this.checkIdentifier())){const e=this.peek();return this.addError(`Missing operator between '${t.raw||t.value}' and '${e.value}'`),t}break}if(this.isCommand(t.name))if(this.isCompoundCommand(t.name.toLowerCase())){if(!(this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkTimeExpression()||this.checkString()||this.checkNumber()||this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()))break;{const e=this.createCommandFromIdentifier(t);e&&(t=e)}}else if("wait"===t.name.toLowerCase()&&this.checkTimeExpression()){const e=this.createCommandFromIdentifier(t);e&&(t=e)}else{if(!this.checkSelector())break;{const e=this.parseCall();t=this.createBinaryExpression(" ",t,e)}}else{if(!this.checkSelector())break;{const e=this.parseCall();t=this.createBinaryExpression(" ",t,e)}}}return t}isCommand(t){return this.keywordResolver?this.keywordResolver.isCommand(t):(t=>w.has(t.toLowerCase()))(t)}isKeyword(t){return this.keywordResolver?this.keywordResolver.isKeyword(t):(t=>C.has(t.toLowerCase()))(t)}createCommandFromIdentifier(t){const e=[],r=this.resolveKeyword(t.name.toLowerCase());if(this.isCompoundCommand(r))return this.parseCompoundCommand(t);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.checkIsCommand())&&(this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()||this.checkEvent()||this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkString()||this.checkNumber()||this.checkTimeExpression()||this.match("<"));)e.push(this.parsePrimary());return{type:"command",name:t.name,args:e,isBlocking:0,...void 0!==t.start&&{start:t.start},end:this.getPosition().end,...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}}}isCompoundCommand(t){return x.has(t.toLowerCase())}parseCompoundCommand(s){return function(s,i){switch(i.name.toLowerCase()){case"put":return le(s,i);case"trigger":case"send":return ne(s,i);case"remove":return ae(s,i);case"toggle":return ce(s,i);case"set":return he(s,i);case"halt":return se(s,i);case"measure":return oe(s,i);case"js":return function(t,e){const n=[];if(t.match("(")){for(;!t.check(")")&&!t.isAtEnd();)t.checkIdentifierLike()&&n.push(t.advance().value),t.match(",");t.consume(")","Expected ) after js parameters")}const s=t.peek().start;for(;!t.check(r)&&!t.isAtEnd();)t.advance();const i=t.peek().start;t.consume(r,"Expected end after js code body");const o={type:"literal",value:t.getInputSlice(s,i).trim(),start:e.start,end:t.getPosition().end},a={type:"arrayLiteral",elements:n.map(t=>({type:"literal",value:t,start:e.start,end:e.end})),start:e.start,end:t.getPosition().end};return re.fromIdentifier(e).withArgs(o,a).endingAt(t.getPosition()).build()}(s,i);case"tell":return function(s,i){const o=s.parseExpression();if(!o)throw Error("tell command requires a target expression");const a=[];for(;!s.isAtEnd();){if(s.checkIsCommand()){try{s.advance();const t=s.parseCommand();if(!t)break;a.push(t)}catch{break}if(s.match(n))continue;if(s.check(t)||s.check(e)||s.check(r))break;if(s.checkIsCommand())continue;break}break}if(0===a.length)throw Error("tell command requires at least one command after the target");return re.fromIdentifier(i).withArgs(o,...a).endingAt(s.getPosition()).build()}(s,i);case"swap":case"morph":return function(t,e){console.log("[PARSER DEBUG] parseSwapCommand called");const r=[];let n=null;if(!t.isAtEnd()){const e=t.peek();if(e&&e.value){const s=e.value.toLowerCase();ue.includes(s)&&(n=s,t.advance(),r.push(t.createIdentifier(n)))}}if("delete"===n){const n=t.parseExpression();return n&&r.push(n),re.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}!t.isAtEnd()&&t.check(p)&&(t.advance(),r.push(t.createIdentifier("of")));const s=t.parseExpression();if(s&&r.push(s),!t.isAtEnd()&&t.check(d)){t.advance(),r.push(t.createIdentifier("with"));const e=t.parseExpression();e&&r.push(e)}return re.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}(s,i);default:return fe(s,i)}}(this.getContext(),s)}parsePutCommand(t){return le(this.getContext(),t)}parseSetCommand(t){return he(this.getContext(),t)}parseHaltCommand(t){return se(this.getContext(),t)}parseMeasureCommand(t){return oe(this.getContext(),t)}parseTriggerCommand(t){return ne(this.getContext(),t)}parseCommandListUntilEnd(){const t=[];for(lt("🔄 parseCommandListUntilEnd: Starting to parse command list");!this.isAtEnd()&&!this.check("end");){lt("📍 Loop iteration, current token:",this.peek().value,"kind:",this.peek().kind);let e=0;const r=this.checkIsCommand(),n=!r&&this.checkIdentifier()&&this.isCommand(this.peek().value);if(r||n){lt(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&&(lt("⚠️ parseCommandListUntilEnd: Command parsing added error, restoring error state. Error was:",this.error.message),this.error=n),r&&(lt("✅ Parsed command:",r.name),t.push(r),e=1)}catch(t){lt("⚠️ parseCommandListUntilEnd: Command parsing threw exception, restoring error state:",t instanceof Error?t.message:t+""),this.error=n}}else this.checkIdentifier()&&lt("❌ IDENTIFIER is not a command:",this.peek().value);if(!e){lt("❌ No command parsed, breaking. Current token:",this.peek().value);break}for(lt("📍 After parsing command, current token:",this.peek().value);!(this.isAtEnd()||this.check("end")||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(","));)lt("⚠️ Skipping unexpected token:",this.peek().value),this.advance();if(this.match("then","and",","))lt("✅ Found separator, continuing");else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){lt("📍 No separator and no command, breaking. Current token:",this.peek().value);break}lt("✅ Next token is a command, continuing without separator")}}if(lt('🔍 After loop, checking for "end". Current token:',this.peek().value),!this.check("end"))throw lt('❌ ERROR: Expected "end" but got:',this.peek().value,"at position:",this.peek().start),Error('Expected "end" to close repeat block');return lt('✅ Found "end", consuming it'),this.advance(),lt("✅ parseCommandListUntilEnd: Successfully parsed",t.length,"commands"),t}parseRepeatCommand(t){return function(t,e){const r=[];let n="forever",h=null,p=null,m=null,v=null,g=null,E=null;if(t.check(s)){t.advance(),n=s;const e=t.peek();wt(e)&&(g=e.value,t.advance()),t.check(u)&&(t.advance(),v=t.parseExpression())}else if(t.check(u))t.advance(),n=s,g="it",v=t.parseExpression();else if(t.check(i))t.advance(),n=i,m=t.parseExpression();else if(t.check(o))if(t.advance(),n=o,t.check(y)){t.advance(),n="until-event";const e=t.peek();if(lt("📍 Parsing event name, current token:",{value:e.value,kind:e.kind}),!wt(e)&&!gt(e))throw Error('Expected event name after "event"');if(h=e.value,t.advance(),lt("✅ Got event name:",h,"Next token:",t.peek().value),lt('🔍 Checking for "from", current token:',t.peek().value),t.check(f)){lt('✅ Found "from", advancing...'),t.advance(),lt('📍 After consuming "from", current token:',t.peek().value),ee(t,b)&&lt('✅ Found "the", advancing...');const e=t.peek();lt("🔍 Before parsePrimary for event target:",{value:e.value,kind:e.kind,position:e.start}),p=t.parsePrimary(),lt("✅ After parsePrimary, eventTarget:",p)}else lt('❌ No "from" found, skipping target parsing')}else m=t.parseExpression();else t.check(a)?(t.advance(),n=a):(E=t.parseExpression(),t.check(c)&&(t.advance(),n=c));let w=null;if(t.check(d)){const e=t.peekAt(1);e&&e.value.toLowerCase()===l&&(t.advance(),t.advance(),w=l)}else if(t.check(l)){t.advance();const e=t.peek();wt(e)?(w=e.value,t.advance()):w=l}const x=t.parseCommandListUntilEnd();r.push({type:"identifier",name:n,start:e.start,end:e.end,line:e.line,column:e.column});const k={start:e.start,end:e.end,line:e.line,column:e.column};return g&&r.push(Ut(g,k)),v&&r.push(v),m&&r.push(m),E&&r.push(E),h&&r.push(Ut(h,k)),p&&r.push(p),w&&r.push(Ut(w,k)),r.push(Ht(x,{...k,end:k.end||0})),re.from(e).withArgs(...r).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseForCommand(t){return function(t,e){const r=[];let n=null,s=null;t.check("each")&&t.advance();const i=t.peek();if(!wt(i))throw Error('Expected variable name after "for"');if(n=i.value,t.advance(),!t.check(u))throw Error('Expected "in" after variable name in for loop');if(t.advance(),s=t.parseExpression(),!s)throw Error('Expected collection expression after "in"');let o=null;if(t.check(d)){const e=t.peekAt(1);e&&e.value.toLowerCase()===l&&(t.advance(),t.advance(),o=l)}else if(t.check(l)){t.advance();const e=t.peek();wt(e)?(o=e.value,t.advance()):o=l}const a=t.parseCommandListUntilEnd();r.push({type:"identifier",name:"for",start:e.start,end:e.end,line:e.line,column:e.column});const c={start:e.start,end:e.end,line:e.line,column:e.column};return r.push(Ut(n,c)),r.push(s),o&&r.push(Ut(o,c)),r.push(Ht(a,{...c,end:c.end||0})),re.from({...e,value:"repeat"}).withArgs(...r).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseWaitCommand(t){return function(t,e){const r=[];if(t.checkTimeExpression()||t.checkLiteral()){const n=t.parsePrimary();return r.push(n),re.from(e).withArgs(...r).blocking().endingAt(t.getPosition()).build()}if(t.check("for")){t.advance();const n=[];do{const e=t.peek();if(!wt(e))throw Error('Expected event name after "for"');const r=e.value;t.advance();const s=[];if(t.check("(")){for(t.advance();!t.isAtEnd()&&!t.check(")");){const e=t.peek();if(!wt(e))break;s.push(e.value),t.advance(),t.check(",")&&t.advance()}if(!t.check(")"))throw Error('Expected ")" after event parameters');t.advance()}if(n.push({name:r,params:s}),!t.check("or"))break;t.advance()}while(!t.isAtEnd());let s=null;t.check(f)&&(t.advance(),ee(t,b),s=t.parsePrimary());const i={start:e.start,end:t.getPosition().end,line:e.line,column:e.column};r.push(zt(n.map(t=>Wt([{key:_t("name",i),value:Ft(t.name,`"${t.name}"`,i)},{key:_t("args",i),value:zt(t.params.map(t=>Ft(t,`"${t}"`,i)),i)}],i)),i)),s&&r.push(s)}return re.from(e).withArgs(...r).blocking().endingAt(t.getPosition()).build()}(this.getContext(),t)}parseInstallCommand(t){return function(t,e){const r=[];if(!t.checkIdentifierLike())throw Error('Expected behavior name after "install"');const n=t.advance().value,s=t.previous();if(r.push(_t(n,{start:s.start,end:s.end,line:s.line,column:s.column})),t.check("(")){t.advance();const n=[];for(;!t.isAtEnd()&&!t.check(")");){const e=t.savePosition();let r;if(t.checkIdentifierLike()){const n=t.peek().value;t.advance(),t.check(":")?(t.advance(),r=n):t.restorePosition(e)}const s=t.parseExpression();if(n.push(void 0!==r?{name:r,value:s}:{value:s}),t.check(","))t.advance();else if(!t.check(")"))break}if(!t.check(")"))throw Error('Expected ")" after behavior parameters');if(t.advance(),n.length>0){const s={start:e.start,end:t.getPosition().end,line:e.line,column:e.column};r.push(Wt(n.map(t=>({key:t.name?_t(t.name,s):Ft("_positional","_positional",s),value:t.value})),s))}}return re.from(e).withArgs(...r).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseTransitionCommand(t){return function(t,e){const r=[],n={};let s=null;const i=t.peek();if(wt(i)||"*"===i.value){let e="";t.check("*")&&(e="*",t.advance());const r=function(t){if(!t.checkIdentifierLike())return"";let e=t.advance().value;for(;t.check("-")&&!t.isAtEnd();)e+="-",t.advance(),t.checkIdentifierLike()&&(e+=t.advance().value);return e}(t);r&&(e+=r,s={type:"string",value:e,start:i.start||0,end:t.getPosition().end,line:i.line,column:i.column})}if(!s)throw Error("Transition command requires a CSS property");if(r.push(s),!t.check(h))throw Error('Expected "to" keyword after property in transition command');t.advance();const o=t.parsePrimary();if(n.to=o,t.check("over")){t.advance();const e=t.parsePrimary();n.over=e}if(t.check(d)){t.advance();const e=t.parsePrimary();n.with=e}return re.from(e).withArgs(...r).withModifiers(n).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseAddCommand(t){return function(t,e){const r=[];if(t.match("{"))r.push(t.parseCSSObjectLiteral());else{const e=Kt(t,[h]);e&&r.push(e)}if(t.check(h)){t.advance();const e=Kt(t);e&&r.push(e)}return re.from(e).withArgs(...r).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseIfCommand(t){return ie(this.getContext(),t)}parseRemoveCommand(t){return ae(this.getContext(),t)}parseToggleCommand(t){return ce(this.getContext(),t)}parseRegularCommand(t){return fe(this.getContext(),t)}parseCall(){let t=this.parsePrimary();for(;;)if(this.match("("))t=this.finishCall(t);else if(this.match(".")){const e=this.consumeIdentifier("Expected property name after '.' - malformed member access");t=this.createMemberExpression(t,this.createIdentifier(e.value),0)}else if(this.match("[")){const e=this.parseExpression();this.consume("]","Expected ']' after array index"),t=this.createMemberExpression(t,e,1)}else{if(!this.check("'s"))break;{let e;this.advance(),this.check("*")?(this.advance(),e="*"+this.consumeIdentifier("Expected property name after * in CSS property syntax").value):e=Nt(this.peek())&&this.peek().value.startsWith("@")?this.advance().value:this.consumeIdentifier("Expected property name after possessive").value,t=this.createPossessiveExpression(t,this.createIdentifier(e))}}return t}parsePrimary(){if(this.check("*")){const t=this.current;if(this.advance(),!this.isAtEnd()&&wt(this.peek())){const t=this.advance().value;return this.createSelector("*"+t)}this.current=t}if(this.check("*")||this.check("/")||this.check("%")||this.check("mod")){const t=this.peek();return this.addError(`Binary operator '${t.value}' requires a left operand`),this.createErrorNode()}if(this.matchNumber()){const t=parseFloat(this.previous().value);return this.createLiteral(t,this.previous().value)}if(this.matchString()){const t=this.previous().value;if(2>t.length||t.startsWith('"')&&!t.endsWith('"')||t.startsWith("'")&&!t.endsWith("'"))return this.addError("Unclosed string literal - string not properly closed"),this.createErrorNode();const e=t.slice(1,-1),r=this.processEscapeSequences(e);return this.createLiteral(r,t)}if(this.matchTemplateLiteral()){const t=this.previous();return{type:"templateLiteral",value:t.value,start:t.start||0,end:t.end||0,line:t.line,column:t.column}}if(this.matchBoolean()){const t=this.previous().value;let e;switch(t){case"true":e=1;break;case"false":e=0;break;case"null":e=null;break;case"undefined":e=void 0;break;default:e="true"===t}return this.createLiteral(e,t)}if(this.matchTimeExpression()){const t=this.previous().value;return this.createLiteral(t,t)}if(this.matchQueryReference()){const t=this.previous().value.slice(1,-2).trim();return this.createSelector(t)}if(this.matchSelector())return this.createSelector(this.previous().value);if(this.match("<"))return this.parseHyperscriptSelector();if(this.match("(")){if(this.isAtEnd())return this.addError("Expected expression inside parentheses"),this.createErrorNode();const t=this.parseExpression();return this.consume(")","Expected closing parenthesis ')' after expression - unclosed parentheses"),t}if(this.match("{"))return this.parseObjectLiteral();if(this.match("["))return this.parseAttributeOrArrayLiteral();if(this.check(":")){if(this.advance(),this.check(":")){this.advance();const t=this.advance();return{type:"identifier",name:t.value,scope:"global",start:t.start-2,end:t.end,line:t.line,column:t.column}}{const t=this.advance();return{type:"identifier",name:t.value,scope:"local",start:t.start-1,end:t.end,line:t.line,column:t.column}}}if(this.matchBasicOperator()){const t=this.previous();return this.createIdentifier(t.value)}const t=this.peek();if((!t||"end"!==t.value&&"else"!==t.value&&"then"!==t.value)&&(this.matchPredicate(Ot)||this.matchPredicate(vt)||this.matchPredicate(bt)||this.matchPredicate(yt)||this.matchPredicate(gt))){const t=this.previous();if("new"===t.value)return this.parseConstructorCall();if("on"===t.value)return this.parseEventHandler();if("if"===t.value)return this.parseConditional();if("closest"===t.value||"first"===t.value||"last"===t.value||"previous"===t.value||"next"===t.value){if(this.check("(")||this.checkCssSelector()||this.checkClassSelector()||this.checkIdSelector()||this.check("<")||this.checkQueryReference())return this.parseNavigationFunction(t.value);if(this.check(".")){const e=this.current;if(this.advance(),this.checkIdentifier()){const e=this.advance().value,r=this.createSelector("."+e);return this.createCallExpression(this.createIdentifier(t.value),[r])}this.current=e}if(this.check("#")){const e=this.current;if(this.advance(),this.checkIdentifier()){const e=this.advance().value,r=this.createSelector("#"+e);return this.createCallExpression(this.createIdentifier(t.value),[r])}this.current=e}return this.createIdentifier(t.value)}return"my"!==t.value||this.check(".")?"its"!==t.value||this.check(".")?"your"!==t.value||this.check(".")?"the"===t.value?this.parseTheXofY():"values"===t.value&&this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:"values"},target:this.parsePrimary(),line:t.line,column:t.column}):this.createIdentifier(t.value):this.parseContextPropertyAccess("you"):this.parseContextPropertyAccess("it"):this.parseContextPropertyAccess("me")}if(this.match("$"))return this.parseDollarExpression();if(Nt(this.peek())&&this.peek().value.startsWith("@")){const t=this.advance();return{type:"attributeAccess",attributeName:t.value.substring(1),start:t.start,end:t.end,line:t.line,column:t.column}}const e=this.peek();return this.addError(`Unexpected token: ${e.value} at line ${e.line}, column ${e.column}`),this.advance(),this.createErrorNode()}parseDollarExpression(){if(this.checkNumber()){const t=this.advance().value;return this.createLiteral(t,"$"+t)}if(this.checkIdentifier()){const t=this.advance();let e=this.createIdentifier(t.value);for(;this.match(".");){if(!this.checkIdentifier())return this.addError("Expected property name after '.' in dollar expression"),this.createErrorNode();{const t=this.advance();e=this.createMemberExpression(e,this.createIdentifier(t.value),0)}}return{type:"dollarExpression",expression:e,raw:`$${t.value}${this.previous().value||""}`,line:t.line,column:t.column-1}}return this.addError("Expected identifier or number after '$'"),this.createErrorNode()}parseHyperscriptSelector(){let t="";for(;!this.check("/")&&!this.isAtEnd();)t+=this.advance().value;return this.consume("/","Expected '/' in hyperscript selector"),this.consume(">","Expected '>' after '/' in hyperscript selector"),this.createSelector(t)}parseObjectLiteral(){const t=[],e=this.getPosition();if(this.check("}"))return this.advance(),{type:"objectLiteral",properties:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column};do{let e;if(this.matchPredicate(Ot))e=this.createIdentifier(this.previous().value);else{if(!this.matchString())return this.addError("Expected property name in object literal"),this.createErrorNode();{const t=this.previous().value,r=t.slice(1,-1);e=this.createLiteral(r,t)}}this.consume(":","Expected ':' after property name in object literal");const r=this.parseExpression();if(t.push({key:e,value:r}),!this.match(","))break;if(this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after object literal properties"),{type:"objectLiteral",properties:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseCSSObjectLiteral(){const t=this.getPosition(),e=[];do{if(this.check("}"))break;let r;if(this.matchPredicate(Ot))r=this.createIdentifier(this.previous().value);else{if(!this.matchString())return this.addError("Expected CSS property name"),this.createErrorNode();{const t=this.previous().value,e=t.slice(1,-1);r=this.createLiteral(e,t)}}if(!this.consume(":","Expected ':' after CSS property name"))return this.createErrorNode();const n=[];let s=0,i=0;for(;!this.isAtEnd()&&(0!==i||!this.check(";")&&!this.check("}"));){const t=this.advance();n.push(t.value),"$"===t.value&&this.check("{")&&(s=1),"{"===t.value&&i++,"}"===t.value&&i--}const o=n.join(""),a=s?{type:"templateLiteral",value:o,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}:this.createLiteral(o,o);if(e.push({key:r,value:a}),this.check(";")&&this.advance(),this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after CSS object literal properties"),{type:"objectLiteral",properties:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseConstructorCall(){const t=this.previous();if(!this.checkIdentifier())return this.addError('Expected constructor name after "new"'),this.createErrorNode();const e=this.advance(),r=e.value;if(!this.check("("))return this.addError('Expected "(" after constructor name'),this.createErrorNode();if(this.advance(),this.check(")"))this.advance();else{let t=1;for(;t>0&&!this.isAtEnd();){const e=this.advance();"("===e.value&&t++,")"===e.value&&t--}}return{type:"callExpression",callee:{type:"identifier",name:r,start:e.start,end:e.end,line:e.line,column:e.column},arguments:[],isConstructor:1,start:t.start,end:this.previous().end,line:t.line,column:t.column}}parseTopLevelInitBlock(){const t=this.getPosition(),e=this.parseCommandBlock(["end"]);return this.consume("end","Expected 'end' after init block"),{type:"initBlock",commands:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseDefFeature(){const t=this.getPosition();let e="";if(!this.checkIdentifier())return this.addError("Expected function name after 'def'"),{type:"def",name:"",params:[],body:[],start:t.start,end:this.getPosition().end,line:t.line,column:t.column};for(e=this.advance().value;this.check(".");)this.advance(),this.checkIdentifier()&&(e+="."+this.advance().value);const r=[];if(this.check("(")){if(this.advance(),!this.check(")"))for(this.checkIdentifier()&&r.push(this.advance().value);this.check(",");)this.advance(),this.checkIdentifier()&&r.push(this.advance().value);this.consume(")","Expected ')' after parameter list")}const n=this.parseCommandBlock(["end","catch","finally"]);let s,i,o;return this.check("catch")&&(this.advance(),this.checkIdentifier()&&(s=this.advance().value),i=this.parseCommandBlock(["end","finally"])),this.check("finally")&&(this.advance(),o=this.parseCommandBlock(["end"])),this.consume("end","Expected 'end' after function definition"),{type:"def",name:e,params:r,body:n,...void 0!==s&&{errorSymbol:s},...void 0!==i&&{errorHandler:i},...void 0!==o&&{finallyHandler:o},start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseEventNameWithNamespace(t){let e;e=this.checkEvent()||this.checkIdentifier()||this.checkIsCommand()||this.checkIdentifierLike()?this.advance():this.consumeEvent(t);let r=e.value;return this.check(":")&&(this.advance(),r=`${r}:${this.advance().value}`),r}callExprToCommandNode(t,e){return{type:"command",name:t.callee.name,args:t.arguments,isBlocking:0,...void 0!==e.start&&{start:e.start},...void 0!==e.end&&{end:e.end},...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}}}createPseudoCommandNode(t,e,r,n,s){return{type:"command",name:"pseudo-command",args:[{type:"objectLiteral",properties:[{key:{type:"identifier",name:"methodName"},value:{type:"literal",value:t,raw:`"${t}"`}},{key:{type:"identifier",name:"methodArgs"},value:{type:"literal",value:e.arguments,raw:JSON.stringify(e.arguments)}},...r?[{key:{type:"identifier",name:"preposition"},value:{type:"literal",value:r,raw:`"${r}"`}}]:[],{key:{type:"identifier",name:"targetExpression"},value:n}]}],isBlocking:0,...void 0!==s.start&&{start:s.start},...void 0!==s.end&&{end:s.end},...void 0!==s.line&&{line:s.line},...void 0!==s.column&&{column:s.column}}}tryParsePseudoCommand(t,e){const r=t.callee.name,n=this.peek();if(!(Te.PSEUDO_COMMAND_PREPOSITIONS.includes(n.value.toLowerCase())||Ot(n)&&!this.isCommand(n.value)||bt(n)))return{node:this.callExprToCommandNode(t,e),isPseudo:0,targetFailed:0};let s,i;this.isCommand(r)&&this.addWarning({type:"command-shadow",message:`Method '${r}' shadows hyperscript command`,suggestions:[`Rename method to avoid confusion (e.g., '${r}Fn', 'my${r.charAt(0).toUpperCase()+r.slice(1)}')`,`Use 'call' command instead: call ${r}(...)`,"This works but may cause ambiguity"],severity:"warning",code:"PSEUDO_CMD_SHADOW",...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}}),Te.PSEUDO_COMMAND_PREPOSITIONS.includes(this.peek().value.toLowerCase())&&(s=this.advance().value.toLowerCase());try{i=this.parseExpression()}catch{return{node:this.callExprToCommandNode(t,e),isPseudo:0,targetFailed:1}}return{node:this.createPseudoCommandNode(r,t,s,i,e),isPseudo:1,targetFailed:0}}parseCommandWithErrorRecovery(){this.advance();const t=this.error;try{const e=this.parseCommand();return this.error&&this.error!==t&&(lt("⚠️ Command parsing added error, restoring error state. Error was:",this.error.message),this.error=t),e}catch(e){return lt("⚠️ Command parsing threw exception, restoring error state:",e instanceof Error?e.message:e+""),this.error=t,null}}parseEventHandler(){lt("🔧 parseEventHandler: ENTRY - parsing event handler");const t=[],e=this.parseEventNameWithNamespace("Expected event name after 'on'");for(t.push(e),lt("🔧 parseEventHandler: Parsed first event name: "+e);this.check("or");){this.advance(),lt("🔧 parseEventHandler: Found 'or', parsing additional event name");const e=this.parseEventNameWithNamespace("Expected event name after 'or'");t.push(e),lt("🔧 parseEventHandler: Parsed additional event name: "+e)}let r;if(lt("🔧 parseEventHandler: Total events parsed: "+t.join(", ")),this.registryIntegration){const e=t[0];if(this.registryIntegration.hasEventSource(e)){const t=this.registryIntegration.getEventSource(e);r=t?.name,lt(`🔧 parseEventHandler: Detected custom event source '${r}' for event '${e}'`)}}const n=[];if(this.match("(")){if(!this.check(")"))do{const t=this.advance();n.push(t.value)}while(this.match(","));this.consume(")","Expected ')' after event parameters"),lt("🔧 parseEventHandler: Parsed event parameters: "+n.join(", "))}const s={};for(;this.check(".");){this.advance();const t=this.advance().value.toLowerCase();if("once"===t)s.once=1,lt("🔧 parseEventHandler: Parsed modifier '.once'");else if("prevent"===t)s.prevent=1,lt("🔧 parseEventHandler: Parsed modifier '.prevent'");else if("stop"===t)s.stop=1,lt("🔧 parseEventHandler: Parsed modifier '.stop'");else if("debounce"===t||"throttle"===t){if(!this.check("("))throw Error(`Expected '(' after '.${t}'`);{this.advance();const e=this.advance(),r=parseInt(e.value,10);if(isNaN(r))throw Error(`Expected number for ${t} delay, got: ${e.value}`);"debounce"===t?(s.debounce=r,lt(`🔧 parseEventHandler: Parsed modifier '.debounce(${r})'`)):(s.throttle=r,lt(`🔧 parseEventHandler: Parsed modifier '.throttle(${r})'`)),this.consume(")",`Expected ')' after ${t} delay`)}}else lt(`🔧 parseEventHandler: Warning - unknown modifier '.${t}'`)}if(this.check("debounced")||this.check("throttled")){const t=this.advance().value.toLowerCase(),e="debounced"===t?"debounce":"throttle";if(this.match("at"))if(this.checkTimeExpression()){const r=this.advance(),n=(i=r.value).endsWith("ms")?parseInt(i,10):i.endsWith("seconds")||i.endsWith("s")?1e3*parseFloat(i):i.endsWith("minutes")?6e4*parseFloat(i):i.endsWith("hours")?36e5*parseFloat(i):i.endsWith("days")?864e5*parseFloat(i):parseInt(i,10);s[e]=n,lt(`🔧 parseEventHandler: Parsed '${t} at ${r.value}' (${n}ms)`)}else if(this.matchNumber()){const r=parseInt(this.previous().value,10);s[e]=r,lt(`🔧 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 i;let o,a,c,l;if(Object.keys(s).length>0&&lt("🔧 parseEventHandler: Parsed modifiers:",s),this.match("[")&&(o=this.parseExpression(),this.consume("]","Expected ']' after event condition")),this.match("from")){const t=this.advance();a=t.value,lt(`🔧 parseEventHandler: Parsed 'from' target: ${a} (kind: ${t.kind})`)}if(this.match("of")){const t=this.advance();c=t.value.startsWith("@")?t.value.substring(1):t.value,lt("🔧 parseEventHandler: Parsed attribute name: "+c)}this.match("in")&&(lt("🔧 parseEventHandler: Found 'in' keyword, parsing watch target"),l=this.parseExpression(),lt("🔧 parseEventHandler: Parsed watch target expression"));const u=[];for(lt(`✅ parseEventHandler: About to parse commands, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd: ${this.isAtEnd()}`);!this.isAtEnd();){if(lt(`✅ parseEventHandler: Loop iteration, current token: ${this.peek().value}, kind: ${this.peek().kind}`),this.check("on")){lt("✅ parseEventHandler: Stopping command parsing, found next event handler 'on'");break}if(this.checkComment())lt("✅ parseEventHandler: Skipping comment token: "+this.peek().value),this.advance();else{if(this.check("end")){lt("✅ parseEventHandler: Stopping command parsing, found 'end' keyword"),this.advance();break}if(this.checkIsCommand()){const t="("===this.tokens[this.current+1]?.value,e=this.peek().value.toLowerCase();if(t&&"js"!==e&&"tell"!==e){let t;const e=this.error;try{t=this.parseExpression()}catch(t){this.error=e,this.advance();const r=this.parseCommand();u.push(r);continue}if(t&&"callExpression"===t.type){const e=this.tryParsePseudoCommand(t,t);if(u.push(e.node),e.isPseudo||e.targetFailed)continue}}else{const t=this.parseCommandWithErrorRecovery();t&&(u.push(t),lt("✅ parseEventHandler: Parsed command, next token: "+(this.isAtEnd()?"END":this.peek().value)))}}else{if(!this.checkIdentifier())break;{const t=this.peek();if(this.isCommand(t.value)){const t=this.parseCommandWithErrorRecovery();t&&u.push(t)}else{let t;const e=this.error;try{t=this.parseExpression()}catch(t){lt("⚠️ Expression parsing error, restoring error state:",t instanceof Error?t.message:t+""),this.error=e;break}if(t&&"callExpression"===t.type){const e=this.tryParsePseudoCommand(t,t);if(u.push(e.node),e.targetFailed)continue}else{if(!t||"binaryExpression"!==t.type||" "!==t.operator)break;{const e=t;if(!e.left||"identifier"!==e.left.type||!this.isCommand(e.left.name))break;{const r={type:"command",name:e.left.name,args:[e.right],isBlocking:0,...void 0!==t.start&&{start:t.start},...void 0!==t.end&&{end:t.end},...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}};u.push(r)}}}}}}for(;!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(",")||this.check("on"));)this.advance();if(!this.match("then","and",",")&&!this.checkIsCommand()&&!this.isCommand(this.peek().value))break}}const h=this.getPosition(),f={type:"eventHandler",event:1===t.length?t[0]:t.join("|"),events:t,commands:u,...n.length>0&&{params:n},...o&&{condition:o},...a&&{target:a},...c&&{attributeName:c},...l&&{watchTarget:l},...r&&{customEventSource:r},...Object.keys(s).length>0&&{modifiers:s},start:h.start,end:h.end,line:h.line,column:h.column};return lt(`🔧 parseEventHandler: Created node with events: ${t.join(", ")}, attributeName: ${c||"none"}, watchTarget: ${l?"yes":"none"}`),f}parseBehaviorDefinition(){const t=this.getPosition(),e=this.consumeIdentifier("Expected behavior name after 'behavior' keyword").value;/^[A-Z]/.test(e)||this.addError(`Behavior name must start with uppercase letter (got "${e}")`);const r=[];if(this.match("(")){if(!this.check(")"))do{const t=this.consumeIdentifierLike("Expected parameter name");r.push(t.value)}while(this.match(","));this.consume(")","Expected ')' after behavior parameters")}const n=new Set(r),s=[];let i;for(;!this.isAtEnd()&&!this.check("end");)if(this.match("on")){const t=this.getPosition(),e=this.peek().value;this.advance();const r=[];if(this.check("(")){for(this.advance();!this.isAtEnd()&&!this.check(")");){const t=this.peek();Ot(t)?(r.push(t.value),this.advance(),this.check(",")&&this.advance()):this.advance()}this.check(")")&&this.advance()}let i;if(this.check("from")){this.advance();const t=[];if(this.check("the")&&this.advance(),!this.isAtEnd()){const e=this.peek(),r=n.has(e.value);this.checkIsCommand()&&!r||(t.push(e.value),i=e.value,this.advance())}}const o={type:"eventHandler",event:e,commands:this.parseCommandListUntilEnd(),...void 0!==i&&{target:i},...r.length>0&&{args:r},start:t.start,end:this.getPosition().end,line:t.line,column:t.column};s.push(o)}else{if(!this.match("init")){this.addError("Unexpected token in behavior body: "+this.peek().value);break}i={type:"initBlock",commands:this.parseCommandBlock(["end"]),start:t.start,end:this.getPosition().end,line:t.line,column:t.column},this.consume("end","Expected 'end' after init block")}return this.consume("end","Expected 'end' to close behavior definition"),{type:"behavior",name:e,parameters:r,eventHandlers:s,...void 0!==i?{initBlock:i}:{},start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseCommandSequence(){const t=[];for(;!this.isAtEnd();){if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){this.advance();const e=this.error,r=this.parseCommand();for(this.error&&this.error!==e&&(this.error.message.includes("Expected closing parenthesis")||this.error.message.includes("Expected ')'")||this.error.message.includes("unclosed parenthes")||this.error.message.includes("Unclosed parenthes")||(lt("⚠️ parseCommandSequence: Command parsing added non-critical error, restoring error state. Error was:",this.error.message),this.error=e)),t.push(r);!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("on"));)lt("⚠️ parseCommandSequence: Skipping unexpected token:",this.peek().value),this.advance();if(this.check("on")){lt('✅ parseCommandSequence: Found "on" token, stopping command sequence to allow event handler parsing');break}if(this.match("then"))continue;if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value))continue;break}{const e=this.peek(),r=this.getPosition(),n="Expected command, got: "+e.value;this.addError(n);const s=Jt(r,n,e.value);if(t.push(s),this.synchronizeToCommandBoundary(),this.isAtEnd())break;if(this.match("then"))continue;if(this.check("end")||this.check("on"))break;if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value))continue;break}}return 1===t.length?t[0]:function(t){return{type:"CommandSequence",commands:t,start:t[0]?.start||0,end:t[t.length-1]?.end||0,line:t[0]?.line||1,column:t[0]?.column||1}}(t)}getMultiWordPattern(t){return function(t){return Zt.find(e=>e.command===t.toLowerCase())||null}(t)}isTokenKeyword(t,e){return Gt(t,e)}parseMultiWordCommand(t,e){return function(t,e,r){const n=t.getMultiWordPattern(r);if(!n)return null;const s=[],i={};for(;!Yt(t,["catch","finally",...n.keywords])&&!Gt(t.peek(),n.keywords);){const e=t.parsePrimary();if(!e)break;if(s.push(e),!t.match(",")&&Gt(t.peek(),n.keywords))break}for(;!t.isAtEnd()&&Gt(t.peek(),n.keywords);){const e=t.advance().value,r=t.parseExpression();if(r&&(i[e]=r),!Gt(t.peek(),n.keywords))break}const o=re.from(e).withArgs(...s).endingAt(t.getPosition());return Object.keys(i).length>0&&o.withModifiers(i),o.build()}(this.getContext(),t,e)}parseCommandBlock(t){const e=[];for(;!this.isAtEnd()&&!t.some(t=>this.check(t));)if(this.checkComment())this.advance();else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value))break;{this.advance();const t=this.parseCommand();e.push(t)}}return e}trySemanticParse(t){if(!this.semanticAdapter||!this.semanticAdapter.isAvailable())return null;try{const e=this.semanticAdapter.trySemanticParse(t);return e.success&&e.node?(lt(`[Semantic] Successfully parsed with confidence ${e.confidence}:`,e.node.name),e.node):(lt(`[Semantic] Low confidence (${e.confidence}), falling back to traditional parser`),null)}catch(t){return lt("[Semantic] Error during semantic parse:",t),null}}getRemainingInput(){if(!this.originalInput)return this.tokens.slice(this.current>0?this.current-1:0).map(t=>t.value).join(" ");const t=this.current>0?this.tokens[this.current-1]:this.tokens[0];return t&&void 0!==t.start?this.originalInput.slice(t.start):this.originalInput}skipToCommandBoundary(){const t=["then","and","else","end"];for(;!this.isAtEnd();){const e=this.peek(),r=e.value.toLowerCase();if(t.includes(r))break;if(yt(e))break;this.advance()}}parseCommand(){const t=this.previous();let e=t.value;if(this.semanticAdapter&&!["install","wait","repeat","for","set","put","increment","decrement","add","if","unless","make","measure","trigger","halt","remove","exit","return","closest","js","tell"].includes(e.toLowerCase())){const t=this.getRemainingInput(),e=this.trySemanticParse(t);if(e)return this.skipToCommandBoundary(),e}if("beep"===e&&this.check("!")&&(this.advance(),e="beep!"),"fetch"===e)return function(t,e){const r={};let n=null;if(!t.isAtEnd()&&t.check("/")&&(n=function(t){const e=t.savePosition();let r="";for(;!t.isAtEnd()&&!de(t);)r+=t.advance().value;return r&&"/"!==r?{type:"literal",value:r,raw:r,start:e,end:t.savePosition()}:(t.restorePosition(e),null)}(t)),n||(n=t.parsePrimary()),!n)return t.addError("fetch requires a URL"),re.from(e).endingAt(t.getPosition()).build();!t.isAtEnd()&&t.check("{")&&(r.with=t.parsePrimary());for(let e=0;2>e&&!t.isAtEnd();e++)if(!t.check("as")||r.as){if(!t.check("with")||r.with)break;t.advance(),r.with=pe(t)?me(t):t.parsePrimary()}else t.advance(),t.isAtEnd()||ee(t,"a")||ee(t,"an"),r.as=t.parsePrimary();const s=re.from(e).withArgs(n).endingAt(t.getPosition());return Object.keys(r).length>0&&s.withModifiers(r),s.build()}(this.getContext(),t);const r=this.parseMultiWordCommand(t,e);if(r)return r;const n=e.toLowerCase();if("repeat"===n)return this.parseRepeatCommand(t);if("for"===n)return this.parseForCommand(t);if("if"===n||"unless"===n)return this.parseIfCommand(t);if("wait"===n)return this.parseWaitCommand(t);if("install"===n)return this.parseInstallCommand(t);if("transition"===n)return this.parseTransitionCommand(t);if("add"===n)return this.parseAddCommand(t);if(this.isCompoundCommand(n))return this.parseCompoundCommand({type:"identifier",name:n,start:t.start||0,end:t.end||0,line:t.line,column:t.column})||this.createErrorNode();const s=[];if(("increment"===e||"decrement"===e)&&!this.isAtEnd())return function(t,e){const r=e.value,n="increment"===r?"+":"-";let s=0;t.check(g)&&(s=1,t.advance());const i=t.parseExpression();if(!i)throw Error("Expected variable or expression after "+r);let o;if(t.check("by")){t.advance();const e=t.parseExpression();if(!e)throw Error(`Expected amount after 'by' in ${r} command`);o=e}else o=Ft(1,"1",{start:e.start,end:t.previous().end,line:e.line,column:e.column});let a=i;s&&"identifier"===i.type&&(a={...i,scope:"global"});const c={start:e.start,end:t.previous().end,line:e.line,column:e.column},l=qt(n,i,o,c),u=[a,_t(h,c),l];return re.from(e).withName("set").withArgs(...u).withOriginalCommand(r).endingAt({end:t.previous().end}).build()}(this.getContext(),t);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.check("end")||this.checkIsCommand());){const t=this.parseExpression();if(s.push(t||this.parsePrimary()),this.match(","))continue;const e=["into","from","to","with","by","at","before","after","over"];if(e.some(t=>this.check(t)))continue;const r=s[s.length-1];if(!r||"identifier"!==r.type&&"keyword"!==r.type||!e.includes(r.name??r.value))break}const i=this.getPosition();return{type:"command",name:e,args:s,isBlocking:0,start:i.start,end:i.end,line:i.line,column:i.column}}parseConditional(){const t=this.parseExpression();this.consume("then","Expected 'then' after if condition");const e=this.parseConditionalBranch();let r;this.match("else")&&(r=this.parseConditionalBranch());const n=this.getPosition();return{type:"conditionalExpression",test:t,consequent:e,alternate:r,start:n.start,end:n.end,line:n.line,column:n.column}}parseConditionalBranch(){if(this.checkIsCommand()){const t=this.advance(),e=this.createIdentifier(t.value);return this.createCommandFromIdentifier(e)||e}if(this.checkIdentifier()||this.checkKeyword()){const t=this.peek();if(this.isCommand(t.value)){const t=this.advance(),e=this.createIdentifier(t.value);return this.createCommandFromIdentifier(e)||e}}return this.parseExpression()}parseNavigationFunction(t){const e=[];if(this.match("of"))e.push(this.parseExpression());else{if(this.check("("))return this.finishCall(this.createIdentifier(t));this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||e.push(this.parsePrimary())}return this.createCallExpression(this.createIdentifier(t),e)}parseTheXofY(){if(!this.checkIdentifier())return this.createIdentifier("the");const t=this.peek(),e=t.value;return["first","last","next","previous","random","closest"].includes(e)?(this.advance(),this.parseNavigationFunction(e)):(this.advance(),this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:e},target:this.parsePrimary(),line:t.line,column:t.column}):this.createIdentifier(e))}parseContextPropertyAccess(t){if("me"===t&&this.match("*")){let e="";if(!this.checkIdentifier())return this.addError("Expected property name after 'my *'"),this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(""),0);for(e=this.advance().value;this.check("-")&&!this.isAtEnd();){if(e+="-",this.advance(),!this.checkIdentifier()){this.addError("Expected identifier after hyphen in CSS property name");break}e+=this.advance().value}const r="computed-"+e;return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(r),0)}{if(Nt(this.peek())&&this.peek().value.startsWith("@")){const e=this.advance();return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(e.value),0)}const e=this.consumeIdentifier(`Expected property name after '${{me:"my",it:"its",you:"your"}[t]}'`);return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(e.value),0)}}parseMyPropertyAccess(){return this.parseContextPropertyAccess("me")}finishCall(t){const e=[];if(!this.check(")"))do{if(this.check(","))return this.addError("Unexpected token in function arguments"),this.createCallExpression(t,[this.createErrorNode()]);e.push(this.parseExpression())}while(this.match(","));if(!this.check(")")&&"identifier"===t.type){const e=t.name;N.has(e.toLowerCase())&&lt(`💡 Tip: CSS functions like ${e}() should be quoted for clean parsing. Use '${e}(...)' or \`${e}(...)\` instead.`)}return this.consume(")","Expected ')' after arguments"),this.createCallExpression(t,e)}createLiteral(t,e){return Ft(t,e,this.getPosition())}createIdentifier(t){return _t(t,this.getPosition())}createBinaryExpression(t,e,r){return qt(t,e,r,this.getPosition())}createUnaryExpression(t,e,r){return function(t,e,r,n){return{type:"unaryExpression",operator:t,argument:e,prefix:r,start:n.start,end:n.end,line:n.line,column:n.column}}(t,e,r,this.getPosition())}createCallExpression(t,e){return function(t,e,r){return{type:"callExpression",callee:t,arguments:e,start:r.start,end:r.end,line:r.line,column:r.column}}(t,e,this.getPosition())}createMemberExpression(t,e,r){return function(t,e,r,n){return{type:"memberExpression",object:t,property:e,computed:r,start:n.start,end:n.end,line:n.line,column:n.column}}(t,e,r,this.getPosition())}createSelector(t){return function(t,e){return{type:"selector",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}(t,this.getPosition())}createPossessiveExpression(t,e){return function(t,e,r){return{type:"possessiveExpression",object:t,property:e,start:r.start,end:r.end,line:r.line,column:r.column}}(t,e,this.getPosition())}createErrorNode(){return{type:"identifier",name:"__ERROR__",start:(t=this.getPosition()).start,end:t.end,line:t.line,column:t.column};var t}processEscapeSequences(t){return t.replace(/\\(.)/g,(t,e)=>{switch(e){case"n":return"\n";case"t":return"\t";case"r":return"\r";case"b":return"\b";case"f":return"\f";case"v":return"\v";case"0":return"\0";case"\\":return"\\";case'"':return'"';case"'":return"'";default:return e}})}createProgramNode(t){return function(t){if(lt(`✅ createProgramNode: Called with ${t.length} statements`),0===t.length)return lt("✅ createProgramNode: Returning error node (0 statements)"),{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===t.length)return lt(`✅ createProgramNode: Returning single statement (type=${t[0].type})`),t[0];const e={type:"Program",statements:t,start:t[0]?.start||0,end:t[t.length-1]?.end||0,line:t[0]?.line||1,column:t[0]?.column||1};return lt(`✅ createProgramNode: Returning Program node with ${t.length} statements, type=${e.type}`),e}(t)}match(...t){for(const e of t)if(this.check(e))return this.advance(),1;return 0}matchOperator(t){if(this.isAtEnd())return 0;const e=this.peek();return Vt(e)&&e.value===t?(this.advance(),1):0}check(t){if(this.isAtEnd())return 0;const e=this.peek().value;return this.resolveKeyword(e)===t}checkPredicate(t){return this.isAtEnd()?0:t(this.peek())}matchPredicate(t){return this.checkPredicate(t)?(this.advance(),1):0}checkSelector(){return this.checkPredicate(kt)}matchSelector(){return this.matchPredicate(kt)}checkAnySelector(){return this.checkPredicate(xt)}checkLiteral(){return this.checkPredicate(At)}checkIdentifierLike(){return this.checkPredicate(wt)}checkIsCommand(){return this.checkPredicate(yt)}checkCommandTerminator(){return this.checkPredicate(Bt)}checkReference(){return this.checkPredicate(St)}checkTimeExpression(){return this.checkPredicate(Ct)}checkEvent(){return this.checkPredicate(gt)}checkContextVar(){return this.checkPredicate(bt)}checkComment(){return this.checkPredicate(Tt)}checkIdentifier(){return this.checkPredicate(Ot)}checkKeyword(){return this.checkPredicate(vt)}checkString(){return this.checkPredicate($t)}matchString(){return this.matchPredicate($t)}checkNumber(){return this.checkPredicate(Lt)}matchNumber(){return this.matchPredicate(Lt)}checkBoolean(){return this.checkPredicate(Rt)}matchBoolean(){return this.matchPredicate(Rt)}checkTemplateLiteral(){return this.checkPredicate(It)}matchTemplateLiteral(){return this.matchPredicate(It)}checkQueryReference(){return this.checkPredicate(jt)}matchQueryReference(){return this.matchPredicate(jt)}checkIdSelector(){return this.checkPredicate(Mt)}checkClassSelector(){return this.checkPredicate(Dt)}checkCssSelector(){return this.checkPredicate(Pt)}checkBasicOperator(){return this.checkPredicate(Vt)}matchBasicOperator(){return this.matchPredicate(Vt)}matchTimeExpression(){return this.matchPredicate(Ct)}matchIdentifierLike(){return this.matchPredicate(wt)}matchComparisonOperator(){return this.matchPredicate(Et)}consumePredicate(t,e){return this.checkPredicate(t)?this.advance():(this.addError(e),this.peek())}consumeIdentifier(t){return this.consumePredicate(Ot,t)}consumeIdentifierLike(t){return this.consumePredicate(wt,t)}consumeEvent(t){return this.consumePredicate(gt,t)}advance(){return this.isAtEnd()||this.current++,this.previous()}isAtEnd(){return this.current>=this.tokens.length}peek(){return this.isAtEnd()?{kind:"unknown",value:"",start:0,end:0,line:1,column:1}:this.tokens[this.current]}previous(){return this.tokens[this.current-1]}consume(t,e){return this.check(t)?this.advance():(this.addError(e),this.peek())}addError(t){const e=this.peek();let r=e.start||0,n=e.line||1,s=e.column||1;if(t.includes("property name after '.'")){const t=this.current>0?this.previous():e;r=t.end||t.start||0,n=t.line||1,s=t.column||1}if(t.includes("parenthes")){const t=this.current>0?this.previous():e;r=t.end||t.start||0,n=t.line||1,s=t.column||1,0===r&&this.current>0&&(r=this.current)}if(t.includes("Expected expression after")){const t=this.current>0?this.previous():e;r=t.start||0,n=t.line||1,s=t.column||1,0===r&&(r=Math.max(1,this.current-1))}if(t.includes("Missing operand")){let t=e;for(let e=this.current-1;e>=0;e--){const r=this.tokens[e];if(r&&("+"===r.value||"-"===r.value)){t=r;break}}r=t.start||0,n=t.line||1,s=t.column||1}this.error={message:t,line:Math.max(1,n),column:Math.max(1,s),position:Math.max(0,r)},this.errors.push(this.error)}synchronizeToCommandBoundary(){for(;!this.isAtEnd();){const t=this.peek();if("then"===t.value||"end"===t.value||"on"===t.value)return;if(this.checkIsCommand()||this.isCommand(t.value)&&!this.isKeyword(t.value))return;lt("⚠️ synchronize: Skipping token:",t.value),this.advance()}}parseAttributeOrArrayLiteral(){const t=this.previous().start,e=this.previous().line,r=this.previous().column;if(!this.isAtEnd()&&this.peek().value.startsWith("@")){const n=[];for(;!this.check("]")&&!this.isAtEnd();){const t=this.advance();n.push(t.value)}this.consume("]","Expected ']' after attribute literal");const s="["+n.join("")+"]";return{type:"literal",value:s,raw:s,start:t,end:this.previous().end,line:e,column:r}}const n=[];if(!this.check("]"))do{if(this.check("]"))break;n.push(this.parseExpression())}while(this.match(","));return this.consume("]","Expected ']' after array elements"),{type:"arrayLiteral",elements:n,start:t,end:this.previous().end,line:e,column:r}}getPosition(){const t=this.current>0?this.previous():this.peek();return{start:t.start||0,end:t.end||0,line:t.line||1,column:t.column||1}}getContext(){const t=this,e={tokens:this.tokens,advance:this.advance.bind(this),peek:this.peek.bind(this),previous:this.previous.bind(this),consume:this.consume.bind(this),check:this.check.bind(this),checkIdentifierLike:this.checkIdentifierLike.bind(this),checkSelector:this.checkSelector.bind(this),checkAnySelector:this.checkAnySelector.bind(this),checkLiteral:this.checkLiteral.bind(this),checkReference:this.checkReference.bind(this),checkTimeExpression:this.checkTimeExpression.bind(this),checkEvent:this.checkEvent.bind(this),checkIsCommand:this.checkIsCommand.bind(this),checkContextVar:this.checkContextVar.bind(this),match:this.match.bind(this),matchOperator:this.matchOperator.bind(this),isAtEnd:this.isAtEnd.bind(this),createIdentifier:this.createIdentifier.bind(this),createLiteral:this.createLiteral.bind(this),createSelector:this.createSelector.bind(this),createBinaryExpression:this.createBinaryExpression.bind(this),createUnaryExpression:this.createUnaryExpression.bind(this),createMemberExpression:this.createMemberExpression.bind(this),createPossessiveExpression:this.createPossessiveExpression.bind(this),createCallExpression:this.createCallExpression.bind(this),createErrorNode:this.createErrorNode.bind(this),createProgramNode:this.createProgramNode.bind(this),createCommandFromIdentifier:this.createCommandFromIdentifier.bind(this),parseExpression:this.parseExpression.bind(this),parsePrimary:this.parsePrimary.bind(this),parseCall:this.parseCall.bind(this),parseAssignment:this.parseAssignment.bind(this),parseLogicalOr:this.parseLogicalOr.bind(this),parseLogicalAnd:this.parseLogicalAnd.bind(this),parseEquality:this.parseEquality.bind(this),parseComparison:this.parseComparison.bind(this),parseAddition:this.parseAddition.bind(this),parseMultiplication:this.parseMultiplication.bind(this),parseImplicitBinary:this.parseImplicitBinary.bind(this),parseConditional:this.parseConditional.bind(this),parseConditionalBranch:this.parseConditionalBranch.bind(this),parseEventHandler:this.parseEventHandler.bind(this),parseBehaviorDefinition:this.parseBehaviorDefinition.bind(this),parseNavigationFunction:this.parseNavigationFunction.bind(this),parseMyPropertyAccess:this.parseMyPropertyAccess.bind(this),parseDollarExpression:this.parseDollarExpression.bind(this),parseHyperscriptSelector:this.parseHyperscriptSelector.bind(this),parseAttributeOrArrayLiteral:this.parseAttributeOrArrayLiteral.bind(this),parseObjectLiteral:this.parseObjectLiteral.bind(this),parseCSSObjectLiteral:this.parseCSSObjectLiteral.bind(this),parseCommand:this.parseCommand.bind(this),parseCommandSequence:this.parseCommandSequence.bind(this),parseCommandListUntilEnd:this.parseCommandListUntilEnd.bind(this),getPosition:this.getPosition.bind(this),addError:this.addError.bind(this),addWarning:this.addWarning.bind(this),isCommand:this.isCommand.bind(this),isCompoundCommand:this.isCompoundCommand.bind(this),isKeyword:this.isKeyword.bind(this),getMultiWordPattern:this.getMultiWordPattern.bind(this),resolveKeyword:this.resolveKeyword.bind(this),savePosition:()=>t.current,restorePosition:e=>{t.current=e},peekAt:e=>{const r=t.current+e;return r>=0&&t.tokens.length>r?t.tokens[r]:null},getInputSlice:(t,e)=>this.originalInput?0>t||t>=this.originalInput.length?"":void 0!==e?this.originalInput.slice(t,e):this.originalInput.slice(t):""};return Object.defineProperty(e,"current",{get:()=>t.current,set:e=>{t.current=e},enumerable:1,configurable:1}),e}}function Oe(t,e){const r=function(t){const e={input:"",position:0,line:1,column:1,tokens:[]};e.input=t;const r=t.length;for(;r>e.position&&(V(e),r>e.position);){const r=t[e.position];if("-"!==r||"-"!==D(e,1))if('"'!==r){if("'"===r||"'"===r){const t=D(e,1),r=e.tokens[e.tokens.length-1];if("s"!==t||!r||r.kind!==I.IDENTIFIER&&r.kind!==I.SELECTOR&&"]"!==r.value&&")"!==r.value&&"}"!==r.value)q(e);else{const t=e.position;P(e),P(e),B(e,I.OPERATOR,"'s",t)}continue}if("`"!==r)if("<"!==r)if("#"!==r){if("."===r){if("."===D(e,1)){const t=e.position;P(e),P(e),B(e,I.OPERATOR,"..",t);continue}const t=e.tokens[e.tokens.length-1],r=new Set(["from","to","into","on","in","at","first","last","next","previous","closest","random"]),n=t&&t.kind===I.IDENTIFIER&&w.has(t.value.toLowerCase()),s=t&&t.kind===I.IDENTIFIER&&r.has(t.value.toLowerCase());if((!t||t.kind===I.OPERATOR&&")"!==t.value&&"]"!==t.value||n||s||"("===t.value||"["===t.value||"{"===t.value||","===t.value||";"===t.value)&&Y(D(e))){U(e);continue}}if("@"!==r)if("{"!==r)if("}"!==r){if("["===r){const t=e.tokens[e.tokens.length-1],r=t&&t.kind===I.IDENTIFIER&&L.has(t.value)&&e.tokens.length>=2&&"on"===e.tokens[e.tokens.length-2]?.value;(!t||t.kind!==I.IDENTIFIER&&")"!==t.value&&"]"!==t.value||r)&&r?(B(e,I.SYMBOL,"["),P(e)):(B(e,I.OPERATOR,"["),P(e));continue}if("]"!==r){if("$"===r){const t=D(e,1);if(t>="a"&&"z">=t||t>="A"&&"Z">=t||"_"===t){X(e);continue}}tt(r)?J(e):"0">r||r>"9"?("a">r||r>"z")&&("A">r||r>"Z")&&"_"!==r?(B(e,I.UNKNOWN,r),P(e)):G(e):Z(e)}else B(e,I.OPERATOR,"]"),P(e)}else B(e,I.OPERATOR,"}"),P(e);else B(e,I.OPERATOR,"{"),P(e);else z(e)}else U(e);else Q(e)?W(e):J(e);else H(e)}else q(e);else _(e)}return e.tokens}(t);return new Te(r,e,t).parse()}Te.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty"]),Te.PRATT_TABLE=Ne,Te.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];class $e{constructor(){this.hooks=new Map,this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}register(t,e){this.unregister(t),this.hooks.set(t,e),e.beforeExecute&&this.beforeExecuteHooks.push(e.beforeExecute),e.afterExecute&&this.afterExecuteHooks.push(e.afterExecute),e.onError&&this.onErrorHooks.push(e.onError),e.interceptCommand&&this.interceptCommandHooks.push(e.interceptCommand)}unregister(t){const e=this.hooks.get(t);if(!e)return 0;if(e.beforeExecute){const t=this.beforeExecuteHooks.indexOf(e.beforeExecute);t>-1&&this.beforeExecuteHooks.splice(t,1)}if(e.afterExecute){const t=this.afterExecuteHooks.indexOf(e.afterExecute);t>-1&&this.afterExecuteHooks.splice(t,1)}if(e.onError){const t=this.onErrorHooks.indexOf(e.onError);t>-1&&this.onErrorHooks.splice(t,1)}if(e.interceptCommand){const t=this.interceptCommandHooks.indexOf(e.interceptCommand);t>-1&&this.interceptCommandHooks.splice(t,1)}return this.hooks.delete(t)}has(t){return this.hooks.has(t)}async runBeforeExecute(t){for(const e of this.beforeExecuteHooks)await e(t)}async runAfterExecute(t,e){for(const r of this.afterExecuteHooks)await r(t,e)}async runOnError(t,e){let r=e;for(const e of this.onErrorHooks){const n=await e(t,r);n instanceof Error&&(r=n)}return r}shouldIntercept(t,e){for(const r of this.interceptCommandHooks)if(r(t,e))return 1;return 0}getRegisteredNames(){return Array.from(this.hooks.keys())}clear(){this.hooks.clear(),this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}}function Le(t){return t instanceof Error&&("isHalt"in t||"isExit"in t||"isBreak"in t||"isContinue"in t||"isReturn"in t)?t:null}function Re(t){return{ok:1,value:t}}function Ie(t){return{ok:0,error:t}}function je(t){return 1==t.ok}class Me{constructor(t){this.elementCleanups=new WeakMap,this.elementCount=0,this.typeCounts={listener:0,observer:0,interval:0,timeout:0,custom:0},this.globalCleanups=[],this.debugMode=t?.debug??0}registerListener(t,e,r,n,s){this.addCleanup(t,{type:"listener",target:e,eventName:r,cleanup:()=>{e.removeEventListener(r,n,s),this.debugMode&&ht(`CleanupRegistry: Removed listener '${r}'`)},description:r+" listener"})}registerObserver(t,e){this.addCleanup(t,{type:"observer",cleanup:()=>{e.disconnect(),this.debugMode&&ht("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(t,e){this.addCleanup(t,{type:"interval",cleanup:()=>{clearInterval(e),this.debugMode&&ht("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(t,e){this.addCleanup(t,{type:"timeout",cleanup:()=>{clearTimeout(e),this.debugMode&&ht("CleanupRegistry: Cleared timeout")},description:"Timeout"})}registerCustom(t,e,r){this.addCleanup(t,{type:"custom",cleanup:e,description:r||"Custom cleanup"})}registerGlobal(t,e="custom",r){this.globalCleanups.push({type:e,cleanup:t,description:r||"Global cleanup"}),this.debugMode&&ht("CleanupRegistry: Registered global cleanup: "+(r||e))}addCleanup(t,e){const r=this.elementCleanups.get(t);r?r.push(e):(this.elementCleanups.set(t,[e]),this.elementCount++),this.typeCounts[e.type]++,this.debugMode&&ht(`CleanupRegistry: Registered ${e.type} for element`,t)}cleanupElement(t){const e=this.elementCleanups.get(t);if(!e||0===e.length)return 0;let r=0;for(const t of e){try{t.cleanup(),r++}catch(t){this.debugMode&&ht("CleanupRegistry: Error during cleanup:",t)}this.typeCounts[t.type]--}return this.elementCleanups.delete(t),this.elementCount--,this.debugMode&&ht(`CleanupRegistry: Cleaned up ${r} resources for element`),r}cleanupElementTree(t){let e=this.cleanupElement(t);const r=t.querySelectorAll("*");for(const t of r)e+=this.cleanupElement(t);return e}cleanupGlobal(){let t=0;for(const e of this.globalCleanups)try{e.cleanup(),t++}catch(t){this.debugMode&&ht("CleanupRegistry: Error during global cleanup:",t)}return this.globalCleanups=[],this.debugMode&&ht(`CleanupRegistry: Cleaned up ${t} global resources`),t}cleanupAll(){return this.cleanupGlobal()}hasCleanups(t){const e=this.elementCleanups.get(t);return void 0!==e&&e.length>0}getCleanupCount(t){const e=this.elementCleanups.get(t);return e?.length??0}getStats(){let t=0,e=0,r=0,n=0,s=0;for(const i of this.globalCleanups)switch(i.type){case"listener":t++;break;case"observer":e++;break;case"interval":r++;break;case"timeout":n++;break;case"custom":s++}return{elementsTracked:this.elementCount,listeners:this.typeCounts.listener+t,observers:this.typeCounts.observer+e,intervals:this.typeCounts.interval+r,timeouts:this.typeCounts.timeout+n,custom:this.typeCounts.custom+s,global:this.globalCleanups.length}}setDebugMode(t){this.debugMode=t}}const De=new Map;function Pe(t,e){return{me:t??null,it:null,you:null,result:null,locals:new Map,globals:e||De,flags:{halted:0,breaking:0,continuing:0,returning:0,async:0}}}class Ve{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(t,e){const r=t.toLowerCase();this.sources.has(r)&&console.warn("[EventSourceRegistry] Overwriting existing event source: "+t),this.sources.set(r,e)}unregister(t){const e=t.toLowerCase(),r=this.sources.get(e);if(r){for(const[t,r]of this.subscriptions.entries())r.source===e&&(r.unsubscribe(),this.subscriptions.delete(t));return r.destroy?.(),this.sources.delete(e)}return 0}get(t){return this.sources.get(t.toLowerCase())}has(t){return this.sources.has(t.toLowerCase())}subscribe(t,e,r){const n=this.get(t);if(!n)return void console.warn("[EventSourceRegistry] Unknown event source: "+t);n.initialize?.();const s=n.subscribe(e,r);return this.subscriptions.set(s.id,s),s}unsubscribe(t){const e=this.subscriptions.get(t);return e?(e.unsubscribe(),this.subscriptions.delete(t)):0}getSourceNames(){return Array.from(this.sources.keys())}getSubscriptions(){return Array.from(this.subscriptions.values())}findSourceForEvent(t){for(const[e,r]of this.sources.entries())if(r.supports?.(t)??r.supportedEvents?.includes(t))return e}generateId(){return`sub_${this.nextId++}_${Date.now().toString(36)}`}destroy(){for(const t of this.subscriptions.values())t.unsubscribe();this.subscriptions.clear();for(const t of this.sources.values())t.destroy?.();this.sources.clear()}}class Be{constructor(){this.providers=new Map,this.globalProviders=new Map}register(t,e,r){const n=t.toLowerCase();this.providers.set(n,"function"==typeof e?{name:n,provide:e,cache:r?.cache??1,description:r?.description,dependencies:r?.dependencies}:e)}registerGlobal(t,e,r){const n=t.toLowerCase();this.globalProviders.set(n,"function"==typeof e?{name:n,provide:e,cache:r?.cache??1,description:r?.description,dependencies:r?.dependencies}:e)}unregister(t){return this.providers.delete(t.toLowerCase())}unregisterGlobal(t){return this.globalProviders.delete(t.toLowerCase())}get(t){const e=t.toLowerCase();return this.providers.get(e)??this.globalProviders.get(e)}has(t){const e=t.toLowerCase();return this.providers.has(e)||this.globalProviders.has(e)}async resolve(t,e,r){const n=this.get(t);if(!n)return;const s="__provider_"+n.name;if(n.cache&&r?.has(s))return r.get(s);if(n.dependencies)for(const t of n.dependencies)await this.resolve(t,e,r);const i=await n.provide(e);return n.cache&&r&&r.set(s,i),i}resolveSync(t,e,r){const n=this.get(t);if(!n)return;const s="__provider_"+n.name;if(n.cache&&r?.has(s))return r.get(s);const i=n.provide(e);if(i instanceof Promise)throw Error(`Context provider '${t}' is async. Use resolve() instead of resolveSync().`);return n.cache&&r&&r.set(s,i),i}enhance(t){const e=this,r=new Map;return new Proxy(t,{get(t,n,s){if("string"==typeof n&&e.get(n))try{return e.resolveSync(n,t,r)}catch{return e.resolve(n,t,r)}return Reflect.get(t,n,s)},has:(t,r)=>"string"==typeof r&&e.has(r)?1:Reflect.has(t,r)})}async resolveAll(t){const e=new Map,r={},n=[...this.globalProviders.entries(),...this.providers.entries()];for(const[s,i]of n)try{r[s]=await this.resolve(s,t,e)}catch(t){console.warn(`[ContextProviderRegistry] Failed to resolve '${s}':`,t),r[s]=void 0}return r}getProviderNames(){return[...new Set([...this.globalProviders.keys(),...this.providers.keys()])]}clear(){this.providers.clear(),this.globalProviders.clear()}}const Fe=new class{constructor(t={}){this.types=new Map,this.coercionCache=new Map,this.config={strictMode:0,cacheCoercions:1,...t},this.registerBuiltinTypes()}register(t){this.types.has(t.name)&&console.warn(`ExpressionTypeRegistry: Overwriting existing type '${t.name}'`),this.types.set(t.name,t)}get(t){return this.types.get(t)}has(t){return this.types.has(t)}getTypeNames(){return Array.from(this.types.keys())}inferType(t){for(const[e,r]of this.types)if(r.isType(t))return e;return"Unknown"}getHyperScriptType(t){const e=this.inferType(t),r=this.types.get(e);return r?.hyperscriptType??"unknown"}coerce(t,e,r){const n=this.types.get(e);if(!n){if(this.config.strictMode)throw Error("Unknown target type: "+e);return null}if(n.isType(t))return t;if(this.config.cacheCoercions){const r=`${this.inferType(t)}:${e}:${JSON.stringify(t)}`;if(this.coercionCache.has(r))return this.coercionCache.get(r)}const s=this.inferType(t),i=n.coerceFrom?.[s];if(i){const n=i(t,r);if(this.config.cacheCoercions&&null!==n){const r=`${s}:${e}:${JSON.stringify(t)}`;this.coercionCache.set(r,n)}return n}return n.defaultValue}canCoerce(t,e){const r=this.types.get(e);if(!r)return 0;if(r.isType(t))return 1;const n=this.inferType(t);return void 0!==r.coerceFrom?.[n]}getCoercionInfo(t,e){const r=this.types.get(e);return r&&(t===e||r.coerceFrom?.[t])?{possible:1,direct:1}:{possible:0,direct:0}}clearCache(){this.coercionCache.clear()}getStats(){return{typeCount:this.types.size,cacheSize:this.coercionCache.size,typeNames:this.getTypeNames()}}registerBuiltinTypes(){this.register({name:"String",hyperscriptType:"string",tsType:"string",isType:t=>"string"==typeof t,defaultValue:"",description:"Text string value",examples:["hello","world",""],coerceFrom:{Number:t=>t+"",Boolean:t=>t+"",Null:()=>"",Undefined:()=>"",Array:t=>Array.isArray(t)?t.join(", "):null,Object:t=>{try{return JSON.stringify(t)}catch{return t+""}},Element:t=>t instanceof Element?t.textContent??t.outerHTML:null}}),this.register({name:"Number",hyperscriptType:"number",tsType:"number",isType:t=>"number"==typeof t&&!isNaN(t),defaultValue:0,description:"Numeric value (integer or float)",examples:[0,1,3.14,-42],coerceFrom:{String:t=>{const e=parseFloat(t);return isNaN(e)?null:e},Boolean:t=>t?1:0,Null:()=>0,Undefined:()=>null}}),this.register({name:"Boolean",hyperscriptType:"boolean",tsType:"boolean",isType:t=>"boolean"==typeof t,defaultValue:0,description:"True or false value",examples:[1,0],coerceFrom:{String:t=>{const e=t.toLowerCase().trim();return"true"===e||"yes"===e||"1"===e?1:"false"===e||"no"===e||"0"===e||""===e?0:e.length>0},Number:t=>0!==t,Null:()=>0,Undefined:()=>0,Array:t=>Array.isArray(t)?t.length>0:0,Element:t=>t instanceof Element,ElementList:t=>Array.isArray(t)&&t.length>0}}),this.register({name:"Element",hyperscriptType:"element",tsType:"Element | HTMLElement",isType:t=>t instanceof Element,defaultValue:null,description:"DOM Element",coerceFrom:{String:(t,e)=>{const r=t;if(r.startsWith("#")||r.startsWith(".")||r.match(/^[\w-]+$/))try{return document.querySelector(r)}catch{return null}return null},ElementList:t=>Array.isArray(t)&&t.length>0?t[0]:null,NodeList:t=>t.length>0?t[0]:null}}),this.register({name:"ElementList",hyperscriptType:"element-list",tsType:"Element[]",isType:t=>Array.isArray(t)&&t.length>0&&t.every(t=>t instanceof Element),defaultValue:[],description:"Array of DOM Elements",coerceFrom:{Element:t=>t instanceof Element?[t]:[],NodeList:t=>Array.from(t),String:t=>{try{return Array.from(document.querySelectorAll(t))}catch{return[]}},Array:t=>{const e=t;return e.every(t=>t instanceof Element)?e:[]}}}),this.register({name:"Array",hyperscriptType:"array",tsType:"unknown[]",isType:t=>Array.isArray(t),defaultValue:[],description:"Array of values",coerceFrom:{String:t=>{const e=t;try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map(t=>t.trim())},ElementList:t=>t,NodeList:t=>Array.from(t),Object:t=>Object.values(t)}}),this.register({name:"Object",hyperscriptType:"object",tsType:"Record<string, unknown>",isType:t=>!("object"!=typeof t||null===t||Array.isArray(t)||t instanceof Element),defaultValue:{},description:"Plain JavaScript object",coerceFrom:{String:t=>{try{const e=JSON.parse(t);if("object"==typeof e&&null!==e&&!Array.isArray(e))return e}catch{}return null},Array:t=>{const e={};return t.forEach((t,r)=>{e[r+""]=t}),e}}}),this.register({name:"Null",hyperscriptType:"null",tsType:"null",isType:t=>null===t,defaultValue:null,description:"Null value"}),this.register({name:"Undefined",hyperscriptType:"undefined",tsType:"undefined",isType:t=>void 0===t,defaultValue:void 0,description:"Undefined value"}),this.register({name:"Function",hyperscriptType:"function",tsType:"Function",isType:t=>"function"==typeof t,defaultValue:null,description:"JavaScript function"}),this.register({name:"Event",hyperscriptType:"event",tsType:"Event",isType:t=>t instanceof Event,defaultValue:null,description:"DOM Event"}),this.register({name:"NodeList",hyperscriptType:"element-list",tsType:"NodeList",isType:t=>t instanceof NodeList,defaultValue:null,description:"DOM NodeList (typically from querySelectorAll)",coerceFrom:{Array:t=>null}}),this.register({name:"Unknown",hyperscriptType:"unknown",tsType:"unknown",isType:t=>1,defaultValue:null,description:"Unknown/any value type"})}};function _e(t){const e=Fe.get("String");return e?e.isType(t):"string"==typeof t}function qe(t){const e=Fe.get("Number");return e?e.isType(t):"number"==typeof t}function He(t){const e=Fe.get("Boolean");return e?e.isType(t):"boolean"==typeof t}function Ue(t){const e=Fe.get("Object");return e?e.isType(t):"object"==typeof t&&null!==t}function We(t){const e=Fe.get("Function");return e?e.isType(t):"function"==typeof t}function ze(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"style"in t}function Je(t){return t instanceof Element}const Ze=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function Ge(t,e){return Ze.has(e.toLowerCase())?t.hasAttribute(e):t.getAttribute(e)}const Xe={id:t=>t.id,classname:t=>t.className,class:t=>t.className,tagname:t=>t.tagName.toLowerCase(),innertext:t=>t.textContent?.trim(),innerHTML:t=>t.innerHTML,outerhtml:t=>t.outerHTML,value:t=>function(t){if(null===t||"object"!=typeof t||!("tagName"in t))return 0;const e=t.tagName;return"INPUT"===e||"SELECT"===e||"TEXTAREA"===e}(t)?t.value:void 0,checked:t=>function(t){return null!==t&&"object"==typeof t&&"tagName"in t&&"INPUT"===t.tagName}(t)?t.checked:void 0,disabled:t=>"disabled"in t?t.disabled:void 0,selected:t=>function(t){return null!=t&&"object"==typeof t&&"tagName"in t&&"OPTION"===t.tagName}(t)?t.selected:void 0,tabindex:t=>ze(t)?t.tabIndex:void 0,hidden:t=>ze(t)?t.hidden:void 0,style:t=>getComputedStyle(t),children:t=>Array.from(t.children),parent:t=>t.parentElement,firstchild:t=>t.firstElementChild,lastchild:t=>t.lastElementChild,nextsibling:t=>t.nextElementSibling,previoussibling:t=>t.previousElementSibling,values:t=>function(t){if(t instanceof HTMLFormElement)return new FormData(t);const e=new FormData;return t.querySelectorAll("input, select, textarea").forEach(t=>{const r=t.getAttribute("name");r&&"value"in t&&e.append(r,t.value)}),e}(t)};function Ye(t,e){if(e.startsWith("computed-")){const r=e.slice(9);return function(t){return t instanceof HTMLElement}(t)?getComputedStyle(t).getPropertyValue(r):void 0}if(e.startsWith("@"))return Ge(t,e.slice(1));const r=Xe[e.toLowerCase()];if(r)return r(t);if(function(t,e){return t.hasAttribute(e)}(t,e))return Ge(t,e);const n=t[e];return We(n)?n.bind(t):n}function Ke(t){if("string"==typeof t)return t;if(t&&"object"==typeof t){if("string"==typeof t.name)return t.name;if("string"==typeof t.value)return t.value}return t}function Qe(t){return t.me?.ownerDocument??("undefined"!=typeof document?document:null)}function tr(t,e){return e.locals?.has(t)?e.locals.get(t):e.globals?.has(t)?e.globals.get(t):e.variables?.has(t)?e.variables.get(t):"me"===t?e.me:"it"===t?e.it:"result"===t?e.result:void 0}async function er(t,e){if(t.includes(".")){const r=t.split(".");let n=tr(r[0],e);for(let t=1;r.length>t&&null!=n;t++)n=n[r[t]];return n}return tr(t,e)}async function rr(t,e){if(ut(`RESOLVE: Looking for '${t}' in context`,{hasInLocals:e.locals.has(t),localsKeys:Array.from(e.locals.keys()),value:e.locals.get(t)}),e.locals.has(t)){const r=e.locals.get(t);return ut(`RESOLVE: Found '${t}' in locals:`,r),r}if(e.globals&&e.globals.has(t)){const r=e.globals.get(t);return ut(`RESOLVE: Found '${t}' in globals:`,r),r}if(e.variables&&e.variables.has(t)){const r=e.variables.get(t);return ut(`RESOLVE: Found '${t}' in variables (legacy):`,r),r}const r=Number(t);if(!isNaN(r))return r;if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t.includes(".")){const r=t.split("."),n=r[0];let s=null;if(e.locals.has(n)?s=e.locals.get(n):e.globals&&e.globals.has(n)?s=e.globals.get(n):e.variables&&e.variables.has(n)&&(s=e.variables.get(n)),null!=s){for(let t=1;r.length>t;t++){if(null==s)return void ut(`RESOLVE: Property access failed at '${r[t-1]}'`);s=s[r[t]]}return ut(`RESOLVE: Property access '${t}' =`,s),s}}return t}async function nr(t,e){ut("EVAL: Evaluating expression:",t);const r=t.match(/^(.+?)\s*\?(?![\.\[])\s*(.+?)\s*:\s*(.+)$/);if(r){const[,t,n,s]=r;ut("EVAL: Parsed ternary:",{conditionExpr:t,trueExpr:n,falseExpr:s});const i=await rr(t.trim(),e);if(ut("EVAL: Ternary condition value:",i),i){const t=await rr(n.trim(),e);return ut("EVAL: Ternary returned true branch:",t),t}{const t=await rr(s.trim(),e);return ut("EVAL: Ternary returned false branch:",t),t}}const n=t.match(/^([a-zA-Z_$][a-zA-Z0-9_$]*|\d+(?:\.\d+)?)\s*([\+\-\*\/\%])\s*([a-zA-Z_$][a-zA-Z0-9_$]*|\d+(?:\.\d+)?)$/);if(n){const[,t,r,s]=n;ut("EVAL: Parsed arithmetic:",{left:t,operator:r,right:s});const i=await rr(t.trim(),e),o=await rr(s.trim(),e);ut("EVAL: Resolved values:",{leftValue:i,rightValue:o});const a=Number(i),c=Number(o);if(!isNaN(a)&&!isNaN(c)){let t;switch(r){case"+":t=a+c;break;case"-":t=a-c;break;case"*":t=a*c;break;case"/":t=a/c;break;case"%":t=a%c;break;default:t=a}return ut("EVAL: Arithmetic result:",t),t}}const s=await rr(t.trim(),e);return ut("EVAL: Fallback result:",s),s}function sr(t){if(Array.isArray(t)&&1===t.length&&(t=t[0]),null!==t&&"object"==typeof t&&"string"==typeof t.textContent){const e=t.value??t.textContent;if(null!=e){const t=(e+"").trim();if(""===t)return 0;const r=parseFloat(t);return isNaN(r)?t:r}return 0}return t}async function ir(t,e,r,n,s){try{const i=s(await n(t.object,r));if(null==i)throw Error("Cannot call method on null or undefined");const o=Ke(t.property);if(!o||"string"!=typeof o)throw Error("Invalid method name: "+o);const a=i[o];if("function"!=typeof a)throw Error(`Property "${o}" is not a function on ${i.constructor?.name||typeof i}`);const c=await Promise.all(e.map(t=>n(t,r)));return a.apply(i,c)}catch(t){if(t instanceof Error)throw t;throw Error("Failed to evaluate method call: "+t)}}class or{constructor(){this.expressionRegistry=new Map}registerCategory(t){Object.entries(t).forEach(([t,e])=>{this.expressionRegistry.set(t,e)})}unwrapSelectorResult(t){if(t instanceof NodeList&&t.length>0)return t[0];if(Array.isArray(t)&&t.length>0){const e=t[0];return"index"in t&&"input"in t?t:e instanceof Element||e instanceof Node?e:t}return t}async evaluate(t,e){if(!t)return ut("EVALUATOR: Received null/undefined node, returning null"),null;if(!t.type)throw console.error("EVALUATOR: Node missing type property:",t),Error("Node missing type property: "+JSON.stringify(t));switch(t.type){case"identifier":return this.evaluateIdentifier(t,e);case"literal":return this.evaluateLiteral(t,e);case"string":return t.value??"";case"memberExpression":return this.evaluateMemberExpression(t,e);case"binaryExpression":return this.evaluateBinaryExpression(t,e);case"unaryExpression":return this.evaluateUnaryExpression(t,e);case"callExpression":return this.evaluateCallExpression(t,e);case"selector":return this.evaluateSelector(t,e);case"dollarExpression":return this.evaluateDollarExpression(t,e);case"possessiveExpression":return this.evaluatePossessiveExpression(t,e);case"templateLiteral":return this.evaluateTemplateLiteral(t,e);case"arrayLiteral":return this.evaluateArrayLiteral(t,e);case"objectLiteral":return this.evaluateObjectLiteral(t,e);case"conditionalExpression":return this.evaluateConditionalExpression(t,e);case"cssSelector":return this.evaluateCSSSelector(t,e);case"propertyAccess":return this.evaluatePropertyAccess(t,e);case"propertyOfExpression":return this.evaluatePropertyOfExpression(t,e);case"contextReference":return this.evaluateContextReference(t,e);case"queryReference":return this.evaluateQueryReference(t,e);case"idSelector":return this.evaluateIdSelector(t,e);case"attributeAccess":return this.evaluateAttributeAccess(t,e);default:throw Error("Unsupported AST node type for evaluation: "+t.type)}}async evaluateWithResult(t,e){try{return Re(await this.evaluate(t,e))}catch(t){if(t instanceof Error){const e=t;if(e.isHalt||"HALT_EXECUTION"===e.message)return Ie({type:"halt"});if(e.isExit||"EXIT_COMMAND"===e.message)return Ie({type:"exit",returnValue:e.returnValue});if(e.isBreak)return Ie({type:"break"});if(e.isContinue)return Ie({type:"continue"});if(e.isReturn)return Ie({type:"return",returnValue:e.returnValue})}throw t}}async evaluateArrayLiteral(t,e){const r=t.elements||[],n=[];for(const t of r){const r=await this.evaluate(t,e);n.push(r)}return n}async evaluateObjectLiteral(t,e){const r=t.properties||[],n={};for(const t of r){let r;r="identifier"===t.key.type?t.key.name:"literal"===t.key.type?t.key.value+"":await this.evaluate(t.key,e)+"";const s=await this.evaluate(t.value,e);n[r]=s}return n}async evaluateConditionalExpression(t,e){return await this.evaluate(t.test,e)?this.evaluate(t.consequent,e):t.alternate?this.evaluate(t.alternate,e):void 0}async evaluateTemplateLiteral(t,e){return async function(t,e){let r=t.value||"";ut("TEMPLATE LITERAL: Evaluating",{template:r,node:t});const n=/\$([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)/g,s=[];let i;for(;null!==(i=n.exec(r));)"{"!==r[i.index+1]&&s.push({match:i[0],varName:i[1],index:i.index});for(let t=s.length-1;t>=0;t--){const{match:n,varName:i,index:o}=s[t],a=await er(i,e);ut(`TEMPLATE: $${i} resolved to`,a),r=r.slice(0,o)+((a??"")+"")+r.slice(o+n.length)}let o="",a=0;for(;r.length>a;){const t=r.indexOf("${",a);if(-1===t){o+=r.slice(a);break}o+=r.slice(a,t);let n=1,s=t+2;for(;r.length>s&&n>0;)"{"===r[s]&&n++,"}"===r[s]&&n--,n>0&&s++;if(0!==n)throw Error("Unterminated template expression in: "+r);const i=r.slice(t+2,s);let c;ut("TEMPLATE: Evaluating expression:",i);const l=i.trim();e.locals.has(l)?(c=e.locals.get(l),ut(`TEMPLATE: Found in locals: ${l} =`,c)):e.globals&&e.globals.has(l)?(c=e.globals.get(l),ut(`TEMPLATE: Found in globals: ${l} =`,c)):e.variables&&e.variables.has(l)?(c=e.variables.get(l),ut(`TEMPLATE: Found in variables (legacy): ${l} =`,c)):(c=await nr(i,e),ut(`TEMPLATE: Evaluated expression "${i}" =`,c)),o+=c+"",a=s+1}return o}(t,e)}async evaluateSimpleExpression(t,e){return nr(t,e)}async resolveValue(t,e){return rr(t,e)}async evaluateIdentifier(t,e){const{name:r,scope:n}=t;if("me"===r||"my"===r||"I"===r)return e.me;if("you"===r||"your"===r)return e.you;if("it"===r||"its"===r)return e.it;if("result"===r)return e.result;if("event"===r)return e.event;const s=this.expressionRegistry.get(r);return s?s.evaluate(e):"local"===n?e.locals?.has(r)?e.locals.get(r):void 0:"global"===n?e.globals?.has(r)?e.globals.get(r):"undefined"!=typeof window&&r in window?window[r]:void 0:e.locals?.has(r)?e.locals.get(r):e.globals?.has(r)?e.globals.get(r):e.variables?.has(r)?e.variables.get(r):"undefined"!=typeof globalThis&&r in globalThis?globalThis[r]:"undefined"!=typeof window&&r in window?window[r]:void 0}async evaluateLiteral(t,e){return t.value}async evaluateContextReference(t,e){const{contextType:r}=t;switch(r){case"me":return e.me;case"it":return e.result;case"you":return e.you;case"event":return e.event;case"body":return e.meta?.ownerDocument?.body||document?.body;case"detail":return e.event?.detail;case"target":return e.you||e.event?.target;case"sender":return e.event?.target;default:return e.locals&&e.locals.has(r)?e.locals.get(r):void ut("Unknown context reference type: "+r)}}async evaluateMemberExpression(t,e){const{object:r,property:n,computed:s}=t;if("identifier"===r.type&&["add","remove"].includes(r.name)){const t=r.name,s=Ke(n);if(!e.me)throw Error('Context element "me" is null');return void("add"===t?e.me.classList.add(s):"remove"===t&&e.me.classList.remove(s))}let i=await this.evaluate(r,e);if(s)return i[await this.evaluate(n,e)];{const t=Ke(n);if(Array.isArray(i)&&"string"==typeof t&&("length"===t||t in Array.prototype)||(i=this.unwrapSelectorResult(i)),"string"==typeof t){if(t.startsWith("computed-")){const e=t.substring(9);return i&&"undefined"!=typeof window&&i instanceof Element?window.getComputedStyle(i).getPropertyValue(e):void 0}if(t.startsWith("@")){const e=t.substring(1);return i&&"function"==typeof i.getAttribute?Ge(i,e):void 0}if(i&&i instanceof Element){if("previous"===t||"prev"===t)return i.previousElementSibling;if("next"===t)return i.nextElementSibling}}const e=i?.[t];return"function"==typeof e?e.bind(i):e}}coerceArithmeticOperand(t){return sr(t)}async evaluateBinaryExpression(t,e){return async function(t,e,r,n,s){const{operator:i,left:o,right:a}=t;if("in"===i&&"selector"===o.type){let t=o.value;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const s=n(await r(a,e));if(!s||"function"!=typeof s.querySelector)throw Error(`'in' operator requires a DOM element as the right operand (got: ${typeof s})`);const i=s.querySelectorAll(t);return Array.from(i)}if("in"===i&&"queryReference"===o.type){let t=o.selector;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const s=n(await r(a,e));if(!s||"function"!=typeof s.querySelector)throw Error(`'in' operator requires a DOM element as the right operand (got: ${typeof s})`);const i=s.querySelectorAll(t);return Array.from(i)}if("in"===i){let t=null,s=null;if("positionalExpression"===o.type){t=o.operator;const n=o.argument;"cssSelector"===n?.type?s=n.selector:"selector"===n?.type?s=n.value:"classSelector"===n?.type?s="."+n.className:"idSelector"===n?.type?s="#"+n.id:n&&(s=await r(n,e)+"")}else if("memberExpression"!==o.type||"identifier"!==o.object?.type||"first"!==o.object.name&&"last"!==o.object.name){if("callExpression"===o.type&&"identifier"===o.callee?.type&&("first"===o.callee.name||"last"===o.callee.name)){t=o.callee.name;const n=o.arguments?.[0];"selector"===n?.type?s=n.value:"cssSelector"===n?.type?s=n.selector:"classSelector"===n?.type?s="."+n.className:"idSelector"===n?.type?s="#"+n.id:n&&(s=await r(n,e)+"")}}else t=o.object.name,"identifier"===o.property?.type&&o.property.name&&(s="."+o.property.name);if(t&&s){const i=n(await r(a,e));if(!i||"function"!=typeof i.querySelectorAll)return;const o=i.querySelectorAll(s),c=Array.from(o);return"first"===t?c.length>0?c[0]:void 0:"last"===t?c.length>0?c[c.length-1]:void 0:c}}if("matches"===i&&("selector"===a.type||"cssSelector"===a.type||"classSelector"===a.type)){const t=await r(o,e),n=a.value||a.selector;if(t&&"function"==typeof t.matches)try{return t.matches(n)}catch{return 0}return 0}const c=await r(o,e),l=await r(a,e);if("has"===i||"have"===i){if(c instanceof Element){if("cssSelector"===a.type&&"class"===a.selectorType||"selector"===a.type&&a.value?.startsWith(".")){const t=a.selector?.slice(1)||a.value?.slice(1)||"";return c.classList.contains(t)}if("attributeAccess"===a.type||"attributeRef"===a.type){const t=a.attributeName||a.name||a.value?.replace(/^@/,"")||"";return c.hasAttribute(t)}if("cssSelector"===a.type&&"attribute"===a.selectorType){const t=(a.selector||a.value||"").replace(/^@/,"");return c.hasAttribute(t)}if("cssSelector"===a.type&&"id"===a.selectorType||"idSelector"===a.type){const t=(a.selector||a.value||"").replace(/^#/,"");return null!==c.querySelector("#"+CSS.escape(t))}if("selector"===a.type||"queryReference"===a.type){let t=a.value||a.selector||"";t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());try{return null!==c.querySelector(t)}catch{return 0}}if("cssSelector"===a.type){const t=a.selector||"";try{return null!==c.querySelector(t)}catch{return 0}}}return Array.isArray(c)?c.includes(l):"string"==typeof c?c.includes(l+""):0}switch(i){case">":case"is greater than":return c>l;case"<":case"is less than":return l>c;case">=":case"is greater than or equal to":return c>=l;case"<=":case"is less than or equal to":return l>=c;case"==":case"equals":case"is equal to":return c==l;case"===":case"is really equal to":case"really equals":return c===l;case"!=":case"is not equal to":return c!=l;case"!==":case"is not really equal to":return c!==l;case"+":{const t=sr(c),r=sr(l);if("string"==typeof t||"string"==typeof r){const n=s.get("stringConcatenation");if(n){ut("Using string concatenation for:",{leftValue:t,rightValue:r});const s=await n.evaluate(e,{left:t,right:r});return s.success?s.value:t+r}}else{const n=s.get("addition");if(n){ut("Using numeric addition for:",{leftValue:t,rightValue:r});const s=await n.evaluate(e,{left:t,right:r});return s.success?s.value:t+r}}return t+r}case"-":return sr(c)-sr(l);case"*":return sr(c)*sr(l);case"/":return sr(c)/sr(l);case"%":case"mod":return sr(c)%sr(l);case"as":const t="string"==typeof l?l:"identifier"===a.type?a.name:"literal"===a.type?a.value:l+"",r=s.get("as");return r?r.evaluate(e,c,t):c;case"&&":case"and":return c&&l;case"||":case"or":return c||l;case"is":return c===l;case"is not":return c!==l;case"is a":case"is an":switch("identifier"===a.type?a.name.toLowerCase():(l+"").toLowerCase()){case"string":return"string"==typeof c;case"number":return"number"==typeof c;case"boolean":return"boolean"==typeof c;case"object":return"object"==typeof c&&null!==c;case"array":return Array.isArray(c);case"function":return"function"==typeof c;case"null":return null===c;case"undefined":return void 0===c;default:const t="identifier"===a.type?a.name:l+"";return null!=c&&c.constructor?.name===t}case"is not a":case"is not an":switch("identifier"===a.type?a.name.toLowerCase():(l+"").toLowerCase()){case"string":return"string"!=typeof c;case"number":return"number"!=typeof c;case"boolean":return"boolean"!=typeof c;case"object":return!("object"==typeof c&&null!==c);case"array":return!Array.isArray(c);case"function":return"function"!=typeof c;case"null":return null!==c;case"undefined":return void 0!==c;default:const t="identifier"===a.type?a.name:l+"";return!(null!=c&&c.constructor?.name===t)}case"=":if("identifier"===o.type){const t=o.name;return"result"===t?e.result=l:"it"===t?e.it=l:"you"===t?e.you=l:e.locals.set(t,l),l}throw Error("Left side of assignment must be an identifier");case"contains":case"include":case"includes":return Array.isArray(c)?c.includes(l):"string"==typeof c?c.includes(l+""):c&&"function"==typeof c.matches?c.matches(l+""):0;case"match":case"matches":if(c&&"function"==typeof c.matches){const t="string"==typeof l?l:l+"";try{return c.matches(t)}catch{return 0}}return 0;case"in":const n="string"==typeof c?c:c+"",u=l;if(!u||"function"!=typeof u.querySelector){if(Array.isArray(u))return u.includes(c);if("object"==typeof u&&null!==u)return n in u;throw Error(`'in' operator requires a DOM element, array, or object as the right operand (got: ${typeof u})`)}return u.querySelector(n);case" ":return"string"==typeof c&&"string"==typeof l?{command:c,selector:l}:"identifier"===o.type&&"selector"===a.type?{command:o.name,selector:a.value}:l;default:throw Error(`Unsupported binary operator: "${i}" (length: ${i.length})`)}}(t,e,this.evaluate.bind(this),this.unwrapSelectorResult.bind(this),this.expressionRegistry,this.evaluateSelector.bind(this))}async evaluateUnaryExpression(t,e){const{operator:r,argument:n}=t,s=await this.evaluate(n,e);switch(r){case"not":case"!":const t=this.expressionRegistry.get("not");return t?t.evaluate(e,s):!s;case"no":const n=this.expressionRegistry.get("no");return n?n.evaluate(e,s):0;case"some":return null==s?0:"string"==typeof s||Array.isArray(s)||s instanceof NodeList||s instanceof HTMLCollection?s.length>0:"object"==typeof s?Object.keys(s).length>0:1;case"exists":const i=this.expressionRegistry.get("exists");return i?i.evaluate(e,s):null!=s;case"does not exist":const o=this.expressionRegistry.get("doesNotExist");return o?o.evaluate(e,s):null==s;case"-":return-s;case"+":return+s;default:throw Error("Unsupported unary operator: "+r)}}async evaluateCallExpression(t,e){return async function(t,e,r,n,s,i){const{callee:o,arguments:a,isConstructor:c}=t;if(c){const t=o.name,n=e.globals?.get(t)||window[t];if("function"==typeof n)return new n(...await Promise.all(a.map(t=>r(t,e))));throw Error("Unknown constructor: "+t)}if("memberExpression"===o.type||"propertyAccess"===o.type)return ir(o,a,e,r,n);const l=o.name||o,u=s.get(l);if(u){const t=["first","last","random","at"],n=["closest","previous","next"].includes(l),s=t.includes(l),o=await Promise.all(a.map(t=>n&&t&&"selector"===t.type&&"string"==typeof t.value?t.value:n&&t&&"identifier"===t.type&&"string"==typeof t.name?t.name:s&&t&&"selector"===t.type&&"string"==typeof t.value?i(t,e):r(t,e)));return u.evaluate(e,...o)}const h=e.globals?.get(l)||window[l];if("function"==typeof h)return h(...await Promise.all(a.map(t=>r(t,e))));throw Error("Unknown function: "+l)}(t,e,this.evaluate.bind(this),this.unwrapSelectorResult.bind(this),this.expressionRegistry,this.evaluateSelector.bind(this))}async evaluateMethodCall(t,e,r){return ir(t,e,r,this.evaluate.bind(this),this.unwrapSelectorResult.bind(this))}async evaluateSelector(t,e){return function(t,e){let r=t.value;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());const n=Qe(e);if(!n)return[];const s=n.querySelectorAll(r);return Array.from(s).filter(t=>t&&"object"==typeof t&&1===t.nodeType&&"string"==typeof t.tagName)}(t,e)}evaluateAttributeAccess(t,e){return e.me&&"function"==typeof e.me.getAttribute?Ge(e.me,t.attributeName):"@"+t.attributeName}getAvailableExpressions(){return Array.from(this.expressionRegistry.keys())}async evaluateDollarExpression(t,e){const r=await this.evaluate(t.expression,e);if("identifier"===t.expression.type){const r=t.expression.name;return/^\d+$/.test(r)?r:e.locals?.has(r)?e.locals.get(r):"me"===r&&e.me?e.me:"you"===r&&e.you?e.you:"it"===r&&e.it?e.it:"result"===r&&e.result?e.result:"undefined"!=typeof window&&"window"===r?window:e.globals?.has(r)?e.globals.get(r):void 0}return r}async evaluatePossessiveExpression(t,e){const{object:r,property:n}=t,s=this.unwrapSelectorResult(await this.evaluate(r,e));if(!s)return;const i=Ke(n);return"string"==typeof i&&Je(s)?Ye(s,i):s[i]}hasExpression(t){return this.expressionRegistry.has(t)}async evaluateCSSSelector(t,e){return function(t,e){let r=t.selector;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());const n=Qe(e);if(!n)return"id"===t.selectorType?null:[];if("id"===t.selectorType){const t=r.startsWith("#")?r.slice(1):r;return n.getElementById(t)}if("class"===t.selectorType){const t=r.replace(/:/g,"\\:"),e=n.querySelectorAll(t);return Array.from(e).filter(t=>t instanceof HTMLElement)}const s=n.querySelectorAll(r);return Array.from(s).filter(t=>t instanceof HTMLElement)}(t,e)}async evaluateIdSelector(t,e){return function(t,e){const r=Qe(e);if(!r)return null;const n=t.value.startsWith("#")?t.value.slice(1):t.value;return r.getElementById(n)}(t,e)}async evaluateQueryReference(t,e){return function(t,e){let r=t.selector;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());const n=Qe(e);if(!n)return[];try{return n.querySelectorAll(r)}catch{return n.createDocumentFragment().childNodes}}(t,e)}async evaluatePropertyAccess(t,e){const r=await this.evaluate(t.object,e),n=t.property;if(null==r)throw Error(`Cannot access property "${n.name||n.value}" of ${r}`);const s=n.name||n.value;if(!s)throw Error("Property name must be an identifier");try{let t;return t=Je(r)?Ye(r,s):r[s],"function"==typeof t?t.bind(r):t}catch(t){throw Error(`Error accessing property "${s}": ${t}`)}}async evaluatePropertyOfExpression(t,e){const r=t.property,n=r.name||r.value;if(!n)throw Error('Property name must be an identifier in "the X of Y" pattern');const s=this.unwrapSelectorResult(await this.evaluate(t.target,e));if(null==s)throw Error(`Cannot access property "${n}" of ${s}`);try{let t;return t=Je(s)?Ye(s,n):s[n],"function"==typeof t?t.bind(s):t}catch(t){throw Error(`Failed to access property "${n}" on target: ${t}`)}}}const ar={1:"one",2:"two",3:"three",4:"four",5:"five"};function cr(t,e,r,n){return t.length!==e?`${r} requires exactly ${s=e,ar[s]??s+""} argument${1===e?"":"s"}${n?` (${n})`:""}`:null;var s}function lr(t,e,r,n){return"string"!=typeof t[e]?`${r} ${n||"argument "+(e+1)} must be a string`:null}function ur(t,e,r){return cr(t,1,e,r)??lr(t,0,e,r)}function hr(t,e){return cr(t,2,e,"left, right")}function fr(){return null}function dr(t,e,r,n){return t.length>e?`${r} expression takes at most ${1===e?"one":e+""} argument${1===e?"":"s"}${n?` (${n})`:""}`:null}function pr(t,e,r,n,s){return e>t.length||t.length>r?`${n} requires ${e}-${r} arguments${s?` (${s})`:""}`:null}function mr(t,e,r,n=[]){return{type:t,message:e,suggestions:n,...r&&{path:r}}}const yr=("undefined"!=typeof process?1:0)||"undefined"!=typeof process&&"true"===process.env.HYPERFIXI_SKIP_VALIDATION||"undefined"!=typeof globalThis&&"true"===globalThis.HYPERFIXI_SKIP_VALIDATION;let vr;function gr(){return vr({validate:t=>({success:1,data:t})})}function br(t,e){if(yr)return gr();const r=vr({validate:r=>{if("object"!=typeof r||null===r||Array.isArray(r))return{success:0,error:mr("type-mismatch","Expected object, received "+typeof r)};const n=r,s={};if(e?.strict){const e=Object.keys(t),r=Object.keys(n).filter(t=>!e.includes(t));if(r.length>0)return{success:0,error:mr("runtime-error","Unexpected properties: "+r.join(", "))}}for(const[e,r]of Object.entries(t)){const t=n[e];if(!(e in n)&&!r.t)return{success:0,error:mr("missing-argument",`Required field "${e}" is missing`,e)};const i=r.validate(t);if(!i.success)return{success:0,error:mr("validation-error",i.error.message||`Field "${e}" validation failed`,i.error.path?`${e}.${i.error.path}`:e)};void 0!==i.data&&(s[e]=i.data)}return{success:1,data:s}}});return r.strict=()=>br(t,{strict:1}),r}vr=function(t){return t.describe||(t.describe=function(t){return this.description=t,this}),t.safeParse||(t.safeParse=function(t){const e=this.validate(t);return e.success?{success:1,data:e.data}:{success:0,error:{errors:e.error?[e.error]:[]}}}),t.parse||(t.parse=function(t){const e=this.validate(t);if(e.success&&void 0!==e.data)return e.data;throw Error(e.error?.message||"Validation failed")}),t.optional||(t.optional=function(){const t=this.validate.bind(this),e={...this,t:1,validate:e=>null==e?{success:1,data:void 0}:t(e)};return vr(e)}),t.min||(t.min=function(t){const e=this.validate.bind(this),r={...this,validate:r=>{const n=e(r);return n.success&&"string"==typeof n.data&&t>n.data.length?{success:0,error:mr("runtime-error",`String must be at least ${t} characters long`)}:n}};return vr(r)}),t.max||(t.max=function(t){const e=this.validate.bind(this),r={...this,validate:r=>{const n=e(r);return n.success&&"string"==typeof n.data&&n.data.length>t?{success:0,error:mr("runtime-error",`String must be at most ${t} characters long`)}:n}};return vr(r)}),t.default||(t.default=function(t){const e=this.validate.bind(this),r={...this,i:t,o:1,validate:r=>void 0===r?{success:1,data:t}:e(r)};return vr(r)}),t.rest||(t.rest=function(t){return this}),t.refine||(t.refine=function(t,e){const r=this.validate.bind(this),n={...this,validate:n=>{const s=r(n);return s.success?t(s.data)?s:{success:0,error:mr("runtime-error",e||"Refinement validation failed")}:s}};return vr(n)}),new Proxy(t,{get:(t,e,r)=>e in t||"string"!=typeof e||e.startsWith("_")||"constructor"===e||"validate"===e||"then"===e?Reflect.get(t,e,r):function(...t){return r}})};const Er=t=>function(t={}){return yr?gr():vr({validate:e=>t.optional&&null==e?{success:1,data:void 0}:"string"!=typeof e?{success:0,error:mr("type-mismatch","Expected string, received "+typeof e)}:void 0!==t.minLength&&t.minLength>e.length?{success:0,error:mr("runtime-error",`String must be at least ${t.minLength} characters long`)}:void 0!==t.maxLength&&e.length>t.maxLength?{success:0,error:mr("runtime-error",`String must be at most ${t.maxLength} characters long`)}:t.pattern&&!t.pattern.test(e)?t.pattern.source.startsWith("^")&&t.pattern.source.endsWith("$")?{success:0,error:mr("runtime-error",`Expected "${t.pattern.source.slice(1,-1)}", received "${e}"`)}:{success:0,error:mr("missing-argument","String does not match required pattern")}:{success:1,data:e},...t.description&&{description:t.description}})}(t||{}),wr=t=>function(t={}){return yr?gr():vr({validate:e=>{const r=Number(e);return isNaN(r)?{success:0,error:mr("type-mismatch","Expected number, received "+typeof e)}:void 0!==t.min&&t.min>r?{success:0,error:mr("runtime-error","Number must be at least "+t.min)}:void 0!==t.max&&r>t.max?{success:0,error:mr("runtime-error","Number must be at most "+t.max)}:{success:1,data:r}}})}(t||{}),xr=()=>yr?gr():vr({validate:t=>"boolean"!=typeof t?{success:0,error:mr("type-mismatch","Expected boolean, received "+typeof t)}:{success:1,data:t}}),kr=t=>br(t),Ar=t=>function(t){return yr?gr():vr({validate:e=>{if(!Array.isArray(e))return{success:0,error:mr("type-mismatch","Expected array, received "+typeof e)};if(e.length!==t.length)return{success:0,error:mr("runtime-error",`Expected tuple of length ${t.length}, received length ${e.length}`)};const r=[];for(let n=0;t.length>n;n++){const s=t[n].validate(e[n]);if(!s.success)return{success:0,error:mr("runtime-error",s.error.message,s.error.path?`${n}.${s.error.path}`:""+n)};r.push(s.data)}return{success:1,data:r}}})}(t),Sr=()=>gr(),Cr=()=>gr(),Nr=()=>function(t,e="Custom validation failed"){return yr?gr():vr({validate:r=>t(r)?{success:1,data:r}:{success:0,error:mr("runtime-error",e)}})}(t=>void 0===t,"Expected undefined");class Tr{trackPerformance(t,e,r,n){t.evaluationHistory&&t.evaluationHistory.push({expressionName:this.name,category:this.category,input:e,output:r.success?r.value:r.error,timestamp:n,duration:Date.now()-n,success:r.success})}trackSimple(t,e,r,n=(r?"success":"error")){t.evaluationHistory&&t.evaluationHistory.push({expressionName:this.name,category:this.category,input:"operation",output:n,timestamp:e,duration:Date.now()-e,success:r})}toBoolean(t){return 0==t||0===t||0n===t||""===t||null==t||qe(t)&&isNaN(t)?0:1}success(t,e){return{success:1,value:t,type:e}}failure(t,e,r,n,s=[]){return{success:0,error:{name:t,type:e,message:r,code:n,suggestions:s}}}validationSuccess(){return{isValid:1,errors:[],suggestions:[]}}validationFailure(t,e,r=[]){return{isValid:0,errors:[{type:t,message:e,suggestions:r}],suggestions:r}}isElement(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"tagName"in t&&"string"==typeof t.tagName}inferType(t){return null===t?"null":void 0===t?"undefined":this.isElement(t)?"element":Array.isArray(t)?"array":Ue(t)?"object":typeof t}inferEvaluationType(t){return void 0===t?"Undefined":null===t?"Null":_e(t)?"String":qe(t)?"Number":He(t)?"Boolean":Array.isArray(t)?"Array":this.isElement(t)?"Element":"Object"}normalizeCollection(t){return Array.isArray(t)?t:t instanceof NodeList?Array.from(t):_e(t)?t.split(""):null==t?[]:Ue(t)&&Symbol.iterator in t?Array.from(t):[]}toNumber(t){if(qe(t)&&Number.isFinite(t))return t;if(_e(t)){const e=Number(t);return Number.isFinite(e)?e:null}return He(t)?t?1:0:null}}const Or=kr({selector:Er().min(1),single:xr().optional().default(0)});new class extends Tr{constructor(){super(...arguments),this.name="me",this.category="Reference",this.syntax="me",this.description="References the current element in the execution context",this.inputSchema=Nr(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=t.me,s=this.isElement(n)?n:null,i=this.success(s,"element");return this.trackPerformance(t,e,i,r),i}catch(n){const s=this.failure("MeExpressionError","runtime-error",n instanceof Error?n.message:'Failed to evaluate "me"',"ME_EVALUATION_FAILED",["Ensure element context is properly set",'Check if "me" is available in current scope']);return this.trackPerformance(t,e,s,r),s}}validate(t){return void 0!==t?this.validationFailure("type-mismatch",'"me" expression takes no arguments',['Use "me" without any parameters']):this.validationSuccess()}},new class extends Tr{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=Nr(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=t.you,s=this.isElement(n)?n:null,i=this.success(s,"element");return this.trackPerformance(t,e,i,r),i}catch(n){const s=this.failure("YouExpressionError","runtime-error",n instanceof Error?n.message:'Failed to evaluate "you"',"YOU_EVALUATION_FAILED",["Ensure target element is available in context",'Check if "you" is set by event or command']);return this.trackPerformance(t,e,s,r),s}}validate(t){return void 0!==t?this.validationFailure("type-mismatch",'"you" expression takes no arguments',['Use "you" without any parameters']):this.validationSuccess()}},new class extends Tr{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=Nr(),this.outputType="Any",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=t.it,s={success:1,value:n,type:this.inferType(n)};return this.trackPerformance(t,e,s,r),s}catch(n){const s=this.failure("ItExpressionError","runtime-error",n instanceof Error?n.message:'Failed to evaluate "it"',"IT_EVALUATION_FAILED",['Ensure "it" is set by previous operation',"Check if context variable is available"]);return this.trackPerformance(t,e,s,r),s}}validate(t){return void 0!==t?this.validationFailure("type-mismatch",'"it" expression takes no arguments',['Use "it" without any parameters']):this.validationSuccess()}},new class extends Tr{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=Or,this.outputType="ElementList",this.metadata={category:"Reference",complexity:"medium"}}async evaluate(t,e){const r=Date.now();try{if(!this.isValidCSSSelector(e.selector)){const n=this.failure("CSSSelectorError","invalid-argument",`Invalid CSS selector: "${e.selector}"`,"INVALID_CSS_SELECTOR",["Check selector syntax","Use valid CSS selector patterns like .class, #id, tag[attr]","Avoid special characters that need escaping"]);return this.trackPerformance(t,e,n,r),n}let n;if(e.single)n=document.querySelector(e.selector);else{const t=Array.from(document.querySelectorAll(e.selector));n=t.length>0?t:null}const s={success:1,value:n,type:Array.isArray(n)?"element-list":"element"};return this.trackPerformance(t,e,s,r),s}catch(n){const s=this.failure("CSSSelectorError","runtime-error",n instanceof Error?n.message:"CSS selector evaluation failed","CSS_SELECTOR_EVALUATION_FAILED",["Check if selector is valid CSS","Ensure DOM is ready when query executes","Verify elements exist in document"]);return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);if(!e.success)return{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid input: "+t.message,suggestions:this.getValidationSuggestion(t.code??"unknown")}))??[],suggestions:["Provide valid CSS selector string","Check selector syntax"]};const{selector:r}=e.data;return this.isValidCSSSelector(r)?this.validationSuccess():this.validationFailure("syntax-error",`Invalid CSS selector syntax: "${r}"`,["Use .class for class selectors","Use #id for ID selectors","Use tag for element selectors","Use [attr] for attribute selectors"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Ensure input matches expected format"])}}isValidCSSSelector(t){try{return document.querySelector(t),1}catch{return 0}}getValidationSuggestion(t){return[{too_small:"CSS selector cannot be empty",invalid_type:"Selector must be a string",required:"CSS selector is required"}[t]||"Check input format and types"]}};const $r={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.me instanceof HTMLElement?t.me:null,validate:fr},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.you instanceof HTMLElement?t.you:null,validate:fr},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it,validate:fr},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it,validate:fr},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.result,validate:fr},querySelector:{name:"querySelector",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){const[r]=e;if("string"!=typeof r)throw Error("querySelector requires a string selector");return document.querySelector(r)},validate:t=>ur(t,"querySelector","selector")},querySelectorAll:{name:"querySelectorAll",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const r=e[0];if("string"!=typeof r)throw Error("querySelectorAll requires a string selector");const n=document.querySelectorAll(r);return Array.from(n)},validate:t=>ur(t,"querySelectorAll","selector")},getElementById:{name:"getElementById",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){const r=e[0];if("string"!=typeof r)throw Error("getElementById requires a string ID");return document.getElementById(r)},validate:t=>ur(t,"getElementById","ID")},getElementsByClassName:{name:"getElementsByClassName",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const r=e[0];if("string"!=typeof r)throw Error("getElementsByClassName requires a string class name");const n=document.getElementsByClassName(r);return Array.from(n)},validate:t=>ur(t,"getElementsByClassName","className")},closest:{name:"closest",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){let r=e[0];if(r&&"object"==typeof r&&"type"in r){const t=r;"identifier"===t.type&&t.name?r=t.name:"literal"===t.type&&"string"==typeof t.value&&(r=t.value)}if("string"!=typeof r)throw Error("closest requires a string selector");return t.me?t.me.closest(r):null},validate(t){if(1!==t.length)return"closest requires exactly 1 argument (selector)";const e=t[0];return"string"==typeof e||e&&"object"==typeof e&&"type"in e&&("identifier"===e.type||"literal"===e.type)?null:"closest selector must be a string or identifier"}},parent:{name:"parent",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.me?t.me.parentElement:null,validate:fr},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async t=>window,validate:fr},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async t=>document,validate:fr},elementWithSelector:{name:"elementWithSelector",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const r=e[0];if("string"!=typeof r)throw Error("Selector must be a string");const n=document.querySelectorAll(r);return Array.from(n)},validate:t=>ur(t,"elementWithSelector","selector")},styleRef:{name:"styleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const r=e[0],n=e[1];if("string"!=typeof r)throw Error("StyleRef requires a string property name");const s=n||t.me;if(s&&s instanceof HTMLElement){if(r.startsWith("computed-")){const t=r.substring(9);return getComputedStyle(s).getPropertyValue(t)||""}return s.style.getPropertyValue(r)||void 0}},validate:t=>pr(t,1,2,"styleRef","property, optional element")??lr(t,0,"styleRef","property")??(2===t.length&&t[1]&&"object"!=typeof t[1]?"styleRef element must be an HTMLElement":null)},possessiveStyleRef:{name:"possessiveStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const r=e[0],n=e[1];if("string"!=typeof r||"string"!=typeof n)throw Error("Possessive styleRef requires possessor and property strings");let s=null;if("my"===r&&t.me?s=t.me instanceof HTMLElement?t.me:null:"its"===r&&t.it&&(s=t.it instanceof HTMLElement?t.it:null),s){if(n.startsWith("computed-")){const t=n.substring(9);return getComputedStyle(s).getPropertyValue(t)||""}return s.style.getPropertyValue(n)||void 0}},validate:t=>cr(t,2,"possessiveStyleRef","possessor, property")??lr(t,0,"possessiveStyleRef","possessor")??lr(t,1,"possessiveStyleRef","property")},ofStyleRef:{name:"ofStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const r=e[0],n=e[1];if("string"!=typeof r||"string"!=typeof n)throw Error("Of styleRef requires property and reference strings");let s=null;if("me"===n&&t.me?s=t.me instanceof HTMLElement?t.me:null:"it"===n&&t.it&&(s=t.it instanceof HTMLElement?t.it:null),s){if(r.startsWith("computed-")){const t=r.substring(9);return getComputedStyle(s).getPropertyValue(t)||""}return s.style.getPropertyValue(r)||void 0}},validate:t=>cr(t,2,"ofStyleRef","property, reference")??lr(t,0,"ofStyleRef","property")??lr(t,1,"ofStyleRef","reference")}};class Lr{constructor(t=100,e=5e3){this.maxSize=t,this.ttl=e,this.cache=new Map,this.accessOrder=new Map,this.accessCounter=0}get(t){const e=this.cache.get(t);if(e){if(Date.now()-e.timestamp<=this.ttl)return e.accessCount++,this.accessOrder.set(t,++this.accessCounter),e.result;this.delete(t)}}set(t,e){this.maxSize>this.cache.size||this.cache.has(t)||this.evictLRU();const r={result:e,timestamp:Date.now(),accessCount:1};this.cache.set(t,r),this.accessOrder.set(t,++this.accessCounter)}delete(t){return this.accessOrder.delete(t),this.cache.delete(t)}clear(){this.cache.clear(),this.accessOrder.clear(),this.accessCounter=0}size(){return this.cache.size}evictLRU(){let t,e=1/0;for(const[r,n]of this.accessOrder)e>n&&(e=n,t=r);void 0!==t&&this.delete(t)}getStats(){const t=Array.from(this.cache.values()),e=Date.now();return{size:this.cache.size,maxSize:this.maxSize,hitRate:t.length>0?t.filter(t=>t.accessCount>1).length/t.length:0,avgAge:t.length>0?t.reduce((t,r)=>t+(e-r.timestamp),0)/t.length:0,totalAccesses:t.reduce((t,e)=>t+e.accessCount,0)}}}const Rr=new class{constructor(){this.domQueryCache=new Lr(200,3e3),this.exprResultCache=new Lr(500,2e3),this.cssMatchCache=new Lr(100,5e3),this.formValueCache=new Lr(50,1e3),this.hits=0,this.misses=0}querySelector(t){const e="querySelector:"+t,r=this.domQueryCache.get(e);if(void 0!==r)return this.hits++,r;this.misses++;const n=document.querySelector(t);return this.domQueryCache.set(e,n),n}querySelectorAll(t){const e="querySelectorAll:"+t,r=this.domQueryCache.get(e);if(void 0!==r)return this.hits++,r;this.misses++;const n=Array.from(document.querySelectorAll(t));return this.domQueryCache.set(e,n),n}getElementById(t){const e="getElementById:"+t,r=this.domQueryCache.get(e);if(void 0!==r)return this.hits++,r;this.misses++;const n=document.getElementById(t);return this.domQueryCache.set(e,n),n}getElementsByClassName(t){const e="getElementsByClassName:"+t,r=this.domQueryCache.get(e);if(void 0!==r)return this.hits++,r;this.misses++;const n=Array.from(document.getElementsByClassName(t));return this.domQueryCache.set(e,n),n}matches(t,e){const r=`matches:${this.getElementCacheKey(t)}:${e}`,n=this.cssMatchCache.get(r);if(void 0!==n)return this.hits++,n;this.misses++;const s=t.matches(e);return this.cssMatchCache.set(r,s),s}getExpressionResult(t){const e=this.exprResultCache.get(t);if(void 0!==e)return this.hits++,e;this.misses++}setExpressionResult(t,e){this.exprResultCache.set(t,e)}getFormValue(t){const e=this.getElementCacheKey(t),r=this.formValueCache.get("formValue:"+e);if(void 0!==r)return this.hits++,r;this.misses++}setFormValue(t,e){const r=this.getElementCacheKey(t);this.formValueCache.set("formValue:"+r,e)}invalidateElementCache(t){const e=this.getElementCacheKey(t);for(const t of[this.domQueryCache,this.cssMatchCache,this.formValueCache])for(const r of Array.from(t.cache.keys()))"string"==typeof r&&r.includes(e)&&t.delete(r)}invalidateAll(){this.domQueryCache.clear(),this.exprResultCache.clear(),this.cssMatchCache.clear(),this.formValueCache.clear(),this.hits=0,this.misses=0}getElementCacheKey(t){if(t.id)return"#"+t.id;const e=Array.from(t.classList).sort().join("."),r=this.getElementPosition(t);return`${t.tagName.toLowerCase()}${e?"."+e:""}@${r}`}getElementPosition(t){return""+Array.from(t.parentElement?.children||[]).indexOf(t)}getPerformanceStats(){const t=this.hits+this.misses;return{hits:this.hits,misses:this.misses,hitRate:Math.round(100*(t>0?this.hits/t*100:0))/100,domQueryCache:this.domQueryCache.getStats(),exprResultCache:this.exprResultCache.getStats(),cssMatchCache:this.cssMatchCache.getStats(),formValueCache:this.formValueCache.getStats()}}cleanup(){const t=Date.now();[this.domQueryCache,this.exprResultCache,this.cssMatchCache,this.formValueCache].forEach(e=>{Array.from(e.cache.entries()).forEach(([r,n])=>{t-n.timestamp>e.ttl&&e.delete(r)})})}};"undefined"!=typeof window&&setInterval(()=>{Rr.cleanup()},1e4);const Ir=new class{constructor(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0},this.startTimes=new Map}startTimer(t){this.startTimes.set(t,performance.now())}endTimer(t){const e=this.startTimes.get(t);if(e){const r=performance.now()-e;return this.startTimes.delete(t),r}return 0}recordTokenization(t){this.metrics.tokenizationTime+=t}recordEvaluation(t){this.metrics.evaluationTime+=t}updateCacheMetrics(){const t=Rr.getPerformanceStats();this.metrics.cacheHitRate=t.hitRate}getMetrics(){return this.updateCacheMetrics(),{...this.metrics}}reset(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0}}};function jr(){Rr.cleanup(),Ir.getMetrics().memoryUsage>52428800&&Ir.reset()}let Mr=null;function Dr(t,e){if("number"==typeof t){if(!Number.isFinite(t))throw Error(`${e} must be a finite number, got ${t}`);return t}if("string"==typeof t){const r=t.trim();if(""===r)return 0;const n=parseFloat(r);if(isNaN(n))throw Error(`${e} cannot be converted to number: "${t}"`);return n}if("boolean"==typeof t)return t?1:0;if(null==t)return 0;if("object"==typeof t&&null!==t){if(Array.isArray(t)&&1===t.length){const r=t[0];if(Array.isArray(r))throw Error(e+" is a nested array, cannot convert to number");return Dr(r,e)}if("string"==typeof t.textContent||"value"in t){const e=t.value??t.textContent;if(null!=e){const t=(e+"").trim();if(""===t)return 0;const r=parseFloat(t);if(!isNaN(r))return r}}const r=t.valueOf();if("number"==typeof r&&Number.isFinite(r))return r}throw Error(`${e} cannot be converted to number: ${typeof t}`)}function Pr(t){if("number"==typeof t)return Number.isFinite(t)?t:null;if("string"==typeof t){const e=t.trim();if(""===e)return 0;const r=parseFloat(e);return isNaN(r)?null:r}return"boolean"==typeof t?t?1:0:null==t?0:null}function Vr(t,e,r){if("==="===r)return t===e;if("!=="===r)return t!==e;if(null==t||null==e)return function(t,e,r){if(null==t&&null==e)switch(r){case"==":case">=":case"<=":return 1;default:return 0}switch(r){case"==":case">":case"<":case">=":case"<=":default:return 0;case"!=":return 1}}(t,e,r);const[n,s]=function(t,e){if("number"==typeof t&&"number"==typeof e)return[t,e];if("string"==typeof t&&"string"==typeof e){const r=parseFloat(t),n=parseFloat(e);return isNaN(r)||isNaN(n)?[t,e]:[r,n]}const r=Pr(t),n=Pr(e);return null!==r&&null!==n?[r,n]:[t+"",e+""]}(t,e);switch(r){case">":return n>s;case"<":return s>n;case">=":return n>=s;case"<=":return s>=n;case"==":return Br(t,e);case"!=":return!Br(t,e);default:return 0}}function Br(t,e){if(t===e)return 1;if(typeof t==typeof e)return"string"==typeof t||"number"==typeof t?t===e:0;if("number"==typeof t&&"string"==typeof e){const r=parseFloat(e);return!isNaN(r)&&t===r}if("string"==typeof t&&"number"==typeof e){const r=parseFloat(t);return!isNaN(r)&&r===e}return"boolean"==typeof t?Br(t?1:0,e):"boolean"==typeof e?Br(t,e?1:0):t+""==e+""}function Fr(t,e,r,n,s,i=1,o){return e&&"object"==typeof e&&"evaluationHistory"in e&&Array.isArray(e.evaluationHistory)&&e.evaluationHistory.push({expressionName:t.name,category:t.category,input:r,output:n,timestamp:s,duration:Date.now()-s,success:i,...void 0!==o&&{error:o}}),n}"undefined"!=typeof window&&function(t=3e4){Mr&&clearInterval(Mr),Mr=setInterval(jr,t)}();const _r=kr({left:Sr().describe("Left operand value"),right:Sr().describe("Right operand value")}).strict(),qr=kr({operand:Sr().describe("Operand value to negate")}).strict();function Hr(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType}new class extends Tr{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=_r,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:0,error:n.errors[0]};const s=this.toBoolean(e.left);if(!s)return this.trackSimple(t,r,1,"boolean"),this.success(0,"boolean");const i=this.toBoolean(e.right),o=s&&i;return this.trackSimple(t,r,1,"boolean"),this.success(o,"boolean")}catch(e){return this.trackSimple(t,r,0),this.failure("AndExpressionError","runtime-error","Logical AND operation failed: "+(e instanceof Error?e.message:e+""),"AND_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid AND operation input: "+t.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends Tr{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=_r,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:0,error:n.errors[0]};const s=this.toBoolean(e.left);if(s)return this.trackSimple(t,r,1,"boolean"),this.success(1,"boolean");const i=this.toBoolean(e.right),o=s||i;return this.trackSimple(t,r,1,"boolean"),this.success(o,"boolean")}catch(e){return this.trackSimple(t,r,0),this.failure("OrExpressionError","runtime-error","Logical OR operation failed: "+(e instanceof Error?e.message:e+""),"OR_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid OR operation input: "+t.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends Tr{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=qr,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:0,error:n.errors[0]};const s=!this.toBoolean(e.operand);return this.trackSimple(t,r,1,"boolean"),this.success(s,"boolean")}catch(e){return this.trackSimple(t,r,0),this.failure("NotExpressionError","runtime-error","Logical NOT operation failed: "+(e instanceof Error?e.message:e+""),"NOT_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid NOT operation input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a single operand","Ensure operand is a valid value"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}};const Ur=Ar([Sr(),Sr()]),Wr=Ar([Sr(),Er()]),zr={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(t,e,r){const n=Date.now();try{return Fr(this,t,[e,r],e==r,n)}catch(s){throw Fr(this,t,[e,r],0,n,0,s instanceof Error?s:Error(s+"")),s}},validate:t=>hr(t,"equals"),inputSchema:Ur,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"value is 5",description:"Check if value equals 5 using loose equality",expectedOutput:1,context:{result:5}},{input:'"5" == 5',description:'String "5" equals number 5 with type coercion',expectedOutput:1}],relatedExpressions:["strictEquals","notEquals"],performance:{averageTime:.001,complexity:"O(1)"}},documentation:{summary:"Compares two values for loose equality, allowing type coercion",parameters:[{name:"left",type:"unknown",description:"Left operand for comparison",optional:0,examples:["5",'"hello"',"true","null"]},{name:"right",type:"unknown",description:"Right operand for comparison",optional:0,examples:["5",'"hello"',"true","null"]}],returns:{type:"Boolean",description:"True if values are loosely equal, false otherwise",examples:["true","false"]},examples:[{title:"Basic equality check",code:"if my.value is 10",explanation:"Check if element value equals 10",output:"Boolean result"},{title:"Type coercion",code:'if "5" == 5',explanation:'String "5" equals number 5 with automatic type conversion',output:"true"},{title:"Null checks",code:"if value is null",explanation:"Check if value is null or undefined",output:"Boolean result"}],seeAlso:["strictEquals","notEquals","matches"],tags:["comparison","equality","logic","type-coercion"]}},Jr={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=e===r;return n&&Fr(this,t,[e,r],i,s),i},validate:t=>hr(t,"strictEquals")},Zr={name:"notEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=","is not","does not equal"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=e!=r;return n&&Fr(this,t,[e,r],i,s),i},validate:t=>hr(t,"notEquals")},Gr={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=e!==r;return n&&Fr(this,t,[e,r],i,s),i},validate:t=>hr(t,"strictNotEquals")},Xr={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=Vr(e,r,"<");return n&&Fr(this,t,[e,r],i,s),i},validate:t=>hr(t,"lessThan")},Yr={name:"lessThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<=","is less than or equal to"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=Vr(e,r,"<=");return n&&Fr(this,t,[e,r],i,s),i},validate:t=>hr(t,"lessThanOrEqual")},Kr={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=Vr(e,r,">");return n&&Fr(this,t,[e,r],i,s),i},validate:t=>hr(t,"greaterThan")},Qr={name:"greaterThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">=","is greater than or equal to"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=Vr(e,r,">=");return n&&Fr(this,t,[e,r],i,s),i},validate:t=>hr(t,"greaterThanOrEqual")},tn={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(t,e,r){const n=Date.now();try{return Fr(this,t,[e,r],e&&r,n)}catch(s){throw Fr(this,t,[e,r],0,n,0,s instanceof Error?s:Error(s+"")),s}},validate:t=>hr(t,"and"),inputSchema:Ur,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"true and false",description:"Logical AND of boolean values",expectedOutput:0},{input:"name and age",description:"Both name and age must be truthy",expectedOutput:1,context:{variables:new Map([["name","John"],["age",25]])}}],relatedExpressions:["or","not"],performance:{averageTime:.001,complexity:"O(1)"}},documentation:{summary:"Logical AND operation that returns true only if both operands are truthy",parameters:[{name:"left",type:"unknown",description:"Left operand (evaluated for truthiness)",optional:0,examples:["true","name","5",'"hello"']},{name:"right",type:"unknown",description:"Right operand (evaluated for truthiness)",optional:0,examples:["false","age","0",'""']}],returns:{type:"Boolean",description:"True if both operands are truthy, false otherwise",examples:["true","false"]},examples:[{title:"Form validation",code:"if name and email",explanation:"Check if both name and email have values",output:"Boolean result"},{title:"Multiple conditions",code:"if age > 18 and hasLicense",explanation:"Combine multiple conditions",output:"Boolean result"},{title:"Short-circuit evaluation",code:"if element and element.value",explanation:"Check element exists before accessing properties",output:"Boolean result"}],seeAlso:["or","not","exists"],tags:["logic","boolean","conditions","validation"]}},en={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=e||r;return n&&Fr(this,t,[e,r],i,s),i},validate:t=>hr(t,"or")},rn={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],async evaluate(t,e){const r=t.evaluationHistory,n=r?Date.now():0,s=!e;return r&&Fr(this,t,[e],s,n),s},validate:t=>cr(t,1,"not","operand")},nn={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],async evaluate(t,e){const r=t.evaluationHistory,n=r?Date.now():0;let s;return s=null==e?1:_e(e)||Array.isArray(e)||e instanceof NodeList?0===e.length:e instanceof Node||e instanceof Element?0:Ue(e)?0===Object.keys(e).length:0,r&&Fr(this,t,[e],s,n),s},validate:t=>cr(t,1,"isEmpty","value")},sn={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],async evaluate(t,e){const r=t.evaluationHistory,n=r?Date.now():0;let s;return s=null==e||0==e?1:Array.isArray(e)||e instanceof NodeList?0===e.length:_e(e)||e instanceof Node||e instanceof Element?0:Ue(e)?0===Object.keys(e).length:0,r&&Fr(this,t,[e],s,n),s},validate:t=>cr(t,1,"no","value")},on={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],async evaluate(t,e){const r=t.evaluationHistory,n=r?Date.now():0,s=!await nn.evaluate(t,e);return r&&Fr(this,t,[e],s,n),s},validate:t=>cr(t,1,"isNotEmpty","value")},an={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],async evaluate(t,e){const r=t.evaluationHistory,n=r?Date.now():0,s=null!=e;return r&&Fr(this,t,[e],s,n),s},validate:t=>cr(t,1,"exists","value")},cn={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],async evaluate(t,e){const r=t.evaluationHistory,n=r?Date.now():0,s=null==e;return r&&Fr(this,t,[e],s,n),s},validate:t=>cr(t,1,"doesNotExist","value")},ln={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0;let i;if(e&&r){if(Hr(e)&&Hr(r))return i=e.contains(r),n&&Fr(this,t,[e,r],i,s),i;if(_e(e)&&e.match(/^[.#][\w-]+$/)){const o=document.querySelector(e);if(o&&Hr(r))return i=o.contains(r),n&&Fr(this,t,[e,r],i,s),i;if(o&&_e(r)&&r.match(/^[.#][\w-]+$/)){const a=document.querySelector(r);return i=a?o.contains(a):0,n&&Fr(this,t,[e,r],i,s),i}}if(_e(r)&&r.match(/^[.#][\w-]+$/)&&Hr(e)){const o=document.querySelector(r);return i=o?e.contains(o):0,n&&Fr(this,t,[e,r],i,s),i}}return i=_e(e)&&_e(r)||Array.isArray(e)?e.includes(r):"undefined"!=typeof NodeList&&e instanceof NodeList?Array.from(e).includes(r):Ue(e)&&_e(r)?r in e:0,n&&Fr(this,t,[e,r],i,s),i},validate:t=>cr(t,2,"contains","container, value")},un={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=!await ln.evaluate(t,e,r);return n&&Fr(this,t,[e,r],i,s),i},validate:t=>cr(t,2,"doesNotContain","container, value")},hn={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=_e(e)&&_e(r)?e.startsWith(r):0;return n&&Fr(this,t,[e,r],i,s),i},validate:t=>cr(t,2,"startsWith","str, prefix")},fn={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=_e(e)&&_e(r)?e.endsWith(r):0;return n&&Fr(this,t,[e,r],i,s),i},validate:t=>cr(t,2,"endsWith","str, suffix")},dn={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(t,e,r){const n=Date.now();try{let s;if(e instanceof Element&&_e(r)){const t=r;if(t.startsWith(".")||t.startsWith("#")||t.startsWith(":")||t.startsWith("[")||/^[a-zA-Z][\w-]*$/.test(t))try{s=function(t,e){return Rr.matches(t,e)}(e,t)}catch(t){s=0}else s=0}else if(_e(e)&&_e(r)){const t=e,n=r;try{s=(n.startsWith("/")&&n.endsWith("/")?RegExp(n.slice(1,-1)):RegExp(n)).test(t)}catch(e){s=t.includes(n)}}else s=0;return Fr(this,t,[e,r],s,n)}catch(s){throw Fr(this,t,[e,r],0,n,0,s instanceof Error?s:Error(s+"")),s}},validate:t=>cr(t,2,"matches","element, selector"),inputSchema:Wr,metadata:{category:"Logical",complexity:"medium",sideEffects:["dom-query"],dependencies:[],returnTypes:["Boolean"],examples:[{input:'element matches ".active"',description:"Check if element has active class",expectedOutput:1},{input:'text matches "/^hello/"',description:'Check if text starts with "hello" using regex',expectedOutput:1,context:{variables:new Map([["text","hello world"]])}}],relatedExpressions:["contains","startsWith","endsWith"],performance:{averageTime:.5,complexity:"O(n)"}},documentation:{summary:"Tests if element matches CSS selector or string matches regex pattern",parameters:[{name:"element",type:"Element | string",description:"DOM element or string to test",optional:0,examples:["<div>",'"hello world"',"me","target"]},{name:"selector",type:"string",description:"CSS selector or regex pattern to match against",optional:0,examples:['".active"','"#navbar"','"/^hello/"','"\\\\d+"']}],returns:{type:"Boolean",description:"True if element matches selector/pattern",examples:["true","false"]},examples:[{title:"CSS class matching",code:'if me matches ".active"',explanation:'Check if current element has "active" class',output:"Boolean result"},{title:"Attribute matching",code:'if target matches "[data-role=\\"button\\"]"',explanation:"Check if element has specific data attribute",output:"Boolean result"},{title:"Regex pattern matching",code:'if email matches "/^[^@]+@[^@]+\\\\.[^@]+$/"',explanation:"Validate email format with regex",output:"Boolean result"},{title:"Complex CSS selector",code:'if element matches ".card:hover .button"',explanation:"Match complex CSS selector with pseudo-classes",output:"Boolean result"}],seeAlso:["contains","startsWith","endsWith","querySelector"],tags:["pattern","css","regex","validation","dom"]}},pn={name:"has",category:"Logical",evaluatesTo:"Boolean",operators:["has","have"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0;let i=0;if(e instanceof Element&&_e(r)){const t=r;t.startsWith(".")?i=e.classList.contains(t.slice(1)):t.startsWith("[")&&t.endsWith("]")&&(i=e.hasAttribute(t.slice(1,-1)))}return n&&Fr(this,t,[e,r],i,s),i},validate:t=>cr(t,2,"has","element, selector")},mn={name:"doesNotHave",category:"Logical",evaluatesTo:"Boolean",operators:["does not have"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=!await pn.evaluate(t,e,r);return n&&Fr(this,t,[e,r],i,s),i},validate:t=>cr(t,2,"doesNotHave","element, selector")},yn={equals:zr,strictEquals:Jr,notEquals:Zr,strictNotEquals:Gr,lessThan:Xr,lessThanOrEqual:Yr,greaterThan:Kr,greaterThanOrEqual:Qr,and:tn,or:en,not:rn,no:sn,isEmpty:nn,isNotEmpty:on,exists:an,doesNotExist:cn,contains:ln,doesNotContain:un,startsWith:hn,endsWith:fn,matches:dn,has:pn,doesNotHave:mn};function vn(t,e,r,n,s="runtime-error"){return{success:0,error:{name:t+"ConversionError",type:s,message:r,code:e,suggestions:n}}}function gn(t,e){return{success:1,value:t,type:e}}function bn(t,e){return`${t}: ${e instanceof Error?e.message:e+""}`}const En={Array:(t,e)=>{try{return Array.isArray(t)?gn(t,"array"):t instanceof NodeList?gn(Array.from(t),"array"):gn(null==t?[]:[t],"array")}catch(t){return vn("Array","ARRAY_CONVERSION_FAILED",bn("Failed to convert value to Array",t),["Check if value is iterable","Ensure value is not circular reference"])}},String:(t,e)=>{try{return null==t?gn("","string"):_e(t)?gn(t,"string"):Ue(t)?gn(JSON.stringify(t),"string"):gn(t+"","string")}catch(t){return vn("String","STRING_CONVERSION_FAILED",bn("Failed to convert value to String",t),["Check if object has circular references","Ensure value is serializable"])}},Boolean:(t,e)=>{try{if(He(t))return gn(t,"boolean");if(null==t)return gn(0,"boolean");if(_e(t)){const e=t.toLowerCase().trim();return gn("false"!==e&&"0"!==e&&""!==e,"boolean")}return qe(t)?gn(0!==t&&!isNaN(t),"boolean"):gn(!!t,"boolean")}catch(t){return vn("Boolean","BOOLEAN_CONVERSION_FAILED",bn("Failed to convert value to Boolean",t),["Use explicit true/false values","Check for unexpected data types"])}},Number:(t,e)=>{try{if(qe(t))return gn(t,"number");if(null==t)return gn(0,"number");const e=Number(t);return isNaN(e)?vn("Number","INVALID_NUMBER",`Cannot convert "${t}" to a valid number`,["Check if value contains non-numeric characters","Use a valid numeric format"],"invalid-argument"):gn(e,"number")}catch(t){return vn("Number","NUMBER_CONVERSION_FAILED",bn("Failed to convert value to Number",t),["Ensure value is convertible to number","Check for special characters"])}},Int:(t,e)=>{const r=En.Number(t,e);return r.success?gn(Math.trunc(r.value),"number"):r},Float:(t,e)=>{const r=En.Number(t,e);return r.success?gn(parseFloat(""+r.value),"number"):r},Date:(t,e)=>{try{if(t instanceof Date)return gn(t,"object");if(null==t)return gn(new Date(""),"object");if(_e(t)&&/^\d{4}-\d{2}-\d{2}$/.test(t)){const[e,r,n]=t.split("-").map(Number);return gn(new Date(e,r-1,n),"object")}const e=new Date(t);return isNaN(e.getTime())?vn("Date","INVALID_DATE",`Cannot convert "${t}" to a valid date`,["Use ISO 8601 format (YYYY-MM-DD)","Check date string format","Ensure date values are valid"],"invalid-argument"):gn(e,"object")}catch(t){return vn("Date","DATE_CONVERSION_FAILED",bn("Failed to convert value to Date",t),["Check date format","Ensure value is a valid date string or timestamp"])}},JSON:(t,e)=>{try{return gn(JSON.stringify(t),"string")}catch(t){return vn("JSON","JSON_STRINGIFY_FAILED",bn("Failed to convert value to JSON",t),["Check for circular references","Ensure all properties are serializable","Remove functions and undefined values"])}},Object:(t,e)=>{try{if(Ue(t))return gn(t,"object");if(_e(t))try{return gn(JSON.parse(t),"object")}catch(t){return vn("Object","JSON_PARSE_FAILED",bn("Cannot parse JSON string",t),["Check JSON syntax","Ensure proper escaping of quotes","Validate JSON format"],"syntax-error")}return gn({},"object")}catch(t){return vn("Object","OBJECT_CONVERSION_FAILED",bn("Failed to convert value to Object",t),["Ensure value is valid JSON string or object","Check for syntax errors"])}},Values:(t,e)=>{try{if(t instanceof HTMLFormElement)return gn(An(t),"object");if(t instanceof HTMLElement){const e=t.querySelectorAll("input, select, textarea"),r={};return e.forEach(t=>{const e=t;if(e.name){const t=Sn(e);void 0!==t&&(r[e.name]=t)}}),gn(r,"object")}return gn({},"object")}catch(t){return vn("FormValues","FORM_VALUES_EXTRACTION_FAILED",bn("Failed to extract form values",t),["Ensure element is a form or contains form inputs","Check form structure","Verify input names are set"])}}},wn=kr({value:Cr(),type:Er().min(1)}),xn=kr({value:Cr(),type:Er().min(1)});new class extends Tr{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=wn,this.metadata={category:"Conversion",complexity:"medium",sideEffects:[],dependencies:[],returnTypes:["Any"],examples:[{input:'"123" as Int',description:"Convert string to integer",expectedOutput:123},{input:"form as Values",description:"Extract form values as object",expectedOutput:{name:"John",age:"25"}},{input:"[1,2,3] as JSON",description:"Convert array to JSON string",expectedOutput:"[1,2,3]"},{input:'"2023-12-25" as Date',description:"Parse date string",expectedOutput:new Date(2023,11,25)}],relatedExpressions:["is","Object","Array"],performance:{averageTime:1,complexity:"O(n)"}},this.documentation={summary:'Converts values between different types using the "as" keyword with comprehensive type safety',parameters:[{name:"value",type:"object",description:"The value to convert",optional:0,examples:['"123"',"form","[1,2,3]","true","null"]},{name:"type",type:"string",description:"Target conversion type",optional:0,examples:["Int","String","Boolean","Array","JSON","Object","Date","Values","HTML","Fragment"]}],returns:{type:"object",description:"Structured result with converted value or detailed error information",examples:['{ success: true, value: 123, type: "number" }',"{ success: false, error: { ... } }"]},examples:[{title:"String to number conversion",code:"if my.value as Int > 100",explanation:"Convert form input to integer for comparison",output:"Boolean result"},{title:"Form data extraction",code:"put closest <form /> as Values into result",explanation:"Extract all form values as structured object",output:'{ name: "John", age: "25", ... }'},{title:"Array to JSON serialization",code:"put items as JSON into storage",explanation:"Convert array to JSON string for storage",output:'"[1,2,3]"'},{title:"Date parsing with validation",code:"put my.dateInput as Date into event.detail.date",explanation:"Parse date input with automatic validation",output:"Date object or validation error"},{title:"Boolean conversion with smart parsing",code:'if "false" as Boolean then hide else show',explanation:"Parse string boolean values correctly",output:"false (not true like naive conversion)"}],seeAlso:["is","Values","JSON","Array","Object"],tags:["conversion","types","validation","forms","json","parsing"]}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:0,error:{name:"AsExpressionValidationError",type:"validation-error",message:n.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:n.suggestions}};const{value:s,type:i}=e;if(i.startsWith("Fixed")){const n=i.match(/^Fixed:(\d+)$/),o=n?parseInt(n[1],10):2,a=En.Number(s,t);if(!a.success)return a;const c={success:1,value:a.value.toFixed(o),type:"string"};return this.trackPerformance(t,e,c,r),c}let o=En[i];if(o){const n=o(s,t);return this.trackPerformance(t,e,n,r),n}const a={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON"}[i.toLowerCase()];if(a&&(o=En[a],o)){const n=o(s,t);return this.trackPerformance(t,e,n,r),n}const c={success:0,error:{name:"UnknownConversionTypeError",type:"validation-error",message:"Unknown conversion type: "+i,code:"UNKNOWN_CONVERSION_TYPE",suggestions:["Use supported types: String, Number, Boolean, Array, Object, Date, JSON, Values","Check type spelling and capitalization","See documentation for complete list of conversion types"]}};return this.trackPerformance(t,e,c,r),c}catch(n){const s={success:0,error:{name:"AsExpressionError",type:"runtime-error",message:"Conversion failed: "+(n instanceof Error?n.message:n+""),code:"CONVERSION_FAILED",suggestions:["Check value and type compatibility","Ensure value is convertible to target type"]}};return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?{isValid:1,errors:[],suggestions:[]}:{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:t.message,suggestions:["Expected valid input structure, got: "+t.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(t){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}},new class extends Tr{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=xn,this.metadata={category:"Conversion",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"42 is number",description:"Check if value is a number",expectedOutput:1},{input:"null is empty",description:"Check if value is empty/null",expectedOutput:1},{input:"element is Element",description:"Check if value is DOM element",expectedOutput:1,context:{element:"<div>...</div>"}}],relatedExpressions:["as","empty","exists"],performance:{averageTime:.1,complexity:"O(1)"}},this.documentation={summary:"Checks if a value is of a specific type with comprehensive type detection",parameters:[{name:"value",type:"object",description:"The value to check",optional:0,examples:["42","null","element",'"text"',"[]"]},{name:"type",type:"string",description:"Type name to check against",optional:0,examples:["number","string","boolean","array","object","element","empty","null"]}],returns:{type:"object",description:"Boolean result indicating type match",examples:['{ success: true, value: true, type: "boolean" }']},examples:[{title:"Number validation",code:"if my.age is number then proceed",explanation:"Check if form input is valid number",output:"Boolean result"},{title:"Empty check",code:"if result is empty then show message",explanation:"Check if result is null, undefined, or empty",output:"Boolean result"},{title:"Element validation",code:"if target is element then addClass",explanation:"Ensure target is valid DOM element before manipulation",output:"Boolean result"}],seeAlso:["as","empty","exists","null"],tags:["validation","types","checking","guards"]}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:0,error:{name:"IsExpressionValidationError",type:"validation-error",message:n.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:n.suggestions}};const{value:s,type:i}=e,o=i.toLowerCase();let a;switch(o){case"null":a=null===s;break;case"undefined":a=void 0===s;break;case"string":a=_e(s);break;case"number":a=qe(s)&&!isNaN(s);break;case"boolean":a=He(s);break;case"object":a=Ue(s);break;case"array":a=Array.isArray(s);break;case"function":a=We(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||Ue(s)&&0===Object.keys(s).length;break;default:a=s?.constructor?.name?.toLowerCase()===o}const c=this.success(a,"boolean");return this.trackPerformance(t,e,c,r),c}catch(n){const s=this.failure("IsExpressionError","type-mismatch","Type check failed: "+(n instanceof Error?n.message:n+""),"TYPE_CHECK_FAILED",["Check type name spelling","Ensure value is accessible"]);return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:t.message,suggestions:["Expected valid input structure, got: "+t.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(t){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}};const kn={Array:t=>Array.isArray(t)?t:t instanceof NodeList?Array.from(t):null==t?[]:[t],String:t=>null==t?"":_e(t)?t:Ue(t)?JSON.stringify(t):t+"",Boolean:t=>{if(He(t))return t;if(null==t)return 0;if(_e(t)){const e=t.toLowerCase().trim();return"false"===e||"0"===e||""===e?0:1}return qe(t)?0!==t&&!isNaN(t):!!t},Number:t=>{if(qe(t))return t;if(null==t)return 0;const e=Number(t);return isNaN(e)?0:e},Math:t=>{if(qe(t))return t;if(null==t)return 0;const e=(t+"").trim();if(!e)return 0;try{return function(t){if(t=t.replace(/\s/g,""),!/^[0-9+\-*/().]+$/.test(t))throw Error("Invalid characters in math expression");try{const e=Function(`"use strict"; return (${t})`)();if(!qe(e)||!isFinite(e))throw Error("Expression did not evaluate to a finite number");return e}catch(t){throw Error("Math expression evaluation failed: "+(t instanceof Error?t.message:t+""))}}(e)}catch(t){return console.warn("Math conversion failed:",t),0}},Int:t=>{const e=kn.Number(t);return Math.trunc(e)},Float:t=>{const e=kn.Number(t);return parseFloat(""+e)},Date:t=>{if(t instanceof Date)return t;if(null==t)return new Date(NaN);if(_e(t)&&/^\d{4}-\d{2}-\d{2}$/.test(t)){const[e,r,n]=t.split("-").map(Number);return new Date(e,r-1,n)}return new Date(t)},JSON:t=>{try{return JSON.stringify(t)}catch(t){return"{}"}},Object:t=>{if(Ue(t))return t;if(_e(t))try{return JSON.parse(t)}catch(t){return{}}return{}},Fragment:t=>{_e(t)||(t=kn.String(t));const e=document.createElement("template");return e.innerHTML=t+"",e.content},HTML:t=>_e(t)?t:t instanceof NodeList?Array.from(t).map(t=>t instanceof Element?t.outerHTML:t.textContent||"").join(""):Array.isArray(t)?t.map(t=>t instanceof Element?t.outerHTML:kn.String(t)).join(""):t instanceof Element?t.outerHTML:kn.String(t),Values:(t,e)=>{if(t instanceof HTMLFormElement)return An(t);if(t instanceof HTMLElement){const e=t.querySelectorAll("input, select, textarea"),r={};return e.forEach(t=>{t.name&&(r[t.name]=Sn(t))}),r}return{}},"Values:Form":(t,e)=>{const r=kn.Values(t,e);return""+new URLSearchParams(r)},"Values:JSON":(t,e)=>{const r=kn.Values(t,e);return JSON.stringify(r)}};function An(t){const e={};return t.querySelectorAll("input, select, textarea").forEach(t=>{const r=t;if(r.name){const t=Sn(r);void 0!==t&&(void 0!==e[r.name]?(Array.isArray(e[r.name])||(e[r.name]=[e[r.name]]),e[r.name].push(t)):e[r.name]=t)}}),e}function Sn(t){if(t instanceof HTMLInputElement)switch(t.type){case"checkbox":return t.checked;case"radio":return t.checked?t.value:void 0;case"number":case"range":return t.valueAsNumber;case"date":case"datetime-local":return t.valueAsDate;case"file":return t.files;default:return t.value}return t instanceof HTMLSelectElement&&t.multiple?Array.from(t.selectedOptions).map(t=>t.value):t.value}const Cn={as:{name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(t,...e){const[r,n]=e;if("string"!=typeof n)throw Error("Conversion type must be a string");if(n.startsWith("Fixed")){const{precision:t}=function(t){const e=t.match(/^Fixed(?::(\d+))?$/);return e?{precision:e[1]?parseInt(e[1],10):2}:{}}(n);return kn.Number(r).toFixed(t||2)}let s=kn[n];if(s)return s(r,t);const i={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON"}[n.toLowerCase()];return i&&(s=kn[i],s)?s(r,t):(console.warn("Unknown conversion type: "+n),r)},validate:t=>cr(t,2,"as","value, type")??lr(t,1,"as","conversion type")},is:{name:"is",category:"Conversion",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is a","is an"],async evaluate(t,...e){const[r,n]=e;if(!_e(n))throw Error("Type check requires a string type");switch(n.toLowerCase()){case"null":return null===r;case"undefined":return void 0===r;case"string":return _e(r);case"number":return qe(r)&&!isNaN(r);case"boolean":return He(r);case"object":return Ue(r);case"array":return Array.isArray(r);case"function":return We(r);case"date":return r instanceof Date;case"element":return r instanceof Element;case"node":return r instanceof Node;case"nodelist":return r instanceof NodeList;case"empty":return null==r||""===r||Array.isArray(r)&&0===r.length||Ue(r)&&0===Object.keys(r).length;default:return r?.constructor?.name?.toLowerCase()===n.toLowerCase()}},validate:t=>cr(t,2,"is","value, type")??lr(t,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(t,e)=>e,validate:t=>cr(t,1,"async","expression")}},Nn={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"},Tn=kr({collection:Sr().describe("Collection to operate on (array, NodeList, or string)")}).strict(),On=kr({collection:Sr().describe("Collection to access"),index:wr().describe("Index position to access")}).strict(),$n=kr({collection:Sr().describe("Collection to select random item from")}).strict();function Ln(t,e){let r=t.nextElementSibling;for(;r;){if(r.matches(e))return r;const t=r.querySelector(e);if(t)return t;r=r.nextElementSibling}const n=t.parentElement;return n&&n!==document.documentElement?Ln(n,e):null}function Rn(t,e){let r=t.previousElementSibling;for(;r;){const t=Array.from(r.querySelectorAll(e)).reverse();if(t.length>0)return t[0];if(r.matches(e))return r;r=r.previousElementSibling}const n=t.parentElement;return n&&n!==document.documentElement?Rn(n,e):null}function In(t){let e=0,r=t;for(;r&&r.parentElement;)e+=Array.from(r.parentElement.children).indexOf(r),r=r.parentElement,e+=1e3;return e}new class extends Tr{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=Tn,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:0,error:n.errors[0]};const s=this.normalizeCollection(e.collection),i=s.length>0?s[0]:void 0,o={success:1,value:i,type:Nn[this.inferEvaluationType(i)]};return this.trackPerformance(t,e,o,r),o}catch(n){const s=this.failure("FirstExpressionError","runtime-error","First operation failed: "+(n instanceof Error?n.message:n+""),"FIRST_OPERATION_FAILED");return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid first input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends Tr{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=Tn,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:0,error:n.errors[0]};const s=this.normalizeCollection(e.collection),i=s.length>0?s[s.length-1]:void 0,o={success:1,value:i,type:Nn[this.inferEvaluationType(i)]};return this.trackPerformance(t,e,o,r),o}catch(n){const s=this.failure("LastExpressionError","runtime-error","Last operation failed: "+(n instanceof Error?n.message:n+""),"LAST_OPERATION_FAILED");return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid last input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends Tr{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=On,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:0,error:n.errors[0]};const s=this.normalizeCollection(e.collection),i=this.normalizeIndex(e.index,s.length),o=i>=0&&s.length>i?s[i]:void 0,a={success:1,value:o,type:Nn[this.inferEvaluationType(o)]};return this.trackPerformance(t,e,a,r),a}catch(n){const s=this.failure("AtExpressionError","runtime-error","At operation failed: "+(n instanceof Error?n.message:n+""),"AT_OPERATION_FAILED");return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid at input: "+t.message,suggestions:[]}))??[],suggestions:["Provide collection and index parameters","Ensure index is a number"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}normalizeIndex(t,e){return 0>t?e+t:t}},new class extends Tr{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=$n,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:0,error:n.errors[0]};const s=this.normalizeCollection(e.collection);if(0===s.length){const n={success:1,value:void 0,type:"undefined"};return this.trackPerformance(t,e,n,r),n}const i=s[this.getSecureRandomIndex(s.length)],o={success:1,value:i,type:Nn[this.inferEvaluationType(i)]};return this.trackPerformance(t,e,o,r),o}catch(n){const s=this.failure("RandomExpressionError","runtime-error","Random operation failed: "+(n instanceof Error?n.message:n+""),"RANDOM_OPERATION_FAILED");return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid random input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}getSecureRandomIndex(t){if("undefined"!=typeof crypto&&crypto.getRandomValues){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]%t}return Math.floor(Math.random()*t)}};const jn={first:{name:"first",category:"Reference",evaluatesTo:"Any",operators:["first"],async evaluate(t,e){const r=void 0!==e?e:t.it;return null==r?null:Array.isArray(r)||r instanceof NodeList||r instanceof HTMLCollection?r.length>0?r[0]:null:r instanceof Element?r.children.length>0?r.children[0]:null:_e(r)?r.length>0?r[0]:null:Ue(r)&&"length"in r&&qe(r.length)&&r.length>0?r[0]:null},validate:t=>dr(t,1,"first","collection")},last:{name:"last",category:"Reference",evaluatesTo:"Any",operators:["last"],async evaluate(t,e){const r=void 0!==e?e:t.it;if(null==r)return null;if(Array.isArray(r))return r.length>0?r[r.length-1]:null;if(r instanceof NodeList||r instanceof HTMLCollection)return r.length>0?r[r.length-1]:null;if(r instanceof Element){const t=r.children;return t.length>0?t[t.length-1]:null}return _e(r)?r.length>0?r[r.length-1]:null:Ue(r)&&"length"in r&&qe(r.length)&&r.length>0?r[r.length-1]:null},validate:t=>dr(t,1,"last","collection")},at:{name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(t,...e){const[r,n]=e;if(!qe(r))throw Error("Index must be a number");const s=r,i=void 0!==n?n:t.it;if(null==i)return null;if(Array.isArray(i)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}if(i instanceof NodeList||i instanceof HTMLCollection){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}if(i instanceof Element){const t=i.children,e=0>s?t.length+s:s;return e>=0&&t.length>e?t[e]:null}if(_e(i)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}if(Ue(i)&&"length"in i&&qe(i.length)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}return null},validate:t=>pr(t,1,2,"at","index, optional collection")??function(t){return"number"!=typeof t[0]?"at index must be a number":null}(t)},next:{name:"next",category:"Reference",evaluatesTo:"Element",operators:["next"],async evaluate(t,...e){const[r,n]=e,s=n||t.me;return s&&s instanceof Element?r?Ln(s,r):s.nextElementSibling:null},validate:t=>dr(t,2,"next","optional selector, optional fromElement")||(1>t.length||null==t[0]||"string"==typeof t[0]?2>t.length||null==t[1]||t[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},previous:{name:"previous",category:"Reference",evaluatesTo:"Element",operators:["previous","prev"],async evaluate(t,...e){const[r,n]=e,s=n||t.me;return s&&s instanceof Element?r?Rn(s,r):s.previousElementSibling:null},validate:t=>dr(t,2,"previous","optional selector, optional fromElement")||(1>t.length||null==t[0]||"string"==typeof t[0]?2>t.length||null==t[1]||t[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},nextWithin:{name:"nextWithin",category:"Reference",evaluatesTo:"Element",operators:["next within"],async evaluate(t,...e){const[r,n,s]=e,i=s||t.me;if(!(i&&i instanceof Element))return null;const o=i.closest(n);return o?function(t,e,r){const n=Array.from(r.querySelectorAll(e)),s=In(t);for(const t of n)if(In(t)>s)return t;return null}(i,r,o):null},validate:t=>pr(t,2,3,"nextWithin","selector, withinSelector, optional fromElement")||("string"!=typeof t[0]?"selector must be a string":"string"!=typeof t[1]?"withinSelector must be a string":3>t.length||null==t[2]||t[2]instanceof Element?null:"fromElement must be an Element")},previousWithin:{name:"previousWithin",category:"Reference",evaluatesTo:"Element",operators:["previous within"],async evaluate(t,...e){const[r,n,s]=e,i=s||t.me;if(!(i&&i instanceof Element))return null;const o=i.closest(n);return o?function(t,e,r){const n=Array.from(r.querySelectorAll(e)),s=In(t);for(let t=n.length-1;t>=0;t--){const e=n[t];if(s>In(e))return e}return null}(i,r,o):null},validate:t=>pr(t,2,3,"previousWithin","selector, withinSelector, optional fromElement")||("string"!=typeof t[0]?"selector must be a string":"string"!=typeof t[1]?"withinSelector must be a string":3>t.length||null==t[2]||t[2]instanceof Element?null:"fromElement must be an Element")}},Mn=new Set(["__proto__","constructor","prototype"]),Dn={possessive:{name:"possessive",category:"Reference",evaluatesTo:"Any",operators:["'s","s"],async evaluate(t,...e){const[r,n]=e;if(null!=r){if("string"!=typeof n)throw Error("Property name must be a string");if(r instanceof Element)return Ye(r,n);if(Ue(r)){if(Mn.has(n))return;return r[n]}return r[n]}},validate:t=>cr(t,2,"possessive","element, property")??lr(t,1,"possessive","property name")},my:{name:"my",category:"Reference",evaluatesTo:"Any",operators:["my"],async evaluate(t,...e){const[r]=e;if(t.me){if("string"!=typeof r)throw Error("Property name must be a string");if(t.me instanceof Element)return Ye(t.me,r);if(Ue(t.me)){if(Mn.has(r))return;return t.me[r]}return t.me[r]}},validate:t=>ur(t,"my","property")},its:{name:"its",category:"Reference",evaluatesTo:"Any",operators:["its"],async evaluate(t,...e){const[r]=e;if(null==t.it)return;if("string"!=typeof r)throw Error("Property name must be a string");const n=t.it;if(n instanceof Element)return Ye(n,r);if(Ue(n)){if(Mn.has(r))return;return n[r]}return n[r]},validate:t=>ur(t,"its","property")},your:{name:"your",category:"Reference",evaluatesTo:"Any",operators:["your"],async evaluate(t,...e){const[r]=e;if(t.you){if("string"!=typeof r)throw Error("Property name must be a string");if(t.you instanceof Element)return Ye(t.you,r);if(Ue(t.you)){if(Mn.has(r))return;return t.you[r]}return t.you[r]}},validate:t=>ur(t,"your","property")},of:{name:"of",category:"Reference",evaluatesTo:"Any",operators:["of"],async evaluate(t,...e){const[r,n]=e;if(null!=n){if("string"!=typeof r)throw Error("Property name must be a string");if(n instanceof Element)return Ye(n,r);if(Ue(n)){if(Mn.has(r))return;return n[r]}return n[r]}},validate:t=>cr(t,2,"of","property, object")??lr(t,0,"of","property name")},attribute:{name:"attribute",category:"Reference",evaluatesTo:"String",operators:["@"],async evaluate(t,...e){const[r,n]=e;if("string"!=typeof r)throw Error("Attribute name must be a string");const s=n||t.me;return s&&s instanceof Element?s.getAttribute(r):null},validate:t=>pr(t,1,2,"attribute","attributeName, optional element")??lr(t,0,"attribute","attribute name")??(2>t.length||null==t[1]||t[1]instanceof Element?null:"attribute element must be an Element")},attributeWithValue:{name:"attributeWithValue",category:"Reference",evaluatesTo:"Boolean",operators:["@="],async evaluate(t,...e){const[r,n,s]=e;if("string"!=typeof r)throw Error("Attribute name must be a string");if("string"!=typeof n)throw Error("Expected value must be a string");const i=s||t.me;return i&&i instanceof Element?i.getAttribute(r)===n:0},validate:t=>pr(t,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??lr(t,0,"attributeWithValue","attribute name")??lr(t,1,"attributeWithValue","expected value")??(3>t.length||null==t[2]||t[2]instanceof Element?null:"attributeWithValue element must be an Element")},classReference:{name:"classReference",category:"Reference",evaluatesTo:"Array",operators:["."],async evaluate(t,...e){const[r]=e;if("string"!=typeof r)throw Error("Class name must be a string");const n=r.startsWith(".")?r.slice(1):r,s=document.getElementsByClassName(n);return Array.from(s)},validate:t=>ur(t,"classReference","className")},idReference:{name:"idReference",category:"Reference",evaluatesTo:"Element",operators:["#"],async evaluate(t,...e){const[r]=e;if("string"!=typeof r)throw Error("ID value must be a string");const n=r.startsWith("#")?r.slice(1):r;return document.getElementById(n)},validate:t=>ur(t,"idReference","idValue")}},Pn=kr({value:Er().describe("String literal value")}).strict(),Vn=kr({value:wr().describe("Number literal value")}).strict(),Bn=kr({value:xr().describe("Boolean literal value")}).strict(),Fn=kr({left:Sr().describe("Left operand"),right:Sr().describe("Right operand")}).strict(),_n={stringLiteral:new class extends Tr{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=Pn,this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid){const e=this.failure("ValidationError","validation-error",n.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",n.suggestions);return this.trackSimple(t,r,0),e}let s=e.value;(s.includes("${")||s.includes("$"))&&(s=this.interpolateString(s,t));const i=this.success(s,"string");return this.trackSimple(t,r,1,s),i}catch(e){return this.trackSimple(t,r,0),this.failure("StringEvaluationError","runtime-error","String literal evaluation failed: "+(e instanceof Error?e.message:e+""),"STRING_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid string literal input",["Provide a value parameter","Ensure value is a string"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}interpolateString(t,e){let r=t.replace(/\$\{([^}]+)\}/g,(t,r)=>{try{const t=this.resolveExpression(r.trim(),e);return void 0!==t?t+"":""}catch(t){return""}});return r=r.replace(/\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g,(t,r)=>{try{const t=this.resolveVariable(r,e);return void 0!==t?t+"":""}catch(t){return""}}),r}resolveExpression(t,e){if(t.includes(".")){const r=t.split(".");let n=this.resolveVariable(r[0],e);for(let t=1;r.length>t&&null!=n;t++)n=n[r[t]];return n}return this.resolveVariable(t,e)}resolveVariable(t,e){return"me"===t&&e.me?e.me:"you"===t&&e.you?e.you:"it"===t&&e.it?e.it:"result"===t&&e.result?e.result:e.locals?.has(t)?e.locals.get(t):e.globals?.has(t)?e.globals.get(t):void 0}},numberLiteral:new class extends Tr{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=Vn,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);return n.isValid?Number.isFinite(e.value)?(this.trackSimple(t,r,1,e.value),this.success(e.value,"number")):(this.trackSimple(t,r,0),this.failure("NumberValidationError","invalid-argument","Number literal must be finite","NUMBER_NOT_FINITE")):(this.trackSimple(t,r,0),this.failure("ValidationError","validation-error",n.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",n.suggestions))}catch(e){return this.trackSimple(t,r,0),this.failure("NumberEvaluationError","runtime-error","Number literal evaluation failed: "+(e instanceof Error?e.message:e+""),"NUMBER_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?Number.isFinite(e.data.value)?this.validationSuccess():this.validationFailure("invalid-argument","Number literal value must be finite",["Use finite numbers only","Avoid Infinity and NaN values"]):this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid number literal input",["Provide a value parameter","Ensure value is a number"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},booleanLiteral:new class extends Tr{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=Bn,this.outputType="Boolean",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);return n.isValid?(this.trackSimple(t,r,1,e.value),this.success(e.value,"boolean")):(this.trackSimple(t,r,0),this.failure("ValidationError","validation-error",n.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",n.suggestions))}catch(e){return this.trackSimple(t,r,0),this.failure("BooleanEvaluationError","runtime-error","Boolean literal evaluation failed: "+(e instanceof Error?e.message:e+""),"BOOLEAN_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid boolean literal input",["Provide a value parameter","Ensure value is a boolean"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},addition:new class extends Tr{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=Fn,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return this.trackSimple(t,r,0),this.failure("ValidationError","validation-error",n.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",n.suggestions);const s=Dr(e.left,"left operand")+Dr(e.right,"right operand");return this.trackSimple(t,r,1,s),this.success(s,"number")}catch(e){return this.trackSimple(t,r,0),this.failure("AdditionError","runtime-error","Addition failed: "+(e instanceof Error?e.message:e+""),"ADDITION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid addition input",["Provide left and right operands"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},stringConcatenation:new class extends Tr{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=Fn,this.outputType="String",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return this.trackSimple(t,r,0),this.failure("ValidationError","validation-error",n.errors[0]?.message||"Invalid input","STRING_CONCATENATION_VALIDATION_FAILED",n.suggestions);const s=this.convertToString(e.left)+this.convertToString(e.right);return this.trackSimple(t,r,1,s),this.success(s,"string")}catch(e){return this.trackSimple(t,r,0),this.failure("StringConcatenationError","runtime-error",e instanceof Error?e.message:"String concatenation failed","STRING_CONCATENATION_ERROR",["Check that operands can be converted to strings"])}}validate(t){const e=Fn.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid string concatenation input",["Provide left and right operands for concatenation"])}convertToString(t){if(null===t)return"null";if(void 0===t)return"undefined";if(_e(t))return t;if(qe(t))return""+t;if(He(t))return""+t;if(t instanceof Date)return""+t;try{return t+""}catch{return"[object Object]"}}},multiplication:new class extends Tr{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=Fn,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return this.trackSimple(t,r,0),this.failure("ValidationError","validation-error",n.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",n.suggestions);const s=Dr(e.left,"left operand")*Dr(e.right,"right operand");return this.trackSimple(t,r,1,s),this.success(s,"number")}catch(e){return this.trackSimple(t,r,0),this.failure("MultiplicationError","runtime-error","Multiplication failed: "+(e instanceof Error?e.message:e+""),"MULTIPLICATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid multiplication input",["Provide left and right operands"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}};class qn extends or{constructor(){super(),this.registerExpressions()}registerExpressions(){this.registerCategory($r),this.registerCategory(yn),this.registerCategory(Cn),this.registerCategory(jn),this.registerCategory(Dn),this.registerCategory(_n)}}class Hn{static toTyped(t){return{me:t.me,it:t.it,you:t.you,result:t.result,...void 0!==t.event&&{event:t.event},variables:t.variables||new Map,locals:t.locals||new Map,globals:t.globals||new Map,...void 0!==t.events&&{events:t.events},meta:t.meta||{},expressionStack:[],evaluationDepth:0,validationMode:"strict",evaluationHistory:[]}}static fromTyped(t,e){return{...e,me:t.me,it:t.it,you:t.you,result:t.result,...void 0!==t.event&&{event:t.event},...void 0!==t.variables&&{variables:t.variables},locals:t.locals,globals:t.globals,...void 0!==t.events&&{events:t.events},...void 0!==t.meta&&{meta:t.meta}}}}class Un{constructor(t,e,r){this.impl=t,this.expressionEvaluator=e??new qn,this.hookRegistry=r??null}setHookRegistry(t){this.hookRegistry=t}createHookContext(t,e,r={}){return{commandName:this.name,element:t.me instanceof Element?t.me:null,args:e,modifiers:r,event:t.event??void 0,executionContext:t}}get name(){return this.impl.name||this.impl.metadata?.name}get metadata(){return{description:this.impl.metadata?.description||"",examples:this.impl.metadata?.examples||[],syntax:this.impl.metadata?.syntax||""}}async execute(t,...e){const r=e[0],n=this.createHookContext(t,e,r&&"object"==typeof r&&"modifiers"in r&&r.modifiers||{});try{if(at(`CommandAdapterV2: Executing '${this.name}' with args:`,e),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(n),this.hookRegistry?.shouldIntercept(this.name,n))return void at(`CommandAdapterV2: '${this.name}' intercepted by hook`);t.locals||(t.locals=new Map),t.locals.set("__evaluator",this.expressionEvaluator);const s=Hn.toTyped(t);let i,o;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(at(`CommandAdapterV2: '${this.name}' has parseInput(), calling it`),r&&"object"==typeof r&&("args"in r||"modifiers"in r)){const e=r.modifiers,n=e?.when||e?.where;if(n&&!await this.expressionEvaluator.evaluate(n,t))return void at(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);i=await this.impl.parseInput({args:r.args||[],modifiers:e||{},commandName:r.commandName},this.expressionEvaluator,t)}else i=e;else at(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),i=e;return at("CommandAdapterV2: Calling execute with parsed input:",i),o=2===this.impl.execute.length?await this.impl.execute(i,s):await this.impl.execute(s,...i),at("CommandAdapterV2: Command result:",o),Object.assign(t,Hn.fromTyped(s,t)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(n,o),o}catch(t){if(Xn(t)||at(`CommandAdapterV2: Error executing '${this.name}':`,t),this.hookRegistry&&t instanceof Error)throw await this.hookRegistry.runOnError(n,t);throw t}}validate(t){return this.impl.validate?this.impl.validate(t):{isValid:1,errors:[],suggestions:[]}}}class Wn{constructor(t,e){this.adapters=new Map,this.implementations=new Map,this.sharedEvaluator=t,this.hookRegistry=e}setHookRegistry(t){this.hookRegistry=t;for(const e of this.adapters.values())e.setHookRegistry(t);ht(`CommandRegistryV2: Hook registry set and propagated to ${this.adapters.size} adapters`)}getHookRegistry(){return this.hookRegistry}register(t){const e=t.name||t.metadata?.name;if(!e||"string"!=typeof e)throw Error("Cannot register command: no name found. Provide a 'name' property or 'metadata.name' on the implementation.");const r=e.toLowerCase();ht(`CommandRegistryV2: Registering command '${r}'`),this.implementations.set(r,t);const n=new Un(t,this.sharedEvaluator,this.hookRegistry);this.adapters.set(r,n),w.add(r);const s=t.metadata?.aliases;if(s&&Array.isArray(s))for(const e of s){const r=e.toLowerCase();this.implementations.set(r,t),this.adapters.set(r,n),w.add(r)}}getAdapter(t){return this.adapters.get(t.toLowerCase())}has(t){return this.adapters.has(t.toLowerCase())}getCommandNames(){return Array.from(this.adapters.keys())}getImplementation(t){return this.implementations.get(t.toLowerCase())}getAdapters(){return new Map(this.adapters)}validateCommand(t,e){const r=this.getAdapter(t);return r?r.validate(e):{isValid:0,errors:[{type:"runtime-error",message:"Unknown command: "+t,suggestions:["Available commands: "+this.getCommandNames().join(", ")]}],suggestions:["Available commands: "+this.getCommandNames().join(", ")]}}}let zn=null;function Jn(){return zn||(zn=function(){const t=new Wn,e=new Ve,r=new Be,n=new Set,s={commands:t,eventSources:e,context:r,use(i){if(n.has(i.name))console.warn(`[LokaScriptRegistry] Plugin '${i.name}' is already installed`);else{if(i.commands)for(const e of i.commands)t.register(e);if(i.eventSources)for(const t of i.eventSources)e.register(t.name,t);if(i.contextProviders)for(const{name:t,provide:e,options:n}of i.contextProviders)r.register(t,e,n);i.setup?.(s),n.add(i.name)}},reset(){n.clear()}};return s}()),zn}class Zn{constructor(t={}){this.contextCache=new WeakMap;const e=Jn();this.options={enableContextProviders:t.enableContextProviders??1,enableEventSources:t.enableEventSources??1,registry:t.registry??{}},this.contextRegistry=this.options.registry.context??e.context,this.eventSourceRegistry=this.options.registry.eventSources??e.eventSources,ht(`[RegistryIntegration] Initialized (context=${this.options.enableContextProviders}, events=${this.options.enableEventSources})`)}enhanceContext(t){if(!this.options.enableContextProviders)return t;const e=this.contextCache.get(t);if(e)return e;try{const e=this.contextRegistry.enhance(t);return this.contextCache.set(t,e),ht(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),e}catch(e){return ht("[RegistryIntegration] Failed to enhance context: "+(e instanceof Error?e.message:e+"")),t}}getEventSource(t){if(!this.options.enableEventSources)return;const e=this.eventSourceRegistry.get(t);if(e)return ht(`[RegistryIntegration] Found event source for '${t}'`),e;const r=this.eventSourceRegistry.findSourceForEvent(t);if(r){const e=this.eventSourceRegistry.get(r);return ht(`[RegistryIntegration] Found event source '${r}' supporting '${t}'`),e}}hasEventSource(t){return void 0!==this.getEventSource(t)}subscribeToEventSource(t,e,r){if(!this.options.enableEventSources)throw Error("Event sources are disabled in this runtime");const n=this.eventSourceRegistry.subscribe(t,e,r);if(!n)throw Error(`Failed to subscribe to event source '${t}'`);return ht(`[RegistryIntegration] Subscribed to '${t}' event '${e.event}' (id: ${n.id})`),n}getEventSourceNames(){return this.eventSourceRegistry.getSourceNames()}getContextProviderNames(){return this.contextRegistry.getProviderNames()}destroy(){this.eventSourceRegistry.destroy(),this.contextCache=new WeakMap,ht("[RegistryIntegration] Destroyed")}}function Gn(t){const e=Error(t.type.toUpperCase()+"_EXECUTION");return e["is"+t.type.charAt(0).toUpperCase()+t.type.slice(1)]=1,"returnValue"in t&&(e.returnValue=t.returnValue),e}function Xn(t){return t instanceof Error?null!==Le(t)||"HALT_EXECUTION"===t.message||"EXIT_COMMAND"===t.message||"EXIT_EXECUTION"===t.message:0}function Yn(t){if(void 0===t)return;let e=t;if(e&&"object"==typeof e){const t=e;if("result"in t&&"wasAsync"in t)e=t.result;else if("result"in t&&"executed"in t){if(e=t.result,t.preserveArrayResult)return void 0!==e?e:void 0}else if("lastResult"in t&&"type"in t)e=t.lastResult;else if("conditionResult"in t&&"executedBranch"in t){if(void 0===t.result)return;e=t.result}else"value"in t&&1===Object.keys(t).length||"value"in t&&"target"in t&&"targetType"in t?e=t.value:"data"in t&&"status"in t&&"headers"in t&&(e=t.data)}return Array.isArray(e)&&e.length>0&&(e=e[0]),e}function Kn(t){return null!==t&&"object"==typeof t&&"command"in t&&"selector"in t}const Qn=new WeakMap;class ts{constructor(t){this.autoCleanupObserver=null,this.registryIntegration=null,this.runtimeWarnings=[],this.options={commandTimeout:1e4,enableErrorReporting:1,enableResultPattern:1,enableAutoCleanup:1,...t},this.registry=t.registry,this.expressionEvaluator=t.expressionEvaluator,this.behaviorRegistry=new Map,this.globalVariables=De,this.hookRegistry=new $e,t.hooks&&this.hookRegistry.register("default",t.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new Me,this.options.enableAutoCleanup&&this.setupAutoCleanup(),0!=t.registryIntegration&&(this.registryIntegration=new Zn("object"==typeof t.registryIntegration?t.registryIntegration:{}),ht("RuntimeBase: Registry integration enabled")),this.behaviorAPI={has:t=>this.behaviorRegistry.has(t),get:t=>this.behaviorRegistry.get(t),install:async(t,e,r)=>await this.installBehaviorOnElement(t,e,r)}}setupAutoCleanup(){"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.autoCleanupObserver=new MutationObserver(t=>{const e=[];for(const r of t)for(const t of r.removedNodes)t instanceof Element&&e.push(t);e.length>0&&queueMicrotask(()=>{for(const t of e)if(!t.isConnected){const e=this.cleanupRegistry.cleanupElementTree(t);e>0&&ht(`RuntimeBase: Auto-cleaned ${e} resources for removed element`)}})}),document.body?this.autoCleanupObserver.observe(document.body,{childList:1,subtree:1}):document.addEventListener("DOMContentLoaded",()=>{this.autoCleanupObserver?.observe(document.body,{childList:1,subtree:1})},{once:1}))}registerHooks(t,e){this.hookRegistry.register(t,e)}unregisterHooks(t){return this.hookRegistry.unregister(t)}getRegisteredHooks(){return this.hookRegistry.getRegisteredNames()}cleanup(t){return this.cleanupRegistry.cleanupElement(t)}cleanupTree(t){return this.cleanupRegistry.cleanupElementTree(t)}getCleanupStats(){return this.cleanupRegistry.getStats()}destroy(){this.autoCleanupObserver&&(this.autoCleanupObserver.disconnect(),this.autoCleanupObserver=null),this.cleanupRegistry.cleanupAll(),this.hookRegistry.clear(),this.behaviorRegistry.clear(),ht("RuntimeBase: Destroyed")}hasErrorDiagnostics(t){const e=t.diagnostics;return!!e?.some(t=>"error"===t.severity)}getWarnings(){return this.runtimeWarnings}async execute(t,e){ht(`RUNTIME BASE: execute() called with node type: '${t.type}'`),e.locals.has("_behaviors")||e.locals.set("_behaviors",this.behaviorAPI),e.locals.has("_runtimeExecute")||e.locals.set("_runtimeExecute",(t,r)=>this.execute(t,r||e));try{if(this.hasErrorDiagnostics(t)){const e=t.diagnostics?.[0];return ht("⚠️ RUNTIME: Skipping error node: "+(e?.message||"unknown error")),void this.runtimeWarnings.push(e?.message||"Skipped error node")}switch(t.type){case"command":if(this.options.enableResultPattern)try{const r=await this.processCommandWithResult(t,e);if(!je(r))throw Gn(r.error);return r.value}catch(t){throw t}return await this.processCommand(t,e);case"eventHandler":return await this.executeEventHandler(t,e);case"event":{const r={type:"eventHandler",event:t.event,events:[t.event],commands:t.body||[],target:t.filter,modifiers:t.modifiers||{}};return await this.executeEventHandler(r,e)}case"behavior":return await this.executeBehaviorDefinition(t,e);case"Program":return await this.executeProgram(t,e);case"initBlock":case"block":return await this.executeBlock(t,e);case"sequence":case"CommandSequence":if(this.options.enableResultPattern){const r=t,n=await this.executeCommandSequenceWithResult(r.commands||[],e);if(!je(n))throw Gn(n.error);return n.value}return await this.executeCommandSequence(t,e);case"objectLiteral":return await this.executeObjectLiteral(t,e);default:if(this.options.enableResultPattern){const r=await this.evaluateExpressionWithResult(t,e);if(!je(r))throw Gn(r.error);return r.value}return await this.evaluateExpression(t,e)}}catch(t){throw t}}async processCommand(t,e){const{name:r,args:n,modifiers:s}=t,i=r.toLowerCase();if(at(`RUNTIME BASE: Processing command '${i}'`),this.registry.has(i)){const t=await this.registry.getAdapter(i);if(!t)throw Error(`Command '${i}' is registered but failed to load adapter.`);try{return await t.execute(e,{args:n||[],modifiers:s||{},commandName:i,runtime:this})}catch(t){throw Xn(t)||console.error(`Error executing command '${i}':`,t),t}}const o=`Unknown command: ${r}. Ensure it is registered in the Runtime options.`;throw this.options.enableErrorReporting&&console.warn(o),Error(o)}toSignal(t){const e=Le(t);if(e){if(e.isHalt||"HALT_EXECUTION"===e.message)return{type:"halt"};if(e.isExit||"EXIT_COMMAND"===e.message)return{type:"exit",returnValue:e.returnValue};if(e.isBreak)return{type:"break"};if(e.isContinue)return{type:"continue"};if(e.isReturn)return{type:"return",returnValue:e.returnValue}}if(t instanceof Error){if("HALT_EXECUTION"===t.message)return{type:"halt"};if("EXIT_COMMAND"===t.message)return{type:"exit"}}return null}async processCommandWithResult(t,e){const{name:r,args:n,modifiers:s}=t,i=r.toLowerCase();if(at(`RUNTIME BASE (Result): Processing command '${i}'`),!this.registry.has(i)){const t=`Unknown command: ${r}. Ensure it is registered in the Runtime options.`;throw this.options.enableErrorReporting&&console.warn(t),Error(t)}const o=await this.registry.getAdapter(i);if(!o)throw Error(`Command '${i}' is registered but failed to load adapter.`);try{return Re(await o.execute(e,{args:n||[],modifiers:s||{},commandName:i,runtime:this}))}catch(t){const e=this.toSignal(t);if(e)return Ie(e);throw console.error(`Error executing command '${i}':`,t),t}}async executeCommandSequenceWithResult(t,e){let r;for(const n of t){if(this.hasErrorDiagnostics(n)){const t=n.diagnostics?.[0];ht("⚠️ RUNTIME: Skipping error node: "+(t?.message||"unknown error")),this.runtimeWarnings.push(t?.message||"Skipped error node");continue}if("command"===n.type){const t=await this.processCommandWithResult(n,e);if(!je(t)){const r=t.error;switch(r.type){case"halt":case"exit":case"break":case"continue":return t;case"return":return void 0!==r.returnValue&&Object.assign(e,{it:r.returnValue,result:r.returnValue}),Re(r.returnValue)}}r=t.value}else{const t=await this.evaluateExpressionWithResult(n,e);if(!je(t))return t;r=t.value}}return Re(r)}async evaluateExpression(t,e){const r=await this.expressionEvaluator.evaluate(t,e);return Kn(r)?await this.executeCommandFromPattern(r.command,r.selector,e):r}async evaluateExpressionWithResult(t,e){const r=await this.expressionEvaluator.evaluateWithResult(t,e);if(!je(r))return r;const n=r.value;if(Kn(n)){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:n.command,args:[{type:"literal",value:n.selector}]},e);try{return Re(await this.executeCommandFromPattern(n.command,n.selector,e))}catch(t){const e=this.toSignal(t);if(e)return Ie(e);throw t}}return Re(n)}async executeCommandFromPattern(t,e,r){return this.processCommand({type:"command",name:t,args:[{type:"literal",value:e}]},r)}async executeProgram(t,e){if(!t.statements||!Array.isArray(t.statements))return;let r;const n=[],s=[],i=[];for(const e of t.statements)"eventHandler"===e.type?n.push(e):"initBlock"===e.type?s.push(e):i.push(e);for(const t of n)try{await this.execute(t,e)}catch(t){if(Xn(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of s)try{r=await this.execute(t,e)}catch(t){if(Xn(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of i)try{r=await this.execute(t,e)}catch(t){if(Xn(t)&&(t.isHalt||t.isExit))break;throw t}return r}async executeBlock(t,e){if(t.commands&&Array.isArray(t.commands))for(const r of t.commands)try{await this.execute(r,e)}catch(t){if(Xn(t)&&t.isHalt)break;throw t}}async executeCommandSequence(t,e){if(!t.commands||!Array.isArray(t.commands))return;let r;for(const n of t.commands)try{r=await this.execute(n,e)}catch(t){if(Xn(t)){if(t.isHalt||t.isExit)break;if(t.isReturn){if(void 0!==t.returnValue)return Object.assign(e,{it:t.returnValue,result:t.returnValue}),t.returnValue;break}if(t.isBreak)throw t}throw t}return r}async executeObjectLiteral(t,e){const r={};if(!t.properties)return r;for(const n of t.properties){let t;t="identifier"===n.key.type?n.key.name:"literal"===n.key.type?n.key.value+"":await this.execute(n.key,e)+"";const s=await this.execute(n.value,e);r[t]=s}return r}enhanceContext(t){return this.registryIntegration?this.registryIntegration.enhanceContext(t):t}async executeBehaviorDefinition(t,e){const{name:r,parameters:n,eventHandlers:s,initBlock:i}=t,o=t.imperativeInstaller;"function"==typeof o?(this.behaviorRegistry.set(r,{name:r,parameters:n,type:"imperative",install:o}),ht(`RUNTIME BASE: Registered imperative behavior '${r}'`)):(this.behaviorRegistry.set(r,{name:r,parameters:n,eventHandlers:s,initBlock:i}),ht(`RUNTIME BASE: Registered behavior '${r}'`))}async installBehaviorOnElement(t,e,r){ht("BEHAVIOR: installBehaviorOnElement called: "+t);const n=this.behaviorRegistry.get(t);if(!n)throw Error(`Behavior "${t}" not found`);if("imperative"===n.type&&"function"==typeof n.install)return ht(`BEHAVIOR: Installing imperative behavior '${t}'`),n.install(e,r),void ht(`BEHAVIOR: Finished installing imperative behavior '${t}'`);ht("BEHAVIOR: Found behavior, eventHandlers count: "+(n.eventHandlers?.length||0));const s={me:e,you:null,it:null,result:null,locals:new Map,globals:this.globalVariables,halted:0,returned:0,broke:0,continued:0,async:0},i=this.enhanceContext(s);if(n.parameters)for(const t of n.parameters)i.locals.set(t,t in r?r[t]:void 0);for(const[t,e]of Object.entries(r))n.parameters?.includes(t)||i.locals.set(t,e);if(n.initBlock){ht("BEHAVIOR: Running init block for "+t);const e=this.options.commandTimeout??1e4;try{await Promise.race([this.execute(n.initBlock,i),new Promise((r,n)=>setTimeout(()=>n(Error(`Behavior "${t}" init block timed out after ${e}ms`)),e))]),ht("BEHAVIOR: Init block completed for "+t)}catch(e){if(ht(`BEHAVIOR: Init block error for ${t}:`,e),!(e instanceof Error&&Xn(e)))throw e}}if(ht(`BEHAVIOR: About to attach ${n.eventHandlers?.length||0} handlers for ${t}`),n.eventHandlers){const e=this.options.commandTimeout??1e4;for(const r of n.eventHandlers)await Promise.race([this.executeEventHandler(r,i),new Promise((r,n)=>setTimeout(()=>n(Error(`Behavior "${t}" handler attachment timed out after ${e}ms`)),e))])}ht("BEHAVIOR: Finished installing "+t)}async executeEventHandler(t,e){const{event:r,events:n,commands:s,target:i,args:o,selector:a,attributeName:c,watchTarget:l,modifiers:u}=t,h=n&&n.length>0?n:[r];ht(`BEHAVIOR: executeEventHandler: event='${r}', target='${i}'`);let f=[],d=null;if(i){const t="string"==typeof i?i.toLowerCase():"";if("window"===t||"the window"===t)d=window;else if("document"===t||"the document"===t||"body"===t)d=document;else if("me"===t||"myself"===t)f=e.me?[e.me]:[];else if("string"==typeof i&&e.locals.has(i)){const t=e.locals.get(i);ht(`BEHAVIOR: Target resolution: found local '${i}', isElement: ${this.isElement(t)}`),this.isElement(t)?f=[t]:Array.isArray(t)?f=t.filter(t=>this.isElement(t)):"string"==typeof t&&(f=this.queryElements(t,e))}else ht(`BEHAVIOR: Target resolution: querying for '${i}'`),f=this.queryElements(i,e)}else f=e.me?[e.me]:[];if(0===f.length&&!d)return void ht(`BEHAVIOR: executeEventHandler - No targets found for event '${r}', returning early`);if("mutation"===r&&c)return void this.setupMutationObserver(f,c,s,e);if("change"===r&&l)return void this.setupChangeObserver(l,s,e);const p=t.customEventSource;if(p&&this.registryIntegration){ht(`BEHAVIOR: executeEventHandler - Using custom event source '${p}' for event '${r}'`);const t=async t=>{const n=new Map(e.locals),i={...e,locals:n,it:t,event:t},o=this.enhanceContext(i);ht(`CUSTOM EVENT: Executing commands for event '${r}'`);try{await this.execute({type:"program",commands:s},o)}catch(t){console.error(`[HyperFixi] Error executing commands for custom event '${r}':`,t)}};try{const n=this.registryIntegration.subscribeToEventSource(p,{event:r,handler:t,target:i,selector:a},e);ht(`BEHAVIOR: Subscribed to custom event source '${p}' (id: ${n.id})`),this.cleanupRegistry.registerGlobal(()=>n.unsubscribe(),"listener",`Custom event source '${p}' subscription ${n.id}`)}catch(t){console.error(`[HyperFixi] Failed to subscribe to custom event source '${p}':`,t)}return}const m=ts.createEventHandler(this,s,e,a,o);let y,v=null;if(u){let t=m;if(u.prevent){const e=t;t=async t=>(t.preventDefault(),e(t))}if(u.stop){const e=t;t=async t=>(t.stopPropagation(),e(t))}if(u.debounce){const e=u.debounce;let r;y=n=>{r&&clearTimeout(r),r=setTimeout(()=>t(n),e)},v=()=>{r&&(clearTimeout(r),r=void 0)}}else if(u.throttle){const e=u.throttle;let r=0;y=n=>{const s=Date.now();e>s-r||(r=s,t(n))}}else y=t}else y=m;const g=u?.once?{once:1}:void 0;if(d){for(const t of h)d.addEventListener(t,y,g),f.length>0?this.cleanupRegistry.registerListener(f[0],d,t,y):this.cleanupRegistry.registerGlobal(()=>d.removeEventListener(t,y),"listener",`Global ${t} listener`);v&&(f.length>0?this.cleanupRegistry.registerCustom(f[0],v,"debounce-timeout"):this.cleanupRegistry.registerGlobal(v,"timeout","debounce-timeout"))}else for(const t of f){for(const e of h)t.addEventListener(e,y,g),this.cleanupRegistry.registerListener(t,t,e,y);v&&this.cleanupRegistry.registerCustom(t,v,"debounce-timeout")}}static createEventHandler(t,e,r,n,s){return async i=>{const o=Qn.get(i)??0;if(o>=100)return;if(Qn.set(i,o+1),n&&i.target instanceof Element)try{if(!i.target.matches(n)&&!i.target.closest(n))return}catch{ht(`Event delegation: invalid CSS selector '${n}', skipping filter`)}const a=new Map(r.locals),c={...r,locals:a,it:i,event:i};a.has("target")||c.locals.set("target",i.target);const l=t.enhanceContext(c);if(s&&s.length>0){const t=i,e=t.detail;for(const r of s)l.locals.set(r,t[r]??e?.[r]??null)}for(const r of e)try{const e=Yn(await t.execute(r,l));void 0!==e&&Object.assign(l,{it:e,result:e})}catch(t){if(Xn(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 console.error("COMMAND FAILED:",t),t}}}setupMutationObserver(t,e,r,n){ht(`RUNTIME BASE: Setting up MutationObserver for attribute '${e}' on ${t.length} elements`);for(const s of t){const t=new MutationObserver(async t=>{for(const i of t)if("attributes"===i.type&&i.attributeName===e){ct(`MUTATION DETECTED: attribute '${e}' changed on`,s);const t={...n,me:s,it:i,locals:new Map(n.locals)},o=i.oldValue,a=s.getAttribute(e);t.locals.set("oldValue",o),t.locals.set("newValue",a);const c=this.enhanceContext(t);for(const t of r)try{await this.execute(t,c)}catch(t){if(Xn(t)){if(t.isHalt||t.isExit||t.isReturn)break}else console.error("Error executing mutation handler command:",t)}}});t.observe(s,{attributes:1,attributeOldValue:1,attributeFilter:[e]}),this.cleanupRegistry.registerObserver(s,t),ht("RUNTIME BASE: MutationObserver attached to",s,`for attribute '${e}'`)}}async setupChangeObserver(t,e,r){ht("RUNTIME BASE: Setting up MutationObserver for content changes on watch target");const n=await this.execute(t,r);let s=[];this.isElement(n)?s=[n]:Array.isArray(n)&&(s=n.filter(t=>this.isElement(t))),ht(`RUNTIME BASE: Watching ${s.length} target elements for content changes`);for(const t of s){const n=new MutationObserver(async n=>{for(const s of n)if("childList"===s.type||"characterData"===s.type){ct("CONTENT CHANGE DETECTED on",t,"mutation type:",s.type);const n={...r,me:r.me,it:s,locals:new Map(r.locals)};n.locals.set("target",t);const i=s.oldValue,o=t.textContent;null!==i&&n.locals.set("oldValue",i),n.locals.set("newValue",o);const a=this.enhanceContext(n);for(const t of e)try{await this.execute(t,a)}catch(t){if(Xn(t)){if(t.isHalt||t.isExit||t.isReturn)break}else console.error("Error executing change handler command:",t)}}});n.observe(t,{childList:1,characterData:1,subtree:1,characterDataOldValue:1}),this.cleanupRegistry.registerObserver(t,n),ht("RUNTIME BASE: MutationObserver attached to",t,"for content changes")}}queryElements(t,e){const r=e.me,n=(r instanceof Element?r.ownerDocument:null)??("undefined"!=typeof document?document:null);if(!n)return[];let s=t;s.startsWith("<")&&s.endsWith("/>")&&(s=s.slice(1,-2).trim());try{return Array.from(n.querySelectorAll(s))}catch{return ht(`queryElements: invalid CSS selector '${s}'`),[]}}isElement(t){return"undefined"!=typeof HTMLElement&&t instanceof HTMLElement?1:t&&"object"==typeof t?!!t.style&&!!t.classList:0}}class es{constructor(t){this.observer=null,this.initialized=0,this.runtime=t}init(){"undefined"!=typeof document&&(this.initialized||(this.initialized=1,this.scanDocument(),this.observer=new MutationObserver(t=>{for(const e of t)"childList"===e.type?e.addedNodes.forEach(t=>{t.nodeType===Node.ELEMENT_NODE&&(this.processElement(t),this.scanElement(t))}):"attributes"===e.type&&"_"===e.attributeName&&this.processElement(e.target)}),this.observer.observe(document.body,{childList:1,subtree:1,attributes:1,attributeFilter:["_"]})))}destroy(){this.observer&&(this.observer.disconnect(),this.observer=null),this.initialized=0}reset(){this.destroy()}scanAndProcessAll(){this.scanDocument()}scanDocument(){document.body&&this.scanElement(document.body)}scanElement(t){t.hasAttribute("_")&&this.processElement(t),t.querySelectorAll("[_]").forEach(t=>this.processElement(t))}processElement(t){const e=t.getAttribute("_");if(!e)return;const r=Pe(t);this.runtime.execute(e,r).catch(r=>{console.error('[HyperFixi] Error executing _="" attribute:',r),console.error("Element:",t),console.error("Code:",e)})}}function rs(t,e,r,n,s,i){function o(t){if(void 0!==t&&"function"!=typeof t)throw new TypeError("Function expected");return t}for(var a,c=n.kind,l="getter"===c?"get":"setter"===c?"set":"value",u=!e&&t?n.static?t:t.prototype:null,h=e||(u?Object.getOwnPropertyDescriptor(u,n.name):{}),f=0,d=r.length-1;d>=0;d--){var p={};for(var m in n)p[m]="access"===m?{}:n[m];for(var m in n.access)p.access[m]=n.access[m];p.addInitializer=function(t){if(f)throw new TypeError("Cannot add initializers after decoration has completed");i.push(o(t||null))};var y=(0,r[d])("accessor"===c?{get:h.get,set:h.set}:h[l],p);if("accessor"===c){if(void 0===y)continue;if(null===y||"object"!=typeof y)throw new TypeError("Object expected");(a=o(y.get))&&(h.get=a),(a=o(y.set))&&(h.set=a),(a=o(y.init))&&s.unshift(a)}else(a=o(y))&&("field"===c?s.unshift(a):h[l]=a)}u&&Object.defineProperty(u,n.name,h),f=1}function ns(t,e,r){for(var n=arguments.length>2,s=0;e.length>s;s++)r=n?e[s].call(t,r):e[s].call(t);return n?r:void 0}function ss(t,e,r){return"symbol"==typeof e&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:1,value:r?"".concat(r," ",e):e})}function is(t){const e=t.trim();return e.startsWith("[@")&&e.endsWith("]")||e.startsWith("@")?1:0}function os(t){const e=t.trim();if(e.startsWith("[@")&&e.endsWith("]")){const t=e.slice(2,-1),r=t.indexOf("=");if(-1===r)return{name:t.trim()};const n=t.slice(0,r).trim();let s=t.slice(r+1).trim();return(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),{name:n,value:s}}if(e.startsWith("@"))return{name:e.substring(1).trim()};throw Error("Invalid attribute syntax: "+t)}function as(t,e){for(const r of t)e(r);return t}function cs(t,e,r){for(const n of t)for(const t of e)r(n,t);return t}function ls(t,e,r){const n=t.hasAttribute(e);void 0!==r?n&&t.getAttribute(e)===r?t.removeAttribute(e):t.setAttribute(e,r):n?t.removeAttribute(e):t.setAttribute(e,"")}function us(t){if(!t)return[];if("string"==typeof t)return t.trim().split(/[\s,]+/).map(t=>{const e=t.trim();return e.startsWith(".")?e.substring(1):e}).filter(t=>t.length>0&&fs(t));if(Array.isArray(t))return t.map(t=>{const e=(t+"").trim();return e.startsWith(".")?e.substring(1):e}).filter(t=>t.length>0&&fs(t));const e=(t+"").trim(),r=e.startsWith(".")?e.substring(1):e;return r.length>0&&fs(r)?[r]:[]}function hs(t){const e=t.trim();return/^\{[^}]+\}$/.test(e)}function fs(t){if(!t||0===t.trim().length)return 0;const e=t.trim();return hs(e)?1:/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(e)}function ds(t,e){return t.map(t=>{if(hs(t)){const r=function(t){const e=t.trim(),r=e.match(/^\{(.+)\}$/);return r?r[1].trim():e}(t),n=e.locals.get(r)??e.globals.get(r);return null!=n?n+"":(console.warn(`Dynamic class variable '${r}' not found in context`),"")}return t}).filter(t=>t.length>0)}"function"==typeof SuppressedError&&SuppressedError;const ps=Symbol("command:name"),ms=Symbol("command:category"),ys=Symbol("command:metadata");function vs(t){return function(e,r){const n=e;n[ps]=t.name,n[ms]=t.category,Object.defineProperty(e.prototype,"name",{value:t.name,writable:0,enumerable:1})}}function gs(t){return function(e,r){const n=e,s=n[ms];if(!s)throw Error("@meta decorator requires @command decorator to be applied first on "+e.name);const i={description:t.description,syntax:t.syntax,examples:t.examples,category:s,sideEffects:t.sideEffects,deprecated:t.deprecated,deprecationMessage:t.deprecationMessage,aliases:t.aliases,relatedCommands:t.relatedCommands,isBlocking:t.isBlocking??0,hasBody:t.hasBody??0,version:"1.0.0",compatibility:t.compatibility};n[ys]=i,Object.defineProperty(e,"metadata",{value:i,writable:0,enumerable:1,configurable:0}),Object.defineProperty(e.prototype,"metadata",{get:()=>i,enumerable:1,configurable:0})}}function bs(t){return()=>new t}function Es(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"tagName"in t&&"string"==typeof t.tagName&&"classList"in t}function ws(t,e){if(Es(t))return t;if(!t){const t=e.me;if(!t)throw Error("No target element - provide explicit target or ensure context.me is set");return xs(t)}if("string"==typeof t){const r=t.trim();if("me"===r){if(!e.me)throw Error('Context reference "me" is not available');return xs(e.me)}if("it"===r){if(!Es(e.it))throw Error('Context reference "it" is not an HTMLElement');return e.it}if("you"===r){if(!e.you)throw Error('Context reference "you" is not available');return xs(e.you)}const n=e.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!n)throw Error("DOM not available - cannot resolve element selector");const s=n.querySelector(r);if(!s)throw Error("Element not found with selector: "+r);if(!Es(s))throw Error("Element found but is not an HTMLElement: "+r);return s}throw Error("Invalid target type: "+typeof t)}function xs(t){if(Es(t))return t;throw Error("Value is not an HTMLElement")}function ks(t,e){switch(t.toLowerCase()){case"my":case"me":if(!e.me)throw Error('No "me" element in context');if(!Es(e.me))throw Error("context.me is not an HTMLElement");return e.me;case"its":case"it":if(!e.it)throw Error('No "it" value in context');if(!Es(e.it))throw Error("context.it is not an HTMLElement");return e.it;case"your":case"you":if(!e.you)throw Error('No "you" element in context');if(!Es(e.you))throw Error("context.you is not an HTMLElement");return e.you;default:throw Error("Unknown possessive: "+t)}}const As=["on","from","to","in","with","at"];async function Ss(t,e,r,n,s={},i){let o=t;if(s.filterPrepositions&&t&&(o=t.filter(t=>{const e=t;return"identifier"===e?.type&&"string"==typeof e.name?!As.includes(e.name.toLowerCase()):1})),(!o||0===o.length)&&s.fallbackModifierKey&&i){const t=i[s.fallbackModifierKey];t&&(o=[t])}if(!o||0===o.length){if(!r.me)throw Error(n+" command: no target specified and context.me is null");if(!Es(r.me))throw Error(n+" command: context.me must be an HTMLElement");return[r.me]}const a=[];for(const t of o){const s=await e.evaluate(t,r);if(""!==s&&("string"!=typeof s||""!==s.trim()))if(Es(s))a.push(s);else if(s instanceof NodeList){const t=Array.from(s).filter(Es);a.push(...t)}else if(Array.isArray(s)){const t=s.filter(Es);a.push(...t)}else{if("string"!=typeof s)throw Error(`Invalid ${n} target: expected HTMLElement or CSS selector, got ${typeof s}`);try{let t=s;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const e=r.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!e)throw Error("DOM not available - cannot resolve element selector");const n=e.querySelectorAll(t),i=Array.from(n).filter(Es);a.push(...i)}catch(t){throw Error(`Invalid CSS selector: "${s}" - ${t instanceof Error?t.message:t+""}`)}}}if(0===a.length){if(!r.me)throw Error(n+" command: no target specified and context.me is null");if(!Es(r.me))throw Error(n+" command: context.me must be an HTMLElement");return[r.me]}return a}function Cs(t){return"string"==typeof t&&t.trim().startsWith("*")}function Ns(t){const e=function(t){const e=t.trim();if(!e.startsWith("*"))return null;const r=e.substring(1).trim();return r?{property:r}:null}(t);if(!e)return null;const r=e.property.toLowerCase();return["display","visibility","opacity"].includes(r)?r:null}function Ts(t,e,r){t.style.setProperty(e,r)}const Os=["dialog","details","summary","select"];function $s(t){return t&&"object"==typeof t?"string"==typeof t.selector?t.selector:"string"==typeof t.value?t.value:"string"==typeof t.name?t.name:null:null}async function Ls(t,e,r){return function(t){if(!t||"object"!=typeof t)return 0;const e=t.type;if("selector"!==e&&"cssSelector"!==e&&"classSelector"!==e)return 0;const r=$s(t);return"string"==typeof r&&r.startsWith(".")}(t)||function(t){if(!t||"object"!=typeof t)return 0;const e=t.type;if("selector"!==e&&"cssSelector"!==e&&"cssProperty"!==e)return 0;const r=$s(t);return"string"==typeof r&&r.startsWith("*")}(t)?{value:$s(t),extractedFromNode:1}:function(t){if(!t||"object"!=typeof t)return 0;if("attributeAccess"===t.type)return 1;if("selector"===t.type||"cssSelector"===t.type){const e=$s(t);return"string"==typeof e&&e.startsWith("@")}return 0}(t)?{value:(n=t,"attributeAccess"===n.type?"@"+n.attributeName:$s(n)),extractedFromNode:1}:{value:await e.evaluate(t,r),extractedFromNode:0};var n}class Rs{async resolveTargets(t,e,r,n){return Ss(t,e,r,this.mode,{filterPrepositions:1,fallbackModifierKey:this.preposition},n)}async evaluateFirst(t,e,r){return Ls(t,e,r)}parseClassNames(t){return us(t)}isAttribute(t){return is(t.trim())}isCSSProperty(t){return Cs(t.trim())}validateTargets(t){return Array.isArray(t)&&function(t){return Array.isArray(t)&&t.length>0&&t.every(t=>Es(t))}(t)}validateType(t,e){return function(t,e){return"string"==typeof t&&e.includes(t)}(t,e)}validateStringArray(t,e=1){return Array.isArray(t)&&function(t,e=1){return Array.isArray(t)&&t.length>=e&&t.every(t=>"string"==typeof t&&t.length>0)}(t,e)}}let Is=(()=>{let t,e,r=[gs({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"]}),vs({name:"add",category:"dom"})],n=[],s=Rs;return e=class extends s{constructor(){super(...arguments),this.mode="add",this.preposition="to"}async parseInput(t,e,r){if(!t.args||0===t.args.length)throw Error("add command requires an argument");const{value:n}=await this.evaluateFirst(t.args[0],e,r);if("object"==typeof n&&null!==n&&!Array.isArray(n))return{type:"styles",styles:n,targets:await this.resolveTargets(t.args.slice(1),e,r,t.modifiers)};if("string"==typeof n){const s=n.trim();if(this.isAttribute(s)){const{name:n,value:i}=function(t){const e=os(t);return{name:e.name,value:e.value??""}}(s);return{type:"attribute",name:n,value:i,targets:await this.resolveTargets(t.args.slice(1),e,r,t.modifiers)}}if(this.isCSSProperty(s)){const n=s.substring(1).trim();if(2>t.args.length)throw Error("add *property requires a value argument");const i=await e.evaluate(t.args[1],r);return{type:"styles",styles:{[n]:i+""},targets:await this.resolveTargets(t.args.slice(2),e,r,t.modifiers)}}}const s=this.parseClassNames(n);if(0===s.length)throw Error("add command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(t.args.slice(1),e,r,t.modifiers)}}async execute(t,e){switch(t.type){case"classes":{const r=ds(t.classes,e);r.length>0&&cs(t.targets,r,(t,e)=>{t.classList.contains(e)||t.classList.add(e)});break}case"attribute":r=t.name,n=t.value,as(t.targets,t=>{t.setAttribute(r,n)});break;case"styles":cs(t.targets,Object.entries(t.styles),(t,[e,r])=>{t.style.setProperty(e,r)})}var r,n}validate(t){if("object"!=typeof t||null===t)return 0;const e=t;if(!this.validateType(e.type,["classes","attribute","styles"]))return 0;if(!this.validateTargets(e.targets))return 0;if("classes"===e.type){if(!this.validateStringArray(t.classes,1))return 0}else if("attribute"===e.type){if("string"!=typeof t.name||0===t.name.length)return 0;if("string"!=typeof t.value)return 0}else if("styles"===e.type){const e=t;if("object"!=typeof e.styles||null===e.styles)return 0;if(Array.isArray(e.styles))return 0;const r=e.styles;if(0===Object.keys(r).length)return 0;if(!Object.values(r).every(t=>"string"==typeof t))return 0}return 1}},ss(e,"AddCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;rs(null,t={value:e},r,{kind:"class",name:e.name,metadata:i},null,n),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:i}),ns(e,n)})(),e})();const js=bs(Is);function Ms(t){return t.parentNode?(t.remove(),1):0}let Ds=(()=>{let t,e,r=[gs({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"]}),vs({name:"remove",category:"dom"})],n=[],s=Rs;return e=class extends s{constructor(){super(...arguments),this.mode="remove",this.preposition="from"}async parseInput(t,e,r){if(!t.args||0===t.args.length)throw Error("remove command requires an argument");const{value:n}=await this.evaluateFirst(t.args[0],e,r);if(Es(n))return{type:"element",targets:[n]};if(Array.isArray(n)&&n.length>0&&Es(n[0]))return{type:"element",targets:n.filter(t=>Es(t))};if("string"==typeof n){const s=n.trim();if(this.isAttribute(s))return{type:"attribute",name:os(s).name,targets:await this.resolveTargets(t.args.slice(1),e,r,t.modifiers)};if(this.isCSSProperty(s))return{type:"styles",properties:[s.substring(1).trim()],targets:await this.resolveTargets(t.args.slice(1),e,r,t.modifiers)}}const s=this.parseClassNames(n);if(0===s.length)throw Error("remove command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(t.args.slice(1),e,r,t.modifiers)}}execute(t,e){switch(t.type){case"classes":{const r=ds(t.classes,e);r.length>0&&cs(t.targets,r,(t,e)=>{t.classList.remove(e)});break}case"attribute":r=t.name,as(t.targets,t=>{t.removeAttribute(r)});break;case"styles":cs(t.targets,t.properties,(t,e)=>{t.style.removeProperty(e)});break;case"element":for(const e of t.targets)Ms(e)}var r}validate(t){if("object"!=typeof t||null===t)return 0;const e=t;if(!this.validateType(e.type,["classes","attribute","styles","element"]))return 0;if(!this.validateTargets(e.targets))return 0;if("classes"===e.type){if(!this.validateStringArray(t.classes,1))return 0}else if("attribute"===e.type){if("string"!=typeof t.name||0===t.name.length)return 0}else if("styles"===e.type&&!this.validateStringArray(t.properties,1))return 0;return 1}},ss(e,"RemoveCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;rs(null,t={value:e},r,{kind:"class",name:e.name,metadata:i},null,n),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:i}),ns(e,n)})(),e})();const Ps=bs(Ds);function Vs(t){const e=t.trim().match(/^(\d+(?:\.\d+)?)\s*(s|ms|sec|seconds?|milliseconds?)?$/i);if(!e)return null;const r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();return"ms"===n||"millisecond"===n||"milliseconds"===n?{number:r,milliseconds:Math.floor(r)}:"s"===n||"sec"===n||"second"===n||"seconds"===n?{number:r,milliseconds:Math.floor(1e3*r)}:null}function Bs(t){if("number"==typeof t){if(0>t)throw Error("Duration must be >= 0");return Math.floor(t)}if("string"==typeof t){const e=Vs(t);if(!e)throw Error(`Invalid duration format: "${t}"`);return e.milliseconds}throw Error("Invalid duration type: "+typeof t)}function Fs(t){return 0===t.length?[]:"SUMMARY"===t[0].tagName?t.map(t=>t.closest("details")).filter(t=>null!==t):t}function _s(t,e,r){return()=>{"class"===e?t.classList.toggle(r):"attribute"===e&&ls(t,r)}}function qs(t,e,r,n){const s=_s(t,e,r),i=setTimeout(s,n);return()=>{clearTimeout(i)}}function Hs(t,e,r,n){const s=_s(t,e,r),i=()=>{s(),t.removeEventListener(n,i)};return t.addEventListener(n,i,{once:1}),()=>{t.removeEventListener(n,i)}}function Us(t,e,r){if(e.startsWith("@")){const n=e.substring(1);return void(0==r?t.removeAttribute(n):t.setAttribute(n,1==r?"":r+""))}const n=r+"";switch(e){case"textContent":return void(t.textContent=n);case"innerHTML":return void(t.innerHTML=n);case"innerText":return void(t.innerText=n);case"id":return void(t.id=n);case"className":return void(t.className=n);case"value":return void("value"in t&&(t.value=n));case"checked":return void("checked"in t&&(t.checked=!!r))}if(e.includes(".")){const n=e.split(".");let s=t;for(let t=0;n.length-1>t;t++)if(s=s[n[t]],null==s)return;return void(s[n[n.length-1]]=r)}if(e.includes("-")||e in t.style)t.style.setProperty(e,n);else try{t[e]=r}catch(t){if(!(t instanceof TypeError&&(t.message.includes("only a getter")||t.message.includes("read only"))))throw Error(`Cannot set property '${e}': ${t instanceof Error?t.message:"Unknown error"}`)}}const Ws=/^the\s+(.+?)\s+of\s+(.+)$/i,zs=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 Js(t){return"string"==typeof t&&Ws.test(t)}function Zs(t,e){const r=t.match(Ws);if(!r)return null;try{return{element:ws(r[2].trim(),e),property:r[1].trim()}}catch{return null}}async function Gs(t,e,r){if(function(t){return t&&"object"==typeof t?"propertyOfExpression"===t.type&&"object"==typeof t.property&&null!==t.property:0}(t))return async function(t,e,r){const n=t.property?.name;if(!n)return null;let s=await e.evaluate(t.target,r);return Array.isArray(s)&&(s=s[0]),Es(s)?{element:s,property:n}:null}(t,e,r);if(function(t){return t&&"object"==typeof t?"propertyAccess"!==t.type?0:"string"==typeof t.property||"object"==typeof t.property&&null!==t.property&&"string"==typeof t.property.name:0}(t))return async function(t,e,r){const n="string"==typeof t.property?t.property:t.property?.name;if(!n)return null;let s=await e.evaluate(t.object,r);return Array.isArray(s)&&(s=s[0]),Es(s)?{element:s,property:n}:null}(t,e,r);const n=t;if("possessiveExpression"===n?.type||"memberExpression"===n?.type){const t=n.object,s=n.property;let i=await e.evaluate(t,r);if(Array.isArray(i)&&(i=i[0]),!Es(i))return null;const o=s?.name||s?.value;return o&&(o.startsWith("@")||o.startsWith("*"))?{element:i,property:o}:null}return null}function Xs(t,e){const{element:r,property:n}=t;n.startsWith("*")?Ts(r,n.substring(1),e+""):Us(r,n,e)}async function Ys(t,e,r){let n,s;if(t?.for){const s=await e.evaluate(t.for,r);n="number"==typeof s?s:"string"==typeof s?function(t,e=300){if("number"==typeof t)return Math.max(0,Math.floor(t));if("string"==typeof t){const r=Vs(t);return r?r.milliseconds:e}return e}(s):void 0}if(t?.until){const n=await e.evaluate(t.until,r);"string"==typeof n&&(s=n)}return{duration:n,untilEvent:s}}const Ks=bs((()=>{let t,e,r=[gs({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"]}),vs({name:"toggle",category:"dom"})],n=[];return e=class{async parseInput(t,e,r){if(!t.args?.length)throw Error("toggle command requires an argument");const n=t.args[0],s=n?.name;if("between"===s&&t.args.length>=4){const{duration:n,untilEvent:s}=await Ys(t.modifiers,e,r),i=await e.evaluate(t.args[1],r),o=await e.evaluate(t.args[3],r),a=[];for(let e=4;t.args.length>e;e++){const r=t.args[e]?.name;"on"!==r&&"from"!==r&&a.push(t.args[e])}const c={filterPrepositions:1,fallbackModifierKey:"on"},l=await Ss(a,e,r,"toggle",c,t.modifiers);return{type:"classes-between",classA:(i+"").replace(/^\./,""),classB:(o+"").replace(/^\./,""),targets:l,duration:n,untilEvent:s}}const i=await Gs(n,e,r);if(i)return{type:"property",target:i};if("selector"===n.type&&"string"==typeof n.value&&n.value.startsWith("*")){let s=n.value,i=1;if("*"===s&&t.args.length>1&&"identifier"===t.args[1].type&&(s="*"+t.args[1].name,i=2),"*"===s&&t.modifiers?.on){const n=t.modifiers.on?.name;if(n&&["display","visibility","opacity"].includes(n)){s="*"+n;const{duration:i,untilEvent:o}=await Ys(t.modifiers,e,r),a=Ns(s);if(a){const t=r.me;return{type:"css-property",property:a,targets:t?[t]:[],duration:i,untilEvent:o}}}}const o=Ns(s);if(o){const{duration:n,untilEvent:s}=await Ys(t.modifiers,e,r),a={filterPrepositions:1,fallbackModifierKey:"on"};return{type:"css-property",property:o,targets:await Ss(t.args.slice(i),e,r,"toggle",a,t.modifiers),duration:n,untilEvent:s}}}const{duration:o,untilEvent:a}=await Ys(t.modifiers,e,r),{value:c}=await Ls(n,e,r);if(Js(c)){const t=Zs(c,r);if(t)return{type:"property",target:t}}const{type:l,expression:u}=function(t,e){const r=e?.name,n=function(t){if(!t||"object"!=typeof t)return 0;if("identifier"!==t.type)return 0;const e=t.name;return"string"==typeof e&&function(t){if("string"!=typeof t)return 0;const e=t.toLowerCase();return Os.includes(e)}(e)}(e);if(Es(t)||Array.isArray(t)&&t.every(t=>Es(t)))return{type:"element",expression:""};if(n&&r)return{type:"element",expression:r};if("string"==typeof t){const e=t.trim();return e.startsWith("@")||e.startsWith("[@")?{type:"attribute",expression:e}:e.startsWith("*")?{type:"css-property",expression:e}:e.startsWith(".")?{type:"class",expression:e}:e.startsWith("#")||function(t){if("string"!=typeof t)return 0;const e=t.toLowerCase();return Os.some(t=>e.includes(t))}(e)?{type:"element",expression:e}:{type:"class",expression:e}}return{type:"class",expression:""}}(c,n),h={filterPrepositions:1,fallbackModifierKey:"on"};switch(l){case"attribute":{const{name:n,value:s}=os(u);return{type:"attribute",name:n,value:s,targets:await Ss(t.args.slice(1),e,r,"toggle",h,t.modifiers),duration:o,untilEvent:a}}case"css-property":{const n=Ns(u);if(!n)throw Error("Invalid CSS property: "+u);return{type:"css-property",property:n,targets:await Ss(t.args.slice(1),e,r,"toggle",h,t.modifiers)}}case"element":{let s;if(Es(c))s=[c];else if(Array.isArray(c)&&c.every(t=>Es(t)))s=c;else if(u){const t=document.querySelectorAll(u);s=Array.from(t).filter(t=>Es(t))}else s=await Ss([n],e,r,"toggle",h,t.modifiers);const i=function(t){if(0===t.length)return null;const e=t[0].tagName;if(!t.every(t=>t.tagName===e))return null;switch(e){case"DIALOG":return"dialog";case"DETAILS":return"details";case"SELECT":return"select";case"SUMMARY":return t.map(t=>t.closest("details")).filter(t=>null!==t).length>0?"details":null;default:return null}}(s);if("dialog"===i){const n=await async function(t,e,r,n){if(e?.as){const t=await r.evaluate(e.as,n);if("string"==typeof t&&"modal"===t.toLowerCase())return"modal"}if(t.length>=2){const e=await r.evaluate(t[1],n);if("string"==typeof e){const s=e.toLowerCase();if("modal"===s||"as modal"===s)return"modal";if("as"===s&&t.length>=3){const e=await r.evaluate(t[2],n);if("string"==typeof e&&"modal"===e.toLowerCase())return"modal"}}}return"non-modal"}(t.args,t.modifiers,e,r);return{type:"dialog",mode:n,targets:s}}return"details"===i?{type:"details",targets:Fs(s)}:"select"===i?{type:"select",targets:s}:{type:"classes",classes:us(u),targets:s,duration:o,untilEvent:a}}default:{const n=us(u||c);if(!n.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:n,targets:await Ss(t.args.slice(1),e,r,"toggle",h,t.modifiers),duration:o,untilEvent:a}}}}async execute(t,e){switch(t.type){case"classes":{const r=ds(t.classes,e);if(0===r.length)return[...t.targets];if(cs(t.targets,r,(t,e)=>{t.classList.toggle(e)}),(t.duration||t.untilEvent)&&r.length)for(const e of t.targets)t.duration&&qs(e,"class",r[0],t.duration),t.untilEvent&&Hs(e,"class",r[0],t.untilEvent);return[...t.targets]}case"attribute":if(r=t.name,n=t.value,as(t.targets,t=>{ls(t,r,n)}),t.duration||t.untilEvent)for(const e of t.targets)t.duration&&qs(e,"attribute",t.name,t.duration),t.untilEvent&&Hs(e,"attribute",t.name,t.untilEvent);return[...t.targets];case"css-property":return as(t.targets,e=>function(t,e){const r=window.getComputedStyle(t);switch(e){case"display":"none"===r.display?(t.style.display=t.dataset.previousDisplay||"block",delete t.dataset.previousDisplay):(t.dataset.previousDisplay=r.display,t.style.display="none");break;case"visibility":t.style.visibility="hidden"===r.visibility?"visible":"hidden";break;case"opacity":t.style.opacity=0===parseFloat(r.opacity)?"1":"0"}}(e,t.property));case"property":return function(t){const e=function(t){const{element:e,property:r}=t;return r.startsWith("*")?function(t,e){return window.getComputedStyle(t).getPropertyValue(e)}(e,r.substring(1)):Ye(e,r)}(t),r=t.property,n=r.startsWith("@")?r.substring(1):r;if("boolean"==typeof e||zs.has(n)||zs.has(n.toLowerCase())){const r=!e;return Xs(t,r),r}if("number"==typeof e){const r=0===e?1:0;return Xs(t,r),r}if("string"==typeof e){const n="__ht_"+r,s=t.element[n];return""===e&&void 0!==s?(Xs(t,s),s):(t.element[n]=e,Xs(t,""),"")}Xs(t,!e)}(t.target),[t.target.element];case"dialog":return as(t.targets,e=>{return n=t.mode,void((r=e).open?r.close():"modal"===n?r.showModal():r.show());var r,n});case"details":return as(t.targets,t=>{var e;(e=t).open=!e.open});case"select":return as(t.targets,t=>function(t){if(document.activeElement===t)t.blur();else{if(t.focus(),"showPicker"in t&&"function"==typeof t.showPicker)try{return void t.showPicker()}catch{}const e=new MouseEvent("click",{view:window,bubbles:1,cancelable:1});t.dispatchEvent(e)}}(t));case"classes-between":for(const e of t.targets){const r=e.classList.contains(t.classA),n=e.classList.contains(t.classB);r?(e.classList.remove(t.classA),e.classList.add(t.classB)):n?(e.classList.remove(t.classB),e.classList.add(t.classA)):e.classList.add(t.classA)}if(t.duration||t.untilEvent)for(const e of t.targets)t.duration&&qs(e,"class",t.classA,t.duration),t.untilEvent&&Hs(e,"class",t.classA,t.untilEvent);return[...t.targets]}var r,n}},ss(e,"ToggleCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;rs(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),ns(e,n)})(),e})());class Qs{async parseInput(t,e,r){const{targets:n}=await async function(t,e,r,n){return{targets:await Ss(t.args,e,r,n)}}(t,e,r,this.mode);return{targets:n,mode:this.mode,defaultDisplay:"show"===this.mode?"block":void 0}}validate(t){if("object"!=typeof t||null===t)return 0;const e=t;return Array.isArray(e.targets)&&e.targets.every(t=>Es(t))?"show"!==e.mode&&"hide"!==e.mode||"show"===e.mode&&"string"!=typeof e.defaultDisplay?0:1:0}showElement(t,e="block"){const r=t.dataset.originalDisplay;void 0!==r?(t.style.display=r||e,delete t.dataset.originalDisplay):"none"===t.style.display&&(t.style.display=e),t.classList.add("show")}hideElement(t){if(!t.dataset.originalDisplay){const e=t.style.display;t.dataset.originalDisplay="none"===e?"":e}t.style.display="none",t.classList.remove("show")}}let ti=(()=>{let t,e,r=[gs({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"]}),vs({name:"show",category:"dom"})],n=[],s=Qs;return e=class extends s{constructor(){super(...arguments),this.mode="show"}async execute(t,e){const r=t.defaultDisplay||"block";for(const e of t.targets)this.showElement(e,r)}validate(t){if("object"!=typeof t||null===t)return 0;const e=t;return Array.isArray(e.targets)&&e.targets.every(t=>Es(t))?"string"!=typeof e.defaultDisplay?0:1:0}},ss(e,"ShowCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;rs(null,t={value:e},r,{kind:"class",name:e.name,metadata:i},null,n),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:i}),ns(e,n)})(),e})();const ei=bs(ti);let ri=(()=>{let t,e,r=[gs({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"]}),vs({name:"hide",category:"dom"})],n=[],s=Qs;return e=class extends s{constructor(){super(...arguments),this.mode="hide"}async execute(t,e){for(const e of t.targets)this.hideElement(e)}validate(t){if("object"!=typeof t||null===t)return 0;const e=t;return Array.isArray(e.targets)&&e.targets.every(t=>Es(t))?1:0}},ss(e,"HideCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;rs(null,t={value:e},r,{kind:"class",name:e.name,metadata:i},null,n),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:i}),ns(e,n)})(),e})();const ni=bs(ri),si=bs((()=>{let t,e,r=[gs({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"]}),vs({name:"put",category:"dom"})],n=[];return e=class{async parseInput(t,e,r){if(!t.args?.length)throw Error("put requires arguments");const n=t=>t?.type||"unknown",s=["into","before","after","at","at start of","at end of"];let i=-1,o=null;for(let e=0;t.args.length>e;e++){const r=t.args[e],a=n(r),c="literal"===a?r.value:r.name;if(("literal"===a||"identifier"===a)&&s.includes(c)){i=e,o=c;break}}let a=null,c=null;if(-1===i)if(t.modifiers.into||t.modifiers.before||t.modifiers.after){const e=t.modifiers.into?"into":t.modifiers.before?"before":"after";a=t.args[0],o=e,c=t.modifiers[e]}else if(3>t.args.length){if(2>t.args.length)throw Error("put requires content and position");a=t.args[0],o=t.args[1]?.value||t.args[1]?.name||"into"}else a=t.args[0],o=t.args[1]?.value||t.args[1]?.name||null,c=t.args[2];else a=t.args.slice(0,i)[0]||null,c=t.args.slice(i+1)[0]||null;if(!a)throw Error("put requires content");if(!o)throw Error("put requires position keyword");const l=await e.evaluate(a,r),u=this.mapPosition(o);let h,f,d=null;if(c){const t=n(c),s=await Gs(c,e,r);if(s)return{value:l,targets:[s.element],position:"replace",memberPath:s.property};if("memberExpression"===t){const t=c.object,n=c.property;if("selector"===t?.type?d=t.value:"identifier"===t?.type&&(d=t.name),d&&n?.name)h=n.name;else{const t=await e.evaluate(c,r);"string"==typeof t&&(d=t)}}else if("identifier"===t&&"me"===c.name)d=null;else if("selector"===t||"cssSelector"===t)d=c.value||c.selector;else if("literal"===t){const t=c.value;if("string"==typeof t&&Js(t)){const e=Zs(t,r);if(e)return{value:l,targets:[e.element],position:"replace",memberPath:e.property}}"string"==typeof t&&this.looksLikeCss(t)?d=t:f=t+""}else if("identifier"===t){const t=c.name;if(this.looksLikeCss(t))d=t;else{const n=await e.evaluate(c,r),s=this.resolveEvaluatedAsElements(n);if(s)return{value:l,targets:s,position:u,memberPath:h};f=t}}else{const t=await e.evaluate(c,r),n=this.resolveEvaluatedAsElements(t);if(n)return{value:l,targets:n,position:u,memberPath:h};"string"==typeof t&&(this.looksLikeCss(t)?d=t:f=t)}}return f?{value:l,targets:[],position:u,memberPath:h,variableName:f}:{value:l,targets:await this.resolveTargets(d,r),position:u,memberPath:h}}async execute(t,e){const{value:r,targets:n,position:s,memberPath:i,variableName:o}=t;if(o)return e.locals&&e.locals.set(o,r),e[o]=r,void Object.assign(e,{it:r});if(i)for(const t of n)this.setProperty(t,i,r);else for(const t of n){const e=this.parseValue(r);this.insertContent(t,e,s)}return n}mapPosition(t){switch(t){case"into":return"replace";case"before":return"beforebegin";case"after":return"afterend";case"at start of":return"afterbegin";case"at end of":return"beforeend";default:throw Error("Invalid position: "+t)}}async resolveTargets(t,e){if(!t||"me"===t){if(!e.me||!Es(e.me))throw Error("put: no target and context.me is null");return[e.me]}const r=Array.from(document.querySelectorAll(t)).filter(t=>Es(t));if(!r.length)throw Error(`No elements: "${t}"`);return r}parseValue(t){return Es(t)?t:null==t?"":t+""}insertContent(t,e,r){if("replace"!==r)if(Es(e)){const n=e;switch(r){case"beforebegin":t.parentElement?.insertBefore(n,t);break;case"afterbegin":t.insertBefore(n,t.firstChild);break;case"beforeend":t.appendChild(n);break;case"afterend":t.parentElement?.insertBefore(n,t.nextSibling)}}else e.includes("<")&&e.includes(">")?t.insertAdjacentHTML(r,e):t.insertAdjacentText(r,e);else Es(e)?(t.innerHTML="",t.appendChild(e)):e.includes("<")&&e.includes(">")?t.innerHTML=e:t.textContent=e}resolveEvaluatedAsElements(t){if(Es(t))return[t];if(Array.isArray(t)){const e=t.filter(Es);return e.length>0?e:null}if("undefined"!=typeof NodeList&&t instanceof NodeList){const e=Array.from(t).filter(Es);return e.length>0?e:null}return null}looksLikeCss(t){return t?/^[#.\[]/.test(t)||/[>+~\s]/.test(t)&&t.length>1?1:["div","span","p","a","button","input","form","ul","li","ol","table","tr","td","th","img","h1","h2","h3","h4","h5","h6","section","article","header","footer","nav","main","aside","dialog","label","select","option","textarea"].includes(t.toLowerCase()):0}setProperty(t,e,r){const n=e.split(".");let s=t;for(let t=0;n.length-1>t;t++){if(!s[n[t]])throw Error(`Property path "${e}" does not exist`);s=s[n[t]]}s[n[n.length-1]]=r}},ss(e,"PutCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;rs(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),ns(e,n)})(),e})()),ii=bs((()=>{let t,e,r=[gs({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"]}),vs({name:"set",category:"data"})],n=[];return e=class{async parseInput(t,e,r){if(!t.args?.length)throw Error("set command requires a target");const n=t.args[0],s=n?.name||n?.value,i=await Gs(n,e,r);if(i){const n=await this.extractValue(t,e,r);if(i.property.startsWith("*")){const t=i.property.substring(1);return{type:"style",element:i.element,property:t,value:n+""}}return{type:"property",element:i.element,property:i.property,value:n}}if("memberExpression"===n?.type||"propertyAccess"===n?.type){const s=await this.tryParseMemberExpression(n,t,e,r);if(s)return s}let o;if(o="identifier"!==n?.type&&"variable"!==n?.type||"string"!=typeof s?await e.evaluate(n,r):s,function(t){if("object"!=typeof t||null===t||Array.isArray(t))return 0;if(Es(t)||t instanceof Node)return 0;const e=Object.getPrototypeOf(t);return e===Object.prototype||null===e}(o))return{type:"object-literal",properties:o,targets:await this.resolveTargets(t.modifiers.on,e,r)};if(Js(o)){const n=Zs(o,r);if(n){const s=await this.extractValue(t,e,r);return{type:"property",element:n.element,property:n.property,value:s}}return this.parseTheXofY(o,t,e,r)}if("string"==typeof o&&Cs(o)){const n=o.substring(1).trim(),s=await this.extractValue(t,e,r);return{type:"style",element:await this.resolveElement(t.modifiers.on,e,r),property:n,value:s+""}}if("string"==typeof o&&is(o)){const n=o.substring(1).trim(),s=await this.extractValue(t,e,r);return{type:"attribute",element:await this.resolveElement(t.modifiers.on,e,r),name:n,value:s}}if("string"==typeof o){const n=o.match(/^(my|me|its?|your?)\s+(.+)$/i);if(n){const s=ks(n[1],r),i=await this.extractValue(t,e,r);return{type:"property",element:s,property:n[2],value:i}}}if(Es(o))return{type:"property",element:o,property:"textContent",value:await this.extractValue(t,e,r)};if(Array.isArray(o)&&o.length>0&&Es(o[0])){const n=await this.extractValue(t,e,r);return{type:"property",element:o[0],property:"textContent",value:n}}if("string"!=typeof o)throw Error("set command target must be a string or object literal");return{type:"variable",name:o,value:await this.extractValue(t,e,r)}}async execute(t,e){switch(t.type){case"variable":return e.locals.set(t.name,t.value),"result"!==t.name&&"it"!==t.name||Object.assign(e,{[t.name]:t.value}),Object.assign(e,{it:t.value}),{target:t.name,value:t.value,targetType:"variable"};case"attribute":return t.element.setAttribute(t.name,t.value+""),Object.assign(e,{it:t.value}),{target:"@"+t.name,value:t.value,targetType:"attribute"};case"property":return Us(t.element,t.property,t.value),Object.assign(e,{it:t.value}),{target:t.element,value:t.value,targetType:"property"};case"style":return Ts(t.element,t.property,t.value),Object.assign(e,{it:t.value}),{target:t.element,value:t.value,targetType:"property"};case"object-literal":for(const e of t.targets)for(const[r,n]of Object.entries(t.properties))Us(e,r,n);return Object.assign(e,{it:t.properties}),{target:t.targets[0]||"unknown",value:t.properties,targetType:"property"};case"member-assignment":return t.container[t.property]=t.value,Object.assign(e,{it:t.value}),{target:t.property,value:t.value,targetType:"property"};default:throw Error("Unknown input type: "+t.type)}}async tryParseMemberExpression(t,e,r,n){const s=t.object,i=t.property;if(s?.name&&i?.name){const t=s.name.toLowerCase();if(["me","my","it","its","you","your"].includes(t)){const s=ks(t,n),o=await this.extractValue(e,r,n);return{type:"property",element:s,property:i.name,value:o}}}const o=t.object,a=t.computed;if(o){const s=await r.evaluate(o,n);if(null!=s&&"object"==typeof s){const o=a?await r.evaluate(t.property,n)+"":i?.name||"";if(o)return{type:"member-assignment",container:s,property:o,value:await this.extractValue(e,r,n)}}}return null}async extractValue(t,e,r){if(t.modifiers.to)return e.evaluate(t.modifiers.to,r);const n=t.args.findIndex(t=>"identifier"===t.type&&"to"===t.name);if(n>=0&&t.args.length>n+1)return e.evaluate(t.args[n+1],r);if(t.args.length>=2)return e.evaluate(t.args[1],r);throw Error('set command requires a value (use "to" keyword)')}async resolveElement(t,e,r){return ws(t?await e.evaluate(t,r):void 0,r)}async resolveTargets(t,e,r){return function(t,e){if(Array.isArray(t))return t.filter(Es);if(t instanceof NodeList)return Array.from(t).filter(Es);if(Es(t))return[t];if(!t){const t=e.me;return t&&Es(t)?[t]:[]}if("string"==typeof t){const r=t.trim();if("me"===r)return e.me&&Es(e.me)?[e.me]:[];if("it"===r)return Es(e.it)?[e.it]:[];if("you"===r)return e.you&&Es(e.you)?[e.you]:[];const n=e.me?.ownerDocument??("undefined"!=typeof document?document:null);if(n){let t=r;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const e=n.querySelectorAll(t);return Array.from(e).filter(Es)}}return[]}(t?await e.evaluate(t,r):void 0,r)}async parseTheXofY(t,e,r,n){const s=t.match(/^the\s+(.+?)\s+of\s+(.+)$/i);if(!s)throw Error('Invalid "the X of Y" syntax');const[,i,o]=s,a=ws(o,n),c=await this.extractValue(e,r,n);return{type:"property",element:a,property:i.trim(),value:c}}validate(t){if(!t||"object"!=typeof t)return 0;const e=t;if(!e.type||"string"!=typeof e.type)return 0;if(!["variable","attribute","property","style","object-literal"].includes(e.type))return 0;switch(e.type){case"variable":return"string"==typeof e.name&&"value"in e;case"attribute":return"string"==typeof e.name&&Es(e.element)&&"value"in e;case"property":return"string"==typeof e.property&&Es(e.element)&&"value"in e;case"style":return"string"==typeof e.property&&""!==e.property&&Es(e.element)&&"string"==typeof e.value;case"object-literal":return null!==e.properties&&"object"==typeof e.properties&&Array.isArray(e.targets)&&e.targets.length>0;default:return 0}}},ss(e,"SetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;rs(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),ns(e,n)})(),e})());function oi(t){const e=t.trim();return/^\d+$/.test(e)?parseInt(e,10):/^\d*\.\d+$/.test(e)?parseFloat(e):"true"===e?1:"false"===e?0:"null"===e?null:"undefined"!==e?e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e:void 0}const ai=bs((()=>{let t,e,r=[gs({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"]}),vs({name:"trigger",category:"event"})],n=[];return e=class{async parseInput(t,e,r){const n="send"===t.commandName?.toLowerCase()?"send":"trigger",s=n;if(!t.args?.length)throw Error(s+" command requires an event name");const i=t=>t?.type||"unknown",o=t.args[0];let a,c,l;if("functionCall"===i(o)||"callExpression"===i(o)){a=o.name||o.callee?.name;const t=o.args||o.arguments;t?.length&&(c=await this.parseEventDetail(t,e,r))}else if("identifier"===i(o)||"keyword"===i(o))a=o.name;else{const t=await e.evaluate(o,r);a="string"==typeof t?t:t+""}const u=t.modifiers?.on||t.modifiers?.to;if(u)l=await this.resolveTargets([u],e,r,s);else{const n=t.args.findIndex((t,e)=>{if(0===e)return 0;const r=t.name||t.value;return"on"===r||"to"===r});if(-1!==n&&t.args.length-1>n){const i=t.args.slice(n+1),o=i.findIndex(t=>"with"===(t.name||t.value)),a=-1===o?i:i.slice(0,o);l=await this.resolveTargets(a,e,r,s)}else{if(!r.me)throw Error(s+": no target specified and context.me is null");l=[r.me]}}return{eventName:a,detail:c,targets:l,options:await this.parseEventOptions(t.args,e,r),mode:n}}async execute(t,e){const r=function(t,e,r={}){return new CustomEvent(t,{detail:void 0!==e?e:{},bubbles:void 0!==r.bubbles?r.bubbles:1,cancelable:void 0!==r.cancelable?r.cancelable:1,composed:void 0!==r.composed?r.composed:0})}(t.eventName,t.detail,t.options);for(const e of t.targets)e.dispatchEvent(r);e.it=r}async resolveTargets(t,e,r,n){const s=[];for(const n of t){const t=await e.evaluate(n,r);if("window"!==t&&t!==window)if("document"!==t&&t!==document)if("me"===t&&r.me)s.push(r.me);else if("you"===t&&r.you)s.push(r.you);else if("it"===t&&r.it)s.push(r.it);else if(Es(t))s.push(t);else if(t instanceof NodeList)s.push(...Array.from(t).filter(Es));else if(Array.isArray(t))s.push(...t.filter(Es));else{if("string"==typeof t){const e=document.querySelectorAll(t);if(0===e.length)throw Error(`No elements found: "${t}"`);s.push(...Array.from(e).filter(Es));continue}if(!t||"object"!=typeof t||!("addEventListener"in t))throw Error("Invalid target: "+typeof t);s.push(t)}else s.push(document);else s.push(window)}if(!s.length)throw Error(n+": no valid targets");return s}async parseEventDetail(t,e,r){if(!t?.length)return;if(1===t.length){const n=t[0];if("objectLiteral"!==n?.type)return await e.evaluate(n,r)}const n={};for(const s of t){const t=await e.evaluate(s,r);if("object"!=typeof t||null===t||Array.isArray(t)){if("string"==typeof t&&t.includes(":")){const[e,r]=t.split(":",2);n[e.trim()]=oi(r.trim())}}else Object.assign(n,t)}return Object.keys(n).length?n:void 0}async parseEventOptions(t,e,r){const n={bubbles:1,cancelable:1,composed:0},s=t.findIndex(t=>"with"===(t.name||t.value));if(-1===s)return n;for(const i of t.slice(s+1)){const t=await e.evaluate(i,r);if("string"==typeof t){const e=t.toLowerCase();"bubbles"===e?n.bubbles=1:"nobubbles"===e?n.bubbles=0:"cancelable"===e?n.cancelable=1:"nocancelable"===e?n.cancelable=0:"composed"===e&&(n.composed=1)}}return n}},ss(e,"EventDispatchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;rs(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),ns(e,n)})(),e})()),ci=bs((()=>{let t,e,r=[gs({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"]}),vs({name:"log",category:"utility"})],n=[];return e=class{async parseInput(t,e,r){return t.args&&0!==t.args.length?{values:await Promise.all(t.args.map(t=>e.evaluate(t,r)))}:{values:[]}}async execute(t,e){const r="undefined"!=typeof window?window.console:console;0===t.values.length?r.log():r.log(...t.values)}validate(t){return"object"!=typeof t||null===t?0:Array.isArray(t.values)}},ss(e,"LogCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;rs(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),ns(e,n)})(),e})());function li(t,e,r){return t?new Promise(r=>{const n=function(r,n){let i=0;return r=>{i||(i=1,t.removeEventListener(e,s),n(r))}}(0,r),s=t=>{n({event:t,timedOut:0,cancelled:0})};t.addEventListener(e,s)}):Promise.reject(Error("waitForEvent: no target provided"))}function ui(t){return new Promise(e=>setTimeout(e,t))}const hi=bs((()=>{let t,e,r=[gs({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"]}),vs({name:"wait",category:"async"})],n=[];return e=class{async parseInput(t,e,r){if(!t.args?.length)throw Error("wait command requires an argument");if(t.modifiers.or)return this.parseRaceCondition(t,e,r);if(t.modifiers.for)return this.parseEventWait(t.modifiers.for,t.modifiers.from,e,r);const n=t.args[0];return"arrayLiteral"===n.type&&n.elements?this.parseEventArrayWait(n.elements,t.args[1],e,r):this.parseTimeWait(t.args[0],e,r)}async execute(t,e){const r=Date.now();if("time"===t.type)return await ui(t.milliseconds),{type:"time",result:t.milliseconds,duration:Date.now()-r};if("event"===t.type){const n=t.target??e.me??document,s=(await li(n,t.eventName)).event;if(Object.assign(e,{it:s}),t.destructure)for(const r of t.destructure)r in s&&e.locals.set(r,s[r]);return{type:"event",result:s,duration:Date.now()-r}}const{result:n,winningCondition:s}=await this.executeRace(t.conditions,e);if(Object.assign(e,{it:n}),n instanceof Event&&"event"===s?.type&&s.destructure)for(const t of s.destructure)t in n&&e.locals.set(t,n[t]);return{type:n instanceof Event?"event":"time",result:n,duration:Date.now()-r}}async parseTimeWait(t,e,r){return{type:"time",milliseconds:Bs(await e.evaluate(t,r))}}async parseEventWait(t,e,r,n){const s=await r.evaluate(t,n);if("string"!=typeof s)throw Error("wait for: event name must be a string");const i=s.match(/^(\w+)\(([^)]+)\)$/),o=i?i[1]:s,a=i?i[2].split(",").map(t=>t.trim()):void 0;let c;if(e){const t=await r.evaluate(e,n);if(!t||"object"!=typeof t||!("addEventListener"in t))throw Error("wait for from: target must be an EventTarget");c=t}else c=n.me??void 0;return{type:"event",eventName:o,target:c,destructure:a}}async parseEventArrayWait(t,e,r,n){const s=[];for(const e of t){const t=e;if("objectLiteral"===t.type&&t.properties){let e="",r=[];for(const n of t.properties){const t=n.key?.name||n.key?.value;"name"===t&&n.value?e=n.value.value||"":"args"===t&&n.value?.elements&&(r=n.value.elements.map(t=>t.value||t.name||""))}e&&s.push({name:e,params:r})}}let i;if(e){const t=await r.evaluate(e,n);t&&"object"==typeof t&&"addEventListener"in t&&(i=t)}return i||(i=n.me??void 0),1===s.length?{type:"event",eventName:s[0].name,target:i,destructure:s[0].params.length>0?s[0].params:void 0}:{type:"race",conditions:s.map(t=>({type:"event",eventName:t.name,target:i,destructure:t.params.length>0?t.params:void 0}))}}async parseRaceCondition(t,e,r){const n=[];t.modifiers.for?n.push(await this.parseEventWait(t.modifiers.for,t.modifiers.from,e,r)):t.args[0]&&n.push(await this.parseTimeWait(t.args[0],e,r));const s=await e.evaluate(t.modifiers.or,r),i=Array.isArray(s)?s:[s];for(const t of i)try{n.push({type:"time",milliseconds:Bs(t)})}catch{if("string"==typeof t){const e=t.match(/^(\w+)\(([^)]+)\)$/);n.push(e?{type:"event",eventName:e[1],target:r.me??void 0,destructure:e[2].split(",").map(t=>t.trim())}:{type:"event",eventName:t,target:r.me??void 0})}}if(2>n.length)throw Error("wait: race requires at least 2 conditions");return{type:"race",conditions:n}}async executeRace(t,e){const r=t.map(t=>"time"===t.type?ui(t.milliseconds).then(()=>({result:t.milliseconds,winningCondition:t})):li(t.target??e.me??document,t.eventName).then(e=>({result:e.event,winningCondition:t})));return Promise.race(r)}},ss(e,"WaitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;rs(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),ns(e,n)})(),e})()),fi=function(t,e){const r=new Wn(e.expressionEvaluator);for(const e of t)r.register(e);return new ts({registry:r,expressionEvaluator:e.expressionEvaluator,enableAsyncCommands:e.enableAsyncCommands??1,commandTimeout:e.commandTimeout??1e4,enableErrorReporting:e.enableErrorReporting??1,enableResultPattern:e.enableResultPattern??1})}([js(),Ps(),Ks(),ei(),ni(),si(),ii(),ai(),ci(),hi()],{expressionEvaluator:new class extends or{constructor(t){super();for(const e of t)this.registerCategory(e)}}([$r,yn,_n])}),di={parse:t=>Oe(t),execute:async(t,e)=>{const r=function(t){if(!t)return Pe();if(t.locals instanceof Map&&t.globals instanceof Map&&t.flags)return t;const e=Pe(t.me instanceof Element?t.me:null);return void 0!==t.it&&(e.it=t.it),void 0!==t.you&&(e.you=t.you),void 0!==t.result&&(e.result=t.result),void 0!==t.event&&Object.assign(e,{event:t.event}),e}(e),n=Oe(t);if(!n.success||!n.node)throw Error(n.error?.message||"Parse failed");return await fi.execute(n.node,r)}},pi=function(t){return new es(t)}(di),mi={runtime:di,parse:t=>di.parse(t),execute:async(t,e)=>di.execute(t,e),createContext:Pe,attributeProcessor:pi,version:"1.1.0-minimal-v2-tree-shakeable",commands:["add","remove","toggle","show","hide","put","set","send","log","wait"],eval:async(t,e)=>di.execute(t,e),init:()=>{pi.init()}};return"undefined"!=typeof window&&(window.hyperfixi=mi,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{pi.init()}):pi.init()),mi}();